blob: d37d1e753eb86583e5b6d5c7786d9bd105898515 [file] [log] [blame]
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This transformation implements the well known scalar replacement of
11/// aggregates transformation. It tries to identify promotable elements of an
12/// aggregate alloca, and promote them to registers. It will also try to
13/// convert uses of an element (or set of elements) of an alloca into a vector
14/// or bitfield-style integer scalar if appropriate.
15///
16/// It works to do this with minimal slicing of the alloca so that regions
17/// which are merely transferred in and out of external memory remain unchanged
18/// and are not decomposed to scalar code.
19///
20/// Because this also performs alloca promotion, it can be thought of as also
21/// serving the purpose of SSA formation. The algorithm iterates on the
22/// function until all opportunities for promotion have been realized.
23///
24//===----------------------------------------------------------------------===//
25
Chandler Carruth1b398ae2012-09-14 09:22:59 +000026#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/SetVector.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/Statistic.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000031#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000033#include "llvm/Analysis/PtrUseVisitor.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000036#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000038#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000040#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Function.h"
42#include "llvm/IR/IRBuilder.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000043#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Instructions.h"
45#include "llvm/IR/IntrinsicInst.h"
46#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/Operator.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000048#include "llvm/Pass.h"
Chandler Carruth70b44c52012-09-15 11:43:14 +000049#include "llvm/Support/CommandLine.h"
Chandler Carruthf0546402013-07-18 07:15:00 +000050#include "llvm/Support/Compiler.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000051#include "llvm/Support/Debug.h"
52#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000053#include "llvm/Support/MathExtras.h"
Chandler Carruth83cee772014-02-25 03:59:29 +000054#include "llvm/Support/TimeValue.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000055#include "llvm/Support/raw_ostream.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000056#include "llvm/Transforms/Utils/Local.h"
57#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Chandler Carruth83cee772014-02-25 03:59:29 +000058
59#if __cplusplus >= 201103L && !defined(NDEBUG)
60// We only use this for a debug check in C++11
61#include <random>
62#endif
63
Chandler Carruth1b398ae2012-09-14 09:22:59 +000064using namespace llvm;
65
Chandler Carruth964daaa2014-04-22 02:55:47 +000066#define DEBUG_TYPE "sroa"
67
Chandler Carruth1b398ae2012-09-14 09:22:59 +000068STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000069STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +000070STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
71STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
72STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000073STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
74STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000075STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000076STATISTIC(NumDeleted, "Number of instructions deleted");
77STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000078
Chandler Carruth83cee772014-02-25 03:59:29 +000079/// Hidden option to enable randomly shuffling the slices to help uncover
80/// instability in their order.
81static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
82 cl::init(false), cl::Hidden);
83
Chandler Carruth3b79b2a2014-02-25 21:24:45 +000084/// Hidden option to experiment with completely strict handling of inbounds
85/// GEPs.
Chandler Carruth113dc642014-12-20 02:39:18 +000086static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
87 cl::Hidden);
Chandler Carruth3b79b2a2014-02-25 21:24:45 +000088
Chandler Carruth1b398ae2012-09-14 09:22:59 +000089namespace {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000090/// \brief A custom IRBuilder inserter which prefixes all names if they are
91/// preserved.
92template <bool preserveNames = true>
Chandler Carruth113dc642014-12-20 02:39:18 +000093class IRBuilderPrefixedInserter
94 : public IRBuilderDefaultInserter<preserveNames> {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000095 std::string Prefix;
96
97public:
98 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
99
100protected:
101 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
102 BasicBlock::iterator InsertPt) const {
103 IRBuilderDefaultInserter<preserveNames>::InsertHelper(
104 I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
105 }
106};
107
108// Specialization for not preserving the name is trivial.
109template <>
Chandler Carruth113dc642014-12-20 02:39:18 +0000110class IRBuilderPrefixedInserter<false>
111 : public IRBuilderDefaultInserter<false> {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000112public:
113 void SetNamePrefix(const Twine &P) {}
114};
115
Chandler Carruthd177f862013-03-20 07:30:36 +0000116/// \brief Provide a typedef for IRBuilder that drops names in release builds.
117#ifndef NDEBUG
Chandler Carruth113dc642014-12-20 02:39:18 +0000118typedef llvm::IRBuilder<true, ConstantFolder, IRBuilderPrefixedInserter<true>>
119 IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000120#else
Chandler Carruth113dc642014-12-20 02:39:18 +0000121typedef llvm::IRBuilder<false, ConstantFolder, IRBuilderPrefixedInserter<false>>
122 IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000123#endif
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000124}
Chandler Carruthd177f862013-03-20 07:30:36 +0000125
126namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000127/// \brief A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000128///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000129/// This structure represents a slice of an alloca used by some instruction. It
130/// stores both the begin and end offsets of this use, a pointer to the use
131/// itself, and a flag indicating whether we can classify the use as splittable
132/// or not when forming partitions of the alloca.
133class Slice {
Chandler Carruthf74654d2013-03-18 08:36:46 +0000134 /// \brief The beginning offset of the range.
135 uint64_t BeginOffset;
136
137 /// \brief The ending offset, not included in the range.
138 uint64_t EndOffset;
139
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000140 /// \brief Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000141 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000142 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000143
144public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000145 Slice() : BeginOffset(), EndOffset() {}
146 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000147 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000148 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000149
150 uint64_t beginOffset() const { return BeginOffset; }
151 uint64_t endOffset() const { return EndOffset; }
152
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000153 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
154 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000155
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000156 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000157
Craig Topperf40110f2014-04-25 05:29:35 +0000158 bool isDead() const { return getUse() == nullptr; }
159 void kill() { UseAndIsSplittable.setPointer(nullptr); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000160
161 /// \brief Support for ordering ranges.
162 ///
163 /// This provides an ordering over ranges such that start offsets are
164 /// always increasing, and within equal start offsets, the end offsets are
165 /// decreasing. Thus the spanning range comes first in a cluster with the
166 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000167 bool operator<(const Slice &RHS) const {
Chandler Carruth113dc642014-12-20 02:39:18 +0000168 if (beginOffset() < RHS.beginOffset())
169 return true;
170 if (beginOffset() > RHS.beginOffset())
171 return false;
172 if (isSplittable() != RHS.isSplittable())
173 return !isSplittable();
174 if (endOffset() > RHS.endOffset())
175 return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000176 return false;
177 }
178
179 /// \brief Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000180 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000181 uint64_t RHSOffset) {
182 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000183 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000184 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000185 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000186 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000187 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000188
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000189 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000190 return isSplittable() == RHS.isSplittable() &&
191 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000192 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000193 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000194};
Chandler Carruthf0546402013-07-18 07:15:00 +0000195} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000196
197namespace llvm {
Chandler Carruthf0546402013-07-18 07:15:00 +0000198template <typename T> struct isPodLike;
Chandler Carruth113dc642014-12-20 02:39:18 +0000199template <> struct isPodLike<Slice> { static const bool value = true; };
Chandler Carruthf74654d2013-03-18 08:36:46 +0000200}
201
202namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000203/// \brief Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000204///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000205/// This class represents the slices of an alloca which are formed by its
206/// various uses. If a pointer escapes, we can't fully build a representation
207/// for the slices used and we reflect that in this structure. The uses are
208/// stored, sorted by increasing beginning offset and with unsplittable slices
209/// starting at a particular offset before splittable slices.
210class AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000211public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000212 /// \brief Construct the slices of a particular alloca.
213 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000214
215 /// \brief Test whether a pointer to the allocation escapes our analysis.
216 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000217 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000218 /// ignored.
219 bool isEscaped() const { return PointerEscapingInstr; }
220
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000221 /// \brief Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000222 /// @{
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000223 typedef SmallVectorImpl<Slice>::iterator iterator;
Chandler Carruthc659df92014-10-16 20:24:07 +0000224 typedef iterator_range<iterator> range;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000225 iterator begin() { return Slices.begin(); }
226 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000227
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000228 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
Chandler Carruthc659df92014-10-16 20:24:07 +0000229 typedef iterator_range<const_iterator> const_range;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000230 const_iterator begin() const { return Slices.begin(); }
231 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000232 /// @}
233
Chandler Carruth0715cba2015-01-01 11:54:38 +0000234 /// \brief Erase a range of slices.
Chandler Carruth994cde82015-01-01 12:01:03 +0000235 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
Chandler Carruth0715cba2015-01-01 11:54:38 +0000236
237 /// \brief Insert new slices for this alloca.
238 ///
239 /// This moves the slices into the alloca's slices collection, and re-sorts
240 /// everything so that the usual ordering properties of the alloca's slices
241 /// hold.
242 void insert(ArrayRef<Slice> NewSlices) {
243 int OldSize = Slices.size();
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000244 Slices.append(NewSlices.begin(), NewSlices.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +0000245 auto SliceI = Slices.begin() + OldSize;
246 std::sort(SliceI, Slices.end());
247 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
248 }
249
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000250 // Forward declare an iterator to befriend it.
251 class partition_iterator;
252
253 /// \brief A partition of the slices.
254 ///
255 /// An ephemeral representation for a range of slices which can be viewed as
256 /// a partition of the alloca. This range represents a span of the alloca's
257 /// memory which cannot be split, and provides access to all of the slices
258 /// overlapping some part of the partition.
259 ///
260 /// Objects of this type are produced by traversing the alloca's slices, but
261 /// are only ephemeral and not persistent.
262 class Partition {
263 private:
264 friend class AllocaSlices;
265 friend class AllocaSlices::partition_iterator;
266
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000267 /// \brief The beginning and ending offsets of the alloca for this
268 /// partition.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000269 uint64_t BeginOffset, EndOffset;
270
271 /// \brief The start end end iterators of this partition.
272 iterator SI, SJ;
273
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000274 /// \brief A collection of split slice tails overlapping the partition.
275 SmallVector<Slice *, 4> SplitTails;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000276
277 /// \brief Raw constructor builds an empty partition starting and ending at
278 /// the given iterator.
279 Partition(iterator SI) : SI(SI), SJ(SI) {}
280
281 public:
282 /// \brief The start offset of this partition.
283 ///
284 /// All of the contained slices start at or after this offset.
285 uint64_t beginOffset() const { return BeginOffset; }
286
287 /// \brief The end offset of this partition.
288 ///
289 /// All of the contained slices end at or before this offset.
290 uint64_t endOffset() const { return EndOffset; }
291
292 /// \brief The size of the partition.
293 ///
294 /// Note that this can never be zero.
295 uint64_t size() const {
296 assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
297 return EndOffset - BeginOffset;
298 }
299
300 /// \brief Test whether this partition contains no slices, and merely spans
301 /// a region occupied by split slices.
302 bool empty() const { return SI == SJ; }
303
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000304 /// \name Iterate slices that start within the partition.
305 /// These may be splittable or unsplittable. They have a begin offset >= the
306 /// partition begin offset.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000307 /// @{
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000308 // FIXME: We should probably define a "concat_iterator" helper and use that
309 // to stitch together pointee_iterators over the split tails and the
310 // contiguous iterators of the partition. That would give a much nicer
311 // interface here. We could then additionally expose filtered iterators for
312 // split, unsplit, and unsplittable splices based on the usage patterns.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000313 iterator begin() const { return SI; }
314 iterator end() const { return SJ; }
315 /// @}
316
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000317 /// \brief Get the sequence of split slice tails.
318 ///
319 /// These tails are of slices which start before this partition but are
320 /// split and overlap into the partition. We accumulate these while forming
321 /// partitions.
322 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000323 };
324
325 /// \brief An iterator over partitions of the alloca's slices.
326 ///
327 /// This iterator implements the core algorithm for partitioning the alloca's
328 /// slices. It is a forward iterator as we don't support backtracking for
329 /// efficiency reasons, and re-use a single storage area to maintain the
330 /// current set of split slices.
331 ///
332 /// It is templated on the slice iterator type to use so that it can operate
333 /// with either const or non-const slice iterators.
334 class partition_iterator
335 : public iterator_facade_base<partition_iterator,
336 std::forward_iterator_tag, Partition> {
337 friend class AllocaSlices;
338
339 /// \brief Most of the state for walking the partitions is held in a class
340 /// with a nice interface for examining them.
341 Partition P;
342
343 /// \brief We need to keep the end of the slices to know when to stop.
344 AllocaSlices::iterator SE;
345
346 /// \brief We also need to keep track of the maximum split end offset seen.
347 /// FIXME: Do we really?
348 uint64_t MaxSplitSliceEndOffset;
349
350 /// \brief Sets the partition to be empty at given iterator, and sets the
351 /// end iterator.
352 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
353 : P(SI), SE(SE), MaxSplitSliceEndOffset(0) {
354 // If not already at the end, advance our state to form the initial
355 // partition.
356 if (SI != SE)
357 advance();
358 }
359
360 /// \brief Advance the iterator to the next partition.
361 ///
362 /// Requires that the iterator not be at the end of the slices.
363 void advance() {
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000364 assert((P.SI != SE || !P.SplitTails.empty()) &&
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000365 "Cannot advance past the end of the slices!");
366
367 // Clear out any split uses which have ended.
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000368 if (!P.SplitTails.empty()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000369 if (P.EndOffset >= MaxSplitSliceEndOffset) {
370 // If we've finished all splits, this is easy.
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000371 P.SplitTails.clear();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000372 MaxSplitSliceEndOffset = 0;
373 } else {
374 // Remove the uses which have ended in the prior partition. This
375 // cannot change the max split slice end because we just checked that
376 // the prior partition ended prior to that max.
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000377 P.SplitTails.erase(
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000378 std::remove_if(
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000379 P.SplitTails.begin(), P.SplitTails.end(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000380 [&](Slice *S) { return S->endOffset() <= P.EndOffset; }),
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000381 P.SplitTails.end());
382 assert(std::any_of(P.SplitTails.begin(), P.SplitTails.end(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000383 [&](Slice *S) {
384 return S->endOffset() == MaxSplitSliceEndOffset;
385 }) &&
386 "Could not find the current max split slice offset!");
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000387 assert(std::all_of(P.SplitTails.begin(), P.SplitTails.end(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000388 [&](Slice *S) {
389 return S->endOffset() <= MaxSplitSliceEndOffset;
390 }) &&
391 "Max split slice end offset is not actually the max!");
392 }
393 }
394
395 // If P.SI is already at the end, then we've cleared the split tail and
396 // now have an end iterator.
397 if (P.SI == SE) {
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000398 assert(P.SplitTails.empty() && "Failed to clear the split slices!");
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000399 return;
400 }
401
402 // If we had a non-empty partition previously, set up the state for
403 // subsequent partitions.
404 if (P.SI != P.SJ) {
405 // Accumulate all the splittable slices which started in the old
406 // partition into the split list.
407 for (Slice &S : P)
408 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000409 P.SplitTails.push_back(&S);
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000410 MaxSplitSliceEndOffset =
411 std::max(S.endOffset(), MaxSplitSliceEndOffset);
412 }
413
414 // Start from the end of the previous partition.
415 P.SI = P.SJ;
416
417 // If P.SI is now at the end, we at most have a tail of split slices.
418 if (P.SI == SE) {
419 P.BeginOffset = P.EndOffset;
420 P.EndOffset = MaxSplitSliceEndOffset;
421 return;
422 }
423
424 // If the we have split slices and the next slice is after a gap and is
425 // not splittable immediately form an empty partition for the split
426 // slices up until the next slice begins.
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000427 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000428 !P.SI->isSplittable()) {
429 P.BeginOffset = P.EndOffset;
430 P.EndOffset = P.SI->beginOffset();
431 return;
432 }
433 }
434
435 // OK, we need to consume new slices. Set the end offset based on the
436 // current slice, and step SJ past it. The beginning offset of the
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000437 // partition is the beginning offset of the next slice unless we have
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000438 // pre-existing split slices that are continuing, in which case we begin
439 // at the prior end offset.
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000440 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000441 P.EndOffset = P.SI->endOffset();
442 ++P.SJ;
443
444 // There are two strategies to form a partition based on whether the
445 // partition starts with an unsplittable slice or a splittable slice.
446 if (!P.SI->isSplittable()) {
447 // When we're forming an unsplittable region, it must always start at
448 // the first slice and will extend through its end.
449 assert(P.BeginOffset == P.SI->beginOffset());
450
451 // Form a partition including all of the overlapping slices with this
452 // unsplittable slice.
453 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
454 if (!P.SJ->isSplittable())
455 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
456 ++P.SJ;
457 }
458
459 // We have a partition across a set of overlapping unsplittable
460 // partitions.
461 return;
462 }
463
464 // If we're starting with a splittable slice, then we need to form
465 // a synthetic partition spanning it and any other overlapping splittable
466 // splices.
467 assert(P.SI->isSplittable() && "Forming a splittable partition!");
468
469 // Collect all of the overlapping splittable slices.
470 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
471 P.SJ->isSplittable()) {
472 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
473 ++P.SJ;
474 }
475
476 // Back upiP.EndOffset if we ended the span early when encountering an
477 // unsplittable slice. This synthesizes the early end offset of
478 // a partition spanning only splittable slices.
479 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
480 assert(!P.SJ->isSplittable());
481 P.EndOffset = P.SJ->beginOffset();
482 }
483 }
484
485 public:
486 bool operator==(const partition_iterator &RHS) const {
487 assert(SE == RHS.SE &&
488 "End iterators don't match between compared partition iterators!");
489
490 // The observed positions of partitions is marked by the P.SI iterator and
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000491 // the emptiness of the split slices. The latter is only relevant when
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000492 // P.SI == SE, as the end iterator will additionally have an empty split
493 // slices list, but the prior may have the same P.SI and a tail of split
494 // slices.
495 if (P.SI == RHS.P.SI &&
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000496 P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000497 assert(P.SJ == RHS.P.SJ &&
498 "Same set of slices formed two different sized partitions!");
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000499 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000500 "Same slice position with differently sized non-empty split "
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000501 "slice tails!");
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000502 return true;
503 }
504 return false;
505 }
506
507 partition_iterator &operator++() {
508 advance();
509 return *this;
510 }
511
512 Partition &operator*() { return P; }
513 };
514
515 /// \brief A forward range over the partitions of the alloca's slices.
516 ///
517 /// This accesses an iterator range over the partitions of the alloca's
518 /// slices. It computes these partitions on the fly based on the overlapping
519 /// offsets of the slices and the ability to split them. It will visit "empty"
520 /// partitions to cover regions of the alloca only accessed via split
521 /// slices.
522 iterator_range<partition_iterator> partitions() {
523 return make_range(partition_iterator(begin(), end()),
524 partition_iterator(end(), end()));
525 }
526
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000527 /// \brief Access the dead users for this alloca.
528 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000529
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000530 /// \brief Access the dead operands referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000531 ///
532 /// These are operands which have cannot actually be used to refer to the
533 /// alloca as they are outside its range and the user doesn't correct for
534 /// that. These mostly consist of PHI node inputs and the like which we just
535 /// need to replace with undef.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000536 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000537
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000538#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000539 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000540 void printSlice(raw_ostream &OS, const_iterator I,
541 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000542 void printUse(raw_ostream &OS, const_iterator I,
543 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000544 void print(raw_ostream &OS) const;
Alp Tokerf929e092014-01-04 22:47:48 +0000545 void dump(const_iterator I) const;
546 void dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000547#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000548
549private:
550 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000551 class SliceBuilder;
552 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000553
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000554#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000555 /// \brief Handle to alloca instruction to simplify method interfaces.
556 AllocaInst &AI;
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000557#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000558
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000559 /// \brief The instruction responsible for this alloca not having a known set
560 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000561 ///
562 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000563 /// store a pointer to that here and abort trying to form slices of the
564 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000565 Instruction *PointerEscapingInstr;
566
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000567 /// \brief The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000568 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000569 /// We store a vector of the slices formed by uses of the alloca here. This
570 /// vector is sorted by increasing begin offset, and then the unsplittable
571 /// slices before the splittable ones. See the Slice inner class for more
572 /// details.
573 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000574
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000575 /// \brief Instructions which will become dead if we rewrite the alloca.
576 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000577 /// Note that these are not separated by slice. This is because we expect an
578 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
579 /// all these instructions can simply be removed and replaced with undef as
580 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000581 SmallVector<Instruction *, 8> DeadUsers;
582
583 /// \brief Operands which will become dead if we rewrite the alloca.
584 ///
585 /// These are operands that in their particular use can be replaced with
586 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
587 /// to PHI nodes and the like. They aren't entirely dead (there might be
588 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
589 /// want to swap this particular input for undef to simplify the use lists of
590 /// the alloca.
591 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000592};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000593}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000594
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000595static Value *foldSelectInst(SelectInst &SI) {
596 // If the condition being selected on is a constant or the same value is
597 // being selected between, fold the select. Yes this does (rarely) happen
598 // early on.
599 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
Chandler Carruth113dc642014-12-20 02:39:18 +0000600 return SI.getOperand(1 + CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000601 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000602 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000603
Craig Topperf40110f2014-04-25 05:29:35 +0000604 return nullptr;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000605}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000606
Jingyue Wuec33fa92014-08-22 22:45:57 +0000607/// \brief A helper that folds a PHI node or a select.
608static Value *foldPHINodeOrSelectInst(Instruction &I) {
609 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
610 // If PN merges together the same value, return that value.
611 return PN->hasConstantValue();
612 }
613 return foldSelectInst(cast<SelectInst>(I));
614}
615
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000616/// \brief Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000617///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000618/// This class builds a set of alloca slices by recursively visiting the uses
619/// of an alloca and making a slice for each load and store at each offset.
620class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
621 friend class PtrUseVisitor<SliceBuilder>;
622 friend class InstVisitor<SliceBuilder>;
623 typedef PtrUseVisitor<SliceBuilder> Base;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000624
625 const uint64_t AllocSize;
Chandler Carruth83934062014-10-16 21:11:55 +0000626 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000627
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000628 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000629 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
630
631 /// \brief Set to de-duplicate dead instructions found in the use walk.
632 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000633
634public:
Chandler Carruth83934062014-10-16 21:11:55 +0000635 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000636 : PtrUseVisitor<SliceBuilder>(DL),
Chandler Carruth83934062014-10-16 21:11:55 +0000637 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000638
639private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000640 void markAsDead(Instruction &I) {
David Blaikie70573dc2014-11-19 07:49:26 +0000641 if (VisitedDeadInsts.insert(&I).second)
Chandler Carruth83934062014-10-16 21:11:55 +0000642 AS.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000643 }
644
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000645 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000646 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000647 // Completely skip uses which have a zero size or start either before or
648 // past the end of the allocation.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000649 if (Size == 0 || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000650 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000651 << " which has zero size or starts outside of the "
652 << AllocSize << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000653 << " alloca: " << AS.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000654 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000655 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000656 }
657
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000658 uint64_t BeginOffset = Offset.getZExtValue();
659 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000660
661 // Clamp the end offset to the end of the allocation. Note that this is
662 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000663 // This may appear superficially to be something we could ignore entirely,
664 // but that is not so! There may be widened loads or PHI-node uses where
665 // some instructions are dead but not others. We can't completely ignore
666 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000667 assert(AllocSize >= BeginOffset); // Established above.
668 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000669 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
670 << " to remain within the " << AllocSize << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000671 << " alloca: " << AS.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000672 << " use: " << I << "\n");
673 EndOffset = AllocSize;
674 }
675
Chandler Carruth83934062014-10-16 21:11:55 +0000676 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000677 }
678
679 void visitBitCastInst(BitCastInst &BC) {
680 if (BC.use_empty())
681 return markAsDead(BC);
682
683 return Base::visitBitCastInst(BC);
684 }
685
686 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
687 if (GEPI.use_empty())
688 return markAsDead(GEPI);
689
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000690 if (SROAStrictInbounds && GEPI.isInBounds()) {
691 // FIXME: This is a manually un-factored variant of the basic code inside
692 // of GEPs with checking of the inbounds invariant specified in the
693 // langref in a very strict sense. If we ever want to enable
694 // SROAStrictInbounds, this code should be factored cleanly into
695 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
696 // by writing out the code here where we have tho underlying allocation
697 // size readily available.
698 APInt GEPOffset = Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000699 const DataLayout &DL = GEPI.getModule()->getDataLayout();
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000700 for (gep_type_iterator GTI = gep_type_begin(GEPI),
701 GTE = gep_type_end(GEPI);
702 GTI != GTE; ++GTI) {
703 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
704 if (!OpC)
705 break;
706
707 // Handle a struct index, which adds its field offset to the pointer.
708 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
709 unsigned ElementIdx = OpC->getZExtValue();
710 const StructLayout *SL = DL.getStructLayout(STy);
711 GEPOffset +=
712 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
713 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +0000714 // For array or vector indices, scale the index by the size of the
715 // type.
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000716 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
717 GEPOffset += Index * APInt(Offset.getBitWidth(),
718 DL.getTypeAllocSize(GTI.getIndexedType()));
719 }
720
721 // If this index has computed an intermediate pointer which is not
722 // inbounds, then the result of the GEP is a poison value and we can
723 // delete it and all uses.
724 if (GEPOffset.ugt(AllocSize))
725 return markAsDead(GEPI);
726 }
727 }
728
Chandler Carruthf0546402013-07-18 07:15:00 +0000729 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000730 }
731
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000732 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000733 uint64_t Size, bool IsVolatile) {
Chandler Carruth24ac8302015-01-02 03:55:54 +0000734 // We allow splitting of non-volatile loads and stores where the type is an
735 // integer type. These may be used to implement 'memcpy' or other "transfer
736 // of bits" patterns.
737 bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
Chandler Carruth58d05562012-10-25 04:37:07 +0000738
739 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000740 }
741
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000742 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000743 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
744 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000745
746 if (!IsOffsetKnown)
747 return PI.setAborted(&LI);
748
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000749 const DataLayout &DL = LI.getModule()->getDataLayout();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000750 uint64_t Size = DL.getTypeStoreSize(LI.getType());
751 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000752 }
753
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000754 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000755 Value *ValOp = SI.getValueOperand();
756 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000757 return PI.setEscapedAndAborted(&SI);
758 if (!IsOffsetKnown)
759 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000760
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000761 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000762 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
763
764 // If this memory access can be shown to *statically* extend outside the
765 // bounds of of the allocation, it's behavior is undefined, so simply
766 // ignore it. Note that this is more strict than the generic clamping
767 // behavior of insertUse. We also try to handle cases which might run the
768 // risk of overflow.
769 // FIXME: We should instead consider the pointer to have escaped if this
770 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000771 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000772 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
773 << " which extends past the end of the " << AllocSize
774 << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000775 << " alloca: " << AS.AI << "\n"
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000776 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000777 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000778 }
779
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000780 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
781 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000782 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000783 }
784
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000785 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000786 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000787 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000788 if ((Length && Length->getValue() == 0) ||
Chandler Carruth6aedc102014-02-26 03:14:14 +0000789 (IsOffsetKnown && Offset.uge(AllocSize)))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000790 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000791 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000792
793 if (!IsOffsetKnown)
794 return PI.setAborted(&II);
795
Chandler Carruth113dc642014-12-20 02:39:18 +0000796 insertUse(II, Offset, Length ? Length->getLimitedValue()
797 : AllocSize - Offset.getLimitedValue(),
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000798 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000799 }
800
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000801 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000802 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000803 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000804 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000805 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000806
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000807 // Because we can visit these intrinsics twice, also check to see if the
808 // first time marked this instruction as dead. If so, skip it.
809 if (VisitedDeadInsts.count(&II))
810 return;
811
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000812 if (!IsOffsetKnown)
813 return PI.setAborted(&II);
814
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000815 // This side of the transfer is completely out-of-bounds, and so we can
816 // nuke the entire transfer. However, we also need to nuke the other side
817 // if already added to our partitions.
818 // FIXME: Yet another place we really should bypass this when
819 // instrumenting for ASan.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000820 if (Offset.uge(AllocSize)) {
Chandler Carruth113dc642014-12-20 02:39:18 +0000821 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
822 MemTransferSliceMap.find(&II);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000823 if (MTPI != MemTransferSliceMap.end())
Chandler Carruth83934062014-10-16 21:11:55 +0000824 AS.Slices[MTPI->second].kill();
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000825 return markAsDead(II);
826 }
827
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000828 uint64_t RawOffset = Offset.getLimitedValue();
Chandler Carruth113dc642014-12-20 02:39:18 +0000829 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000830
Chandler Carruthf0546402013-07-18 07:15:00 +0000831 // Check for the special case where the same exact value is used for both
832 // source and dest.
833 if (*U == II.getRawDest() && *U == II.getRawSource()) {
834 // For non-volatile transfers this is a no-op.
835 if (!II.isVolatile())
836 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000837
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000838 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000839 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000840
Chandler Carruthf0546402013-07-18 07:15:00 +0000841 // If we have seen both source and destination for a mem transfer, then
842 // they both point to the same alloca.
843 bool Inserted;
844 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000845 std::tie(MTPI, Inserted) =
Chandler Carruth83934062014-10-16 21:11:55 +0000846 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000847 unsigned PrevIdx = MTPI->second;
848 if (!Inserted) {
Chandler Carruth83934062014-10-16 21:11:55 +0000849 Slice &PrevP = AS.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000850
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000851 // Check if the begin offsets match and this is a non-volatile transfer.
852 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000853 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
854 PrevP.kill();
855 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000856 }
857
858 // Otherwise we have an offset transfer within the same alloca. We can't
859 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000860 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000861 }
862
Chandler Carruthe3899f22013-07-15 17:36:21 +0000863 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000864 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000865
Chandler Carruthf0546402013-07-18 07:15:00 +0000866 // Check that we ended up with a valid index in the map.
Chandler Carruth83934062014-10-16 21:11:55 +0000867 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000868 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000869 }
870
871 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000872 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000873 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000874 void visitIntrinsicInst(IntrinsicInst &II) {
875 if (!IsOffsetKnown)
876 return PI.setAborted(&II);
877
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000878 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
879 II.getIntrinsicID() == Intrinsic::lifetime_end) {
880 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000881 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
882 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000883 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000884 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000885 }
886
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000887 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000888 }
889
890 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
891 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000892 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000893 // are considered unsplittable and the size is the maximum loaded or stored
894 // size.
895 SmallPtrSet<Instruction *, 4> Visited;
896 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
897 Visited.insert(Root);
898 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000899 const DataLayout &DL = Root->getModule()->getDataLayout();
Chandler Carruth8b907e82012-09-25 10:03:40 +0000900 // If there are no loads or stores, the access is dead. We mark that as
901 // a size zero access.
902 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000903 do {
904 Instruction *I, *UsedI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000905 std::tie(UsedI, I) = Uses.pop_back_val();
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000906
907 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000908 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000909 continue;
910 }
911 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
912 Value *Op = SI->getOperand(0);
913 if (Op == UsedI)
914 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000915 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000916 continue;
917 }
918
919 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
920 if (!GEP->hasAllZeroIndices())
921 return GEP;
922 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
923 !isa<SelectInst>(I)) {
924 return I;
925 }
926
Chandler Carruthcdf47882014-03-09 03:16:01 +0000927 for (User *U : I->users())
David Blaikie70573dc2014-11-19 07:49:26 +0000928 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000929 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000930 } while (!Uses.empty());
931
Craig Topperf40110f2014-04-25 05:29:35 +0000932 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000933 }
934
Jingyue Wuec33fa92014-08-22 22:45:57 +0000935 void visitPHINodeOrSelectInst(Instruction &I) {
936 assert(isa<PHINode>(I) || isa<SelectInst>(I));
937 if (I.use_empty())
938 return markAsDead(I);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000939
Jingyue Wuec33fa92014-08-22 22:45:57 +0000940 // TODO: We could use SimplifyInstruction here to fold PHINodes and
941 // SelectInsts. However, doing so requires to change the current
942 // dead-operand-tracking mechanism. For instance, suppose neither loading
943 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
944 // trap either. However, if we simply replace %U with undef using the
945 // current dead-operand-tracking mechanism, "load (select undef, undef,
946 // %other)" may trap because the select may return the first operand
947 // "undef".
948 if (Value *Result = foldPHINodeOrSelectInst(I)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000949 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000950 // If the result of the constant fold will be the pointer, recurse
Jingyue Wuec33fa92014-08-22 22:45:57 +0000951 // through the PHI/select as if we had RAUW'ed it.
952 enqueueUsers(I);
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000953 else
Jingyue Wuec33fa92014-08-22 22:45:57 +0000954 // Otherwise the operand to the PHI/select is dead, and we can replace
955 // it with undef.
Chandler Carruth83934062014-10-16 21:11:55 +0000956 AS.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000957
958 return;
959 }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000960
Chandler Carruthf0546402013-07-18 07:15:00 +0000961 if (!IsOffsetKnown)
Jingyue Wuec33fa92014-08-22 22:45:57 +0000962 return PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000963
Chandler Carruthf0546402013-07-18 07:15:00 +0000964 // See if we already have computed info on this node.
Jingyue Wuec33fa92014-08-22 22:45:57 +0000965 uint64_t &Size = PHIOrSelectSizes[&I];
966 if (!Size) {
967 // This is a new PHI/Select, check for an unsafe use of it.
968 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
Chandler Carruthf0546402013-07-18 07:15:00 +0000969 return PI.setAborted(UnsafeI);
970 }
971
972 // For PHI and select operands outside the alloca, we can't nuke the entire
973 // phi or select -- the other side might still be relevant, so we special
974 // case them here and use a separate structure to track the operands
975 // themselves which should be replaced with undef.
976 // FIXME: This should instead be escaped in the event we're instrumenting
977 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000978 if (Offset.uge(AllocSize)) {
Chandler Carruth83934062014-10-16 21:11:55 +0000979 AS.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +0000980 return;
981 }
982
Jingyue Wuec33fa92014-08-22 22:45:57 +0000983 insertUse(I, Offset, Size);
984 }
985
Chandler Carruth113dc642014-12-20 02:39:18 +0000986 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000987
Chandler Carruth113dc642014-12-20 02:39:18 +0000988 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000989
Chandler Carruthf0546402013-07-18 07:15:00 +0000990 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth113dc642014-12-20 02:39:18 +0000991 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000992};
993
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000994AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000995 :
996#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
997 AI(AI),
998#endif
Craig Topperf40110f2014-04-25 05:29:35 +0000999 PointerEscapingInstr(nullptr) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001000 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001001 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001002 if (PtrI.isEscaped() || PtrI.isAborted()) {
1003 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001004 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001005 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1006 : PtrI.getAbortingInst();
1007 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001008 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001009 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001010
Benjamin Kramer08e50702013-07-20 08:38:34 +00001011 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
Chandler Carruth68ea4152014-12-18 05:19:47 +00001012 [](const Slice &S) {
1013 return S.isDead();
1014 }),
Benjamin Kramer08e50702013-07-20 08:38:34 +00001015 Slices.end());
1016
Chandler Carruth83cee772014-02-25 03:59:29 +00001017#if __cplusplus >= 201103L && !defined(NDEBUG)
1018 if (SROARandomShuffleSlices) {
1019 std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
1020 std::shuffle(Slices.begin(), Slices.end(), MT);
1021 }
1022#endif
1023
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001024 // Sort the uses. This arranges for the offsets to be in ascending order,
1025 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001026 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001027}
1028
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001029#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1030
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001031void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1032 StringRef Indent) const {
1033 printSlice(OS, I, Indent);
Chandler Carruth0715cba2015-01-01 11:54:38 +00001034 OS << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001035 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001036}
1037
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001038void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1039 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001040 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001041 << " slice #" << (I - begin())
Chandler Carruth0715cba2015-01-01 11:54:38 +00001042 << (I->isSplittable() ? " (splittable)" : "");
Chandler Carruthf0546402013-07-18 07:15:00 +00001043}
1044
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001045void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1046 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001047 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001048}
1049
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001050void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001051 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001052 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001053 << " A pointer to this alloca escaped by:\n"
1054 << " " << *PointerEscapingInstr << "\n";
1055 return;
1056 }
1057
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001058 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001059 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001060 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001061}
1062
Alp Tokerf929e092014-01-04 22:47:48 +00001063LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1064 print(dbgs(), I);
1065}
1066LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001067
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001068#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1069
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001070namespace {
1071/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1072///
1073/// This pass takes allocations which can be completely analyzed (that is, they
1074/// don't escape) and tries to turn them into scalar SSA values. There are
1075/// a few steps to this process.
1076///
1077/// 1) It takes allocations of aggregates and analyzes the ways in which they
1078/// are used to try to split them into smaller allocations, ideally of
1079/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001080/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001081/// 2) It will transform accesses into forms which are suitable for SSA value
1082/// promotion. This can be replacing a memset with a scalar store of an
1083/// integer value, or it can involve speculating operations on a PHI or
1084/// select to be a PHI or select of the results.
1085/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1086/// onto insert and extract operations on a vector value, and convert them to
1087/// this form. By doing so, it will enable promotion of vector aggregates to
1088/// SSA vector values.
1089class SROA : public FunctionPass {
1090 LLVMContext *C;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001091 DominatorTree *DT;
Chandler Carruth66b31302015-01-04 12:03:27 +00001092 AssumptionCache *AC;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001093
1094 /// \brief Worklist of alloca instructions to simplify.
1095 ///
1096 /// Each alloca in the function is added to this. Each new alloca formed gets
1097 /// added to it as well to recursively simplify unless that alloca can be
1098 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1099 /// the one being actively rewritten, we add it back onto the list if not
1100 /// already present to ensure it is re-visited.
Chandler Carruth113dc642014-12-20 02:39:18 +00001101 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> Worklist;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001102
1103 /// \brief A collection of instructions to delete.
1104 /// We try to batch deletions to simplify code and make things a bit more
1105 /// efficient.
Chandler Carruth113dc642014-12-20 02:39:18 +00001106 SetVector<Instruction *, SmallVector<Instruction *, 8>> DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001107
Chandler Carruthac8317f2012-10-04 12:33:50 +00001108 /// \brief Post-promotion worklist.
1109 ///
1110 /// Sometimes we discover an alloca which has a high probability of becoming
1111 /// viable for SROA after a round of promotion takes place. In those cases,
1112 /// the alloca is enqueued here for re-processing.
1113 ///
1114 /// Note that we have to be very careful to clear allocas out of this list in
1115 /// the event they are deleted.
Chandler Carruth113dc642014-12-20 02:39:18 +00001116 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> PostPromotionWorklist;
Chandler Carruthac8317f2012-10-04 12:33:50 +00001117
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001118 /// \brief A collection of alloca instructions we can directly promote.
1119 std::vector<AllocaInst *> PromotableAllocas;
1120
Chandler Carruthf0546402013-07-18 07:15:00 +00001121 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
1122 ///
1123 /// All of these PHIs have been checked for the safety of speculation and by
1124 /// being speculated will allow promoting allocas currently in the promotable
1125 /// queue.
Chandler Carruth113dc642014-12-20 02:39:18 +00001126 SetVector<PHINode *, SmallVector<PHINode *, 2>> SpeculatablePHIs;
Chandler Carruthf0546402013-07-18 07:15:00 +00001127
1128 /// \brief A worklist of select instructions to speculate prior to promoting
1129 /// allocas.
1130 ///
1131 /// All of these select instructions have been checked for the safety of
1132 /// speculation and by being speculated will allow promoting allocas
1133 /// currently in the promotable queue.
Chandler Carruth113dc642014-12-20 02:39:18 +00001134 SetVector<SelectInst *, SmallVector<SelectInst *, 2>> SpeculatableSelects;
Chandler Carruthf0546402013-07-18 07:15:00 +00001135
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001136public:
Chandler Carruth748d0952015-08-26 09:09:29 +00001137 SROA() : FunctionPass(ID), C(nullptr), DT(nullptr) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001138 initializeSROAPass(*PassRegistry::getPassRegistry());
1139 }
Craig Topper3e4c6972014-03-05 09:10:37 +00001140 bool runOnFunction(Function &F) override;
1141 void getAnalysisUsage(AnalysisUsage &AU) const override;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001142
Craig Topper3e4c6972014-03-05 09:10:37 +00001143 const char *getPassName() const override { return "SROA"; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001144 static char ID;
1145
1146private:
Chandler Carruth82a57542012-10-01 10:54:05 +00001147 friend class PHIOrSelectSpeculator;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001148 friend class AllocaSliceRewriter;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001149
Chandler Carruth0715cba2015-01-01 11:54:38 +00001150 bool presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS);
Adrian Prantl565cc182015-01-20 19:42:22 +00001151 AllocaInst *rewritePartition(AllocaInst &AI, AllocaSlices &AS,
1152 AllocaSlices::Partition &P);
Chandler Carruth83934062014-10-16 21:11:55 +00001153 bool splitAlloca(AllocaInst &AI, AllocaSlices &AS);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001154 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00001155 void clobberUse(Use &U);
Craig Topper71b7b682014-08-21 05:55:13 +00001156 void deleteDeadInstructions(SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +00001157 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001158};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001159}
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001160
1161char SROA::ID = 0;
1162
Chandler Carruth748d0952015-08-26 09:09:29 +00001163FunctionPass *llvm::createSROAPass() {
1164 return new SROA();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001165}
1166
Chandler Carruth113dc642014-12-20 02:39:18 +00001167INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
1168 false)
Chandler Carruth66b31302015-01-04 12:03:27 +00001169INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth73523022014-01-13 13:07:17 +00001170INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth113dc642014-12-20 02:39:18 +00001171INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
1172 false)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001173
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001174/// Walk the range of a partitioning looking for a common type to cover this
1175/// sequence of slices.
1176static Type *findCommonType(AllocaSlices::const_iterator B,
1177 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001178 uint64_t EndOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001179 Type *Ty = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001180 bool TyIsCommon = true;
Craig Topperf40110f2014-04-25 05:29:35 +00001181 IntegerType *ITy = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001182
1183 // Note that we need to look at *every* alloca slice's Use to ensure we
1184 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001185 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001186 Use *U = I->getUse();
1187 if (isa<IntrinsicInst>(*U->getUser()))
1188 continue;
1189 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1190 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001191
Craig Topperf40110f2014-04-25 05:29:35 +00001192 Type *UserTy = nullptr;
Chandler Carrutha1262002013-11-19 09:03:18 +00001193 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001194 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001195 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001196 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001197 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001198
Chandler Carruth4de31542014-01-21 23:16:05 +00001199 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001200 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001201 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001202 // entity causing the split. Also skip if the type is not a byte width
1203 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001204 if (UserITy->getBitWidth() % 8 != 0 ||
1205 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001206 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001207
Chandler Carruth4de31542014-01-21 23:16:05 +00001208 // Track the largest bitwidth integer type used in this way in case there
1209 // is no common type.
1210 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1211 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001212 }
Duncan P. N. Exon Smith73686d32014-06-17 00:19:35 +00001213
1214 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1215 // depend on types skipped above.
1216 if (!UserTy || (Ty && Ty != UserTy))
1217 TyIsCommon = false; // Give up on anything but an iN type.
1218 else
1219 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001220 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001221
1222 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001223}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001224
Chandler Carruthf0546402013-07-18 07:15:00 +00001225/// PHI instructions that use an alloca and are subsequently loaded can be
1226/// rewritten to load both input pointers in the pred blocks and then PHI the
1227/// results, allowing the load of the alloca to be promoted.
1228/// From this:
1229/// %P2 = phi [i32* %Alloca, i32* %Other]
1230/// %V = load i32* %P2
1231/// to:
1232/// %V1 = load i32* %Alloca -> will be mem2reg'd
1233/// ...
1234/// %V2 = load i32* %Other
1235/// ...
1236/// %V = phi [i32 %V1, i32 %V2]
1237///
1238/// We can do this to a select if its only uses are loads and if the operands
1239/// to the select can be loaded unconditionally.
1240///
1241/// FIXME: This should be hoisted into a generic utility, likely in
1242/// Transforms/Util/Local.h
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001243static bool isSafePHIToSpeculate(PHINode &PN) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001244 // For now, we can only do this promotion if the load is in the same block
1245 // as the PHI, and if there are no stores between the phi and load.
1246 // TODO: Allow recursive phi users.
1247 // TODO: Allow stores.
1248 BasicBlock *BB = PN.getParent();
1249 unsigned MaxAlign = 0;
1250 bool HaveLoad = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001251 for (User *U : PN.users()) {
1252 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001253 if (!LI || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001254 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001255
Chandler Carruthf0546402013-07-18 07:15:00 +00001256 // For now we only allow loads in the same block as the PHI. This is
1257 // a common case that happens when instcombine merges two loads through
1258 // a PHI.
1259 if (LI->getParent() != BB)
1260 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001261
Chandler Carruthf0546402013-07-18 07:15:00 +00001262 // Ensure that there are no instructions between the PHI and the load that
1263 // could store.
1264 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1265 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001266 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001267
Chandler Carruthf0546402013-07-18 07:15:00 +00001268 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1269 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001270 }
1271
Chandler Carruthf0546402013-07-18 07:15:00 +00001272 if (!HaveLoad)
1273 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001274
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001275 const DataLayout &DL = PN.getModule()->getDataLayout();
1276
Chandler Carruthf0546402013-07-18 07:15:00 +00001277 // We can only transform this if it is safe to push the loads into the
1278 // predecessor blocks. The only thing to watch out for is that we can't put
1279 // a possibly trapping load in the predecessor if it is a critical edge.
1280 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1281 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1282 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001283
Chandler Carruthf0546402013-07-18 07:15:00 +00001284 // If the value is produced by the terminator of the predecessor (an
1285 // invoke) or it has side-effects, there is no valid place to put a load
1286 // in the predecessor.
1287 if (TI == InVal || TI->mayHaveSideEffects())
1288 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001289
Chandler Carruthf0546402013-07-18 07:15:00 +00001290 // If the predecessor has a single successor, then the edge isn't
1291 // critical.
1292 if (TI->getNumSuccessors() == 1)
1293 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001294
Chandler Carruthf0546402013-07-18 07:15:00 +00001295 // If this pointer is always safe to load, or if we can prove that there
1296 // is already a load in the block, then we can move the load to the pred
1297 // block.
Philip Reames5461d452015-04-23 17:36:48 +00001298 if (isDereferenceablePointer(InVal, DL) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001299 isSafeToLoadUnconditionally(InVal, TI, MaxAlign))
Chandler Carruthf0546402013-07-18 07:15:00 +00001300 continue;
1301
1302 return false;
1303 }
1304
1305 return true;
1306}
1307
1308static void speculatePHINodeLoads(PHINode &PN) {
1309 DEBUG(dbgs() << " original: " << PN << "\n");
1310
1311 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1312 IRBuilderTy PHIBuilder(&PN);
1313 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1314 PN.getName() + ".sroa.speculated");
1315
Hal Finkelcc39b672014-07-24 12:16:19 +00001316 // Get the AA tags and alignment to use from one of the loads. It doesn't
Chandler Carruthf0546402013-07-18 07:15:00 +00001317 // matter which one we get and if any differ.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001318 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
Hal Finkelcc39b672014-07-24 12:16:19 +00001319
1320 AAMDNodes AATags;
1321 SomeLoad->getAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001322 unsigned Align = SomeLoad->getAlignment();
1323
1324 // Rewrite all loads of the PN to use the new PHI.
1325 while (!PN.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001326 LoadInst *LI = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001327 LI->replaceAllUsesWith(NewPN);
1328 LI->eraseFromParent();
1329 }
1330
1331 // Inject loads into all of the pred blocks.
1332 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1333 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1334 TerminatorInst *TI = Pred->getTerminator();
1335 Value *InVal = PN.getIncomingValue(Idx);
1336 IRBuilderTy PredBuilder(TI);
1337
1338 LoadInst *Load = PredBuilder.CreateLoad(
1339 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1340 ++NumLoadsSpeculated;
1341 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001342 if (AATags)
1343 Load->setAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001344 NewPN->addIncoming(Load, Pred);
1345 }
1346
1347 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1348 PN.eraseFromParent();
1349}
1350
1351/// Select instructions that use an alloca and are subsequently loaded can be
1352/// rewritten to load both input pointers and then select between the result,
1353/// allowing the load of the alloca to be promoted.
1354/// From this:
1355/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1356/// %V = load i32* %P2
1357/// to:
1358/// %V1 = load i32* %Alloca -> will be mem2reg'd
1359/// %V2 = load i32* %Other
1360/// %V = select i1 %cond, i32 %V1, i32 %V2
1361///
1362/// We can do this to a select if its only uses are loads and if the operand
1363/// to the select can be loaded unconditionally.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001364static bool isSafeSelectToSpeculate(SelectInst &SI) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001365 Value *TValue = SI.getTrueValue();
1366 Value *FValue = SI.getFalseValue();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001367 const DataLayout &DL = SI.getModule()->getDataLayout();
Philip Reames5461d452015-04-23 17:36:48 +00001368 bool TDerefable = isDereferenceablePointer(TValue, DL);
1369 bool FDerefable = isDereferenceablePointer(FValue, DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00001370
Chandler Carruthcdf47882014-03-09 03:16:01 +00001371 for (User *U : SI.users()) {
1372 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001373 if (!LI || !LI->isSimple())
Chandler Carruthf0546402013-07-18 07:15:00 +00001374 return false;
1375
1376 // Both operands to the select need to be dereferencable, either
1377 // absolutely (e.g. allocas) or at this point because we can see other
1378 // accesses to it.
1379 if (!TDerefable &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001380 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001381 return false;
1382 if (!FDerefable &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001383 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001384 return false;
1385 }
1386
1387 return true;
1388}
1389
1390static void speculateSelectInstLoads(SelectInst &SI) {
1391 DEBUG(dbgs() << " original: " << SI << "\n");
1392
1393 IRBuilderTy IRB(&SI);
1394 Value *TV = SI.getTrueValue();
1395 Value *FV = SI.getFalseValue();
1396 // Replace the loads of the select with a select of two loads.
1397 while (!SI.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001398 LoadInst *LI = cast<LoadInst>(SI.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001399 assert(LI->isSimple() && "We only speculate simple loads");
1400
1401 IRB.SetInsertPoint(LI);
1402 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001403 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001404 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001405 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001406 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001407
Hal Finkelcc39b672014-07-24 12:16:19 +00001408 // Transfer alignment and AA info if present.
Chandler Carruthf0546402013-07-18 07:15:00 +00001409 TL->setAlignment(LI->getAlignment());
1410 FL->setAlignment(LI->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +00001411
1412 AAMDNodes Tags;
1413 LI->getAAMetadata(Tags);
1414 if (Tags) {
1415 TL->setAAMetadata(Tags);
1416 FL->setAAMetadata(Tags);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001417 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001418
1419 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1420 LI->getName() + ".sroa.speculated");
1421
1422 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1423 LI->replaceAllUsesWith(V);
1424 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001425 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001426 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001427}
1428
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001429/// \brief Build a GEP out of a base pointer and indices.
1430///
1431/// This will return the BasePtr if that is valid, or build a new GEP
1432/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001433static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001434 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001435 if (Indices.empty())
1436 return BasePtr;
1437
1438 // A single zero index is a no-op, so check for this and avoid building a GEP
1439 // in that case.
1440 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1441 return BasePtr;
1442
David Blaikieaa41cd52015-04-03 21:33:42 +00001443 return IRB.CreateInBoundsGEP(nullptr, BasePtr, Indices,
1444 NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001445}
1446
1447/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1448/// TargetTy without changing the offset of the pointer.
1449///
1450/// This routine assumes we've already established a properly offset GEP with
1451/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1452/// zero-indices down through type layers until we find one the same as
1453/// TargetTy. If we can't find one with the same type, we at least try to use
1454/// one with the same size. If none of that works, we just produce the GEP as
1455/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001456static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001457 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001458 SmallVectorImpl<Value *> &Indices,
1459 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001460 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001461 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001462
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001463 // Pointer size to use for the indices.
1464 unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1465
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001466 // See if we can descend into a struct and locate a field with the correct
1467 // type.
1468 unsigned NumLayers = 0;
1469 Type *ElementTy = Ty;
1470 do {
1471 if (ElementTy->isPointerTy())
1472 break;
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001473
1474 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1475 ElementTy = ArrayTy->getElementType();
1476 Indices.push_back(IRB.getIntN(PtrSize, 0));
1477 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1478 ElementTy = VectorTy->getElementType();
1479 Indices.push_back(IRB.getInt32(0));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001480 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001481 if (STy->element_begin() == STy->element_end())
1482 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001483 ElementTy = *STy->element_begin();
1484 Indices.push_back(IRB.getInt32(0));
1485 } else {
1486 break;
1487 }
1488 ++NumLayers;
1489 } while (ElementTy != TargetTy);
1490 if (ElementTy != TargetTy)
1491 Indices.erase(Indices.end() - NumLayers, Indices.end());
1492
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001493 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001494}
1495
1496/// \brief Recursively compute indices for a natural GEP.
1497///
1498/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1499/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001500static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001501 Value *Ptr, Type *Ty, APInt &Offset,
1502 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001503 SmallVectorImpl<Value *> &Indices,
1504 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001505 if (Offset == 0)
Chandler Carruth113dc642014-12-20 02:39:18 +00001506 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1507 NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001508
1509 // We can't recurse through pointer types.
1510 if (Ty->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001511 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001512
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001513 // We try to analyze GEPs over vectors here, but note that these GEPs are
1514 // extremely poorly defined currently. The long-term goal is to remove GEPing
1515 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001516 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001517 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Craig Topperf40110f2014-04-25 05:29:35 +00001518 if (ElementSizeInBits % 8 != 0) {
1519 // GEPs over non-multiple of 8 size vector elements are invalid.
1520 return nullptr;
1521 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001522 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001523 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001524 if (NumSkippedElements.ugt(VecTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001525 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001526 Offset -= NumSkippedElements * ElementSize;
1527 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001528 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001529 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001530 }
1531
1532 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1533 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001534 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001535 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001536 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001537 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001538
1539 Offset -= NumSkippedElements * ElementSize;
1540 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001541 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001542 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001543 }
1544
1545 StructType *STy = dyn_cast<StructType>(Ty);
1546 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00001547 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001548
Chandler Carruth90a735d2013-07-19 07:21:28 +00001549 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001550 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001551 if (StructOffset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00001552 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001553 unsigned Index = SL->getElementContainingOffset(StructOffset);
1554 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1555 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001556 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Craig Topperf40110f2014-04-25 05:29:35 +00001557 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001558
1559 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001560 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001561 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001562}
1563
1564/// \brief Get a natural GEP from a base pointer to a particular offset and
1565/// resulting in a particular type.
1566///
1567/// The goal is to produce a "natural" looking GEP that works with the existing
1568/// composite types to arrive at the appropriate offset and element type for
1569/// a pointer. TargetTy is the element type the returned GEP should point-to if
1570/// possible. We recurse by decreasing Offset, adding the appropriate index to
1571/// Indices, and setting Ty to the result subtype.
1572///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001573/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001574static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001575 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001576 SmallVectorImpl<Value *> &Indices,
1577 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001578 PointerType *Ty = cast<PointerType>(Ptr->getType());
1579
1580 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1581 // an i8.
Chandler Carruth286d87e2014-02-26 08:25:02 +00001582 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +00001583 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001584
1585 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001586 if (!ElementTy->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +00001587 return nullptr; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001588 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001589 if (ElementSize == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001590 return nullptr; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001591 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001592
1593 Offset -= NumSkippedElements * ElementSize;
1594 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001595 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001596 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001597}
1598
1599/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1600/// resulting pointer has PointerTy.
1601///
1602/// This tries very hard to compute a "natural" GEP which arrives at the offset
1603/// and produces the pointer type desired. Where it cannot, it will try to use
1604/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1605/// fails, it will try to use an existing i8* and GEP to the byte offset and
1606/// bitcast to the type.
1607///
1608/// The strategy for finding the more natural GEPs is to peel off layers of the
1609/// pointer, walking back through bit casts and GEPs, searching for a base
1610/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001611/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001612/// a single GEP as possible, thus making each GEP more independent of the
1613/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001614static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
Chandler Carruth113dc642014-12-20 02:39:18 +00001615 APInt Offset, Type *PointerTy, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001616 // Even though we don't look through PHI nodes, we could be called on an
1617 // instruction in an unreachable block, which may be on a cycle.
1618 SmallPtrSet<Value *, 4> Visited;
1619 Visited.insert(Ptr);
1620 SmallVector<Value *, 4> Indices;
1621
1622 // We may end up computing an offset pointer that has the wrong type. If we
1623 // never are able to compute one directly that has the correct type, we'll
Chandler Carruth5986b542015-01-02 02:47:38 +00001624 // fall back to it, so keep it and the base it was computed from around here.
Craig Topperf40110f2014-04-25 05:29:35 +00001625 Value *OffsetPtr = nullptr;
Chandler Carruth5986b542015-01-02 02:47:38 +00001626 Value *OffsetBasePtr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001627
1628 // Remember any i8 pointer we come across to re-use if we need to do a raw
1629 // byte offset.
Craig Topperf40110f2014-04-25 05:29:35 +00001630 Value *Int8Ptr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001631 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1632
1633 Type *TargetTy = PointerTy->getPointerElementType();
1634
1635 do {
1636 // First fold any existing GEPs into the offset.
1637 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1638 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001639 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001640 break;
1641 Offset += GEPOffset;
1642 Ptr = GEP->getPointerOperand();
David Blaikie70573dc2014-11-19 07:49:26 +00001643 if (!Visited.insert(Ptr).second)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001644 break;
1645 }
1646
1647 // See if we can perform a natural GEP here.
1648 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001649 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001650 Indices, NamePrefix)) {
Chandler Carruth5986b542015-01-02 02:47:38 +00001651 // If we have a new natural pointer at the offset, clear out any old
1652 // offset pointer we computed. Unless it is the base pointer or
1653 // a non-instruction, we built a GEP we don't need. Zap it.
1654 if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1655 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1656 assert(I->use_empty() && "Built a GEP with uses some how!");
1657 I->eraseFromParent();
1658 }
1659 OffsetPtr = P;
1660 OffsetBasePtr = Ptr;
1661 // If we also found a pointer of the right type, we're done.
1662 if (P->getType() == PointerTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001663 return P;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001664 }
1665
1666 // Stash this pointer if we've found an i8*.
1667 if (Ptr->getType()->isIntegerTy(8)) {
1668 Int8Ptr = Ptr;
1669 Int8PtrOffset = Offset;
1670 }
1671
1672 // Peel off a layer of the pointer and update the offset appropriately.
1673 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1674 Ptr = cast<Operator>(Ptr)->getOperand(0);
1675 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1676 if (GA->mayBeOverridden())
1677 break;
1678 Ptr = GA->getAliasee();
1679 } else {
1680 break;
1681 }
1682 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +00001683 } while (Visited.insert(Ptr).second);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001684
1685 if (!OffsetPtr) {
1686 if (!Int8Ptr) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00001687 Int8Ptr = IRB.CreateBitCast(
1688 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1689 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001690 Int8PtrOffset = Offset;
1691 }
1692
Chandler Carruth113dc642014-12-20 02:39:18 +00001693 OffsetPtr = Int8PtrOffset == 0
1694 ? Int8Ptr
David Blaikieaa41cd52015-04-03 21:33:42 +00001695 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1696 IRB.getInt(Int8PtrOffset),
Chandler Carruth113dc642014-12-20 02:39:18 +00001697 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001698 }
1699 Ptr = OffsetPtr;
1700
1701 // On the off chance we were targeting i8*, guard the bitcast here.
1702 if (Ptr->getType() != PointerTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001703 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001704
1705 return Ptr;
1706}
1707
Chandler Carruth0715cba2015-01-01 11:54:38 +00001708/// \brief Compute the adjusted alignment for a load or store from an offset.
1709static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
1710 const DataLayout &DL) {
1711 unsigned Alignment;
1712 Type *Ty;
1713 if (auto *LI = dyn_cast<LoadInst>(I)) {
1714 Alignment = LI->getAlignment();
1715 Ty = LI->getType();
1716 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
1717 Alignment = SI->getAlignment();
1718 Ty = SI->getValueOperand()->getType();
1719 } else {
1720 llvm_unreachable("Only loads and stores are allowed!");
1721 }
1722
1723 if (!Alignment)
1724 Alignment = DL.getABITypeAlignment(Ty);
1725
1726 return MinAlign(Alignment, Offset);
1727}
1728
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001729/// \brief Test whether we can convert a value from the old to the new type.
1730///
1731/// This predicate should be used to guard calls to convertValue in order to
1732/// ensure that we only try to convert viable values. The strategy is that we
1733/// will peel off single element struct and array wrappings to get to an
1734/// underlying value, and convert that value.
1735static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1736 if (OldTy == NewTy)
1737 return true;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001738
1739 // For integer types, we can't handle any bit-width differences. This would
1740 // break both vector conversions with extension and introduce endianness
1741 // issues when in conjunction with loads and stores.
1742 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1743 assert(cast<IntegerType>(OldTy)->getBitWidth() !=
1744 cast<IntegerType>(NewTy)->getBitWidth() &&
1745 "We can't have the same bitwidth for different int types");
1746 return false;
1747 }
1748
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001749 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1750 return false;
1751 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1752 return false;
1753
Benjamin Kramer56262592013-09-22 11:24:58 +00001754 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001755 // of pointers and integers.
1756 OldTy = OldTy->getScalarType();
1757 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001758 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1759 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1760 return true;
1761 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1762 return true;
1763 return false;
1764 }
1765
1766 return true;
1767}
1768
1769/// \brief Generic routine to convert an SSA value to a value of a different
1770/// type.
1771///
1772/// This will try various different casting techniques, such as bitcasts,
1773/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1774/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001775static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001776 Type *NewTy) {
1777 Type *OldTy = V->getType();
1778 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1779
1780 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001781 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001782
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001783 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
1784 "Integer types must be the exact same to convert.");
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001785
Benjamin Kramer90901a32013-09-21 20:36:04 +00001786 // See if we need inttoptr for this type pair. A cast involving both scalars
1787 // and vectors requires and additional bitcast.
1788 if (OldTy->getScalarType()->isIntegerTy() &&
1789 NewTy->getScalarType()->isPointerTy()) {
1790 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1791 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1792 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1793 NewTy);
1794
1795 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1796 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1797 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1798 NewTy);
1799
1800 return IRB.CreateIntToPtr(V, NewTy);
1801 }
1802
1803 // See if we need ptrtoint for this type pair. A cast involving both scalars
1804 // and vectors requires and additional bitcast.
1805 if (OldTy->getScalarType()->isPointerTy() &&
1806 NewTy->getScalarType()->isIntegerTy()) {
1807 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1808 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1809 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1810 NewTy);
1811
1812 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1813 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1814 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1815 NewTy);
1816
1817 return IRB.CreatePtrToInt(V, NewTy);
1818 }
1819
1820 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001821}
1822
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001823/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001824///
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001825/// This function is called to test each entry in a partition which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001826/// for a single slice.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001827static bool isVectorPromotionViableForSlice(AllocaSlices::Partition &P,
1828 const Slice &S, VectorType *Ty,
1829 uint64_t ElementSize,
1830 const DataLayout &DL) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001831 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001832 uint64_t BeginOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001833 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001834 uint64_t BeginIndex = BeginOffset / ElementSize;
1835 if (BeginIndex * ElementSize != BeginOffset ||
1836 BeginIndex >= Ty->getNumElements())
1837 return false;
1838 uint64_t EndOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001839 std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001840 uint64_t EndIndex = EndOffset / ElementSize;
1841 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1842 return false;
1843
1844 assert(EndIndex > BeginIndex && "Empty vector!");
1845 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruthc659df92014-10-16 20:24:07 +00001846 Type *SliceTy = (NumElements == 1)
1847 ? Ty->getElementType()
1848 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruthf0546402013-07-18 07:15:00 +00001849
1850 Type *SplitIntTy =
1851 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1852
Chandler Carruthc659df92014-10-16 20:24:07 +00001853 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001854
1855 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1856 if (MI->isVolatile())
1857 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001858 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001859 return false; // Skip any unsplittable intrinsics.
Owen Anderson6c19ab12014-08-07 21:07:35 +00001860 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1861 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1862 II->getIntrinsicID() != Intrinsic::lifetime_end)
1863 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001864 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1865 // Disable vector promotion when there are loads or stores of an FCA.
1866 return false;
1867 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1868 if (LI->isVolatile())
1869 return false;
1870 Type *LTy = LI->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001871 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001872 assert(LTy->isIntegerTy());
1873 LTy = SplitIntTy;
1874 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001875 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001876 return false;
1877 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1878 if (SI->isVolatile())
1879 return false;
1880 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001881 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001882 assert(STy->isIntegerTy());
1883 STy = SplitIntTy;
1884 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001885 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001886 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001887 } else {
1888 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001889 }
1890
1891 return true;
1892}
1893
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001894/// \brief Test whether the given alloca partitioning and range of slices can be
1895/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001896///
1897/// This is a quick test to check whether we can rewrite a particular alloca
1898/// partition (and its newly formed alloca) into a vector alloca with only
1899/// whole-vector loads and stores such that it could be promoted to a vector
1900/// SSA value. We only can ensure this for a limited set of operations, and we
1901/// don't want to do the rewrites unless we are confident that the result will
1902/// be promotable, so we have an early test here.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001903static VectorType *isVectorPromotionViable(AllocaSlices::Partition &P,
1904 const DataLayout &DL) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001905 // Collect the candidate types for vector-based promotion. Also track whether
1906 // we have different element types.
1907 SmallVector<VectorType *, 4> CandidateTys;
1908 Type *CommonEltTy = nullptr;
1909 bool HaveCommonEltTy = true;
1910 auto CheckCandidateType = [&](Type *Ty) {
1911 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1912 CandidateTys.push_back(VTy);
1913 if (!CommonEltTy)
1914 CommonEltTy = VTy->getElementType();
1915 else if (CommonEltTy != VTy->getElementType())
1916 HaveCommonEltTy = false;
1917 }
1918 };
Chandler Carruth2dc96822014-10-18 00:44:02 +00001919 // Consider any loads or stores that are the exact size of the slice.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001920 for (const Slice &S : P)
1921 if (S.beginOffset() == P.beginOffset() &&
1922 S.endOffset() == P.endOffset()) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001923 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1924 CheckCandidateType(LI->getType());
1925 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1926 CheckCandidateType(SI->getValueOperand()->getType());
1927 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001928
Chandler Carruth2dc96822014-10-18 00:44:02 +00001929 // If we didn't find a vector type, nothing to do here.
1930 if (CandidateTys.empty())
1931 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001932
Chandler Carruth2dc96822014-10-18 00:44:02 +00001933 // Remove non-integer vector types if we had multiple common element types.
1934 // FIXME: It'd be nice to replace them with integer vector types, but we can't
1935 // do that until all the backends are known to produce good code for all
1936 // integer vector types.
1937 if (!HaveCommonEltTy) {
1938 CandidateTys.erase(std::remove_if(CandidateTys.begin(), CandidateTys.end(),
1939 [](VectorType *VTy) {
1940 return !VTy->getElementType()->isIntegerTy();
1941 }),
1942 CandidateTys.end());
1943
1944 // If there were no integer vector types, give up.
1945 if (CandidateTys.empty())
1946 return nullptr;
1947
1948 // Rank the remaining candidate vector types. This is easy because we know
1949 // they're all integer vectors. We sort by ascending number of elements.
1950 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
1951 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
1952 "Cannot have vector types of different sizes!");
1953 assert(RHSTy->getElementType()->isIntegerTy() &&
1954 "All non-integer types eliminated!");
1955 assert(LHSTy->getElementType()->isIntegerTy() &&
1956 "All non-integer types eliminated!");
1957 return RHSTy->getNumElements() < LHSTy->getNumElements();
1958 };
1959 std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
1960 CandidateTys.erase(
1961 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1962 CandidateTys.end());
1963 } else {
1964// The only way to have the same element type in every vector type is to
1965// have the same vector type. Check that and remove all but one.
1966#ifndef NDEBUG
1967 for (VectorType *VTy : CandidateTys) {
1968 assert(VTy->getElementType() == CommonEltTy &&
1969 "Unaccounted for element type!");
1970 assert(VTy == CandidateTys[0] &&
1971 "Different vector types with the same element type!");
1972 }
1973#endif
1974 CandidateTys.resize(1);
1975 }
1976
1977 // Try each vector type, and return the one which works.
1978 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1979 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
1980
1981 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1982 // that aren't byte sized.
1983 if (ElementSize % 8)
1984 return false;
1985 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
1986 "vector size not a multiple of element size?");
1987 ElementSize /= 8;
1988
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001989 for (const Slice &S : P)
1990 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001991 return false;
1992
Chandler Carruthffb7ce52014-12-24 01:48:09 +00001993 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001994 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001995 return false;
1996
1997 return true;
1998 };
1999 for (VectorType *VTy : CandidateTys)
2000 if (CheckVectorTypeForPromotion(VTy))
2001 return VTy;
2002
2003 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00002004}
2005
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002006/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00002007///
2008/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002009/// test below on a single slice of the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002010static bool isIntegerWideningViableForSlice(const Slice &S,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002011 uint64_t AllocBeginOffset,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002012 Type *AllocaTy,
2013 const DataLayout &DL,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002014 bool &WholeAllocaOp) {
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002015 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
2016
Chandler Carruthc659df92014-10-16 20:24:07 +00002017 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
2018 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00002019
2020 // We can't reasonably handle cases where the load or store extends past
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002021 // the end of the alloca's type and into its padding.
Chandler Carruthf0546402013-07-18 07:15:00 +00002022 if (RelEnd > Size)
2023 return false;
2024
Chandler Carruthc659df92014-10-16 20:24:07 +00002025 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00002026
2027 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2028 if (LI->isVolatile())
2029 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002030 // We can't handle loads that extend past the allocated memory.
2031 if (DL.getTypeStoreSize(LI->getType()) > Size)
2032 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00002033 // Note that we don't count vector loads or stores as whole-alloca
2034 // operations which enable integer widening because we would prefer to use
2035 // vector widening instead.
2036 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00002037 WholeAllocaOp = true;
2038 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002039 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00002040 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002041 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002042 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002043 // Non-integer loads need to be convertible from the alloca type so that
2044 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002045 return false;
2046 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002047 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2048 Type *ValueTy = SI->getValueOperand()->getType();
2049 if (SI->isVolatile())
2050 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002051 // We can't handle stores that extend past the allocated memory.
2052 if (DL.getTypeStoreSize(ValueTy) > Size)
2053 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00002054 // Note that we don't count vector loads or stores as whole-alloca
2055 // operations which enable integer widening because we would prefer to use
2056 // vector widening instead.
2057 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00002058 WholeAllocaOp = true;
2059 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002060 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00002061 return false;
2062 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002063 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002064 // Non-integer stores need to be convertible to the alloca type so that
2065 // they are promotable.
2066 return false;
2067 }
2068 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2069 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2070 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00002071 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00002072 return false; // Skip any unsplittable intrinsics.
2073 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2074 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2075 II->getIntrinsicID() != Intrinsic::lifetime_end)
2076 return false;
2077 } else {
2078 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002079 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002080
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002081 return true;
2082}
2083
Chandler Carruth435c4e02012-10-15 08:40:30 +00002084/// \brief Test whether the given alloca partition's integer operations can be
2085/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002086///
Chandler Carruth435c4e02012-10-15 08:40:30 +00002087/// This is a quick test to check whether we can rewrite the integer loads and
2088/// stores to a particular alloca into wider loads and stores and be able to
2089/// promote the resulting alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002090static bool isIntegerWideningViable(AllocaSlices::Partition &P, Type *AllocaTy,
2091 const DataLayout &DL) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002092 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00002093 // Don't create integer types larger than the maximum bitwidth.
2094 if (SizeInBits > IntegerType::MAX_INT_BITS)
2095 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002096
2097 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002098 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002099 return false;
2100
Chandler Carruth58d05562012-10-25 04:37:07 +00002101 // We need to ensure that an integer type with the appropriate bitwidth can
2102 // be converted to the alloca type, whatever that is. We don't want to force
2103 // the alloca itself to have an integer type if there is a more suitable one.
2104 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002105 if (!canConvertValue(DL, AllocaTy, IntTy) ||
2106 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00002107 return false;
2108
Chandler Carruthf0546402013-07-18 07:15:00 +00002109 // While examining uses, we ensure that the alloca has a covering load or
2110 // store. We don't want to widen the integer operations only to fail to
2111 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00002112 // later). However, if there are only splittable uses, go ahead and assume
2113 // that we cover the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002114 // FIXME: We shouldn't consider split slices that happen to start in the
2115 // partition here...
Chandler Carruthc659df92014-10-16 20:24:07 +00002116 bool WholeAllocaOp =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002117 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00002118
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002119 for (const Slice &S : P)
2120 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2121 WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00002122 return false;
2123
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002124 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002125 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2126 WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002127 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002128
Chandler Carruth92924fd2012-09-24 00:34:20 +00002129 return WholeAllocaOp;
2130}
2131
Chandler Carruthd177f862013-03-20 07:30:36 +00002132static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002133 IntegerType *Ty, uint64_t Offset,
2134 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002135 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002136 IntegerType *IntTy = cast<IntegerType>(V->getType());
2137 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2138 "Element extends past full value");
Chandler Carruth113dc642014-12-20 02:39:18 +00002139 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002140 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002141 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002142 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002143 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002144 DEBUG(dbgs() << " shifted: " << *V << "\n");
2145 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002146 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2147 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002148 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002149 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00002150 DEBUG(dbgs() << " trunced: " << *V << "\n");
2151 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002152 return V;
2153}
2154
Chandler Carruthd177f862013-03-20 07:30:36 +00002155static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002156 Value *V, uint64_t Offset, const Twine &Name) {
2157 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2158 IntegerType *Ty = cast<IntegerType>(V->getType());
2159 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2160 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002161 DEBUG(dbgs() << " start: " << *V << "\n");
2162 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002163 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00002164 DEBUG(dbgs() << " extended: " << *V << "\n");
2165 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002166 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2167 "Element store outside of alloca store");
Chandler Carruth113dc642014-12-20 02:39:18 +00002168 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002169 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002170 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002171 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002172 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002173 DEBUG(dbgs() << " shifted: " << *V << "\n");
2174 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002175
2176 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2177 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2178 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00002179 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002180 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00002181 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002182 }
2183 return V;
2184}
2185
Chandler Carruth113dc642014-12-20 02:39:18 +00002186static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2187 unsigned EndIndex, const Twine &Name) {
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002188 VectorType *VecTy = cast<VectorType>(V->getType());
2189 unsigned NumElements = EndIndex - BeginIndex;
2190 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2191
2192 if (NumElements == VecTy->getNumElements())
2193 return V;
2194
2195 if (NumElements == 1) {
2196 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2197 Name + ".extract");
2198 DEBUG(dbgs() << " extract: " << *V << "\n");
2199 return V;
2200 }
2201
Chandler Carruth113dc642014-12-20 02:39:18 +00002202 SmallVector<Constant *, 8> Mask;
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002203 Mask.reserve(NumElements);
2204 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2205 Mask.push_back(IRB.getInt32(i));
2206 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002207 ConstantVector::get(Mask), Name + ".extract");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002208 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2209 return V;
2210}
2211
Chandler Carruthd177f862013-03-20 07:30:36 +00002212static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00002213 unsigned BeginIndex, const Twine &Name) {
2214 VectorType *VecTy = cast<VectorType>(Old->getType());
2215 assert(VecTy && "Can only insert a vector into a vector");
2216
2217 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2218 if (!Ty) {
2219 // Single element to insert.
2220 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2221 Name + ".insert");
Chandler Carruth113dc642014-12-20 02:39:18 +00002222 DEBUG(dbgs() << " insert: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002223 return V;
2224 }
2225
2226 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2227 "Too many elements!");
2228 if (Ty->getNumElements() == VecTy->getNumElements()) {
2229 assert(V->getType() == VecTy && "Vector type mismatch");
2230 return V;
2231 }
2232 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2233
2234 // When inserting a smaller vector into the larger to store, we first
2235 // use a shuffle vector to widen it with undef elements, and then
2236 // a second shuffle vector to select between the loaded vector and the
2237 // incoming vector.
Chandler Carruth113dc642014-12-20 02:39:18 +00002238 SmallVector<Constant *, 8> Mask;
Chandler Carruthce4562b2012-12-17 13:41:21 +00002239 Mask.reserve(VecTy->getNumElements());
2240 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2241 if (i >= BeginIndex && i < EndIndex)
2242 Mask.push_back(IRB.getInt32(i - BeginIndex));
2243 else
2244 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2245 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002246 ConstantVector::get(Mask), Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00002247 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002248
2249 Mask.clear();
2250 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00002251 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2252
2253 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2254
2255 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002256 return V;
2257}
2258
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002259namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002260/// \brief Visitor to rewrite instructions using p particular slice of an alloca
2261/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002262///
2263/// Also implements the rewriting to vector-based accesses when the partition
2264/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2265/// lives here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002266class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002267 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002268 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
2269 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002270
Chandler Carruth90a735d2013-07-19 07:21:28 +00002271 const DataLayout &DL;
Chandler Carruth83934062014-10-16 21:11:55 +00002272 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002273 SROA &Pass;
2274 AllocaInst &OldAI, &NewAI;
2275 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002276 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002277
Chandler Carruth2dc96822014-10-18 00:44:02 +00002278 // This is a convenience and flag variable that will be null unless the new
2279 // alloca's integer operations should be widened to this integer type due to
2280 // passing isIntegerWideningViable above. If it is non-null, the desired
2281 // integer type will be stored here for easy access during rewriting.
2282 IntegerType *IntTy;
2283
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002284 // If we are rewriting an alloca partition which can be written as pure
2285 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002286 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002287 // - The new alloca is exactly the size of the vector type here.
2288 // - The accesses all either map to the entire vector or to a single
2289 // element.
2290 // - The set of accessing instructions is only one of those handled above
2291 // in isVectorPromotionViable. Generally these are the same access kinds
2292 // which are promotable via mem2reg.
2293 VectorType *VecTy;
2294 Type *ElementTy;
2295 uint64_t ElementSize;
2296
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002297 // The original offset of the slice currently being rewritten relative to
2298 // the original alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002299 uint64_t BeginOffset, EndOffset;
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002300 // The new offsets of the slice currently being rewritten relative to the
2301 // original alloca.
2302 uint64_t NewBeginOffset, NewEndOffset;
2303
2304 uint64_t SliceSize;
Chandler Carruthf0546402013-07-18 07:15:00 +00002305 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002306 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002307 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002308 Instruction *OldPtr;
2309
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002310 // Track post-rewrite users which are PHI nodes and Selects.
2311 SmallPtrSetImpl<PHINode *> &PHIUsers;
2312 SmallPtrSetImpl<SelectInst *> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002313
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002314 // Utility IR builder, whose name prefix is setup for each visited use, and
2315 // the insertion point is set to point to the user.
2316 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002317
2318public:
Chandler Carruth83934062014-10-16 21:11:55 +00002319 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002320 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002321 uint64_t NewAllocaBeginOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00002322 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2323 VectorType *PromotableVecTy,
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002324 SmallPtrSetImpl<PHINode *> &PHIUsers,
2325 SmallPtrSetImpl<SelectInst *> &SelectUsers)
Chandler Carruth83934062014-10-16 21:11:55 +00002326 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002327 NewAllocaBeginOffset(NewAllocaBeginOffset),
2328 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002329 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002330 IntTy(IsIntegerPromotable
2331 ? Type::getIntNTy(
2332 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002333 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Craig Topperf40110f2014-04-25 05:29:35 +00002334 : nullptr),
Chandler Carruth2dc96822014-10-18 00:44:02 +00002335 VecTy(PromotableVecTy),
2336 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2337 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00002338 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002339 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002340 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002341 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002342 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002343 "Only multiple-of-8 sized vector elements are viable");
2344 ++NumVectorized;
2345 }
Chandler Carruth2dc96822014-10-18 00:44:02 +00002346 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002347 }
2348
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002349 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002350 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002351 BeginOffset = I->beginOffset();
2352 EndOffset = I->endOffset();
2353 IsSplittable = I->isSplittable();
2354 IsSplit =
2355 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002356 DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2357 DEBUG(AS.printSlice(dbgs(), I, ""));
Chandler Carruth0715cba2015-01-01 11:54:38 +00002358 DEBUG(dbgs() << "\n");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002359
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002360 // Compute the intersecting offset range.
2361 assert(BeginOffset < NewAllocaEndOffset);
2362 assert(EndOffset > NewAllocaBeginOffset);
2363 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2364 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2365
2366 SliceSize = NewEndOffset - NewBeginOffset;
2367
Chandler Carruthf0546402013-07-18 07:15:00 +00002368 OldUse = I->getUse();
2369 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002370
Chandler Carruthf0546402013-07-18 07:15:00 +00002371 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2372 IRB.SetInsertPoint(OldUserI);
2373 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2374 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2375
2376 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2377 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002378 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002379 return CanSROA;
2380 }
2381
2382private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002383 // Make sure the other visit overloads are visible.
2384 using Base::visit;
2385
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002386 // Every instruction which can end up as a user must have a rewrite rule.
2387 bool visitInstruction(Instruction &I) {
2388 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2389 llvm_unreachable("No rewrite rule for this instruction!");
2390 }
2391
Chandler Carruth47954c82014-02-26 05:12:43 +00002392 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2393 // Note that the offset computation can use BeginOffset or NewBeginOffset
2394 // interchangeably for unsplit slices.
2395 assert(IsSplit || BeginOffset == NewBeginOffset);
2396 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2397
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002398#ifndef NDEBUG
2399 StringRef OldName = OldPtr->getName();
2400 // Skip through the last '.sroa.' component of the name.
2401 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2402 if (LastSROAPrefix != StringRef::npos) {
2403 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2404 // Look for an SROA slice index.
2405 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2406 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2407 // Strip the index and look for the offset.
2408 OldName = OldName.substr(IndexEnd + 1);
2409 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2410 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2411 // Strip the offset.
2412 OldName = OldName.substr(OffsetEnd + 1);
2413 }
2414 }
2415 // Strip any SROA suffixes as well.
2416 OldName = OldName.substr(0, OldName.find(".sroa_"));
2417#endif
Chandler Carruth47954c82014-02-26 05:12:43 +00002418
2419 return getAdjustedPtr(IRB, DL, &NewAI,
2420 APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002421#ifndef NDEBUG
2422 Twine(OldName) + "."
2423#else
2424 Twine()
2425#endif
2426 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002427 }
2428
Chandler Carruth113dc642014-12-20 02:39:18 +00002429 /// \brief Compute suitable alignment to access this slice of the *new*
2430 /// alloca.
Chandler Carruth2659e502014-02-26 05:02:19 +00002431 ///
2432 /// You can optionally pass a type to this routine and if that type's ABI
2433 /// alignment is itself suitable, this will return zero.
Craig Topperf40110f2014-04-25 05:29:35 +00002434 unsigned getSliceAlign(Type *Ty = nullptr) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002435 unsigned NewAIAlign = NewAI.getAlignment();
2436 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002437 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth113dc642014-12-20 02:39:18 +00002438 unsigned Align =
2439 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
Chandler Carruth2659e502014-02-26 05:02:19 +00002440 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002441 }
2442
Chandler Carruth845b73c2012-11-21 08:16:30 +00002443 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002444 assert(VecTy && "Can only call getIndex when rewriting a vector");
2445 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2446 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2447 uint32_t Index = RelOffset / ElementSize;
2448 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002449 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002450 }
2451
2452 void deleteIfTriviallyDead(Value *V) {
2453 Instruction *I = cast<Instruction>(V);
2454 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002455 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002456 }
2457
Chandler Carruthea27cf02014-02-26 04:25:04 +00002458 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002459 unsigned BeginIndex = getIndex(NewBeginOffset);
2460 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002461 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002462
Chandler Carruth113dc642014-12-20 02:39:18 +00002463 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002464 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002465 }
2466
Chandler Carruthea27cf02014-02-26 04:25:04 +00002467 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002468 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002469 assert(!LI.isVolatile());
Chandler Carruth113dc642014-12-20 02:39:18 +00002470 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002471 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002472 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2473 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2474 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002475 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002476 "extract");
Chandler Carruth18db7952012-11-20 01:12:50 +00002477 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002478 }
2479
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002480 bool visitLoadInst(LoadInst &LI) {
2481 DEBUG(dbgs() << " original: " << LI << "\n");
2482 Value *OldOp = LI.getOperand(0);
2483 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002484
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002485 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002486 : LI.getType();
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002487 const bool IsLoadPastEnd = DL.getTypeStoreSize(TargetTy) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002488 bool IsPtrAdjusted = false;
2489 Value *V;
2490 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002491 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002492 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002493 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002494 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002495 NewEndOffset == NewAllocaEndOffset &&
2496 (canConvertValue(DL, NewAllocaTy, TargetTy) ||
2497 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
2498 TargetTy->isIntegerTy()))) {
David Majnemer62690b12015-07-14 06:19:58 +00002499 LoadInst *NewLI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2500 LI.isVolatile(), LI.getName());
2501 if (LI.isVolatile())
2502 NewLI->setAtomic(LI.getOrdering(), LI.getSynchScope());
David Majnemer62690b12015-07-14 06:19:58 +00002503 V = NewLI;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002504
2505 // If this is an integer load past the end of the slice (which means the
2506 // bytes outside the slice are undef or this load is dead) just forcibly
2507 // fix the integer size with correct handling of endianness.
2508 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2509 if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
2510 if (AITy->getBitWidth() < TITy->getBitWidth()) {
2511 V = IRB.CreateZExt(V, TITy, "load.ext");
2512 if (DL.isBigEndian())
2513 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2514 "endian_shift");
2515 }
Chandler Carruth18db7952012-11-20 01:12:50 +00002516 } else {
2517 Type *LTy = TargetTy->getPointerTo();
David Majnemer62690b12015-07-14 06:19:58 +00002518 LoadInst *NewLI = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2519 getSliceAlign(TargetTy),
2520 LI.isVolatile(), LI.getName());
2521 if (LI.isVolatile())
2522 NewLI->setAtomic(LI.getOrdering(), LI.getSynchScope());
2523
2524 V = NewLI;
Chandler Carruth18db7952012-11-20 01:12:50 +00002525 IsPtrAdjusted = true;
2526 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002527 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002528
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002529 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002530 assert(!LI.isVolatile());
2531 assert(LI.getType()->isIntegerTy() &&
2532 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002533 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002534 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002535 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002536 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002537 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002538 // Move the insertion point just past the load so that we can refer to it.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002539 IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002540 // Create a placeholder value with the same type as LI to use as the
2541 // basis for the new value. This allows us to replace the uses of LI with
2542 // the computed value, and then replace the placeholder with LI, leaving
2543 // LI only used for this computation.
Chandler Carruth113dc642014-12-20 02:39:18 +00002544 Value *Placeholder =
2545 new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth24ac8302015-01-02 03:55:54 +00002546 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2547 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002548 LI.replaceAllUsesWith(V);
2549 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002550 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002551 } else {
2552 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002553 }
2554
Chandler Carruth18db7952012-11-20 01:12:50 +00002555 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002556 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002557 DEBUG(dbgs() << " to: " << *V << "\n");
2558 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002559 }
2560
Chandler Carruthea27cf02014-02-26 04:25:04 +00002561 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002562 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002563 unsigned BeginIndex = getIndex(NewBeginOffset);
2564 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002565 assert(EndIndex > BeginIndex && "Empty vector!");
2566 unsigned NumElements = EndIndex - BeginIndex;
2567 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth113dc642014-12-20 02:39:18 +00002568 Type *SliceTy = (NumElements == 1)
2569 ? ElementTy
2570 : VectorType::get(ElementTy, NumElements);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002571 if (V->getType() != SliceTy)
2572 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002573
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002574 // Mix in the existing elements.
Chandler Carruth113dc642014-12-20 02:39:18 +00002575 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002576 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2577 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002578 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002579 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002580
2581 (void)Store;
2582 DEBUG(dbgs() << " to: " << *Store << "\n");
2583 return true;
2584 }
2585
Chandler Carruthea27cf02014-02-26 04:25:04 +00002586 bool rewriteIntegerStore(Value *V, StoreInst &SI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002587 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002588 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002589 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002590 Value *Old =
2591 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002592 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002593 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2594 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth113dc642014-12-20 02:39:18 +00002595 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002596 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002597 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002598 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002599 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002600 (void)Store;
2601 DEBUG(dbgs() << " to: " << *Store << "\n");
2602 return true;
2603 }
2604
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002605 bool visitStoreInst(StoreInst &SI) {
2606 DEBUG(dbgs() << " original: " << SI << "\n");
2607 Value *OldOp = SI.getOperand(1);
2608 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002609
Chandler Carruth18db7952012-11-20 01:12:50 +00002610 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002611
Chandler Carruthac8317f2012-10-04 12:33:50 +00002612 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2613 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002614 if (V->getType()->isPointerTy())
2615 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002616 Pass.PostPromotionWorklist.insert(AI);
2617
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002618 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002619 assert(!SI.isVolatile());
2620 assert(V->getType()->isIntegerTy() &&
2621 "Only integer type loads and stores are split");
2622 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002623 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002624 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002625 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth24ac8302015-01-02 03:55:54 +00002626 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2627 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002628 }
2629
Chandler Carruth18db7952012-11-20 01:12:50 +00002630 if (VecTy)
Chandler Carruthea27cf02014-02-26 04:25:04 +00002631 return rewriteVectorizedStoreInst(V, SI, OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002632 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthea27cf02014-02-26 04:25:04 +00002633 return rewriteIntegerStore(V, SI);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002634
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002635 const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002636 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002637 if (NewBeginOffset == NewAllocaBeginOffset &&
2638 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002639 (canConvertValue(DL, V->getType(), NewAllocaTy) ||
2640 (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
2641 V->getType()->isIntegerTy()))) {
2642 // If this is an integer store past the end of slice (and thus the bytes
2643 // past that point are irrelevant or this is unreachable), truncate the
2644 // value prior to storing.
2645 if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
2646 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2647 if (VITy->getBitWidth() > AITy->getBitWidth()) {
2648 if (DL.isBigEndian())
2649 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2650 "endian_shift");
2651 V = IRB.CreateTrunc(V, AITy, "load.trunc");
2652 }
2653
Chandler Carruth90a735d2013-07-19 07:21:28 +00002654 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002655 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2656 SI.isVolatile());
2657 } else {
Chandler Carruth47954c82014-02-26 05:12:43 +00002658 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
Chandler Carruth2659e502014-02-26 05:02:19 +00002659 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2660 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002661 }
David Majnemer62690b12015-07-14 06:19:58 +00002662 if (SI.isVolatile())
2663 NewSI->setAtomic(SI.getOrdering(), SI.getSynchScope());
Chandler Carruth18db7952012-11-20 01:12:50 +00002664 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002665 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002666
2667 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2668 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002669 }
2670
Chandler Carruth514f34f2012-12-17 04:07:30 +00002671 /// \brief Compute an integer value from splatting an i8 across the given
2672 /// number of bytes.
2673 ///
2674 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2675 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002676 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002677 ///
2678 /// \param V The i8 value to splat.
2679 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002680 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002681 assert(Size > 0 && "Expected a positive number of bytes.");
2682 IntegerType *VTy = cast<IntegerType>(V->getType());
2683 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2684 if (Size == 1)
2685 return V;
2686
Chandler Carruth113dc642014-12-20 02:39:18 +00002687 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2688 V = IRB.CreateMul(
2689 IRB.CreateZExt(V, SplatIntTy, "zext"),
2690 ConstantExpr::getUDiv(
2691 Constant::getAllOnesValue(SplatIntTy),
2692 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2693 SplatIntTy)),
2694 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002695 return V;
2696 }
2697
Chandler Carruthccca5042012-12-17 04:07:37 +00002698 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002699 Value *getVectorSplat(Value *V, unsigned NumElements) {
2700 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002701 DEBUG(dbgs() << " splat: " << *V << "\n");
2702 return V;
2703 }
2704
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002705 bool visitMemSetInst(MemSetInst &II) {
2706 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002707 assert(II.getRawDest() == OldPtr);
2708
2709 // If the memset has a variable size, it cannot be split, just adjust the
2710 // pointer to the new alloca.
2711 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002712 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002713 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002714 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002715 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth2659e502014-02-26 05:02:19 +00002716 II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002717
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002718 deleteIfTriviallyDead(OldPtr);
2719 return false;
2720 }
2721
2722 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002723 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002724
2725 Type *AllocaTy = NewAI.getAllocatedType();
2726 Type *ScalarTy = AllocaTy->getScalarType();
2727
2728 // If this doesn't map cleanly onto the alloca type, and that type isn't
2729 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002730 if (!VecTy && !IntTy &&
Chandler Carruth113dc642014-12-20 02:39:18 +00002731 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002732 SliceSize != DL.getTypeStoreSize(AllocaTy) ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002733 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002734 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
Chandler Carruth113dc642014-12-20 02:39:18 +00002735 DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002736 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002737 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2738 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002739 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2740 getSliceAlign(), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002741 (void)New;
2742 DEBUG(dbgs() << " to: " << *New << "\n");
2743 return false;
2744 }
2745
2746 // If we can represent this as a simple value, we have to build the actual
2747 // value to store, which requires expanding the byte present in memset to
2748 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002749 // splatting the byte to a sufficiently wide integer, splatting it across
2750 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002751 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002752
Chandler Carruthccca5042012-12-17 04:07:37 +00002753 if (VecTy) {
2754 // If this is a memset of a vectorized alloca, insert it.
2755 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002756
Chandler Carruthf0546402013-07-18 07:15:00 +00002757 unsigned BeginIndex = getIndex(NewBeginOffset);
2758 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002759 assert(EndIndex > BeginIndex && "Empty vector!");
2760 unsigned NumElements = EndIndex - BeginIndex;
2761 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2762
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002763 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002764 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2765 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002766 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002767 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002768
Chandler Carruth113dc642014-12-20 02:39:18 +00002769 Value *Old =
2770 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002771 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002772 } else if (IntTy) {
2773 // If this is a memset on an alloca where we can widen stores, insert the
2774 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002775 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002776
Chandler Carruthf0546402013-07-18 07:15:00 +00002777 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002778 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002779
2780 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2781 EndOffset != NewAllocaBeginOffset)) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002782 Value *Old =
2783 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002784 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002785 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002786 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002787 } else {
2788 assert(V->getType() == IntTy &&
2789 "Wrong type for an alloca wide integer!");
2790 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002791 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002792 } else {
2793 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002794 assert(NewBeginOffset == NewAllocaBeginOffset);
2795 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002796
Chandler Carruth90a735d2013-07-19 07:21:28 +00002797 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002798 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002799 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002800
Chandler Carruth90a735d2013-07-19 07:21:28 +00002801 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002802 }
2803
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002804 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002805 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002806 (void)New;
2807 DEBUG(dbgs() << " to: " << *New << "\n");
2808 return !II.isVolatile();
2809 }
2810
2811 bool visitMemTransferInst(MemTransferInst &II) {
2812 // Rewriting of memory transfer instructions can be a bit tricky. We break
2813 // them into two categories: split intrinsics and unsplit intrinsics.
2814
2815 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002816
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002817 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002818 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002819 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002820
Chandler Carruthaa72b932014-02-26 07:29:54 +00002821 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002822
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002823 // For unsplit intrinsics, we simply modify the source and destination
2824 // pointers in place. This isn't just an optimization, it is a matter of
2825 // correctness. With unsplit intrinsics we may be dealing with transfers
2826 // within a single alloca before SROA ran, or with transfers that have
2827 // a variable length. We may also be dealing with memmove instead of
2828 // memcpy, and so simply updating the pointers is the necessary for us to
2829 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002830 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002831 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002832 if (IsDest)
Chandler Carruth8183a502014-02-25 11:08:02 +00002833 II.setDest(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002834 else
Chandler Carruth8183a502014-02-25 11:08:02 +00002835 II.setSource(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002836
Chandler Carruthaa72b932014-02-26 07:29:54 +00002837 if (II.getAlignment() > SliceAlign) {
Chandler Carruth181ed052014-02-26 05:33:36 +00002838 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthaa72b932014-02-26 07:29:54 +00002839 II.setAlignment(
2840 ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
Chandler Carruth181ed052014-02-26 05:33:36 +00002841 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002842
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002843 DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002844 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002845 return false;
2846 }
2847 // For split transfer intrinsics we have an incredibly useful assurance:
2848 // the source and destination do not reside within the same alloca, and at
2849 // least one of them does not escape. This means that we can replace
2850 // memmove with memcpy, and we don't need to worry about all manner of
2851 // downsides to splitting and transforming the operations.
2852
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002853 // If this doesn't map cleanly onto the alloca type, and that type isn't
2854 // a single value type, just emit a memcpy.
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002855 bool EmitMemCpy =
2856 !VecTy && !IntTy &&
2857 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2858 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2859 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002860
2861 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2862 // size hasn't been shrunk based on analysis of the viable range, this is
2863 // a no-op.
2864 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002865 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002866 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002867
2868 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002869 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002870 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002871 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002872 return false;
2873 }
2874 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002875 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002876
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002877 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2878 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002879 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth113dc642014-12-20 02:39:18 +00002880 if (AllocaInst *AI =
2881 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002882 assert(AI != &OldAI && AI != &NewAI &&
2883 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002884 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002885 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002886
Chandler Carruth286d87e2014-02-26 08:25:02 +00002887 Type *OtherPtrTy = OtherPtr->getType();
2888 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2889
Chandler Carruth181ed052014-02-26 05:33:36 +00002890 // Compute the relative offset for the other pointer within the transfer.
Chandler Carruth286d87e2014-02-26 08:25:02 +00002891 unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
Chandler Carruth181ed052014-02-26 05:33:36 +00002892 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002893 unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2894 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002895
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002896 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002897 // Compute the other pointer, folding as much as possible to produce
2898 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002899 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002900 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002901
Chandler Carruth47954c82014-02-26 05:12:43 +00002902 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002903 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002904 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002905
Chandler Carruthaa72b932014-02-26 07:29:54 +00002906 CallInst *New = IRB.CreateMemCpy(
2907 IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2908 MinAlign(SliceAlign, OtherAlign), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002909 (void)New;
2910 DEBUG(dbgs() << " to: " << *New << "\n");
2911 return false;
2912 }
2913
Chandler Carruthf0546402013-07-18 07:15:00 +00002914 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2915 NewEndOffset == NewAllocaEndOffset;
2916 uint64_t Size = NewEndOffset - NewBeginOffset;
2917 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2918 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002919 unsigned NumElements = EndIndex - BeginIndex;
Chandler Carruth113dc642014-12-20 02:39:18 +00002920 IntegerType *SubIntTy =
2921 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002922
Chandler Carruth286d87e2014-02-26 08:25:02 +00002923 // Reset the other pointer type to match the register type we're going to
2924 // use, but using the address space of the original other pointer.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002925 if (VecTy && !IsWholeAlloca) {
2926 if (NumElements == 1)
2927 OtherPtrTy = VecTy->getElementType();
2928 else
2929 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2930
Chandler Carruth286d87e2014-02-26 08:25:02 +00002931 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002932 } else if (IntTy && !IsWholeAlloca) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00002933 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2934 } else {
2935 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002936 }
2937
Chandler Carruth181ed052014-02-26 05:33:36 +00002938 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002939 OtherPtr->getName() + ".");
Chandler Carruthaa72b932014-02-26 07:29:54 +00002940 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002941 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00002942 unsigned DstAlign = SliceAlign;
2943 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002944 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002945 std::swap(SrcAlign, DstAlign);
2946 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002947
2948 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002949 if (VecTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002950 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002951 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002952 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002953 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002954 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002955 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002956 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002957 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +00002958 Src =
2959 IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002960 }
2961
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002962 if (VecTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002963 Value *Old =
2964 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002965 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002966 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002967 Value *Old =
2968 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002969 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002970 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002971 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2972 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002973 }
2974
Chandler Carruth871ba722012-09-26 10:27:46 +00002975 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00002976 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Chandler Carruth871ba722012-09-26 10:27:46 +00002977 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002978 DEBUG(dbgs() << " to: " << *Store << "\n");
2979 return !II.isVolatile();
2980 }
2981
2982 bool visitIntrinsicInst(IntrinsicInst &II) {
2983 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2984 II.getIntrinsicID() == Intrinsic::lifetime_end);
2985 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002986 assert(II.getArgOperand(1) == OldPtr);
2987
2988 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002989 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002990
Chandler Carruth113dc642014-12-20 02:39:18 +00002991 ConstantInt *Size =
2992 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002993 NewEndOffset - NewBeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002994 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002995 Value *New;
2996 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2997 New = IRB.CreateLifetimeStart(Ptr, Size);
2998 else
2999 New = IRB.CreateLifetimeEnd(Ptr, Size);
3000
Edwin Vane82f80d42013-01-29 17:42:24 +00003001 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003002 DEBUG(dbgs() << " to: " << *New << "\n");
3003 return true;
3004 }
3005
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003006 bool visitPHINode(PHINode &PN) {
3007 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00003008 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
3009 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003010
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003011 // We would like to compute a new pointer in only one place, but have it be
3012 // as local as possible to the PHI. To do that, we re-use the location of
3013 // the old pointer, which necessarily must be in the right position to
3014 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00003015 IRBuilderTy PtrBuilder(IRB);
David Majnemerd4cffcf2014-09-01 21:20:14 +00003016 if (isa<PHINode>(OldPtr))
3017 PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
3018 else
3019 PtrBuilder.SetInsertPoint(OldPtr);
Chandler Carruth51175532014-02-25 11:12:04 +00003020 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003021
Chandler Carruth47954c82014-02-26 05:12:43 +00003022 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00003023 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003024 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003025
Chandler Carruth82a57542012-10-01 10:54:05 +00003026 DEBUG(dbgs() << " to: " << PN << "\n");
3027 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003028
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003029 // PHIs can't be promoted on their own, but often can be speculated. We
3030 // check the speculation outside of the rewriter so that we see the
3031 // fully-rewritten alloca.
3032 PHIUsers.insert(&PN);
3033 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003034 }
3035
3036 bool visitSelectInst(SelectInst &SI) {
3037 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003038 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3039 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00003040 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
3041 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003042
Chandler Carruth47954c82014-02-26 05:12:43 +00003043 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003044 // Replace the operands which were using the old pointer.
3045 if (SI.getOperand(1) == OldPtr)
3046 SI.setOperand(1, NewPtr);
3047 if (SI.getOperand(2) == OldPtr)
3048 SI.setOperand(2, NewPtr);
3049
Chandler Carruth82a57542012-10-01 10:54:05 +00003050 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003051 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003052
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003053 // Selects can't be promoted on their own, but often can be speculated. We
3054 // check the speculation outside of the rewriter so that we see the
3055 // fully-rewritten alloca.
3056 SelectUsers.insert(&SI);
3057 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003058 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003059};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00003060}
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003061
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003062namespace {
3063/// \brief Visitor to rewrite aggregate loads and stores as scalar.
3064///
3065/// This pass aggressively rewrites all aggregate loads and stores on
3066/// a particular pointer (or any pointer derived from it which we can identify)
3067/// with scalar loads and stores.
3068class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3069 // Befriend the base class so it can delegate to private visit methods.
3070 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3071
Chandler Carruth90a735d2013-07-19 07:21:28 +00003072 const DataLayout &DL;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003073
3074 /// Queue of pointer uses to analyze and potentially rewrite.
3075 SmallVector<Use *, 8> Queue;
3076
3077 /// Set to prevent us from cycling with phi nodes and loops.
3078 SmallPtrSet<User *, 8> Visited;
3079
3080 /// The current pointer use being rewritten. This is used to dig up the used
3081 /// value (as opposed to the user).
3082 Use *U;
3083
3084public:
Chandler Carruth90a735d2013-07-19 07:21:28 +00003085 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003086
3087 /// Rewrite loads and stores through a pointer and all pointers derived from
3088 /// it.
3089 bool rewrite(Instruction &I) {
3090 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3091 enqueueUsers(I);
3092 bool Changed = false;
3093 while (!Queue.empty()) {
3094 U = Queue.pop_back_val();
3095 Changed |= visit(cast<Instruction>(U->getUser()));
3096 }
3097 return Changed;
3098 }
3099
3100private:
3101 /// Enqueue all the users of the given instruction for further processing.
3102 /// This uses a set to de-duplicate users.
3103 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003104 for (Use &U : I.uses())
David Blaikie70573dc2014-11-19 07:49:26 +00003105 if (Visited.insert(U.getUser()).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003106 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003107 }
3108
3109 // Conservative default is to not rewrite anything.
3110 bool visitInstruction(Instruction &I) { return false; }
3111
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003112 /// \brief Generic recursive split emission class.
Chandler Carruth113dc642014-12-20 02:39:18 +00003113 template <typename Derived> class OpSplitter {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003114 protected:
3115 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00003116 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003117 /// The indices which to be used with insert- or extractvalue to select the
3118 /// appropriate value within the aggregate.
3119 SmallVector<unsigned, 4> Indices;
3120 /// The indices to a GEP instruction which will move Ptr to the correct slot
3121 /// within the aggregate.
3122 SmallVector<Value *, 4> GEPIndices;
3123 /// The base pointer of the original op, used as a base for GEPing the
3124 /// split operations.
3125 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003126
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003127 /// Initialize the splitter with an insertion point, Ptr and start with a
3128 /// single zero GEP index.
3129 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003130 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003131
3132 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003133 /// \brief Generic recursive split emission routine.
3134 ///
3135 /// This method recursively splits an aggregate op (load or store) into
3136 /// scalar or vector ops. It splits recursively until it hits a single value
3137 /// and emits that single value operation via the template argument.
3138 ///
3139 /// The logic of this routine relies on GEPs and insertvalue and
3140 /// extractvalue all operating with the same fundamental index list, merely
3141 /// formatted differently (GEPs need actual values).
3142 ///
3143 /// \param Ty The type being split recursively into smaller ops.
3144 /// \param Agg The aggregate value being built up or stored, depending on
3145 /// whether this is splitting a load or a store respectively.
3146 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3147 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003148 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003149
3150 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3151 unsigned OldSize = Indices.size();
3152 (void)OldSize;
3153 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3154 ++Idx) {
3155 assert(Indices.size() == OldSize && "Did not return to the old size");
3156 Indices.push_back(Idx);
3157 GEPIndices.push_back(IRB.getInt32(Idx));
3158 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3159 GEPIndices.pop_back();
3160 Indices.pop_back();
3161 }
3162 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003163 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003164
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003165 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3166 unsigned OldSize = Indices.size();
3167 (void)OldSize;
3168 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3169 ++Idx) {
3170 assert(Indices.size() == OldSize && "Did not return to the old size");
3171 Indices.push_back(Idx);
3172 GEPIndices.push_back(IRB.getInt32(Idx));
3173 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3174 GEPIndices.pop_back();
3175 Indices.pop_back();
3176 }
3177 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003178 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003179
3180 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003181 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003182 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003183
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003184 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003185 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003186 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003187
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003188 /// Emit a leaf load of a single value. This is called at the leaves of the
3189 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003190 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003191 assert(Ty->isSingleValueType());
3192 // Load the single value and insert it using the indices.
David Blaikieaa41cd52015-04-03 21:33:42 +00003193 Value *GEP =
3194 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
Jakub Staszak3c6583a2013-02-19 22:14:45 +00003195 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003196 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3197 DEBUG(dbgs() << " to: " << *Load << "\n");
3198 }
3199 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003200
3201 bool visitLoadInst(LoadInst &LI) {
3202 assert(LI.getPointerOperand() == *U);
3203 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3204 return false;
3205
3206 // We have an aggregate being loaded, split it apart.
3207 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003208 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003209 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003210 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003211 LI.replaceAllUsesWith(V);
3212 LI.eraseFromParent();
3213 return true;
3214 }
3215
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003216 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003217 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003218 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003219
3220 /// Emit a leaf store of a single value. This is called at the leaves of the
3221 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003222 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003223 assert(Ty->isSingleValueType());
3224 // Extract the single value and store it using the indices.
3225 Value *Store = IRB.CreateStore(
Chandler Carruth113dc642014-12-20 02:39:18 +00003226 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
David Blaikieaa41cd52015-04-03 21:33:42 +00003227 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep"));
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003228 (void)Store;
3229 DEBUG(dbgs() << " to: " << *Store << "\n");
3230 }
3231 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003232
3233 bool visitStoreInst(StoreInst &SI) {
3234 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3235 return false;
3236 Value *V = SI.getValueOperand();
3237 if (V->getType()->isSingleValueType())
3238 return false;
3239
3240 // We have an aggregate being stored, split it apart.
3241 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003242 StoreOpSplitter Splitter(&SI, *U);
3243 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003244 SI.eraseFromParent();
3245 return true;
3246 }
3247
3248 bool visitBitCastInst(BitCastInst &BC) {
3249 enqueueUsers(BC);
3250 return false;
3251 }
3252
3253 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3254 enqueueUsers(GEPI);
3255 return false;
3256 }
3257
3258 bool visitPHINode(PHINode &PN) {
3259 enqueueUsers(PN);
3260 return false;
3261 }
3262
3263 bool visitSelectInst(SelectInst &SI) {
3264 enqueueUsers(SI);
3265 return false;
3266 }
3267};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00003268}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003269
Chandler Carruthba931992012-10-13 10:49:33 +00003270/// \brief Strip aggregate type wrapping.
3271///
3272/// This removes no-op aggregate types wrapping an underlying type. It will
3273/// strip as many layers of types as it can without changing either the type
3274/// size or the allocated size.
3275static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3276 if (Ty->isSingleValueType())
3277 return Ty;
3278
3279 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3280 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3281
3282 Type *InnerTy;
3283 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3284 InnerTy = ArrTy->getElementType();
3285 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3286 const StructLayout *SL = DL.getStructLayout(STy);
3287 unsigned Index = SL->getElementContainingOffset(0);
3288 InnerTy = STy->getElementType(Index);
3289 } else {
3290 return Ty;
3291 }
3292
3293 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3294 TypeSize > DL.getTypeSizeInBits(InnerTy))
3295 return Ty;
3296
3297 return stripAggregateTypeWrapping(DL, InnerTy);
3298}
3299
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003300/// \brief Try to find a partition of the aggregate type passed in for a given
3301/// offset and size.
3302///
3303/// This recurses through the aggregate type and tries to compute a subtype
3304/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003305/// of an array, it will even compute a new array type for that sub-section,
3306/// and the same for structs.
3307///
3308/// Note that this routine is very strict and tries to find a partition of the
3309/// type which produces the *exact* right offset and size. It is not forgiving
3310/// when the size or offset cause either end of type-based partition to be off.
3311/// Also, this is a best-effort routine. It is reasonable to give up and not
3312/// return a type if necessary.
Chandler Carruth113dc642014-12-20 02:39:18 +00003313static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3314 uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003315 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3316 return stripAggregateTypeWrapping(DL, Ty);
3317 if (Offset > DL.getTypeAllocSize(Ty) ||
3318 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003319 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003320
3321 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3322 // We can't partition pointers...
3323 if (SeqTy->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00003324 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003325
3326 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003327 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003328 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003329 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003330 if (NumSkippedElements >= ArrTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +00003331 return nullptr;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003332 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003333 if (NumSkippedElements >= VecTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +00003334 return nullptr;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003335 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003336 Offset -= NumSkippedElements * ElementSize;
3337
3338 // First check if we need to recurse.
3339 if (Offset > 0 || Size < ElementSize) {
3340 // Bail if the partition ends in a different array element.
3341 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003342 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003343 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003344 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003345 }
3346 assert(Offset == 0);
3347
3348 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003349 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003350 assert(Size > ElementSize);
3351 uint64_t NumElements = Size / ElementSize;
3352 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003353 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003354 return ArrayType::get(ElementTy, NumElements);
3355 }
3356
3357 StructType *STy = dyn_cast<StructType>(Ty);
3358 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003359 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003360
Chandler Carruth90a735d2013-07-19 07:21:28 +00003361 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003362 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003363 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003364 uint64_t EndOffset = Offset + Size;
3365 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003366 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003367
3368 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003369 Offset -= SL->getElementOffset(Index);
3370
3371 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003372 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003373 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003374 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003375
3376 // See if any partition must be contained by the element.
3377 if (Offset > 0 || Size < ElementSize) {
3378 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003379 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003380 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003381 }
3382 assert(Offset == 0);
3383
3384 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003385 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003386
3387 StructType::element_iterator EI = STy->element_begin() + Index,
3388 EE = STy->element_end();
3389 if (EndOffset < SL->getSizeInBytes()) {
3390 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3391 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003392 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003393
3394 // Don't try to form "natural" types if the elements don't line up with the
3395 // expected size.
3396 // FIXME: We could potentially recurse down through the last element in the
3397 // sub-struct to find a natural end point.
3398 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003399 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003400
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003401 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003402 EE = STy->element_begin() + EndIndex;
3403 }
3404
3405 // Try to build up a sub-structure.
Chandler Carruth113dc642014-12-20 02:39:18 +00003406 StructType *SubTy =
3407 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003408 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003409 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003410 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003411
Chandler Carruth054a40a2012-09-14 11:08:31 +00003412 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003413}
3414
Chandler Carruth0715cba2015-01-01 11:54:38 +00003415/// \brief Pre-split loads and stores to simplify rewriting.
3416///
3417/// We want to break up the splittable load+store pairs as much as
3418/// possible. This is important to do as a preprocessing step, as once we
3419/// start rewriting the accesses to partitions of the alloca we lose the
3420/// necessary information to correctly split apart paired loads and stores
3421/// which both point into this alloca. The case to consider is something like
3422/// the following:
3423///
3424/// %a = alloca [12 x i8]
3425/// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3426/// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3427/// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3428/// %iptr1 = bitcast i8* %gep1 to i64*
3429/// %iptr2 = bitcast i8* %gep2 to i64*
3430/// %fptr1 = bitcast i8* %gep1 to float*
3431/// %fptr2 = bitcast i8* %gep2 to float*
3432/// %fptr3 = bitcast i8* %gep3 to float*
3433/// store float 0.0, float* %fptr1
3434/// store float 1.0, float* %fptr2
3435/// %v = load i64* %iptr1
3436/// store i64 %v, i64* %iptr2
3437/// %f1 = load float* %fptr2
3438/// %f2 = load float* %fptr3
3439///
3440/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3441/// promote everything so we recover the 2 SSA values that should have been
3442/// there all along.
3443///
3444/// \returns true if any changes are made.
3445bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
3446 DEBUG(dbgs() << "Pre-splitting loads and stores\n");
3447
3448 // Track the loads and stores which are candidates for pre-splitting here, in
3449 // the order they first appear during the partition scan. These give stable
3450 // iteration order and a basis for tracking which loads and stores we
3451 // actually split.
3452 SmallVector<LoadInst *, 4> Loads;
3453 SmallVector<StoreInst *, 4> Stores;
3454
3455 // We need to accumulate the splits required of each load or store where we
3456 // can find them via a direct lookup. This is important to cross-check loads
3457 // and stores against each other. We also track the slice so that we can kill
3458 // all the slices that end up split.
3459 struct SplitOffsets {
3460 Slice *S;
3461 std::vector<uint64_t> Splits;
3462 };
3463 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3464
Chandler Carruth73b01642015-01-05 04:17:53 +00003465 // Track loads out of this alloca which cannot, for any reason, be pre-split.
3466 // This is important as we also cannot pre-split stores of those loads!
3467 // FIXME: This is all pretty gross. It means that we can be more aggressive
3468 // in pre-splitting when the load feeding the store happens to come from
3469 // a separate alloca. Put another way, the effectiveness of SROA would be
3470 // decreased by a frontend which just concatenated all of its local allocas
3471 // into one big flat alloca. But defeating such patterns is exactly the job
3472 // SROA is tasked with! Sadly, to not have this discrepancy we would have
3473 // change store pre-splitting to actually force pre-splitting of the load
3474 // that feeds it *and all stores*. That makes pre-splitting much harder, but
3475 // maybe it would make it more principled?
3476 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3477
Chandler Carruth0715cba2015-01-01 11:54:38 +00003478 DEBUG(dbgs() << " Searching for candidate loads and stores\n");
3479 for (auto &P : AS.partitions()) {
3480 for (Slice &S : P) {
Chandler Carruth73b01642015-01-05 04:17:53 +00003481 Instruction *I = cast<Instruction>(S.getUse()->getUser());
3482 if (!S.isSplittable() ||S.endOffset() <= P.endOffset()) {
3483 // If this was a load we have to track that it can't participate in any
3484 // pre-splitting!
3485 if (auto *LI = dyn_cast<LoadInst>(I))
3486 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003487 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003488 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003489 assert(P.endOffset() > S.beginOffset() &&
3490 "Empty or backwards partition!");
3491
3492 // Determine if this is a pre-splittable slice.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003493 if (auto *LI = dyn_cast<LoadInst>(I)) {
3494 assert(!LI->isVolatile() && "Cannot split volatile loads!");
3495
3496 // The load must be used exclusively to store into other pointers for
3497 // us to be able to arbitrarily pre-split it. The stores must also be
3498 // simple to avoid changing semantics.
3499 auto IsLoadSimplyStored = [](LoadInst *LI) {
3500 for (User *LU : LI->users()) {
3501 auto *SI = dyn_cast<StoreInst>(LU);
3502 if (!SI || !SI->isSimple())
3503 return false;
3504 }
3505 return true;
3506 };
Chandler Carruth73b01642015-01-05 04:17:53 +00003507 if (!IsLoadSimplyStored(LI)) {
3508 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003509 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003510 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003511
3512 Loads.push_back(LI);
3513 } else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser())) {
Chandler Carruth994cde82015-01-01 12:01:03 +00003514 if (!SI ||
3515 S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3516 continue;
3517 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3518 if (!StoredLoad || !StoredLoad->isSimple())
3519 continue;
3520 assert(!SI->isVolatile() && "Cannot split volatile stores!");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003521
Chandler Carruth994cde82015-01-01 12:01:03 +00003522 Stores.push_back(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003523 } else {
3524 // Other uses cannot be pre-split.
3525 continue;
3526 }
3527
3528 // Record the initial split.
3529 DEBUG(dbgs() << " Candidate: " << *I << "\n");
3530 auto &Offsets = SplitOffsetsMap[I];
3531 assert(Offsets.Splits.empty() &&
3532 "Should not have splits the first time we see an instruction!");
3533 Offsets.S = &S;
Chandler Carruth24ac8302015-01-02 03:55:54 +00003534 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003535 }
3536
3537 // Now scan the already split slices, and add a split for any of them which
3538 // we're going to pre-split.
3539 for (Slice *S : P.splitSliceTails()) {
3540 auto SplitOffsetsMapI =
3541 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3542 if (SplitOffsetsMapI == SplitOffsetsMap.end())
3543 continue;
3544 auto &Offsets = SplitOffsetsMapI->second;
3545
3546 assert(Offsets.S == S && "Found a mismatched slice!");
3547 assert(!Offsets.Splits.empty() &&
3548 "Cannot have an empty set of splits on the second partition!");
Chandler Carruth24ac8302015-01-02 03:55:54 +00003549 assert(Offsets.Splits.back() ==
3550 P.beginOffset() - Offsets.S->beginOffset() &&
Chandler Carruth0715cba2015-01-01 11:54:38 +00003551 "Previous split does not end where this one begins!");
3552
3553 // Record each split. The last partition's end isn't needed as the size
3554 // of the slice dictates that.
3555 if (S->endOffset() > P.endOffset())
Chandler Carruth24ac8302015-01-02 03:55:54 +00003556 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003557 }
3558 }
3559
3560 // We may have split loads where some of their stores are split stores. For
3561 // such loads and stores, we can only pre-split them if their splits exactly
3562 // match relative to their starting offset. We have to verify this prior to
3563 // any rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003564 Stores.erase(
Chandler Carruth994cde82015-01-01 12:01:03 +00003565 std::remove_if(Stores.begin(), Stores.end(),
Chandler Carruth73b01642015-01-05 04:17:53 +00003566 [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
Chandler Carruth994cde82015-01-01 12:01:03 +00003567 // Lookup the load we are storing in our map of split
3568 // offsets.
3569 auto *LI = cast<LoadInst>(SI->getValueOperand());
Chandler Carruth73b01642015-01-05 04:17:53 +00003570 // If it was completely unsplittable, then we're done,
3571 // and this store can't be pre-split.
3572 if (UnsplittableLoads.count(LI))
3573 return true;
3574
Chandler Carruth994cde82015-01-01 12:01:03 +00003575 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3576 if (LoadOffsetsI == SplitOffsetsMap.end())
Chandler Carruth73b01642015-01-05 04:17:53 +00003577 return false; // Unrelated loads are definitely safe.
Chandler Carruth994cde82015-01-01 12:01:03 +00003578 auto &LoadOffsets = LoadOffsetsI->second;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003579
Chandler Carruth994cde82015-01-01 12:01:03 +00003580 // Now lookup the store's offsets.
3581 auto &StoreOffsets = SplitOffsetsMap[SI];
Chandler Carruth0715cba2015-01-01 11:54:38 +00003582
Chandler Carruth994cde82015-01-01 12:01:03 +00003583 // If the relative offsets of each split in the load and
3584 // store match exactly, then we can split them and we
3585 // don't need to remove them here.
3586 if (LoadOffsets.Splits == StoreOffsets.Splits)
3587 return false;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003588
Chandler Carruth994cde82015-01-01 12:01:03 +00003589 DEBUG(dbgs()
3590 << " Mismatched splits for load and store:\n"
3591 << " " << *LI << "\n"
3592 << " " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003593
Chandler Carruth994cde82015-01-01 12:01:03 +00003594 // We've found a store and load that we need to split
3595 // with mismatched relative splits. Just give up on them
3596 // and remove both instructions from our list of
3597 // candidates.
Chandler Carruth73b01642015-01-05 04:17:53 +00003598 UnsplittableLoads.insert(LI);
Chandler Carruth994cde82015-01-01 12:01:03 +00003599 return true;
3600 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003601 Stores.end());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003602 // Now we have to go *back* through all the stores, because a later store may
Chandler Carruth73b01642015-01-05 04:17:53 +00003603 // have caused an earlier store's load to become unsplittable and if it is
3604 // unsplittable for the later store, then we can't rely on it being split in
3605 // the earlier store either.
3606 Stores.erase(std::remove_if(Stores.begin(), Stores.end(),
3607 [&UnsplittableLoads](StoreInst *SI) {
3608 auto *LI =
3609 cast<LoadInst>(SI->getValueOperand());
3610 return UnsplittableLoads.count(LI);
3611 }),
3612 Stores.end());
3613 // Once we've established all the loads that can't be split for some reason,
3614 // filter any that made it into our list out.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003615 Loads.erase(std::remove_if(Loads.begin(), Loads.end(),
Chandler Carruth73b01642015-01-05 04:17:53 +00003616 [&UnsplittableLoads](LoadInst *LI) {
3617 return UnsplittableLoads.count(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003618 }),
3619 Loads.end());
3620
Chandler Carruth73b01642015-01-05 04:17:53 +00003621
Chandler Carruth0715cba2015-01-01 11:54:38 +00003622 // If no loads or stores are left, there is no pre-splitting to be done for
3623 // this alloca.
3624 if (Loads.empty() && Stores.empty())
3625 return false;
3626
3627 // From here on, we can't fail and will be building new accesses, so rig up
3628 // an IR builder.
3629 IRBuilderTy IRB(&AI);
3630
3631 // Collect the new slices which we will merge into the alloca slices.
3632 SmallVector<Slice, 4> NewSlices;
3633
3634 // Track any allocas we end up splitting loads and stores for so we iterate
3635 // on them.
3636 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3637
3638 // At this point, we have collected all of the loads and stores we can
3639 // pre-split, and the specific splits needed for them. We actually do the
3640 // splitting in a specific order in order to handle when one of the loads in
3641 // the value operand to one of the stores.
3642 //
3643 // First, we rewrite all of the split loads, and just accumulate each split
3644 // load in a parallel structure. We also build the slices for them and append
3645 // them to the alloca slices.
3646 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3647 std::vector<LoadInst *> SplitLoads;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003648 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003649 for (LoadInst *LI : Loads) {
3650 SplitLoads.clear();
3651
3652 IntegerType *Ty = cast<IntegerType>(LI->getType());
3653 uint64_t LoadSize = Ty->getBitWidth() / 8;
3654 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3655
3656 auto &Offsets = SplitOffsetsMap[LI];
3657 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3658 "Slice size should always match load size exactly!");
3659 uint64_t BaseOffset = Offsets.S->beginOffset();
3660 assert(BaseOffset + LoadSize > BaseOffset &&
3661 "Cannot represent alloca access size using 64-bit integers!");
3662
3663 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
3664 IRB.SetInsertPoint(BasicBlock::iterator(LI));
3665
3666 DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
3667
3668 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3669 int Idx = 0, Size = Offsets.Splits.size();
3670 for (;;) {
3671 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3672 auto *PartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3673 LoadInst *PLoad = IRB.CreateAlignedLoad(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003674 getAdjustedPtr(IRB, DL, BasePtr,
3675 APInt(DL.getPointerSizeInBits(), PartOffset),
Chandler Carruth994cde82015-01-01 12:01:03 +00003676 PartPtrTy, BasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003677 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003678 LI->getName());
3679
3680 // Append this load onto the list of split loads so we can find it later
3681 // to rewrite the stores.
3682 SplitLoads.push_back(PLoad);
3683
3684 // Now build a new slice for the alloca.
Chandler Carruth994cde82015-01-01 12:01:03 +00003685 NewSlices.push_back(
3686 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3687 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003688 /*IsSplittable*/ false));
Chandler Carruth6044c0b2015-01-01 12:56:47 +00003689 DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3690 << ", " << NewSlices.back().endOffset() << "): " << *PLoad
3691 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003692
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003693 // See if we've handled all the splits.
3694 if (Idx >= Size)
3695 break;
3696
Chandler Carruth0715cba2015-01-01 11:54:38 +00003697 // Setup the next partition.
3698 PartOffset = Offsets.Splits[Idx];
3699 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003700 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3701 }
3702
3703 // Now that we have the split loads, do the slow walk over all uses of the
3704 // load and rewrite them as split stores, or save the split loads to use
3705 // below if the store is going to be split there anyways.
3706 bool DeferredStores = false;
3707 for (User *LU : LI->users()) {
3708 StoreInst *SI = cast<StoreInst>(LU);
3709 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3710 DeferredStores = true;
3711 DEBUG(dbgs() << " Deferred splitting of store: " << *SI << "\n");
3712 continue;
3713 }
3714
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003715 Value *StoreBasePtr = SI->getPointerOperand();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003716 IRB.SetInsertPoint(BasicBlock::iterator(SI));
3717
3718 DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
3719
3720 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3721 LoadInst *PLoad = SplitLoads[Idx];
3722 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
Chandler Carruth994cde82015-01-01 12:01:03 +00003723 auto *PartPtrTy =
3724 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003725
3726 StoreInst *PStore = IRB.CreateAlignedStore(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003727 PLoad, getAdjustedPtr(IRB, DL, StoreBasePtr,
3728 APInt(DL.getPointerSizeInBits(), PartOffset),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003729 PartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003730 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003731 (void)PStore;
3732 DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
3733 }
3734
3735 // We want to immediately iterate on any allocas impacted by splitting
3736 // this store, and we have to track any promotable alloca (indicated by
3737 // a direct store) as needing to be resplit because it is no longer
3738 // promotable.
3739 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3740 ResplitPromotableAllocas.insert(OtherAI);
3741 Worklist.insert(OtherAI);
3742 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3743 StoreBasePtr->stripInBoundsOffsets())) {
3744 Worklist.insert(OtherAI);
3745 }
3746
3747 // Mark the original store as dead.
3748 DeadInsts.insert(SI);
3749 }
3750
3751 // Save the split loads if there are deferred stores among the users.
3752 if (DeferredStores)
3753 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3754
3755 // Mark the original load as dead and kill the original slice.
3756 DeadInsts.insert(LI);
3757 Offsets.S->kill();
3758 }
3759
3760 // Second, we rewrite all of the split stores. At this point, we know that
3761 // all loads from this alloca have been split already. For stores of such
3762 // loads, we can simply look up the pre-existing split loads. For stores of
3763 // other loads, we split those loads first and then write split stores of
3764 // them.
3765 for (StoreInst *SI : Stores) {
3766 auto *LI = cast<LoadInst>(SI->getValueOperand());
3767 IntegerType *Ty = cast<IntegerType>(LI->getType());
3768 uint64_t StoreSize = Ty->getBitWidth() / 8;
3769 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3770
3771 auto &Offsets = SplitOffsetsMap[SI];
3772 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3773 "Slice size should always match load size exactly!");
3774 uint64_t BaseOffset = Offsets.S->beginOffset();
3775 assert(BaseOffset + StoreSize > BaseOffset &&
3776 "Cannot represent alloca access size using 64-bit integers!");
3777
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003778 Value *LoadBasePtr = LI->getPointerOperand();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003779 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3780
3781 DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
3782
3783 // Check whether we have an already split load.
3784 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3785 std::vector<LoadInst *> *SplitLoads = nullptr;
3786 if (SplitLoadsMapI != SplitLoadsMap.end()) {
3787 SplitLoads = &SplitLoadsMapI->second;
3788 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3789 "Too few split loads for the number of splits in the store!");
3790 } else {
3791 DEBUG(dbgs() << " of load: " << *LI << "\n");
3792 }
3793
Chandler Carruth0715cba2015-01-01 11:54:38 +00003794 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3795 int Idx = 0, Size = Offsets.Splits.size();
3796 for (;;) {
3797 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3798 auto *PartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
3799
3800 // Either lookup a split load or create one.
3801 LoadInst *PLoad;
3802 if (SplitLoads) {
3803 PLoad = (*SplitLoads)[Idx];
3804 } else {
3805 IRB.SetInsertPoint(BasicBlock::iterator(LI));
3806 PLoad = IRB.CreateAlignedLoad(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003807 getAdjustedPtr(IRB, DL, LoadBasePtr,
3808 APInt(DL.getPointerSizeInBits(), PartOffset),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003809 PartPtrTy, LoadBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003810 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003811 LI->getName());
3812 }
3813
3814 // And store this partition.
3815 IRB.SetInsertPoint(BasicBlock::iterator(SI));
3816 StoreInst *PStore = IRB.CreateAlignedStore(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003817 PLoad, getAdjustedPtr(IRB, DL, StoreBasePtr,
3818 APInt(DL.getPointerSizeInBits(), PartOffset),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003819 PartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003820 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003821
3822 // Now build a new slice for the alloca.
3823 NewSlices.push_back(
3824 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3825 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003826 /*IsSplittable*/ false));
Chandler Carruth6044c0b2015-01-01 12:56:47 +00003827 DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3828 << ", " << NewSlices.back().endOffset() << "): " << *PStore
3829 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003830 if (!SplitLoads) {
3831 DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
3832 }
3833
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003834 // See if we've finished all the splits.
3835 if (Idx >= Size)
3836 break;
3837
Chandler Carruth0715cba2015-01-01 11:54:38 +00003838 // Setup the next partition.
3839 PartOffset = Offsets.Splits[Idx];
3840 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003841 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
3842 }
3843
3844 // We want to immediately iterate on any allocas impacted by splitting
3845 // this load, which is only relevant if it isn't a load of this alloca and
3846 // thus we didn't already split the loads above. We also have to keep track
3847 // of any promotable allocas we split loads on as they can no longer be
3848 // promoted.
3849 if (!SplitLoads) {
3850 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
3851 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3852 ResplitPromotableAllocas.insert(OtherAI);
3853 Worklist.insert(OtherAI);
3854 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3855 LoadBasePtr->stripInBoundsOffsets())) {
3856 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3857 Worklist.insert(OtherAI);
3858 }
3859 }
3860
3861 // Mark the original store as dead now that we've split it up and kill its
Chandler Carruth24ac8302015-01-02 03:55:54 +00003862 // slice. Note that we leave the original load in place unless this store
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003863 // was its only use. It may in turn be split up if it is an alloca load
Chandler Carruth24ac8302015-01-02 03:55:54 +00003864 // for some other alloca, but it may be a normal load. This may introduce
3865 // redundant loads, but where those can be merged the rest of the optimizer
3866 // should handle the merging, and this uncovers SSA splits which is more
3867 // important. In practice, the original loads will almost always be fully
3868 // split and removed eventually, and the splits will be merged by any
3869 // trivial CSE, including instcombine.
3870 if (LI->hasOneUse()) {
3871 assert(*LI->user_begin() == SI && "Single use isn't this store!");
3872 DeadInsts.insert(LI);
3873 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003874 DeadInsts.insert(SI);
3875 Offsets.S->kill();
3876 }
3877
Chandler Carruth24ac8302015-01-02 03:55:54 +00003878 // Remove the killed slices that have ben pre-split.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003879 AS.erase(std::remove_if(AS.begin(), AS.end(), [](const Slice &S) {
3880 return S.isDead();
3881 }), AS.end());
3882
Chandler Carruth24ac8302015-01-02 03:55:54 +00003883 // Insert our new slices. This will sort and merge them into the sorted
3884 // sequence.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003885 AS.insert(NewSlices);
3886
3887 DEBUG(dbgs() << " Pre-split slices:\n");
3888#ifndef NDEBUG
3889 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
3890 DEBUG(AS.print(dbgs(), I, " "));
3891#endif
3892
3893 // Finally, don't try to promote any allocas that new require re-splitting.
3894 // They have already been added to the worklist above.
3895 PromotableAllocas.erase(
3896 std::remove_if(
3897 PromotableAllocas.begin(), PromotableAllocas.end(),
3898 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
3899 PromotableAllocas.end());
3900
3901 return true;
3902}
3903
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003904/// \brief Rewrite an alloca partition's users.
3905///
3906/// This routine drives both of the rewriting goals of the SROA pass. It tries
3907/// to rewrite uses of an alloca partition to be conducive for SSA value
3908/// promotion. If the partition needs a new, more refined alloca, this will
3909/// build that new alloca, preserving as much type information as possible, and
3910/// rewrite the uses of the old alloca to point at the new one and have the
3911/// appropriate new offsets. It also evaluates how successful the rewrite was
3912/// at enabling promotion and if it was successful queues the alloca to be
3913/// promoted.
Adrian Prantl565cc182015-01-20 19:42:22 +00003914AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
3915 AllocaSlices::Partition &P) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003916 // Try to compute a friendly type for this partition of the alloca. This
3917 // won't always succeed, in which case we fall back to a legal integer type
3918 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00003919 Type *SliceTy = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003920 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003921 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003922 if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003923 SliceTy = CommonUseTy;
3924 if (!SliceTy)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003925 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003926 P.beginOffset(), P.size()))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003927 SliceTy = TypePartitionTy;
3928 if ((!SliceTy || (SliceTy->isArrayTy() &&
3929 SliceTy->getArrayElementType()->isIntegerTy())) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003930 DL.isLegalInteger(P.size() * 8))
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003931 SliceTy = Type::getIntNTy(*C, P.size() * 8);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003932 if (!SliceTy)
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003933 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003934 assert(DL.getTypeAllocSize(SliceTy) >= P.size());
Chandler Carruthf0546402013-07-18 07:15:00 +00003935
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003936 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00003937
Chandler Carruth2dc96822014-10-18 00:44:02 +00003938 VectorType *VecTy =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003939 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
Chandler Carruth2dc96822014-10-18 00:44:02 +00003940 if (VecTy)
3941 SliceTy = VecTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003942
3943 // Check for the case where we're going to rewrite to a new alloca of the
3944 // exact same type as the original, and with the same access offsets. In that
3945 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003946 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003947 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003948 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003949 assert(P.beginOffset() == 0 &&
3950 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003951 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003952 // FIXME: We should be able to bail at this point with "nothing changed".
3953 // FIXME: We might want to defer PHI speculation until after here.
Adrian Prantl565cc182015-01-20 19:42:22 +00003954 // FIXME: return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003955 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003956 unsigned Alignment = AI.getAlignment();
3957 if (!Alignment) {
3958 // The minimum alignment which users can rely on when the explicit
3959 // alignment is omitted or zero is that required by the ABI for this
3960 // type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003961 Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003962 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003963 Alignment = MinAlign(Alignment, P.beginOffset());
Chandler Carruth903790e2012-09-29 10:41:21 +00003964 // If we will get at least this much alignment from the type alone, leave
3965 // the alloca's alignment unconstrained.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003966 if (Alignment <= DL.getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003967 Alignment = 0;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003968 NewAI = new AllocaInst(
3969 SliceTy, nullptr, Alignment,
3970 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003971 ++NumNewAllocas;
3972 }
3973
3974 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003975 << "[" << P.beginOffset() << "," << P.endOffset()
3976 << ") to: " << *NewAI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003977
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003978 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00003979 // promoted allocas. We will reset it to this point if the alloca is not in
3980 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003981 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00003982 unsigned NumUses = 0;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003983 SmallPtrSet<PHINode *, 8> PHIUsers;
3984 SmallPtrSet<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003985
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003986 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003987 P.endOffset(), IsIntegerPromotable, VecTy,
3988 PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00003989 bool Promotable = true;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00003990 for (Slice *S : P.splitSliceTails()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003991 Promotable &= Rewriter.visit(S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003992 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003993 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003994 for (Slice &S : P) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003995 Promotable &= Rewriter.visit(&S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003996 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003997 }
3998
Chandler Carruth6c321c12013-07-19 10:57:36 +00003999 NumAllocaPartitionUses += NumUses;
4000 MaxUsesPerAllocaPartition =
4001 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004002
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004003 // Now that we've processed all the slices in the new partition, check if any
4004 // PHIs or Selects would block promotion.
4005 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
4006 E = PHIUsers.end();
4007 I != E; ++I)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004008 if (!isSafePHIToSpeculate(**I)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004009 Promotable = false;
4010 PHIUsers.clear();
4011 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00004012 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004013 }
4014 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
4015 E = SelectUsers.end();
4016 I != E; ++I)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004017 if (!isSafeSelectToSpeculate(**I)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004018 Promotable = false;
4019 PHIUsers.clear();
4020 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00004021 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004022 }
4023
4024 if (Promotable) {
4025 if (PHIUsers.empty() && SelectUsers.empty()) {
4026 // Promote the alloca.
4027 PromotableAllocas.push_back(NewAI);
4028 } else {
4029 // If we have either PHIs or Selects to speculate, add them to those
4030 // worklists and re-queue the new alloca so that we promote in on the
4031 // next iteration.
Chandler Carruth61747042014-10-16 21:05:14 +00004032 for (PHINode *PHIUser : PHIUsers)
4033 SpeculatablePHIs.insert(PHIUser);
4034 for (SelectInst *SelectUser : SelectUsers)
4035 SpeculatableSelects.insert(SelectUser);
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004036 Worklist.insert(NewAI);
4037 }
4038 } else {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004039 // If we can't promote the alloca, iterate on it to check for new
4040 // refinements exposed by splitting the current alloca. Don't iterate on an
4041 // alloca which didn't actually change and didn't get promoted.
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004042 if (NewAI != &AI)
4043 Worklist.insert(NewAI);
Chandler Carruthac8317f2012-10-04 12:33:50 +00004044
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004045 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00004046 while (PostPromotionWorklist.size() > PPWOldSize)
4047 PostPromotionWorklist.pop_back();
Chandler Carruthf0546402013-07-18 07:15:00 +00004048 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00004049
Adrian Prantl565cc182015-01-20 19:42:22 +00004050 return NewAI;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004051}
4052
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004053/// \brief Walks the slices of an alloca and form partitions based on them,
4054/// rewriting each of their uses.
Chandler Carruth83934062014-10-16 21:11:55 +00004055bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
4056 if (AS.begin() == AS.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00004057 return false;
4058
Chandler Carruth6c321c12013-07-19 10:57:36 +00004059 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004060 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004061 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00004062
Chandler Carruth24ac8302015-01-02 03:55:54 +00004063 // First try to pre-split loads and stores.
Chandler Carruth0715cba2015-01-01 11:54:38 +00004064 Changed |= presplitLoadsAndStores(AI, AS);
4065
Chandler Carruth24ac8302015-01-02 03:55:54 +00004066 // Now that we have identified any pre-splitting opportunities, mark any
4067 // splittable (non-whole-alloca) loads and stores as unsplittable. If we fail
4068 // to split these during pre-splitting, we want to force them to be
4069 // rewritten into a partition.
4070 bool IsSorted = true;
4071 for (Slice &S : AS) {
4072 if (!S.isSplittable())
4073 continue;
4074 // FIXME: We currently leave whole-alloca splittable loads and stores. This
4075 // used to be the only splittable loads and stores and we need to be
4076 // confident that the above handling of splittable loads and stores is
4077 // completely sufficient before we forcibly disable the remaining handling.
4078 if (S.beginOffset() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004079 S.endOffset() >= DL.getTypeAllocSize(AI.getAllocatedType()))
Chandler Carruth24ac8302015-01-02 03:55:54 +00004080 continue;
4081 if (isa<LoadInst>(S.getUse()->getUser()) ||
4082 isa<StoreInst>(S.getUse()->getUser())) {
4083 S.makeUnsplittable();
4084 IsSorted = false;
4085 }
4086 }
4087 if (!IsSorted)
4088 std::sort(AS.begin(), AS.end());
4089
Adrian Prantl565cc182015-01-20 19:42:22 +00004090 /// \brief Describes the allocas introduced by rewritePartition
4091 /// in order to migrate the debug info.
4092 struct Piece {
4093 AllocaInst *Alloca;
4094 uint64_t Offset;
4095 uint64_t Size;
4096 Piece(AllocaInst *AI, uint64_t O, uint64_t S)
4097 : Alloca(AI), Offset(O), Size(S) {}
4098 };
4099 SmallVector<Piece, 4> Pieces;
4100
Chandler Carruth0715cba2015-01-01 11:54:38 +00004101 // Rewrite each partition.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004102 for (auto &P : AS.partitions()) {
Adrian Prantl565cc182015-01-20 19:42:22 +00004103 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4104 Changed = true;
Adrian Prantl34e75902015-02-09 23:57:22 +00004105 if (NewAI != &AI) {
4106 uint64_t SizeOfByte = 8;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004107 uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
Adrian Prantl34e75902015-02-09 23:57:22 +00004108 // Don't include any padding.
4109 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
4110 Pieces.push_back(Piece(NewAI, P.beginOffset() * SizeOfByte, Size));
4111 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004112 }
Chandler Carruth6c321c12013-07-19 10:57:36 +00004113 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00004114 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004115
Chandler Carruth6c321c12013-07-19 10:57:36 +00004116 NumAllocaPartitions += NumPartitions;
4117 MaxPartitionsPerAlloca =
4118 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004119
Adrian Prantl565cc182015-01-20 19:42:22 +00004120 // Migrate debug information from the old alloca to the new alloca(s)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004121 // and the individual partitions.
Adrian Prantl565cc182015-01-20 19:42:22 +00004122 if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(&AI)) {
Duncan P. N. Exon Smith60635e32015-04-21 18:44:06 +00004123 auto *Var = DbgDecl->getVariable();
4124 auto *Expr = DbgDecl->getExpression();
Adrian Prantl565cc182015-01-20 19:42:22 +00004125 DIBuilder DIB(*AI.getParent()->getParent()->getParent(),
4126 /*AllowUnresolved*/ false);
4127 bool IsSplit = Pieces.size() > 1;
4128 for (auto Piece : Pieces) {
4129 // Create a piece expression describing the new partition or reuse AI's
4130 // expression if there is only one partition.
Duncan P. N. Exon Smith60635e32015-04-21 18:44:06 +00004131 auto *PieceExpr = Expr;
Duncan P. N. Exon Smith6a0320a2015-04-14 01:12:42 +00004132 if (IsSplit || Expr->isBitPiece()) {
Adrian Prantl152ac392015-02-01 00:58:04 +00004133 // If this alloca is already a scalar replacement of a larger aggregate,
4134 // Piece.Offset describes the offset inside the scalar.
Duncan P. N. Exon Smith6a0320a2015-04-14 01:12:42 +00004135 uint64_t Offset = Expr->isBitPiece() ? Expr->getBitPieceOffset() : 0;
Adrian Prantl34e75902015-02-09 23:57:22 +00004136 uint64_t Start = Offset + Piece.Offset;
4137 uint64_t Size = Piece.Size;
Duncan P. N. Exon Smith6a0320a2015-04-14 01:12:42 +00004138 if (Expr->isBitPiece()) {
4139 uint64_t AbsEnd = Expr->getBitPieceOffset() + Expr->getBitPieceSize();
Adrian Prantl34e75902015-02-09 23:57:22 +00004140 if (Start >= AbsEnd)
4141 // No need to describe a SROAed padding.
4142 continue;
4143 Size = std::min(Size, AbsEnd - Start);
4144 }
4145 PieceExpr = DIB.createBitPieceExpression(Start, Size);
Adrian Prantl152ac392015-02-01 00:58:04 +00004146 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004147
4148 // Remove any existing dbg.declare intrinsic describing the same alloca.
4149 if (DbgDeclareInst *OldDDI = FindAllocaDbgDeclare(Piece.Alloca))
4150 OldDDI->eraseFromParent();
4151
Duncan P. N. Exon Smithcd1aecf2015-04-15 21:18:07 +00004152 DIB.insertDeclare(Piece.Alloca, Var, PieceExpr, DbgDecl->getDebugLoc(),
4153 &AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004154 }
4155 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004156 return Changed;
4157}
4158
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004159/// \brief Clobber a use with undef, deleting the used value if it becomes dead.
4160void SROA::clobberUse(Use &U) {
4161 Value *OldV = U;
4162 // Replace the use with an undef value.
4163 U = UndefValue::get(OldV->getType());
4164
4165 // Check for this making an instruction dead. We have to garbage collect
4166 // all the dead instructions to ensure the uses of any alloca end up being
4167 // minimal.
4168 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4169 if (isInstructionTriviallyDead(OldI)) {
4170 DeadInsts.insert(OldI);
4171 }
4172}
4173
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004174/// \brief Analyze an alloca for SROA.
4175///
4176/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004177/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004178/// rewritten as needed.
4179bool SROA::runOnAlloca(AllocaInst &AI) {
4180 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
4181 ++NumAllocasAnalyzed;
4182
4183 // Special case dead allocas, as they're trivial.
4184 if (AI.use_empty()) {
4185 AI.eraseFromParent();
4186 return true;
4187 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004188 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004189
4190 // Skip alloca forms that this analysis can't handle.
4191 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004192 DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004193 return false;
4194
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004195 bool Changed = false;
4196
4197 // First, split any FCA loads and stores touching this alloca to promote
4198 // better splitting and promotion opportunities.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004199 AggLoadStoreRewriter AggRewriter(DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004200 Changed |= AggRewriter.rewrite(AI);
4201
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004202 // Build the slices using a recursive instruction-visiting builder.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004203 AllocaSlices AS(DL, AI);
Chandler Carruth83934062014-10-16 21:11:55 +00004204 DEBUG(AS.print(dbgs()));
4205 if (AS.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004206 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004207
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004208 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth83934062014-10-16 21:11:55 +00004209 for (Instruction *DeadUser : AS.getDeadUsers()) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004210 // Free up everything used by this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004211 for (Use &DeadOp : DeadUser->operands())
Chandler Carruth1583e992014-03-03 10:42:58 +00004212 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004213
4214 // Now replace the uses of this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004215 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004216
4217 // And mark it for deletion.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004218 DeadInsts.insert(DeadUser);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004219 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004220 }
Chandler Carruth83934062014-10-16 21:11:55 +00004221 for (Use *DeadOp : AS.getDeadOperands()) {
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004222 clobberUse(*DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004223 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004224 }
4225
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004226 // No slices to split. Leave the dead alloca for a later pass to clean up.
Chandler Carruth83934062014-10-16 21:11:55 +00004227 if (AS.begin() == AS.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00004228 return Changed;
4229
Chandler Carruth83934062014-10-16 21:11:55 +00004230 Changed |= splitAlloca(AI, AS);
Chandler Carruthf0546402013-07-18 07:15:00 +00004231
4232 DEBUG(dbgs() << " Speculating PHIs\n");
4233 while (!SpeculatablePHIs.empty())
4234 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4235
4236 DEBUG(dbgs() << " Speculating Selects\n");
4237 while (!SpeculatableSelects.empty())
4238 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4239
4240 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004241}
4242
Chandler Carruth19450da2012-09-14 10:26:38 +00004243/// \brief Delete the dead instructions accumulated in this run.
4244///
4245/// Recursively deletes the dead instructions we've accumulated. This is done
4246/// at the very end to maximize locality of the recursive delete and to
4247/// minimize the problems of invalidated instruction pointers as such pointers
4248/// are used heavily in the intermediate stages of the algorithm.
4249///
4250/// We also record the alloca instructions deleted here so that they aren't
4251/// subsequently handed to mem2reg to promote.
Chandler Carruth113dc642014-12-20 02:39:18 +00004252void SROA::deleteDeadInstructions(
4253 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004254 while (!DeadInsts.empty()) {
4255 Instruction *I = DeadInsts.pop_back_val();
4256 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
4257
Chandler Carruth58d05562012-10-25 04:37:07 +00004258 I->replaceAllUsesWith(UndefValue::get(I->getType()));
4259
Chandler Carruth1583e992014-03-03 10:42:58 +00004260 for (Use &Operand : I->operands())
4261 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004262 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00004263 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004264 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00004265 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004266 }
4267
Adrian Prantl565cc182015-01-20 19:42:22 +00004268 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004269 DeletedAllocas.insert(AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004270 if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(AI))
4271 DbgDecl->eraseFromParent();
4272 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004273
4274 ++NumDeleted;
4275 I->eraseFromParent();
4276 }
4277}
4278
Chandler Carruth70b44c52012-09-15 11:43:14 +00004279/// \brief Promote the allocas, using the best available technique.
4280///
4281/// This attempts to promote whatever allocas have been identified as viable in
4282/// the PromotableAllocas list. If that list is empty, there is nothing to do.
Chandler Carruth748d0952015-08-26 09:09:29 +00004283/// This function returns whether any promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004284bool SROA::promoteAllocas(Function &F) {
4285 if (PromotableAllocas.empty())
4286 return false;
4287
4288 NumPromoted += PromotableAllocas.size();
4289
Chandler Carruth748d0952015-08-26 09:09:29 +00004290 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
4291 PromoteMemToReg(PromotableAllocas, *DT, nullptr, AC);
Chandler Carruth70b44c52012-09-15 11:43:14 +00004292 PromotableAllocas.clear();
4293 return true;
4294}
4295
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004296bool SROA::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00004297 if (skipOptnoneFunction(F))
4298 return false;
4299
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004300 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
4301 C = &F.getContext();
Chandler Carruth748d0952015-08-26 09:09:29 +00004302 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth66b31302015-01-04 12:03:27 +00004303 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004304
4305 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00004306 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Adrian Prantl565cc182015-01-20 19:42:22 +00004307 I != E; ++I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004308 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4309 Worklist.insert(AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004310 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004311
4312 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00004313 // A set of deleted alloca instruction pointers which should be removed from
4314 // the list of promotable allocas.
4315 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4316
Chandler Carruthac8317f2012-10-04 12:33:50 +00004317 do {
4318 while (!Worklist.empty()) {
4319 Changed |= runOnAlloca(*Worklist.pop_back_val());
4320 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00004321
Chandler Carruthac8317f2012-10-04 12:33:50 +00004322 // Remove the deleted allocas from various lists so that we don't try to
4323 // continue processing them.
4324 if (!DeletedAllocas.empty()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00004325 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00004326 Worklist.remove_if(IsInSet);
4327 PostPromotionWorklist.remove_if(IsInSet);
Chandler Carruthac8317f2012-10-04 12:33:50 +00004328 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
4329 PromotableAllocas.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00004330 IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00004331 PromotableAllocas.end());
4332 DeletedAllocas.clear();
4333 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004334 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004335
Chandler Carruthac8317f2012-10-04 12:33:50 +00004336 Changed |= promoteAllocas(F);
4337
4338 Worklist = PostPromotionWorklist;
4339 PostPromotionWorklist.clear();
4340 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004341
4342 return Changed;
4343}
4344
4345void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth66b31302015-01-04 12:03:27 +00004346 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth748d0952015-08-26 09:09:29 +00004347 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004348 AU.setPreservesCFG();
4349}