blob: d01e91a7f2356f4261193881a19b02605579372b [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 Carruth29a18a42015-09-12 09:09:14 +000026#include "llvm/Transforms/Scalar/SROA.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/ADT/SmallVector.h"
29#include "llvm/ADT/Statistic.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000030#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +000031#include "llvm/Analysis/GlobalsModRef.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 Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/IRBuilder.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000041#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/Instructions.h"
43#include "llvm/IR/IntrinsicInst.h"
44#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000045#include "llvm/IR/Operator.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000046#include "llvm/Pass.h"
Pavel Labathc207bec2016-11-09 12:07:12 +000047#include "llvm/Support/Chrono.h"
Chandler Carruth70b44c52012-09-15 11:43:14 +000048#include "llvm/Support/CommandLine.h"
Chandler Carruthf0546402013-07-18 07:15:00 +000049#include "llvm/Support/Compiler.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000050#include "llvm/Support/Debug.h"
51#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000052#include "llvm/Support/MathExtras.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000053#include "llvm/Support/raw_ostream.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +000054#include "llvm/Transforms/Scalar.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000055#include "llvm/Transforms/Utils/Local.h"
56#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Chandler Carruth83cee772014-02-25 03:59:29 +000057
Hal Finkel29f51312016-03-28 11:13:03 +000058#ifndef NDEBUG
59// We only use this for a debug check.
Chandler Carruth83cee772014-02-25 03:59:29 +000060#include <random>
61#endif
62
Chandler Carruth1b398ae2012-09-14 09:22:59 +000063using namespace llvm;
Chandler Carruth29a18a42015-09-12 09:09:14 +000064using namespace llvm::sroa;
Chandler Carruth1b398ae2012-09-14 09:22:59 +000065
Chandler Carruth964daaa2014-04-22 02:55:47 +000066#define DEBUG_TYPE "sroa"
67
Chandler Carruth1b398ae2012-09-14 09:22:59 +000068STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000069STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +000070STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
71STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
72STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000073STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
74STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000075STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000076STATISTIC(NumDeleted, "Number of instructions deleted");
77STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000078
Chandler Carruth83cee772014-02-25 03:59:29 +000079/// Hidden option to enable randomly shuffling the slices to help uncover
80/// instability in their order.
81static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
82 cl::init(false), cl::Hidden);
83
Chandler Carruth3b79b2a2014-02-25 21:24:45 +000084/// Hidden option to experiment with completely strict handling of inbounds
85/// GEPs.
Chandler Carruth113dc642014-12-20 02:39:18 +000086static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
87 cl::Hidden);
Chandler Carruth3b79b2a2014-02-25 21:24:45 +000088
Chandler Carruth1b398ae2012-09-14 09:22:59 +000089namespace {
Mehdi Amini1e9c9252016-03-11 17:15:34 +000090/// \brief A custom IRBuilder inserter which prefixes all names, but only in
91/// Assert builds.
Mehdi Aminiba9fba82016-03-13 21:05:13 +000092class IRBuilderPrefixedInserter : public IRBuilderDefaultInserter {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000093 std::string Prefix;
Mehdi Amini1e9c9252016-03-11 17:15:34 +000094 const Twine getNameWithPrefix(const Twine &Name) const {
95 return Name.isTriviallyEmpty() ? Name : Prefix + Name;
96 }
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000097
98public:
99 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
100
101protected:
102 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
103 BasicBlock::iterator InsertPt) const {
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000104 IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name), BB,
105 InsertPt);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000106 }
107};
108
Chandler Carruthd177f862013-03-20 07:30:36 +0000109/// \brief Provide a typedef for IRBuilder that drops names in release builds.
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000110using IRBuilderTy = llvm::IRBuilder<ConstantFolder, IRBuilderPrefixedInserter>;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000111}
Chandler Carruthd177f862013-03-20 07:30:36 +0000112
113namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000114/// \brief A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000115///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000116/// This structure represents a slice of an alloca used by some instruction. It
117/// stores both the begin and end offsets of this use, a pointer to the use
118/// itself, and a flag indicating whether we can classify the use as splittable
119/// or not when forming partitions of the alloca.
120class Slice {
Chandler Carruthf74654d2013-03-18 08:36:46 +0000121 /// \brief The beginning offset of the range.
122 uint64_t BeginOffset;
123
124 /// \brief The ending offset, not included in the range.
125 uint64_t EndOffset;
126
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000127 /// \brief Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000128 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000129 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000130
131public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000132 Slice() : BeginOffset(), EndOffset() {}
133 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000134 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000135 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000136
137 uint64_t beginOffset() const { return BeginOffset; }
138 uint64_t endOffset() const { return EndOffset; }
139
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000140 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
141 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000142
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000143 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000144
Craig Topperf40110f2014-04-25 05:29:35 +0000145 bool isDead() const { return getUse() == nullptr; }
146 void kill() { UseAndIsSplittable.setPointer(nullptr); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000147
148 /// \brief Support for ordering ranges.
149 ///
150 /// This provides an ordering over ranges such that start offsets are
151 /// always increasing, and within equal start offsets, the end offsets are
152 /// decreasing. Thus the spanning range comes first in a cluster with the
153 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000154 bool operator<(const Slice &RHS) const {
Chandler Carruth113dc642014-12-20 02:39:18 +0000155 if (beginOffset() < RHS.beginOffset())
156 return true;
157 if (beginOffset() > RHS.beginOffset())
158 return false;
159 if (isSplittable() != RHS.isSplittable())
160 return !isSplittable();
161 if (endOffset() > RHS.endOffset())
162 return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000163 return false;
164 }
165
166 /// \brief Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000167 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000168 uint64_t RHSOffset) {
169 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000170 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000171 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000172 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000173 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000174 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000175
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000176 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000177 return isSplittable() == RHS.isSplittable() &&
178 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000179 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000180 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000181};
Chandler Carruthf0546402013-07-18 07:15:00 +0000182} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000183
184namespace llvm {
Chandler Carruthf0546402013-07-18 07:15:00 +0000185template <typename T> struct isPodLike;
Chandler Carruth113dc642014-12-20 02:39:18 +0000186template <> struct isPodLike<Slice> { static const bool value = true; };
Chandler Carruthf74654d2013-03-18 08:36:46 +0000187}
188
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000189/// \brief Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000190///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000191/// This class represents the slices of an alloca which are formed by its
192/// various uses. If a pointer escapes, we can't fully build a representation
193/// for the slices used and we reflect that in this structure. The uses are
194/// stored, sorted by increasing beginning offset and with unsplittable slices
195/// starting at a particular offset before splittable slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000196class llvm::sroa::AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000197public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000198 /// \brief Construct the slices of a particular alloca.
199 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000200
201 /// \brief Test whether a pointer to the allocation escapes our analysis.
202 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000203 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000204 /// ignored.
205 bool isEscaped() const { return PointerEscapingInstr; }
206
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000207 /// \brief Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000208 /// @{
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000209 typedef SmallVectorImpl<Slice>::iterator iterator;
Chandler Carruthc659df92014-10-16 20:24:07 +0000210 typedef iterator_range<iterator> range;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000211 iterator begin() { return Slices.begin(); }
212 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000213
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000214 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
Chandler Carruthc659df92014-10-16 20:24:07 +0000215 typedef iterator_range<const_iterator> const_range;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000216 const_iterator begin() const { return Slices.begin(); }
217 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000218 /// @}
219
Chandler Carruth0715cba2015-01-01 11:54:38 +0000220 /// \brief Erase a range of slices.
Chandler Carruth994cde82015-01-01 12:01:03 +0000221 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
Chandler Carruth0715cba2015-01-01 11:54:38 +0000222
223 /// \brief Insert new slices for this alloca.
224 ///
225 /// This moves the slices into the alloca's slices collection, and re-sorts
226 /// everything so that the usual ordering properties of the alloca's slices
227 /// hold.
228 void insert(ArrayRef<Slice> NewSlices) {
229 int OldSize = Slices.size();
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000230 Slices.append(NewSlices.begin(), NewSlices.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +0000231 auto SliceI = Slices.begin() + OldSize;
232 std::sort(SliceI, Slices.end());
233 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
234 }
235
Chandler Carruth29a18a42015-09-12 09:09:14 +0000236 // Forward declare the iterator and range accessor for walking the
237 // partitions.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000238 class partition_iterator;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000239 iterator_range<partition_iterator> partitions();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000240
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000241 /// \brief Access the dead users for this alloca.
242 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000243
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000244 /// \brief Access the dead operands referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000245 ///
246 /// These are operands which have cannot actually be used to refer to the
247 /// alloca as they are outside its range and the user doesn't correct for
248 /// that. These mostly consist of PHI node inputs and the like which we just
249 /// need to replace with undef.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000250 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000251
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000252#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000253 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000254 void printSlice(raw_ostream &OS, const_iterator I,
255 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000256 void printUse(raw_ostream &OS, const_iterator I,
257 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000258 void print(raw_ostream &OS) const;
Alp Tokerf929e092014-01-04 22:47:48 +0000259 void dump(const_iterator I) const;
260 void dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000261#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000262
263private:
264 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000265 class SliceBuilder;
266 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000267
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000268#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000269 /// \brief Handle to alloca instruction to simplify method interfaces.
270 AllocaInst &AI;
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000271#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000272
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000273 /// \brief The instruction responsible for this alloca not having a known set
274 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000275 ///
276 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000277 /// store a pointer to that here and abort trying to form slices of the
278 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000279 Instruction *PointerEscapingInstr;
280
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000281 /// \brief The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000282 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000283 /// We store a vector of the slices formed by uses of the alloca here. This
284 /// vector is sorted by increasing begin offset, and then the unsplittable
285 /// slices before the splittable ones. See the Slice inner class for more
286 /// details.
287 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000288
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000289 /// \brief Instructions which will become dead if we rewrite the alloca.
290 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000291 /// Note that these are not separated by slice. This is because we expect an
292 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
293 /// all these instructions can simply be removed and replaced with undef as
294 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000295 SmallVector<Instruction *, 8> DeadUsers;
296
297 /// \brief Operands which will become dead if we rewrite the alloca.
298 ///
299 /// These are operands that in their particular use can be replaced with
300 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
301 /// to PHI nodes and the like. They aren't entirely dead (there might be
302 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
303 /// want to swap this particular input for undef to simplify the use lists of
304 /// the alloca.
305 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000306};
Chandler Carruth29a18a42015-09-12 09:09:14 +0000307
308/// \brief A partition of the slices.
309///
310/// An ephemeral representation for a range of slices which can be viewed as
311/// a partition of the alloca. This range represents a span of the alloca's
312/// memory which cannot be split, and provides access to all of the slices
313/// overlapping some part of the partition.
314///
315/// Objects of this type are produced by traversing the alloca's slices, but
316/// are only ephemeral and not persistent.
317class llvm::sroa::Partition {
318private:
319 friend class AllocaSlices;
320 friend class AllocaSlices::partition_iterator;
321
322 typedef AllocaSlices::iterator iterator;
323
324 /// \brief The beginning and ending offsets of the alloca for this
325 /// partition.
326 uint64_t BeginOffset, EndOffset;
327
328 /// \brief The start end end iterators of this partition.
329 iterator SI, SJ;
330
331 /// \brief A collection of split slice tails overlapping the partition.
332 SmallVector<Slice *, 4> SplitTails;
333
334 /// \brief Raw constructor builds an empty partition starting and ending at
335 /// the given iterator.
336 Partition(iterator SI) : SI(SI), SJ(SI) {}
337
338public:
339 /// \brief The start offset of this partition.
340 ///
341 /// All of the contained slices start at or after this offset.
342 uint64_t beginOffset() const { return BeginOffset; }
343
344 /// \brief The end offset of this partition.
345 ///
346 /// All of the contained slices end at or before this offset.
347 uint64_t endOffset() const { return EndOffset; }
348
349 /// \brief The size of the partition.
350 ///
351 /// Note that this can never be zero.
352 uint64_t size() const {
353 assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
354 return EndOffset - BeginOffset;
355 }
356
357 /// \brief Test whether this partition contains no slices, and merely spans
358 /// a region occupied by split slices.
359 bool empty() const { return SI == SJ; }
360
361 /// \name Iterate slices that start within the partition.
362 /// These may be splittable or unsplittable. They have a begin offset >= the
363 /// partition begin offset.
364 /// @{
365 // FIXME: We should probably define a "concat_iterator" helper and use that
366 // to stitch together pointee_iterators over the split tails and the
367 // contiguous iterators of the partition. That would give a much nicer
368 // interface here. We could then additionally expose filtered iterators for
369 // split, unsplit, and unsplittable splices based on the usage patterns.
370 iterator begin() const { return SI; }
371 iterator end() const { return SJ; }
372 /// @}
373
374 /// \brief Get the sequence of split slice tails.
375 ///
376 /// These tails are of slices which start before this partition but are
377 /// split and overlap into the partition. We accumulate these while forming
378 /// partitions.
379 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
380};
381
382/// \brief An iterator over partitions of the alloca's slices.
383///
384/// This iterator implements the core algorithm for partitioning the alloca's
385/// slices. It is a forward iterator as we don't support backtracking for
386/// efficiency reasons, and re-use a single storage area to maintain the
387/// current set of split slices.
388///
389/// It is templated on the slice iterator type to use so that it can operate
390/// with either const or non-const slice iterators.
391class AllocaSlices::partition_iterator
392 : public iterator_facade_base<partition_iterator, std::forward_iterator_tag,
393 Partition> {
394 friend class AllocaSlices;
395
396 /// \brief Most of the state for walking the partitions is held in a class
397 /// with a nice interface for examining them.
398 Partition P;
399
400 /// \brief We need to keep the end of the slices to know when to stop.
401 AllocaSlices::iterator SE;
402
403 /// \brief We also need to keep track of the maximum split end offset seen.
404 /// FIXME: Do we really?
405 uint64_t MaxSplitSliceEndOffset;
406
407 /// \brief Sets the partition to be empty at given iterator, and sets the
408 /// end iterator.
409 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
410 : P(SI), SE(SE), MaxSplitSliceEndOffset(0) {
411 // If not already at the end, advance our state to form the initial
412 // partition.
413 if (SI != SE)
414 advance();
415 }
416
417 /// \brief Advance the iterator to the next partition.
418 ///
419 /// Requires that the iterator not be at the end of the slices.
420 void advance() {
421 assert((P.SI != SE || !P.SplitTails.empty()) &&
422 "Cannot advance past the end of the slices!");
423
424 // Clear out any split uses which have ended.
425 if (!P.SplitTails.empty()) {
426 if (P.EndOffset >= MaxSplitSliceEndOffset) {
427 // If we've finished all splits, this is easy.
428 P.SplitTails.clear();
429 MaxSplitSliceEndOffset = 0;
430 } else {
431 // Remove the uses which have ended in the prior partition. This
432 // cannot change the max split slice end because we just checked that
433 // the prior partition ended prior to that max.
434 P.SplitTails.erase(
David Majnemer0a16c222016-08-11 21:15:00 +0000435 remove_if(P.SplitTails,
436 [&](Slice *S) { return S->endOffset() <= P.EndOffset; }),
Chandler Carruth29a18a42015-09-12 09:09:14 +0000437 P.SplitTails.end());
David Majnemer0a16c222016-08-11 21:15:00 +0000438 assert(any_of(P.SplitTails,
439 [&](Slice *S) {
440 return S->endOffset() == MaxSplitSliceEndOffset;
441 }) &&
Chandler Carruth29a18a42015-09-12 09:09:14 +0000442 "Could not find the current max split slice offset!");
David Majnemer0a16c222016-08-11 21:15:00 +0000443 assert(all_of(P.SplitTails,
444 [&](Slice *S) {
445 return S->endOffset() <= MaxSplitSliceEndOffset;
446 }) &&
Chandler Carruth29a18a42015-09-12 09:09:14 +0000447 "Max split slice end offset is not actually the max!");
448 }
449 }
450
451 // If P.SI is already at the end, then we've cleared the split tail and
452 // now have an end iterator.
453 if (P.SI == SE) {
454 assert(P.SplitTails.empty() && "Failed to clear the split slices!");
455 return;
456 }
457
458 // If we had a non-empty partition previously, set up the state for
459 // subsequent partitions.
460 if (P.SI != P.SJ) {
461 // Accumulate all the splittable slices which started in the old
462 // partition into the split list.
463 for (Slice &S : P)
464 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
465 P.SplitTails.push_back(&S);
466 MaxSplitSliceEndOffset =
467 std::max(S.endOffset(), MaxSplitSliceEndOffset);
468 }
469
470 // Start from the end of the previous partition.
471 P.SI = P.SJ;
472
473 // If P.SI is now at the end, we at most have a tail of split slices.
474 if (P.SI == SE) {
475 P.BeginOffset = P.EndOffset;
476 P.EndOffset = MaxSplitSliceEndOffset;
477 return;
478 }
479
480 // If the we have split slices and the next slice is after a gap and is
481 // not splittable immediately form an empty partition for the split
482 // slices up until the next slice begins.
483 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
484 !P.SI->isSplittable()) {
485 P.BeginOffset = P.EndOffset;
486 P.EndOffset = P.SI->beginOffset();
487 return;
488 }
489 }
490
491 // OK, we need to consume new slices. Set the end offset based on the
492 // current slice, and step SJ past it. The beginning offset of the
493 // partition is the beginning offset of the next slice unless we have
494 // pre-existing split slices that are continuing, in which case we begin
495 // at the prior end offset.
496 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
497 P.EndOffset = P.SI->endOffset();
498 ++P.SJ;
499
500 // There are two strategies to form a partition based on whether the
501 // partition starts with an unsplittable slice or a splittable slice.
502 if (!P.SI->isSplittable()) {
503 // When we're forming an unsplittable region, it must always start at
504 // the first slice and will extend through its end.
505 assert(P.BeginOffset == P.SI->beginOffset());
506
507 // Form a partition including all of the overlapping slices with this
508 // unsplittable slice.
509 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
510 if (!P.SJ->isSplittable())
511 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
512 ++P.SJ;
513 }
514
515 // We have a partition across a set of overlapping unsplittable
516 // partitions.
517 return;
518 }
519
520 // If we're starting with a splittable slice, then we need to form
521 // a synthetic partition spanning it and any other overlapping splittable
522 // splices.
523 assert(P.SI->isSplittable() && "Forming a splittable partition!");
524
525 // Collect all of the overlapping splittable slices.
526 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
527 P.SJ->isSplittable()) {
528 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
529 ++P.SJ;
530 }
531
532 // Back upiP.EndOffset if we ended the span early when encountering an
533 // unsplittable slice. This synthesizes the early end offset of
534 // a partition spanning only splittable slices.
535 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
536 assert(!P.SJ->isSplittable());
537 P.EndOffset = P.SJ->beginOffset();
538 }
539 }
540
541public:
542 bool operator==(const partition_iterator &RHS) const {
543 assert(SE == RHS.SE &&
544 "End iterators don't match between compared partition iterators!");
545
546 // The observed positions of partitions is marked by the P.SI iterator and
547 // the emptiness of the split slices. The latter is only relevant when
548 // P.SI == SE, as the end iterator will additionally have an empty split
549 // slices list, but the prior may have the same P.SI and a tail of split
550 // slices.
551 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
552 assert(P.SJ == RHS.P.SJ &&
553 "Same set of slices formed two different sized partitions!");
554 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
555 "Same slice position with differently sized non-empty split "
556 "slice tails!");
557 return true;
558 }
559 return false;
560 }
561
562 partition_iterator &operator++() {
563 advance();
564 return *this;
565 }
566
567 Partition &operator*() { return P; }
568};
569
570/// \brief A forward range over the partitions of the alloca's slices.
571///
572/// This accesses an iterator range over the partitions of the alloca's
573/// slices. It computes these partitions on the fly based on the overlapping
574/// offsets of the slices and the ability to split them. It will visit "empty"
575/// partitions to cover regions of the alloca only accessed via split
576/// slices.
577iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() {
578 return make_range(partition_iterator(begin(), end()),
579 partition_iterator(end(), end()));
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000580}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000581
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000582static Value *foldSelectInst(SelectInst &SI) {
583 // If the condition being selected on is a constant or the same value is
584 // being selected between, fold the select. Yes this does (rarely) happen
585 // early on.
586 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
Chandler Carruth113dc642014-12-20 02:39:18 +0000587 return SI.getOperand(1 + CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000588 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000589 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000590
Craig Topperf40110f2014-04-25 05:29:35 +0000591 return nullptr;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000592}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000593
Jingyue Wuec33fa92014-08-22 22:45:57 +0000594/// \brief A helper that folds a PHI node or a select.
595static Value *foldPHINodeOrSelectInst(Instruction &I) {
596 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
597 // If PN merges together the same value, return that value.
598 return PN->hasConstantValue();
599 }
600 return foldSelectInst(cast<SelectInst>(I));
601}
602
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000603/// \brief Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000604///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000605/// This class builds a set of alloca slices by recursively visiting the uses
606/// of an alloca and making a slice for each load and store at each offset.
607class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
608 friend class PtrUseVisitor<SliceBuilder>;
609 friend class InstVisitor<SliceBuilder>;
610 typedef PtrUseVisitor<SliceBuilder> Base;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000611
612 const uint64_t AllocSize;
Chandler Carruth83934062014-10-16 21:11:55 +0000613 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000614
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000615 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000616 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
617
618 /// \brief Set to de-duplicate dead instructions found in the use walk.
619 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000620
621public:
Chandler Carruth83934062014-10-16 21:11:55 +0000622 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000623 : PtrUseVisitor<SliceBuilder>(DL),
Chandler Carruth83934062014-10-16 21:11:55 +0000624 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000625
626private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000627 void markAsDead(Instruction &I) {
David Blaikie70573dc2014-11-19 07:49:26 +0000628 if (VisitedDeadInsts.insert(&I).second)
Chandler Carruth83934062014-10-16 21:11:55 +0000629 AS.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000630 }
631
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000632 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000633 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000634 // Completely skip uses which have a zero size or start either before or
635 // past the end of the allocation.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000636 if (Size == 0 || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000637 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000638 << " which has zero size or starts outside of the "
639 << AllocSize << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000640 << " alloca: " << AS.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000641 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000642 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000643 }
644
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000645 uint64_t BeginOffset = Offset.getZExtValue();
646 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000647
648 // Clamp the end offset to the end of the allocation. Note that this is
649 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000650 // This may appear superficially to be something we could ignore entirely,
651 // but that is not so! There may be widened loads or PHI-node uses where
652 // some instructions are dead but not others. We can't completely ignore
653 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000654 assert(AllocSize >= BeginOffset); // Established above.
655 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000656 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
657 << " to remain within the " << AllocSize << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000658 << " alloca: " << AS.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000659 << " use: " << I << "\n");
660 EndOffset = AllocSize;
661 }
662
Chandler Carruth83934062014-10-16 21:11:55 +0000663 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000664 }
665
666 void visitBitCastInst(BitCastInst &BC) {
667 if (BC.use_empty())
668 return markAsDead(BC);
669
670 return Base::visitBitCastInst(BC);
671 }
672
673 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
674 if (GEPI.use_empty())
675 return markAsDead(GEPI);
676
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000677 if (SROAStrictInbounds && GEPI.isInBounds()) {
678 // FIXME: This is a manually un-factored variant of the basic code inside
679 // of GEPs with checking of the inbounds invariant specified in the
680 // langref in a very strict sense. If we ever want to enable
681 // SROAStrictInbounds, this code should be factored cleanly into
682 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
Hal Finkel5c83a092016-03-28 11:23:21 +0000683 // by writing out the code here where we have the underlying allocation
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000684 // size readily available.
685 APInt GEPOffset = Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000686 const DataLayout &DL = GEPI.getModule()->getDataLayout();
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000687 for (gep_type_iterator GTI = gep_type_begin(GEPI),
688 GTE = gep_type_end(GEPI);
689 GTI != GTE; ++GTI) {
690 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
691 if (!OpC)
692 break;
693
694 // Handle a struct index, which adds its field offset to the pointer.
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000695 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000696 unsigned ElementIdx = OpC->getZExtValue();
697 const StructLayout *SL = DL.getStructLayout(STy);
698 GEPOffset +=
699 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
700 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +0000701 // For array or vector indices, scale the index by the size of the
702 // type.
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000703 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
704 GEPOffset += Index * APInt(Offset.getBitWidth(),
705 DL.getTypeAllocSize(GTI.getIndexedType()));
706 }
707
708 // If this index has computed an intermediate pointer which is not
709 // inbounds, then the result of the GEP is a poison value and we can
710 // delete it and all uses.
711 if (GEPOffset.ugt(AllocSize))
712 return markAsDead(GEPI);
713 }
714 }
715
Chandler Carruthf0546402013-07-18 07:15:00 +0000716 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000717 }
718
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000719 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000720 uint64_t Size, bool IsVolatile) {
Chandler Carruth24ac8302015-01-02 03:55:54 +0000721 // We allow splitting of non-volatile loads and stores where the type is an
722 // integer type. These may be used to implement 'memcpy' or other "transfer
723 // of bits" patterns.
724 bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
Chandler Carruth58d05562012-10-25 04:37:07 +0000725
726 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000727 }
728
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000729 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000730 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
731 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000732
733 if (!IsOffsetKnown)
734 return PI.setAborted(&LI);
735
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000736 const DataLayout &DL = LI.getModule()->getDataLayout();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000737 uint64_t Size = DL.getTypeStoreSize(LI.getType());
738 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000739 }
740
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000741 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000742 Value *ValOp = SI.getValueOperand();
743 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000744 return PI.setEscapedAndAborted(&SI);
745 if (!IsOffsetKnown)
746 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000747
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000748 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000749 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
750
751 // If this memory access can be shown to *statically* extend outside the
752 // bounds of of the allocation, it's behavior is undefined, so simply
753 // ignore it. Note that this is more strict than the generic clamping
754 // behavior of insertUse. We also try to handle cases which might run the
755 // risk of overflow.
756 // FIXME: We should instead consider the pointer to have escaped if this
757 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000758 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000759 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
760 << " which extends past the end of the " << AllocSize
761 << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000762 << " alloca: " << AS.AI << "\n"
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000763 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000764 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000765 }
766
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000767 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
768 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000769 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000770 }
771
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000772 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000773 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000774 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000775 if ((Length && Length->getValue() == 0) ||
Chandler Carruth6aedc102014-02-26 03:14:14 +0000776 (IsOffsetKnown && Offset.uge(AllocSize)))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000777 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000778 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000779
780 if (!IsOffsetKnown)
781 return PI.setAborted(&II);
782
Chandler Carruth113dc642014-12-20 02:39:18 +0000783 insertUse(II, Offset, Length ? Length->getLimitedValue()
784 : AllocSize - Offset.getLimitedValue(),
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000785 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000786 }
787
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000788 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000789 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000790 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000791 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000792 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000793
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000794 // Because we can visit these intrinsics twice, also check to see if the
795 // first time marked this instruction as dead. If so, skip it.
796 if (VisitedDeadInsts.count(&II))
797 return;
798
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000799 if (!IsOffsetKnown)
800 return PI.setAborted(&II);
801
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000802 // This side of the transfer is completely out-of-bounds, and so we can
803 // nuke the entire transfer. However, we also need to nuke the other side
804 // if already added to our partitions.
805 // FIXME: Yet another place we really should bypass this when
806 // instrumenting for ASan.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000807 if (Offset.uge(AllocSize)) {
Chandler Carruth113dc642014-12-20 02:39:18 +0000808 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
809 MemTransferSliceMap.find(&II);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000810 if (MTPI != MemTransferSliceMap.end())
Chandler Carruth83934062014-10-16 21:11:55 +0000811 AS.Slices[MTPI->second].kill();
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000812 return markAsDead(II);
813 }
814
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000815 uint64_t RawOffset = Offset.getLimitedValue();
Chandler Carruth113dc642014-12-20 02:39:18 +0000816 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000817
Chandler Carruthf0546402013-07-18 07:15:00 +0000818 // Check for the special case where the same exact value is used for both
819 // source and dest.
820 if (*U == II.getRawDest() && *U == II.getRawSource()) {
821 // For non-volatile transfers this is a no-op.
822 if (!II.isVolatile())
823 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000824
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000825 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000826 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000827
Chandler Carruthf0546402013-07-18 07:15:00 +0000828 // If we have seen both source and destination for a mem transfer, then
829 // they both point to the same alloca.
830 bool Inserted;
831 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000832 std::tie(MTPI, Inserted) =
Chandler Carruth83934062014-10-16 21:11:55 +0000833 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000834 unsigned PrevIdx = MTPI->second;
835 if (!Inserted) {
Chandler Carruth83934062014-10-16 21:11:55 +0000836 Slice &PrevP = AS.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000837
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000838 // Check if the begin offsets match and this is a non-volatile transfer.
839 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000840 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
841 PrevP.kill();
842 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000843 }
844
845 // Otherwise we have an offset transfer within the same alloca. We can't
846 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000847 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000848 }
849
Chandler Carruthe3899f22013-07-15 17:36:21 +0000850 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000851 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000852
Chandler Carruthf0546402013-07-18 07:15:00 +0000853 // Check that we ended up with a valid index in the map.
Chandler Carruth83934062014-10-16 21:11:55 +0000854 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000855 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000856 }
857
858 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000859 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000860 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000861 void visitIntrinsicInst(IntrinsicInst &II) {
862 if (!IsOffsetKnown)
863 return PI.setAborted(&II);
864
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000865 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
866 II.getIntrinsicID() == Intrinsic::lifetime_end) {
867 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000868 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
869 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000870 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000871 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000872 }
873
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000874 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000875 }
876
877 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
878 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000879 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000880 // are considered unsplittable and the size is the maximum loaded or stored
881 // size.
882 SmallPtrSet<Instruction *, 4> Visited;
883 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
884 Visited.insert(Root);
885 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000886 const DataLayout &DL = Root->getModule()->getDataLayout();
Chandler Carruth8b907e82012-09-25 10:03:40 +0000887 // If there are no loads or stores, the access is dead. We mark that as
888 // a size zero access.
889 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000890 do {
891 Instruction *I, *UsedI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000892 std::tie(UsedI, I) = Uses.pop_back_val();
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000893
894 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000895 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000896 continue;
897 }
898 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
899 Value *Op = SI->getOperand(0);
900 if (Op == UsedI)
901 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000902 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000903 continue;
904 }
905
906 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
907 if (!GEP->hasAllZeroIndices())
908 return GEP;
909 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
910 !isa<SelectInst>(I)) {
911 return I;
912 }
913
Chandler Carruthcdf47882014-03-09 03:16:01 +0000914 for (User *U : I->users())
David Blaikie70573dc2014-11-19 07:49:26 +0000915 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000916 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000917 } while (!Uses.empty());
918
Craig Topperf40110f2014-04-25 05:29:35 +0000919 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000920 }
921
Jingyue Wuec33fa92014-08-22 22:45:57 +0000922 void visitPHINodeOrSelectInst(Instruction &I) {
923 assert(isa<PHINode>(I) || isa<SelectInst>(I));
924 if (I.use_empty())
925 return markAsDead(I);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000926
Jingyue Wuec33fa92014-08-22 22:45:57 +0000927 // TODO: We could use SimplifyInstruction here to fold PHINodes and
928 // SelectInsts. However, doing so requires to change the current
929 // dead-operand-tracking mechanism. For instance, suppose neither loading
930 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
931 // trap either. However, if we simply replace %U with undef using the
932 // current dead-operand-tracking mechanism, "load (select undef, undef,
933 // %other)" may trap because the select may return the first operand
934 // "undef".
935 if (Value *Result = foldPHINodeOrSelectInst(I)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000936 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000937 // If the result of the constant fold will be the pointer, recurse
Jingyue Wuec33fa92014-08-22 22:45:57 +0000938 // through the PHI/select as if we had RAUW'ed it.
939 enqueueUsers(I);
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000940 else
Jingyue Wuec33fa92014-08-22 22:45:57 +0000941 // Otherwise the operand to the PHI/select is dead, and we can replace
942 // it with undef.
Chandler Carruth83934062014-10-16 21:11:55 +0000943 AS.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000944
945 return;
946 }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000947
Chandler Carruthf0546402013-07-18 07:15:00 +0000948 if (!IsOffsetKnown)
Jingyue Wuec33fa92014-08-22 22:45:57 +0000949 return PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000950
Chandler Carruthf0546402013-07-18 07:15:00 +0000951 // See if we already have computed info on this node.
Jingyue Wuec33fa92014-08-22 22:45:57 +0000952 uint64_t &Size = PHIOrSelectSizes[&I];
953 if (!Size) {
954 // This is a new PHI/Select, check for an unsafe use of it.
955 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
Chandler Carruthf0546402013-07-18 07:15:00 +0000956 return PI.setAborted(UnsafeI);
957 }
958
959 // For PHI and select operands outside the alloca, we can't nuke the entire
960 // phi or select -- the other side might still be relevant, so we special
961 // case them here and use a separate structure to track the operands
962 // themselves which should be replaced with undef.
963 // FIXME: This should instead be escaped in the event we're instrumenting
964 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000965 if (Offset.uge(AllocSize)) {
Chandler Carruth83934062014-10-16 21:11:55 +0000966 AS.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +0000967 return;
968 }
969
Jingyue Wuec33fa92014-08-22 22:45:57 +0000970 insertUse(I, Offset, Size);
971 }
972
Chandler Carruth113dc642014-12-20 02:39:18 +0000973 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000974
Chandler Carruth113dc642014-12-20 02:39:18 +0000975 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000976
Chandler Carruthf0546402013-07-18 07:15:00 +0000977 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth113dc642014-12-20 02:39:18 +0000978 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000979};
980
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000981AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000982 :
983#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
984 AI(AI),
985#endif
Craig Topperf40110f2014-04-25 05:29:35 +0000986 PointerEscapingInstr(nullptr) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000987 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000988 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000989 if (PtrI.isEscaped() || PtrI.isAborted()) {
990 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000991 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000992 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
993 : PtrI.getAbortingInst();
994 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000995 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000996 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000997
David Majnemerc7004902016-08-12 04:32:37 +0000998 Slices.erase(remove_if(Slices, [](const Slice &S) { return S.isDead(); }),
Benjamin Kramer08e50702013-07-20 08:38:34 +0000999 Slices.end());
1000
Hal Finkel29f51312016-03-28 11:13:03 +00001001#ifndef NDEBUG
Chandler Carruth83cee772014-02-25 03:59:29 +00001002 if (SROARandomShuffleSlices) {
Pavel Labathc207bec2016-11-09 12:07:12 +00001003 std::mt19937 MT(static_cast<unsigned>(
1004 std::chrono::system_clock::now().time_since_epoch().count()));
Chandler Carruth83cee772014-02-25 03:59:29 +00001005 std::shuffle(Slices.begin(), Slices.end(), MT);
1006 }
1007#endif
1008
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001009 // Sort the uses. This arranges for the offsets to be in ascending order,
1010 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001011 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001012}
1013
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001014#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1015
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001016void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1017 StringRef Indent) const {
1018 printSlice(OS, I, Indent);
Chandler Carruth0715cba2015-01-01 11:54:38 +00001019 OS << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001020 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001021}
1022
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001023void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1024 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001025 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001026 << " slice #" << (I - begin())
Chandler Carruth0715cba2015-01-01 11:54:38 +00001027 << (I->isSplittable() ? " (splittable)" : "");
Chandler Carruthf0546402013-07-18 07:15:00 +00001028}
1029
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001030void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1031 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001032 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001033}
1034
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001035void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001036 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001037 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001038 << " A pointer to this alloca escaped by:\n"
1039 << " " << *PointerEscapingInstr << "\n";
1040 return;
1041 }
1042
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001043 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001044 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001045 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001046}
1047
Alp Tokerf929e092014-01-04 22:47:48 +00001048LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1049 print(dbgs(), I);
1050}
1051LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001052
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001053#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1054
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001055/// Walk the range of a partitioning looking for a common type to cover this
1056/// sequence of slices.
1057static Type *findCommonType(AllocaSlices::const_iterator B,
1058 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001059 uint64_t EndOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001060 Type *Ty = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001061 bool TyIsCommon = true;
Craig Topperf40110f2014-04-25 05:29:35 +00001062 IntegerType *ITy = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001063
1064 // Note that we need to look at *every* alloca slice's Use to ensure we
1065 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001066 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001067 Use *U = I->getUse();
1068 if (isa<IntrinsicInst>(*U->getUser()))
1069 continue;
1070 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1071 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001072
Craig Topperf40110f2014-04-25 05:29:35 +00001073 Type *UserTy = nullptr;
Chandler Carrutha1262002013-11-19 09:03:18 +00001074 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001075 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001076 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001077 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001078 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001079
Chandler Carruth4de31542014-01-21 23:16:05 +00001080 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001081 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001082 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001083 // entity causing the split. Also skip if the type is not a byte width
1084 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001085 if (UserITy->getBitWidth() % 8 != 0 ||
1086 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001087 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001088
Chandler Carruth4de31542014-01-21 23:16:05 +00001089 // Track the largest bitwidth integer type used in this way in case there
1090 // is no common type.
1091 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1092 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001093 }
Duncan P. N. Exon Smith73686d32014-06-17 00:19:35 +00001094
1095 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1096 // depend on types skipped above.
1097 if (!UserTy || (Ty && Ty != UserTy))
1098 TyIsCommon = false; // Give up on anything but an iN type.
1099 else
1100 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001101 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001102
1103 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001104}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001105
Chandler Carruthf0546402013-07-18 07:15:00 +00001106/// PHI instructions that use an alloca and are subsequently loaded can be
1107/// rewritten to load both input pointers in the pred blocks and then PHI the
1108/// results, allowing the load of the alloca to be promoted.
1109/// From this:
1110/// %P2 = phi [i32* %Alloca, i32* %Other]
1111/// %V = load i32* %P2
1112/// to:
1113/// %V1 = load i32* %Alloca -> will be mem2reg'd
1114/// ...
1115/// %V2 = load i32* %Other
1116/// ...
1117/// %V = phi [i32 %V1, i32 %V2]
1118///
1119/// We can do this to a select if its only uses are loads and if the operands
1120/// to the select can be loaded unconditionally.
1121///
1122/// FIXME: This should be hoisted into a generic utility, likely in
1123/// Transforms/Util/Local.h
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001124static bool isSafePHIToSpeculate(PHINode &PN) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001125 // For now, we can only do this promotion if the load is in the same block
1126 // as the PHI, and if there are no stores between the phi and load.
1127 // TODO: Allow recursive phi users.
1128 // TODO: Allow stores.
1129 BasicBlock *BB = PN.getParent();
1130 unsigned MaxAlign = 0;
1131 bool HaveLoad = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001132 for (User *U : PN.users()) {
1133 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001134 if (!LI || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001135 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001136
Chandler Carruthf0546402013-07-18 07:15:00 +00001137 // For now we only allow loads in the same block as the PHI. This is
1138 // a common case that happens when instcombine merges two loads through
1139 // a PHI.
1140 if (LI->getParent() != BB)
1141 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001142
Chandler Carruthf0546402013-07-18 07:15:00 +00001143 // Ensure that there are no instructions between the PHI and the load that
1144 // could store.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001145 for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
Chandler Carruthf0546402013-07-18 07:15:00 +00001146 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001147 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001148
Chandler Carruthf0546402013-07-18 07:15:00 +00001149 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1150 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001151 }
1152
Chandler Carruthf0546402013-07-18 07:15:00 +00001153 if (!HaveLoad)
1154 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001155
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001156 const DataLayout &DL = PN.getModule()->getDataLayout();
1157
Chandler Carruthf0546402013-07-18 07:15:00 +00001158 // We can only transform this if it is safe to push the loads into the
1159 // predecessor blocks. The only thing to watch out for is that we can't put
1160 // a possibly trapping load in the predecessor if it is a critical edge.
1161 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1162 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1163 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001164
Chandler Carruthf0546402013-07-18 07:15:00 +00001165 // If the value is produced by the terminator of the predecessor (an
1166 // invoke) or it has side-effects, there is no valid place to put a load
1167 // in the predecessor.
1168 if (TI == InVal || TI->mayHaveSideEffects())
1169 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001170
Chandler Carruthf0546402013-07-18 07:15:00 +00001171 // If the predecessor has a single successor, then the edge isn't
1172 // critical.
1173 if (TI->getNumSuccessors() == 1)
1174 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001175
Chandler Carruthf0546402013-07-18 07:15:00 +00001176 // If this pointer is always safe to load, or if we can prove that there
1177 // is already a load in the block, then we can move the load to the pred
1178 // block.
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001179 if (isSafeToLoadUnconditionally(InVal, MaxAlign, DL, TI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001180 continue;
1181
1182 return false;
1183 }
1184
1185 return true;
1186}
1187
1188static void speculatePHINodeLoads(PHINode &PN) {
1189 DEBUG(dbgs() << " original: " << PN << "\n");
1190
1191 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1192 IRBuilderTy PHIBuilder(&PN);
1193 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1194 PN.getName() + ".sroa.speculated");
1195
Hal Finkelcc39b672014-07-24 12:16:19 +00001196 // Get the AA tags and alignment to use from one of the loads. It doesn't
Chandler Carruthf0546402013-07-18 07:15:00 +00001197 // matter which one we get and if any differ.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001198 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
Hal Finkelcc39b672014-07-24 12:16:19 +00001199
1200 AAMDNodes AATags;
1201 SomeLoad->getAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001202 unsigned Align = SomeLoad->getAlignment();
1203
1204 // Rewrite all loads of the PN to use the new PHI.
1205 while (!PN.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001206 LoadInst *LI = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001207 LI->replaceAllUsesWith(NewPN);
1208 LI->eraseFromParent();
1209 }
1210
1211 // Inject loads into all of the pred blocks.
1212 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1213 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1214 TerminatorInst *TI = Pred->getTerminator();
1215 Value *InVal = PN.getIncomingValue(Idx);
1216 IRBuilderTy PredBuilder(TI);
1217
1218 LoadInst *Load = PredBuilder.CreateLoad(
1219 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1220 ++NumLoadsSpeculated;
1221 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001222 if (AATags)
1223 Load->setAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001224 NewPN->addIncoming(Load, Pred);
1225 }
1226
1227 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1228 PN.eraseFromParent();
1229}
1230
1231/// Select instructions that use an alloca and are subsequently loaded can be
1232/// rewritten to load both input pointers and then select between the result,
1233/// allowing the load of the alloca to be promoted.
1234/// From this:
1235/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1236/// %V = load i32* %P2
1237/// to:
1238/// %V1 = load i32* %Alloca -> will be mem2reg'd
1239/// %V2 = load i32* %Other
1240/// %V = select i1 %cond, i32 %V1, i32 %V2
1241///
1242/// We can do this to a select if its only uses are loads and if the operand
1243/// to the select can be loaded unconditionally.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001244static bool isSafeSelectToSpeculate(SelectInst &SI) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001245 Value *TValue = SI.getTrueValue();
1246 Value *FValue = SI.getFalseValue();
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001247 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00001248
Chandler Carruthcdf47882014-03-09 03:16:01 +00001249 for (User *U : SI.users()) {
1250 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001251 if (!LI || !LI->isSimple())
Chandler Carruthf0546402013-07-18 07:15:00 +00001252 return false;
1253
1254 // Both operands to the select need to be dereferencable, either
1255 // absolutely (e.g. allocas) or at this point because we can see other
1256 // accesses to it.
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001257 if (!isSafeToLoadUnconditionally(TValue, LI->getAlignment(), DL, LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001258 return false;
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001259 if (!isSafeToLoadUnconditionally(FValue, LI->getAlignment(), DL, LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001260 return false;
1261 }
1262
1263 return true;
1264}
1265
1266static void speculateSelectInstLoads(SelectInst &SI) {
1267 DEBUG(dbgs() << " original: " << SI << "\n");
1268
1269 IRBuilderTy IRB(&SI);
1270 Value *TV = SI.getTrueValue();
1271 Value *FV = SI.getFalseValue();
1272 // Replace the loads of the select with a select of two loads.
1273 while (!SI.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001274 LoadInst *LI = cast<LoadInst>(SI.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001275 assert(LI->isSimple() && "We only speculate simple loads");
1276
1277 IRB.SetInsertPoint(LI);
1278 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001279 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001280 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001281 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001282 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001283
Hal Finkelcc39b672014-07-24 12:16:19 +00001284 // Transfer alignment and AA info if present.
Chandler Carruthf0546402013-07-18 07:15:00 +00001285 TL->setAlignment(LI->getAlignment());
1286 FL->setAlignment(LI->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +00001287
1288 AAMDNodes Tags;
1289 LI->getAAMetadata(Tags);
1290 if (Tags) {
1291 TL->setAAMetadata(Tags);
1292 FL->setAAMetadata(Tags);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001293 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001294
1295 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1296 LI->getName() + ".sroa.speculated");
1297
1298 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1299 LI->replaceAllUsesWith(V);
1300 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001301 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001302 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001303}
1304
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001305/// \brief Build a GEP out of a base pointer and indices.
1306///
1307/// This will return the BasePtr if that is valid, or build a new GEP
1308/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001309static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001310 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001311 if (Indices.empty())
1312 return BasePtr;
1313
1314 // A single zero index is a no-op, so check for this and avoid building a GEP
1315 // in that case.
1316 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1317 return BasePtr;
1318
David Blaikieaa41cd52015-04-03 21:33:42 +00001319 return IRB.CreateInBoundsGEP(nullptr, BasePtr, Indices,
1320 NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001321}
1322
1323/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1324/// TargetTy without changing the offset of the pointer.
1325///
1326/// This routine assumes we've already established a properly offset GEP with
1327/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1328/// zero-indices down through type layers until we find one the same as
1329/// TargetTy. If we can't find one with the same type, we at least try to use
1330/// one with the same size. If none of that works, we just produce the GEP as
1331/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001332static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001333 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001334 SmallVectorImpl<Value *> &Indices,
1335 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001336 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001337 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001338
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001339 // Pointer size to use for the indices.
1340 unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1341
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001342 // See if we can descend into a struct and locate a field with the correct
1343 // type.
1344 unsigned NumLayers = 0;
1345 Type *ElementTy = Ty;
1346 do {
1347 if (ElementTy->isPointerTy())
1348 break;
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001349
1350 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1351 ElementTy = ArrayTy->getElementType();
1352 Indices.push_back(IRB.getIntN(PtrSize, 0));
1353 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1354 ElementTy = VectorTy->getElementType();
1355 Indices.push_back(IRB.getInt32(0));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001356 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001357 if (STy->element_begin() == STy->element_end())
1358 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001359 ElementTy = *STy->element_begin();
1360 Indices.push_back(IRB.getInt32(0));
1361 } else {
1362 break;
1363 }
1364 ++NumLayers;
1365 } while (ElementTy != TargetTy);
1366 if (ElementTy != TargetTy)
1367 Indices.erase(Indices.end() - NumLayers, Indices.end());
1368
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001369 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001370}
1371
1372/// \brief Recursively compute indices for a natural GEP.
1373///
1374/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1375/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001376static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001377 Value *Ptr, Type *Ty, APInt &Offset,
1378 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001379 SmallVectorImpl<Value *> &Indices,
1380 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001381 if (Offset == 0)
Chandler Carruth113dc642014-12-20 02:39:18 +00001382 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1383 NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001384
1385 // We can't recurse through pointer types.
1386 if (Ty->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001387 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001388
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001389 // We try to analyze GEPs over vectors here, but note that these GEPs are
1390 // extremely poorly defined currently. The long-term goal is to remove GEPing
1391 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001392 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001393 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Craig Topperf40110f2014-04-25 05:29:35 +00001394 if (ElementSizeInBits % 8 != 0) {
1395 // GEPs over non-multiple of 8 size vector elements are invalid.
1396 return nullptr;
1397 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001398 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001399 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001400 if (NumSkippedElements.ugt(VecTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001401 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001402 Offset -= NumSkippedElements * ElementSize;
1403 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001404 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001405 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001406 }
1407
1408 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1409 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001410 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001411 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001412 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001413 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001414
1415 Offset -= NumSkippedElements * ElementSize;
1416 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001417 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001418 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001419 }
1420
1421 StructType *STy = dyn_cast<StructType>(Ty);
1422 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00001423 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001424
Chandler Carruth90a735d2013-07-19 07:21:28 +00001425 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001426 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001427 if (StructOffset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00001428 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001429 unsigned Index = SL->getElementContainingOffset(StructOffset);
1430 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1431 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001432 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Craig Topperf40110f2014-04-25 05:29:35 +00001433 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001434
1435 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001436 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001437 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001438}
1439
1440/// \brief Get a natural GEP from a base pointer to a particular offset and
1441/// resulting in a particular type.
1442///
1443/// The goal is to produce a "natural" looking GEP that works with the existing
1444/// composite types to arrive at the appropriate offset and element type for
1445/// a pointer. TargetTy is the element type the returned GEP should point-to if
1446/// possible. We recurse by decreasing Offset, adding the appropriate index to
1447/// Indices, and setting Ty to the result subtype.
1448///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001449/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001450static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001451 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001452 SmallVectorImpl<Value *> &Indices,
1453 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001454 PointerType *Ty = cast<PointerType>(Ptr->getType());
1455
1456 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1457 // an i8.
Chandler Carruth286d87e2014-02-26 08:25:02 +00001458 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +00001459 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001460
1461 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001462 if (!ElementTy->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +00001463 return nullptr; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001464 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001465 if (ElementSize == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001466 return nullptr; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001467 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001468
1469 Offset -= NumSkippedElements * ElementSize;
1470 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001471 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001472 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001473}
1474
1475/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1476/// resulting pointer has PointerTy.
1477///
1478/// This tries very hard to compute a "natural" GEP which arrives at the offset
1479/// and produces the pointer type desired. Where it cannot, it will try to use
1480/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1481/// fails, it will try to use an existing i8* and GEP to the byte offset and
1482/// bitcast to the type.
1483///
1484/// The strategy for finding the more natural GEPs is to peel off layers of the
1485/// pointer, walking back through bit casts and GEPs, searching for a base
1486/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001487/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001488/// a single GEP as possible, thus making each GEP more independent of the
1489/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001490static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
Chandler Carruth113dc642014-12-20 02:39:18 +00001491 APInt Offset, Type *PointerTy, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001492 // Even though we don't look through PHI nodes, we could be called on an
1493 // instruction in an unreachable block, which may be on a cycle.
1494 SmallPtrSet<Value *, 4> Visited;
1495 Visited.insert(Ptr);
1496 SmallVector<Value *, 4> Indices;
1497
1498 // We may end up computing an offset pointer that has the wrong type. If we
1499 // never are able to compute one directly that has the correct type, we'll
Chandler Carruth5986b542015-01-02 02:47:38 +00001500 // fall back to it, so keep it and the base it was computed from around here.
Craig Topperf40110f2014-04-25 05:29:35 +00001501 Value *OffsetPtr = nullptr;
Chandler Carruth5986b542015-01-02 02:47:38 +00001502 Value *OffsetBasePtr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001503
1504 // Remember any i8 pointer we come across to re-use if we need to do a raw
1505 // byte offset.
Craig Topperf40110f2014-04-25 05:29:35 +00001506 Value *Int8Ptr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001507 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1508
1509 Type *TargetTy = PointerTy->getPointerElementType();
1510
1511 do {
1512 // First fold any existing GEPs into the offset.
1513 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1514 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001515 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001516 break;
1517 Offset += GEPOffset;
1518 Ptr = GEP->getPointerOperand();
David Blaikie70573dc2014-11-19 07:49:26 +00001519 if (!Visited.insert(Ptr).second)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001520 break;
1521 }
1522
1523 // See if we can perform a natural GEP here.
1524 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001525 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001526 Indices, NamePrefix)) {
Chandler Carruth5986b542015-01-02 02:47:38 +00001527 // If we have a new natural pointer at the offset, clear out any old
1528 // offset pointer we computed. Unless it is the base pointer or
1529 // a non-instruction, we built a GEP we don't need. Zap it.
1530 if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1531 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1532 assert(I->use_empty() && "Built a GEP with uses some how!");
1533 I->eraseFromParent();
1534 }
1535 OffsetPtr = P;
1536 OffsetBasePtr = Ptr;
1537 // If we also found a pointer of the right type, we're done.
1538 if (P->getType() == PointerTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001539 return P;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001540 }
1541
1542 // Stash this pointer if we've found an i8*.
1543 if (Ptr->getType()->isIntegerTy(8)) {
1544 Int8Ptr = Ptr;
1545 Int8PtrOffset = Offset;
1546 }
1547
1548 // Peel off a layer of the pointer and update the offset appropriately.
1549 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1550 Ptr = cast<Operator>(Ptr)->getOperand(0);
1551 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001552 if (GA->isInterposable())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001553 break;
1554 Ptr = GA->getAliasee();
1555 } else {
1556 break;
1557 }
1558 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +00001559 } while (Visited.insert(Ptr).second);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001560
1561 if (!OffsetPtr) {
1562 if (!Int8Ptr) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00001563 Int8Ptr = IRB.CreateBitCast(
1564 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1565 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001566 Int8PtrOffset = Offset;
1567 }
1568
Chandler Carruth113dc642014-12-20 02:39:18 +00001569 OffsetPtr = Int8PtrOffset == 0
1570 ? Int8Ptr
David Blaikieaa41cd52015-04-03 21:33:42 +00001571 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1572 IRB.getInt(Int8PtrOffset),
Chandler Carruth113dc642014-12-20 02:39:18 +00001573 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001574 }
1575 Ptr = OffsetPtr;
1576
1577 // On the off chance we were targeting i8*, guard the bitcast here.
1578 if (Ptr->getType() != PointerTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001579 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001580
1581 return Ptr;
1582}
1583
Chandler Carruth0715cba2015-01-01 11:54:38 +00001584/// \brief Compute the adjusted alignment for a load or store from an offset.
1585static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
1586 const DataLayout &DL) {
1587 unsigned Alignment;
1588 Type *Ty;
1589 if (auto *LI = dyn_cast<LoadInst>(I)) {
1590 Alignment = LI->getAlignment();
1591 Ty = LI->getType();
1592 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
1593 Alignment = SI->getAlignment();
1594 Ty = SI->getValueOperand()->getType();
1595 } else {
1596 llvm_unreachable("Only loads and stores are allowed!");
1597 }
1598
1599 if (!Alignment)
1600 Alignment = DL.getABITypeAlignment(Ty);
1601
1602 return MinAlign(Alignment, Offset);
1603}
1604
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001605/// \brief Test whether we can convert a value from the old to the new type.
1606///
1607/// This predicate should be used to guard calls to convertValue in order to
1608/// ensure that we only try to convert viable values. The strategy is that we
1609/// will peel off single element struct and array wrappings to get to an
1610/// underlying value, and convert that value.
1611static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1612 if (OldTy == NewTy)
1613 return true;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001614
1615 // For integer types, we can't handle any bit-width differences. This would
1616 // break both vector conversions with extension and introduce endianness
1617 // issues when in conjunction with loads and stores.
1618 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1619 assert(cast<IntegerType>(OldTy)->getBitWidth() !=
1620 cast<IntegerType>(NewTy)->getBitWidth() &&
1621 "We can't have the same bitwidth for different int types");
1622 return false;
1623 }
1624
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001625 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1626 return false;
1627 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1628 return false;
1629
Benjamin Kramer56262592013-09-22 11:24:58 +00001630 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001631 // of pointers and integers.
1632 OldTy = OldTy->getScalarType();
1633 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001634 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
Jack Liuf101c0f2016-05-03 19:30:48 +00001635 if (NewTy->isPointerTy() && OldTy->isPointerTy()) {
1636 return cast<PointerType>(NewTy)->getPointerAddressSpace() ==
1637 cast<PointerType>(OldTy)->getPointerAddressSpace();
1638 }
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001639 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1640 return true;
1641 return false;
1642 }
1643
1644 return true;
1645}
1646
1647/// \brief Generic routine to convert an SSA value to a value of a different
1648/// type.
1649///
1650/// This will try various different casting techniques, such as bitcasts,
1651/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1652/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001653static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001654 Type *NewTy) {
1655 Type *OldTy = V->getType();
1656 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1657
1658 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001659 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001660
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001661 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
1662 "Integer types must be the exact same to convert.");
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001663
Benjamin Kramer90901a32013-09-21 20:36:04 +00001664 // See if we need inttoptr for this type pair. A cast involving both scalars
1665 // and vectors requires and additional bitcast.
1666 if (OldTy->getScalarType()->isIntegerTy() &&
1667 NewTy->getScalarType()->isPointerTy()) {
1668 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1669 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1670 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1671 NewTy);
1672
1673 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1674 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1675 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1676 NewTy);
1677
1678 return IRB.CreateIntToPtr(V, NewTy);
1679 }
1680
1681 // See if we need ptrtoint for this type pair. A cast involving both scalars
1682 // and vectors requires and additional bitcast.
1683 if (OldTy->getScalarType()->isPointerTy() &&
1684 NewTy->getScalarType()->isIntegerTy()) {
1685 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1686 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1687 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1688 NewTy);
1689
1690 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1691 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1692 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1693 NewTy);
1694
1695 return IRB.CreatePtrToInt(V, NewTy);
1696 }
1697
1698 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001699}
1700
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001701/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001702///
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001703/// This function is called to test each entry in a partition which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001704/// for a single slice.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001705static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
1706 VectorType *Ty,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001707 uint64_t ElementSize,
1708 const DataLayout &DL) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001709 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001710 uint64_t BeginOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001711 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001712 uint64_t BeginIndex = BeginOffset / ElementSize;
1713 if (BeginIndex * ElementSize != BeginOffset ||
1714 BeginIndex >= Ty->getNumElements())
1715 return false;
1716 uint64_t EndOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001717 std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001718 uint64_t EndIndex = EndOffset / ElementSize;
1719 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1720 return false;
1721
1722 assert(EndIndex > BeginIndex && "Empty vector!");
1723 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruthc659df92014-10-16 20:24:07 +00001724 Type *SliceTy = (NumElements == 1)
1725 ? Ty->getElementType()
1726 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruthf0546402013-07-18 07:15:00 +00001727
1728 Type *SplitIntTy =
1729 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1730
Chandler Carruthc659df92014-10-16 20:24:07 +00001731 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001732
1733 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1734 if (MI->isVolatile())
1735 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001736 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001737 return false; // Skip any unsplittable intrinsics.
Owen Anderson6c19ab12014-08-07 21:07:35 +00001738 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1739 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1740 II->getIntrinsicID() != Intrinsic::lifetime_end)
1741 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001742 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1743 // Disable vector promotion when there are loads or stores of an FCA.
1744 return false;
1745 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1746 if (LI->isVolatile())
1747 return false;
1748 Type *LTy = LI->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001749 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001750 assert(LTy->isIntegerTy());
1751 LTy = SplitIntTy;
1752 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001753 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001754 return false;
1755 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1756 if (SI->isVolatile())
1757 return false;
1758 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001759 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001760 assert(STy->isIntegerTy());
1761 STy = SplitIntTy;
1762 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001763 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001764 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001765 } else {
1766 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001767 }
1768
1769 return true;
1770}
1771
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001772/// \brief Test whether the given alloca partitioning and range of slices can be
1773/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001774///
1775/// This is a quick test to check whether we can rewrite a particular alloca
1776/// partition (and its newly formed alloca) into a vector alloca with only
1777/// whole-vector loads and stores such that it could be promoted to a vector
1778/// SSA value. We only can ensure this for a limited set of operations, and we
1779/// don't want to do the rewrites unless we are confident that the result will
1780/// be promotable, so we have an early test here.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001781static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001782 // Collect the candidate types for vector-based promotion. Also track whether
1783 // we have different element types.
1784 SmallVector<VectorType *, 4> CandidateTys;
1785 Type *CommonEltTy = nullptr;
1786 bool HaveCommonEltTy = true;
1787 auto CheckCandidateType = [&](Type *Ty) {
1788 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1789 CandidateTys.push_back(VTy);
1790 if (!CommonEltTy)
1791 CommonEltTy = VTy->getElementType();
1792 else if (CommonEltTy != VTy->getElementType())
1793 HaveCommonEltTy = false;
1794 }
1795 };
Chandler Carruth2dc96822014-10-18 00:44:02 +00001796 // Consider any loads or stores that are the exact size of the slice.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001797 for (const Slice &S : P)
1798 if (S.beginOffset() == P.beginOffset() &&
1799 S.endOffset() == P.endOffset()) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001800 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1801 CheckCandidateType(LI->getType());
1802 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1803 CheckCandidateType(SI->getValueOperand()->getType());
1804 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001805
Chandler Carruth2dc96822014-10-18 00:44:02 +00001806 // If we didn't find a vector type, nothing to do here.
1807 if (CandidateTys.empty())
1808 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001809
Chandler Carruth2dc96822014-10-18 00:44:02 +00001810 // Remove non-integer vector types if we had multiple common element types.
1811 // FIXME: It'd be nice to replace them with integer vector types, but we can't
1812 // do that until all the backends are known to produce good code for all
1813 // integer vector types.
1814 if (!HaveCommonEltTy) {
David Majnemerc7004902016-08-12 04:32:37 +00001815 CandidateTys.erase(remove_if(CandidateTys,
1816 [](VectorType *VTy) {
1817 return !VTy->getElementType()->isIntegerTy();
1818 }),
Chandler Carruth2dc96822014-10-18 00:44:02 +00001819 CandidateTys.end());
1820
1821 // If there were no integer vector types, give up.
1822 if (CandidateTys.empty())
1823 return nullptr;
1824
1825 // Rank the remaining candidate vector types. This is easy because we know
1826 // they're all integer vectors. We sort by ascending number of elements.
1827 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
David L. Jones41cecba2017-01-13 21:02:41 +00001828 (void)DL;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001829 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
1830 "Cannot have vector types of different sizes!");
1831 assert(RHSTy->getElementType()->isIntegerTy() &&
1832 "All non-integer types eliminated!");
1833 assert(LHSTy->getElementType()->isIntegerTy() &&
1834 "All non-integer types eliminated!");
1835 return RHSTy->getNumElements() < LHSTy->getNumElements();
1836 };
1837 std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
1838 CandidateTys.erase(
1839 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1840 CandidateTys.end());
1841 } else {
1842// The only way to have the same element type in every vector type is to
1843// have the same vector type. Check that and remove all but one.
1844#ifndef NDEBUG
1845 for (VectorType *VTy : CandidateTys) {
1846 assert(VTy->getElementType() == CommonEltTy &&
1847 "Unaccounted for element type!");
1848 assert(VTy == CandidateTys[0] &&
1849 "Different vector types with the same element type!");
1850 }
1851#endif
1852 CandidateTys.resize(1);
1853 }
1854
1855 // Try each vector type, and return the one which works.
1856 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1857 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
1858
1859 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1860 // that aren't byte sized.
1861 if (ElementSize % 8)
1862 return false;
1863 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
1864 "vector size not a multiple of element size?");
1865 ElementSize /= 8;
1866
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001867 for (const Slice &S : P)
1868 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001869 return false;
1870
Chandler Carruthffb7ce52014-12-24 01:48:09 +00001871 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001872 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001873 return false;
1874
1875 return true;
1876 };
1877 for (VectorType *VTy : CandidateTys)
1878 if (CheckVectorTypeForPromotion(VTy))
1879 return VTy;
1880
1881 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001882}
1883
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001884/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001885///
1886/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001887/// test below on a single slice of the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001888static bool isIntegerWideningViableForSlice(const Slice &S,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001889 uint64_t AllocBeginOffset,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001890 Type *AllocaTy,
1891 const DataLayout &DL,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001892 bool &WholeAllocaOp) {
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001893 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1894
Chandler Carruthc659df92014-10-16 20:24:07 +00001895 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1896 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001897
1898 // We can't reasonably handle cases where the load or store extends past
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001899 // the end of the alloca's type and into its padding.
Chandler Carruthf0546402013-07-18 07:15:00 +00001900 if (RelEnd > Size)
1901 return false;
1902
Chandler Carruthc659df92014-10-16 20:24:07 +00001903 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001904
1905 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1906 if (LI->isVolatile())
1907 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001908 // We can't handle loads that extend past the allocated memory.
1909 if (DL.getTypeStoreSize(LI->getType()) > Size)
1910 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001911 // Note that we don't count vector loads or stores as whole-alloca
1912 // operations which enable integer widening because we would prefer to use
1913 // vector widening instead.
1914 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00001915 WholeAllocaOp = true;
1916 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001917 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001918 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001919 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001920 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001921 // Non-integer loads need to be convertible from the alloca type so that
1922 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001923 return false;
1924 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001925 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1926 Type *ValueTy = SI->getValueOperand()->getType();
1927 if (SI->isVolatile())
1928 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001929 // We can't handle stores that extend past the allocated memory.
1930 if (DL.getTypeStoreSize(ValueTy) > Size)
1931 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001932 // Note that we don't count vector loads or stores as whole-alloca
1933 // operations which enable integer widening because we would prefer to use
1934 // vector widening instead.
1935 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00001936 WholeAllocaOp = true;
1937 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001938 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001939 return false;
1940 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001941 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001942 // Non-integer stores need to be convertible to the alloca type so that
1943 // they are promotable.
1944 return false;
1945 }
1946 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1947 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1948 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001949 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001950 return false; // Skip any unsplittable intrinsics.
1951 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1952 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1953 II->getIntrinsicID() != Intrinsic::lifetime_end)
1954 return false;
1955 } else {
1956 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001957 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001958
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001959 return true;
1960}
1961
Chandler Carruth435c4e02012-10-15 08:40:30 +00001962/// \brief Test whether the given alloca partition's integer operations can be
1963/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00001964///
Chandler Carruth435c4e02012-10-15 08:40:30 +00001965/// This is a quick test to check whether we can rewrite the integer loads and
1966/// stores to a particular alloca into wider loads and stores and be able to
1967/// promote the resulting alloca.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001968static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001969 const DataLayout &DL) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001970 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00001971 // Don't create integer types larger than the maximum bitwidth.
1972 if (SizeInBits > IntegerType::MAX_INT_BITS)
1973 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00001974
1975 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001976 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001977 return false;
1978
Chandler Carruth58d05562012-10-25 04:37:07 +00001979 // We need to ensure that an integer type with the appropriate bitwidth can
1980 // be converted to the alloca type, whatever that is. We don't want to force
1981 // the alloca itself to have an integer type if there is a more suitable one.
1982 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001983 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1984 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00001985 return false;
1986
Chandler Carruthf0546402013-07-18 07:15:00 +00001987 // While examining uses, we ensure that the alloca has a covering load or
1988 // store. We don't want to widen the integer operations only to fail to
1989 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00001990 // later). However, if there are only splittable uses, go ahead and assume
1991 // that we cover the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001992 // FIXME: We shouldn't consider split slices that happen to start in the
1993 // partition here...
Chandler Carruthc659df92014-10-16 20:24:07 +00001994 bool WholeAllocaOp =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001995 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00001996
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001997 for (const Slice &S : P)
1998 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
1999 WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00002000 return false;
2001
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002002 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002003 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2004 WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002005 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002006
Chandler Carruth92924fd2012-09-24 00:34:20 +00002007 return WholeAllocaOp;
2008}
2009
Chandler Carruthd177f862013-03-20 07:30:36 +00002010static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002011 IntegerType *Ty, uint64_t Offset,
2012 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002013 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002014 IntegerType *IntTy = cast<IntegerType>(V->getType());
2015 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2016 "Element extends past full value");
Chandler Carruth113dc642014-12-20 02:39:18 +00002017 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002018 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002019 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002020 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002021 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002022 DEBUG(dbgs() << " shifted: " << *V << "\n");
2023 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002024 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2025 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002026 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002027 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00002028 DEBUG(dbgs() << " trunced: " << *V << "\n");
2029 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002030 return V;
2031}
2032
Chandler Carruthd177f862013-03-20 07:30:36 +00002033static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002034 Value *V, uint64_t Offset, const Twine &Name) {
2035 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2036 IntegerType *Ty = cast<IntegerType>(V->getType());
2037 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2038 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002039 DEBUG(dbgs() << " start: " << *V << "\n");
2040 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002041 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00002042 DEBUG(dbgs() << " extended: " << *V << "\n");
2043 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002044 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2045 "Element store outside of alloca store");
Chandler Carruth113dc642014-12-20 02:39:18 +00002046 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002047 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002048 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002049 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002050 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002051 DEBUG(dbgs() << " shifted: " << *V << "\n");
2052 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002053
2054 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2055 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2056 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00002057 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002058 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00002059 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002060 }
2061 return V;
2062}
2063
Chandler Carruth113dc642014-12-20 02:39:18 +00002064static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2065 unsigned EndIndex, const Twine &Name) {
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002066 VectorType *VecTy = cast<VectorType>(V->getType());
2067 unsigned NumElements = EndIndex - BeginIndex;
2068 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2069
2070 if (NumElements == VecTy->getNumElements())
2071 return V;
2072
2073 if (NumElements == 1) {
2074 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2075 Name + ".extract");
2076 DEBUG(dbgs() << " extract: " << *V << "\n");
2077 return V;
2078 }
2079
Chandler Carruth113dc642014-12-20 02:39:18 +00002080 SmallVector<Constant *, 8> Mask;
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002081 Mask.reserve(NumElements);
2082 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2083 Mask.push_back(IRB.getInt32(i));
2084 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002085 ConstantVector::get(Mask), Name + ".extract");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002086 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2087 return V;
2088}
2089
Chandler Carruthd177f862013-03-20 07:30:36 +00002090static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00002091 unsigned BeginIndex, const Twine &Name) {
2092 VectorType *VecTy = cast<VectorType>(Old->getType());
2093 assert(VecTy && "Can only insert a vector into a vector");
2094
2095 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2096 if (!Ty) {
2097 // Single element to insert.
2098 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2099 Name + ".insert");
Chandler Carruth113dc642014-12-20 02:39:18 +00002100 DEBUG(dbgs() << " insert: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002101 return V;
2102 }
2103
2104 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2105 "Too many elements!");
2106 if (Ty->getNumElements() == VecTy->getNumElements()) {
2107 assert(V->getType() == VecTy && "Vector type mismatch");
2108 return V;
2109 }
2110 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2111
2112 // When inserting a smaller vector into the larger to store, we first
2113 // use a shuffle vector to widen it with undef elements, and then
2114 // a second shuffle vector to select between the loaded vector and the
2115 // incoming vector.
Chandler Carruth113dc642014-12-20 02:39:18 +00002116 SmallVector<Constant *, 8> Mask;
Chandler Carruthce4562b2012-12-17 13:41:21 +00002117 Mask.reserve(VecTy->getNumElements());
2118 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2119 if (i >= BeginIndex && i < EndIndex)
2120 Mask.push_back(IRB.getInt32(i - BeginIndex));
2121 else
2122 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2123 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002124 ConstantVector::get(Mask), Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00002125 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002126
2127 Mask.clear();
2128 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00002129 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2130
2131 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2132
2133 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002134 return V;
2135}
2136
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002137/// \brief Visitor to rewrite instructions using p particular slice of an alloca
2138/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002139///
2140/// Also implements the rewriting to vector-based accesses when the partition
2141/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2142/// lives here.
Chandler Carruth29a18a42015-09-12 09:09:14 +00002143class llvm::sroa::AllocaSliceRewriter
2144 : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002145 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002146 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
2147 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002148
Chandler Carruth90a735d2013-07-19 07:21:28 +00002149 const DataLayout &DL;
Chandler Carruth83934062014-10-16 21:11:55 +00002150 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002151 SROA &Pass;
2152 AllocaInst &OldAI, &NewAI;
2153 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002154 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002155
Chandler Carruth2dc96822014-10-18 00:44:02 +00002156 // This is a convenience and flag variable that will be null unless the new
2157 // alloca's integer operations should be widened to this integer type due to
2158 // passing isIntegerWideningViable above. If it is non-null, the desired
2159 // integer type will be stored here for easy access during rewriting.
2160 IntegerType *IntTy;
2161
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002162 // If we are rewriting an alloca partition which can be written as pure
2163 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002164 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002165 // - The new alloca is exactly the size of the vector type here.
2166 // - The accesses all either map to the entire vector or to a single
2167 // element.
2168 // - The set of accessing instructions is only one of those handled above
2169 // in isVectorPromotionViable. Generally these are the same access kinds
2170 // which are promotable via mem2reg.
2171 VectorType *VecTy;
2172 Type *ElementTy;
2173 uint64_t ElementSize;
2174
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002175 // The original offset of the slice currently being rewritten relative to
2176 // the original alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002177 uint64_t BeginOffset, EndOffset;
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002178 // The new offsets of the slice currently being rewritten relative to the
2179 // original alloca.
2180 uint64_t NewBeginOffset, NewEndOffset;
2181
2182 uint64_t SliceSize;
Chandler Carruthf0546402013-07-18 07:15:00 +00002183 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002184 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002185 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002186 Instruction *OldPtr;
2187
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002188 // Track post-rewrite users which are PHI nodes and Selects.
2189 SmallPtrSetImpl<PHINode *> &PHIUsers;
2190 SmallPtrSetImpl<SelectInst *> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002191
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002192 // Utility IR builder, whose name prefix is setup for each visited use, and
2193 // the insertion point is set to point to the user.
2194 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002195
2196public:
Chandler Carruth83934062014-10-16 21:11:55 +00002197 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002198 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002199 uint64_t NewAllocaBeginOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00002200 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2201 VectorType *PromotableVecTy,
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002202 SmallPtrSetImpl<PHINode *> &PHIUsers,
2203 SmallPtrSetImpl<SelectInst *> &SelectUsers)
Chandler Carruth83934062014-10-16 21:11:55 +00002204 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002205 NewAllocaBeginOffset(NewAllocaBeginOffset),
2206 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002207 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002208 IntTy(IsIntegerPromotable
2209 ? Type::getIntNTy(
2210 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002211 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Craig Topperf40110f2014-04-25 05:29:35 +00002212 : nullptr),
Chandler Carruth2dc96822014-10-18 00:44:02 +00002213 VecTy(PromotableVecTy),
2214 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2215 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00002216 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002217 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002218 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002219 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002220 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002221 "Only multiple-of-8 sized vector elements are viable");
2222 ++NumVectorized;
2223 }
Chandler Carruth2dc96822014-10-18 00:44:02 +00002224 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002225 }
2226
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002227 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002228 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002229 BeginOffset = I->beginOffset();
2230 EndOffset = I->endOffset();
2231 IsSplittable = I->isSplittable();
2232 IsSplit =
2233 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002234 DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2235 DEBUG(AS.printSlice(dbgs(), I, ""));
Chandler Carruth0715cba2015-01-01 11:54:38 +00002236 DEBUG(dbgs() << "\n");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002237
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002238 // Compute the intersecting offset range.
2239 assert(BeginOffset < NewAllocaEndOffset);
2240 assert(EndOffset > NewAllocaBeginOffset);
2241 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2242 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2243
2244 SliceSize = NewEndOffset - NewBeginOffset;
2245
Chandler Carruthf0546402013-07-18 07:15:00 +00002246 OldUse = I->getUse();
2247 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002248
Chandler Carruthf0546402013-07-18 07:15:00 +00002249 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2250 IRB.SetInsertPoint(OldUserI);
2251 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2252 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2253
2254 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2255 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002256 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002257 return CanSROA;
2258 }
2259
2260private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002261 // Make sure the other visit overloads are visible.
2262 using Base::visit;
2263
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002264 // Every instruction which can end up as a user must have a rewrite rule.
2265 bool visitInstruction(Instruction &I) {
2266 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2267 llvm_unreachable("No rewrite rule for this instruction!");
2268 }
2269
Chandler Carruth47954c82014-02-26 05:12:43 +00002270 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2271 // Note that the offset computation can use BeginOffset or NewBeginOffset
2272 // interchangeably for unsplit slices.
2273 assert(IsSplit || BeginOffset == NewBeginOffset);
2274 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2275
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002276#ifndef NDEBUG
2277 StringRef OldName = OldPtr->getName();
2278 // Skip through the last '.sroa.' component of the name.
2279 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2280 if (LastSROAPrefix != StringRef::npos) {
2281 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2282 // Look for an SROA slice index.
2283 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2284 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2285 // Strip the index and look for the offset.
2286 OldName = OldName.substr(IndexEnd + 1);
2287 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2288 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2289 // Strip the offset.
2290 OldName = OldName.substr(OffsetEnd + 1);
2291 }
2292 }
2293 // Strip any SROA suffixes as well.
2294 OldName = OldName.substr(0, OldName.find(".sroa_"));
2295#endif
Chandler Carruth47954c82014-02-26 05:12:43 +00002296
2297 return getAdjustedPtr(IRB, DL, &NewAI,
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002298 APInt(DL.getPointerTypeSizeInBits(PointerTy), Offset),
2299 PointerTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002300#ifndef NDEBUG
2301 Twine(OldName) + "."
2302#else
2303 Twine()
2304#endif
2305 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002306 }
2307
Chandler Carruth113dc642014-12-20 02:39:18 +00002308 /// \brief Compute suitable alignment to access this slice of the *new*
2309 /// alloca.
Chandler Carruth2659e502014-02-26 05:02:19 +00002310 ///
2311 /// You can optionally pass a type to this routine and if that type's ABI
2312 /// alignment is itself suitable, this will return zero.
Craig Topperf40110f2014-04-25 05:29:35 +00002313 unsigned getSliceAlign(Type *Ty = nullptr) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002314 unsigned NewAIAlign = NewAI.getAlignment();
2315 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002316 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth113dc642014-12-20 02:39:18 +00002317 unsigned Align =
2318 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
Chandler Carruth2659e502014-02-26 05:02:19 +00002319 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002320 }
2321
Chandler Carruth845b73c2012-11-21 08:16:30 +00002322 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002323 assert(VecTy && "Can only call getIndex when rewriting a vector");
2324 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2325 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2326 uint32_t Index = RelOffset / ElementSize;
2327 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002328 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002329 }
2330
2331 void deleteIfTriviallyDead(Value *V) {
2332 Instruction *I = cast<Instruction>(V);
2333 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002334 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002335 }
2336
Chandler Carruthea27cf02014-02-26 04:25:04 +00002337 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002338 unsigned BeginIndex = getIndex(NewBeginOffset);
2339 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002340 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002341
Chandler Carruth113dc642014-12-20 02:39:18 +00002342 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002343 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002344 }
2345
Chandler Carruthea27cf02014-02-26 04:25:04 +00002346 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002347 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002348 assert(!LI.isVolatile());
Chandler Carruth113dc642014-12-20 02:39:18 +00002349 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002350 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002351 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2352 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth4b682f62015-08-28 09:03:52 +00002353 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
2354 IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
2355 V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
2356 }
2357 // It is possible that the extracted type is not the load type. This
2358 // happens if there is a load past the end of the alloca, and as
2359 // a consequence the slice is narrower but still a candidate for integer
2360 // lowering. To handle this case, we just zero extend the extracted
2361 // integer.
2362 assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&
2363 "Can only handle an extract for an overly wide load");
2364 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
2365 V = IRB.CreateZExt(V, LI.getType());
Chandler Carruth18db7952012-11-20 01:12:50 +00002366 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002367 }
2368
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002369 bool visitLoadInst(LoadInst &LI) {
2370 DEBUG(dbgs() << " original: " << LI << "\n");
2371 Value *OldOp = LI.getOperand(0);
2372 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002373
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002374 unsigned AS = LI.getPointerAddressSpace();
2375
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002376 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002377 : LI.getType();
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002378 const bool IsLoadPastEnd = DL.getTypeStoreSize(TargetTy) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002379 bool IsPtrAdjusted = false;
2380 Value *V;
2381 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002382 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002383 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002384 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002385 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002386 NewEndOffset == NewAllocaEndOffset &&
2387 (canConvertValue(DL, NewAllocaTy, TargetTy) ||
2388 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
2389 TargetTy->isIntegerTy()))) {
David Majnemer62690b12015-07-14 06:19:58 +00002390 LoadInst *NewLI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2391 LI.isVolatile(), LI.getName());
2392 if (LI.isVolatile())
2393 NewLI->setAtomic(LI.getOrdering(), LI.getSynchScope());
Luqman Aden3f807c92017-03-22 19:16:39 +00002394
2395 // Try to preserve nonnull metadata
2396 if (TargetTy->isPointerTy())
2397 NewLI->copyMetadata(LI, LLVMContext::MD_nonnull);
David Majnemer62690b12015-07-14 06:19:58 +00002398 V = NewLI;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002399
2400 // If this is an integer load past the end of the slice (which means the
2401 // bytes outside the slice are undef or this load is dead) just forcibly
2402 // fix the integer size with correct handling of endianness.
2403 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2404 if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
2405 if (AITy->getBitWidth() < TITy->getBitWidth()) {
2406 V = IRB.CreateZExt(V, TITy, "load.ext");
2407 if (DL.isBigEndian())
2408 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2409 "endian_shift");
2410 }
Chandler Carruth18db7952012-11-20 01:12:50 +00002411 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002412 Type *LTy = TargetTy->getPointerTo(AS);
David Majnemer62690b12015-07-14 06:19:58 +00002413 LoadInst *NewLI = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2414 getSliceAlign(TargetTy),
2415 LI.isVolatile(), LI.getName());
2416 if (LI.isVolatile())
2417 NewLI->setAtomic(LI.getOrdering(), LI.getSynchScope());
2418
2419 V = NewLI;
Chandler Carruth18db7952012-11-20 01:12:50 +00002420 IsPtrAdjusted = true;
2421 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002422 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002423
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002424 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002425 assert(!LI.isVolatile());
2426 assert(LI.getType()->isIntegerTy() &&
2427 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002428 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002429 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002430 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002431 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002432 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002433 // Move the insertion point just past the load so that we can refer to it.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002434 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002435 // Create a placeholder value with the same type as LI to use as the
2436 // basis for the new value. This allows us to replace the uses of LI with
2437 // the computed value, and then replace the placeholder with LI, leaving
2438 // LI only used for this computation.
Chandler Carruth113dc642014-12-20 02:39:18 +00002439 Value *Placeholder =
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002440 new LoadInst(UndefValue::get(LI.getType()->getPointerTo(AS)));
Chandler Carruth24ac8302015-01-02 03:55:54 +00002441 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2442 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002443 LI.replaceAllUsesWith(V);
2444 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002445 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002446 } else {
2447 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002448 }
2449
Chandler Carruth18db7952012-11-20 01:12:50 +00002450 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002451 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002452 DEBUG(dbgs() << " to: " << *V << "\n");
2453 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002454 }
2455
Chandler Carruthea27cf02014-02-26 04:25:04 +00002456 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002457 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002458 unsigned BeginIndex = getIndex(NewBeginOffset);
2459 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002460 assert(EndIndex > BeginIndex && "Empty vector!");
2461 unsigned NumElements = EndIndex - BeginIndex;
2462 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth113dc642014-12-20 02:39:18 +00002463 Type *SliceTy = (NumElements == 1)
2464 ? ElementTy
2465 : VectorType::get(ElementTy, NumElements);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002466 if (V->getType() != SliceTy)
2467 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002468
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002469 // Mix in the existing elements.
Chandler Carruth113dc642014-12-20 02:39:18 +00002470 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002471 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2472 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002473 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002474 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002475
2476 (void)Store;
2477 DEBUG(dbgs() << " to: " << *Store << "\n");
2478 return true;
2479 }
2480
Chandler Carruthea27cf02014-02-26 04:25:04 +00002481 bool rewriteIntegerStore(Value *V, StoreInst &SI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002482 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002483 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002484 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002485 Value *Old =
2486 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002487 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002488 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2489 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth113dc642014-12-20 02:39:18 +00002490 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002491 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002492 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002493 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Dorit Nuzmand1247a62016-09-22 07:56:23 +00002494 Store->copyMetadata(SI, LLVMContext::MD_mem_parallel_loop_access);
Chandler Carruth18db7952012-11-20 01:12:50 +00002495 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002496 DEBUG(dbgs() << " to: " << *Store << "\n");
2497 return true;
2498 }
2499
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002500 bool visitStoreInst(StoreInst &SI) {
2501 DEBUG(dbgs() << " original: " << SI << "\n");
2502 Value *OldOp = SI.getOperand(1);
2503 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002504
Chandler Carruth18db7952012-11-20 01:12:50 +00002505 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002506
Chandler Carruthac8317f2012-10-04 12:33:50 +00002507 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2508 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002509 if (V->getType()->isPointerTy())
2510 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002511 Pass.PostPromotionWorklist.insert(AI);
2512
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002513 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002514 assert(!SI.isVolatile());
2515 assert(V->getType()->isIntegerTy() &&
2516 "Only integer type loads and stores are split");
2517 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002518 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002519 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002520 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth24ac8302015-01-02 03:55:54 +00002521 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2522 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002523 }
2524
Chandler Carruth18db7952012-11-20 01:12:50 +00002525 if (VecTy)
Chandler Carruthea27cf02014-02-26 04:25:04 +00002526 return rewriteVectorizedStoreInst(V, SI, OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002527 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthea27cf02014-02-26 04:25:04 +00002528 return rewriteIntegerStore(V, SI);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002529
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002530 const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002531 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002532 if (NewBeginOffset == NewAllocaBeginOffset &&
2533 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002534 (canConvertValue(DL, V->getType(), NewAllocaTy) ||
2535 (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
2536 V->getType()->isIntegerTy()))) {
2537 // If this is an integer store past the end of slice (and thus the bytes
2538 // past that point are irrelevant or this is unreachable), truncate the
2539 // value prior to storing.
2540 if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
2541 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2542 if (VITy->getBitWidth() > AITy->getBitWidth()) {
2543 if (DL.isBigEndian())
2544 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2545 "endian_shift");
2546 V = IRB.CreateTrunc(V, AITy, "load.trunc");
2547 }
2548
Chandler Carruth90a735d2013-07-19 07:21:28 +00002549 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002550 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2551 SI.isVolatile());
2552 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002553 unsigned AS = SI.getPointerAddressSpace();
2554 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS));
Chandler Carruth2659e502014-02-26 05:02:19 +00002555 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2556 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002557 }
Dorit Nuzmand1247a62016-09-22 07:56:23 +00002558 NewSI->copyMetadata(SI, LLVMContext::MD_mem_parallel_loop_access);
David Majnemer62690b12015-07-14 06:19:58 +00002559 if (SI.isVolatile())
2560 NewSI->setAtomic(SI.getOrdering(), SI.getSynchScope());
Chandler Carruth18db7952012-11-20 01:12:50 +00002561 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002562 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002563
2564 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2565 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002566 }
2567
Chandler Carruth514f34f2012-12-17 04:07:30 +00002568 /// \brief Compute an integer value from splatting an i8 across the given
2569 /// number of bytes.
2570 ///
2571 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2572 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002573 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002574 ///
2575 /// \param V The i8 value to splat.
2576 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002577 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002578 assert(Size > 0 && "Expected a positive number of bytes.");
2579 IntegerType *VTy = cast<IntegerType>(V->getType());
2580 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2581 if (Size == 1)
2582 return V;
2583
Chandler Carruth113dc642014-12-20 02:39:18 +00002584 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2585 V = IRB.CreateMul(
2586 IRB.CreateZExt(V, SplatIntTy, "zext"),
2587 ConstantExpr::getUDiv(
2588 Constant::getAllOnesValue(SplatIntTy),
2589 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2590 SplatIntTy)),
2591 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002592 return V;
2593 }
2594
Chandler Carruthccca5042012-12-17 04:07:37 +00002595 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002596 Value *getVectorSplat(Value *V, unsigned NumElements) {
2597 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002598 DEBUG(dbgs() << " splat: " << *V << "\n");
2599 return V;
2600 }
2601
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002602 bool visitMemSetInst(MemSetInst &II) {
2603 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002604 assert(II.getRawDest() == OldPtr);
2605
2606 // If the memset has a variable size, it cannot be split, just adjust the
2607 // pointer to the new alloca.
2608 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002609 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002610 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002611 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Pete Cooper67cf9a72015-11-19 05:56:52 +00002612 Type *CstTy = II.getAlignmentCst()->getType();
2613 II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002614
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002615 deleteIfTriviallyDead(OldPtr);
2616 return false;
2617 }
2618
2619 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002620 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002621
2622 Type *AllocaTy = NewAI.getAllocatedType();
2623 Type *ScalarTy = AllocaTy->getScalarType();
2624
2625 // If this doesn't map cleanly onto the alloca type, and that type isn't
2626 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002627 if (!VecTy && !IntTy &&
Chandler Carruth113dc642014-12-20 02:39:18 +00002628 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002629 SliceSize != DL.getTypeStoreSize(AllocaTy) ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002630 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002631 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
Chandler Carruth113dc642014-12-20 02:39:18 +00002632 DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002633 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002634 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2635 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002636 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2637 getSliceAlign(), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002638 (void)New;
2639 DEBUG(dbgs() << " to: " << *New << "\n");
2640 return false;
2641 }
2642
2643 // If we can represent this as a simple value, we have to build the actual
2644 // value to store, which requires expanding the byte present in memset to
2645 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002646 // splatting the byte to a sufficiently wide integer, splatting it across
2647 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002648 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002649
Chandler Carruthccca5042012-12-17 04:07:37 +00002650 if (VecTy) {
2651 // If this is a memset of a vectorized alloca, insert it.
2652 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002653
Chandler Carruthf0546402013-07-18 07:15:00 +00002654 unsigned BeginIndex = getIndex(NewBeginOffset);
2655 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002656 assert(EndIndex > BeginIndex && "Empty vector!");
2657 unsigned NumElements = EndIndex - BeginIndex;
2658 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2659
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002660 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002661 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2662 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002663 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002664 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002665
Chandler Carruth113dc642014-12-20 02:39:18 +00002666 Value *Old =
2667 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002668 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002669 } else if (IntTy) {
2670 // If this is a memset on an alloca where we can widen stores, insert the
2671 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002672 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002673
Chandler Carruthf0546402013-07-18 07:15:00 +00002674 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002675 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002676
2677 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2678 EndOffset != NewAllocaBeginOffset)) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002679 Value *Old =
2680 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002681 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002682 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002683 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002684 } else {
2685 assert(V->getType() == IntTy &&
2686 "Wrong type for an alloca wide integer!");
2687 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002688 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002689 } else {
2690 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002691 assert(NewBeginOffset == NewAllocaBeginOffset);
2692 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002693
Chandler Carruth90a735d2013-07-19 07:21:28 +00002694 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002695 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002696 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002697
Chandler Carruth90a735d2013-07-19 07:21:28 +00002698 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002699 }
2700
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002701 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002702 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002703 (void)New;
2704 DEBUG(dbgs() << " to: " << *New << "\n");
2705 return !II.isVolatile();
2706 }
2707
2708 bool visitMemTransferInst(MemTransferInst &II) {
2709 // Rewriting of memory transfer instructions can be a bit tricky. We break
2710 // them into two categories: split intrinsics and unsplit intrinsics.
2711
2712 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002713
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002714 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002715 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002716 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002717
Chandler Carruthaa72b932014-02-26 07:29:54 +00002718 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002719
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002720 // For unsplit intrinsics, we simply modify the source and destination
2721 // pointers in place. This isn't just an optimization, it is a matter of
2722 // correctness. With unsplit intrinsics we may be dealing with transfers
2723 // within a single alloca before SROA ran, or with transfers that have
2724 // a variable length. We may also be dealing with memmove instead of
2725 // memcpy, and so simply updating the pointers is the necessary for us to
2726 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002727 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002728 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Pete Cooper67cf9a72015-11-19 05:56:52 +00002729 if (IsDest)
Chandler Carruth8183a502014-02-25 11:08:02 +00002730 II.setDest(AdjustedPtr);
Pete Cooper67cf9a72015-11-19 05:56:52 +00002731 else
Chandler Carruth8183a502014-02-25 11:08:02 +00002732 II.setSource(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002733
Pete Cooper67cf9a72015-11-19 05:56:52 +00002734 if (II.getAlignment() > SliceAlign) {
2735 Type *CstTy = II.getAlignmentCst()->getType();
2736 II.setAlignment(
2737 ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
Chandler Carruth181ed052014-02-26 05:33:36 +00002738 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002739
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002740 DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002741 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002742 return false;
2743 }
2744 // For split transfer intrinsics we have an incredibly useful assurance:
2745 // the source and destination do not reside within the same alloca, and at
2746 // least one of them does not escape. This means that we can replace
2747 // memmove with memcpy, and we don't need to worry about all manner of
2748 // downsides to splitting and transforming the operations.
2749
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002750 // If this doesn't map cleanly onto the alloca type, and that type isn't
2751 // a single value type, just emit a memcpy.
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002752 bool EmitMemCpy =
2753 !VecTy && !IntTy &&
2754 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2755 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2756 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002757
2758 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2759 // size hasn't been shrunk based on analysis of the viable range, this is
2760 // a no-op.
2761 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002762 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002763 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002764
2765 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002766 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002767 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002768 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002769 return false;
2770 }
2771 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002772 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002773
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002774 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2775 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002776 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth113dc642014-12-20 02:39:18 +00002777 if (AllocaInst *AI =
2778 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002779 assert(AI != &OldAI && AI != &NewAI &&
2780 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002781 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002782 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002783
Chandler Carruth286d87e2014-02-26 08:25:02 +00002784 Type *OtherPtrTy = OtherPtr->getType();
2785 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2786
Chandler Carruth181ed052014-02-26 05:33:36 +00002787 // Compute the relative offset for the other pointer within the transfer.
Chandler Carruth286d87e2014-02-26 08:25:02 +00002788 unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
Chandler Carruth181ed052014-02-26 05:33:36 +00002789 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Pete Cooper67cf9a72015-11-19 05:56:52 +00002790 unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2791 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002792
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002793 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002794 // Compute the other pointer, folding as much as possible to produce
2795 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002796 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002797 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002798
Chandler Carruth47954c82014-02-26 05:12:43 +00002799 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002800 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002801 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002802
Pete Cooper67cf9a72015-11-19 05:56:52 +00002803 CallInst *New = IRB.CreateMemCpy(
2804 IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2805 MinAlign(SliceAlign, OtherAlign), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002806 (void)New;
2807 DEBUG(dbgs() << " to: " << *New << "\n");
2808 return false;
2809 }
2810
Chandler Carruthf0546402013-07-18 07:15:00 +00002811 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2812 NewEndOffset == NewAllocaEndOffset;
2813 uint64_t Size = NewEndOffset - NewBeginOffset;
2814 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2815 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002816 unsigned NumElements = EndIndex - BeginIndex;
Chandler Carruth113dc642014-12-20 02:39:18 +00002817 IntegerType *SubIntTy =
2818 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002819
Chandler Carruth286d87e2014-02-26 08:25:02 +00002820 // Reset the other pointer type to match the register type we're going to
2821 // use, but using the address space of the original other pointer.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002822 if (VecTy && !IsWholeAlloca) {
2823 if (NumElements == 1)
2824 OtherPtrTy = VecTy->getElementType();
2825 else
2826 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2827
Chandler Carruth286d87e2014-02-26 08:25:02 +00002828 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002829 } else if (IntTy && !IsWholeAlloca) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00002830 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2831 } else {
2832 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002833 }
2834
Chandler Carruth181ed052014-02-26 05:33:36 +00002835 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002836 OtherPtr->getName() + ".");
Pete Cooper67cf9a72015-11-19 05:56:52 +00002837 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002838 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00002839 unsigned DstAlign = SliceAlign;
2840 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002841 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002842 std::swap(SrcAlign, DstAlign);
2843 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002844
2845 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002846 if (VecTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002847 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002848 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002849 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002850 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002851 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002852 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002853 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002854 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +00002855 Src =
2856 IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002857 }
2858
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002859 if (VecTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002860 Value *Old =
2861 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002862 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002863 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002864 Value *Old =
2865 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002866 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002867 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002868 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2869 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002870 }
2871
Chandler Carruth871ba722012-09-26 10:27:46 +00002872 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00002873 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Chandler Carruth871ba722012-09-26 10:27:46 +00002874 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002875 DEBUG(dbgs() << " to: " << *Store << "\n");
2876 return !II.isVolatile();
2877 }
2878
2879 bool visitIntrinsicInst(IntrinsicInst &II) {
2880 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2881 II.getIntrinsicID() == Intrinsic::lifetime_end);
2882 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002883 assert(II.getArgOperand(1) == OldPtr);
2884
2885 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002886 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002887
Eli Friedman50967752016-11-28 21:50:34 +00002888 // Lifetime intrinsics are only promotable if they cover the whole alloca.
2889 // Therefore, we drop lifetime intrinsics which don't cover the whole
2890 // alloca.
2891 // (In theory, intrinsics which partially cover an alloca could be
2892 // promoted, but PromoteMemToReg doesn't handle that case.)
2893 // FIXME: Check whether the alloca is promotable before dropping the
2894 // lifetime intrinsics?
2895 if (NewBeginOffset != NewAllocaBeginOffset ||
2896 NewEndOffset != NewAllocaEndOffset)
2897 return true;
2898
Chandler Carruth113dc642014-12-20 02:39:18 +00002899 ConstantInt *Size =
2900 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002901 NewEndOffset - NewBeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002902 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002903 Value *New;
2904 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2905 New = IRB.CreateLifetimeStart(Ptr, Size);
2906 else
2907 New = IRB.CreateLifetimeEnd(Ptr, Size);
2908
Edwin Vane82f80d42013-01-29 17:42:24 +00002909 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002910 DEBUG(dbgs() << " to: " << *New << "\n");
Eli Friedman2a65dd12016-08-08 01:30:53 +00002911
Eli Friedman50967752016-11-28 21:50:34 +00002912 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002913 }
2914
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002915 bool visitPHINode(PHINode &PN) {
2916 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00002917 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2918 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002919
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002920 // We would like to compute a new pointer in only one place, but have it be
2921 // as local as possible to the PHI. To do that, we re-use the location of
2922 // the old pointer, which necessarily must be in the right position to
2923 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00002924 IRBuilderTy PtrBuilder(IRB);
David Majnemerd4cffcf2014-09-01 21:20:14 +00002925 if (isa<PHINode>(OldPtr))
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002926 PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
David Majnemerd4cffcf2014-09-01 21:20:14 +00002927 else
2928 PtrBuilder.SetInsertPoint(OldPtr);
Chandler Carruth51175532014-02-25 11:12:04 +00002929 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002930
Chandler Carruth47954c82014-02-26 05:12:43 +00002931 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002932 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002933 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002934
Chandler Carruth82a57542012-10-01 10:54:05 +00002935 DEBUG(dbgs() << " to: " << PN << "\n");
2936 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002937
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002938 // PHIs can't be promoted on their own, but often can be speculated. We
2939 // check the speculation outside of the rewriter so that we see the
2940 // fully-rewritten alloca.
2941 PHIUsers.insert(&PN);
2942 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002943 }
2944
2945 bool visitSelectInst(SelectInst &SI) {
2946 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002947 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2948 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00002949 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2950 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002951
Chandler Carruth47954c82014-02-26 05:12:43 +00002952 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002953 // Replace the operands which were using the old pointer.
2954 if (SI.getOperand(1) == OldPtr)
2955 SI.setOperand(1, NewPtr);
2956 if (SI.getOperand(2) == OldPtr)
2957 SI.setOperand(2, NewPtr);
2958
Chandler Carruth82a57542012-10-01 10:54:05 +00002959 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002960 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002961
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002962 // Selects can't be promoted on their own, but often can be speculated. We
2963 // check the speculation outside of the rewriter so that we see the
2964 // fully-rewritten alloca.
2965 SelectUsers.insert(&SI);
2966 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002967 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002968};
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002969
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002970namespace {
2971/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2972///
2973/// This pass aggressively rewrites all aggregate loads and stores on
2974/// a particular pointer (or any pointer derived from it which we can identify)
2975/// with scalar loads and stores.
2976class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2977 // Befriend the base class so it can delegate to private visit methods.
2978 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2979
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002980 /// Queue of pointer uses to analyze and potentially rewrite.
2981 SmallVector<Use *, 8> Queue;
2982
2983 /// Set to prevent us from cycling with phi nodes and loops.
2984 SmallPtrSet<User *, 8> Visited;
2985
2986 /// The current pointer use being rewritten. This is used to dig up the used
2987 /// value (as opposed to the user).
2988 Use *U;
2989
2990public:
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002991 /// Rewrite loads and stores through a pointer and all pointers derived from
2992 /// it.
2993 bool rewrite(Instruction &I) {
2994 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2995 enqueueUsers(I);
2996 bool Changed = false;
2997 while (!Queue.empty()) {
2998 U = Queue.pop_back_val();
2999 Changed |= visit(cast<Instruction>(U->getUser()));
3000 }
3001 return Changed;
3002 }
3003
3004private:
3005 /// Enqueue all the users of the given instruction for further processing.
3006 /// This uses a set to de-duplicate users.
3007 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003008 for (Use &U : I.uses())
David Blaikie70573dc2014-11-19 07:49:26 +00003009 if (Visited.insert(U.getUser()).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003010 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003011 }
3012
3013 // Conservative default is to not rewrite anything.
3014 bool visitInstruction(Instruction &I) { return false; }
3015
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003016 /// \brief Generic recursive split emission class.
Chandler Carruth113dc642014-12-20 02:39:18 +00003017 template <typename Derived> class OpSplitter {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003018 protected:
3019 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00003020 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003021 /// The indices which to be used with insert- or extractvalue to select the
3022 /// appropriate value within the aggregate.
3023 SmallVector<unsigned, 4> Indices;
3024 /// The indices to a GEP instruction which will move Ptr to the correct slot
3025 /// within the aggregate.
3026 SmallVector<Value *, 4> GEPIndices;
3027 /// The base pointer of the original op, used as a base for GEPing the
3028 /// split operations.
3029 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003030
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003031 /// Initialize the splitter with an insertion point, Ptr and start with a
3032 /// single zero GEP index.
3033 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003034 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003035
3036 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003037 /// \brief Generic recursive split emission routine.
3038 ///
3039 /// This method recursively splits an aggregate op (load or store) into
3040 /// scalar or vector ops. It splits recursively until it hits a single value
3041 /// and emits that single value operation via the template argument.
3042 ///
3043 /// The logic of this routine relies on GEPs and insertvalue and
3044 /// extractvalue all operating with the same fundamental index list, merely
3045 /// formatted differently (GEPs need actual values).
3046 ///
3047 /// \param Ty The type being split recursively into smaller ops.
3048 /// \param Agg The aggregate value being built up or stored, depending on
3049 /// whether this is splitting a load or a store respectively.
3050 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3051 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003052 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003053
3054 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3055 unsigned OldSize = Indices.size();
3056 (void)OldSize;
3057 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3058 ++Idx) {
3059 assert(Indices.size() == OldSize && "Did not return to the old size");
3060 Indices.push_back(Idx);
3061 GEPIndices.push_back(IRB.getInt32(Idx));
3062 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3063 GEPIndices.pop_back();
3064 Indices.pop_back();
3065 }
3066 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003067 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003068
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003069 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3070 unsigned OldSize = Indices.size();
3071 (void)OldSize;
3072 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3073 ++Idx) {
3074 assert(Indices.size() == OldSize && "Did not return to the old size");
3075 Indices.push_back(Idx);
3076 GEPIndices.push_back(IRB.getInt32(Idx));
3077 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3078 GEPIndices.pop_back();
3079 Indices.pop_back();
3080 }
3081 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003082 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003083
3084 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003085 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003086 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003087
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003088 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003089 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003090 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003091
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003092 /// Emit a leaf load of a single value. This is called at the leaves of the
3093 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003094 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003095 assert(Ty->isSingleValueType());
3096 // Load the single value and insert it using the indices.
David Blaikieaa41cd52015-04-03 21:33:42 +00003097 Value *GEP =
3098 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
Jakub Staszak3c6583a2013-02-19 22:14:45 +00003099 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003100 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3101 DEBUG(dbgs() << " to: " << *Load << "\n");
3102 }
3103 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003104
3105 bool visitLoadInst(LoadInst &LI) {
3106 assert(LI.getPointerOperand() == *U);
3107 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3108 return false;
3109
3110 // We have an aggregate being loaded, split it apart.
3111 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003112 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003113 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003114 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003115 LI.replaceAllUsesWith(V);
3116 LI.eraseFromParent();
3117 return true;
3118 }
3119
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003120 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003121 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003122 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003123
3124 /// Emit a leaf store of a single value. This is called at the leaves of the
3125 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003126 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003127 assert(Ty->isSingleValueType());
3128 // Extract the single value and store it using the indices.
Patrik Hagglunda83706e2016-06-20 10:19:00 +00003129 //
3130 // The gep and extractvalue values are factored out of the CreateStore
3131 // call to make the output independent of the argument evaluation order.
Patrik Hagglund4e0bd842016-06-20 11:19:58 +00003132 Value *ExtractValue =
3133 IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
3134 Value *InBoundsGEP =
3135 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
Patrik Hagglunda83706e2016-06-20 10:19:00 +00003136 Value *Store = IRB.CreateStore(ExtractValue, InBoundsGEP);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003137 (void)Store;
3138 DEBUG(dbgs() << " to: " << *Store << "\n");
3139 }
3140 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003141
3142 bool visitStoreInst(StoreInst &SI) {
3143 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3144 return false;
3145 Value *V = SI.getValueOperand();
3146 if (V->getType()->isSingleValueType())
3147 return false;
3148
3149 // We have an aggregate being stored, split it apart.
3150 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003151 StoreOpSplitter Splitter(&SI, *U);
3152 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003153 SI.eraseFromParent();
3154 return true;
3155 }
3156
3157 bool visitBitCastInst(BitCastInst &BC) {
3158 enqueueUsers(BC);
3159 return false;
3160 }
3161
3162 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3163 enqueueUsers(GEPI);
3164 return false;
3165 }
3166
3167 bool visitPHINode(PHINode &PN) {
3168 enqueueUsers(PN);
3169 return false;
3170 }
3171
3172 bool visitSelectInst(SelectInst &SI) {
3173 enqueueUsers(SI);
3174 return false;
3175 }
3176};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00003177}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003178
Chandler Carruthba931992012-10-13 10:49:33 +00003179/// \brief Strip aggregate type wrapping.
3180///
3181/// This removes no-op aggregate types wrapping an underlying type. It will
3182/// strip as many layers of types as it can without changing either the type
3183/// size or the allocated size.
3184static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3185 if (Ty->isSingleValueType())
3186 return Ty;
3187
3188 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3189 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3190
3191 Type *InnerTy;
3192 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3193 InnerTy = ArrTy->getElementType();
3194 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3195 const StructLayout *SL = DL.getStructLayout(STy);
3196 unsigned Index = SL->getElementContainingOffset(0);
3197 InnerTy = STy->getElementType(Index);
3198 } else {
3199 return Ty;
3200 }
3201
3202 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3203 TypeSize > DL.getTypeSizeInBits(InnerTy))
3204 return Ty;
3205
3206 return stripAggregateTypeWrapping(DL, InnerTy);
3207}
3208
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003209/// \brief Try to find a partition of the aggregate type passed in for a given
3210/// offset and size.
3211///
3212/// This recurses through the aggregate type and tries to compute a subtype
3213/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003214/// of an array, it will even compute a new array type for that sub-section,
3215/// and the same for structs.
3216///
3217/// Note that this routine is very strict and tries to find a partition of the
3218/// type which produces the *exact* right offset and size. It is not forgiving
3219/// when the size or offset cause either end of type-based partition to be off.
3220/// Also, this is a best-effort routine. It is reasonable to give up and not
3221/// return a type if necessary.
Chandler Carruth113dc642014-12-20 02:39:18 +00003222static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3223 uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003224 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3225 return stripAggregateTypeWrapping(DL, Ty);
3226 if (Offset > DL.getTypeAllocSize(Ty) ||
3227 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003228 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003229
3230 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003231 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003232 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003233 uint64_t NumSkippedElements = Offset / ElementSize;
Peter Collingbournebc070522016-12-02 03:20:58 +00003234 if (NumSkippedElements >= SeqTy->getNumElements())
3235 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003236 Offset -= NumSkippedElements * ElementSize;
3237
3238 // First check if we need to recurse.
3239 if (Offset > 0 || Size < ElementSize) {
3240 // Bail if the partition ends in a different array element.
3241 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003242 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003243 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003244 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003245 }
3246 assert(Offset == 0);
3247
3248 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003249 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003250 assert(Size > ElementSize);
3251 uint64_t NumElements = Size / ElementSize;
3252 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003253 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003254 return ArrayType::get(ElementTy, NumElements);
3255 }
3256
3257 StructType *STy = dyn_cast<StructType>(Ty);
3258 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003259 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003260
Chandler Carruth90a735d2013-07-19 07:21:28 +00003261 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003262 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003263 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003264 uint64_t EndOffset = Offset + Size;
3265 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003266 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003267
3268 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003269 Offset -= SL->getElementOffset(Index);
3270
3271 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003272 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003273 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003274 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003275
3276 // See if any partition must be contained by the element.
3277 if (Offset > 0 || Size < ElementSize) {
3278 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003279 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003280 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003281 }
3282 assert(Offset == 0);
3283
3284 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003285 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003286
3287 StructType::element_iterator EI = STy->element_begin() + Index,
3288 EE = STy->element_end();
3289 if (EndOffset < SL->getSizeInBytes()) {
3290 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3291 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003292 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003293
3294 // Don't try to form "natural" types if the elements don't line up with the
3295 // expected size.
3296 // FIXME: We could potentially recurse down through the last element in the
3297 // sub-struct to find a natural end point.
3298 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003299 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003300
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003301 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003302 EE = STy->element_begin() + EndIndex;
3303 }
3304
3305 // Try to build up a sub-structure.
Chandler Carruth113dc642014-12-20 02:39:18 +00003306 StructType *SubTy =
3307 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003308 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003309 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003310 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003311
Chandler Carruth054a40a2012-09-14 11:08:31 +00003312 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003313}
3314
Chandler Carruth0715cba2015-01-01 11:54:38 +00003315/// \brief Pre-split loads and stores to simplify rewriting.
3316///
3317/// We want to break up the splittable load+store pairs as much as
3318/// possible. This is important to do as a preprocessing step, as once we
3319/// start rewriting the accesses to partitions of the alloca we lose the
3320/// necessary information to correctly split apart paired loads and stores
3321/// which both point into this alloca. The case to consider is something like
3322/// the following:
3323///
3324/// %a = alloca [12 x i8]
3325/// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3326/// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3327/// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3328/// %iptr1 = bitcast i8* %gep1 to i64*
3329/// %iptr2 = bitcast i8* %gep2 to i64*
3330/// %fptr1 = bitcast i8* %gep1 to float*
3331/// %fptr2 = bitcast i8* %gep2 to float*
3332/// %fptr3 = bitcast i8* %gep3 to float*
3333/// store float 0.0, float* %fptr1
3334/// store float 1.0, float* %fptr2
3335/// %v = load i64* %iptr1
3336/// store i64 %v, i64* %iptr2
3337/// %f1 = load float* %fptr2
3338/// %f2 = load float* %fptr3
3339///
3340/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3341/// promote everything so we recover the 2 SSA values that should have been
3342/// there all along.
3343///
3344/// \returns true if any changes are made.
3345bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
3346 DEBUG(dbgs() << "Pre-splitting loads and stores\n");
3347
3348 // Track the loads and stores which are candidates for pre-splitting here, in
3349 // the order they first appear during the partition scan. These give stable
3350 // iteration order and a basis for tracking which loads and stores we
3351 // actually split.
3352 SmallVector<LoadInst *, 4> Loads;
3353 SmallVector<StoreInst *, 4> Stores;
3354
3355 // We need to accumulate the splits required of each load or store where we
3356 // can find them via a direct lookup. This is important to cross-check loads
3357 // and stores against each other. We also track the slice so that we can kill
3358 // all the slices that end up split.
3359 struct SplitOffsets {
3360 Slice *S;
3361 std::vector<uint64_t> Splits;
3362 };
3363 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3364
Chandler Carruth73b01642015-01-05 04:17:53 +00003365 // Track loads out of this alloca which cannot, for any reason, be pre-split.
3366 // This is important as we also cannot pre-split stores of those loads!
3367 // FIXME: This is all pretty gross. It means that we can be more aggressive
3368 // in pre-splitting when the load feeding the store happens to come from
3369 // a separate alloca. Put another way, the effectiveness of SROA would be
3370 // decreased by a frontend which just concatenated all of its local allocas
3371 // into one big flat alloca. But defeating such patterns is exactly the job
3372 // SROA is tasked with! Sadly, to not have this discrepancy we would have
3373 // change store pre-splitting to actually force pre-splitting of the load
3374 // that feeds it *and all stores*. That makes pre-splitting much harder, but
3375 // maybe it would make it more principled?
3376 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3377
Chandler Carruth0715cba2015-01-01 11:54:38 +00003378 DEBUG(dbgs() << " Searching for candidate loads and stores\n");
3379 for (auto &P : AS.partitions()) {
3380 for (Slice &S : P) {
Chandler Carruth73b01642015-01-05 04:17:53 +00003381 Instruction *I = cast<Instruction>(S.getUse()->getUser());
Chandler Carruth37f1f122016-03-10 15:31:17 +00003382 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
3383 // If this is a load we have to track that it can't participate in any
3384 // pre-splitting. If this is a store of a load we have to track that
3385 // that load also can't participate in any pre-splitting.
Chandler Carruth73b01642015-01-05 04:17:53 +00003386 if (auto *LI = dyn_cast<LoadInst>(I))
3387 UnsplittableLoads.insert(LI);
Chandler Carruth37f1f122016-03-10 15:31:17 +00003388 else if (auto *SI = dyn_cast<StoreInst>(I))
3389 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
3390 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003391 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003392 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003393 assert(P.endOffset() > S.beginOffset() &&
3394 "Empty or backwards partition!");
3395
3396 // Determine if this is a pre-splittable slice.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003397 if (auto *LI = dyn_cast<LoadInst>(I)) {
3398 assert(!LI->isVolatile() && "Cannot split volatile loads!");
3399
3400 // The load must be used exclusively to store into other pointers for
3401 // us to be able to arbitrarily pre-split it. The stores must also be
3402 // simple to avoid changing semantics.
3403 auto IsLoadSimplyStored = [](LoadInst *LI) {
3404 for (User *LU : LI->users()) {
3405 auto *SI = dyn_cast<StoreInst>(LU);
3406 if (!SI || !SI->isSimple())
3407 return false;
3408 }
3409 return true;
3410 };
Chandler Carruth73b01642015-01-05 04:17:53 +00003411 if (!IsLoadSimplyStored(LI)) {
3412 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003413 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003414 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003415
3416 Loads.push_back(LI);
Chandler Carruthd94a5962016-03-10 14:16:18 +00003417 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
3418 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3419 // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
Chandler Carruth994cde82015-01-01 12:01:03 +00003420 continue;
3421 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3422 if (!StoredLoad || !StoredLoad->isSimple())
3423 continue;
3424 assert(!SI->isVolatile() && "Cannot split volatile stores!");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003425
Chandler Carruth994cde82015-01-01 12:01:03 +00003426 Stores.push_back(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003427 } else {
3428 // Other uses cannot be pre-split.
3429 continue;
3430 }
3431
3432 // Record the initial split.
3433 DEBUG(dbgs() << " Candidate: " << *I << "\n");
3434 auto &Offsets = SplitOffsetsMap[I];
3435 assert(Offsets.Splits.empty() &&
3436 "Should not have splits the first time we see an instruction!");
3437 Offsets.S = &S;
Chandler Carruth24ac8302015-01-02 03:55:54 +00003438 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003439 }
3440
3441 // Now scan the already split slices, and add a split for any of them which
3442 // we're going to pre-split.
3443 for (Slice *S : P.splitSliceTails()) {
3444 auto SplitOffsetsMapI =
3445 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3446 if (SplitOffsetsMapI == SplitOffsetsMap.end())
3447 continue;
3448 auto &Offsets = SplitOffsetsMapI->second;
3449
3450 assert(Offsets.S == S && "Found a mismatched slice!");
3451 assert(!Offsets.Splits.empty() &&
3452 "Cannot have an empty set of splits on the second partition!");
Chandler Carruth24ac8302015-01-02 03:55:54 +00003453 assert(Offsets.Splits.back() ==
3454 P.beginOffset() - Offsets.S->beginOffset() &&
Chandler Carruth0715cba2015-01-01 11:54:38 +00003455 "Previous split does not end where this one begins!");
3456
3457 // Record each split. The last partition's end isn't needed as the size
3458 // of the slice dictates that.
3459 if (S->endOffset() > P.endOffset())
Chandler Carruth24ac8302015-01-02 03:55:54 +00003460 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003461 }
3462 }
3463
3464 // We may have split loads where some of their stores are split stores. For
3465 // such loads and stores, we can only pre-split them if their splits exactly
3466 // match relative to their starting offset. We have to verify this prior to
3467 // any rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003468 Stores.erase(
David Majnemerc7004902016-08-12 04:32:37 +00003469 remove_if(Stores,
3470 [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
3471 // Lookup the load we are storing in our map of split
3472 // offsets.
3473 auto *LI = cast<LoadInst>(SI->getValueOperand());
3474 // If it was completely unsplittable, then we're done,
3475 // and this store can't be pre-split.
3476 if (UnsplittableLoads.count(LI))
3477 return true;
Chandler Carruth73b01642015-01-05 04:17:53 +00003478
David Majnemerc7004902016-08-12 04:32:37 +00003479 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3480 if (LoadOffsetsI == SplitOffsetsMap.end())
3481 return false; // Unrelated loads are definitely safe.
3482 auto &LoadOffsets = LoadOffsetsI->second;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003483
David Majnemerc7004902016-08-12 04:32:37 +00003484 // Now lookup the store's offsets.
3485 auto &StoreOffsets = SplitOffsetsMap[SI];
Chandler Carruth0715cba2015-01-01 11:54:38 +00003486
David Majnemerc7004902016-08-12 04:32:37 +00003487 // If the relative offsets of each split in the load and
3488 // store match exactly, then we can split them and we
3489 // don't need to remove them here.
3490 if (LoadOffsets.Splits == StoreOffsets.Splits)
3491 return false;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003492
David Majnemerc7004902016-08-12 04:32:37 +00003493 DEBUG(dbgs() << " Mismatched splits for load and store:\n"
3494 << " " << *LI << "\n"
3495 << " " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003496
David Majnemerc7004902016-08-12 04:32:37 +00003497 // We've found a store and load that we need to split
3498 // with mismatched relative splits. Just give up on them
3499 // and remove both instructions from our list of
3500 // candidates.
3501 UnsplittableLoads.insert(LI);
3502 return true;
3503 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003504 Stores.end());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003505 // Now we have to go *back* through all the stores, because a later store may
Chandler Carruth73b01642015-01-05 04:17:53 +00003506 // have caused an earlier store's load to become unsplittable and if it is
3507 // unsplittable for the later store, then we can't rely on it being split in
3508 // the earlier store either.
David Majnemerc7004902016-08-12 04:32:37 +00003509 Stores.erase(remove_if(Stores,
3510 [&UnsplittableLoads](StoreInst *SI) {
3511 auto *LI = cast<LoadInst>(SI->getValueOperand());
3512 return UnsplittableLoads.count(LI);
3513 }),
Chandler Carruth73b01642015-01-05 04:17:53 +00003514 Stores.end());
3515 // Once we've established all the loads that can't be split for some reason,
3516 // filter any that made it into our list out.
David Majnemerc7004902016-08-12 04:32:37 +00003517 Loads.erase(remove_if(Loads,
3518 [&UnsplittableLoads](LoadInst *LI) {
3519 return UnsplittableLoads.count(LI);
3520 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003521 Loads.end());
3522
3523 // If no loads or stores are left, there is no pre-splitting to be done for
3524 // this alloca.
3525 if (Loads.empty() && Stores.empty())
3526 return false;
3527
3528 // From here on, we can't fail and will be building new accesses, so rig up
3529 // an IR builder.
3530 IRBuilderTy IRB(&AI);
3531
3532 // Collect the new slices which we will merge into the alloca slices.
3533 SmallVector<Slice, 4> NewSlices;
3534
3535 // Track any allocas we end up splitting loads and stores for so we iterate
3536 // on them.
3537 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3538
3539 // At this point, we have collected all of the loads and stores we can
3540 // pre-split, and the specific splits needed for them. We actually do the
3541 // splitting in a specific order in order to handle when one of the loads in
3542 // the value operand to one of the stores.
3543 //
3544 // First, we rewrite all of the split loads, and just accumulate each split
3545 // load in a parallel structure. We also build the slices for them and append
3546 // them to the alloca slices.
3547 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3548 std::vector<LoadInst *> SplitLoads;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003549 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003550 for (LoadInst *LI : Loads) {
3551 SplitLoads.clear();
3552
3553 IntegerType *Ty = cast<IntegerType>(LI->getType());
3554 uint64_t LoadSize = Ty->getBitWidth() / 8;
3555 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3556
3557 auto &Offsets = SplitOffsetsMap[LI];
3558 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3559 "Slice size should always match load size exactly!");
3560 uint64_t BaseOffset = Offsets.S->beginOffset();
3561 assert(BaseOffset + LoadSize > BaseOffset &&
3562 "Cannot represent alloca access size using 64-bit integers!");
3563
3564 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003565 IRB.SetInsertPoint(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003566
3567 DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
3568
3569 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3570 int Idx = 0, Size = Offsets.Splits.size();
3571 for (;;) {
3572 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3573 auto *PartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3574 LoadInst *PLoad = IRB.CreateAlignedLoad(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003575 getAdjustedPtr(IRB, DL, BasePtr,
3576 APInt(DL.getPointerSizeInBits(), PartOffset),
Chandler Carruth994cde82015-01-01 12:01:03 +00003577 PartPtrTy, BasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003578 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003579 LI->getName());
Dorit Nuzmand1247a62016-09-22 07:56:23 +00003580 PLoad->copyMetadata(*LI, LLVMContext::MD_mem_parallel_loop_access);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003581
3582 // Append this load onto the list of split loads so we can find it later
3583 // to rewrite the stores.
3584 SplitLoads.push_back(PLoad);
3585
3586 // Now build a new slice for the alloca.
Chandler Carruth994cde82015-01-01 12:01:03 +00003587 NewSlices.push_back(
3588 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3589 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003590 /*IsSplittable*/ false));
Chandler Carruth6044c0b2015-01-01 12:56:47 +00003591 DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3592 << ", " << NewSlices.back().endOffset() << "): " << *PLoad
3593 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003594
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003595 // See if we've handled all the splits.
3596 if (Idx >= Size)
3597 break;
3598
Chandler Carruth0715cba2015-01-01 11:54:38 +00003599 // Setup the next partition.
3600 PartOffset = Offsets.Splits[Idx];
3601 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003602 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3603 }
3604
3605 // Now that we have the split loads, do the slow walk over all uses of the
3606 // load and rewrite them as split stores, or save the split loads to use
3607 // below if the store is going to be split there anyways.
3608 bool DeferredStores = false;
3609 for (User *LU : LI->users()) {
3610 StoreInst *SI = cast<StoreInst>(LU);
3611 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3612 DeferredStores = true;
3613 DEBUG(dbgs() << " Deferred splitting of store: " << *SI << "\n");
3614 continue;
3615 }
3616
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003617 Value *StoreBasePtr = SI->getPointerOperand();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003618 IRB.SetInsertPoint(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003619
3620 DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
3621
3622 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3623 LoadInst *PLoad = SplitLoads[Idx];
3624 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
Chandler Carruth994cde82015-01-01 12:01:03 +00003625 auto *PartPtrTy =
3626 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003627
3628 StoreInst *PStore = IRB.CreateAlignedStore(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003629 PLoad, getAdjustedPtr(IRB, DL, StoreBasePtr,
3630 APInt(DL.getPointerSizeInBits(), PartOffset),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003631 PartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003632 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Dorit Nuzmand1247a62016-09-22 07:56:23 +00003633 PStore->copyMetadata(*LI, LLVMContext::MD_mem_parallel_loop_access);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003634 DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
3635 }
3636
3637 // We want to immediately iterate on any allocas impacted by splitting
3638 // this store, and we have to track any promotable alloca (indicated by
3639 // a direct store) as needing to be resplit because it is no longer
3640 // promotable.
3641 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3642 ResplitPromotableAllocas.insert(OtherAI);
3643 Worklist.insert(OtherAI);
3644 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3645 StoreBasePtr->stripInBoundsOffsets())) {
3646 Worklist.insert(OtherAI);
3647 }
3648
3649 // Mark the original store as dead.
3650 DeadInsts.insert(SI);
3651 }
3652
3653 // Save the split loads if there are deferred stores among the users.
3654 if (DeferredStores)
3655 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3656
3657 // Mark the original load as dead and kill the original slice.
3658 DeadInsts.insert(LI);
3659 Offsets.S->kill();
3660 }
3661
3662 // Second, we rewrite all of the split stores. At this point, we know that
3663 // all loads from this alloca have been split already. For stores of such
3664 // loads, we can simply look up the pre-existing split loads. For stores of
3665 // other loads, we split those loads first and then write split stores of
3666 // them.
3667 for (StoreInst *SI : Stores) {
3668 auto *LI = cast<LoadInst>(SI->getValueOperand());
3669 IntegerType *Ty = cast<IntegerType>(LI->getType());
3670 uint64_t StoreSize = Ty->getBitWidth() / 8;
3671 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3672
3673 auto &Offsets = SplitOffsetsMap[SI];
3674 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3675 "Slice size should always match load size exactly!");
3676 uint64_t BaseOffset = Offsets.S->beginOffset();
3677 assert(BaseOffset + StoreSize > BaseOffset &&
3678 "Cannot represent alloca access size using 64-bit integers!");
3679
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003680 Value *LoadBasePtr = LI->getPointerOperand();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003681 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3682
3683 DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
3684
3685 // Check whether we have an already split load.
3686 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3687 std::vector<LoadInst *> *SplitLoads = nullptr;
3688 if (SplitLoadsMapI != SplitLoadsMap.end()) {
3689 SplitLoads = &SplitLoadsMapI->second;
3690 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3691 "Too few split loads for the number of splits in the store!");
3692 } else {
3693 DEBUG(dbgs() << " of load: " << *LI << "\n");
3694 }
3695
Chandler Carruth0715cba2015-01-01 11:54:38 +00003696 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3697 int Idx = 0, Size = Offsets.Splits.size();
3698 for (;;) {
3699 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3700 auto *PartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
3701
3702 // Either lookup a split load or create one.
3703 LoadInst *PLoad;
3704 if (SplitLoads) {
3705 PLoad = (*SplitLoads)[Idx];
3706 } else {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003707 IRB.SetInsertPoint(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003708 PLoad = IRB.CreateAlignedLoad(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003709 getAdjustedPtr(IRB, DL, LoadBasePtr,
3710 APInt(DL.getPointerSizeInBits(), PartOffset),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003711 PartPtrTy, LoadBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003712 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003713 LI->getName());
3714 }
3715
3716 // And store this partition.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003717 IRB.SetInsertPoint(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003718 StoreInst *PStore = IRB.CreateAlignedStore(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003719 PLoad, getAdjustedPtr(IRB, DL, StoreBasePtr,
3720 APInt(DL.getPointerSizeInBits(), PartOffset),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003721 PartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003722 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003723
3724 // Now build a new slice for the alloca.
3725 NewSlices.push_back(
3726 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3727 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003728 /*IsSplittable*/ false));
Chandler Carruth6044c0b2015-01-01 12:56:47 +00003729 DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3730 << ", " << NewSlices.back().endOffset() << "): " << *PStore
3731 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003732 if (!SplitLoads) {
3733 DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
3734 }
3735
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003736 // See if we've finished all the splits.
3737 if (Idx >= Size)
3738 break;
3739
Chandler Carruth0715cba2015-01-01 11:54:38 +00003740 // Setup the next partition.
3741 PartOffset = Offsets.Splits[Idx];
3742 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003743 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
3744 }
3745
3746 // We want to immediately iterate on any allocas impacted by splitting
3747 // this load, which is only relevant if it isn't a load of this alloca and
3748 // thus we didn't already split the loads above. We also have to keep track
3749 // of any promotable allocas we split loads on as they can no longer be
3750 // promoted.
3751 if (!SplitLoads) {
3752 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
3753 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3754 ResplitPromotableAllocas.insert(OtherAI);
3755 Worklist.insert(OtherAI);
3756 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3757 LoadBasePtr->stripInBoundsOffsets())) {
3758 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3759 Worklist.insert(OtherAI);
3760 }
3761 }
3762
3763 // Mark the original store as dead now that we've split it up and kill its
Chandler Carruth24ac8302015-01-02 03:55:54 +00003764 // slice. Note that we leave the original load in place unless this store
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003765 // was its only use. It may in turn be split up if it is an alloca load
Chandler Carruth24ac8302015-01-02 03:55:54 +00003766 // for some other alloca, but it may be a normal load. This may introduce
3767 // redundant loads, but where those can be merged the rest of the optimizer
3768 // should handle the merging, and this uncovers SSA splits which is more
3769 // important. In practice, the original loads will almost always be fully
3770 // split and removed eventually, and the splits will be merged by any
3771 // trivial CSE, including instcombine.
3772 if (LI->hasOneUse()) {
3773 assert(*LI->user_begin() == SI && "Single use isn't this store!");
3774 DeadInsts.insert(LI);
3775 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003776 DeadInsts.insert(SI);
3777 Offsets.S->kill();
3778 }
3779
Chandler Carruth24ac8302015-01-02 03:55:54 +00003780 // Remove the killed slices that have ben pre-split.
David Majnemerc7004902016-08-12 04:32:37 +00003781 AS.erase(remove_if(AS, [](const Slice &S) { return S.isDead(); }), AS.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003782
Chandler Carruth24ac8302015-01-02 03:55:54 +00003783 // Insert our new slices. This will sort and merge them into the sorted
3784 // sequence.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003785 AS.insert(NewSlices);
3786
3787 DEBUG(dbgs() << " Pre-split slices:\n");
3788#ifndef NDEBUG
3789 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
3790 DEBUG(AS.print(dbgs(), I, " "));
3791#endif
3792
3793 // Finally, don't try to promote any allocas that new require re-splitting.
3794 // They have already been added to the worklist above.
3795 PromotableAllocas.erase(
David Majnemerc7004902016-08-12 04:32:37 +00003796 remove_if(
3797 PromotableAllocas,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003798 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
3799 PromotableAllocas.end());
3800
3801 return true;
3802}
3803
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003804/// \brief Rewrite an alloca partition's users.
3805///
3806/// This routine drives both of the rewriting goals of the SROA pass. It tries
3807/// to rewrite uses of an alloca partition to be conducive for SSA value
3808/// promotion. If the partition needs a new, more refined alloca, this will
3809/// build that new alloca, preserving as much type information as possible, and
3810/// rewrite the uses of the old alloca to point at the new one and have the
3811/// appropriate new offsets. It also evaluates how successful the rewrite was
3812/// at enabling promotion and if it was successful queues the alloca to be
3813/// promoted.
Adrian Prantl565cc182015-01-20 19:42:22 +00003814AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruth29a18a42015-09-12 09:09:14 +00003815 Partition &P) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003816 // Try to compute a friendly type for this partition of the alloca. This
3817 // won't always succeed, in which case we fall back to a legal integer type
3818 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00003819 Type *SliceTy = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003820 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003821 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003822 if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003823 SliceTy = CommonUseTy;
3824 if (!SliceTy)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003825 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003826 P.beginOffset(), P.size()))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003827 SliceTy = TypePartitionTy;
3828 if ((!SliceTy || (SliceTy->isArrayTy() &&
3829 SliceTy->getArrayElementType()->isIntegerTy())) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003830 DL.isLegalInteger(P.size() * 8))
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003831 SliceTy = Type::getIntNTy(*C, P.size() * 8);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003832 if (!SliceTy)
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003833 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003834 assert(DL.getTypeAllocSize(SliceTy) >= P.size());
Chandler Carruthf0546402013-07-18 07:15:00 +00003835
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003836 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00003837
Chandler Carruth2dc96822014-10-18 00:44:02 +00003838 VectorType *VecTy =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003839 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
Chandler Carruth2dc96822014-10-18 00:44:02 +00003840 if (VecTy)
3841 SliceTy = VecTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003842
3843 // Check for the case where we're going to rewrite to a new alloca of the
3844 // exact same type as the original, and with the same access offsets. In that
3845 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003846 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003847 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003848 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003849 assert(P.beginOffset() == 0 &&
3850 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003851 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003852 // FIXME: We should be able to bail at this point with "nothing changed".
3853 // FIXME: We might want to defer PHI speculation until after here.
Adrian Prantl565cc182015-01-20 19:42:22 +00003854 // FIXME: return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003855 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003856 unsigned Alignment = AI.getAlignment();
3857 if (!Alignment) {
3858 // The minimum alignment which users can rely on when the explicit
3859 // alignment is omitted or zero is that required by the ABI for this
3860 // type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003861 Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003862 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003863 Alignment = MinAlign(Alignment, P.beginOffset());
Chandler Carruth903790e2012-09-29 10:41:21 +00003864 // If we will get at least this much alignment from the type alone, leave
3865 // the alloca's alignment unconstrained.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003866 if (Alignment <= DL.getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003867 Alignment = 0;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003868 NewAI = new AllocaInst(
Matt Arsenault3c1fc762017-04-10 22:27:50 +00003869 SliceTy, AI.getType()->getAddressSpace(), nullptr, Alignment,
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003870 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003871 ++NumNewAllocas;
3872 }
3873
3874 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003875 << "[" << P.beginOffset() << "," << P.endOffset()
3876 << ") to: " << *NewAI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003877
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003878 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00003879 // promoted allocas. We will reset it to this point if the alloca is not in
3880 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003881 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00003882 unsigned NumUses = 0;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003883 SmallPtrSet<PHINode *, 8> PHIUsers;
3884 SmallPtrSet<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003885
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003886 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003887 P.endOffset(), IsIntegerPromotable, VecTy,
3888 PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00003889 bool Promotable = true;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00003890 for (Slice *S : P.splitSliceTails()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003891 Promotable &= Rewriter.visit(S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003892 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003893 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003894 for (Slice &S : P) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003895 Promotable &= Rewriter.visit(&S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003896 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003897 }
3898
Chandler Carruth6c321c12013-07-19 10:57:36 +00003899 NumAllocaPartitionUses += NumUses;
3900 MaxUsesPerAllocaPartition =
3901 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003902
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003903 // Now that we've processed all the slices in the new partition, check if any
3904 // PHIs or Selects would block promotion.
3905 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3906 E = PHIUsers.end();
3907 I != E; ++I)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003908 if (!isSafePHIToSpeculate(**I)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003909 Promotable = false;
3910 PHIUsers.clear();
3911 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003912 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003913 }
3914 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3915 E = SelectUsers.end();
3916 I != E; ++I)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003917 if (!isSafeSelectToSpeculate(**I)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003918 Promotable = false;
3919 PHIUsers.clear();
3920 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003921 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003922 }
3923
3924 if (Promotable) {
3925 if (PHIUsers.empty() && SelectUsers.empty()) {
3926 // Promote the alloca.
3927 PromotableAllocas.push_back(NewAI);
3928 } else {
3929 // If we have either PHIs or Selects to speculate, add them to those
3930 // worklists and re-queue the new alloca so that we promote in on the
3931 // next iteration.
Chandler Carruth61747042014-10-16 21:05:14 +00003932 for (PHINode *PHIUser : PHIUsers)
3933 SpeculatablePHIs.insert(PHIUser);
3934 for (SelectInst *SelectUser : SelectUsers)
3935 SpeculatableSelects.insert(SelectUser);
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003936 Worklist.insert(NewAI);
3937 }
3938 } else {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003939 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003940 while (PostPromotionWorklist.size() > PPWOldSize)
3941 PostPromotionWorklist.pop_back();
David Majnemer30ffc4c2016-04-26 01:05:00 +00003942
3943 // We couldn't promote and we didn't create a new partition, nothing
3944 // happened.
3945 if (NewAI == &AI)
3946 return nullptr;
3947
3948 // If we can't promote the alloca, iterate on it to check for new
3949 // refinements exposed by splitting the current alloca. Don't iterate on an
3950 // alloca which didn't actually change and didn't get promoted.
3951 Worklist.insert(NewAI);
Chandler Carruthf0546402013-07-18 07:15:00 +00003952 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003953
Adrian Prantl565cc182015-01-20 19:42:22 +00003954 return NewAI;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003955}
3956
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003957/// \brief Walks the slices of an alloca and form partitions based on them,
3958/// rewriting each of their uses.
Chandler Carruth83934062014-10-16 21:11:55 +00003959bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
3960 if (AS.begin() == AS.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00003961 return false;
3962
Chandler Carruth6c321c12013-07-19 10:57:36 +00003963 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003964 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003965 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00003966
Chandler Carruth24ac8302015-01-02 03:55:54 +00003967 // First try to pre-split loads and stores.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003968 Changed |= presplitLoadsAndStores(AI, AS);
3969
Chandler Carruth24ac8302015-01-02 03:55:54 +00003970 // Now that we have identified any pre-splitting opportunities, mark any
3971 // splittable (non-whole-alloca) loads and stores as unsplittable. If we fail
3972 // to split these during pre-splitting, we want to force them to be
3973 // rewritten into a partition.
3974 bool IsSorted = true;
3975 for (Slice &S : AS) {
3976 if (!S.isSplittable())
3977 continue;
3978 // FIXME: We currently leave whole-alloca splittable loads and stores. This
3979 // used to be the only splittable loads and stores and we need to be
3980 // confident that the above handling of splittable loads and stores is
3981 // completely sufficient before we forcibly disable the remaining handling.
3982 if (S.beginOffset() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003983 S.endOffset() >= DL.getTypeAllocSize(AI.getAllocatedType()))
Chandler Carruth24ac8302015-01-02 03:55:54 +00003984 continue;
3985 if (isa<LoadInst>(S.getUse()->getUser()) ||
3986 isa<StoreInst>(S.getUse()->getUser())) {
3987 S.makeUnsplittable();
3988 IsSorted = false;
3989 }
3990 }
3991 if (!IsSorted)
3992 std::sort(AS.begin(), AS.end());
3993
Adrian Prantl941fa752016-12-05 18:04:47 +00003994 /// Describes the allocas introduced by rewritePartition in order to migrate
3995 /// the debug info.
3996 struct Fragment {
Adrian Prantl565cc182015-01-20 19:42:22 +00003997 AllocaInst *Alloca;
3998 uint64_t Offset;
3999 uint64_t Size;
Adrian Prantl941fa752016-12-05 18:04:47 +00004000 Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
Adrian Prantl565cc182015-01-20 19:42:22 +00004001 : Alloca(AI), Offset(O), Size(S) {}
4002 };
Adrian Prantl941fa752016-12-05 18:04:47 +00004003 SmallVector<Fragment, 4> Fragments;
Adrian Prantl565cc182015-01-20 19:42:22 +00004004
Chandler Carruth0715cba2015-01-01 11:54:38 +00004005 // Rewrite each partition.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004006 for (auto &P : AS.partitions()) {
Adrian Prantl565cc182015-01-20 19:42:22 +00004007 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4008 Changed = true;
Adrian Prantl34e75902015-02-09 23:57:22 +00004009 if (NewAI != &AI) {
4010 uint64_t SizeOfByte = 8;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004011 uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
Adrian Prantl34e75902015-02-09 23:57:22 +00004012 // Don't include any padding.
4013 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
Adrian Prantl941fa752016-12-05 18:04:47 +00004014 Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
Adrian Prantl34e75902015-02-09 23:57:22 +00004015 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004016 }
Chandler Carruth6c321c12013-07-19 10:57:36 +00004017 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00004018 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004019
Chandler Carruth6c321c12013-07-19 10:57:36 +00004020 NumAllocaPartitions += NumPartitions;
4021 MaxPartitionsPerAlloca =
4022 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004023
Adrian Prantl565cc182015-01-20 19:42:22 +00004024 // Migrate debug information from the old alloca to the new alloca(s)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004025 // and the individual partitions.
Adrian Prantl565cc182015-01-20 19:42:22 +00004026 if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(&AI)) {
Duncan P. N. Exon Smith60635e32015-04-21 18:44:06 +00004027 auto *Var = DbgDecl->getVariable();
4028 auto *Expr = DbgDecl->getExpression();
Sanjay Patelaf674fb2015-12-14 17:24:23 +00004029 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
Keno Fischerd5354fd2016-01-14 20:06:34 +00004030 uint64_t AllocaSize = DL.getTypeSizeInBits(AI.getAllocatedType());
Adrian Prantl941fa752016-12-05 18:04:47 +00004031 for (auto Fragment : Fragments) {
4032 // Create a fragment expression describing the new partition or reuse AI's
Adrian Prantl565cc182015-01-20 19:42:22 +00004033 // expression if there is only one partition.
Adrian Prantl941fa752016-12-05 18:04:47 +00004034 auto *FragmentExpr = Expr;
4035 if (Fragment.Size < AllocaSize || Expr->isFragment()) {
Adrian Prantl152ac392015-02-01 00:58:04 +00004036 // If this alloca is already a scalar replacement of a larger aggregate,
Adrian Prantl941fa752016-12-05 18:04:47 +00004037 // Fragment.Offset describes the offset inside the scalar.
Adrian Prantl49797ca2016-12-22 05:27:12 +00004038 auto ExprFragment = Expr->getFragmentInfo();
4039 uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0;
Adrian Prantl941fa752016-12-05 18:04:47 +00004040 uint64_t Start = Offset + Fragment.Offset;
4041 uint64_t Size = Fragment.Size;
Adrian Prantl49797ca2016-12-22 05:27:12 +00004042 if (ExprFragment) {
Adrian Prantl941fa752016-12-05 18:04:47 +00004043 uint64_t AbsEnd =
Adrian Prantl49797ca2016-12-22 05:27:12 +00004044 ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
Adrian Prantl34e75902015-02-09 23:57:22 +00004045 if (Start >= AbsEnd)
4046 // No need to describe a SROAed padding.
4047 continue;
4048 Size = std::min(Size, AbsEnd - Start);
4049 }
Adrian Prantl941fa752016-12-05 18:04:47 +00004050 FragmentExpr = DIB.createFragmentExpression(Start, Size);
Adrian Prantl152ac392015-02-01 00:58:04 +00004051 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004052
4053 // Remove any existing dbg.declare intrinsic describing the same alloca.
Adrian Prantl941fa752016-12-05 18:04:47 +00004054 if (DbgDeclareInst *OldDDI = FindAllocaDbgDeclare(Fragment.Alloca))
Adrian Prantl565cc182015-01-20 19:42:22 +00004055 OldDDI->eraseFromParent();
4056
Adrian Prantl941fa752016-12-05 18:04:47 +00004057 DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr,
4058 DbgDecl->getDebugLoc(), &AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004059 }
4060 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004061 return Changed;
4062}
4063
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004064/// \brief Clobber a use with undef, deleting the used value if it becomes dead.
4065void SROA::clobberUse(Use &U) {
4066 Value *OldV = U;
4067 // Replace the use with an undef value.
4068 U = UndefValue::get(OldV->getType());
4069
4070 // Check for this making an instruction dead. We have to garbage collect
4071 // all the dead instructions to ensure the uses of any alloca end up being
4072 // minimal.
4073 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4074 if (isInstructionTriviallyDead(OldI)) {
4075 DeadInsts.insert(OldI);
4076 }
4077}
4078
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004079/// \brief Analyze an alloca for SROA.
4080///
4081/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004082/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004083/// rewritten as needed.
4084bool SROA::runOnAlloca(AllocaInst &AI) {
4085 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
4086 ++NumAllocasAnalyzed;
4087
4088 // Special case dead allocas, as they're trivial.
4089 if (AI.use_empty()) {
4090 AI.eraseFromParent();
4091 return true;
4092 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004093 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004094
4095 // Skip alloca forms that this analysis can't handle.
4096 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004097 DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004098 return false;
4099
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004100 bool Changed = false;
4101
4102 // First, split any FCA loads and stores touching this alloca to promote
4103 // better splitting and promotion opportunities.
Benjamin Kramer6db33382015-10-15 15:08:58 +00004104 AggLoadStoreRewriter AggRewriter;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004105 Changed |= AggRewriter.rewrite(AI);
4106
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004107 // Build the slices using a recursive instruction-visiting builder.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004108 AllocaSlices AS(DL, AI);
Chandler Carruth83934062014-10-16 21:11:55 +00004109 DEBUG(AS.print(dbgs()));
4110 if (AS.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004111 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004112
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004113 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth83934062014-10-16 21:11:55 +00004114 for (Instruction *DeadUser : AS.getDeadUsers()) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004115 // Free up everything used by this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004116 for (Use &DeadOp : DeadUser->operands())
Chandler Carruth1583e992014-03-03 10:42:58 +00004117 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004118
4119 // Now replace the uses of this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004120 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004121
4122 // And mark it for deletion.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004123 DeadInsts.insert(DeadUser);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004124 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004125 }
Chandler Carruth83934062014-10-16 21:11:55 +00004126 for (Use *DeadOp : AS.getDeadOperands()) {
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004127 clobberUse(*DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004128 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004129 }
4130
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004131 // No slices to split. Leave the dead alloca for a later pass to clean up.
Chandler Carruth83934062014-10-16 21:11:55 +00004132 if (AS.begin() == AS.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00004133 return Changed;
4134
Chandler Carruth83934062014-10-16 21:11:55 +00004135 Changed |= splitAlloca(AI, AS);
Chandler Carruthf0546402013-07-18 07:15:00 +00004136
4137 DEBUG(dbgs() << " Speculating PHIs\n");
4138 while (!SpeculatablePHIs.empty())
4139 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4140
4141 DEBUG(dbgs() << " Speculating Selects\n");
4142 while (!SpeculatableSelects.empty())
4143 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4144
4145 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004146}
4147
Chandler Carruth19450da2012-09-14 10:26:38 +00004148/// \brief Delete the dead instructions accumulated in this run.
4149///
4150/// Recursively deletes the dead instructions we've accumulated. This is done
4151/// at the very end to maximize locality of the recursive delete and to
4152/// minimize the problems of invalidated instruction pointers as such pointers
4153/// are used heavily in the intermediate stages of the algorithm.
4154///
4155/// We also record the alloca instructions deleted here so that they aren't
4156/// subsequently handed to mem2reg to promote.
Chandler Carruth113dc642014-12-20 02:39:18 +00004157void SROA::deleteDeadInstructions(
4158 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004159 while (!DeadInsts.empty()) {
4160 Instruction *I = DeadInsts.pop_back_val();
4161 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
4162
Chandler Carruth58d05562012-10-25 04:37:07 +00004163 I->replaceAllUsesWith(UndefValue::get(I->getType()));
4164
Chandler Carruth1583e992014-03-03 10:42:58 +00004165 for (Use &Operand : I->operands())
4166 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004167 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00004168 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004169 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00004170 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004171 }
4172
Adrian Prantl565cc182015-01-20 19:42:22 +00004173 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004174 DeletedAllocas.insert(AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004175 if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(AI))
4176 DbgDecl->eraseFromParent();
4177 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004178
4179 ++NumDeleted;
4180 I->eraseFromParent();
4181 }
4182}
4183
Chandler Carruth70b44c52012-09-15 11:43:14 +00004184/// \brief Promote the allocas, using the best available technique.
4185///
4186/// This attempts to promote whatever allocas have been identified as viable in
4187/// the PromotableAllocas list. If that list is empty, there is nothing to do.
Chandler Carruth748d0952015-08-26 09:09:29 +00004188/// This function returns whether any promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004189bool SROA::promoteAllocas(Function &F) {
4190 if (PromotableAllocas.empty())
4191 return false;
4192
4193 NumPromoted += PromotableAllocas.size();
4194
Chandler Carruth748d0952015-08-26 09:09:29 +00004195 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Davide Italiano612d5a92017-04-09 20:47:14 +00004196 PromoteMemToReg(PromotableAllocas, *DT, AC);
Chandler Carruth70b44c52012-09-15 11:43:14 +00004197 PromotableAllocas.clear();
4198 return true;
4199}
4200
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004201PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT,
4202 AssumptionCache &RunAC) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004203 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
4204 C = &F.getContext();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004205 DT = &RunDT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004206 AC = &RunAC;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004207
4208 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00004209 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Adrian Prantl565cc182015-01-20 19:42:22 +00004210 I != E; ++I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004211 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4212 Worklist.insert(AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004213 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004214
4215 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00004216 // A set of deleted alloca instruction pointers which should be removed from
4217 // the list of promotable allocas.
4218 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4219
Chandler Carruthac8317f2012-10-04 12:33:50 +00004220 do {
4221 while (!Worklist.empty()) {
4222 Changed |= runOnAlloca(*Worklist.pop_back_val());
4223 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00004224
Chandler Carruthac8317f2012-10-04 12:33:50 +00004225 // Remove the deleted allocas from various lists so that we don't try to
4226 // continue processing them.
4227 if (!DeletedAllocas.empty()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00004228 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00004229 Worklist.remove_if(IsInSet);
4230 PostPromotionWorklist.remove_if(IsInSet);
David Majnemerc7004902016-08-12 04:32:37 +00004231 PromotableAllocas.erase(remove_if(PromotableAllocas, IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00004232 PromotableAllocas.end());
4233 DeletedAllocas.clear();
4234 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004235 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004236
Chandler Carruthac8317f2012-10-04 12:33:50 +00004237 Changed |= promoteAllocas(F);
4238
4239 Worklist = PostPromotionWorklist;
4240 PostPromotionWorklist.clear();
4241 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004242
Davide Italiano16e96d42016-06-07 13:21:17 +00004243 if (!Changed)
4244 return PreservedAnalyses::all();
4245
Davide Italiano16e96d42016-06-07 13:21:17 +00004246 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00004247 PA.preserveSet<CFGAnalyses>();
Davide Italiano16e96d42016-06-07 13:21:17 +00004248 PA.preserve<GlobalsAA>();
4249 return PA;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004250}
4251
Sean Silva36e0d012016-08-09 00:28:15 +00004252PreservedAnalyses SROA::run(Function &F, FunctionAnalysisManager &AM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004253 return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F),
4254 AM.getResult<AssumptionAnalysis>(F));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004255}
Chandler Carruth29a18a42015-09-12 09:09:14 +00004256
4257/// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
4258///
4259/// This is in the llvm namespace purely to allow it to be a friend of the \c
4260/// SROA pass.
4261class llvm::sroa::SROALegacyPass : public FunctionPass {
4262 /// The SROA implementation.
4263 SROA Impl;
4264
4265public:
4266 SROALegacyPass() : FunctionPass(ID) {
4267 initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
4268 }
4269 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00004270 if (skipFunction(F))
Chandler Carruth29a18a42015-09-12 09:09:14 +00004271 return false;
4272
4273 auto PA = Impl.runImpl(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004274 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4275 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
Chandler Carruth29a18a42015-09-12 09:09:14 +00004276 return !PA.areAllPreserved();
4277 }
4278 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004279 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004280 AU.addRequired<DominatorTreeWrapperPass>();
4281 AU.addPreserved<GlobalsAAWrapperPass>();
4282 AU.setPreservesCFG();
4283 }
4284
Mehdi Amini117296c2016-10-01 02:56:57 +00004285 StringRef getPassName() const override { return "SROA"; }
Chandler Carruth29a18a42015-09-12 09:09:14 +00004286 static char ID;
4287};
4288
4289char SROALegacyPass::ID = 0;
4290
4291FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); }
4292
4293INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
4294 "Scalar Replacement Of Aggregates", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004295INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth29a18a42015-09-12 09:09:14 +00004296INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4297INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
4298 false, false)