blob: a7c1dc14713d5391657342f54b45e26b1cb68886 [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"
Hal Finkel60db0582014-09-07 18:57:58 +000031#include "llvm/Analysis/AssumptionTracker.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"
58#include "llvm/Transforms/Utils/SSAUpdater.h"
Chandler Carruth83cee772014-02-25 03:59:29 +000059
60#if __cplusplus >= 201103L && !defined(NDEBUG)
61// We only use this for a debug check in C++11
62#include <random>
63#endif
64
Chandler Carruth1b398ae2012-09-14 09:22:59 +000065using namespace llvm;
66
Chandler Carruth964daaa2014-04-22 02:55:47 +000067#define DEBUG_TYPE "sroa"
68
Chandler Carruth1b398ae2012-09-14 09:22:59 +000069STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000070STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +000071STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
72STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
73STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000074STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
75STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000076STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000077STATISTIC(NumDeleted, "Number of instructions deleted");
78STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000079
Chandler Carruth70b44c52012-09-15 11:43:14 +000080/// Hidden option to force the pass to not use DomTree and mem2reg, instead
81/// forming SSA values through the SSAUpdater infrastructure.
Chandler Carruth113dc642014-12-20 02:39:18 +000082static cl::opt<bool> ForceSSAUpdater("force-ssa-updater", cl::init(false),
83 cl::Hidden);
Chandler Carruth70b44c52012-09-15 11:43:14 +000084
Chandler Carruth83cee772014-02-25 03:59:29 +000085/// Hidden option to enable randomly shuffling the slices to help uncover
86/// instability in their order.
87static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
88 cl::init(false), cl::Hidden);
89
Chandler Carruth3b79b2a2014-02-25 21:24:45 +000090/// Hidden option to experiment with completely strict handling of inbounds
91/// GEPs.
Chandler Carruth113dc642014-12-20 02:39:18 +000092static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
93 cl::Hidden);
Chandler Carruth3b79b2a2014-02-25 21:24:45 +000094
Chandler Carruth1b398ae2012-09-14 09:22:59 +000095namespace {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000096/// \brief A custom IRBuilder inserter which prefixes all names if they are
97/// preserved.
98template <bool preserveNames = true>
Chandler Carruth113dc642014-12-20 02:39:18 +000099class IRBuilderPrefixedInserter
100 : public IRBuilderDefaultInserter<preserveNames> {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000101 std::string Prefix;
102
103public:
104 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
105
106protected:
107 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
108 BasicBlock::iterator InsertPt) const {
109 IRBuilderDefaultInserter<preserveNames>::InsertHelper(
110 I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
111 }
112};
113
114// Specialization for not preserving the name is trivial.
115template <>
Chandler Carruth113dc642014-12-20 02:39:18 +0000116class IRBuilderPrefixedInserter<false>
117 : public IRBuilderDefaultInserter<false> {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000118public:
119 void SetNamePrefix(const Twine &P) {}
120};
121
Chandler Carruthd177f862013-03-20 07:30:36 +0000122/// \brief Provide a typedef for IRBuilder that drops names in release builds.
123#ifndef NDEBUG
Chandler Carruth113dc642014-12-20 02:39:18 +0000124typedef llvm::IRBuilder<true, ConstantFolder, IRBuilderPrefixedInserter<true>>
125 IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000126#else
Chandler Carruth113dc642014-12-20 02:39:18 +0000127typedef llvm::IRBuilder<false, ConstantFolder, IRBuilderPrefixedInserter<false>>
128 IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000129#endif
130}
131
132namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000133/// \brief A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000134///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000135/// This structure represents a slice of an alloca used by some instruction. It
136/// stores both the begin and end offsets of this use, a pointer to the use
137/// itself, and a flag indicating whether we can classify the use as splittable
138/// or not when forming partitions of the alloca.
139class Slice {
Chandler Carruthf74654d2013-03-18 08:36:46 +0000140 /// \brief The beginning offset of the range.
141 uint64_t BeginOffset;
142
143 /// \brief The ending offset, not included in the range.
144 uint64_t EndOffset;
145
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000146 /// \brief Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000147 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000148 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000149
150public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000151 Slice() : BeginOffset(), EndOffset() {}
152 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000153 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000154 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000155
156 uint64_t beginOffset() const { return BeginOffset; }
157 uint64_t endOffset() const { return EndOffset; }
158
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000159 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
160 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000161
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000162 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000163
Craig Topperf40110f2014-04-25 05:29:35 +0000164 bool isDead() const { return getUse() == nullptr; }
165 void kill() { UseAndIsSplittable.setPointer(nullptr); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000166
167 /// \brief Support for ordering ranges.
168 ///
169 /// This provides an ordering over ranges such that start offsets are
170 /// always increasing, and within equal start offsets, the end offsets are
171 /// decreasing. Thus the spanning range comes first in a cluster with the
172 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000173 bool operator<(const Slice &RHS) const {
Chandler Carruth113dc642014-12-20 02:39:18 +0000174 if (beginOffset() < RHS.beginOffset())
175 return true;
176 if (beginOffset() > RHS.beginOffset())
177 return false;
178 if (isSplittable() != RHS.isSplittable())
179 return !isSplittable();
180 if (endOffset() > RHS.endOffset())
181 return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000182 return false;
183 }
184
185 /// \brief Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000186 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000187 uint64_t RHSOffset) {
188 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000189 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000190 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000191 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000192 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000193 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000194
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000195 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000196 return isSplittable() == RHS.isSplittable() &&
197 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000198 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000199 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000200};
Chandler Carruthf0546402013-07-18 07:15:00 +0000201} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000202
203namespace llvm {
Chandler Carruthf0546402013-07-18 07:15:00 +0000204template <typename T> struct isPodLike;
Chandler Carruth113dc642014-12-20 02:39:18 +0000205template <> struct isPodLike<Slice> { static const bool value = true; };
Chandler Carruthf74654d2013-03-18 08:36:46 +0000206}
207
208namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000209/// \brief Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000210///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000211/// This class represents the slices of an alloca which are formed by its
212/// various uses. If a pointer escapes, we can't fully build a representation
213/// for the slices used and we reflect that in this structure. The uses are
214/// stored, sorted by increasing beginning offset and with unsplittable slices
215/// starting at a particular offset before splittable slices.
216class AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000217public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000218 /// \brief Construct the slices of a particular alloca.
219 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000220
221 /// \brief Test whether a pointer to the allocation escapes our analysis.
222 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000223 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000224 /// ignored.
225 bool isEscaped() const { return PointerEscapingInstr; }
226
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000227 /// \brief Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000228 /// @{
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000229 typedef SmallVectorImpl<Slice>::iterator iterator;
Chandler Carruthc659df92014-10-16 20:24:07 +0000230 typedef iterator_range<iterator> range;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000231 iterator begin() { return Slices.begin(); }
232 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000233
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000234 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
Chandler Carruthc659df92014-10-16 20:24:07 +0000235 typedef iterator_range<const_iterator> const_range;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000236 const_iterator begin() const { return Slices.begin(); }
237 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000238 /// @}
239
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000240 // Forward declare an iterator to befriend it.
241 class partition_iterator;
242
243 /// \brief A partition of the slices.
244 ///
245 /// An ephemeral representation for a range of slices which can be viewed as
246 /// a partition of the alloca. This range represents a span of the alloca's
247 /// memory which cannot be split, and provides access to all of the slices
248 /// overlapping some part of the partition.
249 ///
250 /// Objects of this type are produced by traversing the alloca's slices, but
251 /// are only ephemeral and not persistent.
252 class Partition {
253 private:
254 friend class AllocaSlices;
255 friend class AllocaSlices::partition_iterator;
256
257 /// \brief The begining and ending offsets of the alloca for this partition.
258 uint64_t BeginOffset, EndOffset;
259
260 /// \brief The start end end iterators of this partition.
261 iterator SI, SJ;
262
263 /// \brief A collection of split slices.
264 SmallVector<Slice *, 4> SplitSlices;
265
266 /// \brief Raw constructor builds an empty partition starting and ending at
267 /// the given iterator.
268 Partition(iterator SI) : SI(SI), SJ(SI) {}
269
270 public:
271 /// \brief The start offset of this partition.
272 ///
273 /// All of the contained slices start at or after this offset.
274 uint64_t beginOffset() const { return BeginOffset; }
275
276 /// \brief The end offset of this partition.
277 ///
278 /// All of the contained slices end at or before this offset.
279 uint64_t endOffset() const { return EndOffset; }
280
281 /// \brief The size of the partition.
282 ///
283 /// Note that this can never be zero.
284 uint64_t size() const {
285 assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
286 return EndOffset - BeginOffset;
287 }
288
289 /// \brief Test whether this partition contains no slices, and merely spans
290 /// a region occupied by split slices.
291 bool empty() const { return SI == SJ; }
292
293 /// \name Iterate contained slices.
294 /// All of these slices are fully contained in the partition. They may be
295 /// splittable or unsplittable.
296 /// @{
297 iterator begin() const { return SI; }
298 iterator end() const { return SJ; }
299 /// @}
300
301 /// \brief Get the sequence of split slices.
302 ArrayRef<Slice *> splitSlices() const { return SplitSlices; }
303 };
304
305 /// \brief An iterator over partitions of the alloca's slices.
306 ///
307 /// This iterator implements the core algorithm for partitioning the alloca's
308 /// slices. It is a forward iterator as we don't support backtracking for
309 /// efficiency reasons, and re-use a single storage area to maintain the
310 /// current set of split slices.
311 ///
312 /// It is templated on the slice iterator type to use so that it can operate
313 /// with either const or non-const slice iterators.
314 class partition_iterator
315 : public iterator_facade_base<partition_iterator,
316 std::forward_iterator_tag, Partition> {
317 friend class AllocaSlices;
318
319 /// \brief Most of the state for walking the partitions is held in a class
320 /// with a nice interface for examining them.
321 Partition P;
322
323 /// \brief We need to keep the end of the slices to know when to stop.
324 AllocaSlices::iterator SE;
325
326 /// \brief We also need to keep track of the maximum split end offset seen.
327 /// FIXME: Do we really?
328 uint64_t MaxSplitSliceEndOffset;
329
330 /// \brief Sets the partition to be empty at given iterator, and sets the
331 /// end iterator.
332 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
333 : P(SI), SE(SE), MaxSplitSliceEndOffset(0) {
334 // If not already at the end, advance our state to form the initial
335 // partition.
336 if (SI != SE)
337 advance();
338 }
339
340 /// \brief Advance the iterator to the next partition.
341 ///
342 /// Requires that the iterator not be at the end of the slices.
343 void advance() {
344 assert((P.SI != SE || !P.SplitSlices.empty()) &&
345 "Cannot advance past the end of the slices!");
346
347 // Clear out any split uses which have ended.
348 if (!P.SplitSlices.empty()) {
349 if (P.EndOffset >= MaxSplitSliceEndOffset) {
350 // If we've finished all splits, this is easy.
351 P.SplitSlices.clear();
352 MaxSplitSliceEndOffset = 0;
353 } else {
354 // Remove the uses which have ended in the prior partition. This
355 // cannot change the max split slice end because we just checked that
356 // the prior partition ended prior to that max.
357 P.SplitSlices.erase(
358 std::remove_if(
359 P.SplitSlices.begin(), P.SplitSlices.end(),
360 [&](Slice *S) { return S->endOffset() <= P.EndOffset; }),
361 P.SplitSlices.end());
362 assert(std::any_of(P.SplitSlices.begin(), P.SplitSlices.end(),
363 [&](Slice *S) {
364 return S->endOffset() == MaxSplitSliceEndOffset;
365 }) &&
366 "Could not find the current max split slice offset!");
367 assert(std::all_of(P.SplitSlices.begin(), P.SplitSlices.end(),
368 [&](Slice *S) {
369 return S->endOffset() <= MaxSplitSliceEndOffset;
370 }) &&
371 "Max split slice end offset is not actually the max!");
372 }
373 }
374
375 // If P.SI is already at the end, then we've cleared the split tail and
376 // now have an end iterator.
377 if (P.SI == SE) {
378 assert(P.SplitSlices.empty() && "Failed to clear the split slices!");
379 return;
380 }
381
382 // If we had a non-empty partition previously, set up the state for
383 // subsequent partitions.
384 if (P.SI != P.SJ) {
385 // Accumulate all the splittable slices which started in the old
386 // partition into the split list.
387 for (Slice &S : P)
388 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
389 P.SplitSlices.push_back(&S);
390 MaxSplitSliceEndOffset =
391 std::max(S.endOffset(), MaxSplitSliceEndOffset);
392 }
393
394 // Start from the end of the previous partition.
395 P.SI = P.SJ;
396
397 // If P.SI is now at the end, we at most have a tail of split slices.
398 if (P.SI == SE) {
399 P.BeginOffset = P.EndOffset;
400 P.EndOffset = MaxSplitSliceEndOffset;
401 return;
402 }
403
404 // If the we have split slices and the next slice is after a gap and is
405 // not splittable immediately form an empty partition for the split
406 // slices up until the next slice begins.
407 if (!P.SplitSlices.empty() && P.SI->beginOffset() != P.EndOffset &&
408 !P.SI->isSplittable()) {
409 P.BeginOffset = P.EndOffset;
410 P.EndOffset = P.SI->beginOffset();
411 return;
412 }
413 }
414
415 // OK, we need to consume new slices. Set the end offset based on the
416 // current slice, and step SJ past it. The beginning offset of the
417 // parttion is the beginning offset of the next slice unless we have
418 // pre-existing split slices that are continuing, in which case we begin
419 // at the prior end offset.
420 P.BeginOffset = P.SplitSlices.empty() ? P.SI->beginOffset() : P.EndOffset;
421 P.EndOffset = P.SI->endOffset();
422 ++P.SJ;
423
424 // There are two strategies to form a partition based on whether the
425 // partition starts with an unsplittable slice or a splittable slice.
426 if (!P.SI->isSplittable()) {
427 // When we're forming an unsplittable region, it must always start at
428 // the first slice and will extend through its end.
429 assert(P.BeginOffset == P.SI->beginOffset());
430
431 // Form a partition including all of the overlapping slices with this
432 // unsplittable slice.
433 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
434 if (!P.SJ->isSplittable())
435 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
436 ++P.SJ;
437 }
438
439 // We have a partition across a set of overlapping unsplittable
440 // partitions.
441 return;
442 }
443
444 // If we're starting with a splittable slice, then we need to form
445 // a synthetic partition spanning it and any other overlapping splittable
446 // splices.
447 assert(P.SI->isSplittable() && "Forming a splittable partition!");
448
449 // Collect all of the overlapping splittable slices.
450 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
451 P.SJ->isSplittable()) {
452 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
453 ++P.SJ;
454 }
455
456 // Back upiP.EndOffset if we ended the span early when encountering an
457 // unsplittable slice. This synthesizes the early end offset of
458 // a partition spanning only splittable slices.
459 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
460 assert(!P.SJ->isSplittable());
461 P.EndOffset = P.SJ->beginOffset();
462 }
463 }
464
465 public:
466 bool operator==(const partition_iterator &RHS) const {
467 assert(SE == RHS.SE &&
468 "End iterators don't match between compared partition iterators!");
469
470 // The observed positions of partitions is marked by the P.SI iterator and
471 // the emptyness of the split slices. The latter is only relevant when
472 // P.SI == SE, as the end iterator will additionally have an empty split
473 // slices list, but the prior may have the same P.SI and a tail of split
474 // slices.
475 if (P.SI == RHS.P.SI &&
476 P.SplitSlices.empty() == RHS.P.SplitSlices.empty()) {
477 assert(P.SJ == RHS.P.SJ &&
478 "Same set of slices formed two different sized partitions!");
479 assert(P.SplitSlices.size() == RHS.P.SplitSlices.size() &&
480 "Same slice position with differently sized non-empty split "
481 "slices sets!");
482 return true;
483 }
484 return false;
485 }
486
487 partition_iterator &operator++() {
488 advance();
489 return *this;
490 }
491
492 Partition &operator*() { return P; }
493 };
494
495 /// \brief A forward range over the partitions of the alloca's slices.
496 ///
497 /// This accesses an iterator range over the partitions of the alloca's
498 /// slices. It computes these partitions on the fly based on the overlapping
499 /// offsets of the slices and the ability to split them. It will visit "empty"
500 /// partitions to cover regions of the alloca only accessed via split
501 /// slices.
502 iterator_range<partition_iterator> partitions() {
503 return make_range(partition_iterator(begin(), end()),
504 partition_iterator(end(), end()));
505 }
506
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000507 /// \brief Access the dead users for this alloca.
508 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000509
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000510 /// \brief Access the dead operands referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000511 ///
512 /// These are operands which have cannot actually be used to refer to the
513 /// alloca as they are outside its range and the user doesn't correct for
514 /// that. These mostly consist of PHI node inputs and the like which we just
515 /// need to replace with undef.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000516 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000517
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000518#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000519 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000520 void printSlice(raw_ostream &OS, const_iterator I,
521 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000522 void printUse(raw_ostream &OS, const_iterator I,
523 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000524 void print(raw_ostream &OS) const;
Alp Tokerf929e092014-01-04 22:47:48 +0000525 void dump(const_iterator I) const;
526 void dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000527#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000528
529private:
530 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000531 class SliceBuilder;
532 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000533
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000534#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000535 /// \brief Handle to alloca instruction to simplify method interfaces.
536 AllocaInst &AI;
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000537#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000538
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000539 /// \brief The instruction responsible for this alloca not having a known set
540 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000541 ///
542 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000543 /// store a pointer to that here and abort trying to form slices of the
544 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000545 Instruction *PointerEscapingInstr;
546
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000547 /// \brief The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000548 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000549 /// We store a vector of the slices formed by uses of the alloca here. This
550 /// vector is sorted by increasing begin offset, and then the unsplittable
551 /// slices before the splittable ones. See the Slice inner class for more
552 /// details.
553 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000554
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000555 /// \brief Instructions which will become dead if we rewrite the alloca.
556 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000557 /// Note that these are not separated by slice. This is because we expect an
558 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
559 /// all these instructions can simply be removed and replaced with undef as
560 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000561 SmallVector<Instruction *, 8> DeadUsers;
562
563 /// \brief Operands which will become dead if we rewrite the alloca.
564 ///
565 /// These are operands that in their particular use can be replaced with
566 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
567 /// to PHI nodes and the like. They aren't entirely dead (there might be
568 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
569 /// want to swap this particular input for undef to simplify the use lists of
570 /// the alloca.
571 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000572};
573}
574
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000575static Value *foldSelectInst(SelectInst &SI) {
576 // If the condition being selected on is a constant or the same value is
577 // being selected between, fold the select. Yes this does (rarely) happen
578 // early on.
579 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
Chandler Carruth113dc642014-12-20 02:39:18 +0000580 return SI.getOperand(1 + CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000581 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000582 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000583
Craig Topperf40110f2014-04-25 05:29:35 +0000584 return nullptr;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000585}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000586
Jingyue Wuec33fa92014-08-22 22:45:57 +0000587/// \brief A helper that folds a PHI node or a select.
588static Value *foldPHINodeOrSelectInst(Instruction &I) {
589 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
590 // If PN merges together the same value, return that value.
591 return PN->hasConstantValue();
592 }
593 return foldSelectInst(cast<SelectInst>(I));
594}
595
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000596/// \brief Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000597///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000598/// This class builds a set of alloca slices by recursively visiting the uses
599/// of an alloca and making a slice for each load and store at each offset.
600class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
601 friend class PtrUseVisitor<SliceBuilder>;
602 friend class InstVisitor<SliceBuilder>;
603 typedef PtrUseVisitor<SliceBuilder> Base;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000604
605 const uint64_t AllocSize;
Chandler Carruth83934062014-10-16 21:11:55 +0000606 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000607
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000608 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000609 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
610
611 /// \brief Set to de-duplicate dead instructions found in the use walk.
612 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000613
614public:
Chandler Carruth83934062014-10-16 21:11:55 +0000615 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000616 : PtrUseVisitor<SliceBuilder>(DL),
Chandler Carruth83934062014-10-16 21:11:55 +0000617 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000618
619private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000620 void markAsDead(Instruction &I) {
David Blaikie70573dc2014-11-19 07:49:26 +0000621 if (VisitedDeadInsts.insert(&I).second)
Chandler Carruth83934062014-10-16 21:11:55 +0000622 AS.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000623 }
624
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000625 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000626 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000627 // Completely skip uses which have a zero size or start either before or
628 // past the end of the allocation.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000629 if (Size == 0 || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000630 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000631 << " which has zero size or starts outside of the "
632 << AllocSize << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000633 << " alloca: " << AS.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000634 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000635 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000636 }
637
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000638 uint64_t BeginOffset = Offset.getZExtValue();
639 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000640
641 // Clamp the end offset to the end of the allocation. Note that this is
642 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000643 // This may appear superficially to be something we could ignore entirely,
644 // but that is not so! There may be widened loads or PHI-node uses where
645 // some instructions are dead but not others. We can't completely ignore
646 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000647 assert(AllocSize >= BeginOffset); // Established above.
648 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000649 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
650 << " to remain within the " << AllocSize << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000651 << " alloca: " << AS.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000652 << " use: " << I << "\n");
653 EndOffset = AllocSize;
654 }
655
Chandler Carruth83934062014-10-16 21:11:55 +0000656 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000657 }
658
659 void visitBitCastInst(BitCastInst &BC) {
660 if (BC.use_empty())
661 return markAsDead(BC);
662
663 return Base::visitBitCastInst(BC);
664 }
665
666 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
667 if (GEPI.use_empty())
668 return markAsDead(GEPI);
669
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000670 if (SROAStrictInbounds && GEPI.isInBounds()) {
671 // FIXME: This is a manually un-factored variant of the basic code inside
672 // of GEPs with checking of the inbounds invariant specified in the
673 // langref in a very strict sense. If we ever want to enable
674 // SROAStrictInbounds, this code should be factored cleanly into
675 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
676 // by writing out the code here where we have tho underlying allocation
677 // size readily available.
678 APInt GEPOffset = Offset;
679 for (gep_type_iterator GTI = gep_type_begin(GEPI),
680 GTE = gep_type_end(GEPI);
681 GTI != GTE; ++GTI) {
682 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
683 if (!OpC)
684 break;
685
686 // Handle a struct index, which adds its field offset to the pointer.
687 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
688 unsigned ElementIdx = OpC->getZExtValue();
689 const StructLayout *SL = DL.getStructLayout(STy);
690 GEPOffset +=
691 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
692 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +0000693 // For array or vector indices, scale the index by the size of the
694 // type.
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000695 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
696 GEPOffset += Index * APInt(Offset.getBitWidth(),
697 DL.getTypeAllocSize(GTI.getIndexedType()));
698 }
699
700 // If this index has computed an intermediate pointer which is not
701 // inbounds, then the result of the GEP is a poison value and we can
702 // delete it and all uses.
703 if (GEPOffset.ugt(AllocSize))
704 return markAsDead(GEPI);
705 }
706 }
707
Chandler Carruthf0546402013-07-18 07:15:00 +0000708 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000709 }
710
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000711 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000712 uint64_t Size, bool IsVolatile) {
Chandler Carruth58d05562012-10-25 04:37:07 +0000713 // We allow splitting of loads and stores where the type is an integer type
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000714 // and cover the entire alloca. This prevents us from splitting over
715 // eagerly.
716 // FIXME: In the great blue eventually, we should eagerly split all integer
717 // loads and stores, and then have a separate step that merges adjacent
718 // alloca partitions into a single partition suitable for integer widening.
719 // Or we should skip the merge step and rely on GVN and other passes to
720 // merge adjacent loads and stores that survive mem2reg.
721 bool IsSplittable =
722 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
Chandler Carruth58d05562012-10-25 04:37:07 +0000723
724 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000725 }
726
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000727 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000728 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
729 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000730
731 if (!IsOffsetKnown)
732 return PI.setAborted(&LI);
733
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000734 uint64_t Size = DL.getTypeStoreSize(LI.getType());
735 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000736 }
737
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000738 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000739 Value *ValOp = SI.getValueOperand();
740 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000741 return PI.setEscapedAndAborted(&SI);
742 if (!IsOffsetKnown)
743 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000744
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000745 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
746
747 // If this memory access can be shown to *statically* extend outside the
748 // bounds of of the allocation, it's behavior is undefined, so simply
749 // ignore it. Note that this is more strict than the generic clamping
750 // behavior of insertUse. We also try to handle cases which might run the
751 // risk of overflow.
752 // FIXME: We should instead consider the pointer to have escaped if this
753 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000754 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000755 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
756 << " which extends past the end of the " << AllocSize
757 << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000758 << " alloca: " << AS.AI << "\n"
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000759 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000760 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000761 }
762
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000763 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
764 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000765 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000766 }
767
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000768 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000769 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000770 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000771 if ((Length && Length->getValue() == 0) ||
Chandler Carruth6aedc102014-02-26 03:14:14 +0000772 (IsOffsetKnown && Offset.uge(AllocSize)))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000773 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000774 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000775
776 if (!IsOffsetKnown)
777 return PI.setAborted(&II);
778
Chandler Carruth113dc642014-12-20 02:39:18 +0000779 insertUse(II, Offset, Length ? Length->getLimitedValue()
780 : AllocSize - Offset.getLimitedValue(),
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000781 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000782 }
783
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000784 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000785 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000786 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000787 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000788 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000789
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000790 // Because we can visit these intrinsics twice, also check to see if the
791 // first time marked this instruction as dead. If so, skip it.
792 if (VisitedDeadInsts.count(&II))
793 return;
794
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000795 if (!IsOffsetKnown)
796 return PI.setAborted(&II);
797
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000798 // This side of the transfer is completely out-of-bounds, and so we can
799 // nuke the entire transfer. However, we also need to nuke the other side
800 // if already added to our partitions.
801 // FIXME: Yet another place we really should bypass this when
802 // instrumenting for ASan.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000803 if (Offset.uge(AllocSize)) {
Chandler Carruth113dc642014-12-20 02:39:18 +0000804 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
805 MemTransferSliceMap.find(&II);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000806 if (MTPI != MemTransferSliceMap.end())
Chandler Carruth83934062014-10-16 21:11:55 +0000807 AS.Slices[MTPI->second].kill();
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000808 return markAsDead(II);
809 }
810
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000811 uint64_t RawOffset = Offset.getLimitedValue();
Chandler Carruth113dc642014-12-20 02:39:18 +0000812 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000813
Chandler Carruthf0546402013-07-18 07:15:00 +0000814 // Check for the special case where the same exact value is used for both
815 // source and dest.
816 if (*U == II.getRawDest() && *U == II.getRawSource()) {
817 // For non-volatile transfers this is a no-op.
818 if (!II.isVolatile())
819 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000820
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000821 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000822 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000823
Chandler Carruthf0546402013-07-18 07:15:00 +0000824 // If we have seen both source and destination for a mem transfer, then
825 // they both point to the same alloca.
826 bool Inserted;
827 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000828 std::tie(MTPI, Inserted) =
Chandler Carruth83934062014-10-16 21:11:55 +0000829 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000830 unsigned PrevIdx = MTPI->second;
831 if (!Inserted) {
Chandler Carruth83934062014-10-16 21:11:55 +0000832 Slice &PrevP = AS.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000833
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000834 // Check if the begin offsets match and this is a non-volatile transfer.
835 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000836 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
837 PrevP.kill();
838 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000839 }
840
841 // Otherwise we have an offset transfer within the same alloca. We can't
842 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000843 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000844 }
845
Chandler Carruthe3899f22013-07-15 17:36:21 +0000846 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000847 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000848
Chandler Carruthf0546402013-07-18 07:15:00 +0000849 // Check that we ended up with a valid index in the map.
Chandler Carruth83934062014-10-16 21:11:55 +0000850 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000851 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000852 }
853
854 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000855 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000856 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000857 void visitIntrinsicInst(IntrinsicInst &II) {
858 if (!IsOffsetKnown)
859 return PI.setAborted(&II);
860
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000861 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
862 II.getIntrinsicID() == Intrinsic::lifetime_end) {
863 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000864 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
865 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000866 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000867 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000868 }
869
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000870 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000871 }
872
873 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
874 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000875 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000876 // are considered unsplittable and the size is the maximum loaded or stored
877 // size.
878 SmallPtrSet<Instruction *, 4> Visited;
879 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
880 Visited.insert(Root);
881 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruth8b907e82012-09-25 10:03:40 +0000882 // If there are no loads or stores, the access is dead. We mark that as
883 // a size zero access.
884 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000885 do {
886 Instruction *I, *UsedI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000887 std::tie(UsedI, I) = Uses.pop_back_val();
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000888
889 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000890 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000891 continue;
892 }
893 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
894 Value *Op = SI->getOperand(0);
895 if (Op == UsedI)
896 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000897 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000898 continue;
899 }
900
901 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
902 if (!GEP->hasAllZeroIndices())
903 return GEP;
904 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
905 !isa<SelectInst>(I)) {
906 return I;
907 }
908
Chandler Carruthcdf47882014-03-09 03:16:01 +0000909 for (User *U : I->users())
David Blaikie70573dc2014-11-19 07:49:26 +0000910 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000911 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000912 } while (!Uses.empty());
913
Craig Topperf40110f2014-04-25 05:29:35 +0000914 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000915 }
916
Jingyue Wuec33fa92014-08-22 22:45:57 +0000917 void visitPHINodeOrSelectInst(Instruction &I) {
918 assert(isa<PHINode>(I) || isa<SelectInst>(I));
919 if (I.use_empty())
920 return markAsDead(I);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000921
Jingyue Wuec33fa92014-08-22 22:45:57 +0000922 // TODO: We could use SimplifyInstruction here to fold PHINodes and
923 // SelectInsts. However, doing so requires to change the current
924 // dead-operand-tracking mechanism. For instance, suppose neither loading
925 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
926 // trap either. However, if we simply replace %U with undef using the
927 // current dead-operand-tracking mechanism, "load (select undef, undef,
928 // %other)" may trap because the select may return the first operand
929 // "undef".
930 if (Value *Result = foldPHINodeOrSelectInst(I)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000931 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000932 // If the result of the constant fold will be the pointer, recurse
Jingyue Wuec33fa92014-08-22 22:45:57 +0000933 // through the PHI/select as if we had RAUW'ed it.
934 enqueueUsers(I);
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000935 else
Jingyue Wuec33fa92014-08-22 22:45:57 +0000936 // Otherwise the operand to the PHI/select is dead, and we can replace
937 // it with undef.
Chandler Carruth83934062014-10-16 21:11:55 +0000938 AS.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000939
940 return;
941 }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000942
Chandler Carruthf0546402013-07-18 07:15:00 +0000943 if (!IsOffsetKnown)
Jingyue Wuec33fa92014-08-22 22:45:57 +0000944 return PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000945
Chandler Carruthf0546402013-07-18 07:15:00 +0000946 // See if we already have computed info on this node.
Jingyue Wuec33fa92014-08-22 22:45:57 +0000947 uint64_t &Size = PHIOrSelectSizes[&I];
948 if (!Size) {
949 // This is a new PHI/Select, check for an unsafe use of it.
950 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
Chandler Carruthf0546402013-07-18 07:15:00 +0000951 return PI.setAborted(UnsafeI);
952 }
953
954 // For PHI and select operands outside the alloca, we can't nuke the entire
955 // phi or select -- the other side might still be relevant, so we special
956 // case them here and use a separate structure to track the operands
957 // themselves which should be replaced with undef.
958 // FIXME: This should instead be escaped in the event we're instrumenting
959 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000960 if (Offset.uge(AllocSize)) {
Chandler Carruth83934062014-10-16 21:11:55 +0000961 AS.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +0000962 return;
963 }
964
Jingyue Wuec33fa92014-08-22 22:45:57 +0000965 insertUse(I, Offset, Size);
966 }
967
Chandler Carruth113dc642014-12-20 02:39:18 +0000968 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000969
Chandler Carruth113dc642014-12-20 02:39:18 +0000970 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000971
Chandler Carruthf0546402013-07-18 07:15:00 +0000972 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth113dc642014-12-20 02:39:18 +0000973 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000974};
975
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000976AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000977 :
978#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
979 AI(AI),
980#endif
Craig Topperf40110f2014-04-25 05:29:35 +0000981 PointerEscapingInstr(nullptr) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000982 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000983 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000984 if (PtrI.isEscaped() || PtrI.isAborted()) {
985 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000986 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000987 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
988 : PtrI.getAbortingInst();
989 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000990 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000991 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000992
Benjamin Kramer08e50702013-07-20 08:38:34 +0000993 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
Chandler Carruth68ea4152014-12-18 05:19:47 +0000994 [](const Slice &S) {
995 return S.isDead();
996 }),
Benjamin Kramer08e50702013-07-20 08:38:34 +0000997 Slices.end());
998
Chandler Carruth83cee772014-02-25 03:59:29 +0000999#if __cplusplus >= 201103L && !defined(NDEBUG)
1000 if (SROARandomShuffleSlices) {
1001 std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
1002 std::shuffle(Slices.begin(), Slices.end(), MT);
1003 }
1004#endif
1005
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001006 // Sort the uses. This arranges for the offsets to be in ascending order,
1007 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001008 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001009}
1010
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001011#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1012
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001013void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1014 StringRef Indent) const {
1015 printSlice(OS, I, Indent);
Chandler Carruthf0546402013-07-18 07:15:00 +00001016 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001017}
1018
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001019void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1020 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001021 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001022 << " slice #" << (I - begin())
Chandler Carruthf0546402013-07-18 07:15:00 +00001023 << (I->isSplittable() ? " (splittable)" : "") << "\n";
1024}
1025
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001026void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1027 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001028 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001029}
1030
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001031void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001032 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001033 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001034 << " A pointer to this alloca escaped by:\n"
1035 << " " << *PointerEscapingInstr << "\n";
1036 return;
1037 }
1038
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001039 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001040 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001041 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001042}
1043
Alp Tokerf929e092014-01-04 22:47:48 +00001044LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1045 print(dbgs(), I);
1046}
1047LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001048
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001049#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1050
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001051namespace {
Chandler Carruth70b44c52012-09-15 11:43:14 +00001052/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1053///
1054/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1055/// the loads and stores of an alloca instruction, as well as updating its
1056/// debug information. This is used when a domtree is unavailable and thus
1057/// mem2reg in its full form can't be used to handle promotion of allocas to
1058/// scalar values.
1059class AllocaPromoter : public LoadAndStorePromoter {
1060 AllocaInst &AI;
1061 DIBuilder &DIB;
1062
1063 SmallVector<DbgDeclareInst *, 4> DDIs;
1064 SmallVector<DbgValueInst *, 4> DVIs;
1065
1066public:
Chandler Carruth45b136f2013-08-11 01:03:18 +00001067 AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
Chandler Carruth70b44c52012-09-15 11:43:14 +00001068 AllocaInst &AI, DIBuilder &DIB)
Chandler Carruth45b136f2013-08-11 01:03:18 +00001069 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
Chandler Carruth70b44c52012-09-15 11:43:14 +00001070
Chandler Carruth113dc642014-12-20 02:39:18 +00001071 void run(const SmallVectorImpl<Instruction *> &Insts) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00001072 // Retain the debug information attached to the alloca for use when
1073 // rewriting loads and stores.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001074 if (auto *L = LocalAsMetadata::getIfExists(&AI)) {
1075 if (auto *DebugNode = MetadataAsValue::getIfExists(AI.getContext(), L)) {
1076 for (User *U : DebugNode->users())
1077 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
1078 DDIs.push_back(DDI);
1079 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
1080 DVIs.push_back(DVI);
1081 }
Chandler Carruth70b44c52012-09-15 11:43:14 +00001082 }
1083
1084 LoadAndStorePromoter::run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00001085
1086 // While we have the debug information, clear it off of the alloca. The
1087 // caller takes care of deleting the alloca.
Chandler Carruth70b44c52012-09-15 11:43:14 +00001088 while (!DDIs.empty())
1089 DDIs.pop_back_val()->eraseFromParent();
1090 while (!DVIs.empty())
1091 DVIs.pop_back_val()->eraseFromParent();
1092 }
1093
Chandler Carruth113dc642014-12-20 02:39:18 +00001094 bool
1095 isInstInList(Instruction *I,
1096 const SmallVectorImpl<Instruction *> &Insts) const override {
Chandler Carruthc17283b2013-08-11 01:56:15 +00001097 Value *Ptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +00001098 if (LoadInst *LI = dyn_cast<LoadInst>(I))
Chandler Carruthc17283b2013-08-11 01:56:15 +00001099 Ptr = LI->getOperand(0);
1100 else
1101 Ptr = cast<StoreInst>(I)->getPointerOperand();
1102
1103 // Only used to detect cycles, which will be rare and quickly found as
1104 // we're walking up a chain of defs rather than down through uses.
1105 SmallPtrSet<Value *, 4> Visited;
1106
1107 do {
1108 if (Ptr == &AI)
1109 return true;
1110
1111 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
1112 Ptr = BCI->getOperand(0);
1113 else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
1114 Ptr = GEPI->getPointerOperand();
1115 else
1116 return false;
1117
David Blaikie70573dc2014-11-19 07:49:26 +00001118 } while (Visited.insert(Ptr).second);
Chandler Carruthc17283b2013-08-11 01:56:15 +00001119
1120 return false;
Chandler Carruth70b44c52012-09-15 11:43:14 +00001121 }
1122
Craig Topper3e4c6972014-03-05 09:10:37 +00001123 void updateDebugInfo(Instruction *Inst) const override {
Chandler Carruth61747042014-10-16 21:05:14 +00001124 for (DbgDeclareInst *DDI : DDIs)
Chandler Carruth70b44c52012-09-15 11:43:14 +00001125 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1126 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1127 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1128 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
Chandler Carruth61747042014-10-16 21:05:14 +00001129 for (DbgValueInst *DVI : DVIs) {
Craig Topperf40110f2014-04-25 05:29:35 +00001130 Value *Arg = nullptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +00001131 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1132 // If an argument is zero extended then use argument directly. The ZExt
1133 // may be zapped by an optimization pass in future.
1134 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1135 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00001136 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Chandler Carruth70b44c52012-09-15 11:43:14 +00001137 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1138 if (!Arg)
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00001139 Arg = SI->getValueOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +00001140 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00001141 Arg = LI->getPointerOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +00001142 } else {
1143 continue;
1144 }
1145 Instruction *DbgVal =
Adrian Prantl87b7eb92014-10-01 18:55:02 +00001146 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1147 DIExpression(DVI->getExpression()), Inst);
Chandler Carruth70b44c52012-09-15 11:43:14 +00001148 DbgVal->setDebugLoc(DVI->getDebugLoc());
1149 }
1150 }
1151};
1152} // end anon namespace
1153
Chandler Carruth70b44c52012-09-15 11:43:14 +00001154namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001155/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1156///
1157/// This pass takes allocations which can be completely analyzed (that is, they
1158/// don't escape) and tries to turn them into scalar SSA values. There are
1159/// a few steps to this process.
1160///
1161/// 1) It takes allocations of aggregates and analyzes the ways in which they
1162/// are used to try to split them into smaller allocations, ideally of
1163/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001164/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001165/// 2) It will transform accesses into forms which are suitable for SSA value
1166/// promotion. This can be replacing a memset with a scalar store of an
1167/// integer value, or it can involve speculating operations on a PHI or
1168/// select to be a PHI or select of the results.
1169/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1170/// onto insert and extract operations on a vector value, and convert them to
1171/// this form. By doing so, it will enable promotion of vector aggregates to
1172/// SSA vector values.
1173class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +00001174 const bool RequiresDomTree;
1175
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001176 LLVMContext *C;
Chandler Carruth90a735d2013-07-19 07:21:28 +00001177 const DataLayout *DL;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001178 DominatorTree *DT;
Hal Finkel60db0582014-09-07 18:57:58 +00001179 AssumptionTracker *AT;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001180
1181 /// \brief Worklist of alloca instructions to simplify.
1182 ///
1183 /// Each alloca in the function is added to this. Each new alloca formed gets
1184 /// added to it as well to recursively simplify unless that alloca can be
1185 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1186 /// the one being actively rewritten, we add it back onto the list if not
1187 /// already present to ensure it is re-visited.
Chandler Carruth113dc642014-12-20 02:39:18 +00001188 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> Worklist;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001189
1190 /// \brief A collection of instructions to delete.
1191 /// We try to batch deletions to simplify code and make things a bit more
1192 /// efficient.
Chandler Carruth113dc642014-12-20 02:39:18 +00001193 SetVector<Instruction *, SmallVector<Instruction *, 8>> DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001194
Chandler Carruthac8317f2012-10-04 12:33:50 +00001195 /// \brief Post-promotion worklist.
1196 ///
1197 /// Sometimes we discover an alloca which has a high probability of becoming
1198 /// viable for SROA after a round of promotion takes place. In those cases,
1199 /// the alloca is enqueued here for re-processing.
1200 ///
1201 /// Note that we have to be very careful to clear allocas out of this list in
1202 /// the event they are deleted.
Chandler Carruth113dc642014-12-20 02:39:18 +00001203 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> PostPromotionWorklist;
Chandler Carruthac8317f2012-10-04 12:33:50 +00001204
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001205 /// \brief A collection of alloca instructions we can directly promote.
1206 std::vector<AllocaInst *> PromotableAllocas;
1207
Chandler Carruthf0546402013-07-18 07:15:00 +00001208 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
1209 ///
1210 /// All of these PHIs have been checked for the safety of speculation and by
1211 /// being speculated will allow promoting allocas currently in the promotable
1212 /// queue.
Chandler Carruth113dc642014-12-20 02:39:18 +00001213 SetVector<PHINode *, SmallVector<PHINode *, 2>> SpeculatablePHIs;
Chandler Carruthf0546402013-07-18 07:15:00 +00001214
1215 /// \brief A worklist of select instructions to speculate prior to promoting
1216 /// allocas.
1217 ///
1218 /// All of these select instructions have been checked for the safety of
1219 /// speculation and by being speculated will allow promoting allocas
1220 /// currently in the promotable queue.
Chandler Carruth113dc642014-12-20 02:39:18 +00001221 SetVector<SelectInst *, SmallVector<SelectInst *, 2>> SpeculatableSelects;
Chandler Carruthf0546402013-07-18 07:15:00 +00001222
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001223public:
Chandler Carruth70b44c52012-09-15 11:43:14 +00001224 SROA(bool RequiresDomTree = true)
Chandler Carruth113dc642014-12-20 02:39:18 +00001225 : FunctionPass(ID), RequiresDomTree(RequiresDomTree), C(nullptr),
1226 DL(nullptr), DT(nullptr) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001227 initializeSROAPass(*PassRegistry::getPassRegistry());
1228 }
Craig Topper3e4c6972014-03-05 09:10:37 +00001229 bool runOnFunction(Function &F) override;
1230 void getAnalysisUsage(AnalysisUsage &AU) const override;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001231
Craig Topper3e4c6972014-03-05 09:10:37 +00001232 const char *getPassName() const override { return "SROA"; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001233 static char ID;
1234
1235private:
Chandler Carruth82a57542012-10-01 10:54:05 +00001236 friend class PHIOrSelectSpeculator;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001237 friend class AllocaSliceRewriter;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001238
Chandler Carruth83934062014-10-16 21:11:55 +00001239 bool rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00001240 AllocaSlices::Partition &P);
Chandler Carruth83934062014-10-16 21:11:55 +00001241 bool splitAlloca(AllocaInst &AI, AllocaSlices &AS);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001242 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00001243 void clobberUse(Use &U);
Craig Topper71b7b682014-08-21 05:55:13 +00001244 void deleteDeadInstructions(SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +00001245 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001246};
1247}
1248
1249char SROA::ID = 0;
1250
Chandler Carruth70b44c52012-09-15 11:43:14 +00001251FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1252 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001253}
1254
Chandler Carruth113dc642014-12-20 02:39:18 +00001255INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
1256 false)
Hal Finkel60db0582014-09-07 18:57:58 +00001257INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
Chandler Carruth73523022014-01-13 13:07:17 +00001258INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth113dc642014-12-20 02:39:18 +00001259INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
1260 false)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001261
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001262/// Walk the range of a partitioning looking for a common type to cover this
1263/// sequence of slices.
1264static Type *findCommonType(AllocaSlices::const_iterator B,
1265 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001266 uint64_t EndOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001267 Type *Ty = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001268 bool TyIsCommon = true;
Craig Topperf40110f2014-04-25 05:29:35 +00001269 IntegerType *ITy = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001270
1271 // Note that we need to look at *every* alloca slice's Use to ensure we
1272 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001273 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001274 Use *U = I->getUse();
1275 if (isa<IntrinsicInst>(*U->getUser()))
1276 continue;
1277 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1278 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001279
Craig Topperf40110f2014-04-25 05:29:35 +00001280 Type *UserTy = nullptr;
Chandler Carrutha1262002013-11-19 09:03:18 +00001281 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001282 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001283 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001284 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001285 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001286
Chandler Carruth4de31542014-01-21 23:16:05 +00001287 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001288 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001289 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001290 // entity causing the split. Also skip if the type is not a byte width
1291 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001292 if (UserITy->getBitWidth() % 8 != 0 ||
1293 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001294 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001295
Chandler Carruth4de31542014-01-21 23:16:05 +00001296 // Track the largest bitwidth integer type used in this way in case there
1297 // is no common type.
1298 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1299 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001300 }
Duncan P. N. Exon Smith73686d32014-06-17 00:19:35 +00001301
1302 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1303 // depend on types skipped above.
1304 if (!UserTy || (Ty && Ty != UserTy))
1305 TyIsCommon = false; // Give up on anything but an iN type.
1306 else
1307 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001308 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001309
1310 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001311}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001312
Chandler Carruthf0546402013-07-18 07:15:00 +00001313/// PHI instructions that use an alloca and are subsequently loaded can be
1314/// rewritten to load both input pointers in the pred blocks and then PHI the
1315/// results, allowing the load of the alloca to be promoted.
1316/// From this:
1317/// %P2 = phi [i32* %Alloca, i32* %Other]
1318/// %V = load i32* %P2
1319/// to:
1320/// %V1 = load i32* %Alloca -> will be mem2reg'd
1321/// ...
1322/// %V2 = load i32* %Other
1323/// ...
1324/// %V = phi [i32 %V1, i32 %V2]
1325///
1326/// We can do this to a select if its only uses are loads and if the operands
1327/// to the select can be loaded unconditionally.
1328///
1329/// FIXME: This should be hoisted into a generic utility, likely in
1330/// Transforms/Util/Local.h
Chandler Carruth113dc642014-12-20 02:39:18 +00001331static bool isSafePHIToSpeculate(PHINode &PN, const DataLayout *DL = nullptr) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001332 // For now, we can only do this promotion if the load is in the same block
1333 // as the PHI, and if there are no stores between the phi and load.
1334 // TODO: Allow recursive phi users.
1335 // TODO: Allow stores.
1336 BasicBlock *BB = PN.getParent();
1337 unsigned MaxAlign = 0;
1338 bool HaveLoad = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001339 for (User *U : PN.users()) {
1340 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001341 if (!LI || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001342 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001343
Chandler Carruthf0546402013-07-18 07:15:00 +00001344 // For now we only allow loads in the same block as the PHI. This is
1345 // a common case that happens when instcombine merges two loads through
1346 // a PHI.
1347 if (LI->getParent() != BB)
1348 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001349
Chandler Carruthf0546402013-07-18 07:15:00 +00001350 // Ensure that there are no instructions between the PHI and the load that
1351 // could store.
1352 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1353 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001354 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001355
Chandler Carruthf0546402013-07-18 07:15:00 +00001356 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1357 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001358 }
1359
Chandler Carruthf0546402013-07-18 07:15:00 +00001360 if (!HaveLoad)
1361 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001362
Chandler Carruthf0546402013-07-18 07:15:00 +00001363 // We can only transform this if it is safe to push the loads into the
1364 // predecessor blocks. The only thing to watch out for is that we can't put
1365 // a possibly trapping load in the predecessor if it is a critical edge.
1366 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1367 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1368 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001369
Chandler Carruthf0546402013-07-18 07:15:00 +00001370 // If the value is produced by the terminator of the predecessor (an
1371 // invoke) or it has side-effects, there is no valid place to put a load
1372 // in the predecessor.
1373 if (TI == InVal || TI->mayHaveSideEffects())
1374 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001375
Chandler Carruthf0546402013-07-18 07:15:00 +00001376 // If the predecessor has a single successor, then the edge isn't
1377 // critical.
1378 if (TI->getNumSuccessors() == 1)
1379 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001380
Chandler Carruthf0546402013-07-18 07:15:00 +00001381 // If this pointer is always safe to load, or if we can prove that there
1382 // is already a load in the block, then we can move the load to the pred
1383 // block.
Hal Finkel2e42c342014-07-10 05:27:53 +00001384 if (InVal->isDereferenceablePointer(DL) ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001385 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001386 continue;
1387
1388 return false;
1389 }
1390
1391 return true;
1392}
1393
1394static void speculatePHINodeLoads(PHINode &PN) {
1395 DEBUG(dbgs() << " original: " << PN << "\n");
1396
1397 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1398 IRBuilderTy PHIBuilder(&PN);
1399 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1400 PN.getName() + ".sroa.speculated");
1401
Hal Finkelcc39b672014-07-24 12:16:19 +00001402 // Get the AA tags and alignment to use from one of the loads. It doesn't
Chandler Carruthf0546402013-07-18 07:15:00 +00001403 // matter which one we get and if any differ.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001404 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
Hal Finkelcc39b672014-07-24 12:16:19 +00001405
1406 AAMDNodes AATags;
1407 SomeLoad->getAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001408 unsigned Align = SomeLoad->getAlignment();
1409
1410 // Rewrite all loads of the PN to use the new PHI.
1411 while (!PN.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001412 LoadInst *LI = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001413 LI->replaceAllUsesWith(NewPN);
1414 LI->eraseFromParent();
1415 }
1416
1417 // Inject loads into all of the pred blocks.
1418 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1419 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1420 TerminatorInst *TI = Pred->getTerminator();
1421 Value *InVal = PN.getIncomingValue(Idx);
1422 IRBuilderTy PredBuilder(TI);
1423
1424 LoadInst *Load = PredBuilder.CreateLoad(
1425 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1426 ++NumLoadsSpeculated;
1427 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001428 if (AATags)
1429 Load->setAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001430 NewPN->addIncoming(Load, Pred);
1431 }
1432
1433 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1434 PN.eraseFromParent();
1435}
1436
1437/// Select instructions that use an alloca and are subsequently loaded can be
1438/// rewritten to load both input pointers and then select between the result,
1439/// allowing the load of the alloca to be promoted.
1440/// From this:
1441/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1442/// %V = load i32* %P2
1443/// to:
1444/// %V1 = load i32* %Alloca -> will be mem2reg'd
1445/// %V2 = load i32* %Other
1446/// %V = select i1 %cond, i32 %V1, i32 %V2
1447///
1448/// We can do this to a select if its only uses are loads and if the operand
1449/// to the select can be loaded unconditionally.
Craig Topperf40110f2014-04-25 05:29:35 +00001450static bool isSafeSelectToSpeculate(SelectInst &SI,
1451 const DataLayout *DL = nullptr) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001452 Value *TValue = SI.getTrueValue();
1453 Value *FValue = SI.getFalseValue();
Hal Finkel2e42c342014-07-10 05:27:53 +00001454 bool TDerefable = TValue->isDereferenceablePointer(DL);
1455 bool FDerefable = FValue->isDereferenceablePointer(DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00001456
Chandler Carruthcdf47882014-03-09 03:16:01 +00001457 for (User *U : SI.users()) {
1458 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001459 if (!LI || !LI->isSimple())
Chandler Carruthf0546402013-07-18 07:15:00 +00001460 return false;
1461
1462 // Both operands to the select need to be dereferencable, either
1463 // absolutely (e.g. allocas) or at this point because we can see other
1464 // accesses to it.
1465 if (!TDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001466 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001467 return false;
1468 if (!FDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001469 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001470 return false;
1471 }
1472
1473 return true;
1474}
1475
1476static void speculateSelectInstLoads(SelectInst &SI) {
1477 DEBUG(dbgs() << " original: " << SI << "\n");
1478
1479 IRBuilderTy IRB(&SI);
1480 Value *TV = SI.getTrueValue();
1481 Value *FV = SI.getFalseValue();
1482 // Replace the loads of the select with a select of two loads.
1483 while (!SI.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001484 LoadInst *LI = cast<LoadInst>(SI.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001485 assert(LI->isSimple() && "We only speculate simple loads");
1486
1487 IRB.SetInsertPoint(LI);
1488 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001489 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001490 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001491 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001492 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001493
Hal Finkelcc39b672014-07-24 12:16:19 +00001494 // Transfer alignment and AA info if present.
Chandler Carruthf0546402013-07-18 07:15:00 +00001495 TL->setAlignment(LI->getAlignment());
1496 FL->setAlignment(LI->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +00001497
1498 AAMDNodes Tags;
1499 LI->getAAMetadata(Tags);
1500 if (Tags) {
1501 TL->setAAMetadata(Tags);
1502 FL->setAAMetadata(Tags);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001503 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001504
1505 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1506 LI->getName() + ".sroa.speculated");
1507
1508 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1509 LI->replaceAllUsesWith(V);
1510 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001511 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001512 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001513}
1514
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001515/// \brief Build a GEP out of a base pointer and indices.
1516///
1517/// This will return the BasePtr if that is valid, or build a new GEP
1518/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001519static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001520 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001521 if (Indices.empty())
1522 return BasePtr;
1523
1524 // A single zero index is a no-op, so check for this and avoid building a GEP
1525 // in that case.
1526 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1527 return BasePtr;
1528
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001529 return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001530}
1531
1532/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1533/// TargetTy without changing the offset of the pointer.
1534///
1535/// This routine assumes we've already established a properly offset GEP with
1536/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1537/// zero-indices down through type layers until we find one the same as
1538/// TargetTy. If we can't find one with the same type, we at least try to use
1539/// one with the same size. If none of that works, we just produce the GEP as
1540/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001541static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001542 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001543 SmallVectorImpl<Value *> &Indices,
1544 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001545 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001546 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001547
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001548 // Pointer size to use for the indices.
1549 unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1550
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001551 // See if we can descend into a struct and locate a field with the correct
1552 // type.
1553 unsigned NumLayers = 0;
1554 Type *ElementTy = Ty;
1555 do {
1556 if (ElementTy->isPointerTy())
1557 break;
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001558
1559 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1560 ElementTy = ArrayTy->getElementType();
1561 Indices.push_back(IRB.getIntN(PtrSize, 0));
1562 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1563 ElementTy = VectorTy->getElementType();
1564 Indices.push_back(IRB.getInt32(0));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001565 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001566 if (STy->element_begin() == STy->element_end())
1567 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001568 ElementTy = *STy->element_begin();
1569 Indices.push_back(IRB.getInt32(0));
1570 } else {
1571 break;
1572 }
1573 ++NumLayers;
1574 } while (ElementTy != TargetTy);
1575 if (ElementTy != TargetTy)
1576 Indices.erase(Indices.end() - NumLayers, Indices.end());
1577
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001578 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001579}
1580
1581/// \brief Recursively compute indices for a natural GEP.
1582///
1583/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1584/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001585static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001586 Value *Ptr, Type *Ty, APInt &Offset,
1587 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001588 SmallVectorImpl<Value *> &Indices,
1589 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001590 if (Offset == 0)
Chandler Carruth113dc642014-12-20 02:39:18 +00001591 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1592 NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001593
1594 // We can't recurse through pointer types.
1595 if (Ty->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001596 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001597
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001598 // We try to analyze GEPs over vectors here, but note that these GEPs are
1599 // extremely poorly defined currently. The long-term goal is to remove GEPing
1600 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001601 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001602 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Craig Topperf40110f2014-04-25 05:29:35 +00001603 if (ElementSizeInBits % 8 != 0) {
1604 // GEPs over non-multiple of 8 size vector elements are invalid.
1605 return nullptr;
1606 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001607 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001608 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001609 if (NumSkippedElements.ugt(VecTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001610 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001611 Offset -= NumSkippedElements * ElementSize;
1612 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001613 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001614 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001615 }
1616
1617 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1618 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001619 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001620 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001621 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001622 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001623
1624 Offset -= NumSkippedElements * ElementSize;
1625 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001626 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001627 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001628 }
1629
1630 StructType *STy = dyn_cast<StructType>(Ty);
1631 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00001632 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001633
Chandler Carruth90a735d2013-07-19 07:21:28 +00001634 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001635 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001636 if (StructOffset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00001637 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001638 unsigned Index = SL->getElementContainingOffset(StructOffset);
1639 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1640 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001641 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Craig Topperf40110f2014-04-25 05:29:35 +00001642 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001643
1644 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001645 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001646 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001647}
1648
1649/// \brief Get a natural GEP from a base pointer to a particular offset and
1650/// resulting in a particular type.
1651///
1652/// The goal is to produce a "natural" looking GEP that works with the existing
1653/// composite types to arrive at the appropriate offset and element type for
1654/// a pointer. TargetTy is the element type the returned GEP should point-to if
1655/// possible. We recurse by decreasing Offset, adding the appropriate index to
1656/// Indices, and setting Ty to the result subtype.
1657///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001658/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001659static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001660 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001661 SmallVectorImpl<Value *> &Indices,
1662 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001663 PointerType *Ty = cast<PointerType>(Ptr->getType());
1664
1665 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1666 // an i8.
Chandler Carruth286d87e2014-02-26 08:25:02 +00001667 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +00001668 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001669
1670 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001671 if (!ElementTy->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +00001672 return nullptr; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001673 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001674 if (ElementSize == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001675 return nullptr; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001676 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001677
1678 Offset -= NumSkippedElements * ElementSize;
1679 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001680 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001681 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001682}
1683
1684/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1685/// resulting pointer has PointerTy.
1686///
1687/// This tries very hard to compute a "natural" GEP which arrives at the offset
1688/// and produces the pointer type desired. Where it cannot, it will try to use
1689/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1690/// fails, it will try to use an existing i8* and GEP to the byte offset and
1691/// bitcast to the type.
1692///
1693/// The strategy for finding the more natural GEPs is to peel off layers of the
1694/// pointer, walking back through bit casts and GEPs, searching for a base
1695/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001696/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001697/// a single GEP as possible, thus making each GEP more independent of the
1698/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001699static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
Chandler Carruth113dc642014-12-20 02:39:18 +00001700 APInt Offset, Type *PointerTy, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001701 // Even though we don't look through PHI nodes, we could be called on an
1702 // instruction in an unreachable block, which may be on a cycle.
1703 SmallPtrSet<Value *, 4> Visited;
1704 Visited.insert(Ptr);
1705 SmallVector<Value *, 4> Indices;
1706
1707 // We may end up computing an offset pointer that has the wrong type. If we
1708 // never are able to compute one directly that has the correct type, we'll
1709 // fall back to it, so keep it around here.
Craig Topperf40110f2014-04-25 05:29:35 +00001710 Value *OffsetPtr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001711
1712 // Remember any i8 pointer we come across to re-use if we need to do a raw
1713 // byte offset.
Craig Topperf40110f2014-04-25 05:29:35 +00001714 Value *Int8Ptr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001715 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1716
1717 Type *TargetTy = PointerTy->getPointerElementType();
1718
1719 do {
1720 // First fold any existing GEPs into the offset.
1721 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1722 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001723 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001724 break;
1725 Offset += GEPOffset;
1726 Ptr = GEP->getPointerOperand();
David Blaikie70573dc2014-11-19 07:49:26 +00001727 if (!Visited.insert(Ptr).second)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001728 break;
1729 }
1730
1731 // See if we can perform a natural GEP here.
1732 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001733 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001734 Indices, NamePrefix)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001735 if (P->getType() == PointerTy) {
1736 // Zap any offset pointer that we ended up computing in previous rounds.
1737 if (OffsetPtr && OffsetPtr->use_empty())
1738 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1739 I->eraseFromParent();
1740 return P;
1741 }
1742 if (!OffsetPtr) {
1743 OffsetPtr = P;
1744 }
1745 }
1746
1747 // Stash this pointer if we've found an i8*.
1748 if (Ptr->getType()->isIntegerTy(8)) {
1749 Int8Ptr = Ptr;
1750 Int8PtrOffset = Offset;
1751 }
1752
1753 // Peel off a layer of the pointer and update the offset appropriately.
1754 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1755 Ptr = cast<Operator>(Ptr)->getOperand(0);
1756 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1757 if (GA->mayBeOverridden())
1758 break;
1759 Ptr = GA->getAliasee();
1760 } else {
1761 break;
1762 }
1763 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +00001764 } while (Visited.insert(Ptr).second);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001765
1766 if (!OffsetPtr) {
1767 if (!Int8Ptr) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00001768 Int8Ptr = IRB.CreateBitCast(
1769 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1770 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001771 Int8PtrOffset = Offset;
1772 }
1773
Chandler Carruth113dc642014-12-20 02:39:18 +00001774 OffsetPtr = Int8PtrOffset == 0
1775 ? Int8Ptr
1776 : IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1777 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001778 }
1779 Ptr = OffsetPtr;
1780
1781 // On the off chance we were targeting i8*, guard the bitcast here.
1782 if (Ptr->getType() != PointerTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001783 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001784
1785 return Ptr;
1786}
1787
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001788/// \brief Test whether we can convert a value from the old to the new type.
1789///
1790/// This predicate should be used to guard calls to convertValue in order to
1791/// ensure that we only try to convert viable values. The strategy is that we
1792/// will peel off single element struct and array wrappings to get to an
1793/// underlying value, and convert that value.
1794static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1795 if (OldTy == NewTy)
1796 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001797 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1798 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1799 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1800 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001801 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1802 return false;
1803 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1804 return false;
1805
Benjamin Kramer56262592013-09-22 11:24:58 +00001806 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001807 // of pointers and integers.
1808 OldTy = OldTy->getScalarType();
1809 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001810 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1811 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1812 return true;
1813 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1814 return true;
1815 return false;
1816 }
1817
1818 return true;
1819}
1820
1821/// \brief Generic routine to convert an SSA value to a value of a different
1822/// type.
1823///
1824/// This will try various different casting techniques, such as bitcasts,
1825/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1826/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001827static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001828 Type *NewTy) {
1829 Type *OldTy = V->getType();
1830 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1831
1832 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001833 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001834
1835 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1836 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001837 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1838 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001839
Benjamin Kramer90901a32013-09-21 20:36:04 +00001840 // See if we need inttoptr for this type pair. A cast involving both scalars
1841 // and vectors requires and additional bitcast.
1842 if (OldTy->getScalarType()->isIntegerTy() &&
1843 NewTy->getScalarType()->isPointerTy()) {
1844 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1845 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1846 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1847 NewTy);
1848
1849 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1850 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1851 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1852 NewTy);
1853
1854 return IRB.CreateIntToPtr(V, NewTy);
1855 }
1856
1857 // See if we need ptrtoint for this type pair. A cast involving both scalars
1858 // and vectors requires and additional bitcast.
1859 if (OldTy->getScalarType()->isPointerTy() &&
1860 NewTy->getScalarType()->isIntegerTy()) {
1861 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1862 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1863 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1864 NewTy);
1865
1866 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1867 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1868 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1869 NewTy);
1870
1871 return IRB.CreatePtrToInt(V, NewTy);
1872 }
1873
1874 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001875}
1876
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001877/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001878///
1879/// This function is called to test each entry in a partioning which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001880/// for a single slice.
Chandler Carruthc659df92014-10-16 20:24:07 +00001881static bool
1882isVectorPromotionViableForSlice(const DataLayout &DL, uint64_t SliceBeginOffset,
1883 uint64_t SliceEndOffset, VectorType *Ty,
1884 uint64_t ElementSize, const Slice &S) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001885 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001886 uint64_t BeginOffset =
Chandler Carruthc659df92014-10-16 20:24:07 +00001887 std::max(S.beginOffset(), SliceBeginOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001888 uint64_t BeginIndex = BeginOffset / ElementSize;
1889 if (BeginIndex * ElementSize != BeginOffset ||
1890 BeginIndex >= Ty->getNumElements())
1891 return false;
1892 uint64_t EndOffset =
Chandler Carruthc659df92014-10-16 20:24:07 +00001893 std::min(S.endOffset(), SliceEndOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001894 uint64_t EndIndex = EndOffset / ElementSize;
1895 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1896 return false;
1897
1898 assert(EndIndex > BeginIndex && "Empty vector!");
1899 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruthc659df92014-10-16 20:24:07 +00001900 Type *SliceTy = (NumElements == 1)
1901 ? Ty->getElementType()
1902 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruthf0546402013-07-18 07:15:00 +00001903
1904 Type *SplitIntTy =
1905 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1906
Chandler Carruthc659df92014-10-16 20:24:07 +00001907 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001908
1909 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1910 if (MI->isVolatile())
1911 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001912 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001913 return false; // Skip any unsplittable intrinsics.
Owen Anderson6c19ab12014-08-07 21:07:35 +00001914 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1915 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1916 II->getIntrinsicID() != Intrinsic::lifetime_end)
1917 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001918 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1919 // Disable vector promotion when there are loads or stores of an FCA.
1920 return false;
1921 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1922 if (LI->isVolatile())
1923 return false;
1924 Type *LTy = LI->getType();
Chandler Carruthc659df92014-10-16 20:24:07 +00001925 if (SliceBeginOffset > S.beginOffset() || SliceEndOffset < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001926 assert(LTy->isIntegerTy());
1927 LTy = SplitIntTy;
1928 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001929 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001930 return false;
1931 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1932 if (SI->isVolatile())
1933 return false;
1934 Type *STy = SI->getValueOperand()->getType();
Chandler Carruthc659df92014-10-16 20:24:07 +00001935 if (SliceBeginOffset > S.beginOffset() || SliceEndOffset < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001936 assert(STy->isIntegerTy());
1937 STy = SplitIntTy;
1938 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001939 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001940 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001941 } else {
1942 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001943 }
1944
1945 return true;
1946}
1947
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001948/// \brief Test whether the given alloca partitioning and range of slices can be
1949/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001950///
1951/// This is a quick test to check whether we can rewrite a particular alloca
1952/// partition (and its newly formed alloca) into a vector alloca with only
1953/// whole-vector loads and stores such that it could be promoted to a vector
1954/// SSA value. We only can ensure this for a limited set of operations, and we
1955/// don't want to do the rewrites unless we are confident that the result will
1956/// be promotable, so we have an early test here.
Chandler Carruth2dc96822014-10-18 00:44:02 +00001957static VectorType *
Chandler Carruth113dc642014-12-20 02:39:18 +00001958isVectorPromotionViable(const DataLayout &DL, uint64_t SliceBeginOffset,
1959 uint64_t SliceEndOffset,
Chandler Carruthc659df92014-10-16 20:24:07 +00001960 AllocaSlices::const_range Slices,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001961 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001962 // Collect the candidate types for vector-based promotion. Also track whether
1963 // we have different element types.
1964 SmallVector<VectorType *, 4> CandidateTys;
1965 Type *CommonEltTy = nullptr;
1966 bool HaveCommonEltTy = true;
1967 auto CheckCandidateType = [&](Type *Ty) {
1968 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1969 CandidateTys.push_back(VTy);
1970 if (!CommonEltTy)
1971 CommonEltTy = VTy->getElementType();
1972 else if (CommonEltTy != VTy->getElementType())
1973 HaveCommonEltTy = false;
1974 }
1975 };
Chandler Carruth2dc96822014-10-18 00:44:02 +00001976 // Consider any loads or stores that are the exact size of the slice.
Chandler Carruthc659df92014-10-16 20:24:07 +00001977 for (const auto &S : Slices)
Chandler Carruth2dc96822014-10-18 00:44:02 +00001978 if (S.beginOffset() == SliceBeginOffset &&
1979 S.endOffset() == SliceEndOffset) {
1980 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1981 CheckCandidateType(LI->getType());
1982 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1983 CheckCandidateType(SI->getValueOperand()->getType());
1984 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001985
Chandler Carruth2dc96822014-10-18 00:44:02 +00001986 // If we didn't find a vector type, nothing to do here.
1987 if (CandidateTys.empty())
1988 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001989
Chandler Carruth2dc96822014-10-18 00:44:02 +00001990 // Remove non-integer vector types if we had multiple common element types.
1991 // FIXME: It'd be nice to replace them with integer vector types, but we can't
1992 // do that until all the backends are known to produce good code for all
1993 // integer vector types.
1994 if (!HaveCommonEltTy) {
1995 CandidateTys.erase(std::remove_if(CandidateTys.begin(), CandidateTys.end(),
1996 [](VectorType *VTy) {
1997 return !VTy->getElementType()->isIntegerTy();
1998 }),
1999 CandidateTys.end());
2000
2001 // If there were no integer vector types, give up.
2002 if (CandidateTys.empty())
2003 return nullptr;
2004
2005 // Rank the remaining candidate vector types. This is easy because we know
2006 // they're all integer vectors. We sort by ascending number of elements.
2007 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
2008 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
2009 "Cannot have vector types of different sizes!");
2010 assert(RHSTy->getElementType()->isIntegerTy() &&
2011 "All non-integer types eliminated!");
2012 assert(LHSTy->getElementType()->isIntegerTy() &&
2013 "All non-integer types eliminated!");
2014 return RHSTy->getNumElements() < LHSTy->getNumElements();
2015 };
2016 std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
2017 CandidateTys.erase(
2018 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
2019 CandidateTys.end());
2020 } else {
2021// The only way to have the same element type in every vector type is to
2022// have the same vector type. Check that and remove all but one.
2023#ifndef NDEBUG
2024 for (VectorType *VTy : CandidateTys) {
2025 assert(VTy->getElementType() == CommonEltTy &&
2026 "Unaccounted for element type!");
2027 assert(VTy == CandidateTys[0] &&
2028 "Different vector types with the same element type!");
2029 }
2030#endif
2031 CandidateTys.resize(1);
2032 }
2033
2034 // Try each vector type, and return the one which works.
2035 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
2036 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
2037
2038 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2039 // that aren't byte sized.
2040 if (ElementSize % 8)
2041 return false;
2042 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
2043 "vector size not a multiple of element size?");
2044 ElementSize /= 8;
2045
2046 for (const auto &S : Slices)
2047 if (!isVectorPromotionViableForSlice(DL, SliceBeginOffset, SliceEndOffset,
2048 VTy, ElementSize, S))
2049 return false;
2050
2051 for (const auto &SI : SplitUses)
2052 if (!isVectorPromotionViableForSlice(DL, SliceBeginOffset, SliceEndOffset,
2053 VTy, ElementSize, *SI))
2054 return false;
2055
2056 return true;
2057 };
2058 for (VectorType *VTy : CandidateTys)
2059 if (CheckVectorTypeForPromotion(VTy))
2060 return VTy;
2061
2062 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00002063}
2064
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002065/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00002066///
2067/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002068/// test below on a single slice of the alloca.
2069static bool isIntegerWideningViableForSlice(const DataLayout &DL,
2070 Type *AllocaTy,
2071 uint64_t AllocBeginOffset,
Chandler Carruth113dc642014-12-20 02:39:18 +00002072 uint64_t Size, const Slice &S,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002073 bool &WholeAllocaOp) {
Chandler Carruthc659df92014-10-16 20:24:07 +00002074 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
2075 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00002076
2077 // We can't reasonably handle cases where the load or store extends past
2078 // the end of the aloca's type and into its padding.
2079 if (RelEnd > Size)
2080 return false;
2081
Chandler Carruthc659df92014-10-16 20:24:07 +00002082 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00002083
2084 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2085 if (LI->isVolatile())
2086 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00002087 // Note that we don't count vector loads or stores as whole-alloca
2088 // operations which enable integer widening because we would prefer to use
2089 // vector widening instead.
2090 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00002091 WholeAllocaOp = true;
2092 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002093 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00002094 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002095 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002096 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002097 // Non-integer loads need to be convertible from the alloca type so that
2098 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002099 return false;
2100 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002101 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2102 Type *ValueTy = SI->getValueOperand()->getType();
2103 if (SI->isVolatile())
2104 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00002105 // Note that we don't count vector loads or stores as whole-alloca
2106 // operations which enable integer widening because we would prefer to use
2107 // vector widening instead.
2108 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00002109 WholeAllocaOp = true;
2110 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002111 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00002112 return false;
2113 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002114 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002115 // Non-integer stores need to be convertible to the alloca type so that
2116 // they are promotable.
2117 return false;
2118 }
2119 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2120 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2121 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00002122 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00002123 return false; // Skip any unsplittable intrinsics.
2124 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2125 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2126 II->getIntrinsicID() != Intrinsic::lifetime_end)
2127 return false;
2128 } else {
2129 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002130 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002131
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002132 return true;
2133}
2134
Chandler Carruth435c4e02012-10-15 08:40:30 +00002135/// \brief Test whether the given alloca partition's integer operations can be
2136/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002137///
Chandler Carruth435c4e02012-10-15 08:40:30 +00002138/// This is a quick test to check whether we can rewrite the integer loads and
2139/// stores to a particular alloca into wider loads and stores and be able to
2140/// promote the resulting alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +00002141static bool
Chandler Carruth90a735d2013-07-19 07:21:28 +00002142isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
Chandler Carruthc659df92014-10-16 20:24:07 +00002143 uint64_t AllocBeginOffset,
2144 AllocaSlices::const_range Slices,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002145 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002146 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00002147 // Don't create integer types larger than the maximum bitwidth.
2148 if (SizeInBits > IntegerType::MAX_INT_BITS)
2149 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002150
2151 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002152 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002153 return false;
2154
Chandler Carruth58d05562012-10-25 04:37:07 +00002155 // We need to ensure that an integer type with the appropriate bitwidth can
2156 // be converted to the alloca type, whatever that is. We don't want to force
2157 // the alloca itself to have an integer type if there is a more suitable one.
2158 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002159 if (!canConvertValue(DL, AllocaTy, IntTy) ||
2160 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00002161 return false;
2162
Chandler Carruth90a735d2013-07-19 07:21:28 +00002163 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002164
Chandler Carruthf0546402013-07-18 07:15:00 +00002165 // While examining uses, we ensure that the alloca has a covering load or
2166 // store. We don't want to widen the integer operations only to fail to
2167 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00002168 // later). However, if there are only splittable uses, go ahead and assume
2169 // that we cover the alloca.
Chandler Carruthc659df92014-10-16 20:24:07 +00002170 bool WholeAllocaOp =
2171 Slices.begin() != Slices.end() ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00002172
Chandler Carruthc659df92014-10-16 20:24:07 +00002173 for (const auto &S : Slices)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002174 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
Chandler Carruthc659df92014-10-16 20:24:07 +00002175 S, WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00002176 return false;
2177
Chandler Carruthc659df92014-10-16 20:24:07 +00002178 for (const auto &SI : SplitUses)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002179 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
Chandler Carruthc659df92014-10-16 20:24:07 +00002180 *SI, WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002181 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002182
Chandler Carruth92924fd2012-09-24 00:34:20 +00002183 return WholeAllocaOp;
2184}
2185
Chandler Carruthd177f862013-03-20 07:30:36 +00002186static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002187 IntegerType *Ty, uint64_t Offset,
2188 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002189 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002190 IntegerType *IntTy = cast<IntegerType>(V->getType());
2191 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2192 "Element extends past full value");
Chandler Carruth113dc642014-12-20 02:39:18 +00002193 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002194 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002195 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002196 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002197 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002198 DEBUG(dbgs() << " shifted: " << *V << "\n");
2199 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002200 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2201 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002202 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002203 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00002204 DEBUG(dbgs() << " trunced: " << *V << "\n");
2205 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002206 return V;
2207}
2208
Chandler Carruthd177f862013-03-20 07:30:36 +00002209static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002210 Value *V, uint64_t Offset, const Twine &Name) {
2211 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2212 IntegerType *Ty = cast<IntegerType>(V->getType());
2213 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2214 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002215 DEBUG(dbgs() << " start: " << *V << "\n");
2216 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002217 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00002218 DEBUG(dbgs() << " extended: " << *V << "\n");
2219 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002220 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2221 "Element store outside of alloca store");
Chandler Carruth113dc642014-12-20 02:39:18 +00002222 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002223 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002224 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002225 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002226 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002227 DEBUG(dbgs() << " shifted: " << *V << "\n");
2228 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002229
2230 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2231 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2232 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00002233 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002234 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00002235 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002236 }
2237 return V;
2238}
2239
Chandler Carruth113dc642014-12-20 02:39:18 +00002240static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2241 unsigned EndIndex, const Twine &Name) {
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002242 VectorType *VecTy = cast<VectorType>(V->getType());
2243 unsigned NumElements = EndIndex - BeginIndex;
2244 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2245
2246 if (NumElements == VecTy->getNumElements())
2247 return V;
2248
2249 if (NumElements == 1) {
2250 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2251 Name + ".extract");
2252 DEBUG(dbgs() << " extract: " << *V << "\n");
2253 return V;
2254 }
2255
Chandler Carruth113dc642014-12-20 02:39:18 +00002256 SmallVector<Constant *, 8> Mask;
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002257 Mask.reserve(NumElements);
2258 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2259 Mask.push_back(IRB.getInt32(i));
2260 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002261 ConstantVector::get(Mask), Name + ".extract");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002262 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2263 return V;
2264}
2265
Chandler Carruthd177f862013-03-20 07:30:36 +00002266static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00002267 unsigned BeginIndex, const Twine &Name) {
2268 VectorType *VecTy = cast<VectorType>(Old->getType());
2269 assert(VecTy && "Can only insert a vector into a vector");
2270
2271 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2272 if (!Ty) {
2273 // Single element to insert.
2274 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2275 Name + ".insert");
Chandler Carruth113dc642014-12-20 02:39:18 +00002276 DEBUG(dbgs() << " insert: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002277 return V;
2278 }
2279
2280 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2281 "Too many elements!");
2282 if (Ty->getNumElements() == VecTy->getNumElements()) {
2283 assert(V->getType() == VecTy && "Vector type mismatch");
2284 return V;
2285 }
2286 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2287
2288 // When inserting a smaller vector into the larger to store, we first
2289 // use a shuffle vector to widen it with undef elements, and then
2290 // a second shuffle vector to select between the loaded vector and the
2291 // incoming vector.
Chandler Carruth113dc642014-12-20 02:39:18 +00002292 SmallVector<Constant *, 8> Mask;
Chandler Carruthce4562b2012-12-17 13:41:21 +00002293 Mask.reserve(VecTy->getNumElements());
2294 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2295 if (i >= BeginIndex && i < EndIndex)
2296 Mask.push_back(IRB.getInt32(i - BeginIndex));
2297 else
2298 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2299 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002300 ConstantVector::get(Mask), Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00002301 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002302
2303 Mask.clear();
2304 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00002305 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2306
2307 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2308
2309 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002310 return V;
2311}
2312
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002313namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002314/// \brief Visitor to rewrite instructions using p particular slice of an alloca
2315/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002316///
2317/// Also implements the rewriting to vector-based accesses when the partition
2318/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2319/// lives here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002320class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002321 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002322 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
2323 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002324
Chandler Carruth90a735d2013-07-19 07:21:28 +00002325 const DataLayout &DL;
Chandler Carruth83934062014-10-16 21:11:55 +00002326 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002327 SROA &Pass;
2328 AllocaInst &OldAI, &NewAI;
2329 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002330 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002331
Chandler Carruth2dc96822014-10-18 00:44:02 +00002332 // This is a convenience and flag variable that will be null unless the new
2333 // alloca's integer operations should be widened to this integer type due to
2334 // passing isIntegerWideningViable above. If it is non-null, the desired
2335 // integer type will be stored here for easy access during rewriting.
2336 IntegerType *IntTy;
2337
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002338 // If we are rewriting an alloca partition which can be written as pure
2339 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002340 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002341 // - The new alloca is exactly the size of the vector type here.
2342 // - The accesses all either map to the entire vector or to a single
2343 // element.
2344 // - The set of accessing instructions is only one of those handled above
2345 // in isVectorPromotionViable. Generally these are the same access kinds
2346 // which are promotable via mem2reg.
2347 VectorType *VecTy;
2348 Type *ElementTy;
2349 uint64_t ElementSize;
2350
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002351 // The original offset of the slice currently being rewritten relative to
2352 // the original alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002353 uint64_t BeginOffset, EndOffset;
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002354 // The new offsets of the slice currently being rewritten relative to the
2355 // original alloca.
2356 uint64_t NewBeginOffset, NewEndOffset;
2357
2358 uint64_t SliceSize;
Chandler Carruthf0546402013-07-18 07:15:00 +00002359 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002360 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002361 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002362 Instruction *OldPtr;
2363
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002364 // Track post-rewrite users which are PHI nodes and Selects.
2365 SmallPtrSetImpl<PHINode *> &PHIUsers;
2366 SmallPtrSetImpl<SelectInst *> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002367
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002368 // Utility IR builder, whose name prefix is setup for each visited use, and
2369 // the insertion point is set to point to the user.
2370 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002371
2372public:
Chandler Carruth83934062014-10-16 21:11:55 +00002373 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002374 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002375 uint64_t NewAllocaBeginOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00002376 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2377 VectorType *PromotableVecTy,
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002378 SmallPtrSetImpl<PHINode *> &PHIUsers,
2379 SmallPtrSetImpl<SelectInst *> &SelectUsers)
Chandler Carruth83934062014-10-16 21:11:55 +00002380 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002381 NewAllocaBeginOffset(NewAllocaBeginOffset),
2382 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002383 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002384 IntTy(IsIntegerPromotable
2385 ? Type::getIntNTy(
2386 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002387 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Craig Topperf40110f2014-04-25 05:29:35 +00002388 : nullptr),
Chandler Carruth2dc96822014-10-18 00:44:02 +00002389 VecTy(PromotableVecTy),
2390 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2391 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00002392 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002393 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002394 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002395 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002396 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002397 "Only multiple-of-8 sized vector elements are viable");
2398 ++NumVectorized;
2399 }
Chandler Carruth2dc96822014-10-18 00:44:02 +00002400 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002401 }
2402
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002403 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002404 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002405 BeginOffset = I->beginOffset();
2406 EndOffset = I->endOffset();
2407 IsSplittable = I->isSplittable();
2408 IsSplit =
2409 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002410
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002411 // Compute the intersecting offset range.
2412 assert(BeginOffset < NewAllocaEndOffset);
2413 assert(EndOffset > NewAllocaBeginOffset);
2414 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2415 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2416
2417 SliceSize = NewEndOffset - NewBeginOffset;
2418
Chandler Carruthf0546402013-07-18 07:15:00 +00002419 OldUse = I->getUse();
2420 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002421
Chandler Carruthf0546402013-07-18 07:15:00 +00002422 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2423 IRB.SetInsertPoint(OldUserI);
2424 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2425 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2426
2427 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2428 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002429 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002430 return CanSROA;
2431 }
2432
2433private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002434 // Make sure the other visit overloads are visible.
2435 using Base::visit;
2436
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002437 // Every instruction which can end up as a user must have a rewrite rule.
2438 bool visitInstruction(Instruction &I) {
2439 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2440 llvm_unreachable("No rewrite rule for this instruction!");
2441 }
2442
Chandler Carruth47954c82014-02-26 05:12:43 +00002443 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2444 // Note that the offset computation can use BeginOffset or NewBeginOffset
2445 // interchangeably for unsplit slices.
2446 assert(IsSplit || BeginOffset == NewBeginOffset);
2447 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2448
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002449#ifndef NDEBUG
2450 StringRef OldName = OldPtr->getName();
2451 // Skip through the last '.sroa.' component of the name.
2452 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2453 if (LastSROAPrefix != StringRef::npos) {
2454 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2455 // Look for an SROA slice index.
2456 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2457 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2458 // Strip the index and look for the offset.
2459 OldName = OldName.substr(IndexEnd + 1);
2460 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2461 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2462 // Strip the offset.
2463 OldName = OldName.substr(OffsetEnd + 1);
2464 }
2465 }
2466 // Strip any SROA suffixes as well.
2467 OldName = OldName.substr(0, OldName.find(".sroa_"));
2468#endif
Chandler Carruth47954c82014-02-26 05:12:43 +00002469
2470 return getAdjustedPtr(IRB, DL, &NewAI,
2471 APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002472#ifndef NDEBUG
2473 Twine(OldName) + "."
2474#else
2475 Twine()
2476#endif
2477 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002478 }
2479
Chandler Carruth113dc642014-12-20 02:39:18 +00002480 /// \brief Compute suitable alignment to access this slice of the *new*
2481 /// alloca.
Chandler Carruth2659e502014-02-26 05:02:19 +00002482 ///
2483 /// You can optionally pass a type to this routine and if that type's ABI
2484 /// alignment is itself suitable, this will return zero.
Craig Topperf40110f2014-04-25 05:29:35 +00002485 unsigned getSliceAlign(Type *Ty = nullptr) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002486 unsigned NewAIAlign = NewAI.getAlignment();
2487 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002488 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth113dc642014-12-20 02:39:18 +00002489 unsigned Align =
2490 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
Chandler Carruth2659e502014-02-26 05:02:19 +00002491 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002492 }
2493
Chandler Carruth845b73c2012-11-21 08:16:30 +00002494 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002495 assert(VecTy && "Can only call getIndex when rewriting a vector");
2496 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2497 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2498 uint32_t Index = RelOffset / ElementSize;
2499 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002500 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002501 }
2502
2503 void deleteIfTriviallyDead(Value *V) {
2504 Instruction *I = cast<Instruction>(V);
2505 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002506 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002507 }
2508
Chandler Carruthea27cf02014-02-26 04:25:04 +00002509 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002510 unsigned BeginIndex = getIndex(NewBeginOffset);
2511 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002512 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002513
Chandler Carruth113dc642014-12-20 02:39:18 +00002514 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002515 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002516 }
2517
Chandler Carruthea27cf02014-02-26 04:25:04 +00002518 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002519 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002520 assert(!LI.isVolatile());
Chandler Carruth113dc642014-12-20 02:39:18 +00002521 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002522 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002523 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2524 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2525 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002526 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002527 "extract");
Chandler Carruth18db7952012-11-20 01:12:50 +00002528 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002529 }
2530
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002531 bool visitLoadInst(LoadInst &LI) {
2532 DEBUG(dbgs() << " original: " << LI << "\n");
2533 Value *OldOp = LI.getOperand(0);
2534 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002535
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002536 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002537 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002538 bool IsPtrAdjusted = false;
2539 Value *V;
2540 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002541 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002542 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002543 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002544 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002545 canConvertValue(DL, NewAllocaTy, LI.getType())) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002546 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), LI.isVolatile(),
2547 LI.getName());
Chandler Carruth18db7952012-11-20 01:12:50 +00002548 } else {
2549 Type *LTy = TargetTy->getPointerTo();
Chandler Carruth47954c82014-02-26 05:12:43 +00002550 V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
Chandler Carruth2659e502014-02-26 05:02:19 +00002551 getSliceAlign(TargetTy), LI.isVolatile(),
2552 LI.getName());
Chandler Carruth18db7952012-11-20 01:12:50 +00002553 IsPtrAdjusted = true;
2554 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002555 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002556
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002557 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002558 assert(!LI.isVolatile());
2559 assert(LI.getType()->isIntegerTy() &&
2560 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002561 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002562 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002563 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002564 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002565 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002566 // Move the insertion point just past the load so that we can refer to it.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002567 IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002568 // Create a placeholder value with the same type as LI to use as the
2569 // basis for the new value. This allows us to replace the uses of LI with
2570 // the computed value, and then replace the placeholder with LI, leaving
2571 // LI only used for this computation.
Chandler Carruth113dc642014-12-20 02:39:18 +00002572 Value *Placeholder =
2573 new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2574 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset, "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002575 LI.replaceAllUsesWith(V);
2576 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002577 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002578 } else {
2579 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002580 }
2581
Chandler Carruth18db7952012-11-20 01:12:50 +00002582 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002583 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002584 DEBUG(dbgs() << " to: " << *V << "\n");
2585 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002586 }
2587
Chandler Carruthea27cf02014-02-26 04:25:04 +00002588 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002589 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002590 unsigned BeginIndex = getIndex(NewBeginOffset);
2591 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002592 assert(EndIndex > BeginIndex && "Empty vector!");
2593 unsigned NumElements = EndIndex - BeginIndex;
2594 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth113dc642014-12-20 02:39:18 +00002595 Type *SliceTy = (NumElements == 1)
2596 ? ElementTy
2597 : VectorType::get(ElementTy, NumElements);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002598 if (V->getType() != SliceTy)
2599 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002600
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002601 // Mix in the existing elements.
Chandler Carruth113dc642014-12-20 02:39:18 +00002602 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002603 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2604 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002605 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002606 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002607
2608 (void)Store;
2609 DEBUG(dbgs() << " to: " << *Store << "\n");
2610 return true;
2611 }
2612
Chandler Carruthea27cf02014-02-26 04:25:04 +00002613 bool rewriteIntegerStore(Value *V, StoreInst &SI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002614 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002615 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002616 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002617 Value *Old =
2618 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002619 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002620 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2621 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth113dc642014-12-20 02:39:18 +00002622 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002623 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002624 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002625 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002626 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002627 (void)Store;
2628 DEBUG(dbgs() << " to: " << *Store << "\n");
2629 return true;
2630 }
2631
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002632 bool visitStoreInst(StoreInst &SI) {
2633 DEBUG(dbgs() << " original: " << SI << "\n");
2634 Value *OldOp = SI.getOperand(1);
2635 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002636
Chandler Carruth18db7952012-11-20 01:12:50 +00002637 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002638
Chandler Carruthac8317f2012-10-04 12:33:50 +00002639 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2640 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002641 if (V->getType()->isPointerTy())
2642 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002643 Pass.PostPromotionWorklist.insert(AI);
2644
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002645 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002646 assert(!SI.isVolatile());
2647 assert(V->getType()->isIntegerTy() &&
2648 "Only integer type loads and stores are split");
2649 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002650 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002651 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002652 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth113dc642014-12-20 02:39:18 +00002653 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset, "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002654 }
2655
Chandler Carruth18db7952012-11-20 01:12:50 +00002656 if (VecTy)
Chandler Carruthea27cf02014-02-26 04:25:04 +00002657 return rewriteVectorizedStoreInst(V, SI, OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002658 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthea27cf02014-02-26 04:25:04 +00002659 return rewriteIntegerStore(V, SI);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002660
Chandler Carruth18db7952012-11-20 01:12:50 +00002661 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002662 if (NewBeginOffset == NewAllocaBeginOffset &&
2663 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002664 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2665 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002666 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2667 SI.isVolatile());
2668 } else {
Chandler Carruth47954c82014-02-26 05:12:43 +00002669 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
Chandler Carruth2659e502014-02-26 05:02:19 +00002670 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2671 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002672 }
2673 (void)NewSI;
2674 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002675 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002676
2677 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2678 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002679 }
2680
Chandler Carruth514f34f2012-12-17 04:07:30 +00002681 /// \brief Compute an integer value from splatting an i8 across the given
2682 /// number of bytes.
2683 ///
2684 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2685 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002686 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002687 ///
2688 /// \param V The i8 value to splat.
2689 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002690 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002691 assert(Size > 0 && "Expected a positive number of bytes.");
2692 IntegerType *VTy = cast<IntegerType>(V->getType());
2693 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2694 if (Size == 1)
2695 return V;
2696
Chandler Carruth113dc642014-12-20 02:39:18 +00002697 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2698 V = IRB.CreateMul(
2699 IRB.CreateZExt(V, SplatIntTy, "zext"),
2700 ConstantExpr::getUDiv(
2701 Constant::getAllOnesValue(SplatIntTy),
2702 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2703 SplatIntTy)),
2704 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002705 return V;
2706 }
2707
Chandler Carruthccca5042012-12-17 04:07:37 +00002708 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002709 Value *getVectorSplat(Value *V, unsigned NumElements) {
2710 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002711 DEBUG(dbgs() << " splat: " << *V << "\n");
2712 return V;
2713 }
2714
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002715 bool visitMemSetInst(MemSetInst &II) {
2716 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002717 assert(II.getRawDest() == OldPtr);
2718
2719 // If the memset has a variable size, it cannot be split, just adjust the
2720 // pointer to the new alloca.
2721 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002722 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002723 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002724 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002725 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth2659e502014-02-26 05:02:19 +00002726 II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002727
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002728 deleteIfTriviallyDead(OldPtr);
2729 return false;
2730 }
2731
2732 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002733 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002734
2735 Type *AllocaTy = NewAI.getAllocatedType();
2736 Type *ScalarTy = AllocaTy->getScalarType();
2737
2738 // If this doesn't map cleanly onto the alloca type, and that type isn't
2739 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002740 if (!VecTy && !IntTy &&
Chandler Carruth113dc642014-12-20 02:39:18 +00002741 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002742 SliceSize != DL.getTypeStoreSize(AllocaTy) ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002743 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002744 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
Chandler Carruth113dc642014-12-20 02:39:18 +00002745 DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002746 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002747 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2748 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002749 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2750 getSliceAlign(), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002751 (void)New;
2752 DEBUG(dbgs() << " to: " << *New << "\n");
2753 return false;
2754 }
2755
2756 // If we can represent this as a simple value, we have to build the actual
2757 // value to store, which requires expanding the byte present in memset to
2758 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002759 // splatting the byte to a sufficiently wide integer, splatting it across
2760 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002761 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002762
Chandler Carruthccca5042012-12-17 04:07:37 +00002763 if (VecTy) {
2764 // If this is a memset of a vectorized alloca, insert it.
2765 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002766
Chandler Carruthf0546402013-07-18 07:15:00 +00002767 unsigned BeginIndex = getIndex(NewBeginOffset);
2768 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002769 assert(EndIndex > BeginIndex && "Empty vector!");
2770 unsigned NumElements = EndIndex - BeginIndex;
2771 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2772
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002773 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002774 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2775 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002776 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002777 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002778
Chandler Carruth113dc642014-12-20 02:39:18 +00002779 Value *Old =
2780 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002781 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002782 } else if (IntTy) {
2783 // If this is a memset on an alloca where we can widen stores, insert the
2784 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002785 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002786
Chandler Carruthf0546402013-07-18 07:15:00 +00002787 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002788 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002789
2790 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2791 EndOffset != NewAllocaBeginOffset)) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002792 Value *Old =
2793 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002794 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002795 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002796 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002797 } else {
2798 assert(V->getType() == IntTy &&
2799 "Wrong type for an alloca wide integer!");
2800 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002801 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002802 } else {
2803 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002804 assert(NewBeginOffset == NewAllocaBeginOffset);
2805 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002806
Chandler Carruth90a735d2013-07-19 07:21:28 +00002807 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002808 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002809 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002810
Chandler Carruth90a735d2013-07-19 07:21:28 +00002811 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002812 }
2813
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002814 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002815 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002816 (void)New;
2817 DEBUG(dbgs() << " to: " << *New << "\n");
2818 return !II.isVolatile();
2819 }
2820
2821 bool visitMemTransferInst(MemTransferInst &II) {
2822 // Rewriting of memory transfer instructions can be a bit tricky. We break
2823 // them into two categories: split intrinsics and unsplit intrinsics.
2824
2825 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002826
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002827 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002828 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002829 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002830
Chandler Carruthaa72b932014-02-26 07:29:54 +00002831 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002832
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002833 // For unsplit intrinsics, we simply modify the source and destination
2834 // pointers in place. This isn't just an optimization, it is a matter of
2835 // correctness. With unsplit intrinsics we may be dealing with transfers
2836 // within a single alloca before SROA ran, or with transfers that have
2837 // a variable length. We may also be dealing with memmove instead of
2838 // memcpy, and so simply updating the pointers is the necessary for us to
2839 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002840 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002841 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002842 if (IsDest)
Chandler Carruth8183a502014-02-25 11:08:02 +00002843 II.setDest(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002844 else
Chandler Carruth8183a502014-02-25 11:08:02 +00002845 II.setSource(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002846
Chandler Carruthaa72b932014-02-26 07:29:54 +00002847 if (II.getAlignment() > SliceAlign) {
Chandler Carruth181ed052014-02-26 05:33:36 +00002848 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthaa72b932014-02-26 07:29:54 +00002849 II.setAlignment(
2850 ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
Chandler Carruth181ed052014-02-26 05:33:36 +00002851 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002852
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002853 DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002854 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002855 return false;
2856 }
2857 // For split transfer intrinsics we have an incredibly useful assurance:
2858 // the source and destination do not reside within the same alloca, and at
2859 // least one of them does not escape. This means that we can replace
2860 // memmove with memcpy, and we don't need to worry about all manner of
2861 // downsides to splitting and transforming the operations.
2862
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002863 // If this doesn't map cleanly onto the alloca type, and that type isn't
2864 // a single value type, just emit a memcpy.
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002865 bool EmitMemCpy =
2866 !VecTy && !IntTy &&
2867 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2868 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2869 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002870
2871 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2872 // size hasn't been shrunk based on analysis of the viable range, this is
2873 // a no-op.
2874 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002875 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002876 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002877
2878 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002879 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002880 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002881 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002882 return false;
2883 }
2884 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002885 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002886
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002887 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2888 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002889 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth113dc642014-12-20 02:39:18 +00002890 if (AllocaInst *AI =
2891 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002892 assert(AI != &OldAI && AI != &NewAI &&
2893 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002894 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002895 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002896
Chandler Carruth286d87e2014-02-26 08:25:02 +00002897 Type *OtherPtrTy = OtherPtr->getType();
2898 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2899
Chandler Carruth181ed052014-02-26 05:33:36 +00002900 // Compute the relative offset for the other pointer within the transfer.
Chandler Carruth286d87e2014-02-26 08:25:02 +00002901 unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
Chandler Carruth181ed052014-02-26 05:33:36 +00002902 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002903 unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2904 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002905
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002906 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002907 // Compute the other pointer, folding as much as possible to produce
2908 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002909 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002910 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002911
Chandler Carruth47954c82014-02-26 05:12:43 +00002912 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002913 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002914 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002915
Chandler Carruthaa72b932014-02-26 07:29:54 +00002916 CallInst *New = IRB.CreateMemCpy(
2917 IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2918 MinAlign(SliceAlign, OtherAlign), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002919 (void)New;
2920 DEBUG(dbgs() << " to: " << *New << "\n");
2921 return false;
2922 }
2923
Chandler Carruthf0546402013-07-18 07:15:00 +00002924 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2925 NewEndOffset == NewAllocaEndOffset;
2926 uint64_t Size = NewEndOffset - NewBeginOffset;
2927 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2928 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002929 unsigned NumElements = EndIndex - BeginIndex;
Chandler Carruth113dc642014-12-20 02:39:18 +00002930 IntegerType *SubIntTy =
2931 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002932
Chandler Carruth286d87e2014-02-26 08:25:02 +00002933 // Reset the other pointer type to match the register type we're going to
2934 // use, but using the address space of the original other pointer.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002935 if (VecTy && !IsWholeAlloca) {
2936 if (NumElements == 1)
2937 OtherPtrTy = VecTy->getElementType();
2938 else
2939 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2940
Chandler Carruth286d87e2014-02-26 08:25:02 +00002941 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002942 } else if (IntTy && !IsWholeAlloca) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00002943 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2944 } else {
2945 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002946 }
2947
Chandler Carruth181ed052014-02-26 05:33:36 +00002948 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002949 OtherPtr->getName() + ".");
Chandler Carruthaa72b932014-02-26 07:29:54 +00002950 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002951 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00002952 unsigned DstAlign = SliceAlign;
2953 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002954 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002955 std::swap(SrcAlign, DstAlign);
2956 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002957
2958 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002959 if (VecTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002960 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002961 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002962 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002963 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002964 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002965 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002966 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002967 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +00002968 Src =
2969 IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002970 }
2971
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002972 if (VecTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002973 Value *Old =
2974 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002975 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002976 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002977 Value *Old =
2978 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002979 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002980 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002981 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2982 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002983 }
2984
Chandler Carruth871ba722012-09-26 10:27:46 +00002985 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00002986 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Chandler Carruth871ba722012-09-26 10:27:46 +00002987 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002988 DEBUG(dbgs() << " to: " << *Store << "\n");
2989 return !II.isVolatile();
2990 }
2991
2992 bool visitIntrinsicInst(IntrinsicInst &II) {
2993 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2994 II.getIntrinsicID() == Intrinsic::lifetime_end);
2995 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002996 assert(II.getArgOperand(1) == OldPtr);
2997
2998 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002999 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003000
Chandler Carruth113dc642014-12-20 02:39:18 +00003001 ConstantInt *Size =
3002 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00003003 NewEndOffset - NewBeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00003004 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003005 Value *New;
3006 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3007 New = IRB.CreateLifetimeStart(Ptr, Size);
3008 else
3009 New = IRB.CreateLifetimeEnd(Ptr, Size);
3010
Edwin Vane82f80d42013-01-29 17:42:24 +00003011 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003012 DEBUG(dbgs() << " to: " << *New << "\n");
3013 return true;
3014 }
3015
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003016 bool visitPHINode(PHINode &PN) {
3017 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00003018 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
3019 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003020
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003021 // We would like to compute a new pointer in only one place, but have it be
3022 // as local as possible to the PHI. To do that, we re-use the location of
3023 // the old pointer, which necessarily must be in the right position to
3024 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00003025 IRBuilderTy PtrBuilder(IRB);
David Majnemerd4cffcf2014-09-01 21:20:14 +00003026 if (isa<PHINode>(OldPtr))
3027 PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
3028 else
3029 PtrBuilder.SetInsertPoint(OldPtr);
Chandler Carruth51175532014-02-25 11:12:04 +00003030 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003031
Chandler Carruth47954c82014-02-26 05:12:43 +00003032 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00003033 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003034 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003035
Chandler Carruth82a57542012-10-01 10:54:05 +00003036 DEBUG(dbgs() << " to: " << PN << "\n");
3037 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003038
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003039 // PHIs can't be promoted on their own, but often can be speculated. We
3040 // check the speculation outside of the rewriter so that we see the
3041 // fully-rewritten alloca.
3042 PHIUsers.insert(&PN);
3043 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003044 }
3045
3046 bool visitSelectInst(SelectInst &SI) {
3047 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003048 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3049 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00003050 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
3051 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003052
Chandler Carruth47954c82014-02-26 05:12:43 +00003053 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003054 // Replace the operands which were using the old pointer.
3055 if (SI.getOperand(1) == OldPtr)
3056 SI.setOperand(1, NewPtr);
3057 if (SI.getOperand(2) == OldPtr)
3058 SI.setOperand(2, NewPtr);
3059
Chandler Carruth82a57542012-10-01 10:54:05 +00003060 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003061 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003062
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003063 // Selects can't be promoted on their own, but often can be speculated. We
3064 // check the speculation outside of the rewriter so that we see the
3065 // fully-rewritten alloca.
3066 SelectUsers.insert(&SI);
3067 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003068 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003069};
3070}
3071
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003072namespace {
3073/// \brief Visitor to rewrite aggregate loads and stores as scalar.
3074///
3075/// This pass aggressively rewrites all aggregate loads and stores on
3076/// a particular pointer (or any pointer derived from it which we can identify)
3077/// with scalar loads and stores.
3078class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3079 // Befriend the base class so it can delegate to private visit methods.
3080 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3081
Chandler Carruth90a735d2013-07-19 07:21:28 +00003082 const DataLayout &DL;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003083
3084 /// Queue of pointer uses to analyze and potentially rewrite.
3085 SmallVector<Use *, 8> Queue;
3086
3087 /// Set to prevent us from cycling with phi nodes and loops.
3088 SmallPtrSet<User *, 8> Visited;
3089
3090 /// The current pointer use being rewritten. This is used to dig up the used
3091 /// value (as opposed to the user).
3092 Use *U;
3093
3094public:
Chandler Carruth90a735d2013-07-19 07:21:28 +00003095 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003096
3097 /// Rewrite loads and stores through a pointer and all pointers derived from
3098 /// it.
3099 bool rewrite(Instruction &I) {
3100 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3101 enqueueUsers(I);
3102 bool Changed = false;
3103 while (!Queue.empty()) {
3104 U = Queue.pop_back_val();
3105 Changed |= visit(cast<Instruction>(U->getUser()));
3106 }
3107 return Changed;
3108 }
3109
3110private:
3111 /// Enqueue all the users of the given instruction for further processing.
3112 /// This uses a set to de-duplicate users.
3113 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003114 for (Use &U : I.uses())
David Blaikie70573dc2014-11-19 07:49:26 +00003115 if (Visited.insert(U.getUser()).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003116 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003117 }
3118
3119 // Conservative default is to not rewrite anything.
3120 bool visitInstruction(Instruction &I) { return false; }
3121
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003122 /// \brief Generic recursive split emission class.
Chandler Carruth113dc642014-12-20 02:39:18 +00003123 template <typename Derived> class OpSplitter {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003124 protected:
3125 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00003126 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003127 /// The indices which to be used with insert- or extractvalue to select the
3128 /// appropriate value within the aggregate.
3129 SmallVector<unsigned, 4> Indices;
3130 /// The indices to a GEP instruction which will move Ptr to the correct slot
3131 /// within the aggregate.
3132 SmallVector<Value *, 4> GEPIndices;
3133 /// The base pointer of the original op, used as a base for GEPing the
3134 /// split operations.
3135 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003136
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003137 /// Initialize the splitter with an insertion point, Ptr and start with a
3138 /// single zero GEP index.
3139 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003140 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003141
3142 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003143 /// \brief Generic recursive split emission routine.
3144 ///
3145 /// This method recursively splits an aggregate op (load or store) into
3146 /// scalar or vector ops. It splits recursively until it hits a single value
3147 /// and emits that single value operation via the template argument.
3148 ///
3149 /// The logic of this routine relies on GEPs and insertvalue and
3150 /// extractvalue all operating with the same fundamental index list, merely
3151 /// formatted differently (GEPs need actual values).
3152 ///
3153 /// \param Ty The type being split recursively into smaller ops.
3154 /// \param Agg The aggregate value being built up or stored, depending on
3155 /// whether this is splitting a load or a store respectively.
3156 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3157 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003158 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003159
3160 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3161 unsigned OldSize = Indices.size();
3162 (void)OldSize;
3163 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3164 ++Idx) {
3165 assert(Indices.size() == OldSize && "Did not return to the old size");
3166 Indices.push_back(Idx);
3167 GEPIndices.push_back(IRB.getInt32(Idx));
3168 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3169 GEPIndices.pop_back();
3170 Indices.pop_back();
3171 }
3172 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003173 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003174
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003175 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3176 unsigned OldSize = Indices.size();
3177 (void)OldSize;
3178 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3179 ++Idx) {
3180 assert(Indices.size() == OldSize && "Did not return to the old size");
3181 Indices.push_back(Idx);
3182 GEPIndices.push_back(IRB.getInt32(Idx));
3183 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3184 GEPIndices.pop_back();
3185 Indices.pop_back();
3186 }
3187 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003188 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003189
3190 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003191 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003192 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003193
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003194 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003195 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003196 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003197
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003198 /// Emit a leaf load of a single value. This is called at the leaves of the
3199 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003200 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003201 assert(Ty->isSingleValueType());
3202 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00003203 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
3204 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003205 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3206 DEBUG(dbgs() << " to: " << *Load << "\n");
3207 }
3208 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003209
3210 bool visitLoadInst(LoadInst &LI) {
3211 assert(LI.getPointerOperand() == *U);
3212 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3213 return false;
3214
3215 // We have an aggregate being loaded, split it apart.
3216 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003217 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003218 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003219 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003220 LI.replaceAllUsesWith(V);
3221 LI.eraseFromParent();
3222 return true;
3223 }
3224
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003225 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003226 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003227 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003228
3229 /// Emit a leaf store of a single value. This is called at the leaves of the
3230 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003231 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003232 assert(Ty->isSingleValueType());
3233 // Extract the single value and store it using the indices.
3234 Value *Store = IRB.CreateStore(
Chandler Carruth113dc642014-12-20 02:39:18 +00003235 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3236 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003237 (void)Store;
3238 DEBUG(dbgs() << " to: " << *Store << "\n");
3239 }
3240 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003241
3242 bool visitStoreInst(StoreInst &SI) {
3243 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3244 return false;
3245 Value *V = SI.getValueOperand();
3246 if (V->getType()->isSingleValueType())
3247 return false;
3248
3249 // We have an aggregate being stored, split it apart.
3250 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003251 StoreOpSplitter Splitter(&SI, *U);
3252 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003253 SI.eraseFromParent();
3254 return true;
3255 }
3256
3257 bool visitBitCastInst(BitCastInst &BC) {
3258 enqueueUsers(BC);
3259 return false;
3260 }
3261
3262 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3263 enqueueUsers(GEPI);
3264 return false;
3265 }
3266
3267 bool visitPHINode(PHINode &PN) {
3268 enqueueUsers(PN);
3269 return false;
3270 }
3271
3272 bool visitSelectInst(SelectInst &SI) {
3273 enqueueUsers(SI);
3274 return false;
3275 }
3276};
3277}
3278
Chandler Carruthba931992012-10-13 10:49:33 +00003279/// \brief Strip aggregate type wrapping.
3280///
3281/// This removes no-op aggregate types wrapping an underlying type. It will
3282/// strip as many layers of types as it can without changing either the type
3283/// size or the allocated size.
3284static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3285 if (Ty->isSingleValueType())
3286 return Ty;
3287
3288 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3289 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3290
3291 Type *InnerTy;
3292 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3293 InnerTy = ArrTy->getElementType();
3294 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3295 const StructLayout *SL = DL.getStructLayout(STy);
3296 unsigned Index = SL->getElementContainingOffset(0);
3297 InnerTy = STy->getElementType(Index);
3298 } else {
3299 return Ty;
3300 }
3301
3302 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3303 TypeSize > DL.getTypeSizeInBits(InnerTy))
3304 return Ty;
3305
3306 return stripAggregateTypeWrapping(DL, InnerTy);
3307}
3308
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003309/// \brief Try to find a partition of the aggregate type passed in for a given
3310/// offset and size.
3311///
3312/// This recurses through the aggregate type and tries to compute a subtype
3313/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003314/// of an array, it will even compute a new array type for that sub-section,
3315/// and the same for structs.
3316///
3317/// Note that this routine is very strict and tries to find a partition of the
3318/// type which produces the *exact* right offset and size. It is not forgiving
3319/// when the size or offset cause either end of type-based partition to be off.
3320/// Also, this is a best-effort routine. It is reasonable to give up and not
3321/// return a type if necessary.
Chandler Carruth113dc642014-12-20 02:39:18 +00003322static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3323 uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003324 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3325 return stripAggregateTypeWrapping(DL, Ty);
3326 if (Offset > DL.getTypeAllocSize(Ty) ||
3327 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003328 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003329
3330 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3331 // We can't partition pointers...
3332 if (SeqTy->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00003333 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003334
3335 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003336 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003337 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003338 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003339 if (NumSkippedElements >= ArrTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +00003340 return nullptr;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003341 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003342 if (NumSkippedElements >= VecTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +00003343 return nullptr;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003344 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003345 Offset -= NumSkippedElements * ElementSize;
3346
3347 // First check if we need to recurse.
3348 if (Offset > 0 || Size < ElementSize) {
3349 // Bail if the partition ends in a different array element.
3350 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003351 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003352 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003353 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003354 }
3355 assert(Offset == 0);
3356
3357 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003358 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003359 assert(Size > ElementSize);
3360 uint64_t NumElements = Size / ElementSize;
3361 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003362 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003363 return ArrayType::get(ElementTy, NumElements);
3364 }
3365
3366 StructType *STy = dyn_cast<StructType>(Ty);
3367 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003368 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003369
Chandler Carruth90a735d2013-07-19 07:21:28 +00003370 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003371 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003372 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003373 uint64_t EndOffset = Offset + Size;
3374 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003375 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003376
3377 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003378 Offset -= SL->getElementOffset(Index);
3379
3380 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003381 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003382 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003383 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003384
3385 // See if any partition must be contained by the element.
3386 if (Offset > 0 || Size < ElementSize) {
3387 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003388 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003389 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003390 }
3391 assert(Offset == 0);
3392
3393 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003394 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003395
3396 StructType::element_iterator EI = STy->element_begin() + Index,
3397 EE = STy->element_end();
3398 if (EndOffset < SL->getSizeInBytes()) {
3399 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3400 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003401 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003402
3403 // Don't try to form "natural" types if the elements don't line up with the
3404 // expected size.
3405 // FIXME: We could potentially recurse down through the last element in the
3406 // sub-struct to find a natural end point.
3407 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003408 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003409
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003410 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003411 EE = STy->element_begin() + EndIndex;
3412 }
3413
3414 // Try to build up a sub-structure.
Chandler Carruth113dc642014-12-20 02:39:18 +00003415 StructType *SubTy =
3416 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003417 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003418 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003419 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003420
Chandler Carruth054a40a2012-09-14 11:08:31 +00003421 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003422}
3423
3424/// \brief Rewrite an alloca partition's users.
3425///
3426/// This routine drives both of the rewriting goals of the SROA pass. It tries
3427/// to rewrite uses of an alloca partition to be conducive for SSA value
3428/// promotion. If the partition needs a new, more refined alloca, this will
3429/// build that new alloca, preserving as much type information as possible, and
3430/// rewrite the uses of the old alloca to point at the new one and have the
3431/// appropriate new offsets. It also evaluates how successful the rewrite was
3432/// at enabling promotion and if it was successful queues the alloca to be
3433/// promoted.
Chandler Carruth83934062014-10-16 21:11:55 +00003434bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003435 AllocaSlices::Partition &P) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003436 // Try to compute a friendly type for this partition of the alloca. This
3437 // won't always succeed, in which case we fall back to a legal integer type
3438 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00003439 Type *SliceTy = nullptr;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003440 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
3441 if (DL->getTypeAllocSize(CommonUseTy) >= P.size())
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003442 SliceTy = CommonUseTy;
3443 if (!SliceTy)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003444 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003445 P.beginOffset(), P.size()))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003446 SliceTy = TypePartitionTy;
3447 if ((!SliceTy || (SliceTy->isArrayTy() &&
3448 SliceTy->getArrayElementType()->isIntegerTy())) &&
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003449 DL->isLegalInteger(P.size() * 8))
3450 SliceTy = Type::getIntNTy(*C, P.size() * 8);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003451 if (!SliceTy)
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003452 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
3453 assert(DL->getTypeAllocSize(SliceTy) >= P.size());
Chandler Carruthf0546402013-07-18 07:15:00 +00003454
Chandler Carruth2dc96822014-10-18 00:44:02 +00003455 bool IsIntegerPromotable = isIntegerWideningViable(
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003456 *DL, SliceTy, P.beginOffset(),
3457 AllocaSlices::const_range(P.begin(), P.end()), P.splitSlices());
Chandler Carruthf0546402013-07-18 07:15:00 +00003458
Chandler Carruth2dc96822014-10-18 00:44:02 +00003459 VectorType *VecTy =
3460 IsIntegerPromotable
3461 ? nullptr
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003462 : isVectorPromotionViable(
3463 *DL, P.beginOffset(), P.endOffset(),
3464 AllocaSlices::const_range(P.begin(), P.end()), P.splitSlices());
Chandler Carruth2dc96822014-10-18 00:44:02 +00003465 if (VecTy)
3466 SliceTy = VecTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003467
3468 // Check for the case where we're going to rewrite to a new alloca of the
3469 // exact same type as the original, and with the same access offsets. In that
3470 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003471 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003472 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003473 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003474 assert(P.beginOffset() == 0 &&
3475 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003476 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003477 // FIXME: We should be able to bail at this point with "nothing changed".
3478 // FIXME: We might want to defer PHI speculation until after here.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003479 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003480 unsigned Alignment = AI.getAlignment();
3481 if (!Alignment) {
3482 // The minimum alignment which users can rely on when the explicit
3483 // alignment is omitted or zero is that required by the ABI for this
3484 // type.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003485 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003486 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003487 Alignment = MinAlign(Alignment, P.beginOffset());
Chandler Carruth903790e2012-09-29 10:41:21 +00003488 // If we will get at least this much alignment from the type alone, leave
3489 // the alloca's alignment unconstrained.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003490 if (Alignment <= DL->getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003491 Alignment = 0;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003492 NewAI = new AllocaInst(
3493 SliceTy, nullptr, Alignment,
3494 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003495 ++NumNewAllocas;
3496 }
3497
3498 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003499 << "[" << P.beginOffset() << "," << P.endOffset()
3500 << ") to: " << *NewAI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003501
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003502 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00003503 // promoted allocas. We will reset it to this point if the alloca is not in
3504 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003505 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00003506 unsigned NumUses = 0;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003507 SmallPtrSet<PHINode *, 8> PHIUsers;
3508 SmallPtrSet<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003509
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003510 AllocaSliceRewriter Rewriter(*DL, AS, *this, AI, *NewAI, P.beginOffset(),
3511 P.endOffset(), IsIntegerPromotable, VecTy,
3512 PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00003513 bool Promotable = true;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003514 for (Slice *S : P.splitSlices()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003515 DEBUG(dbgs() << " rewriting split ");
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003516 DEBUG(AS.printSlice(dbgs(), S, ""));
3517 Promotable &= Rewriter.visit(S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003518 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003519 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003520 for (Slice &S : P) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003521 DEBUG(dbgs() << " rewriting ");
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003522 DEBUG(AS.printSlice(dbgs(), &S, ""));
3523 Promotable &= Rewriter.visit(&S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003524 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003525 }
3526
Chandler Carruth6c321c12013-07-19 10:57:36 +00003527 NumAllocaPartitionUses += NumUses;
3528 MaxUsesPerAllocaPartition =
3529 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003530
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003531 // Now that we've processed all the slices in the new partition, check if any
3532 // PHIs or Selects would block promotion.
3533 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3534 E = PHIUsers.end();
3535 I != E; ++I)
3536 if (!isSafePHIToSpeculate(**I, DL)) {
3537 Promotable = false;
3538 PHIUsers.clear();
3539 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003540 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003541 }
3542 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3543 E = SelectUsers.end();
3544 I != E; ++I)
3545 if (!isSafeSelectToSpeculate(**I, DL)) {
3546 Promotable = false;
3547 PHIUsers.clear();
3548 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003549 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003550 }
3551
3552 if (Promotable) {
3553 if (PHIUsers.empty() && SelectUsers.empty()) {
3554 // Promote the alloca.
3555 PromotableAllocas.push_back(NewAI);
3556 } else {
3557 // If we have either PHIs or Selects to speculate, add them to those
3558 // worklists and re-queue the new alloca so that we promote in on the
3559 // next iteration.
Chandler Carruth61747042014-10-16 21:05:14 +00003560 for (PHINode *PHIUser : PHIUsers)
3561 SpeculatablePHIs.insert(PHIUser);
3562 for (SelectInst *SelectUser : SelectUsers)
3563 SpeculatableSelects.insert(SelectUser);
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003564 Worklist.insert(NewAI);
3565 }
3566 } else {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003567 // If we can't promote the alloca, iterate on it to check for new
3568 // refinements exposed by splitting the current alloca. Don't iterate on an
3569 // alloca which didn't actually change and didn't get promoted.
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003570 if (NewAI != &AI)
3571 Worklist.insert(NewAI);
Chandler Carruthac8317f2012-10-04 12:33:50 +00003572
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003573 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003574 while (PostPromotionWorklist.size() > PPWOldSize)
3575 PostPromotionWorklist.pop_back();
Chandler Carruthf0546402013-07-18 07:15:00 +00003576 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003577
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003578 return true;
3579}
3580
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003581/// \brief Walks the slices of an alloca and form partitions based on them,
3582/// rewriting each of their uses.
Chandler Carruth83934062014-10-16 21:11:55 +00003583bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
3584 if (AS.begin() == AS.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00003585 return false;
3586
Chandler Carruth6c321c12013-07-19 10:57:36 +00003587 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003588 bool Changed = false;
Chandler Carruthf0546402013-07-18 07:15:00 +00003589
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003590 // Rewrite each parttion.
3591 for (auto &P : AS.partitions()) {
3592 Changed |= rewritePartition(AI, AS, P);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003593 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00003594 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003595
Chandler Carruth6c321c12013-07-19 10:57:36 +00003596 NumAllocaPartitions += NumPartitions;
3597 MaxPartitionsPerAlloca =
3598 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003599
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003600 return Changed;
3601}
3602
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003603/// \brief Clobber a use with undef, deleting the used value if it becomes dead.
3604void SROA::clobberUse(Use &U) {
3605 Value *OldV = U;
3606 // Replace the use with an undef value.
3607 U = UndefValue::get(OldV->getType());
3608
3609 // Check for this making an instruction dead. We have to garbage collect
3610 // all the dead instructions to ensure the uses of any alloca end up being
3611 // minimal.
3612 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3613 if (isInstructionTriviallyDead(OldI)) {
3614 DeadInsts.insert(OldI);
3615 }
3616}
3617
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003618/// \brief Analyze an alloca for SROA.
3619///
3620/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003621/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003622/// rewritten as needed.
3623bool SROA::runOnAlloca(AllocaInst &AI) {
3624 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3625 ++NumAllocasAnalyzed;
3626
3627 // Special case dead allocas, as they're trivial.
3628 if (AI.use_empty()) {
3629 AI.eraseFromParent();
3630 return true;
3631 }
3632
3633 // Skip alloca forms that this analysis can't handle.
3634 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00003635 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003636 return false;
3637
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003638 bool Changed = false;
3639
3640 // First, split any FCA loads and stores touching this alloca to promote
3641 // better splitting and promotion opportunities.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003642 AggLoadStoreRewriter AggRewriter(*DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003643 Changed |= AggRewriter.rewrite(AI);
3644
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003645 // Build the slices using a recursive instruction-visiting builder.
Chandler Carruth83934062014-10-16 21:11:55 +00003646 AllocaSlices AS(*DL, AI);
3647 DEBUG(AS.print(dbgs()));
3648 if (AS.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003649 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003650
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003651 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth83934062014-10-16 21:11:55 +00003652 for (Instruction *DeadUser : AS.getDeadUsers()) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003653 // Free up everything used by this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00003654 for (Use &DeadOp : DeadUser->operands())
Chandler Carruth1583e992014-03-03 10:42:58 +00003655 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003656
3657 // Now replace the uses of this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00003658 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003659
3660 // And mark it for deletion.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00003661 DeadInsts.insert(DeadUser);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003662 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003663 }
Chandler Carruth83934062014-10-16 21:11:55 +00003664 for (Use *DeadOp : AS.getDeadOperands()) {
Chandler Carruth57d4cae2014-10-16 20:42:08 +00003665 clobberUse(*DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003666 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003667 }
3668
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003669 // No slices to split. Leave the dead alloca for a later pass to clean up.
Chandler Carruth83934062014-10-16 21:11:55 +00003670 if (AS.begin() == AS.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003671 return Changed;
3672
Chandler Carruth83934062014-10-16 21:11:55 +00003673 Changed |= splitAlloca(AI, AS);
Chandler Carruthf0546402013-07-18 07:15:00 +00003674
3675 DEBUG(dbgs() << " Speculating PHIs\n");
3676 while (!SpeculatablePHIs.empty())
3677 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3678
3679 DEBUG(dbgs() << " Speculating Selects\n");
3680 while (!SpeculatableSelects.empty())
3681 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3682
3683 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003684}
3685
Chandler Carruth19450da2012-09-14 10:26:38 +00003686/// \brief Delete the dead instructions accumulated in this run.
3687///
3688/// Recursively deletes the dead instructions we've accumulated. This is done
3689/// at the very end to maximize locality of the recursive delete and to
3690/// minimize the problems of invalidated instruction pointers as such pointers
3691/// are used heavily in the intermediate stages of the algorithm.
3692///
3693/// We also record the alloca instructions deleted here so that they aren't
3694/// subsequently handed to mem2reg to promote.
Chandler Carruth113dc642014-12-20 02:39:18 +00003695void SROA::deleteDeadInstructions(
3696 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003697 while (!DeadInsts.empty()) {
3698 Instruction *I = DeadInsts.pop_back_val();
3699 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3700
Chandler Carruth58d05562012-10-25 04:37:07 +00003701 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3702
Chandler Carruth1583e992014-03-03 10:42:58 +00003703 for (Use &Operand : I->operands())
3704 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003705 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00003706 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003707 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003708 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003709 }
3710
3711 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3712 DeletedAllocas.insert(AI);
3713
3714 ++NumDeleted;
3715 I->eraseFromParent();
3716 }
3717}
3718
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003719static void enqueueUsersInWorklist(Instruction &I,
Chandler Carruth45b136f2013-08-11 01:03:18 +00003720 SmallVectorImpl<Instruction *> &Worklist,
Craig Topper71b7b682014-08-21 05:55:13 +00003721 SmallPtrSetImpl<Instruction *> &Visited) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003722 for (User *U : I.users())
David Blaikie70573dc2014-11-19 07:49:26 +00003723 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003724 Worklist.push_back(cast<Instruction>(U));
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003725}
3726
Chandler Carruth70b44c52012-09-15 11:43:14 +00003727/// \brief Promote the allocas, using the best available technique.
3728///
3729/// This attempts to promote whatever allocas have been identified as viable in
3730/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3731/// If there is a domtree available, we attempt to promote using the full power
3732/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3733/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003734/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003735bool SROA::promoteAllocas(Function &F) {
3736 if (PromotableAllocas.empty())
3737 return false;
3738
3739 NumPromoted += PromotableAllocas.size();
3740
3741 if (DT && !ForceSSAUpdater) {
3742 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Hal Finkel60db0582014-09-07 18:57:58 +00003743 PromoteMemToReg(PromotableAllocas, *DT, nullptr, AT);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003744 PromotableAllocas.clear();
3745 return true;
3746 }
3747
3748 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3749 SSAUpdater SSA;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003750 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
Chandler Carruth45b136f2013-08-11 01:03:18 +00003751 SmallVector<Instruction *, 64> Insts;
Chandler Carruth70b44c52012-09-15 11:43:14 +00003752
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003753 // We need a worklist to walk the uses of each alloca.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003754 SmallVector<Instruction *, 8> Worklist;
3755 SmallPtrSet<Instruction *, 8> Visited;
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003756 SmallVector<Instruction *, 32> DeadInsts;
3757
Chandler Carruth70b44c52012-09-15 11:43:14 +00003758 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3759 AllocaInst *AI = PromotableAllocas[Idx];
Chandler Carruth45b136f2013-08-11 01:03:18 +00003760 Insts.clear();
3761 Worklist.clear();
3762 Visited.clear();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003763
Chandler Carruth45b136f2013-08-11 01:03:18 +00003764 enqueueUsersInWorklist(*AI, Worklist, Visited);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003765
Chandler Carruth45b136f2013-08-11 01:03:18 +00003766 while (!Worklist.empty()) {
3767 Instruction *I = Worklist.pop_back_val();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003768
Chandler Carruth70b44c52012-09-15 11:43:14 +00003769 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3770 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3771 // leading to them) here. Eventually it should use them to optimize the
3772 // scalar values produced.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003773 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003774 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3775 II->getIntrinsicID() == Intrinsic::lifetime_end);
3776 II->eraseFromParent();
3777 continue;
3778 }
3779
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003780 // Push the loads and stores we find onto the list. SROA will already
3781 // have validated that all loads and stores are viable candidates for
3782 // promotion.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003783 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003784 assert(LI->getType() == AI->getAllocatedType());
3785 Insts.push_back(LI);
3786 continue;
3787 }
Chandler Carruth45b136f2013-08-11 01:03:18 +00003788 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003789 assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
3790 Insts.push_back(SI);
3791 continue;
3792 }
3793
3794 // For everything else, we know that only no-op bitcasts and GEPs will
3795 // make it this far, just recurse through them and recall them for later
3796 // removal.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003797 DeadInsts.push_back(I);
3798 enqueueUsersInWorklist(*I, Worklist, Visited);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003799 }
3800 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003801 while (!DeadInsts.empty())
3802 DeadInsts.pop_back_val()->eraseFromParent();
3803 AI->eraseFromParent();
Chandler Carruth70b44c52012-09-15 11:43:14 +00003804 }
3805
3806 PromotableAllocas.clear();
3807 return true;
3808}
3809
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003810bool SROA::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00003811 if (skipOptnoneFunction(F))
3812 return false;
3813
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003814 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3815 C = &F.getContext();
Rafael Espindola93512512014-02-25 17:30:31 +00003816 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
3817 if (!DLP) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003818 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3819 return false;
3820 }
Rafael Espindola93512512014-02-25 17:30:31 +00003821 DL = &DLP->getDataLayout();
Chandler Carruth73523022014-01-13 13:07:17 +00003822 DominatorTreeWrapperPass *DTWP =
3823 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperf40110f2014-04-25 05:29:35 +00003824 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Hal Finkel60db0582014-09-07 18:57:58 +00003825 AT = &getAnalysis<AssumptionTracker>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003826
3827 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00003828 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Chandler Carruthc7d1e242014-12-23 02:58:14 +00003829 I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003830 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3831 Worklist.insert(AI);
3832
3833 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003834 // A set of deleted alloca instruction pointers which should be removed from
3835 // the list of promotable allocas.
3836 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3837
Chandler Carruthac8317f2012-10-04 12:33:50 +00003838 do {
3839 while (!Worklist.empty()) {
3840 Changed |= runOnAlloca(*Worklist.pop_back_val());
3841 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003842
Chandler Carruthac8317f2012-10-04 12:33:50 +00003843 // Remove the deleted allocas from various lists so that we don't try to
3844 // continue processing them.
3845 if (!DeletedAllocas.empty()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00003846 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00003847 Worklist.remove_if(IsInSet);
3848 PostPromotionWorklist.remove_if(IsInSet);
Chandler Carruthac8317f2012-10-04 12:33:50 +00003849 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3850 PromotableAllocas.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00003851 IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00003852 PromotableAllocas.end());
3853 DeletedAllocas.clear();
3854 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003855 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003856
Chandler Carruthac8317f2012-10-04 12:33:50 +00003857 Changed |= promoteAllocas(F);
3858
3859 Worklist = PostPromotionWorklist;
3860 PostPromotionWorklist.clear();
3861 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003862
3863 return Changed;
3864}
3865
3866void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Hal Finkel60db0582014-09-07 18:57:58 +00003867 AU.addRequired<AssumptionTracker>();
Chandler Carruth70b44c52012-09-15 11:43:14 +00003868 if (RequiresDomTree)
Chandler Carruth73523022014-01-13 13:07:17 +00003869 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003870 AU.setPreservesCFG();
3871}