blob: 83e5d38a0ad54b6d2564f876f1828d1cc274f489 [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"
Davide Italiano81a26da2017-04-27 23:09:01 +000028#include "llvm/ADT/SetVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/Statistic.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000031#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +000032#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000034#include "llvm/Analysis/PtrUseVisitor.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000037#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000039#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/DerivedTypes.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/IRBuilder.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000042#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Instructions.h"
44#include "llvm/IR/IntrinsicInst.h"
45#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/Operator.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000047#include "llvm/Pass.h"
Pavel Labathc207bec2016-11-09 12:07:12 +000048#include "llvm/Support/Chrono.h"
Chandler Carruth70b44c52012-09-15 11:43:14 +000049#include "llvm/Support/CommandLine.h"
Chandler Carruthf0546402013-07-18 07:15:00 +000050#include "llvm/Support/Compiler.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000051#include "llvm/Support/Debug.h"
52#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000053#include "llvm/Support/MathExtras.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000054#include "llvm/Support/raw_ostream.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +000055#include "llvm/Transforms/Scalar.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000056#include "llvm/Transforms/Utils/Local.h"
57#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Chandler Carruth83cee772014-02-25 03:59:29 +000058
Hal Finkel29f51312016-03-28 11:13:03 +000059#ifndef NDEBUG
60// We only use this for a debug check.
Chandler Carruth83cee772014-02-25 03:59:29 +000061#include <random>
62#endif
63
Chandler Carruth1b398ae2012-09-14 09:22:59 +000064using namespace llvm;
Chandler Carruth29a18a42015-09-12 09:09:14 +000065using namespace llvm::sroa;
Chandler Carruth1b398ae2012-09-14 09:22:59 +000066
Chandler Carruth964daaa2014-04-22 02:55:47 +000067#define DEBUG_TYPE "sroa"
68
Chandler Carruth1b398ae2012-09-14 09:22:59 +000069STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000070STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +000071STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
72STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
73STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000074STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
75STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000076STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000077STATISTIC(NumDeleted, "Number of instructions deleted");
78STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000079
Chandler Carruth83cee772014-02-25 03:59:29 +000080/// Hidden option to enable randomly shuffling the slices to help uncover
81/// instability in their order.
82static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
83 cl::init(false), cl::Hidden);
84
Chandler Carruth3b79b2a2014-02-25 21:24:45 +000085/// Hidden option to experiment with completely strict handling of inbounds
86/// GEPs.
Chandler Carruth113dc642014-12-20 02:39:18 +000087static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
88 cl::Hidden);
Chandler Carruth3b79b2a2014-02-25 21:24:45 +000089
Chandler Carruth1b398ae2012-09-14 09:22:59 +000090namespace {
Mehdi Amini1e9c9252016-03-11 17:15:34 +000091/// \brief A custom IRBuilder inserter which prefixes all names, but only in
92/// Assert builds.
Mehdi Aminiba9fba82016-03-13 21:05:13 +000093class IRBuilderPrefixedInserter : public IRBuilderDefaultInserter {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000094 std::string Prefix;
Mehdi Amini1e9c9252016-03-11 17:15:34 +000095 const Twine getNameWithPrefix(const Twine &Name) const {
96 return Name.isTriviallyEmpty() ? Name : Prefix + Name;
97 }
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000098
99public:
100 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
101
102protected:
103 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
104 BasicBlock::iterator InsertPt) const {
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000105 IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name), BB,
106 InsertPt);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000107 }
108};
109
Chandler Carruthd177f862013-03-20 07:30:36 +0000110/// \brief Provide a typedef for IRBuilder that drops names in release builds.
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000111using IRBuilderTy = llvm::IRBuilder<ConstantFolder, IRBuilderPrefixedInserter>;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000112}
Chandler Carruthd177f862013-03-20 07:30:36 +0000113
114namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000115/// \brief A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000116///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000117/// This structure represents a slice of an alloca used by some instruction. It
118/// stores both the begin and end offsets of this use, a pointer to the use
119/// itself, and a flag indicating whether we can classify the use as splittable
120/// or not when forming partitions of the alloca.
121class Slice {
Chandler Carruthf74654d2013-03-18 08:36:46 +0000122 /// \brief The beginning offset of the range.
123 uint64_t BeginOffset;
124
125 /// \brief The ending offset, not included in the range.
126 uint64_t EndOffset;
127
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000128 /// \brief Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000129 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000130 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000131
132public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000133 Slice() : BeginOffset(), EndOffset() {}
134 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000135 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000136 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000137
138 uint64_t beginOffset() const { return BeginOffset; }
139 uint64_t endOffset() const { return EndOffset; }
140
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000141 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
142 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000143
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000144 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000145
Craig Topperf40110f2014-04-25 05:29:35 +0000146 bool isDead() const { return getUse() == nullptr; }
147 void kill() { UseAndIsSplittable.setPointer(nullptr); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000148
149 /// \brief Support for ordering ranges.
150 ///
151 /// This provides an ordering over ranges such that start offsets are
152 /// always increasing, and within equal start offsets, the end offsets are
153 /// decreasing. Thus the spanning range comes first in a cluster with the
154 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000155 bool operator<(const Slice &RHS) const {
Chandler Carruth113dc642014-12-20 02:39:18 +0000156 if (beginOffset() < RHS.beginOffset())
157 return true;
158 if (beginOffset() > RHS.beginOffset())
159 return false;
160 if (isSplittable() != RHS.isSplittable())
161 return !isSplittable();
162 if (endOffset() > RHS.endOffset())
163 return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000164 return false;
165 }
166
167 /// \brief Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000168 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000169 uint64_t RHSOffset) {
170 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000171 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000172 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000173 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000174 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000175 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000176
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000177 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000178 return isSplittable() == RHS.isSplittable() &&
179 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000180 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000181 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000182};
Chandler Carruthf0546402013-07-18 07:15:00 +0000183} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000184
185namespace llvm {
Chandler Carruthf0546402013-07-18 07:15:00 +0000186template <typename T> struct isPodLike;
Chandler Carruth113dc642014-12-20 02:39:18 +0000187template <> struct isPodLike<Slice> { static const bool value = true; };
Chandler Carruthf74654d2013-03-18 08:36:46 +0000188}
189
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000190/// \brief Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000191///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000192/// This class represents the slices of an alloca which are formed by its
193/// various uses. If a pointer escapes, we can't fully build a representation
194/// for the slices used and we reflect that in this structure. The uses are
195/// stored, sorted by increasing beginning offset and with unsplittable slices
196/// starting at a particular offset before splittable slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000197class llvm::sroa::AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000198public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000199 /// \brief Construct the slices of a particular alloca.
200 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000201
202 /// \brief Test whether a pointer to the allocation escapes our analysis.
203 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000204 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000205 /// ignored.
206 bool isEscaped() const { return PointerEscapingInstr; }
207
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000208 /// \brief Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000209 /// @{
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000210 typedef SmallVectorImpl<Slice>::iterator iterator;
Chandler Carruthc659df92014-10-16 20:24:07 +0000211 typedef iterator_range<iterator> range;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000212 iterator begin() { return Slices.begin(); }
213 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000214
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000215 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
Chandler Carruthc659df92014-10-16 20:24:07 +0000216 typedef iterator_range<const_iterator> const_range;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000217 const_iterator begin() const { return Slices.begin(); }
218 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000219 /// @}
220
Chandler Carruth0715cba2015-01-01 11:54:38 +0000221 /// \brief Erase a range of slices.
Chandler Carruth994cde82015-01-01 12:01:03 +0000222 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
Chandler Carruth0715cba2015-01-01 11:54:38 +0000223
224 /// \brief Insert new slices for this alloca.
225 ///
226 /// This moves the slices into the alloca's slices collection, and re-sorts
227 /// everything so that the usual ordering properties of the alloca's slices
228 /// hold.
229 void insert(ArrayRef<Slice> NewSlices) {
230 int OldSize = Slices.size();
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000231 Slices.append(NewSlices.begin(), NewSlices.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +0000232 auto SliceI = Slices.begin() + OldSize;
233 std::sort(SliceI, Slices.end());
234 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
235 }
236
Chandler Carruth29a18a42015-09-12 09:09:14 +0000237 // Forward declare the iterator and range accessor for walking the
238 // partitions.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000239 class partition_iterator;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000240 iterator_range<partition_iterator> partitions();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000241
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000242 /// \brief Access the dead users for this alloca.
243 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000244
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000245 /// \brief Access the dead operands referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000246 ///
247 /// These are operands which have cannot actually be used to refer to the
248 /// alloca as they are outside its range and the user doesn't correct for
249 /// that. These mostly consist of PHI node inputs and the like which we just
250 /// need to replace with undef.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000251 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000252
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000253#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000254 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000255 void printSlice(raw_ostream &OS, const_iterator I,
256 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000257 void printUse(raw_ostream &OS, const_iterator I,
258 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000259 void print(raw_ostream &OS) const;
Alp Tokerf929e092014-01-04 22:47:48 +0000260 void dump(const_iterator I) const;
261 void dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000262#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000263
264private:
265 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000266 class SliceBuilder;
267 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000268
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000269#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000270 /// \brief Handle to alloca instruction to simplify method interfaces.
271 AllocaInst &AI;
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000272#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000273
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000274 /// \brief The instruction responsible for this alloca not having a known set
275 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000276 ///
277 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000278 /// store a pointer to that here and abort trying to form slices of the
279 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000280 Instruction *PointerEscapingInstr;
281
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000282 /// \brief The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000283 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000284 /// We store a vector of the slices formed by uses of the alloca here. This
285 /// vector is sorted by increasing begin offset, and then the unsplittable
286 /// slices before the splittable ones. See the Slice inner class for more
287 /// details.
288 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000289
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000290 /// \brief Instructions which will become dead if we rewrite the alloca.
291 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000292 /// Note that these are not separated by slice. This is because we expect an
293 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
294 /// all these instructions can simply be removed and replaced with undef as
295 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000296 SmallVector<Instruction *, 8> DeadUsers;
297
298 /// \brief Operands which will become dead if we rewrite the alloca.
299 ///
300 /// These are operands that in their particular use can be replaced with
301 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
302 /// to PHI nodes and the like. They aren't entirely dead (there might be
303 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
304 /// want to swap this particular input for undef to simplify the use lists of
305 /// the alloca.
306 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000307};
Chandler Carruth29a18a42015-09-12 09:09:14 +0000308
309/// \brief A partition of the slices.
310///
311/// An ephemeral representation for a range of slices which can be viewed as
312/// a partition of the alloca. This range represents a span of the alloca's
313/// memory which cannot be split, and provides access to all of the slices
314/// overlapping some part of the partition.
315///
316/// Objects of this type are produced by traversing the alloca's slices, but
317/// are only ephemeral and not persistent.
318class llvm::sroa::Partition {
319private:
320 friend class AllocaSlices;
321 friend class AllocaSlices::partition_iterator;
322
323 typedef AllocaSlices::iterator iterator;
324
325 /// \brief The beginning and ending offsets of the alloca for this
326 /// partition.
327 uint64_t BeginOffset, EndOffset;
328
Hiroshi Inoueac9cd302017-05-29 08:37:42 +0000329 /// \brief The start and end iterators of this partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000330 iterator SI, SJ;
331
332 /// \brief A collection of split slice tails overlapping the partition.
333 SmallVector<Slice *, 4> SplitTails;
334
335 /// \brief Raw constructor builds an empty partition starting and ending at
336 /// the given iterator.
337 Partition(iterator SI) : SI(SI), SJ(SI) {}
338
339public:
340 /// \brief The start offset of this partition.
341 ///
342 /// All of the contained slices start at or after this offset.
343 uint64_t beginOffset() const { return BeginOffset; }
344
345 /// \brief The end offset of this partition.
346 ///
347 /// All of the contained slices end at or before this offset.
348 uint64_t endOffset() const { return EndOffset; }
349
350 /// \brief The size of the partition.
351 ///
352 /// Note that this can never be zero.
353 uint64_t size() const {
354 assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
355 return EndOffset - BeginOffset;
356 }
357
358 /// \brief Test whether this partition contains no slices, and merely spans
359 /// a region occupied by split slices.
360 bool empty() const { return SI == SJ; }
361
362 /// \name Iterate slices that start within the partition.
363 /// These may be splittable or unsplittable. They have a begin offset >= the
364 /// partition begin offset.
365 /// @{
366 // FIXME: We should probably define a "concat_iterator" helper and use that
367 // to stitch together pointee_iterators over the split tails and the
368 // contiguous iterators of the partition. That would give a much nicer
369 // interface here. We could then additionally expose filtered iterators for
370 // split, unsplit, and unsplittable splices based on the usage patterns.
371 iterator begin() const { return SI; }
372 iterator end() const { return SJ; }
373 /// @}
374
375 /// \brief Get the sequence of split slice tails.
376 ///
377 /// These tails are of slices which start before this partition but are
378 /// split and overlap into the partition. We accumulate these while forming
379 /// partitions.
380 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
381};
382
383/// \brief An iterator over partitions of the alloca's slices.
384///
385/// This iterator implements the core algorithm for partitioning the alloca's
386/// slices. It is a forward iterator as we don't support backtracking for
387/// efficiency reasons, and re-use a single storage area to maintain the
388/// current set of split slices.
389///
390/// It is templated on the slice iterator type to use so that it can operate
391/// with either const or non-const slice iterators.
392class AllocaSlices::partition_iterator
393 : public iterator_facade_base<partition_iterator, std::forward_iterator_tag,
394 Partition> {
395 friend class AllocaSlices;
396
397 /// \brief Most of the state for walking the partitions is held in a class
398 /// with a nice interface for examining them.
399 Partition P;
400
401 /// \brief We need to keep the end of the slices to know when to stop.
402 AllocaSlices::iterator SE;
403
404 /// \brief We also need to keep track of the maximum split end offset seen.
405 /// FIXME: Do we really?
406 uint64_t MaxSplitSliceEndOffset;
407
408 /// \brief Sets the partition to be empty at given iterator, and sets the
409 /// end iterator.
410 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
411 : P(SI), SE(SE), MaxSplitSliceEndOffset(0) {
412 // If not already at the end, advance our state to form the initial
413 // partition.
414 if (SI != SE)
415 advance();
416 }
417
418 /// \brief Advance the iterator to the next partition.
419 ///
420 /// Requires that the iterator not be at the end of the slices.
421 void advance() {
422 assert((P.SI != SE || !P.SplitTails.empty()) &&
423 "Cannot advance past the end of the slices!");
424
425 // Clear out any split uses which have ended.
426 if (!P.SplitTails.empty()) {
427 if (P.EndOffset >= MaxSplitSliceEndOffset) {
428 // If we've finished all splits, this is easy.
429 P.SplitTails.clear();
430 MaxSplitSliceEndOffset = 0;
431 } else {
432 // Remove the uses which have ended in the prior partition. This
433 // cannot change the max split slice end because we just checked that
434 // the prior partition ended prior to that max.
435 P.SplitTails.erase(
David Majnemer0a16c222016-08-11 21:15:00 +0000436 remove_if(P.SplitTails,
437 [&](Slice *S) { return S->endOffset() <= P.EndOffset; }),
Chandler Carruth29a18a42015-09-12 09:09:14 +0000438 P.SplitTails.end());
David Majnemer0a16c222016-08-11 21:15:00 +0000439 assert(any_of(P.SplitTails,
440 [&](Slice *S) {
441 return S->endOffset() == MaxSplitSliceEndOffset;
442 }) &&
Chandler Carruth29a18a42015-09-12 09:09:14 +0000443 "Could not find the current max split slice offset!");
David Majnemer0a16c222016-08-11 21:15:00 +0000444 assert(all_of(P.SplitTails,
445 [&](Slice *S) {
446 return S->endOffset() <= MaxSplitSliceEndOffset;
447 }) &&
Chandler Carruth29a18a42015-09-12 09:09:14 +0000448 "Max split slice end offset is not actually the max!");
449 }
450 }
451
452 // If P.SI is already at the end, then we've cleared the split tail and
453 // now have an end iterator.
454 if (P.SI == SE) {
455 assert(P.SplitTails.empty() && "Failed to clear the split slices!");
456 return;
457 }
458
459 // If we had a non-empty partition previously, set up the state for
460 // subsequent partitions.
461 if (P.SI != P.SJ) {
462 // Accumulate all the splittable slices which started in the old
463 // partition into the split list.
464 for (Slice &S : P)
465 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
466 P.SplitTails.push_back(&S);
467 MaxSplitSliceEndOffset =
468 std::max(S.endOffset(), MaxSplitSliceEndOffset);
469 }
470
471 // Start from the end of the previous partition.
472 P.SI = P.SJ;
473
474 // If P.SI is now at the end, we at most have a tail of split slices.
475 if (P.SI == SE) {
476 P.BeginOffset = P.EndOffset;
477 P.EndOffset = MaxSplitSliceEndOffset;
478 return;
479 }
480
481 // If the we have split slices and the next slice is after a gap and is
482 // not splittable immediately form an empty partition for the split
483 // slices up until the next slice begins.
484 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
485 !P.SI->isSplittable()) {
486 P.BeginOffset = P.EndOffset;
487 P.EndOffset = P.SI->beginOffset();
488 return;
489 }
490 }
491
492 // OK, we need to consume new slices. Set the end offset based on the
493 // current slice, and step SJ past it. The beginning offset of the
494 // partition is the beginning offset of the next slice unless we have
495 // pre-existing split slices that are continuing, in which case we begin
496 // at the prior end offset.
497 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
498 P.EndOffset = P.SI->endOffset();
499 ++P.SJ;
500
501 // There are two strategies to form a partition based on whether the
502 // partition starts with an unsplittable slice or a splittable slice.
503 if (!P.SI->isSplittable()) {
504 // When we're forming an unsplittable region, it must always start at
505 // the first slice and will extend through its end.
506 assert(P.BeginOffset == P.SI->beginOffset());
507
508 // Form a partition including all of the overlapping slices with this
509 // unsplittable slice.
510 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
511 if (!P.SJ->isSplittable())
512 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
513 ++P.SJ;
514 }
515
516 // We have a partition across a set of overlapping unsplittable
517 // partitions.
518 return;
519 }
520
521 // If we're starting with a splittable slice, then we need to form
522 // a synthetic partition spanning it and any other overlapping splittable
523 // splices.
524 assert(P.SI->isSplittable() && "Forming a splittable partition!");
525
526 // Collect all of the overlapping splittable slices.
527 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
528 P.SJ->isSplittable()) {
529 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
530 ++P.SJ;
531 }
532
533 // Back upiP.EndOffset if we ended the span early when encountering an
534 // unsplittable slice. This synthesizes the early end offset of
535 // a partition spanning only splittable slices.
536 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
537 assert(!P.SJ->isSplittable());
538 P.EndOffset = P.SJ->beginOffset();
539 }
540 }
541
542public:
543 bool operator==(const partition_iterator &RHS) const {
544 assert(SE == RHS.SE &&
545 "End iterators don't match between compared partition iterators!");
546
547 // The observed positions of partitions is marked by the P.SI iterator and
548 // the emptiness of the split slices. The latter is only relevant when
549 // P.SI == SE, as the end iterator will additionally have an empty split
550 // slices list, but the prior may have the same P.SI and a tail of split
551 // slices.
552 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
553 assert(P.SJ == RHS.P.SJ &&
554 "Same set of slices formed two different sized partitions!");
555 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
556 "Same slice position with differently sized non-empty split "
557 "slice tails!");
558 return true;
559 }
560 return false;
561 }
562
563 partition_iterator &operator++() {
564 advance();
565 return *this;
566 }
567
568 Partition &operator*() { return P; }
569};
570
571/// \brief A forward range over the partitions of the alloca's slices.
572///
573/// This accesses an iterator range over the partitions of the alloca's
574/// slices. It computes these partitions on the fly based on the overlapping
575/// offsets of the slices and the ability to split them. It will visit "empty"
576/// partitions to cover regions of the alloca only accessed via split
577/// slices.
578iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() {
579 return make_range(partition_iterator(begin(), end()),
580 partition_iterator(end(), end()));
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000581}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000582
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000583static Value *foldSelectInst(SelectInst &SI) {
584 // If the condition being selected on is a constant or the same value is
585 // being selected between, fold the select. Yes this does (rarely) happen
586 // early on.
587 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
Chandler Carruth113dc642014-12-20 02:39:18 +0000588 return SI.getOperand(1 + CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000589 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000590 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000591
Craig Topperf40110f2014-04-25 05:29:35 +0000592 return nullptr;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000593}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000594
Jingyue Wuec33fa92014-08-22 22:45:57 +0000595/// \brief A helper that folds a PHI node or a select.
596static Value *foldPHINodeOrSelectInst(Instruction &I) {
597 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
598 // If PN merges together the same value, return that value.
599 return PN->hasConstantValue();
600 }
601 return foldSelectInst(cast<SelectInst>(I));
602}
603
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000604/// \brief Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000605///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000606/// This class builds a set of alloca slices by recursively visiting the uses
607/// of an alloca and making a slice for each load and store at each offset.
608class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
609 friend class PtrUseVisitor<SliceBuilder>;
610 friend class InstVisitor<SliceBuilder>;
611 typedef PtrUseVisitor<SliceBuilder> Base;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000612
613 const uint64_t AllocSize;
Chandler Carruth83934062014-10-16 21:11:55 +0000614 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000615
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000616 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000617 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
618
619 /// \brief Set to de-duplicate dead instructions found in the use walk.
620 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000621
622public:
Chandler Carruth83934062014-10-16 21:11:55 +0000623 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000624 : PtrUseVisitor<SliceBuilder>(DL),
Chandler Carruth83934062014-10-16 21:11:55 +0000625 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000626
627private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000628 void markAsDead(Instruction &I) {
David Blaikie70573dc2014-11-19 07:49:26 +0000629 if (VisitedDeadInsts.insert(&I).second)
Chandler Carruth83934062014-10-16 21:11:55 +0000630 AS.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000631 }
632
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000633 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000634 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000635 // Completely skip uses which have a zero size or start either before or
636 // past the end of the allocation.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000637 if (Size == 0 || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000638 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000639 << " which has zero size or starts outside of the "
640 << AllocSize << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000641 << " alloca: " << AS.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000642 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000643 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000644 }
645
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000646 uint64_t BeginOffset = Offset.getZExtValue();
647 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000648
649 // Clamp the end offset to the end of the allocation. Note that this is
650 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000651 // This may appear superficially to be something we could ignore entirely,
652 // but that is not so! There may be widened loads or PHI-node uses where
653 // some instructions are dead but not others. We can't completely ignore
654 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000655 assert(AllocSize >= BeginOffset); // Established above.
656 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000657 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
658 << " to remain within the " << AllocSize << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000659 << " alloca: " << AS.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000660 << " use: " << I << "\n");
661 EndOffset = AllocSize;
662 }
663
Chandler Carruth83934062014-10-16 21:11:55 +0000664 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000665 }
666
667 void visitBitCastInst(BitCastInst &BC) {
668 if (BC.use_empty())
669 return markAsDead(BC);
670
671 return Base::visitBitCastInst(BC);
672 }
673
674 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
675 if (GEPI.use_empty())
676 return markAsDead(GEPI);
677
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000678 if (SROAStrictInbounds && GEPI.isInBounds()) {
679 // FIXME: This is a manually un-factored variant of the basic code inside
680 // of GEPs with checking of the inbounds invariant specified in the
681 // langref in a very strict sense. If we ever want to enable
682 // SROAStrictInbounds, this code should be factored cleanly into
683 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
Hal Finkel5c83a092016-03-28 11:23:21 +0000684 // by writing out the code here where we have the underlying allocation
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000685 // size readily available.
686 APInt GEPOffset = Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000687 const DataLayout &DL = GEPI.getModule()->getDataLayout();
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000688 for (gep_type_iterator GTI = gep_type_begin(GEPI),
689 GTE = gep_type_end(GEPI);
690 GTI != GTE; ++GTI) {
691 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
692 if (!OpC)
693 break;
694
695 // Handle a struct index, which adds its field offset to the pointer.
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000696 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000697 unsigned ElementIdx = OpC->getZExtValue();
698 const StructLayout *SL = DL.getStructLayout(STy);
699 GEPOffset +=
700 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
701 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +0000702 // For array or vector indices, scale the index by the size of the
703 // type.
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000704 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
705 GEPOffset += Index * APInt(Offset.getBitWidth(),
706 DL.getTypeAllocSize(GTI.getIndexedType()));
707 }
708
709 // If this index has computed an intermediate pointer which is not
710 // inbounds, then the result of the GEP is a poison value and we can
711 // delete it and all uses.
712 if (GEPOffset.ugt(AllocSize))
713 return markAsDead(GEPI);
714 }
715 }
716
Chandler Carruthf0546402013-07-18 07:15:00 +0000717 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000718 }
719
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000720 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000721 uint64_t Size, bool IsVolatile) {
Chandler Carruth24ac8302015-01-02 03:55:54 +0000722 // We allow splitting of non-volatile loads and stores where the type is an
723 // integer type. These may be used to implement 'memcpy' or other "transfer
724 // of bits" patterns.
725 bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
Chandler Carruth58d05562012-10-25 04:37:07 +0000726
727 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000728 }
729
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000730 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000731 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
732 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000733
734 if (!IsOffsetKnown)
735 return PI.setAborted(&LI);
736
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000737 const DataLayout &DL = LI.getModule()->getDataLayout();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000738 uint64_t Size = DL.getTypeStoreSize(LI.getType());
739 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000740 }
741
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000742 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000743 Value *ValOp = SI.getValueOperand();
744 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000745 return PI.setEscapedAndAborted(&SI);
746 if (!IsOffsetKnown)
747 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000748
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000749 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000750 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
751
752 // If this memory access can be shown to *statically* extend outside the
753 // bounds of of the allocation, it's behavior is undefined, so simply
754 // ignore it. Note that this is more strict than the generic clamping
755 // behavior of insertUse. We also try to handle cases which might run the
756 // risk of overflow.
757 // FIXME: We should instead consider the pointer to have escaped if this
758 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000759 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000760 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
761 << " which extends past the end of the " << AllocSize
762 << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000763 << " alloca: " << AS.AI << "\n"
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000764 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000765 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000766 }
767
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000768 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
769 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000770 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000771 }
772
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000773 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000774 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000775 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000776 if ((Length && Length->getValue() == 0) ||
Chandler Carruth6aedc102014-02-26 03:14:14 +0000777 (IsOffsetKnown && Offset.uge(AllocSize)))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000778 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000779 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000780
781 if (!IsOffsetKnown)
782 return PI.setAborted(&II);
783
Chandler Carruth113dc642014-12-20 02:39:18 +0000784 insertUse(II, Offset, Length ? Length->getLimitedValue()
785 : AllocSize - Offset.getLimitedValue(),
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000786 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000787 }
788
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000789 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000790 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000791 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000792 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000793 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000794
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000795 // Because we can visit these intrinsics twice, also check to see if the
796 // first time marked this instruction as dead. If so, skip it.
797 if (VisitedDeadInsts.count(&II))
798 return;
799
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000800 if (!IsOffsetKnown)
801 return PI.setAborted(&II);
802
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000803 // This side of the transfer is completely out-of-bounds, and so we can
804 // nuke the entire transfer. However, we also need to nuke the other side
805 // if already added to our partitions.
806 // FIXME: Yet another place we really should bypass this when
807 // instrumenting for ASan.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000808 if (Offset.uge(AllocSize)) {
Chandler Carruth113dc642014-12-20 02:39:18 +0000809 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
810 MemTransferSliceMap.find(&II);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000811 if (MTPI != MemTransferSliceMap.end())
Chandler Carruth83934062014-10-16 21:11:55 +0000812 AS.Slices[MTPI->second].kill();
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000813 return markAsDead(II);
814 }
815
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000816 uint64_t RawOffset = Offset.getLimitedValue();
Chandler Carruth113dc642014-12-20 02:39:18 +0000817 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000818
Chandler Carruthf0546402013-07-18 07:15:00 +0000819 // Check for the special case where the same exact value is used for both
820 // source and dest.
821 if (*U == II.getRawDest() && *U == II.getRawSource()) {
822 // For non-volatile transfers this is a no-op.
823 if (!II.isVolatile())
824 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000825
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000826 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000827 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000828
Chandler Carruthf0546402013-07-18 07:15:00 +0000829 // If we have seen both source and destination for a mem transfer, then
830 // they both point to the same alloca.
831 bool Inserted;
832 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000833 std::tie(MTPI, Inserted) =
Chandler Carruth83934062014-10-16 21:11:55 +0000834 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000835 unsigned PrevIdx = MTPI->second;
836 if (!Inserted) {
Chandler Carruth83934062014-10-16 21:11:55 +0000837 Slice &PrevP = AS.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000838
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000839 // Check if the begin offsets match and this is a non-volatile transfer.
840 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000841 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
842 PrevP.kill();
843 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000844 }
845
846 // Otherwise we have an offset transfer within the same alloca. We can't
847 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000848 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000849 }
850
Chandler Carruthe3899f22013-07-15 17:36:21 +0000851 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000852 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000853
Chandler Carruthf0546402013-07-18 07:15:00 +0000854 // Check that we ended up with a valid index in the map.
Chandler Carruth83934062014-10-16 21:11:55 +0000855 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000856 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000857 }
858
859 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000860 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000861 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000862 void visitIntrinsicInst(IntrinsicInst &II) {
863 if (!IsOffsetKnown)
864 return PI.setAborted(&II);
865
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000866 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
867 II.getIntrinsicID() == Intrinsic::lifetime_end) {
868 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000869 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
870 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000871 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000872 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000873 }
874
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000875 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000876 }
877
878 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
879 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000880 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000881 // are considered unsplittable and the size is the maximum loaded or stored
882 // size.
883 SmallPtrSet<Instruction *, 4> Visited;
884 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
885 Visited.insert(Root);
886 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000887 const DataLayout &DL = Root->getModule()->getDataLayout();
Chandler Carruth8b907e82012-09-25 10:03:40 +0000888 // If there are no loads or stores, the access is dead. We mark that as
889 // a size zero access.
890 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000891 do {
892 Instruction *I, *UsedI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000893 std::tie(UsedI, I) = Uses.pop_back_val();
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000894
895 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000896 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000897 continue;
898 }
899 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
900 Value *Op = SI->getOperand(0);
901 if (Op == UsedI)
902 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000903 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000904 continue;
905 }
906
907 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
908 if (!GEP->hasAllZeroIndices())
909 return GEP;
910 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
911 !isa<SelectInst>(I)) {
912 return I;
913 }
914
Chandler Carruthcdf47882014-03-09 03:16:01 +0000915 for (User *U : I->users())
David Blaikie70573dc2014-11-19 07:49:26 +0000916 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000917 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000918 } while (!Uses.empty());
919
Craig Topperf40110f2014-04-25 05:29:35 +0000920 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000921 }
922
Jingyue Wuec33fa92014-08-22 22:45:57 +0000923 void visitPHINodeOrSelectInst(Instruction &I) {
924 assert(isa<PHINode>(I) || isa<SelectInst>(I));
925 if (I.use_empty())
926 return markAsDead(I);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000927
Jingyue Wuec33fa92014-08-22 22:45:57 +0000928 // TODO: We could use SimplifyInstruction here to fold PHINodes and
929 // SelectInsts. However, doing so requires to change the current
930 // dead-operand-tracking mechanism. For instance, suppose neither loading
931 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
932 // trap either. However, if we simply replace %U with undef using the
933 // current dead-operand-tracking mechanism, "load (select undef, undef,
934 // %other)" may trap because the select may return the first operand
935 // "undef".
936 if (Value *Result = foldPHINodeOrSelectInst(I)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000937 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000938 // If the result of the constant fold will be the pointer, recurse
Jingyue Wuec33fa92014-08-22 22:45:57 +0000939 // through the PHI/select as if we had RAUW'ed it.
940 enqueueUsers(I);
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000941 else
Jingyue Wuec33fa92014-08-22 22:45:57 +0000942 // Otherwise the operand to the PHI/select is dead, and we can replace
943 // it with undef.
Chandler Carruth83934062014-10-16 21:11:55 +0000944 AS.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000945
946 return;
947 }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000948
Chandler Carruthf0546402013-07-18 07:15:00 +0000949 if (!IsOffsetKnown)
Jingyue Wuec33fa92014-08-22 22:45:57 +0000950 return PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000951
Chandler Carruthf0546402013-07-18 07:15:00 +0000952 // See if we already have computed info on this node.
Jingyue Wuec33fa92014-08-22 22:45:57 +0000953 uint64_t &Size = PHIOrSelectSizes[&I];
954 if (!Size) {
955 // This is a new PHI/Select, check for an unsafe use of it.
956 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
Chandler Carruthf0546402013-07-18 07:15:00 +0000957 return PI.setAborted(UnsafeI);
958 }
959
960 // For PHI and select operands outside the alloca, we can't nuke the entire
961 // phi or select -- the other side might still be relevant, so we special
962 // case them here and use a separate structure to track the operands
963 // themselves which should be replaced with undef.
964 // FIXME: This should instead be escaped in the event we're instrumenting
965 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000966 if (Offset.uge(AllocSize)) {
Chandler Carruth83934062014-10-16 21:11:55 +0000967 AS.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +0000968 return;
969 }
970
Jingyue Wuec33fa92014-08-22 22:45:57 +0000971 insertUse(I, Offset, Size);
972 }
973
Chandler Carruth113dc642014-12-20 02:39:18 +0000974 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000975
Chandler Carruth113dc642014-12-20 02:39:18 +0000976 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000977
Chandler Carruthf0546402013-07-18 07:15:00 +0000978 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth113dc642014-12-20 02:39:18 +0000979 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000980};
981
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000982AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000983 :
984#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
985 AI(AI),
986#endif
Craig Topperf40110f2014-04-25 05:29:35 +0000987 PointerEscapingInstr(nullptr) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000988 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000989 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000990 if (PtrI.isEscaped() || PtrI.isAborted()) {
991 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000992 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000993 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
994 : PtrI.getAbortingInst();
995 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000996 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000997 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000998
David Majnemerc7004902016-08-12 04:32:37 +0000999 Slices.erase(remove_if(Slices, [](const Slice &S) { return S.isDead(); }),
Benjamin Kramer08e50702013-07-20 08:38:34 +00001000 Slices.end());
1001
Hal Finkel29f51312016-03-28 11:13:03 +00001002#ifndef NDEBUG
Chandler Carruth83cee772014-02-25 03:59:29 +00001003 if (SROARandomShuffleSlices) {
Pavel Labathc207bec2016-11-09 12:07:12 +00001004 std::mt19937 MT(static_cast<unsigned>(
1005 std::chrono::system_clock::now().time_since_epoch().count()));
Chandler Carruth83cee772014-02-25 03:59:29 +00001006 std::shuffle(Slices.begin(), Slices.end(), MT);
1007 }
1008#endif
1009
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001010 // Sort the uses. This arranges for the offsets to be in ascending order,
1011 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001012 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001013}
1014
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001015#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1016
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001017void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1018 StringRef Indent) const {
1019 printSlice(OS, I, Indent);
Chandler Carruth0715cba2015-01-01 11:54:38 +00001020 OS << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001021 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001022}
1023
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001024void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1025 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001026 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001027 << " slice #" << (I - begin())
Chandler Carruth0715cba2015-01-01 11:54:38 +00001028 << (I->isSplittable() ? " (splittable)" : "");
Chandler Carruthf0546402013-07-18 07:15:00 +00001029}
1030
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001031void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1032 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001033 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001034}
1035
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001036void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001037 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001038 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001039 << " A pointer to this alloca escaped by:\n"
1040 << " " << *PointerEscapingInstr << "\n";
1041 return;
1042 }
1043
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001044 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001045 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001046 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001047}
1048
Alp Tokerf929e092014-01-04 22:47:48 +00001049LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1050 print(dbgs(), I);
1051}
1052LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001053
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001054#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1055
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001056/// Walk the range of a partitioning looking for a common type to cover this
1057/// sequence of slices.
1058static Type *findCommonType(AllocaSlices::const_iterator B,
1059 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001060 uint64_t EndOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001061 Type *Ty = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001062 bool TyIsCommon = true;
Craig Topperf40110f2014-04-25 05:29:35 +00001063 IntegerType *ITy = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001064
1065 // Note that we need to look at *every* alloca slice's Use to ensure we
1066 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001067 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001068 Use *U = I->getUse();
1069 if (isa<IntrinsicInst>(*U->getUser()))
1070 continue;
1071 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1072 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001073
Craig Topperf40110f2014-04-25 05:29:35 +00001074 Type *UserTy = nullptr;
Chandler Carrutha1262002013-11-19 09:03:18 +00001075 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001076 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001077 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001078 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001079 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001080
Chandler Carruth4de31542014-01-21 23:16:05 +00001081 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001082 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001083 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001084 // entity causing the split. Also skip if the type is not a byte width
1085 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001086 if (UserITy->getBitWidth() % 8 != 0 ||
1087 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001088 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001089
Chandler Carruth4de31542014-01-21 23:16:05 +00001090 // Track the largest bitwidth integer type used in this way in case there
1091 // is no common type.
1092 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1093 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001094 }
Duncan P. N. Exon Smith73686d32014-06-17 00:19:35 +00001095
1096 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1097 // depend on types skipped above.
1098 if (!UserTy || (Ty && Ty != UserTy))
1099 TyIsCommon = false; // Give up on anything but an iN type.
1100 else
1101 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001102 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001103
1104 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001105}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001106
Chandler Carruthf0546402013-07-18 07:15:00 +00001107/// PHI instructions that use an alloca and are subsequently loaded can be
1108/// rewritten to load both input pointers in the pred blocks and then PHI the
1109/// results, allowing the load of the alloca to be promoted.
1110/// From this:
1111/// %P2 = phi [i32* %Alloca, i32* %Other]
1112/// %V = load i32* %P2
1113/// to:
1114/// %V1 = load i32* %Alloca -> will be mem2reg'd
1115/// ...
1116/// %V2 = load i32* %Other
1117/// ...
1118/// %V = phi [i32 %V1, i32 %V2]
1119///
1120/// We can do this to a select if its only uses are loads and if the operands
1121/// to the select can be loaded unconditionally.
1122///
1123/// FIXME: This should be hoisted into a generic utility, likely in
1124/// Transforms/Util/Local.h
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001125static bool isSafePHIToSpeculate(PHINode &PN) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001126 // For now, we can only do this promotion if the load is in the same block
1127 // as the PHI, and if there are no stores between the phi and load.
1128 // TODO: Allow recursive phi users.
1129 // TODO: Allow stores.
1130 BasicBlock *BB = PN.getParent();
1131 unsigned MaxAlign = 0;
1132 bool HaveLoad = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001133 for (User *U : PN.users()) {
1134 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001135 if (!LI || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001136 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001137
Chandler Carruthf0546402013-07-18 07:15:00 +00001138 // For now we only allow loads in the same block as the PHI. This is
1139 // a common case that happens when instcombine merges two loads through
1140 // a PHI.
1141 if (LI->getParent() != BB)
1142 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001143
Chandler Carruthf0546402013-07-18 07:15:00 +00001144 // Ensure that there are no instructions between the PHI and the load that
1145 // could store.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001146 for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
Chandler Carruthf0546402013-07-18 07:15:00 +00001147 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001148 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001149
Chandler Carruthf0546402013-07-18 07:15:00 +00001150 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1151 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001152 }
1153
Chandler Carruthf0546402013-07-18 07:15:00 +00001154 if (!HaveLoad)
1155 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001156
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001157 const DataLayout &DL = PN.getModule()->getDataLayout();
1158
Chandler Carruthf0546402013-07-18 07:15:00 +00001159 // We can only transform this if it is safe to push the loads into the
1160 // predecessor blocks. The only thing to watch out for is that we can't put
1161 // a possibly trapping load in the predecessor if it is a critical edge.
1162 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1163 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1164 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001165
Chandler Carruthf0546402013-07-18 07:15:00 +00001166 // If the value is produced by the terminator of the predecessor (an
1167 // invoke) or it has side-effects, there is no valid place to put a load
1168 // in the predecessor.
1169 if (TI == InVal || TI->mayHaveSideEffects())
1170 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001171
Chandler Carruthf0546402013-07-18 07:15:00 +00001172 // If the predecessor has a single successor, then the edge isn't
1173 // critical.
1174 if (TI->getNumSuccessors() == 1)
1175 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001176
Chandler Carruthf0546402013-07-18 07:15:00 +00001177 // If this pointer is always safe to load, or if we can prove that there
1178 // is already a load in the block, then we can move the load to the pred
1179 // block.
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001180 if (isSafeToLoadUnconditionally(InVal, MaxAlign, DL, TI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001181 continue;
1182
1183 return false;
1184 }
1185
1186 return true;
1187}
1188
1189static void speculatePHINodeLoads(PHINode &PN) {
1190 DEBUG(dbgs() << " original: " << PN << "\n");
1191
1192 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1193 IRBuilderTy PHIBuilder(&PN);
1194 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1195 PN.getName() + ".sroa.speculated");
1196
Hal Finkelcc39b672014-07-24 12:16:19 +00001197 // Get the AA tags and alignment to use from one of the loads. It doesn't
Chandler Carruthf0546402013-07-18 07:15:00 +00001198 // matter which one we get and if any differ.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001199 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
Hal Finkelcc39b672014-07-24 12:16:19 +00001200
1201 AAMDNodes AATags;
1202 SomeLoad->getAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001203 unsigned Align = SomeLoad->getAlignment();
1204
1205 // Rewrite all loads of the PN to use the new PHI.
1206 while (!PN.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001207 LoadInst *LI = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001208 LI->replaceAllUsesWith(NewPN);
1209 LI->eraseFromParent();
1210 }
1211
1212 // Inject loads into all of the pred blocks.
1213 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1214 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1215 TerminatorInst *TI = Pred->getTerminator();
1216 Value *InVal = PN.getIncomingValue(Idx);
1217 IRBuilderTy PredBuilder(TI);
1218
1219 LoadInst *Load = PredBuilder.CreateLoad(
1220 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1221 ++NumLoadsSpeculated;
1222 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001223 if (AATags)
1224 Load->setAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001225 NewPN->addIncoming(Load, Pred);
1226 }
1227
1228 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1229 PN.eraseFromParent();
1230}
1231
1232/// Select instructions that use an alloca and are subsequently loaded can be
1233/// rewritten to load both input pointers and then select between the result,
1234/// allowing the load of the alloca to be promoted.
1235/// From this:
1236/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1237/// %V = load i32* %P2
1238/// to:
1239/// %V1 = load i32* %Alloca -> will be mem2reg'd
1240/// %V2 = load i32* %Other
1241/// %V = select i1 %cond, i32 %V1, i32 %V2
1242///
1243/// We can do this to a select if its only uses are loads and if the operand
1244/// to the select can be loaded unconditionally.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001245static bool isSafeSelectToSpeculate(SelectInst &SI) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001246 Value *TValue = SI.getTrueValue();
1247 Value *FValue = SI.getFalseValue();
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001248 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00001249
Chandler Carruthcdf47882014-03-09 03:16:01 +00001250 for (User *U : SI.users()) {
1251 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001252 if (!LI || !LI->isSimple())
Chandler Carruthf0546402013-07-18 07:15:00 +00001253 return false;
1254
Hiroshi Inoueb3008242017-06-24 15:43:33 +00001255 // Both operands to the select need to be dereferenceable, either
Chandler Carruthf0546402013-07-18 07:15:00 +00001256 // absolutely (e.g. allocas) or at this point because we can see other
1257 // accesses to it.
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001258 if (!isSafeToLoadUnconditionally(TValue, LI->getAlignment(), DL, LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001259 return false;
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001260 if (!isSafeToLoadUnconditionally(FValue, LI->getAlignment(), DL, LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001261 return false;
1262 }
1263
1264 return true;
1265}
1266
1267static void speculateSelectInstLoads(SelectInst &SI) {
1268 DEBUG(dbgs() << " original: " << SI << "\n");
1269
1270 IRBuilderTy IRB(&SI);
1271 Value *TV = SI.getTrueValue();
1272 Value *FV = SI.getFalseValue();
1273 // Replace the loads of the select with a select of two loads.
1274 while (!SI.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001275 LoadInst *LI = cast<LoadInst>(SI.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001276 assert(LI->isSimple() && "We only speculate simple loads");
1277
1278 IRB.SetInsertPoint(LI);
1279 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001280 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001281 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001282 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001283 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001284
Hal Finkelcc39b672014-07-24 12:16:19 +00001285 // Transfer alignment and AA info if present.
Chandler Carruthf0546402013-07-18 07:15:00 +00001286 TL->setAlignment(LI->getAlignment());
1287 FL->setAlignment(LI->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +00001288
1289 AAMDNodes Tags;
1290 LI->getAAMetadata(Tags);
1291 if (Tags) {
1292 TL->setAAMetadata(Tags);
1293 FL->setAAMetadata(Tags);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001294 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001295
1296 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1297 LI->getName() + ".sroa.speculated");
1298
1299 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1300 LI->replaceAllUsesWith(V);
1301 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001302 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001303 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001304}
1305
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001306/// \brief Build a GEP out of a base pointer and indices.
1307///
1308/// This will return the BasePtr if that is valid, or build a new GEP
1309/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001310static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001311 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001312 if (Indices.empty())
1313 return BasePtr;
1314
1315 // A single zero index is a no-op, so check for this and avoid building a GEP
1316 // in that case.
1317 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1318 return BasePtr;
1319
David Blaikieaa41cd52015-04-03 21:33:42 +00001320 return IRB.CreateInBoundsGEP(nullptr, BasePtr, Indices,
1321 NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001322}
1323
1324/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1325/// TargetTy without changing the offset of the pointer.
1326///
1327/// This routine assumes we've already established a properly offset GEP with
1328/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1329/// zero-indices down through type layers until we find one the same as
1330/// TargetTy. If we can't find one with the same type, we at least try to use
1331/// one with the same size. If none of that works, we just produce the GEP as
1332/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001333static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001334 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001335 SmallVectorImpl<Value *> &Indices,
1336 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001337 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001338 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001339
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001340 // Pointer size to use for the indices.
1341 unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1342
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001343 // See if we can descend into a struct and locate a field with the correct
1344 // type.
1345 unsigned NumLayers = 0;
1346 Type *ElementTy = Ty;
1347 do {
1348 if (ElementTy->isPointerTy())
1349 break;
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001350
1351 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1352 ElementTy = ArrayTy->getElementType();
1353 Indices.push_back(IRB.getIntN(PtrSize, 0));
1354 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1355 ElementTy = VectorTy->getElementType();
1356 Indices.push_back(IRB.getInt32(0));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001357 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001358 if (STy->element_begin() == STy->element_end())
1359 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001360 ElementTy = *STy->element_begin();
1361 Indices.push_back(IRB.getInt32(0));
1362 } else {
1363 break;
1364 }
1365 ++NumLayers;
1366 } while (ElementTy != TargetTy);
1367 if (ElementTy != TargetTy)
1368 Indices.erase(Indices.end() - NumLayers, Indices.end());
1369
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001370 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001371}
1372
1373/// \brief Recursively compute indices for a natural GEP.
1374///
1375/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1376/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001377static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001378 Value *Ptr, Type *Ty, APInt &Offset,
1379 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001380 SmallVectorImpl<Value *> &Indices,
1381 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001382 if (Offset == 0)
Chandler Carruth113dc642014-12-20 02:39:18 +00001383 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1384 NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001385
1386 // We can't recurse through pointer types.
1387 if (Ty->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001388 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001389
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001390 // We try to analyze GEPs over vectors here, but note that these GEPs are
1391 // extremely poorly defined currently. The long-term goal is to remove GEPing
1392 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001393 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001394 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Craig Topperf40110f2014-04-25 05:29:35 +00001395 if (ElementSizeInBits % 8 != 0) {
1396 // GEPs over non-multiple of 8 size vector elements are invalid.
1397 return nullptr;
1398 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001399 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001400 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001401 if (NumSkippedElements.ugt(VecTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001402 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001403 Offset -= NumSkippedElements * ElementSize;
1404 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001405 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001406 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001407 }
1408
1409 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1410 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001411 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001412 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001413 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001414 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001415
1416 Offset -= NumSkippedElements * ElementSize;
1417 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001418 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001419 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001420 }
1421
1422 StructType *STy = dyn_cast<StructType>(Ty);
1423 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00001424 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001425
Chandler Carruth90a735d2013-07-19 07:21:28 +00001426 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001427 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001428 if (StructOffset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00001429 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001430 unsigned Index = SL->getElementContainingOffset(StructOffset);
1431 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1432 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001433 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Craig Topperf40110f2014-04-25 05:29:35 +00001434 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001435
1436 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001437 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001438 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001439}
1440
1441/// \brief Get a natural GEP from a base pointer to a particular offset and
1442/// resulting in a particular type.
1443///
1444/// The goal is to produce a "natural" looking GEP that works with the existing
1445/// composite types to arrive at the appropriate offset and element type for
1446/// a pointer. TargetTy is the element type the returned GEP should point-to if
1447/// possible. We recurse by decreasing Offset, adding the appropriate index to
1448/// Indices, and setting Ty to the result subtype.
1449///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001450/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001451static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001452 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001453 SmallVectorImpl<Value *> &Indices,
1454 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001455 PointerType *Ty = cast<PointerType>(Ptr->getType());
1456
1457 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1458 // an i8.
Chandler Carruth286d87e2014-02-26 08:25:02 +00001459 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +00001460 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001461
1462 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001463 if (!ElementTy->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +00001464 return nullptr; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001465 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001466 if (ElementSize == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001467 return nullptr; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001468 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001469
1470 Offset -= NumSkippedElements * ElementSize;
1471 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001472 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001473 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001474}
1475
1476/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1477/// resulting pointer has PointerTy.
1478///
1479/// This tries very hard to compute a "natural" GEP which arrives at the offset
1480/// and produces the pointer type desired. Where it cannot, it will try to use
1481/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1482/// fails, it will try to use an existing i8* and GEP to the byte offset and
1483/// bitcast to the type.
1484///
1485/// The strategy for finding the more natural GEPs is to peel off layers of the
1486/// pointer, walking back through bit casts and GEPs, searching for a base
1487/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001488/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001489/// a single GEP as possible, thus making each GEP more independent of the
1490/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001491static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
Chandler Carruth113dc642014-12-20 02:39:18 +00001492 APInt Offset, Type *PointerTy, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001493 // Even though we don't look through PHI nodes, we could be called on an
1494 // instruction in an unreachable block, which may be on a cycle.
1495 SmallPtrSet<Value *, 4> Visited;
1496 Visited.insert(Ptr);
1497 SmallVector<Value *, 4> Indices;
1498
1499 // We may end up computing an offset pointer that has the wrong type. If we
1500 // never are able to compute one directly that has the correct type, we'll
Chandler Carruth5986b542015-01-02 02:47:38 +00001501 // fall back to it, so keep it and the base it was computed from around here.
Craig Topperf40110f2014-04-25 05:29:35 +00001502 Value *OffsetPtr = nullptr;
Chandler Carruth5986b542015-01-02 02:47:38 +00001503 Value *OffsetBasePtr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001504
1505 // Remember any i8 pointer we come across to re-use if we need to do a raw
1506 // byte offset.
Craig Topperf40110f2014-04-25 05:29:35 +00001507 Value *Int8Ptr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001508 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1509
1510 Type *TargetTy = PointerTy->getPointerElementType();
1511
1512 do {
1513 // First fold any existing GEPs into the offset.
1514 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1515 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001516 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001517 break;
1518 Offset += GEPOffset;
1519 Ptr = GEP->getPointerOperand();
David Blaikie70573dc2014-11-19 07:49:26 +00001520 if (!Visited.insert(Ptr).second)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001521 break;
1522 }
1523
1524 // See if we can perform a natural GEP here.
1525 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001526 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001527 Indices, NamePrefix)) {
Chandler Carruth5986b542015-01-02 02:47:38 +00001528 // If we have a new natural pointer at the offset, clear out any old
1529 // offset pointer we computed. Unless it is the base pointer or
1530 // a non-instruction, we built a GEP we don't need. Zap it.
1531 if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1532 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1533 assert(I->use_empty() && "Built a GEP with uses some how!");
1534 I->eraseFromParent();
1535 }
1536 OffsetPtr = P;
1537 OffsetBasePtr = Ptr;
1538 // If we also found a pointer of the right type, we're done.
1539 if (P->getType() == PointerTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001540 return P;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001541 }
1542
1543 // Stash this pointer if we've found an i8*.
1544 if (Ptr->getType()->isIntegerTy(8)) {
1545 Int8Ptr = Ptr;
1546 Int8PtrOffset = Offset;
1547 }
1548
1549 // Peel off a layer of the pointer and update the offset appropriately.
1550 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1551 Ptr = cast<Operator>(Ptr)->getOperand(0);
1552 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001553 if (GA->isInterposable())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001554 break;
1555 Ptr = GA->getAliasee();
1556 } else {
1557 break;
1558 }
1559 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +00001560 } while (Visited.insert(Ptr).second);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001561
1562 if (!OffsetPtr) {
1563 if (!Int8Ptr) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00001564 Int8Ptr = IRB.CreateBitCast(
1565 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1566 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001567 Int8PtrOffset = Offset;
1568 }
1569
Chandler Carruth113dc642014-12-20 02:39:18 +00001570 OffsetPtr = Int8PtrOffset == 0
1571 ? Int8Ptr
David Blaikieaa41cd52015-04-03 21:33:42 +00001572 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1573 IRB.getInt(Int8PtrOffset),
Chandler Carruth113dc642014-12-20 02:39:18 +00001574 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001575 }
1576 Ptr = OffsetPtr;
1577
1578 // On the off chance we were targeting i8*, guard the bitcast here.
1579 if (Ptr->getType() != PointerTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001580 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001581
1582 return Ptr;
1583}
1584
Chandler Carruth0715cba2015-01-01 11:54:38 +00001585/// \brief Compute the adjusted alignment for a load or store from an offset.
1586static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
1587 const DataLayout &DL) {
1588 unsigned Alignment;
1589 Type *Ty;
1590 if (auto *LI = dyn_cast<LoadInst>(I)) {
1591 Alignment = LI->getAlignment();
1592 Ty = LI->getType();
1593 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
1594 Alignment = SI->getAlignment();
1595 Ty = SI->getValueOperand()->getType();
1596 } else {
1597 llvm_unreachable("Only loads and stores are allowed!");
1598 }
1599
1600 if (!Alignment)
1601 Alignment = DL.getABITypeAlignment(Ty);
1602
1603 return MinAlign(Alignment, Offset);
1604}
1605
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001606/// \brief Test whether we can convert a value from the old to the new type.
1607///
1608/// This predicate should be used to guard calls to convertValue in order to
1609/// ensure that we only try to convert viable values. The strategy is that we
1610/// will peel off single element struct and array wrappings to get to an
1611/// underlying value, and convert that value.
1612static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1613 if (OldTy == NewTy)
1614 return true;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001615
1616 // For integer types, we can't handle any bit-width differences. This would
1617 // break both vector conversions with extension and introduce endianness
1618 // issues when in conjunction with loads and stores.
1619 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1620 assert(cast<IntegerType>(OldTy)->getBitWidth() !=
1621 cast<IntegerType>(NewTy)->getBitWidth() &&
1622 "We can't have the same bitwidth for different int types");
1623 return false;
1624 }
1625
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001626 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1627 return false;
1628 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1629 return false;
1630
Benjamin Kramer56262592013-09-22 11:24:58 +00001631 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001632 // of pointers and integers.
1633 OldTy = OldTy->getScalarType();
1634 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001635 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
Jack Liuf101c0f2016-05-03 19:30:48 +00001636 if (NewTy->isPointerTy() && OldTy->isPointerTy()) {
1637 return cast<PointerType>(NewTy)->getPointerAddressSpace() ==
1638 cast<PointerType>(OldTy)->getPointerAddressSpace();
1639 }
Sanjoy Dasb70ddd82017-06-17 20:28:13 +00001640
1641 // We can convert integers to integral pointers, but not to non-integral
1642 // pointers.
1643 if (OldTy->isIntegerTy())
1644 return !DL.isNonIntegralPointerType(NewTy);
1645
1646 // We can convert integral pointers to integers, but non-integral pointers
1647 // need to remain pointers.
1648 if (!DL.isNonIntegralPointerType(OldTy))
1649 return NewTy->isIntegerTy();
1650
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001651 return false;
1652 }
1653
1654 return true;
1655}
1656
1657/// \brief Generic routine to convert an SSA value to a value of a different
1658/// type.
1659///
1660/// This will try various different casting techniques, such as bitcasts,
1661/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1662/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001663static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001664 Type *NewTy) {
1665 Type *OldTy = V->getType();
1666 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1667
1668 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001669 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001670
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001671 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
1672 "Integer types must be the exact same to convert.");
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001673
Benjamin Kramer90901a32013-09-21 20:36:04 +00001674 // See if we need inttoptr for this type pair. A cast involving both scalars
1675 // and vectors requires and additional bitcast.
Craig Topper95d23472017-07-09 07:04:00 +00001676 if (OldTy->isIntOrIntVectorTy() && NewTy->isPtrOrPtrVectorTy()) {
Benjamin Kramer90901a32013-09-21 20:36:04 +00001677 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1678 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1679 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1680 NewTy);
1681
1682 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1683 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1684 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1685 NewTy);
1686
1687 return IRB.CreateIntToPtr(V, NewTy);
1688 }
1689
1690 // See if we need ptrtoint for this type pair. A cast involving both scalars
1691 // and vectors requires and additional bitcast.
Craig Topper95d23472017-07-09 07:04:00 +00001692 if (OldTy->isPtrOrPtrVectorTy() && NewTy->isIntOrIntVectorTy()) {
Benjamin Kramer90901a32013-09-21 20:36:04 +00001693 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1694 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1695 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1696 NewTy);
1697
1698 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1699 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1700 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1701 NewTy);
1702
1703 return IRB.CreatePtrToInt(V, NewTy);
1704 }
1705
1706 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001707}
1708
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001709/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001710///
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001711/// This function is called to test each entry in a partition which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001712/// for a single slice.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001713static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
1714 VectorType *Ty,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001715 uint64_t ElementSize,
1716 const DataLayout &DL) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001717 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001718 uint64_t BeginOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001719 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001720 uint64_t BeginIndex = BeginOffset / ElementSize;
1721 if (BeginIndex * ElementSize != BeginOffset ||
1722 BeginIndex >= Ty->getNumElements())
1723 return false;
1724 uint64_t EndOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001725 std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001726 uint64_t EndIndex = EndOffset / ElementSize;
1727 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1728 return false;
1729
1730 assert(EndIndex > BeginIndex && "Empty vector!");
1731 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruthc659df92014-10-16 20:24:07 +00001732 Type *SliceTy = (NumElements == 1)
1733 ? Ty->getElementType()
1734 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruthf0546402013-07-18 07:15:00 +00001735
1736 Type *SplitIntTy =
1737 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1738
Chandler Carruthc659df92014-10-16 20:24:07 +00001739 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001740
1741 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1742 if (MI->isVolatile())
1743 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001744 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001745 return false; // Skip any unsplittable intrinsics.
Owen Anderson6c19ab12014-08-07 21:07:35 +00001746 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1747 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1748 II->getIntrinsicID() != Intrinsic::lifetime_end)
1749 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001750 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1751 // Disable vector promotion when there are loads or stores of an FCA.
1752 return false;
1753 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1754 if (LI->isVolatile())
1755 return false;
1756 Type *LTy = LI->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001757 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001758 assert(LTy->isIntegerTy());
1759 LTy = SplitIntTy;
1760 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001761 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001762 return false;
1763 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1764 if (SI->isVolatile())
1765 return false;
1766 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001767 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001768 assert(STy->isIntegerTy());
1769 STy = SplitIntTy;
1770 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001771 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001772 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001773 } else {
1774 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001775 }
1776
1777 return true;
1778}
1779
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001780/// \brief Test whether the given alloca partitioning and range of slices can be
1781/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001782///
1783/// This is a quick test to check whether we can rewrite a particular alloca
1784/// partition (and its newly formed alloca) into a vector alloca with only
1785/// whole-vector loads and stores such that it could be promoted to a vector
1786/// SSA value. We only can ensure this for a limited set of operations, and we
1787/// don't want to do the rewrites unless we are confident that the result will
1788/// be promotable, so we have an early test here.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001789static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001790 // Collect the candidate types for vector-based promotion. Also track whether
1791 // we have different element types.
1792 SmallVector<VectorType *, 4> CandidateTys;
1793 Type *CommonEltTy = nullptr;
1794 bool HaveCommonEltTy = true;
1795 auto CheckCandidateType = [&](Type *Ty) {
1796 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1797 CandidateTys.push_back(VTy);
1798 if (!CommonEltTy)
1799 CommonEltTy = VTy->getElementType();
1800 else if (CommonEltTy != VTy->getElementType())
1801 HaveCommonEltTy = false;
1802 }
1803 };
Chandler Carruth2dc96822014-10-18 00:44:02 +00001804 // Consider any loads or stores that are the exact size of the slice.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001805 for (const Slice &S : P)
1806 if (S.beginOffset() == P.beginOffset() &&
1807 S.endOffset() == P.endOffset()) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001808 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1809 CheckCandidateType(LI->getType());
1810 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1811 CheckCandidateType(SI->getValueOperand()->getType());
1812 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001813
Chandler Carruth2dc96822014-10-18 00:44:02 +00001814 // If we didn't find a vector type, nothing to do here.
1815 if (CandidateTys.empty())
1816 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001817
Chandler Carruth2dc96822014-10-18 00:44:02 +00001818 // Remove non-integer vector types if we had multiple common element types.
1819 // FIXME: It'd be nice to replace them with integer vector types, but we can't
1820 // do that until all the backends are known to produce good code for all
1821 // integer vector types.
1822 if (!HaveCommonEltTy) {
David Majnemerc7004902016-08-12 04:32:37 +00001823 CandidateTys.erase(remove_if(CandidateTys,
1824 [](VectorType *VTy) {
1825 return !VTy->getElementType()->isIntegerTy();
1826 }),
Chandler Carruth2dc96822014-10-18 00:44:02 +00001827 CandidateTys.end());
1828
1829 // If there were no integer vector types, give up.
1830 if (CandidateTys.empty())
1831 return nullptr;
1832
1833 // Rank the remaining candidate vector types. This is easy because we know
1834 // they're all integer vectors. We sort by ascending number of elements.
1835 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
David L. Jones41cecba2017-01-13 21:02:41 +00001836 (void)DL;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001837 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
1838 "Cannot have vector types of different sizes!");
1839 assert(RHSTy->getElementType()->isIntegerTy() &&
1840 "All non-integer types eliminated!");
1841 assert(LHSTy->getElementType()->isIntegerTy() &&
1842 "All non-integer types eliminated!");
1843 return RHSTy->getNumElements() < LHSTy->getNumElements();
1844 };
1845 std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
1846 CandidateTys.erase(
1847 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1848 CandidateTys.end());
1849 } else {
1850// The only way to have the same element type in every vector type is to
1851// have the same vector type. Check that and remove all but one.
1852#ifndef NDEBUG
1853 for (VectorType *VTy : CandidateTys) {
1854 assert(VTy->getElementType() == CommonEltTy &&
1855 "Unaccounted for element type!");
1856 assert(VTy == CandidateTys[0] &&
1857 "Different vector types with the same element type!");
1858 }
1859#endif
1860 CandidateTys.resize(1);
1861 }
1862
1863 // Try each vector type, and return the one which works.
1864 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1865 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
1866
1867 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1868 // that aren't byte sized.
1869 if (ElementSize % 8)
1870 return false;
1871 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
1872 "vector size not a multiple of element size?");
1873 ElementSize /= 8;
1874
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001875 for (const Slice &S : P)
1876 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001877 return false;
1878
Chandler Carruthffb7ce52014-12-24 01:48:09 +00001879 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001880 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001881 return false;
1882
1883 return true;
1884 };
1885 for (VectorType *VTy : CandidateTys)
1886 if (CheckVectorTypeForPromotion(VTy))
1887 return VTy;
1888
1889 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001890}
1891
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001892/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001893///
1894/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001895/// test below on a single slice of the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001896static bool isIntegerWideningViableForSlice(const Slice &S,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001897 uint64_t AllocBeginOffset,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001898 Type *AllocaTy,
1899 const DataLayout &DL,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001900 bool &WholeAllocaOp) {
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001901 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1902
Chandler Carruthc659df92014-10-16 20:24:07 +00001903 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1904 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001905
1906 // We can't reasonably handle cases where the load or store extends past
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001907 // the end of the alloca's type and into its padding.
Chandler Carruthf0546402013-07-18 07:15:00 +00001908 if (RelEnd > Size)
1909 return false;
1910
Chandler Carruthc659df92014-10-16 20:24:07 +00001911 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001912
1913 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1914 if (LI->isVolatile())
1915 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001916 // We can't handle loads that extend past the allocated memory.
1917 if (DL.getTypeStoreSize(LI->getType()) > Size)
1918 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001919 // Note that we don't count vector loads or stores as whole-alloca
1920 // operations which enable integer widening because we would prefer to use
1921 // vector widening instead.
1922 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00001923 WholeAllocaOp = true;
1924 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001925 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001926 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001927 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001928 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001929 // Non-integer loads need to be convertible from the alloca type so that
1930 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001931 return false;
1932 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001933 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1934 Type *ValueTy = SI->getValueOperand()->getType();
1935 if (SI->isVolatile())
1936 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001937 // We can't handle stores that extend past the allocated memory.
1938 if (DL.getTypeStoreSize(ValueTy) > Size)
1939 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001940 // Note that we don't count vector loads or stores as whole-alloca
1941 // operations which enable integer widening because we would prefer to use
1942 // vector widening instead.
1943 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00001944 WholeAllocaOp = true;
1945 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001946 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001947 return false;
1948 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001949 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001950 // Non-integer stores need to be convertible to the alloca type so that
1951 // they are promotable.
1952 return false;
1953 }
1954 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1955 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1956 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001957 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001958 return false; // Skip any unsplittable intrinsics.
1959 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1960 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1961 II->getIntrinsicID() != Intrinsic::lifetime_end)
1962 return false;
1963 } else {
1964 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001965 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001966
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001967 return true;
1968}
1969
Chandler Carruth435c4e02012-10-15 08:40:30 +00001970/// \brief Test whether the given alloca partition's integer operations can be
1971/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00001972///
Chandler Carruth435c4e02012-10-15 08:40:30 +00001973/// This is a quick test to check whether we can rewrite the integer loads and
1974/// stores to a particular alloca into wider loads and stores and be able to
1975/// promote the resulting alloca.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001976static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001977 const DataLayout &DL) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001978 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00001979 // Don't create integer types larger than the maximum bitwidth.
1980 if (SizeInBits > IntegerType::MAX_INT_BITS)
1981 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00001982
1983 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001984 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001985 return false;
1986
Chandler Carruth58d05562012-10-25 04:37:07 +00001987 // We need to ensure that an integer type with the appropriate bitwidth can
1988 // be converted to the alloca type, whatever that is. We don't want to force
1989 // the alloca itself to have an integer type if there is a more suitable one.
1990 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001991 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1992 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00001993 return false;
1994
Chandler Carruthf0546402013-07-18 07:15:00 +00001995 // While examining uses, we ensure that the alloca has a covering load or
1996 // store. We don't want to widen the integer operations only to fail to
1997 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00001998 // later). However, if there are only splittable uses, go ahead and assume
1999 // that we cover the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002000 // FIXME: We shouldn't consider split slices that happen to start in the
2001 // partition here...
Chandler Carruthc659df92014-10-16 20:24:07 +00002002 bool WholeAllocaOp =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002003 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00002004
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002005 for (const Slice &S : P)
2006 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2007 WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00002008 return false;
2009
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002010 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002011 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2012 WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002013 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002014
Chandler Carruth92924fd2012-09-24 00:34:20 +00002015 return WholeAllocaOp;
2016}
2017
Chandler Carruthd177f862013-03-20 07:30:36 +00002018static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002019 IntegerType *Ty, uint64_t Offset,
2020 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002021 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002022 IntegerType *IntTy = cast<IntegerType>(V->getType());
2023 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2024 "Element extends past full value");
Chandler Carruth113dc642014-12-20 02:39:18 +00002025 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002026 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002027 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002028 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002029 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002030 DEBUG(dbgs() << " shifted: " << *V << "\n");
2031 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002032 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2033 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002034 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002035 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00002036 DEBUG(dbgs() << " trunced: " << *V << "\n");
2037 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002038 return V;
2039}
2040
Chandler Carruthd177f862013-03-20 07:30:36 +00002041static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002042 Value *V, uint64_t Offset, const Twine &Name) {
2043 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2044 IntegerType *Ty = cast<IntegerType>(V->getType());
2045 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2046 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002047 DEBUG(dbgs() << " start: " << *V << "\n");
2048 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002049 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00002050 DEBUG(dbgs() << " extended: " << *V << "\n");
2051 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002052 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2053 "Element store outside of alloca store");
Chandler Carruth113dc642014-12-20 02:39:18 +00002054 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002055 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002056 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002057 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002058 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002059 DEBUG(dbgs() << " shifted: " << *V << "\n");
2060 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002061
2062 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2063 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2064 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00002065 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002066 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00002067 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002068 }
2069 return V;
2070}
2071
Chandler Carruth113dc642014-12-20 02:39:18 +00002072static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2073 unsigned EndIndex, const Twine &Name) {
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002074 VectorType *VecTy = cast<VectorType>(V->getType());
2075 unsigned NumElements = EndIndex - BeginIndex;
2076 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2077
2078 if (NumElements == VecTy->getNumElements())
2079 return V;
2080
2081 if (NumElements == 1) {
2082 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2083 Name + ".extract");
2084 DEBUG(dbgs() << " extract: " << *V << "\n");
2085 return V;
2086 }
2087
Chandler Carruth113dc642014-12-20 02:39:18 +00002088 SmallVector<Constant *, 8> Mask;
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002089 Mask.reserve(NumElements);
2090 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2091 Mask.push_back(IRB.getInt32(i));
2092 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002093 ConstantVector::get(Mask), Name + ".extract");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002094 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2095 return V;
2096}
2097
Chandler Carruthd177f862013-03-20 07:30:36 +00002098static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00002099 unsigned BeginIndex, const Twine &Name) {
2100 VectorType *VecTy = cast<VectorType>(Old->getType());
2101 assert(VecTy && "Can only insert a vector into a vector");
2102
2103 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2104 if (!Ty) {
2105 // Single element to insert.
2106 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2107 Name + ".insert");
Chandler Carruth113dc642014-12-20 02:39:18 +00002108 DEBUG(dbgs() << " insert: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002109 return V;
2110 }
2111
2112 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2113 "Too many elements!");
2114 if (Ty->getNumElements() == VecTy->getNumElements()) {
2115 assert(V->getType() == VecTy && "Vector type mismatch");
2116 return V;
2117 }
2118 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2119
2120 // When inserting a smaller vector into the larger to store, we first
2121 // use a shuffle vector to widen it with undef elements, and then
2122 // a second shuffle vector to select between the loaded vector and the
2123 // incoming vector.
Chandler Carruth113dc642014-12-20 02:39:18 +00002124 SmallVector<Constant *, 8> Mask;
Chandler Carruthce4562b2012-12-17 13:41:21 +00002125 Mask.reserve(VecTy->getNumElements());
2126 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2127 if (i >= BeginIndex && i < EndIndex)
2128 Mask.push_back(IRB.getInt32(i - BeginIndex));
2129 else
2130 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2131 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002132 ConstantVector::get(Mask), Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00002133 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002134
2135 Mask.clear();
2136 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00002137 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2138
2139 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2140
2141 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002142 return V;
2143}
2144
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002145/// \brief Visitor to rewrite instructions using p particular slice of an alloca
2146/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002147///
2148/// Also implements the rewriting to vector-based accesses when the partition
2149/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2150/// lives here.
Chandler Carruth29a18a42015-09-12 09:09:14 +00002151class llvm::sroa::AllocaSliceRewriter
2152 : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002153 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002154 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
2155 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002156
Chandler Carruth90a735d2013-07-19 07:21:28 +00002157 const DataLayout &DL;
Chandler Carruth83934062014-10-16 21:11:55 +00002158 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002159 SROA &Pass;
2160 AllocaInst &OldAI, &NewAI;
2161 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002162 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002163
Chandler Carruth2dc96822014-10-18 00:44:02 +00002164 // This is a convenience and flag variable that will be null unless the new
2165 // alloca's integer operations should be widened to this integer type due to
2166 // passing isIntegerWideningViable above. If it is non-null, the desired
2167 // integer type will be stored here for easy access during rewriting.
2168 IntegerType *IntTy;
2169
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002170 // If we are rewriting an alloca partition which can be written as pure
2171 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002172 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002173 // - The new alloca is exactly the size of the vector type here.
2174 // - The accesses all either map to the entire vector or to a single
2175 // element.
2176 // - The set of accessing instructions is only one of those handled above
2177 // in isVectorPromotionViable. Generally these are the same access kinds
2178 // which are promotable via mem2reg.
2179 VectorType *VecTy;
2180 Type *ElementTy;
2181 uint64_t ElementSize;
2182
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002183 // The original offset of the slice currently being rewritten relative to
2184 // the original alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002185 uint64_t BeginOffset, EndOffset;
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002186 // The new offsets of the slice currently being rewritten relative to the
2187 // original alloca.
2188 uint64_t NewBeginOffset, NewEndOffset;
2189
2190 uint64_t SliceSize;
Chandler Carruthf0546402013-07-18 07:15:00 +00002191 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002192 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002193 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002194 Instruction *OldPtr;
2195
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002196 // Track post-rewrite users which are PHI nodes and Selects.
Davide Italiano81a26da2017-04-27 23:09:01 +00002197 SmallSetVector<PHINode *, 8> &PHIUsers;
2198 SmallSetVector<SelectInst *, 8> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002199
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002200 // Utility IR builder, whose name prefix is setup for each visited use, and
2201 // the insertion point is set to point to the user.
2202 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002203
2204public:
Chandler Carruth83934062014-10-16 21:11:55 +00002205 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002206 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002207 uint64_t NewAllocaBeginOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00002208 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2209 VectorType *PromotableVecTy,
Davide Italiano81a26da2017-04-27 23:09:01 +00002210 SmallSetVector<PHINode *, 8> &PHIUsers,
2211 SmallSetVector<SelectInst *, 8> &SelectUsers)
Chandler Carruth83934062014-10-16 21:11:55 +00002212 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002213 NewAllocaBeginOffset(NewAllocaBeginOffset),
2214 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002215 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002216 IntTy(IsIntegerPromotable
2217 ? Type::getIntNTy(
2218 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002219 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Craig Topperf40110f2014-04-25 05:29:35 +00002220 : nullptr),
Chandler Carruth2dc96822014-10-18 00:44:02 +00002221 VecTy(PromotableVecTy),
2222 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2223 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00002224 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002225 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002226 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002227 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002228 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002229 "Only multiple-of-8 sized vector elements are viable");
2230 ++NumVectorized;
2231 }
Chandler Carruth2dc96822014-10-18 00:44:02 +00002232 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002233 }
2234
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002235 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002236 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002237 BeginOffset = I->beginOffset();
2238 EndOffset = I->endOffset();
2239 IsSplittable = I->isSplittable();
2240 IsSplit =
2241 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002242 DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2243 DEBUG(AS.printSlice(dbgs(), I, ""));
Chandler Carruth0715cba2015-01-01 11:54:38 +00002244 DEBUG(dbgs() << "\n");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002245
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002246 // Compute the intersecting offset range.
2247 assert(BeginOffset < NewAllocaEndOffset);
2248 assert(EndOffset > NewAllocaBeginOffset);
2249 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2250 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2251
2252 SliceSize = NewEndOffset - NewBeginOffset;
2253
Chandler Carruthf0546402013-07-18 07:15:00 +00002254 OldUse = I->getUse();
2255 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002256
Chandler Carruthf0546402013-07-18 07:15:00 +00002257 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2258 IRB.SetInsertPoint(OldUserI);
2259 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2260 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2261
2262 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2263 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002264 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002265 return CanSROA;
2266 }
2267
2268private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002269 // Make sure the other visit overloads are visible.
2270 using Base::visit;
2271
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002272 // Every instruction which can end up as a user must have a rewrite rule.
2273 bool visitInstruction(Instruction &I) {
2274 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2275 llvm_unreachable("No rewrite rule for this instruction!");
2276 }
2277
Chandler Carruth47954c82014-02-26 05:12:43 +00002278 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2279 // Note that the offset computation can use BeginOffset or NewBeginOffset
2280 // interchangeably for unsplit slices.
2281 assert(IsSplit || BeginOffset == NewBeginOffset);
2282 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2283
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002284#ifndef NDEBUG
2285 StringRef OldName = OldPtr->getName();
2286 // Skip through the last '.sroa.' component of the name.
2287 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2288 if (LastSROAPrefix != StringRef::npos) {
2289 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2290 // Look for an SROA slice index.
2291 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2292 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2293 // Strip the index and look for the offset.
2294 OldName = OldName.substr(IndexEnd + 1);
2295 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2296 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2297 // Strip the offset.
2298 OldName = OldName.substr(OffsetEnd + 1);
2299 }
2300 }
2301 // Strip any SROA suffixes as well.
2302 OldName = OldName.substr(0, OldName.find(".sroa_"));
2303#endif
Chandler Carruth47954c82014-02-26 05:12:43 +00002304
2305 return getAdjustedPtr(IRB, DL, &NewAI,
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002306 APInt(DL.getPointerTypeSizeInBits(PointerTy), Offset),
2307 PointerTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002308#ifndef NDEBUG
2309 Twine(OldName) + "."
2310#else
2311 Twine()
2312#endif
2313 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002314 }
2315
Chandler Carruth113dc642014-12-20 02:39:18 +00002316 /// \brief Compute suitable alignment to access this slice of the *new*
2317 /// alloca.
Chandler Carruth2659e502014-02-26 05:02:19 +00002318 ///
2319 /// You can optionally pass a type to this routine and if that type's ABI
2320 /// alignment is itself suitable, this will return zero.
Craig Topperf40110f2014-04-25 05:29:35 +00002321 unsigned getSliceAlign(Type *Ty = nullptr) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002322 unsigned NewAIAlign = NewAI.getAlignment();
2323 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002324 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth113dc642014-12-20 02:39:18 +00002325 unsigned Align =
2326 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
Chandler Carruth2659e502014-02-26 05:02:19 +00002327 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002328 }
2329
Chandler Carruth845b73c2012-11-21 08:16:30 +00002330 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002331 assert(VecTy && "Can only call getIndex when rewriting a vector");
2332 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2333 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2334 uint32_t Index = RelOffset / ElementSize;
2335 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002336 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002337 }
2338
2339 void deleteIfTriviallyDead(Value *V) {
2340 Instruction *I = cast<Instruction>(V);
2341 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002342 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002343 }
2344
Chandler Carruthea27cf02014-02-26 04:25:04 +00002345 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002346 unsigned BeginIndex = getIndex(NewBeginOffset);
2347 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002348 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002349
Chandler Carruth113dc642014-12-20 02:39:18 +00002350 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002351 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002352 }
2353
Chandler Carruthea27cf02014-02-26 04:25:04 +00002354 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002355 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002356 assert(!LI.isVolatile());
Chandler Carruth113dc642014-12-20 02:39:18 +00002357 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002358 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002359 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2360 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth4b682f62015-08-28 09:03:52 +00002361 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
2362 IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
2363 V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
2364 }
2365 // It is possible that the extracted type is not the load type. This
2366 // happens if there is a load past the end of the alloca, and as
2367 // a consequence the slice is narrower but still a candidate for integer
2368 // lowering. To handle this case, we just zero extend the extracted
2369 // integer.
2370 assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&
2371 "Can only handle an extract for an overly wide load");
2372 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
2373 V = IRB.CreateZExt(V, LI.getType());
Chandler Carruth18db7952012-11-20 01:12:50 +00002374 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002375 }
2376
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002377 bool visitLoadInst(LoadInst &LI) {
2378 DEBUG(dbgs() << " original: " << LI << "\n");
2379 Value *OldOp = LI.getOperand(0);
2380 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002381
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002382 unsigned AS = LI.getPointerAddressSpace();
2383
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002384 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002385 : LI.getType();
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002386 const bool IsLoadPastEnd = DL.getTypeStoreSize(TargetTy) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002387 bool IsPtrAdjusted = false;
2388 Value *V;
2389 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002390 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002391 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002392 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002393 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002394 NewEndOffset == NewAllocaEndOffset &&
2395 (canConvertValue(DL, NewAllocaTy, TargetTy) ||
2396 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
2397 TargetTy->isIntegerTy()))) {
David Majnemer62690b12015-07-14 06:19:58 +00002398 LoadInst *NewLI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2399 LI.isVolatile(), LI.getName());
2400 if (LI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002401 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
Luqman Aden3f807c92017-03-22 19:16:39 +00002402
Chandler Carruth3f81d802017-06-27 08:32:03 +00002403 // Any !nonnull metadata or !range metadata on the old load is also valid
2404 // on the new load. This is even true in some cases even when the loads
2405 // are different types, for example by mapping !nonnull metadata to
2406 // !range metadata by modeling the null pointer constant converted to the
2407 // integer type.
2408 // FIXME: Add support for range metadata here. Currently the utilities
2409 // for this don't propagate range metadata in trivial cases from one
2410 // integer load to another, don't handle non-addrspace-0 null pointers
2411 // correctly, and don't have any support for mapping ranges as the
2412 // integer type becomes winder or narrower.
2413 if (MDNode *N = LI.getMetadata(LLVMContext::MD_nonnull))
2414 copyNonnullMetadata(LI, N, *NewLI);
2415
Luqman Aden3f807c92017-03-22 19:16:39 +00002416 // Try to preserve nonnull metadata
David Majnemer62690b12015-07-14 06:19:58 +00002417 V = NewLI;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002418
2419 // If this is an integer load past the end of the slice (which means the
2420 // bytes outside the slice are undef or this load is dead) just forcibly
2421 // fix the integer size with correct handling of endianness.
2422 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2423 if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
2424 if (AITy->getBitWidth() < TITy->getBitWidth()) {
2425 V = IRB.CreateZExt(V, TITy, "load.ext");
2426 if (DL.isBigEndian())
2427 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2428 "endian_shift");
2429 }
Chandler Carruth18db7952012-11-20 01:12:50 +00002430 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002431 Type *LTy = TargetTy->getPointerTo(AS);
David Majnemer62690b12015-07-14 06:19:58 +00002432 LoadInst *NewLI = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2433 getSliceAlign(TargetTy),
2434 LI.isVolatile(), LI.getName());
2435 if (LI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002436 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
David Majnemer62690b12015-07-14 06:19:58 +00002437
2438 V = NewLI;
Chandler Carruth18db7952012-11-20 01:12:50 +00002439 IsPtrAdjusted = true;
2440 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002441 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002442
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002443 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002444 assert(!LI.isVolatile());
2445 assert(LI.getType()->isIntegerTy() &&
2446 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002447 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002448 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002449 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002450 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002451 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002452 // 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 +00002453 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002454 // Create a placeholder value with the same type as LI to use as the
2455 // basis for the new value. This allows us to replace the uses of LI with
2456 // the computed value, and then replace the placeholder with LI, leaving
2457 // LI only used for this computation.
Chandler Carruth113dc642014-12-20 02:39:18 +00002458 Value *Placeholder =
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002459 new LoadInst(UndefValue::get(LI.getType()->getPointerTo(AS)));
Chandler Carruth24ac8302015-01-02 03:55:54 +00002460 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2461 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002462 LI.replaceAllUsesWith(V);
2463 Placeholder->replaceAllUsesWith(&LI);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002464 Placeholder->deleteValue();
Chandler Carruth18db7952012-11-20 01:12:50 +00002465 } else {
2466 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002467 }
2468
Chandler Carruth18db7952012-11-20 01:12:50 +00002469 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002470 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002471 DEBUG(dbgs() << " to: " << *V << "\n");
2472 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002473 }
2474
Chandler Carruthea27cf02014-02-26 04:25:04 +00002475 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002476 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002477 unsigned BeginIndex = getIndex(NewBeginOffset);
2478 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002479 assert(EndIndex > BeginIndex && "Empty vector!");
2480 unsigned NumElements = EndIndex - BeginIndex;
2481 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth113dc642014-12-20 02:39:18 +00002482 Type *SliceTy = (NumElements == 1)
2483 ? ElementTy
2484 : VectorType::get(ElementTy, NumElements);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002485 if (V->getType() != SliceTy)
2486 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002487
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002488 // Mix in the existing elements.
Chandler Carruth113dc642014-12-20 02:39:18 +00002489 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002490 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2491 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002492 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002493 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002494
2495 (void)Store;
2496 DEBUG(dbgs() << " to: " << *Store << "\n");
2497 return true;
2498 }
2499
Chandler Carruthea27cf02014-02-26 04:25:04 +00002500 bool rewriteIntegerStore(Value *V, StoreInst &SI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002501 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002502 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002503 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002504 Value *Old =
2505 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002506 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002507 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2508 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth113dc642014-12-20 02:39:18 +00002509 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002510 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002511 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002512 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Dorit Nuzmand1247a62016-09-22 07:56:23 +00002513 Store->copyMetadata(SI, LLVMContext::MD_mem_parallel_loop_access);
Chandler Carruth18db7952012-11-20 01:12:50 +00002514 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002515 DEBUG(dbgs() << " to: " << *Store << "\n");
2516 return true;
2517 }
2518
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002519 bool visitStoreInst(StoreInst &SI) {
2520 DEBUG(dbgs() << " original: " << SI << "\n");
2521 Value *OldOp = SI.getOperand(1);
2522 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002523
Chandler Carruth18db7952012-11-20 01:12:50 +00002524 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002525
Chandler Carruthac8317f2012-10-04 12:33:50 +00002526 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2527 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002528 if (V->getType()->isPointerTy())
2529 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002530 Pass.PostPromotionWorklist.insert(AI);
2531
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002532 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002533 assert(!SI.isVolatile());
2534 assert(V->getType()->isIntegerTy() &&
2535 "Only integer type loads and stores are split");
2536 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002537 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002538 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002539 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth24ac8302015-01-02 03:55:54 +00002540 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2541 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002542 }
2543
Chandler Carruth18db7952012-11-20 01:12:50 +00002544 if (VecTy)
Chandler Carruthea27cf02014-02-26 04:25:04 +00002545 return rewriteVectorizedStoreInst(V, SI, OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002546 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthea27cf02014-02-26 04:25:04 +00002547 return rewriteIntegerStore(V, SI);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002548
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002549 const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002550 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002551 if (NewBeginOffset == NewAllocaBeginOffset &&
2552 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002553 (canConvertValue(DL, V->getType(), NewAllocaTy) ||
2554 (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
2555 V->getType()->isIntegerTy()))) {
2556 // If this is an integer store past the end of slice (and thus the bytes
2557 // past that point are irrelevant or this is unreachable), truncate the
2558 // value prior to storing.
2559 if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
2560 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2561 if (VITy->getBitWidth() > AITy->getBitWidth()) {
2562 if (DL.isBigEndian())
2563 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2564 "endian_shift");
2565 V = IRB.CreateTrunc(V, AITy, "load.trunc");
2566 }
2567
Chandler Carruth90a735d2013-07-19 07:21:28 +00002568 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002569 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2570 SI.isVolatile());
2571 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002572 unsigned AS = SI.getPointerAddressSpace();
2573 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS));
Chandler Carruth2659e502014-02-26 05:02:19 +00002574 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2575 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002576 }
Dorit Nuzmand1247a62016-09-22 07:56:23 +00002577 NewSI->copyMetadata(SI, LLVMContext::MD_mem_parallel_loop_access);
David Majnemer62690b12015-07-14 06:19:58 +00002578 if (SI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002579 NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
Chandler Carruth18db7952012-11-20 01:12:50 +00002580 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002581 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002582
2583 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2584 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002585 }
2586
Chandler Carruth514f34f2012-12-17 04:07:30 +00002587 /// \brief Compute an integer value from splatting an i8 across the given
2588 /// number of bytes.
2589 ///
2590 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2591 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002592 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002593 ///
2594 /// \param V The i8 value to splat.
2595 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002596 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002597 assert(Size > 0 && "Expected a positive number of bytes.");
2598 IntegerType *VTy = cast<IntegerType>(V->getType());
2599 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2600 if (Size == 1)
2601 return V;
2602
Chandler Carruth113dc642014-12-20 02:39:18 +00002603 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2604 V = IRB.CreateMul(
2605 IRB.CreateZExt(V, SplatIntTy, "zext"),
2606 ConstantExpr::getUDiv(
2607 Constant::getAllOnesValue(SplatIntTy),
2608 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2609 SplatIntTy)),
2610 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002611 return V;
2612 }
2613
Chandler Carruthccca5042012-12-17 04:07:37 +00002614 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002615 Value *getVectorSplat(Value *V, unsigned NumElements) {
2616 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002617 DEBUG(dbgs() << " splat: " << *V << "\n");
2618 return V;
2619 }
2620
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002621 bool visitMemSetInst(MemSetInst &II) {
2622 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002623 assert(II.getRawDest() == OldPtr);
2624
2625 // If the memset has a variable size, it cannot be split, just adjust the
2626 // pointer to the new alloca.
2627 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002628 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002629 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002630 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Pete Cooper67cf9a72015-11-19 05:56:52 +00002631 Type *CstTy = II.getAlignmentCst()->getType();
2632 II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002633
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002634 deleteIfTriviallyDead(OldPtr);
2635 return false;
2636 }
2637
2638 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002639 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002640
2641 Type *AllocaTy = NewAI.getAllocatedType();
2642 Type *ScalarTy = AllocaTy->getScalarType();
2643
2644 // If this doesn't map cleanly onto the alloca type, and that type isn't
2645 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002646 if (!VecTy && !IntTy &&
Chandler Carruth113dc642014-12-20 02:39:18 +00002647 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002648 SliceSize != DL.getTypeStoreSize(AllocaTy) ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002649 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002650 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
Chandler Carruth113dc642014-12-20 02:39:18 +00002651 DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002652 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002653 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2654 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002655 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2656 getSliceAlign(), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002657 (void)New;
2658 DEBUG(dbgs() << " to: " << *New << "\n");
2659 return false;
2660 }
2661
2662 // If we can represent this as a simple value, we have to build the actual
2663 // value to store, which requires expanding the byte present in memset to
2664 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002665 // splatting the byte to a sufficiently wide integer, splatting it across
2666 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002667 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002668
Chandler Carruthccca5042012-12-17 04:07:37 +00002669 if (VecTy) {
2670 // If this is a memset of a vectorized alloca, insert it.
2671 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002672
Chandler Carruthf0546402013-07-18 07:15:00 +00002673 unsigned BeginIndex = getIndex(NewBeginOffset);
2674 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002675 assert(EndIndex > BeginIndex && "Empty vector!");
2676 unsigned NumElements = EndIndex - BeginIndex;
2677 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2678
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002679 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002680 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2681 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002682 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002683 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002684
Chandler Carruth113dc642014-12-20 02:39:18 +00002685 Value *Old =
2686 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002687 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002688 } else if (IntTy) {
2689 // If this is a memset on an alloca where we can widen stores, insert the
2690 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002691 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002692
Chandler Carruthf0546402013-07-18 07:15:00 +00002693 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002694 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002695
2696 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2697 EndOffset != NewAllocaBeginOffset)) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002698 Value *Old =
2699 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002700 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002701 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002702 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002703 } else {
2704 assert(V->getType() == IntTy &&
2705 "Wrong type for an alloca wide integer!");
2706 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002707 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002708 } else {
2709 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002710 assert(NewBeginOffset == NewAllocaBeginOffset);
2711 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002712
Chandler Carruth90a735d2013-07-19 07:21:28 +00002713 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002714 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002715 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002716
Chandler Carruth90a735d2013-07-19 07:21:28 +00002717 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002718 }
2719
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002720 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002721 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002722 (void)New;
2723 DEBUG(dbgs() << " to: " << *New << "\n");
2724 return !II.isVolatile();
2725 }
2726
2727 bool visitMemTransferInst(MemTransferInst &II) {
2728 // Rewriting of memory transfer instructions can be a bit tricky. We break
2729 // them into two categories: split intrinsics and unsplit intrinsics.
2730
2731 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002732
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002733 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002734 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002735 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002736
Chandler Carruthaa72b932014-02-26 07:29:54 +00002737 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002738
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002739 // For unsplit intrinsics, we simply modify the source and destination
2740 // pointers in place. This isn't just an optimization, it is a matter of
2741 // correctness. With unsplit intrinsics we may be dealing with transfers
2742 // within a single alloca before SROA ran, or with transfers that have
2743 // a variable length. We may also be dealing with memmove instead of
2744 // memcpy, and so simply updating the pointers is the necessary for us to
2745 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002746 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002747 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Pete Cooper67cf9a72015-11-19 05:56:52 +00002748 if (IsDest)
Chandler Carruth8183a502014-02-25 11:08:02 +00002749 II.setDest(AdjustedPtr);
Pete Cooper67cf9a72015-11-19 05:56:52 +00002750 else
Chandler Carruth8183a502014-02-25 11:08:02 +00002751 II.setSource(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002752
Pete Cooper67cf9a72015-11-19 05:56:52 +00002753 if (II.getAlignment() > SliceAlign) {
2754 Type *CstTy = II.getAlignmentCst()->getType();
2755 II.setAlignment(
2756 ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
Chandler Carruth181ed052014-02-26 05:33:36 +00002757 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002758
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002759 DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002760 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002761 return false;
2762 }
2763 // For split transfer intrinsics we have an incredibly useful assurance:
2764 // the source and destination do not reside within the same alloca, and at
2765 // least one of them does not escape. This means that we can replace
2766 // memmove with memcpy, and we don't need to worry about all manner of
2767 // downsides to splitting and transforming the operations.
2768
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002769 // If this doesn't map cleanly onto the alloca type, and that type isn't
2770 // a single value type, just emit a memcpy.
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002771 bool EmitMemCpy =
2772 !VecTy && !IntTy &&
2773 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2774 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2775 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002776
2777 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2778 // size hasn't been shrunk based on analysis of the viable range, this is
2779 // a no-op.
2780 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002781 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002782 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002783
2784 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002785 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002786 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002787 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002788 return false;
2789 }
2790 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002791 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002792
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002793 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2794 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002795 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth113dc642014-12-20 02:39:18 +00002796 if (AllocaInst *AI =
2797 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002798 assert(AI != &OldAI && AI != &NewAI &&
2799 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002800 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002801 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002802
Chandler Carruth286d87e2014-02-26 08:25:02 +00002803 Type *OtherPtrTy = OtherPtr->getType();
2804 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2805
Chandler Carruth181ed052014-02-26 05:33:36 +00002806 // Compute the relative offset for the other pointer within the transfer.
Chandler Carruth286d87e2014-02-26 08:25:02 +00002807 unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
Chandler Carruth181ed052014-02-26 05:33:36 +00002808 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Pete Cooper67cf9a72015-11-19 05:56:52 +00002809 unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2810 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002811
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002812 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002813 // Compute the other pointer, folding as much as possible to produce
2814 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002815 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002816 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002817
Chandler Carruth47954c82014-02-26 05:12:43 +00002818 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002819 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002820 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002821
Pete Cooper67cf9a72015-11-19 05:56:52 +00002822 CallInst *New = IRB.CreateMemCpy(
2823 IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2824 MinAlign(SliceAlign, OtherAlign), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002825 (void)New;
2826 DEBUG(dbgs() << " to: " << *New << "\n");
2827 return false;
2828 }
2829
Chandler Carruthf0546402013-07-18 07:15:00 +00002830 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2831 NewEndOffset == NewAllocaEndOffset;
2832 uint64_t Size = NewEndOffset - NewBeginOffset;
2833 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2834 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002835 unsigned NumElements = EndIndex - BeginIndex;
Chandler Carruth113dc642014-12-20 02:39:18 +00002836 IntegerType *SubIntTy =
2837 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002838
Chandler Carruth286d87e2014-02-26 08:25:02 +00002839 // Reset the other pointer type to match the register type we're going to
2840 // use, but using the address space of the original other pointer.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002841 if (VecTy && !IsWholeAlloca) {
2842 if (NumElements == 1)
2843 OtherPtrTy = VecTy->getElementType();
2844 else
2845 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2846
Chandler Carruth286d87e2014-02-26 08:25:02 +00002847 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002848 } else if (IntTy && !IsWholeAlloca) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00002849 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2850 } else {
2851 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002852 }
2853
Chandler Carruth181ed052014-02-26 05:33:36 +00002854 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002855 OtherPtr->getName() + ".");
Pete Cooper67cf9a72015-11-19 05:56:52 +00002856 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002857 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00002858 unsigned DstAlign = SliceAlign;
2859 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002860 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002861 std::swap(SrcAlign, DstAlign);
2862 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002863
2864 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002865 if (VecTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002866 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002867 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002868 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002869 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002870 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002871 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002872 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002873 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +00002874 Src =
2875 IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002876 }
2877
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002878 if (VecTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002879 Value *Old =
2880 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002881 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002882 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002883 Value *Old =
2884 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002885 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002886 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002887 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2888 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002889 }
2890
Chandler Carruth871ba722012-09-26 10:27:46 +00002891 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00002892 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Chandler Carruth871ba722012-09-26 10:27:46 +00002893 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002894 DEBUG(dbgs() << " to: " << *Store << "\n");
2895 return !II.isVolatile();
2896 }
2897
2898 bool visitIntrinsicInst(IntrinsicInst &II) {
2899 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2900 II.getIntrinsicID() == Intrinsic::lifetime_end);
2901 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002902 assert(II.getArgOperand(1) == OldPtr);
2903
2904 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002905 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002906
Eli Friedman50967752016-11-28 21:50:34 +00002907 // Lifetime intrinsics are only promotable if they cover the whole alloca.
2908 // Therefore, we drop lifetime intrinsics which don't cover the whole
2909 // alloca.
2910 // (In theory, intrinsics which partially cover an alloca could be
2911 // promoted, but PromoteMemToReg doesn't handle that case.)
2912 // FIXME: Check whether the alloca is promotable before dropping the
2913 // lifetime intrinsics?
2914 if (NewBeginOffset != NewAllocaBeginOffset ||
2915 NewEndOffset != NewAllocaEndOffset)
2916 return true;
2917
Chandler Carruth113dc642014-12-20 02:39:18 +00002918 ConstantInt *Size =
2919 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002920 NewEndOffset - NewBeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002921 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002922 Value *New;
2923 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2924 New = IRB.CreateLifetimeStart(Ptr, Size);
2925 else
2926 New = IRB.CreateLifetimeEnd(Ptr, Size);
2927
Edwin Vane82f80d42013-01-29 17:42:24 +00002928 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002929 DEBUG(dbgs() << " to: " << *New << "\n");
Eli Friedman2a65dd12016-08-08 01:30:53 +00002930
Eli Friedman50967752016-11-28 21:50:34 +00002931 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002932 }
2933
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002934 bool visitPHINode(PHINode &PN) {
2935 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00002936 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2937 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002938
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002939 // We would like to compute a new pointer in only one place, but have it be
2940 // as local as possible to the PHI. To do that, we re-use the location of
2941 // the old pointer, which necessarily must be in the right position to
2942 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00002943 IRBuilderTy PtrBuilder(IRB);
David Majnemerd4cffcf2014-09-01 21:20:14 +00002944 if (isa<PHINode>(OldPtr))
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002945 PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
David Majnemerd4cffcf2014-09-01 21:20:14 +00002946 else
2947 PtrBuilder.SetInsertPoint(OldPtr);
Chandler Carruth51175532014-02-25 11:12:04 +00002948 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002949
Chandler Carruth47954c82014-02-26 05:12:43 +00002950 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002951 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002952 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002953
Chandler Carruth82a57542012-10-01 10:54:05 +00002954 DEBUG(dbgs() << " to: " << PN << "\n");
2955 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002956
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002957 // PHIs can't be promoted on their own, but often can be speculated. We
2958 // check the speculation outside of the rewriter so that we see the
2959 // fully-rewritten alloca.
2960 PHIUsers.insert(&PN);
2961 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002962 }
2963
2964 bool visitSelectInst(SelectInst &SI) {
2965 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002966 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2967 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00002968 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2969 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002970
Chandler Carruth47954c82014-02-26 05:12:43 +00002971 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002972 // Replace the operands which were using the old pointer.
2973 if (SI.getOperand(1) == OldPtr)
2974 SI.setOperand(1, NewPtr);
2975 if (SI.getOperand(2) == OldPtr)
2976 SI.setOperand(2, NewPtr);
2977
Chandler Carruth82a57542012-10-01 10:54:05 +00002978 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002979 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002980
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002981 // Selects can't be promoted on their own, but often can be speculated. We
2982 // check the speculation outside of the rewriter so that we see the
2983 // fully-rewritten alloca.
2984 SelectUsers.insert(&SI);
2985 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002986 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002987};
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002988
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002989namespace {
2990/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2991///
2992/// This pass aggressively rewrites all aggregate loads and stores on
2993/// a particular pointer (or any pointer derived from it which we can identify)
2994/// with scalar loads and stores.
2995class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2996 // Befriend the base class so it can delegate to private visit methods.
2997 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2998
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002999 /// Queue of pointer uses to analyze and potentially rewrite.
3000 SmallVector<Use *, 8> Queue;
3001
3002 /// Set to prevent us from cycling with phi nodes and loops.
3003 SmallPtrSet<User *, 8> Visited;
3004
3005 /// The current pointer use being rewritten. This is used to dig up the used
3006 /// value (as opposed to the user).
3007 Use *U;
3008
3009public:
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003010 /// Rewrite loads and stores through a pointer and all pointers derived from
3011 /// it.
3012 bool rewrite(Instruction &I) {
3013 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3014 enqueueUsers(I);
3015 bool Changed = false;
3016 while (!Queue.empty()) {
3017 U = Queue.pop_back_val();
3018 Changed |= visit(cast<Instruction>(U->getUser()));
3019 }
3020 return Changed;
3021 }
3022
3023private:
3024 /// Enqueue all the users of the given instruction for further processing.
3025 /// This uses a set to de-duplicate users.
3026 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003027 for (Use &U : I.uses())
David Blaikie70573dc2014-11-19 07:49:26 +00003028 if (Visited.insert(U.getUser()).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003029 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003030 }
3031
3032 // Conservative default is to not rewrite anything.
3033 bool visitInstruction(Instruction &I) { return false; }
3034
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003035 /// \brief Generic recursive split emission class.
Chandler Carruth113dc642014-12-20 02:39:18 +00003036 template <typename Derived> class OpSplitter {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003037 protected:
3038 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00003039 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003040 /// The indices which to be used with insert- or extractvalue to select the
3041 /// appropriate value within the aggregate.
3042 SmallVector<unsigned, 4> Indices;
3043 /// The indices to a GEP instruction which will move Ptr to the correct slot
3044 /// within the aggregate.
3045 SmallVector<Value *, 4> GEPIndices;
3046 /// The base pointer of the original op, used as a base for GEPing the
3047 /// split operations.
3048 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003049
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003050 /// Initialize the splitter with an insertion point, Ptr and start with a
3051 /// single zero GEP index.
3052 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003053 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003054
3055 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003056 /// \brief Generic recursive split emission routine.
3057 ///
3058 /// This method recursively splits an aggregate op (load or store) into
3059 /// scalar or vector ops. It splits recursively until it hits a single value
3060 /// and emits that single value operation via the template argument.
3061 ///
3062 /// The logic of this routine relies on GEPs and insertvalue and
3063 /// extractvalue all operating with the same fundamental index list, merely
3064 /// formatted differently (GEPs need actual values).
3065 ///
3066 /// \param Ty The type being split recursively into smaller ops.
3067 /// \param Agg The aggregate value being built up or stored, depending on
3068 /// whether this is splitting a load or a store respectively.
3069 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3070 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003071 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003072
3073 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3074 unsigned OldSize = Indices.size();
3075 (void)OldSize;
3076 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3077 ++Idx) {
3078 assert(Indices.size() == OldSize && "Did not return to the old size");
3079 Indices.push_back(Idx);
3080 GEPIndices.push_back(IRB.getInt32(Idx));
3081 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3082 GEPIndices.pop_back();
3083 Indices.pop_back();
3084 }
3085 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003086 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003087
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003088 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3089 unsigned OldSize = Indices.size();
3090 (void)OldSize;
3091 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3092 ++Idx) {
3093 assert(Indices.size() == OldSize && "Did not return to the old size");
3094 Indices.push_back(Idx);
3095 GEPIndices.push_back(IRB.getInt32(Idx));
3096 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3097 GEPIndices.pop_back();
3098 Indices.pop_back();
3099 }
3100 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003101 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003102
3103 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003104 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003105 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003106
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003107 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003108 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003109 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003110
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003111 /// Emit a leaf load of a single value. This is called at the leaves of the
3112 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003113 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003114 assert(Ty->isSingleValueType());
3115 // Load the single value and insert it using the indices.
David Blaikieaa41cd52015-04-03 21:33:42 +00003116 Value *GEP =
3117 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
Jakub Staszak3c6583a2013-02-19 22:14:45 +00003118 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003119 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3120 DEBUG(dbgs() << " to: " << *Load << "\n");
3121 }
3122 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003123
3124 bool visitLoadInst(LoadInst &LI) {
3125 assert(LI.getPointerOperand() == *U);
3126 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3127 return false;
3128
3129 // We have an aggregate being loaded, split it apart.
3130 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003131 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003132 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003133 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003134 LI.replaceAllUsesWith(V);
3135 LI.eraseFromParent();
3136 return true;
3137 }
3138
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003139 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003140 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003141 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003142
3143 /// Emit a leaf store of a single value. This is called at the leaves of the
3144 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003145 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003146 assert(Ty->isSingleValueType());
3147 // Extract the single value and store it using the indices.
Patrik Hagglunda83706e2016-06-20 10:19:00 +00003148 //
3149 // The gep and extractvalue values are factored out of the CreateStore
3150 // call to make the output independent of the argument evaluation order.
Patrik Hagglund4e0bd842016-06-20 11:19:58 +00003151 Value *ExtractValue =
3152 IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
3153 Value *InBoundsGEP =
3154 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
Patrik Hagglunda83706e2016-06-20 10:19:00 +00003155 Value *Store = IRB.CreateStore(ExtractValue, InBoundsGEP);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003156 (void)Store;
3157 DEBUG(dbgs() << " to: " << *Store << "\n");
3158 }
3159 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003160
3161 bool visitStoreInst(StoreInst &SI) {
3162 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3163 return false;
3164 Value *V = SI.getValueOperand();
3165 if (V->getType()->isSingleValueType())
3166 return false;
3167
3168 // We have an aggregate being stored, split it apart.
3169 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003170 StoreOpSplitter Splitter(&SI, *U);
3171 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003172 SI.eraseFromParent();
3173 return true;
3174 }
3175
3176 bool visitBitCastInst(BitCastInst &BC) {
3177 enqueueUsers(BC);
3178 return false;
3179 }
3180
3181 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3182 enqueueUsers(GEPI);
3183 return false;
3184 }
3185
3186 bool visitPHINode(PHINode &PN) {
3187 enqueueUsers(PN);
3188 return false;
3189 }
3190
3191 bool visitSelectInst(SelectInst &SI) {
3192 enqueueUsers(SI);
3193 return false;
3194 }
3195};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00003196}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003197
Chandler Carruthba931992012-10-13 10:49:33 +00003198/// \brief Strip aggregate type wrapping.
3199///
3200/// This removes no-op aggregate types wrapping an underlying type. It will
3201/// strip as many layers of types as it can without changing either the type
3202/// size or the allocated size.
3203static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3204 if (Ty->isSingleValueType())
3205 return Ty;
3206
3207 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3208 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3209
3210 Type *InnerTy;
3211 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3212 InnerTy = ArrTy->getElementType();
3213 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3214 const StructLayout *SL = DL.getStructLayout(STy);
3215 unsigned Index = SL->getElementContainingOffset(0);
3216 InnerTy = STy->getElementType(Index);
3217 } else {
3218 return Ty;
3219 }
3220
3221 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3222 TypeSize > DL.getTypeSizeInBits(InnerTy))
3223 return Ty;
3224
3225 return stripAggregateTypeWrapping(DL, InnerTy);
3226}
3227
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003228/// \brief Try to find a partition of the aggregate type passed in for a given
3229/// offset and size.
3230///
3231/// This recurses through the aggregate type and tries to compute a subtype
3232/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003233/// of an array, it will even compute a new array type for that sub-section,
3234/// and the same for structs.
3235///
3236/// Note that this routine is very strict and tries to find a partition of the
3237/// type which produces the *exact* right offset and size. It is not forgiving
3238/// when the size or offset cause either end of type-based partition to be off.
3239/// Also, this is a best-effort routine. It is reasonable to give up and not
3240/// return a type if necessary.
Chandler Carruth113dc642014-12-20 02:39:18 +00003241static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3242 uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003243 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3244 return stripAggregateTypeWrapping(DL, Ty);
3245 if (Offset > DL.getTypeAllocSize(Ty) ||
3246 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003247 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003248
3249 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003250 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003251 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003252 uint64_t NumSkippedElements = Offset / ElementSize;
Peter Collingbournebc070522016-12-02 03:20:58 +00003253 if (NumSkippedElements >= SeqTy->getNumElements())
3254 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003255 Offset -= NumSkippedElements * ElementSize;
3256
3257 // First check if we need to recurse.
3258 if (Offset > 0 || Size < ElementSize) {
3259 // Bail if the partition ends in a different array element.
3260 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003261 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003262 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003263 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003264 }
3265 assert(Offset == 0);
3266
3267 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003268 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003269 assert(Size > ElementSize);
3270 uint64_t NumElements = Size / ElementSize;
3271 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003272 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003273 return ArrayType::get(ElementTy, NumElements);
3274 }
3275
3276 StructType *STy = dyn_cast<StructType>(Ty);
3277 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003278 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003279
Chandler Carruth90a735d2013-07-19 07:21:28 +00003280 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003281 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003282 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003283 uint64_t EndOffset = Offset + Size;
3284 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003285 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003286
3287 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003288 Offset -= SL->getElementOffset(Index);
3289
3290 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003291 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003292 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003293 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003294
3295 // See if any partition must be contained by the element.
3296 if (Offset > 0 || Size < ElementSize) {
3297 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003298 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003299 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003300 }
3301 assert(Offset == 0);
3302
3303 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003304 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003305
3306 StructType::element_iterator EI = STy->element_begin() + Index,
3307 EE = STy->element_end();
3308 if (EndOffset < SL->getSizeInBytes()) {
3309 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3310 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003311 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003312
3313 // Don't try to form "natural" types if the elements don't line up with the
3314 // expected size.
3315 // FIXME: We could potentially recurse down through the last element in the
3316 // sub-struct to find a natural end point.
3317 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003318 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003319
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003320 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003321 EE = STy->element_begin() + EndIndex;
3322 }
3323
3324 // Try to build up a sub-structure.
Chandler Carruth113dc642014-12-20 02:39:18 +00003325 StructType *SubTy =
3326 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003327 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003328 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003329 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003330
Chandler Carruth054a40a2012-09-14 11:08:31 +00003331 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003332}
3333
Chandler Carruth0715cba2015-01-01 11:54:38 +00003334/// \brief Pre-split loads and stores to simplify rewriting.
3335///
3336/// We want to break up the splittable load+store pairs as much as
3337/// possible. This is important to do as a preprocessing step, as once we
3338/// start rewriting the accesses to partitions of the alloca we lose the
3339/// necessary information to correctly split apart paired loads and stores
3340/// which both point into this alloca. The case to consider is something like
3341/// the following:
3342///
3343/// %a = alloca [12 x i8]
3344/// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3345/// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3346/// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3347/// %iptr1 = bitcast i8* %gep1 to i64*
3348/// %iptr2 = bitcast i8* %gep2 to i64*
3349/// %fptr1 = bitcast i8* %gep1 to float*
3350/// %fptr2 = bitcast i8* %gep2 to float*
3351/// %fptr3 = bitcast i8* %gep3 to float*
3352/// store float 0.0, float* %fptr1
3353/// store float 1.0, float* %fptr2
3354/// %v = load i64* %iptr1
3355/// store i64 %v, i64* %iptr2
3356/// %f1 = load float* %fptr2
3357/// %f2 = load float* %fptr3
3358///
3359/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3360/// promote everything so we recover the 2 SSA values that should have been
3361/// there all along.
3362///
3363/// \returns true if any changes are made.
3364bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
3365 DEBUG(dbgs() << "Pre-splitting loads and stores\n");
3366
3367 // Track the loads and stores which are candidates for pre-splitting here, in
3368 // the order they first appear during the partition scan. These give stable
3369 // iteration order and a basis for tracking which loads and stores we
3370 // actually split.
3371 SmallVector<LoadInst *, 4> Loads;
3372 SmallVector<StoreInst *, 4> Stores;
3373
3374 // We need to accumulate the splits required of each load or store where we
3375 // can find them via a direct lookup. This is important to cross-check loads
3376 // and stores against each other. We also track the slice so that we can kill
3377 // all the slices that end up split.
3378 struct SplitOffsets {
3379 Slice *S;
3380 std::vector<uint64_t> Splits;
3381 };
3382 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3383
Chandler Carruth73b01642015-01-05 04:17:53 +00003384 // Track loads out of this alloca which cannot, for any reason, be pre-split.
3385 // This is important as we also cannot pre-split stores of those loads!
3386 // FIXME: This is all pretty gross. It means that we can be more aggressive
3387 // in pre-splitting when the load feeding the store happens to come from
3388 // a separate alloca. Put another way, the effectiveness of SROA would be
3389 // decreased by a frontend which just concatenated all of its local allocas
3390 // into one big flat alloca. But defeating such patterns is exactly the job
3391 // SROA is tasked with! Sadly, to not have this discrepancy we would have
3392 // change store pre-splitting to actually force pre-splitting of the load
3393 // that feeds it *and all stores*. That makes pre-splitting much harder, but
3394 // maybe it would make it more principled?
3395 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3396
Chandler Carruth0715cba2015-01-01 11:54:38 +00003397 DEBUG(dbgs() << " Searching for candidate loads and stores\n");
3398 for (auto &P : AS.partitions()) {
3399 for (Slice &S : P) {
Chandler Carruth73b01642015-01-05 04:17:53 +00003400 Instruction *I = cast<Instruction>(S.getUse()->getUser());
Chandler Carruth37f1f122016-03-10 15:31:17 +00003401 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
3402 // If this is a load we have to track that it can't participate in any
3403 // pre-splitting. If this is a store of a load we have to track that
3404 // that load also can't participate in any pre-splitting.
Chandler Carruth73b01642015-01-05 04:17:53 +00003405 if (auto *LI = dyn_cast<LoadInst>(I))
3406 UnsplittableLoads.insert(LI);
Chandler Carruth37f1f122016-03-10 15:31:17 +00003407 else if (auto *SI = dyn_cast<StoreInst>(I))
3408 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
3409 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003410 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003411 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003412 assert(P.endOffset() > S.beginOffset() &&
3413 "Empty or backwards partition!");
3414
3415 // Determine if this is a pre-splittable slice.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003416 if (auto *LI = dyn_cast<LoadInst>(I)) {
3417 assert(!LI->isVolatile() && "Cannot split volatile loads!");
3418
3419 // The load must be used exclusively to store into other pointers for
3420 // us to be able to arbitrarily pre-split it. The stores must also be
3421 // simple to avoid changing semantics.
3422 auto IsLoadSimplyStored = [](LoadInst *LI) {
3423 for (User *LU : LI->users()) {
3424 auto *SI = dyn_cast<StoreInst>(LU);
3425 if (!SI || !SI->isSimple())
3426 return false;
3427 }
3428 return true;
3429 };
Chandler Carruth73b01642015-01-05 04:17:53 +00003430 if (!IsLoadSimplyStored(LI)) {
3431 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003432 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003433 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003434
3435 Loads.push_back(LI);
Chandler Carruthd94a5962016-03-10 14:16:18 +00003436 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
3437 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3438 // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
Chandler Carruth994cde82015-01-01 12:01:03 +00003439 continue;
3440 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3441 if (!StoredLoad || !StoredLoad->isSimple())
3442 continue;
3443 assert(!SI->isVolatile() && "Cannot split volatile stores!");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003444
Chandler Carruth994cde82015-01-01 12:01:03 +00003445 Stores.push_back(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003446 } else {
3447 // Other uses cannot be pre-split.
3448 continue;
3449 }
3450
3451 // Record the initial split.
3452 DEBUG(dbgs() << " Candidate: " << *I << "\n");
3453 auto &Offsets = SplitOffsetsMap[I];
3454 assert(Offsets.Splits.empty() &&
3455 "Should not have splits the first time we see an instruction!");
3456 Offsets.S = &S;
Chandler Carruth24ac8302015-01-02 03:55:54 +00003457 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003458 }
3459
3460 // Now scan the already split slices, and add a split for any of them which
3461 // we're going to pre-split.
3462 for (Slice *S : P.splitSliceTails()) {
3463 auto SplitOffsetsMapI =
3464 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3465 if (SplitOffsetsMapI == SplitOffsetsMap.end())
3466 continue;
3467 auto &Offsets = SplitOffsetsMapI->second;
3468
3469 assert(Offsets.S == S && "Found a mismatched slice!");
3470 assert(!Offsets.Splits.empty() &&
3471 "Cannot have an empty set of splits on the second partition!");
Chandler Carruth24ac8302015-01-02 03:55:54 +00003472 assert(Offsets.Splits.back() ==
3473 P.beginOffset() - Offsets.S->beginOffset() &&
Chandler Carruth0715cba2015-01-01 11:54:38 +00003474 "Previous split does not end where this one begins!");
3475
3476 // Record each split. The last partition's end isn't needed as the size
3477 // of the slice dictates that.
3478 if (S->endOffset() > P.endOffset())
Chandler Carruth24ac8302015-01-02 03:55:54 +00003479 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003480 }
3481 }
3482
3483 // We may have split loads where some of their stores are split stores. For
3484 // such loads and stores, we can only pre-split them if their splits exactly
3485 // match relative to their starting offset. We have to verify this prior to
3486 // any rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003487 Stores.erase(
David Majnemerc7004902016-08-12 04:32:37 +00003488 remove_if(Stores,
3489 [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
3490 // Lookup the load we are storing in our map of split
3491 // offsets.
3492 auto *LI = cast<LoadInst>(SI->getValueOperand());
3493 // If it was completely unsplittable, then we're done,
3494 // and this store can't be pre-split.
3495 if (UnsplittableLoads.count(LI))
3496 return true;
Chandler Carruth73b01642015-01-05 04:17:53 +00003497
David Majnemerc7004902016-08-12 04:32:37 +00003498 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3499 if (LoadOffsetsI == SplitOffsetsMap.end())
3500 return false; // Unrelated loads are definitely safe.
3501 auto &LoadOffsets = LoadOffsetsI->second;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003502
David Majnemerc7004902016-08-12 04:32:37 +00003503 // Now lookup the store's offsets.
3504 auto &StoreOffsets = SplitOffsetsMap[SI];
Chandler Carruth0715cba2015-01-01 11:54:38 +00003505
David Majnemerc7004902016-08-12 04:32:37 +00003506 // If the relative offsets of each split in the load and
3507 // store match exactly, then we can split them and we
3508 // don't need to remove them here.
3509 if (LoadOffsets.Splits == StoreOffsets.Splits)
3510 return false;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003511
David Majnemerc7004902016-08-12 04:32:37 +00003512 DEBUG(dbgs() << " Mismatched splits for load and store:\n"
3513 << " " << *LI << "\n"
3514 << " " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003515
David Majnemerc7004902016-08-12 04:32:37 +00003516 // We've found a store and load that we need to split
3517 // with mismatched relative splits. Just give up on them
3518 // and remove both instructions from our list of
3519 // candidates.
3520 UnsplittableLoads.insert(LI);
3521 return true;
3522 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003523 Stores.end());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003524 // Now we have to go *back* through all the stores, because a later store may
Chandler Carruth73b01642015-01-05 04:17:53 +00003525 // have caused an earlier store's load to become unsplittable and if it is
3526 // unsplittable for the later store, then we can't rely on it being split in
3527 // the earlier store either.
David Majnemerc7004902016-08-12 04:32:37 +00003528 Stores.erase(remove_if(Stores,
3529 [&UnsplittableLoads](StoreInst *SI) {
3530 auto *LI = cast<LoadInst>(SI->getValueOperand());
3531 return UnsplittableLoads.count(LI);
3532 }),
Chandler Carruth73b01642015-01-05 04:17:53 +00003533 Stores.end());
3534 // Once we've established all the loads that can't be split for some reason,
3535 // filter any that made it into our list out.
David Majnemerc7004902016-08-12 04:32:37 +00003536 Loads.erase(remove_if(Loads,
3537 [&UnsplittableLoads](LoadInst *LI) {
3538 return UnsplittableLoads.count(LI);
3539 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003540 Loads.end());
3541
3542 // If no loads or stores are left, there is no pre-splitting to be done for
3543 // this alloca.
3544 if (Loads.empty() && Stores.empty())
3545 return false;
3546
3547 // From here on, we can't fail and will be building new accesses, so rig up
3548 // an IR builder.
3549 IRBuilderTy IRB(&AI);
3550
3551 // Collect the new slices which we will merge into the alloca slices.
3552 SmallVector<Slice, 4> NewSlices;
3553
3554 // Track any allocas we end up splitting loads and stores for so we iterate
3555 // on them.
3556 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3557
3558 // At this point, we have collected all of the loads and stores we can
3559 // pre-split, and the specific splits needed for them. We actually do the
3560 // splitting in a specific order in order to handle when one of the loads in
3561 // the value operand to one of the stores.
3562 //
3563 // First, we rewrite all of the split loads, and just accumulate each split
3564 // load in a parallel structure. We also build the slices for them and append
3565 // them to the alloca slices.
3566 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3567 std::vector<LoadInst *> SplitLoads;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003568 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003569 for (LoadInst *LI : Loads) {
3570 SplitLoads.clear();
3571
3572 IntegerType *Ty = cast<IntegerType>(LI->getType());
3573 uint64_t LoadSize = Ty->getBitWidth() / 8;
3574 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3575
3576 auto &Offsets = SplitOffsetsMap[LI];
3577 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3578 "Slice size should always match load size exactly!");
3579 uint64_t BaseOffset = Offsets.S->beginOffset();
3580 assert(BaseOffset + LoadSize > BaseOffset &&
3581 "Cannot represent alloca access size using 64-bit integers!");
3582
3583 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003584 IRB.SetInsertPoint(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003585
3586 DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
3587
3588 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3589 int Idx = 0, Size = Offsets.Splits.size();
3590 for (;;) {
3591 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
Yaxun Liu7c44f342017-06-27 18:26:06 +00003592 auto AS = LI->getPointerAddressSpace();
3593 auto *PartPtrTy = PartTy->getPointerTo(AS);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003594 LoadInst *PLoad = IRB.CreateAlignedLoad(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003595 getAdjustedPtr(IRB, DL, BasePtr,
Yaxun Liu7c44f342017-06-27 18:26:06 +00003596 APInt(DL.getPointerSizeInBits(AS), PartOffset),
Chandler Carruth994cde82015-01-01 12:01:03 +00003597 PartPtrTy, BasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003598 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003599 LI->getName());
Dorit Nuzmand1247a62016-09-22 07:56:23 +00003600 PLoad->copyMetadata(*LI, LLVMContext::MD_mem_parallel_loop_access);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003601
3602 // Append this load onto the list of split loads so we can find it later
3603 // to rewrite the stores.
3604 SplitLoads.push_back(PLoad);
3605
3606 // Now build a new slice for the alloca.
Chandler Carruth994cde82015-01-01 12:01:03 +00003607 NewSlices.push_back(
3608 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3609 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003610 /*IsSplittable*/ false));
Chandler Carruth6044c0b2015-01-01 12:56:47 +00003611 DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3612 << ", " << NewSlices.back().endOffset() << "): " << *PLoad
3613 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003614
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003615 // See if we've handled all the splits.
3616 if (Idx >= Size)
3617 break;
3618
Chandler Carruth0715cba2015-01-01 11:54:38 +00003619 // Setup the next partition.
3620 PartOffset = Offsets.Splits[Idx];
3621 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003622 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3623 }
3624
3625 // Now that we have the split loads, do the slow walk over all uses of the
3626 // load and rewrite them as split stores, or save the split loads to use
3627 // below if the store is going to be split there anyways.
3628 bool DeferredStores = false;
3629 for (User *LU : LI->users()) {
3630 StoreInst *SI = cast<StoreInst>(LU);
3631 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3632 DeferredStores = true;
3633 DEBUG(dbgs() << " Deferred splitting of store: " << *SI << "\n");
3634 continue;
3635 }
3636
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003637 Value *StoreBasePtr = SI->getPointerOperand();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003638 IRB.SetInsertPoint(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003639
3640 DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
3641
3642 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3643 LoadInst *PLoad = SplitLoads[Idx];
3644 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
Chandler Carruth994cde82015-01-01 12:01:03 +00003645 auto *PartPtrTy =
3646 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003647
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003648 auto AS = SI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003649 StoreInst *PStore = IRB.CreateAlignedStore(
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003650 PLoad,
3651 getAdjustedPtr(IRB, DL, StoreBasePtr,
3652 APInt(DL.getPointerSizeInBits(AS), PartOffset),
3653 PartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003654 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Dorit Nuzmand1247a62016-09-22 07:56:23 +00003655 PStore->copyMetadata(*LI, LLVMContext::MD_mem_parallel_loop_access);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003656 DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
3657 }
3658
3659 // We want to immediately iterate on any allocas impacted by splitting
3660 // this store, and we have to track any promotable alloca (indicated by
3661 // a direct store) as needing to be resplit because it is no longer
3662 // promotable.
3663 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3664 ResplitPromotableAllocas.insert(OtherAI);
3665 Worklist.insert(OtherAI);
3666 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3667 StoreBasePtr->stripInBoundsOffsets())) {
3668 Worklist.insert(OtherAI);
3669 }
3670
3671 // Mark the original store as dead.
3672 DeadInsts.insert(SI);
3673 }
3674
3675 // Save the split loads if there are deferred stores among the users.
3676 if (DeferredStores)
3677 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3678
3679 // Mark the original load as dead and kill the original slice.
3680 DeadInsts.insert(LI);
3681 Offsets.S->kill();
3682 }
3683
3684 // Second, we rewrite all of the split stores. At this point, we know that
3685 // all loads from this alloca have been split already. For stores of such
3686 // loads, we can simply look up the pre-existing split loads. For stores of
3687 // other loads, we split those loads first and then write split stores of
3688 // them.
3689 for (StoreInst *SI : Stores) {
3690 auto *LI = cast<LoadInst>(SI->getValueOperand());
3691 IntegerType *Ty = cast<IntegerType>(LI->getType());
3692 uint64_t StoreSize = Ty->getBitWidth() / 8;
3693 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3694
3695 auto &Offsets = SplitOffsetsMap[SI];
3696 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3697 "Slice size should always match load size exactly!");
3698 uint64_t BaseOffset = Offsets.S->beginOffset();
3699 assert(BaseOffset + StoreSize > BaseOffset &&
3700 "Cannot represent alloca access size using 64-bit integers!");
3701
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003702 Value *LoadBasePtr = LI->getPointerOperand();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003703 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3704
3705 DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
3706
3707 // Check whether we have an already split load.
3708 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3709 std::vector<LoadInst *> *SplitLoads = nullptr;
3710 if (SplitLoadsMapI != SplitLoadsMap.end()) {
3711 SplitLoads = &SplitLoadsMapI->second;
3712 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3713 "Too few split loads for the number of splits in the store!");
3714 } else {
3715 DEBUG(dbgs() << " of load: " << *LI << "\n");
3716 }
3717
Chandler Carruth0715cba2015-01-01 11:54:38 +00003718 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3719 int Idx = 0, Size = Offsets.Splits.size();
3720 for (;;) {
3721 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
Keno Fischer514a6a52017-06-02 19:04:17 +00003722 auto *LoadPartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3723 auto *StorePartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003724
3725 // Either lookup a split load or create one.
3726 LoadInst *PLoad;
3727 if (SplitLoads) {
3728 PLoad = (*SplitLoads)[Idx];
3729 } else {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003730 IRB.SetInsertPoint(LI);
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003731 auto AS = LI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003732 PLoad = IRB.CreateAlignedLoad(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003733 getAdjustedPtr(IRB, DL, LoadBasePtr,
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003734 APInt(DL.getPointerSizeInBits(AS), PartOffset),
Keno Fischer514a6a52017-06-02 19:04:17 +00003735 LoadPartPtrTy, LoadBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003736 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003737 LI->getName());
3738 }
3739
3740 // And store this partition.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003741 IRB.SetInsertPoint(SI);
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003742 auto AS = SI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003743 StoreInst *PStore = IRB.CreateAlignedStore(
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003744 PLoad,
3745 getAdjustedPtr(IRB, DL, StoreBasePtr,
3746 APInt(DL.getPointerSizeInBits(AS), PartOffset),
3747 StorePartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003748 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003749
3750 // Now build a new slice for the alloca.
3751 NewSlices.push_back(
3752 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3753 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003754 /*IsSplittable*/ false));
Chandler Carruth6044c0b2015-01-01 12:56:47 +00003755 DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3756 << ", " << NewSlices.back().endOffset() << "): " << *PStore
3757 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003758 if (!SplitLoads) {
3759 DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
3760 }
3761
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003762 // See if we've finished all the splits.
3763 if (Idx >= Size)
3764 break;
3765
Chandler Carruth0715cba2015-01-01 11:54:38 +00003766 // Setup the next partition.
3767 PartOffset = Offsets.Splits[Idx];
3768 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003769 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
3770 }
3771
3772 // We want to immediately iterate on any allocas impacted by splitting
3773 // this load, which is only relevant if it isn't a load of this alloca and
3774 // thus we didn't already split the loads above. We also have to keep track
3775 // of any promotable allocas we split loads on as they can no longer be
3776 // promoted.
3777 if (!SplitLoads) {
3778 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
3779 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3780 ResplitPromotableAllocas.insert(OtherAI);
3781 Worklist.insert(OtherAI);
3782 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3783 LoadBasePtr->stripInBoundsOffsets())) {
3784 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3785 Worklist.insert(OtherAI);
3786 }
3787 }
3788
3789 // Mark the original store as dead now that we've split it up and kill its
Chandler Carruth24ac8302015-01-02 03:55:54 +00003790 // slice. Note that we leave the original load in place unless this store
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003791 // was its only use. It may in turn be split up if it is an alloca load
Chandler Carruth24ac8302015-01-02 03:55:54 +00003792 // for some other alloca, but it may be a normal load. This may introduce
3793 // redundant loads, but where those can be merged the rest of the optimizer
3794 // should handle the merging, and this uncovers SSA splits which is more
3795 // important. In practice, the original loads will almost always be fully
3796 // split and removed eventually, and the splits will be merged by any
3797 // trivial CSE, including instcombine.
3798 if (LI->hasOneUse()) {
3799 assert(*LI->user_begin() == SI && "Single use isn't this store!");
3800 DeadInsts.insert(LI);
3801 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003802 DeadInsts.insert(SI);
3803 Offsets.S->kill();
3804 }
3805
Chandler Carruth24ac8302015-01-02 03:55:54 +00003806 // Remove the killed slices that have ben pre-split.
David Majnemerc7004902016-08-12 04:32:37 +00003807 AS.erase(remove_if(AS, [](const Slice &S) { return S.isDead(); }), AS.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003808
Chandler Carruth24ac8302015-01-02 03:55:54 +00003809 // Insert our new slices. This will sort and merge them into the sorted
3810 // sequence.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003811 AS.insert(NewSlices);
3812
3813 DEBUG(dbgs() << " Pre-split slices:\n");
3814#ifndef NDEBUG
3815 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
3816 DEBUG(AS.print(dbgs(), I, " "));
3817#endif
3818
3819 // Finally, don't try to promote any allocas that new require re-splitting.
3820 // They have already been added to the worklist above.
3821 PromotableAllocas.erase(
David Majnemerc7004902016-08-12 04:32:37 +00003822 remove_if(
3823 PromotableAllocas,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003824 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
3825 PromotableAllocas.end());
3826
3827 return true;
3828}
3829
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003830/// \brief Rewrite an alloca partition's users.
3831///
3832/// This routine drives both of the rewriting goals of the SROA pass. It tries
3833/// to rewrite uses of an alloca partition to be conducive for SSA value
3834/// promotion. If the partition needs a new, more refined alloca, this will
3835/// build that new alloca, preserving as much type information as possible, and
3836/// rewrite the uses of the old alloca to point at the new one and have the
3837/// appropriate new offsets. It also evaluates how successful the rewrite was
3838/// at enabling promotion and if it was successful queues the alloca to be
3839/// promoted.
Adrian Prantl565cc182015-01-20 19:42:22 +00003840AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruth29a18a42015-09-12 09:09:14 +00003841 Partition &P) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003842 // Try to compute a friendly type for this partition of the alloca. This
3843 // won't always succeed, in which case we fall back to a legal integer type
3844 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00003845 Type *SliceTy = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003846 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003847 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003848 if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003849 SliceTy = CommonUseTy;
3850 if (!SliceTy)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003851 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003852 P.beginOffset(), P.size()))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003853 SliceTy = TypePartitionTy;
3854 if ((!SliceTy || (SliceTy->isArrayTy() &&
3855 SliceTy->getArrayElementType()->isIntegerTy())) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003856 DL.isLegalInteger(P.size() * 8))
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003857 SliceTy = Type::getIntNTy(*C, P.size() * 8);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003858 if (!SliceTy)
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003859 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003860 assert(DL.getTypeAllocSize(SliceTy) >= P.size());
Chandler Carruthf0546402013-07-18 07:15:00 +00003861
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003862 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00003863
Chandler Carruth2dc96822014-10-18 00:44:02 +00003864 VectorType *VecTy =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003865 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
Chandler Carruth2dc96822014-10-18 00:44:02 +00003866 if (VecTy)
3867 SliceTy = VecTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003868
3869 // Check for the case where we're going to rewrite to a new alloca of the
3870 // exact same type as the original, and with the same access offsets. In that
3871 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003872 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003873 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003874 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003875 assert(P.beginOffset() == 0 &&
3876 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003877 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003878 // FIXME: We should be able to bail at this point with "nothing changed".
3879 // FIXME: We might want to defer PHI speculation until after here.
Adrian Prantl565cc182015-01-20 19:42:22 +00003880 // FIXME: return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003881 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003882 unsigned Alignment = AI.getAlignment();
3883 if (!Alignment) {
3884 // The minimum alignment which users can rely on when the explicit
3885 // alignment is omitted or zero is that required by the ABI for this
3886 // type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003887 Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003888 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003889 Alignment = MinAlign(Alignment, P.beginOffset());
Chandler Carruth903790e2012-09-29 10:41:21 +00003890 // If we will get at least this much alignment from the type alone, leave
3891 // the alloca's alignment unconstrained.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003892 if (Alignment <= DL.getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003893 Alignment = 0;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003894 NewAI = new AllocaInst(
Matt Arsenault3c1fc762017-04-10 22:27:50 +00003895 SliceTy, AI.getType()->getAddressSpace(), nullptr, Alignment,
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003896 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003897 ++NumNewAllocas;
3898 }
3899
3900 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003901 << "[" << P.beginOffset() << "," << P.endOffset()
3902 << ") to: " << *NewAI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003903
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003904 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00003905 // promoted allocas. We will reset it to this point if the alloca is not in
3906 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003907 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00003908 unsigned NumUses = 0;
Davide Italiano81a26da2017-04-27 23:09:01 +00003909 SmallSetVector<PHINode *, 8> PHIUsers;
3910 SmallSetVector<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003911
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003912 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003913 P.endOffset(), IsIntegerPromotable, VecTy,
3914 PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00003915 bool Promotable = true;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00003916 for (Slice *S : P.splitSliceTails()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003917 Promotable &= Rewriter.visit(S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003918 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003919 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003920 for (Slice &S : P) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003921 Promotable &= Rewriter.visit(&S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003922 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003923 }
3924
Chandler Carruth6c321c12013-07-19 10:57:36 +00003925 NumAllocaPartitionUses += NumUses;
Craig Topper8a950272017-05-18 00:51:39 +00003926 MaxUsesPerAllocaPartition.updateMax(NumUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003927
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003928 // Now that we've processed all the slices in the new partition, check if any
3929 // PHIs or Selects would block promotion.
Davide Italiano81a26da2017-04-27 23:09:01 +00003930 for (PHINode *PHI : PHIUsers)
3931 if (!isSafePHIToSpeculate(*PHI)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003932 Promotable = false;
3933 PHIUsers.clear();
3934 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003935 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003936 }
Davide Italiano81a26da2017-04-27 23:09:01 +00003937
3938 for (SelectInst *Sel : SelectUsers)
3939 if (!isSafeSelectToSpeculate(*Sel)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003940 Promotable = false;
3941 PHIUsers.clear();
3942 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003943 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003944 }
3945
3946 if (Promotable) {
3947 if (PHIUsers.empty() && SelectUsers.empty()) {
3948 // Promote the alloca.
3949 PromotableAllocas.push_back(NewAI);
3950 } else {
3951 // If we have either PHIs or Selects to speculate, add them to those
3952 // worklists and re-queue the new alloca so that we promote in on the
3953 // next iteration.
Chandler Carruth61747042014-10-16 21:05:14 +00003954 for (PHINode *PHIUser : PHIUsers)
3955 SpeculatablePHIs.insert(PHIUser);
3956 for (SelectInst *SelectUser : SelectUsers)
3957 SpeculatableSelects.insert(SelectUser);
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003958 Worklist.insert(NewAI);
3959 }
3960 } else {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003961 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003962 while (PostPromotionWorklist.size() > PPWOldSize)
3963 PostPromotionWorklist.pop_back();
David Majnemer30ffc4c2016-04-26 01:05:00 +00003964
3965 // We couldn't promote and we didn't create a new partition, nothing
3966 // happened.
3967 if (NewAI == &AI)
3968 return nullptr;
3969
3970 // If we can't promote the alloca, iterate on it to check for new
3971 // refinements exposed by splitting the current alloca. Don't iterate on an
3972 // alloca which didn't actually change and didn't get promoted.
3973 Worklist.insert(NewAI);
Chandler Carruthf0546402013-07-18 07:15:00 +00003974 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003975
Adrian Prantl565cc182015-01-20 19:42:22 +00003976 return NewAI;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003977}
3978
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003979/// \brief Walks the slices of an alloca and form partitions based on them,
3980/// rewriting each of their uses.
Chandler Carruth83934062014-10-16 21:11:55 +00003981bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
3982 if (AS.begin() == AS.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00003983 return false;
3984
Chandler Carruth6c321c12013-07-19 10:57:36 +00003985 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003986 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003987 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00003988
Chandler Carruth24ac8302015-01-02 03:55:54 +00003989 // First try to pre-split loads and stores.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003990 Changed |= presplitLoadsAndStores(AI, AS);
3991
Chandler Carruth24ac8302015-01-02 03:55:54 +00003992 // Now that we have identified any pre-splitting opportunities, mark any
3993 // splittable (non-whole-alloca) loads and stores as unsplittable. If we fail
3994 // to split these during pre-splitting, we want to force them to be
3995 // rewritten into a partition.
3996 bool IsSorted = true;
3997 for (Slice &S : AS) {
3998 if (!S.isSplittable())
3999 continue;
4000 // FIXME: We currently leave whole-alloca splittable loads and stores. This
4001 // used to be the only splittable loads and stores and we need to be
4002 // confident that the above handling of splittable loads and stores is
4003 // completely sufficient before we forcibly disable the remaining handling.
4004 if (S.beginOffset() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004005 S.endOffset() >= DL.getTypeAllocSize(AI.getAllocatedType()))
Chandler Carruth24ac8302015-01-02 03:55:54 +00004006 continue;
4007 if (isa<LoadInst>(S.getUse()->getUser()) ||
4008 isa<StoreInst>(S.getUse()->getUser())) {
4009 S.makeUnsplittable();
4010 IsSorted = false;
4011 }
4012 }
4013 if (!IsSorted)
4014 std::sort(AS.begin(), AS.end());
4015
Adrian Prantl941fa752016-12-05 18:04:47 +00004016 /// Describes the allocas introduced by rewritePartition in order to migrate
4017 /// the debug info.
4018 struct Fragment {
Adrian Prantl565cc182015-01-20 19:42:22 +00004019 AllocaInst *Alloca;
4020 uint64_t Offset;
4021 uint64_t Size;
Adrian Prantl941fa752016-12-05 18:04:47 +00004022 Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
Adrian Prantl565cc182015-01-20 19:42:22 +00004023 : Alloca(AI), Offset(O), Size(S) {}
4024 };
Adrian Prantl941fa752016-12-05 18:04:47 +00004025 SmallVector<Fragment, 4> Fragments;
Adrian Prantl565cc182015-01-20 19:42:22 +00004026
Chandler Carruth0715cba2015-01-01 11:54:38 +00004027 // Rewrite each partition.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004028 for (auto &P : AS.partitions()) {
Adrian Prantl565cc182015-01-20 19:42:22 +00004029 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4030 Changed = true;
Adrian Prantl34e75902015-02-09 23:57:22 +00004031 if (NewAI != &AI) {
4032 uint64_t SizeOfByte = 8;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004033 uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
Adrian Prantl34e75902015-02-09 23:57:22 +00004034 // Don't include any padding.
4035 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
Adrian Prantl941fa752016-12-05 18:04:47 +00004036 Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
Adrian Prantl34e75902015-02-09 23:57:22 +00004037 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004038 }
Chandler Carruth6c321c12013-07-19 10:57:36 +00004039 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00004040 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004041
Chandler Carruth6c321c12013-07-19 10:57:36 +00004042 NumAllocaPartitions += NumPartitions;
Craig Topper8a950272017-05-18 00:51:39 +00004043 MaxPartitionsPerAlloca.updateMax(NumPartitions);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004044
Adrian Prantl565cc182015-01-20 19:42:22 +00004045 // Migrate debug information from the old alloca to the new alloca(s)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004046 // and the individual partitions.
Adrian Prantl565cc182015-01-20 19:42:22 +00004047 if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(&AI)) {
Duncan P. N. Exon Smith60635e32015-04-21 18:44:06 +00004048 auto *Var = DbgDecl->getVariable();
4049 auto *Expr = DbgDecl->getExpression();
Sanjay Patelaf674fb2015-12-14 17:24:23 +00004050 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
Keno Fischerd5354fd2016-01-14 20:06:34 +00004051 uint64_t AllocaSize = DL.getTypeSizeInBits(AI.getAllocatedType());
Adrian Prantl941fa752016-12-05 18:04:47 +00004052 for (auto Fragment : Fragments) {
4053 // Create a fragment expression describing the new partition or reuse AI's
Adrian Prantl565cc182015-01-20 19:42:22 +00004054 // expression if there is only one partition.
Adrian Prantl941fa752016-12-05 18:04:47 +00004055 auto *FragmentExpr = Expr;
4056 if (Fragment.Size < AllocaSize || Expr->isFragment()) {
Adrian Prantl152ac392015-02-01 00:58:04 +00004057 // If this alloca is already a scalar replacement of a larger aggregate,
Adrian Prantl941fa752016-12-05 18:04:47 +00004058 // Fragment.Offset describes the offset inside the scalar.
Adrian Prantl49797ca2016-12-22 05:27:12 +00004059 auto ExprFragment = Expr->getFragmentInfo();
4060 uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0;
Adrian Prantl941fa752016-12-05 18:04:47 +00004061 uint64_t Start = Offset + Fragment.Offset;
4062 uint64_t Size = Fragment.Size;
Adrian Prantl49797ca2016-12-22 05:27:12 +00004063 if (ExprFragment) {
Adrian Prantl941fa752016-12-05 18:04:47 +00004064 uint64_t AbsEnd =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00004065 ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
Adrian Prantl34e75902015-02-09 23:57:22 +00004066 if (Start >= AbsEnd)
4067 // No need to describe a SROAed padding.
4068 continue;
4069 Size = std::min(Size, AbsEnd - Start);
4070 }
Adrian Prantl941fa752016-12-05 18:04:47 +00004071 FragmentExpr = DIB.createFragmentExpression(Start, Size);
Adrian Prantl152ac392015-02-01 00:58:04 +00004072 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004073
4074 // Remove any existing dbg.declare intrinsic describing the same alloca.
Adrian Prantl941fa752016-12-05 18:04:47 +00004075 if (DbgDeclareInst *OldDDI = FindAllocaDbgDeclare(Fragment.Alloca))
Adrian Prantl565cc182015-01-20 19:42:22 +00004076 OldDDI->eraseFromParent();
4077
Adrian Prantl941fa752016-12-05 18:04:47 +00004078 DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr,
4079 DbgDecl->getDebugLoc(), &AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004080 }
4081 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004082 return Changed;
4083}
4084
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004085/// \brief Clobber a use with undef, deleting the used value if it becomes dead.
4086void SROA::clobberUse(Use &U) {
4087 Value *OldV = U;
4088 // Replace the use with an undef value.
4089 U = UndefValue::get(OldV->getType());
4090
4091 // Check for this making an instruction dead. We have to garbage collect
4092 // all the dead instructions to ensure the uses of any alloca end up being
4093 // minimal.
4094 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4095 if (isInstructionTriviallyDead(OldI)) {
4096 DeadInsts.insert(OldI);
4097 }
4098}
4099
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004100/// \brief Analyze an alloca for SROA.
4101///
4102/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004103/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004104/// rewritten as needed.
4105bool SROA::runOnAlloca(AllocaInst &AI) {
4106 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
4107 ++NumAllocasAnalyzed;
4108
4109 // Special case dead allocas, as they're trivial.
4110 if (AI.use_empty()) {
4111 AI.eraseFromParent();
4112 return true;
4113 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004114 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004115
4116 // Skip alloca forms that this analysis can't handle.
4117 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004118 DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004119 return false;
4120
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004121 bool Changed = false;
4122
4123 // First, split any FCA loads and stores touching this alloca to promote
4124 // better splitting and promotion opportunities.
Benjamin Kramer6db33382015-10-15 15:08:58 +00004125 AggLoadStoreRewriter AggRewriter;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004126 Changed |= AggRewriter.rewrite(AI);
4127
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004128 // Build the slices using a recursive instruction-visiting builder.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004129 AllocaSlices AS(DL, AI);
Chandler Carruth83934062014-10-16 21:11:55 +00004130 DEBUG(AS.print(dbgs()));
4131 if (AS.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004132 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004133
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004134 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth83934062014-10-16 21:11:55 +00004135 for (Instruction *DeadUser : AS.getDeadUsers()) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004136 // Free up everything used by this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004137 for (Use &DeadOp : DeadUser->operands())
Chandler Carruth1583e992014-03-03 10:42:58 +00004138 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004139
4140 // Now replace the uses of this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004141 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004142
4143 // And mark it for deletion.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004144 DeadInsts.insert(DeadUser);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004145 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004146 }
Chandler Carruth83934062014-10-16 21:11:55 +00004147 for (Use *DeadOp : AS.getDeadOperands()) {
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004148 clobberUse(*DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004149 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004150 }
4151
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004152 // No slices to split. Leave the dead alloca for a later pass to clean up.
Chandler Carruth83934062014-10-16 21:11:55 +00004153 if (AS.begin() == AS.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00004154 return Changed;
4155
Chandler Carruth83934062014-10-16 21:11:55 +00004156 Changed |= splitAlloca(AI, AS);
Chandler Carruthf0546402013-07-18 07:15:00 +00004157
4158 DEBUG(dbgs() << " Speculating PHIs\n");
4159 while (!SpeculatablePHIs.empty())
4160 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4161
4162 DEBUG(dbgs() << " Speculating Selects\n");
4163 while (!SpeculatableSelects.empty())
4164 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4165
4166 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004167}
4168
Chandler Carruth19450da2012-09-14 10:26:38 +00004169/// \brief Delete the dead instructions accumulated in this run.
4170///
4171/// Recursively deletes the dead instructions we've accumulated. This is done
4172/// at the very end to maximize locality of the recursive delete and to
4173/// minimize the problems of invalidated instruction pointers as such pointers
4174/// are used heavily in the intermediate stages of the algorithm.
4175///
4176/// We also record the alloca instructions deleted here so that they aren't
4177/// subsequently handed to mem2reg to promote.
Chandler Carruth113dc642014-12-20 02:39:18 +00004178void SROA::deleteDeadInstructions(
4179 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004180 while (!DeadInsts.empty()) {
4181 Instruction *I = DeadInsts.pop_back_val();
4182 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
4183
Chandler Carruth58d05562012-10-25 04:37:07 +00004184 I->replaceAllUsesWith(UndefValue::get(I->getType()));
4185
Chandler Carruth1583e992014-03-03 10:42:58 +00004186 for (Use &Operand : I->operands())
4187 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004188 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00004189 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004190 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00004191 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004192 }
4193
Adrian Prantl565cc182015-01-20 19:42:22 +00004194 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004195 DeletedAllocas.insert(AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004196 if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(AI))
4197 DbgDecl->eraseFromParent();
4198 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004199
4200 ++NumDeleted;
4201 I->eraseFromParent();
4202 }
4203}
4204
Chandler Carruth70b44c52012-09-15 11:43:14 +00004205/// \brief Promote the allocas, using the best available technique.
4206///
4207/// This attempts to promote whatever allocas have been identified as viable in
4208/// the PromotableAllocas list. If that list is empty, there is nothing to do.
Chandler Carruth748d0952015-08-26 09:09:29 +00004209/// This function returns whether any promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004210bool SROA::promoteAllocas(Function &F) {
4211 if (PromotableAllocas.empty())
4212 return false;
4213
4214 NumPromoted += PromotableAllocas.size();
4215
Chandler Carruth748d0952015-08-26 09:09:29 +00004216 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Davide Italiano612d5a92017-04-09 20:47:14 +00004217 PromoteMemToReg(PromotableAllocas, *DT, AC);
Chandler Carruth70b44c52012-09-15 11:43:14 +00004218 PromotableAllocas.clear();
4219 return true;
4220}
4221
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004222PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT,
4223 AssumptionCache &RunAC) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004224 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
4225 C = &F.getContext();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004226 DT = &RunDT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004227 AC = &RunAC;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004228
4229 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00004230 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Adrian Prantl565cc182015-01-20 19:42:22 +00004231 I != E; ++I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004232 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4233 Worklist.insert(AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004234 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004235
4236 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00004237 // A set of deleted alloca instruction pointers which should be removed from
4238 // the list of promotable allocas.
4239 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4240
Chandler Carruthac8317f2012-10-04 12:33:50 +00004241 do {
4242 while (!Worklist.empty()) {
4243 Changed |= runOnAlloca(*Worklist.pop_back_val());
4244 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00004245
Chandler Carruthac8317f2012-10-04 12:33:50 +00004246 // Remove the deleted allocas from various lists so that we don't try to
4247 // continue processing them.
4248 if (!DeletedAllocas.empty()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00004249 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00004250 Worklist.remove_if(IsInSet);
4251 PostPromotionWorklist.remove_if(IsInSet);
David Majnemerc7004902016-08-12 04:32:37 +00004252 PromotableAllocas.erase(remove_if(PromotableAllocas, IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00004253 PromotableAllocas.end());
4254 DeletedAllocas.clear();
4255 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004256 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004257
Chandler Carruthac8317f2012-10-04 12:33:50 +00004258 Changed |= promoteAllocas(F);
4259
4260 Worklist = PostPromotionWorklist;
4261 PostPromotionWorklist.clear();
4262 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004263
Davide Italiano16e96d42016-06-07 13:21:17 +00004264 if (!Changed)
4265 return PreservedAnalyses::all();
4266
Davide Italiano16e96d42016-06-07 13:21:17 +00004267 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00004268 PA.preserveSet<CFGAnalyses>();
Davide Italiano16e96d42016-06-07 13:21:17 +00004269 PA.preserve<GlobalsAA>();
4270 return PA;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004271}
4272
Sean Silva36e0d012016-08-09 00:28:15 +00004273PreservedAnalyses SROA::run(Function &F, FunctionAnalysisManager &AM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004274 return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F),
4275 AM.getResult<AssumptionAnalysis>(F));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004276}
Chandler Carruth29a18a42015-09-12 09:09:14 +00004277
4278/// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
4279///
4280/// This is in the llvm namespace purely to allow it to be a friend of the \c
4281/// SROA pass.
4282class llvm::sroa::SROALegacyPass : public FunctionPass {
4283 /// The SROA implementation.
4284 SROA Impl;
4285
4286public:
4287 SROALegacyPass() : FunctionPass(ID) {
4288 initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
4289 }
4290 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00004291 if (skipFunction(F))
Chandler Carruth29a18a42015-09-12 09:09:14 +00004292 return false;
4293
4294 auto PA = Impl.runImpl(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004295 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4296 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
Chandler Carruth29a18a42015-09-12 09:09:14 +00004297 return !PA.areAllPreserved();
4298 }
4299 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004300 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004301 AU.addRequired<DominatorTreeWrapperPass>();
4302 AU.addPreserved<GlobalsAAWrapperPass>();
4303 AU.setPreservesCFG();
4304 }
4305
Mehdi Amini117296c2016-10-01 02:56:57 +00004306 StringRef getPassName() const override { return "SROA"; }
Chandler Carruth29a18a42015-09-12 09:09:14 +00004307 static char ID;
4308};
4309
4310char SROALegacyPass::ID = 0;
4311
4312FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); }
4313
4314INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
4315 "Scalar Replacement Of Aggregates", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004316INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth29a18a42015-09-12 09:09:14 +00004317INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4318INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
4319 false, false)