blob: 33f7e1582ca60892db7f0f6654cdb1777d9616c0 [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
26#define DEBUG_TYPE "sroa"
27#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SetVector.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000033#include "llvm/Analysis/PtrUseVisitor.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000035#include "llvm/DIBuilder.h"
36#include "llvm/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/Constants.h"
38#include "llvm/IR/DataLayout.h"
39#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000040#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Function.h"
42#include "llvm/IR/IRBuilder.h"
43#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 Carruthdbd69582012-11-30 03:08:41 +000047#include "llvm/InstVisitor.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000048#include "llvm/Pass.h"
Chandler Carruth70b44c52012-09-15 11:43:14 +000049#include "llvm/Support/CommandLine.h"
Chandler Carruthf0546402013-07-18 07:15:00 +000050#include "llvm/Support/Compiler.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000051#include "llvm/Support/Debug.h"
52#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000053#include "llvm/Support/MathExtras.h"
Chandler Carruth83cee772014-02-25 03:59:29 +000054#include "llvm/Support/TimeValue.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000055#include "llvm/Support/raw_ostream.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000056#include "llvm/Transforms/Utils/Local.h"
57#include "llvm/Transforms/Utils/PromoteMemToReg.h"
58#include "llvm/Transforms/Utils/SSAUpdater.h"
Chandler Carruth83cee772014-02-25 03:59:29 +000059
60#if __cplusplus >= 201103L && !defined(NDEBUG)
61// We only use this for a debug check in C++11
62#include <random>
63#endif
64
Chandler Carruth1b398ae2012-09-14 09:22:59 +000065using namespace llvm;
66
67STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000068STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +000069STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
70STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
71STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000072STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
73STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000074STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000075STATISTIC(NumDeleted, "Number of instructions deleted");
76STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000077
Chandler Carruth70b44c52012-09-15 11:43:14 +000078/// Hidden option to force the pass to not use DomTree and mem2reg, instead
79/// forming SSA values through the SSAUpdater infrastructure.
80static cl::opt<bool>
81ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
82
Chandler Carruth83cee772014-02-25 03:59:29 +000083/// Hidden option to enable randomly shuffling the slices to help uncover
84/// instability in their order.
85static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
86 cl::init(false), cl::Hidden);
87
Chandler Carruth1b398ae2012-09-14 09:22:59 +000088namespace {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000089/// \brief A custom IRBuilder inserter which prefixes all names if they are
90/// preserved.
91template <bool preserveNames = true>
92class IRBuilderPrefixedInserter :
93 public IRBuilderDefaultInserter<preserveNames> {
94 std::string Prefix;
95
96public:
97 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
98
99protected:
100 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
101 BasicBlock::iterator InsertPt) const {
102 IRBuilderDefaultInserter<preserveNames>::InsertHelper(
103 I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
104 }
105};
106
107// Specialization for not preserving the name is trivial.
108template <>
109class IRBuilderPrefixedInserter<false> :
110 public IRBuilderDefaultInserter<false> {
111public:
112 void SetNamePrefix(const Twine &P) {}
113};
114
Chandler Carruthd177f862013-03-20 07:30:36 +0000115/// \brief Provide a typedef for IRBuilder that drops names in release builds.
116#ifndef NDEBUG
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000117typedef llvm::IRBuilder<true, ConstantFolder,
118 IRBuilderPrefixedInserter<true> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000119#else
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000120typedef llvm::IRBuilder<false, ConstantFolder,
121 IRBuilderPrefixedInserter<false> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000122#endif
123}
124
125namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000126/// \brief A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000127///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000128/// This structure represents a slice of an alloca used by some instruction. It
129/// stores both the begin and end offsets of this use, a pointer to the use
130/// itself, and a flag indicating whether we can classify the use as splittable
131/// or not when forming partitions of the alloca.
132class Slice {
Chandler Carruthf74654d2013-03-18 08:36:46 +0000133 /// \brief The beginning offset of the range.
134 uint64_t BeginOffset;
135
136 /// \brief The ending offset, not included in the range.
137 uint64_t EndOffset;
138
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000139 /// \brief Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000140 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000141 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000142
143public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000144 Slice() : BeginOffset(), EndOffset() {}
145 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000146 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000147 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000148
149 uint64_t beginOffset() const { return BeginOffset; }
150 uint64_t endOffset() const { return EndOffset; }
151
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000152 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
153 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000154
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000155 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000156
157 bool isDead() const { return getUse() == 0; }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000158 void kill() { UseAndIsSplittable.setPointer(0); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000159
160 /// \brief Support for ordering ranges.
161 ///
162 /// This provides an ordering over ranges such that start offsets are
163 /// always increasing, and within equal start offsets, the end offsets are
164 /// decreasing. Thus the spanning range comes first in a cluster with the
165 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000166 bool operator<(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000167 if (beginOffset() < RHS.beginOffset()) return true;
168 if (beginOffset() > RHS.beginOffset()) return false;
169 if (isSplittable() != RHS.isSplittable()) return !isSplittable();
170 if (endOffset() > RHS.endOffset()) return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000171 return false;
172 }
173
174 /// \brief Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000175 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000176 uint64_t RHSOffset) {
177 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000178 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000179 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000180 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000181 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000182 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000183
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000184 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000185 return isSplittable() == RHS.isSplittable() &&
186 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000187 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000188 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000189};
Chandler Carruthf0546402013-07-18 07:15:00 +0000190} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000191
192namespace llvm {
Chandler Carruthf0546402013-07-18 07:15:00 +0000193template <typename T> struct isPodLike;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000194template <> struct isPodLike<Slice> {
Chandler Carruthf0546402013-07-18 07:15:00 +0000195 static const bool value = true;
196};
Chandler Carruthf74654d2013-03-18 08:36:46 +0000197}
198
199namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000200/// \brief Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000201///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000202/// This class represents the slices of an alloca which are formed by its
203/// various uses. If a pointer escapes, we can't fully build a representation
204/// for the slices used and we reflect that in this structure. The uses are
205/// stored, sorted by increasing beginning offset and with unsplittable slices
206/// starting at a particular offset before splittable slices.
207class AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000208public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000209 /// \brief Construct the slices of a particular alloca.
210 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000211
212 /// \brief Test whether a pointer to the allocation escapes our analysis.
213 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000214 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000215 /// ignored.
216 bool isEscaped() const { return PointerEscapingInstr; }
217
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000218 /// \brief Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000219 /// @{
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000220 typedef SmallVectorImpl<Slice>::iterator iterator;
221 iterator begin() { return Slices.begin(); }
222 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000223
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000224 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
225 const_iterator begin() const { return Slices.begin(); }
226 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000227 /// @}
228
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000229 /// \brief Allow iterating the dead users for this alloca.
230 ///
231 /// These are instructions which will never actually use the alloca as they
232 /// are outside the allocated range. They are safe to replace with undef and
233 /// delete.
234 /// @{
235 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
236 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
237 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
238 /// @}
239
Chandler Carruth93a21e72012-09-14 10:18:49 +0000240 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000241 ///
242 /// These are operands which have cannot actually be used to refer to the
243 /// alloca as they are outside its range and the user doesn't correct for
244 /// that. These mostly consist of PHI node inputs and the like which we just
245 /// need to replace with undef.
246 /// @{
247 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
248 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
249 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
250 /// @}
251
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000252#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000253 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000254 void printSlice(raw_ostream &OS, const_iterator I,
255 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000256 void printUse(raw_ostream &OS, const_iterator I,
257 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000258 void print(raw_ostream &OS) const;
Alp Tokerf929e092014-01-04 22:47:48 +0000259 void dump(const_iterator I) const;
260 void dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000261#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000262
263private:
264 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000265 class SliceBuilder;
266 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000267
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000268#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000269 /// \brief Handle to alloca instruction to simplify method interfaces.
270 AllocaInst &AI;
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000271#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000272
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000273 /// \brief The instruction responsible for this alloca not having a known set
274 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000275 ///
276 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000277 /// store a pointer to that here and abort trying to form slices of the
278 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000279 Instruction *PointerEscapingInstr;
280
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000281 /// \brief The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000282 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000283 /// We store a vector of the slices formed by uses of the alloca here. This
284 /// vector is sorted by increasing begin offset, and then the unsplittable
285 /// slices before the splittable ones. See the Slice inner class for more
286 /// details.
287 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000288
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000289 /// \brief Instructions which will become dead if we rewrite the alloca.
290 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000291 /// Note that these are not separated by slice. This is because we expect an
292 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
293 /// all these instructions can simply be removed and replaced with undef as
294 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000295 SmallVector<Instruction *, 8> DeadUsers;
296
297 /// \brief Operands which will become dead if we rewrite the alloca.
298 ///
299 /// These are operands that in their particular use can be replaced with
300 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
301 /// to PHI nodes and the like. They aren't entirely dead (there might be
302 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
303 /// want to swap this particular input for undef to simplify the use lists of
304 /// the alloca.
305 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000306};
307}
308
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000309static Value *foldSelectInst(SelectInst &SI) {
310 // If the condition being selected on is a constant or the same value is
311 // being selected between, fold the select. Yes this does (rarely) happen
312 // early on.
313 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
314 return SI.getOperand(1+CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000315 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000316 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000317
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000318 return 0;
319}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000320
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000321/// \brief Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000322///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000323/// This class builds a set of alloca slices by recursively visiting the uses
324/// of an alloca and making a slice for each load and store at each offset.
325class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
326 friend class PtrUseVisitor<SliceBuilder>;
327 friend class InstVisitor<SliceBuilder>;
328 typedef PtrUseVisitor<SliceBuilder> Base;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000329
330 const uint64_t AllocSize;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000331 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000332
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000333 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000334 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
335
336 /// \brief Set to de-duplicate dead instructions found in the use walk.
337 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000338
339public:
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000340 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &S)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000341 : PtrUseVisitor<SliceBuilder>(DL),
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000342 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), S(S) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000343
344private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000345 void markAsDead(Instruction &I) {
346 if (VisitedDeadInsts.insert(&I))
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000347 S.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000348 }
349
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000350 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000351 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000352 // Completely skip uses which have a zero size or start either before or
353 // past the end of the allocation.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000354 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000355 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000356 << " which has zero size or starts outside of the "
357 << AllocSize << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000358 << " alloca: " << S.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000359 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000360 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000361 }
362
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000363 uint64_t BeginOffset = Offset.getZExtValue();
364 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000365
366 // Clamp the end offset to the end of the allocation. Note that this is
367 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000368 // This may appear superficially to be something we could ignore entirely,
369 // but that is not so! There may be widened loads or PHI-node uses where
370 // some instructions are dead but not others. We can't completely ignore
371 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000372 assert(AllocSize >= BeginOffset); // Established above.
373 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000374 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
375 << " to remain within the " << AllocSize << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000376 << " alloca: " << S.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000377 << " use: " << I << "\n");
378 EndOffset = AllocSize;
379 }
380
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000381 S.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000382 }
383
384 void visitBitCastInst(BitCastInst &BC) {
385 if (BC.use_empty())
386 return markAsDead(BC);
387
388 return Base::visitBitCastInst(BC);
389 }
390
391 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
392 if (GEPI.use_empty())
393 return markAsDead(GEPI);
394
395 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000396 }
397
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000398 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000399 uint64_t Size, bool IsVolatile) {
Chandler Carruth58d05562012-10-25 04:37:07 +0000400 // We allow splitting of loads and stores where the type is an integer type
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000401 // and cover the entire alloca. This prevents us from splitting over
402 // eagerly.
403 // FIXME: In the great blue eventually, we should eagerly split all integer
404 // loads and stores, and then have a separate step that merges adjacent
405 // alloca partitions into a single partition suitable for integer widening.
406 // Or we should skip the merge step and rely on GVN and other passes to
407 // merge adjacent loads and stores that survive mem2reg.
408 bool IsSplittable =
409 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
Chandler Carruth58d05562012-10-25 04:37:07 +0000410
411 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000412 }
413
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000414 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000415 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
416 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000417
418 if (!IsOffsetKnown)
419 return PI.setAborted(&LI);
420
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000421 uint64_t Size = DL.getTypeStoreSize(LI.getType());
422 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000423 }
424
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000425 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000426 Value *ValOp = SI.getValueOperand();
427 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000428 return PI.setEscapedAndAborted(&SI);
429 if (!IsOffsetKnown)
430 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000431
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000432 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
433
434 // If this memory access can be shown to *statically* extend outside the
435 // bounds of of the allocation, it's behavior is undefined, so simply
436 // ignore it. Note that this is more strict than the generic clamping
437 // behavior of insertUse. We also try to handle cases which might run the
438 // risk of overflow.
439 // FIXME: We should instead consider the pointer to have escaped if this
440 // function is being instrumented for addressing bugs or race conditions.
441 if (Offset.isNegative() || Size > AllocSize ||
442 Offset.ugt(AllocSize - Size)) {
443 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
444 << " which extends past the end of the " << AllocSize
445 << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000446 << " alloca: " << S.AI << "\n"
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000447 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000448 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000449 }
450
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000451 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
452 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000453 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000454 }
455
456
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000457 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000458 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000459 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000460 if ((Length && Length->getValue() == 0) ||
461 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
462 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000463 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000464
465 if (!IsOffsetKnown)
466 return PI.setAborted(&II);
467
468 insertUse(II, Offset,
469 Length ? Length->getLimitedValue()
470 : AllocSize - Offset.getLimitedValue(),
471 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000472 }
473
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000474 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000475 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000476 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000477 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000478 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000479
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000480 // Because we can visit these intrinsics twice, also check to see if the
481 // first time marked this instruction as dead. If so, skip it.
482 if (VisitedDeadInsts.count(&II))
483 return;
484
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000485 if (!IsOffsetKnown)
486 return PI.setAborted(&II);
487
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000488 // This side of the transfer is completely out-of-bounds, and so we can
489 // nuke the entire transfer. However, we also need to nuke the other side
490 // if already added to our partitions.
491 // FIXME: Yet another place we really should bypass this when
492 // instrumenting for ASan.
493 if (!Offset.isNegative() && Offset.uge(AllocSize)) {
494 SmallDenseMap<Instruction *, unsigned>::iterator MTPI = MemTransferSliceMap.find(&II);
495 if (MTPI != MemTransferSliceMap.end())
496 S.Slices[MTPI->second].kill();
497 return markAsDead(II);
498 }
499
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000500 uint64_t RawOffset = Offset.getLimitedValue();
501 uint64_t Size = Length ? Length->getLimitedValue()
502 : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000503
Chandler Carruthf0546402013-07-18 07:15:00 +0000504 // Check for the special case where the same exact value is used for both
505 // source and dest.
506 if (*U == II.getRawDest() && *U == II.getRawSource()) {
507 // For non-volatile transfers this is a no-op.
508 if (!II.isVolatile())
509 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000510
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000511 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000512 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000513
Chandler Carruthf0546402013-07-18 07:15:00 +0000514 // If we have seen both source and destination for a mem transfer, then
515 // they both point to the same alloca.
516 bool Inserted;
517 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
518 llvm::tie(MTPI, Inserted) =
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000519 MemTransferSliceMap.insert(std::make_pair(&II, S.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000520 unsigned PrevIdx = MTPI->second;
521 if (!Inserted) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000522 Slice &PrevP = S.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000523
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000524 // Check if the begin offsets match and this is a non-volatile transfer.
525 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000526 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
527 PrevP.kill();
528 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000529 }
530
531 // Otherwise we have an offset transfer within the same alloca. We can't
532 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000533 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000534 }
535
Chandler Carruthe3899f22013-07-15 17:36:21 +0000536 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000537 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000538
Chandler Carruthf0546402013-07-18 07:15:00 +0000539 // Check that we ended up with a valid index in the map.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000540 assert(S.Slices[PrevIdx].getUse()->getUser() == &II &&
541 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000542 }
543
544 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000545 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000546 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000547 void visitIntrinsicInst(IntrinsicInst &II) {
548 if (!IsOffsetKnown)
549 return PI.setAborted(&II);
550
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000551 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
552 II.getIntrinsicID() == Intrinsic::lifetime_end) {
553 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000554 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
555 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000556 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000557 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000558 }
559
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000560 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000561 }
562
563 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
564 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000565 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000566 // are considered unsplittable and the size is the maximum loaded or stored
567 // size.
568 SmallPtrSet<Instruction *, 4> Visited;
569 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
570 Visited.insert(Root);
571 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruth8b907e82012-09-25 10:03:40 +0000572 // If there are no loads or stores, the access is dead. We mark that as
573 // a size zero access.
574 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000575 do {
576 Instruction *I, *UsedI;
577 llvm::tie(UsedI, I) = Uses.pop_back_val();
578
579 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000580 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000581 continue;
582 }
583 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
584 Value *Op = SI->getOperand(0);
585 if (Op == UsedI)
586 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000587 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000588 continue;
589 }
590
591 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
592 if (!GEP->hasAllZeroIndices())
593 return GEP;
594 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
595 !isa<SelectInst>(I)) {
596 return I;
597 }
598
599 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
600 ++UI)
601 if (Visited.insert(cast<Instruction>(*UI)))
602 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
603 } while (!Uses.empty());
604
605 return 0;
606 }
607
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000608 void visitPHINode(PHINode &PN) {
609 if (PN.use_empty())
Chandler Carruthf0546402013-07-18 07:15:00 +0000610 return markAsDead(PN);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000611 if (!IsOffsetKnown)
612 return PI.setAborted(&PN);
613
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000614 // See if we already have computed info on this node.
Chandler Carruthf0546402013-07-18 07:15:00 +0000615 uint64_t &PHISize = PHIOrSelectSizes[&PN];
616 if (!PHISize) {
617 // This is a new PHI node, check for an unsafe use of the PHI node.
618 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHISize))
619 return PI.setAborted(UnsafeI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000620 }
621
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000622 // For PHI and select operands outside the alloca, we can't nuke the entire
623 // phi or select -- the other side might still be relevant, so we special
624 // case them here and use a separate structure to track the operands
625 // themselves which should be replaced with undef.
Chandler Carruthf0546402013-07-18 07:15:00 +0000626 // FIXME: This should instead be escaped in the event we're instrumenting
627 // for address sanitization.
628 if ((Offset.isNegative() && (-Offset).uge(PHISize)) ||
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000629 (!Offset.isNegative() && Offset.uge(AllocSize))) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000630 S.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000631 return;
632 }
633
Chandler Carruthf0546402013-07-18 07:15:00 +0000634 insertUse(PN, Offset, PHISize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000635 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000636
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000637 void visitSelectInst(SelectInst &SI) {
638 if (SI.use_empty())
639 return markAsDead(SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000640 if (Value *Result = foldSelectInst(SI)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000641 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000642 // If the result of the constant fold will be the pointer, recurse
643 // through the select as if we had RAUW'ed it.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000644 enqueueUsers(SI);
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000645 else
Chandler Carruth225d4bd2012-09-21 23:36:40 +0000646 // Otherwise the operand to the select is dead, and we can replace it
647 // with undef.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000648 S.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000649
650 return;
651 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000652 if (!IsOffsetKnown)
653 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000654
Chandler Carruthf0546402013-07-18 07:15:00 +0000655 // See if we already have computed info on this node.
656 uint64_t &SelectSize = PHIOrSelectSizes[&SI];
657 if (!SelectSize) {
658 // This is a new Select, check for an unsafe use of it.
659 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectSize))
660 return PI.setAborted(UnsafeI);
661 }
662
663 // For PHI and select operands outside the alloca, we can't nuke the entire
664 // phi or select -- the other side might still be relevant, so we special
665 // case them here and use a separate structure to track the operands
666 // themselves which should be replaced with undef.
667 // FIXME: This should instead be escaped in the event we're instrumenting
668 // for address sanitization.
669 if ((Offset.isNegative() && Offset.uge(SelectSize)) ||
670 (!Offset.isNegative() && Offset.uge(AllocSize))) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000671 S.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +0000672 return;
673 }
674
675 insertUse(SI, Offset, SelectSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000676 }
677
Chandler Carruthf0546402013-07-18 07:15:00 +0000678 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000679 void visitInstruction(Instruction &I) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000680 PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000681 }
682};
683
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000684AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000685 :
686#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
687 AI(AI),
688#endif
689 PointerEscapingInstr(0) {
690 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000691 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000692 if (PtrI.isEscaped() || PtrI.isAborted()) {
693 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000694 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000695 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
696 : PtrI.getAbortingInst();
697 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000698 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000699 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000700
Benjamin Kramer08e50702013-07-20 08:38:34 +0000701 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
702 std::mem_fun_ref(&Slice::isDead)),
703 Slices.end());
704
Chandler Carruth83cee772014-02-25 03:59:29 +0000705#if __cplusplus >= 201103L && !defined(NDEBUG)
706 if (SROARandomShuffleSlices) {
707 std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
708 std::shuffle(Slices.begin(), Slices.end(), MT);
709 }
710#endif
711
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000712 // Sort the uses. This arranges for the offsets to be in ascending order,
713 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000714 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000715}
716
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000717#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
718
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000719void AllocaSlices::print(raw_ostream &OS, const_iterator I,
720 StringRef Indent) const {
721 printSlice(OS, I, Indent);
Chandler Carruthf0546402013-07-18 07:15:00 +0000722 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000723}
724
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000725void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
726 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000727 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000728 << " slice #" << (I - begin())
Chandler Carruthf0546402013-07-18 07:15:00 +0000729 << (I->isSplittable() ? " (splittable)" : "") << "\n";
730}
731
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000732void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
733 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000734 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000735}
736
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000737void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000738 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000739 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000740 << " A pointer to this alloca escaped by:\n"
741 << " " << *PointerEscapingInstr << "\n";
742 return;
743 }
744
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000745 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +0000746 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000747 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000748}
749
Alp Tokerf929e092014-01-04 22:47:48 +0000750LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
751 print(dbgs(), I);
752}
753LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000754
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000755#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
756
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000757namespace {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000758/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
759///
760/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
761/// the loads and stores of an alloca instruction, as well as updating its
762/// debug information. This is used when a domtree is unavailable and thus
763/// mem2reg in its full form can't be used to handle promotion of allocas to
764/// scalar values.
765class AllocaPromoter : public LoadAndStorePromoter {
766 AllocaInst &AI;
767 DIBuilder &DIB;
768
769 SmallVector<DbgDeclareInst *, 4> DDIs;
770 SmallVector<DbgValueInst *, 4> DVIs;
771
772public:
Chandler Carruth45b136f2013-08-11 01:03:18 +0000773 AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
Chandler Carruth70b44c52012-09-15 11:43:14 +0000774 AllocaInst &AI, DIBuilder &DIB)
Chandler Carruth45b136f2013-08-11 01:03:18 +0000775 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
Chandler Carruth70b44c52012-09-15 11:43:14 +0000776
777 void run(const SmallVectorImpl<Instruction*> &Insts) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +0000778 // Retain the debug information attached to the alloca for use when
779 // rewriting loads and stores.
Chandler Carruth70b44c52012-09-15 11:43:14 +0000780 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
781 for (Value::use_iterator UI = DebugNode->use_begin(),
782 UE = DebugNode->use_end();
783 UI != UE; ++UI)
784 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
785 DDIs.push_back(DDI);
786 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
787 DVIs.push_back(DVI);
788 }
789
790 LoadAndStorePromoter::run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +0000791
792 // While we have the debug information, clear it off of the alloca. The
793 // caller takes care of deleting the alloca.
Chandler Carruth70b44c52012-09-15 11:43:14 +0000794 while (!DDIs.empty())
795 DDIs.pop_back_val()->eraseFromParent();
796 while (!DVIs.empty())
797 DVIs.pop_back_val()->eraseFromParent();
798 }
799
800 virtual bool isInstInList(Instruction *I,
801 const SmallVectorImpl<Instruction*> &Insts) const {
Chandler Carruthc17283b2013-08-11 01:56:15 +0000802 Value *Ptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000803 if (LoadInst *LI = dyn_cast<LoadInst>(I))
Chandler Carruthc17283b2013-08-11 01:56:15 +0000804 Ptr = LI->getOperand(0);
805 else
806 Ptr = cast<StoreInst>(I)->getPointerOperand();
807
808 // Only used to detect cycles, which will be rare and quickly found as
809 // we're walking up a chain of defs rather than down through uses.
810 SmallPtrSet<Value *, 4> Visited;
811
812 do {
813 if (Ptr == &AI)
814 return true;
815
816 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
817 Ptr = BCI->getOperand(0);
818 else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
819 Ptr = GEPI->getPointerOperand();
820 else
821 return false;
822
823 } while (Visited.insert(Ptr));
824
825 return false;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000826 }
827
828 virtual void updateDebugInfo(Instruction *Inst) const {
Craig Topper31ee5862013-07-03 15:07:05 +0000829 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000830 E = DDIs.end(); I != E; ++I) {
831 DbgDeclareInst *DDI = *I;
832 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
833 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
834 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
835 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
836 }
Craig Topper31ee5862013-07-03 15:07:05 +0000837 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000838 E = DVIs.end(); I != E; ++I) {
839 DbgValueInst *DVI = *I;
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000840 Value *Arg = 0;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000841 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
842 // If an argument is zero extended then use argument directly. The ZExt
843 // may be zapped by an optimization pass in future.
844 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
845 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000846 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000847 Arg = dyn_cast<Argument>(SExt->getOperand(0));
848 if (!Arg)
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000849 Arg = SI->getValueOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000850 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000851 Arg = LI->getPointerOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000852 } else {
853 continue;
854 }
855 Instruction *DbgVal =
856 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
857 Inst);
858 DbgVal->setDebugLoc(DVI->getDebugLoc());
859 }
860 }
861};
862} // end anon namespace
863
864
865namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000866/// \brief An optimization pass providing Scalar Replacement of Aggregates.
867///
868/// This pass takes allocations which can be completely analyzed (that is, they
869/// don't escape) and tries to turn them into scalar SSA values. There are
870/// a few steps to this process.
871///
872/// 1) It takes allocations of aggregates and analyzes the ways in which they
873/// are used to try to split them into smaller allocations, ideally of
874/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000875/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000876/// 2) It will transform accesses into forms which are suitable for SSA value
877/// promotion. This can be replacing a memset with a scalar store of an
878/// integer value, or it can involve speculating operations on a PHI or
879/// select to be a PHI or select of the results.
880/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
881/// onto insert and extract operations on a vector value, and convert them to
882/// this form. By doing so, it will enable promotion of vector aggregates to
883/// SSA vector values.
884class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000885 const bool RequiresDomTree;
886
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000887 LLVMContext *C;
Chandler Carruth90a735d2013-07-19 07:21:28 +0000888 const DataLayout *DL;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000889 DominatorTree *DT;
890
891 /// \brief Worklist of alloca instructions to simplify.
892 ///
893 /// Each alloca in the function is added to this. Each new alloca formed gets
894 /// added to it as well to recursively simplify unless that alloca can be
895 /// directly promoted. Finally, each time we rewrite a use of an alloca other
896 /// the one being actively rewritten, we add it back onto the list if not
897 /// already present to ensure it is re-visited.
898 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
899
900 /// \brief A collection of instructions to delete.
901 /// We try to batch deletions to simplify code and make things a bit more
902 /// efficient.
Chandler Carruth18db7952012-11-20 01:12:50 +0000903 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000904
Chandler Carruthac8317f2012-10-04 12:33:50 +0000905 /// \brief Post-promotion worklist.
906 ///
907 /// Sometimes we discover an alloca which has a high probability of becoming
908 /// viable for SROA after a round of promotion takes place. In those cases,
909 /// the alloca is enqueued here for re-processing.
910 ///
911 /// Note that we have to be very careful to clear allocas out of this list in
912 /// the event they are deleted.
913 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
914
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000915 /// \brief A collection of alloca instructions we can directly promote.
916 std::vector<AllocaInst *> PromotableAllocas;
917
Chandler Carruthf0546402013-07-18 07:15:00 +0000918 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
919 ///
920 /// All of these PHIs have been checked for the safety of speculation and by
921 /// being speculated will allow promoting allocas currently in the promotable
922 /// queue.
923 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
924
925 /// \brief A worklist of select instructions to speculate prior to promoting
926 /// allocas.
927 ///
928 /// All of these select instructions have been checked for the safety of
929 /// speculation and by being speculated will allow promoting allocas
930 /// currently in the promotable queue.
931 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
932
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000933public:
Chandler Carruth70b44c52012-09-15 11:43:14 +0000934 SROA(bool RequiresDomTree = true)
935 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
Chandler Carruth90a735d2013-07-19 07:21:28 +0000936 C(0), DL(0), DT(0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000937 initializeSROAPass(*PassRegistry::getPassRegistry());
938 }
939 bool runOnFunction(Function &F);
940 void getAnalysisUsage(AnalysisUsage &AU) const;
941
942 const char *getPassName() const { return "SROA"; }
943 static char ID;
944
945private:
Chandler Carruth82a57542012-10-01 10:54:05 +0000946 friend class PHIOrSelectSpeculator;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000947 friend class AllocaSliceRewriter;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000948
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000949 bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
950 AllocaSlices::iterator B, AllocaSlices::iterator E,
951 int64_t BeginOffset, int64_t EndOffset,
952 ArrayRef<AllocaSlices::iterator> SplitUses);
953 bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000954 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000955 void clobberUse(Use &U);
Chandler Carruth19450da2012-09-14 10:26:38 +0000956 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +0000957 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000958};
959}
960
961char SROA::ID = 0;
962
Chandler Carruth70b44c52012-09-15 11:43:14 +0000963FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
964 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000965}
966
967INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
968 false, false)
Chandler Carruth73523022014-01-13 13:07:17 +0000969INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000970INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
971 false, false)
972
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000973/// Walk the range of a partitioning looking for a common type to cover this
974/// sequence of slices.
975static Type *findCommonType(AllocaSlices::const_iterator B,
976 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +0000977 uint64_t EndOffset) {
978 Type *Ty = 0;
Chandler Carruth4de31542014-01-21 23:16:05 +0000979 bool TyIsCommon = true;
980 IntegerType *ITy = 0;
981
982 // Note that we need to look at *every* alloca slice's Use to ensure we
983 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000984 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000985 Use *U = I->getUse();
986 if (isa<IntrinsicInst>(*U->getUser()))
987 continue;
988 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
989 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000990
Chandler Carruthf0546402013-07-18 07:15:00 +0000991 Type *UserTy = 0;
Chandler Carrutha1262002013-11-19 09:03:18 +0000992 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000993 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +0000994 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000995 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +0000996 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000997
Chandler Carruth4de31542014-01-21 23:16:05 +0000998 if (!UserTy || (Ty && Ty != UserTy))
999 TyIsCommon = false; // Give up on anything but an iN type.
1000 else
1001 Ty = UserTy;
1002
1003 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001004 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001005 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001006 // entity causing the split. Also skip if the type is not a byte width
1007 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001008 if (UserITy->getBitWidth() % 8 != 0 ||
1009 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001010 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001011
Chandler Carruth4de31542014-01-21 23:16:05 +00001012 // Track the largest bitwidth integer type used in this way in case there
1013 // is no common type.
1014 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1015 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001016 }
1017 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001018
1019 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001020}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001021
Chandler Carruthf0546402013-07-18 07:15:00 +00001022/// PHI instructions that use an alloca and are subsequently loaded can be
1023/// rewritten to load both input pointers in the pred blocks and then PHI the
1024/// results, allowing the load of the alloca to be promoted.
1025/// From this:
1026/// %P2 = phi [i32* %Alloca, i32* %Other]
1027/// %V = load i32* %P2
1028/// to:
1029/// %V1 = load i32* %Alloca -> will be mem2reg'd
1030/// ...
1031/// %V2 = load i32* %Other
1032/// ...
1033/// %V = phi [i32 %V1, i32 %V2]
1034///
1035/// We can do this to a select if its only uses are loads and if the operands
1036/// to the select can be loaded unconditionally.
1037///
1038/// FIXME: This should be hoisted into a generic utility, likely in
1039/// Transforms/Util/Local.h
1040static bool isSafePHIToSpeculate(PHINode &PN,
Chandler Carruth90a735d2013-07-19 07:21:28 +00001041 const DataLayout *DL = 0) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001042 // For now, we can only do this promotion if the load is in the same block
1043 // as the PHI, and if there are no stores between the phi and load.
1044 // TODO: Allow recursive phi users.
1045 // TODO: Allow stores.
1046 BasicBlock *BB = PN.getParent();
1047 unsigned MaxAlign = 0;
1048 bool HaveLoad = false;
1049 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end(); UI != UE;
1050 ++UI) {
1051 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1052 if (LI == 0 || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001053 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001054
Chandler Carruthf0546402013-07-18 07:15:00 +00001055 // For now we only allow loads in the same block as the PHI. This is
1056 // a common case that happens when instcombine merges two loads through
1057 // a PHI.
1058 if (LI->getParent() != BB)
1059 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001060
Chandler Carruthf0546402013-07-18 07:15:00 +00001061 // Ensure that there are no instructions between the PHI and the load that
1062 // could store.
1063 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1064 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001065 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001066
Chandler Carruthf0546402013-07-18 07:15:00 +00001067 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1068 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001069 }
1070
Chandler Carruthf0546402013-07-18 07:15:00 +00001071 if (!HaveLoad)
1072 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001073
Chandler Carruthf0546402013-07-18 07:15:00 +00001074 // We can only transform this if it is safe to push the loads into the
1075 // predecessor blocks. The only thing to watch out for is that we can't put
1076 // a possibly trapping load in the predecessor if it is a critical edge.
1077 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1078 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1079 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001080
Chandler Carruthf0546402013-07-18 07:15:00 +00001081 // If the value is produced by the terminator of the predecessor (an
1082 // invoke) or it has side-effects, there is no valid place to put a load
1083 // in the predecessor.
1084 if (TI == InVal || TI->mayHaveSideEffects())
1085 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001086
Chandler Carruthf0546402013-07-18 07:15:00 +00001087 // If the predecessor has a single successor, then the edge isn't
1088 // critical.
1089 if (TI->getNumSuccessors() == 1)
1090 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001091
Chandler Carruthf0546402013-07-18 07:15:00 +00001092 // If this pointer is always safe to load, or if we can prove that there
1093 // is already a load in the block, then we can move the load to the pred
1094 // block.
1095 if (InVal->isDereferenceablePointer() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001096 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001097 continue;
1098
1099 return false;
1100 }
1101
1102 return true;
1103}
1104
1105static void speculatePHINodeLoads(PHINode &PN) {
1106 DEBUG(dbgs() << " original: " << PN << "\n");
1107
1108 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1109 IRBuilderTy PHIBuilder(&PN);
1110 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1111 PN.getName() + ".sroa.speculated");
1112
1113 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1114 // matter which one we get and if any differ.
1115 LoadInst *SomeLoad = cast<LoadInst>(*PN.use_begin());
1116 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1117 unsigned Align = SomeLoad->getAlignment();
1118
1119 // Rewrite all loads of the PN to use the new PHI.
1120 while (!PN.use_empty()) {
1121 LoadInst *LI = cast<LoadInst>(*PN.use_begin());
1122 LI->replaceAllUsesWith(NewPN);
1123 LI->eraseFromParent();
1124 }
1125
1126 // Inject loads into all of the pred blocks.
1127 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1128 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1129 TerminatorInst *TI = Pred->getTerminator();
1130 Value *InVal = PN.getIncomingValue(Idx);
1131 IRBuilderTy PredBuilder(TI);
1132
1133 LoadInst *Load = PredBuilder.CreateLoad(
1134 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1135 ++NumLoadsSpeculated;
1136 Load->setAlignment(Align);
1137 if (TBAATag)
1138 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1139 NewPN->addIncoming(Load, Pred);
1140 }
1141
1142 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1143 PN.eraseFromParent();
1144}
1145
1146/// Select instructions that use an alloca and are subsequently loaded can be
1147/// rewritten to load both input pointers and then select between the result,
1148/// allowing the load of the alloca to be promoted.
1149/// From this:
1150/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1151/// %V = load i32* %P2
1152/// to:
1153/// %V1 = load i32* %Alloca -> will be mem2reg'd
1154/// %V2 = load i32* %Other
1155/// %V = select i1 %cond, i32 %V1, i32 %V2
1156///
1157/// We can do this to a select if its only uses are loads and if the operand
1158/// to the select can be loaded unconditionally.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001159static bool isSafeSelectToSpeculate(SelectInst &SI, const DataLayout *DL = 0) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001160 Value *TValue = SI.getTrueValue();
1161 Value *FValue = SI.getFalseValue();
1162 bool TDerefable = TValue->isDereferenceablePointer();
1163 bool FDerefable = FValue->isDereferenceablePointer();
1164
1165 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end(); UI != UE;
1166 ++UI) {
1167 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1168 if (LI == 0 || !LI->isSimple())
1169 return false;
1170
1171 // Both operands to the select need to be dereferencable, either
1172 // absolutely (e.g. allocas) or at this point because we can see other
1173 // accesses to it.
1174 if (!TDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001175 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001176 return false;
1177 if (!FDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001178 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001179 return false;
1180 }
1181
1182 return true;
1183}
1184
1185static void speculateSelectInstLoads(SelectInst &SI) {
1186 DEBUG(dbgs() << " original: " << SI << "\n");
1187
1188 IRBuilderTy IRB(&SI);
1189 Value *TV = SI.getTrueValue();
1190 Value *FV = SI.getFalseValue();
1191 // Replace the loads of the select with a select of two loads.
1192 while (!SI.use_empty()) {
1193 LoadInst *LI = cast<LoadInst>(*SI.use_begin());
1194 assert(LI->isSimple() && "We only speculate simple loads");
1195
1196 IRB.SetInsertPoint(LI);
1197 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001198 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001199 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001200 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001201 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001202
Chandler Carruthf0546402013-07-18 07:15:00 +00001203 // Transfer alignment and TBAA info if present.
1204 TL->setAlignment(LI->getAlignment());
1205 FL->setAlignment(LI->getAlignment());
1206 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1207 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1208 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001209 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001210
1211 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1212 LI->getName() + ".sroa.speculated");
1213
1214 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1215 LI->replaceAllUsesWith(V);
1216 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001217 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001218 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001219}
1220
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001221/// \brief Build a GEP out of a base pointer and indices.
1222///
1223/// This will return the BasePtr if that is valid, or build a new GEP
1224/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001225static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001226 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001227 if (Indices.empty())
1228 return BasePtr;
1229
1230 // A single zero index is a no-op, so check for this and avoid building a GEP
1231 // in that case.
1232 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1233 return BasePtr;
1234
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001235 return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001236}
1237
1238/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1239/// TargetTy without changing the offset of the pointer.
1240///
1241/// This routine assumes we've already established a properly offset GEP with
1242/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1243/// zero-indices down through type layers until we find one the same as
1244/// TargetTy. If we can't find one with the same type, we at least try to use
1245/// one with the same size. If none of that works, we just produce the GEP as
1246/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001247static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001248 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001249 SmallVectorImpl<Value *> &Indices,
1250 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001251 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001252 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001253
1254 // See if we can descend into a struct and locate a field with the correct
1255 // type.
1256 unsigned NumLayers = 0;
1257 Type *ElementTy = Ty;
1258 do {
1259 if (ElementTy->isPointerTy())
1260 break;
1261 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1262 ElementTy = SeqTy->getElementType();
Chandler Carruth40617f52012-10-17 07:22:16 +00001263 // Note that we use the default address space as this index is over an
1264 // array or a vector, not a pointer.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001265 Indices.push_back(IRB.getInt(APInt(DL.getPointerSizeInBits(0), 0)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001266 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001267 if (STy->element_begin() == STy->element_end())
1268 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001269 ElementTy = *STy->element_begin();
1270 Indices.push_back(IRB.getInt32(0));
1271 } else {
1272 break;
1273 }
1274 ++NumLayers;
1275 } while (ElementTy != TargetTy);
1276 if (ElementTy != TargetTy)
1277 Indices.erase(Indices.end() - NumLayers, Indices.end());
1278
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001279 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001280}
1281
1282/// \brief Recursively compute indices for a natural GEP.
1283///
1284/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1285/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001286static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001287 Value *Ptr, Type *Ty, APInt &Offset,
1288 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001289 SmallVectorImpl<Value *> &Indices,
1290 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001291 if (Offset == 0)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001292 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001293
1294 // We can't recurse through pointer types.
1295 if (Ty->isPointerTy())
1296 return 0;
1297
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001298 // We try to analyze GEPs over vectors here, but note that these GEPs are
1299 // extremely poorly defined currently. The long-term goal is to remove GEPing
1300 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001301 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001302 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001303 if (ElementSizeInBits % 8)
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001304 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001305 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001306 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001307 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1308 return 0;
1309 Offset -= NumSkippedElements * ElementSize;
1310 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001311 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001312 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001313 }
1314
1315 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1316 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001317 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001318 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001319 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1320 return 0;
1321
1322 Offset -= NumSkippedElements * ElementSize;
1323 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001324 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001325 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001326 }
1327
1328 StructType *STy = dyn_cast<StructType>(Ty);
1329 if (!STy)
1330 return 0;
1331
Chandler Carruth90a735d2013-07-19 07:21:28 +00001332 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001333 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001334 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001335 return 0;
1336 unsigned Index = SL->getElementContainingOffset(StructOffset);
1337 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1338 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001339 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001340 return 0; // The offset points into alignment padding.
1341
1342 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001343 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001344 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001345}
1346
1347/// \brief Get a natural GEP from a base pointer to a particular offset and
1348/// resulting in a particular type.
1349///
1350/// The goal is to produce a "natural" looking GEP that works with the existing
1351/// composite types to arrive at the appropriate offset and element type for
1352/// a pointer. TargetTy is the element type the returned GEP should point-to if
1353/// possible. We recurse by decreasing Offset, adding the appropriate index to
1354/// Indices, and setting Ty to the result subtype.
1355///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001356/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001357static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001358 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001359 SmallVectorImpl<Value *> &Indices,
1360 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001361 PointerType *Ty = cast<PointerType>(Ptr->getType());
1362
1363 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1364 // an i8.
1365 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1366 return 0;
1367
1368 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001369 if (!ElementTy->isSized())
1370 return 0; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001371 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001372 if (ElementSize == 0)
1373 return 0; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001374 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001375
1376 Offset -= NumSkippedElements * ElementSize;
1377 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001378 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001379 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001380}
1381
1382/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1383/// resulting pointer has PointerTy.
1384///
1385/// This tries very hard to compute a "natural" GEP which arrives at the offset
1386/// and produces the pointer type desired. Where it cannot, it will try to use
1387/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1388/// fails, it will try to use an existing i8* and GEP to the byte offset and
1389/// bitcast to the type.
1390///
1391/// The strategy for finding the more natural GEPs is to peel off layers of the
1392/// pointer, walking back through bit casts and GEPs, searching for a base
1393/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001394/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001395/// a single GEP as possible, thus making each GEP more independent of the
1396/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001397static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1398 APInt Offset, Type *PointerTy,
1399 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001400 // Even though we don't look through PHI nodes, we could be called on an
1401 // instruction in an unreachable block, which may be on a cycle.
1402 SmallPtrSet<Value *, 4> Visited;
1403 Visited.insert(Ptr);
1404 SmallVector<Value *, 4> Indices;
1405
1406 // We may end up computing an offset pointer that has the wrong type. If we
1407 // never are able to compute one directly that has the correct type, we'll
1408 // fall back to it, so keep it around here.
1409 Value *OffsetPtr = 0;
1410
1411 // Remember any i8 pointer we come across to re-use if we need to do a raw
1412 // byte offset.
1413 Value *Int8Ptr = 0;
1414 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1415
1416 Type *TargetTy = PointerTy->getPointerElementType();
1417
1418 do {
1419 // First fold any existing GEPs into the offset.
1420 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1421 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001422 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001423 break;
1424 Offset += GEPOffset;
1425 Ptr = GEP->getPointerOperand();
1426 if (!Visited.insert(Ptr))
1427 break;
1428 }
1429
1430 // See if we can perform a natural GEP here.
1431 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001432 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001433 Indices, NamePrefix)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001434 if (P->getType() == PointerTy) {
1435 // Zap any offset pointer that we ended up computing in previous rounds.
1436 if (OffsetPtr && OffsetPtr->use_empty())
1437 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1438 I->eraseFromParent();
1439 return P;
1440 }
1441 if (!OffsetPtr) {
1442 OffsetPtr = P;
1443 }
1444 }
1445
1446 // Stash this pointer if we've found an i8*.
1447 if (Ptr->getType()->isIntegerTy(8)) {
1448 Int8Ptr = Ptr;
1449 Int8PtrOffset = Offset;
1450 }
1451
1452 // Peel off a layer of the pointer and update the offset appropriately.
1453 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1454 Ptr = cast<Operator>(Ptr)->getOperand(0);
1455 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1456 if (GA->mayBeOverridden())
1457 break;
1458 Ptr = GA->getAliasee();
1459 } else {
1460 break;
1461 }
1462 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1463 } while (Visited.insert(Ptr));
1464
1465 if (!OffsetPtr) {
1466 if (!Int8Ptr) {
1467 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001468 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001469 Int8PtrOffset = Offset;
1470 }
1471
1472 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1473 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001474 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001475 }
1476 Ptr = OffsetPtr;
1477
1478 // On the off chance we were targeting i8*, guard the bitcast here.
1479 if (Ptr->getType() != PointerTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001480 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001481
1482 return Ptr;
1483}
1484
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001485/// \brief Test whether we can convert a value from the old to the new type.
1486///
1487/// This predicate should be used to guard calls to convertValue in order to
1488/// ensure that we only try to convert viable values. The strategy is that we
1489/// will peel off single element struct and array wrappings to get to an
1490/// underlying value, and convert that value.
1491static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1492 if (OldTy == NewTy)
1493 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001494 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1495 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1496 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1497 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001498 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1499 return false;
1500 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1501 return false;
1502
Benjamin Kramer56262592013-09-22 11:24:58 +00001503 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001504 // of pointers and integers.
1505 OldTy = OldTy->getScalarType();
1506 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001507 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1508 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1509 return true;
1510 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1511 return true;
1512 return false;
1513 }
1514
1515 return true;
1516}
1517
1518/// \brief Generic routine to convert an SSA value to a value of a different
1519/// type.
1520///
1521/// This will try various different casting techniques, such as bitcasts,
1522/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1523/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001524static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001525 Type *NewTy) {
1526 Type *OldTy = V->getType();
1527 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1528
1529 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001530 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001531
1532 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1533 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001534 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1535 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001536
Benjamin Kramer90901a32013-09-21 20:36:04 +00001537 // See if we need inttoptr for this type pair. A cast involving both scalars
1538 // and vectors requires and additional bitcast.
1539 if (OldTy->getScalarType()->isIntegerTy() &&
1540 NewTy->getScalarType()->isPointerTy()) {
1541 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1542 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1543 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1544 NewTy);
1545
1546 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1547 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1548 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1549 NewTy);
1550
1551 return IRB.CreateIntToPtr(V, NewTy);
1552 }
1553
1554 // See if we need ptrtoint for this type pair. A cast involving both scalars
1555 // and vectors requires and additional bitcast.
1556 if (OldTy->getScalarType()->isPointerTy() &&
1557 NewTy->getScalarType()->isIntegerTy()) {
1558 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1559 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1560 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1561 NewTy);
1562
1563 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1564 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1565 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1566 NewTy);
1567
1568 return IRB.CreatePtrToInt(V, NewTy);
1569 }
1570
1571 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001572}
1573
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001574/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001575///
1576/// This function is called to test each entry in a partioning which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001577/// for a single slice.
1578static bool isVectorPromotionViableForSlice(
1579 const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
1580 uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
1581 AllocaSlices::const_iterator I) {
1582 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001583 uint64_t BeginOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001584 std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001585 uint64_t BeginIndex = BeginOffset / ElementSize;
1586 if (BeginIndex * ElementSize != BeginOffset ||
1587 BeginIndex >= Ty->getNumElements())
1588 return false;
1589 uint64_t EndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001590 std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001591 uint64_t EndIndex = EndOffset / ElementSize;
1592 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1593 return false;
1594
1595 assert(EndIndex > BeginIndex && "Empty vector!");
1596 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001597 Type *SliceTy =
Chandler Carruthf0546402013-07-18 07:15:00 +00001598 (NumElements == 1) ? Ty->getElementType()
1599 : VectorType::get(Ty->getElementType(), NumElements);
1600
1601 Type *SplitIntTy =
1602 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1603
1604 Use *U = I->getUse();
1605
1606 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1607 if (MI->isVolatile())
1608 return false;
1609 if (!I->isSplittable())
1610 return false; // Skip any unsplittable intrinsics.
1611 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1612 // Disable vector promotion when there are loads or stores of an FCA.
1613 return false;
1614 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1615 if (LI->isVolatile())
1616 return false;
1617 Type *LTy = LI->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001618 if (SliceBeginOffset > I->beginOffset() ||
1619 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001620 assert(LTy->isIntegerTy());
1621 LTy = SplitIntTy;
1622 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001623 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001624 return false;
1625 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1626 if (SI->isVolatile())
1627 return false;
1628 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001629 if (SliceBeginOffset > I->beginOffset() ||
1630 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001631 assert(STy->isIntegerTy());
1632 STy = SplitIntTy;
1633 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001634 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001635 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001636 } else {
1637 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001638 }
1639
1640 return true;
1641}
1642
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001643/// \brief Test whether the given alloca partitioning and range of slices can be
1644/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001645///
1646/// This is a quick test to check whether we can rewrite a particular alloca
1647/// partition (and its newly formed alloca) into a vector alloca with only
1648/// whole-vector loads and stores such that it could be promoted to a vector
1649/// SSA value. We only can ensure this for a limited set of operations, and we
1650/// don't want to do the rewrites unless we are confident that the result will
1651/// be promotable, so we have an early test here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001652static bool
1653isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
1654 uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
1655 AllocaSlices::const_iterator I,
1656 AllocaSlices::const_iterator E,
1657 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001658 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1659 if (!Ty)
1660 return false;
1661
Chandler Carruth90a735d2013-07-19 07:21:28 +00001662 uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001663
1664 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1665 // that aren't byte sized.
1666 if (ElementSize % 8)
1667 return false;
Chandler Carruth90a735d2013-07-19 07:21:28 +00001668 assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
Benjamin Kramerc003a452013-01-01 16:13:35 +00001669 "vector size not a multiple of element size?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001670 ElementSize /= 8;
1671
Chandler Carruthf0546402013-07-18 07:15:00 +00001672 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001673 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1674 SliceEndOffset, Ty, ElementSize, I))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001675 return false;
1676
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001677 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1678 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001679 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001680 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1681 SliceEndOffset, Ty, ElementSize, *SUI))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001682 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001683
1684 return true;
1685}
1686
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001687/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001688///
1689/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001690/// test below on a single slice of the alloca.
1691static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1692 Type *AllocaTy,
1693 uint64_t AllocBeginOffset,
1694 uint64_t Size, AllocaSlices &S,
1695 AllocaSlices::const_iterator I,
1696 bool &WholeAllocaOp) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001697 uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
1698 uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
1699
1700 // We can't reasonably handle cases where the load or store extends past
1701 // the end of the aloca's type and into its padding.
1702 if (RelEnd > Size)
1703 return false;
1704
1705 Use *U = I->getUse();
1706
1707 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1708 if (LI->isVolatile())
1709 return false;
1710 if (RelBegin == 0 && RelEnd == Size)
1711 WholeAllocaOp = true;
1712 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001713 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001714 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001715 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001716 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001717 // Non-integer loads need to be convertible from the alloca type so that
1718 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001719 return false;
1720 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001721 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1722 Type *ValueTy = SI->getValueOperand()->getType();
1723 if (SI->isVolatile())
1724 return false;
1725 if (RelBegin == 0 && RelEnd == Size)
1726 WholeAllocaOp = true;
1727 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001728 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001729 return false;
1730 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001731 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001732 // Non-integer stores need to be convertible to the alloca type so that
1733 // they are promotable.
1734 return false;
1735 }
1736 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1737 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1738 return false;
1739 if (!I->isSplittable())
1740 return false; // Skip any unsplittable intrinsics.
1741 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1742 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1743 II->getIntrinsicID() != Intrinsic::lifetime_end)
1744 return false;
1745 } else {
1746 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001747 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001748
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001749 return true;
1750}
1751
Chandler Carruth435c4e02012-10-15 08:40:30 +00001752/// \brief Test whether the given alloca partition's integer operations can be
1753/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00001754///
Chandler Carruth435c4e02012-10-15 08:40:30 +00001755/// This is a quick test to check whether we can rewrite the integer loads and
1756/// stores to a particular alloca into wider loads and stores and be able to
1757/// promote the resulting alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +00001758static bool
Chandler Carruth90a735d2013-07-19 07:21:28 +00001759isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001760 uint64_t AllocBeginOffset, AllocaSlices &S,
1761 AllocaSlices::const_iterator I,
1762 AllocaSlices::const_iterator E,
1763 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001764 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00001765 // Don't create integer types larger than the maximum bitwidth.
1766 if (SizeInBits > IntegerType::MAX_INT_BITS)
1767 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00001768
1769 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001770 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001771 return false;
1772
Chandler Carruth58d05562012-10-25 04:37:07 +00001773 // We need to ensure that an integer type with the appropriate bitwidth can
1774 // be converted to the alloca type, whatever that is. We don't want to force
1775 // the alloca itself to have an integer type if there is a more suitable one.
1776 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001777 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1778 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00001779 return false;
1780
Chandler Carruth90a735d2013-07-19 07:21:28 +00001781 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
Chandler Carruth435c4e02012-10-15 08:40:30 +00001782
Chandler Carruthf0546402013-07-18 07:15:00 +00001783 // While examining uses, we ensure that the alloca has a covering load or
1784 // store. We don't want to widen the integer operations only to fail to
1785 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00001786 // later). However, if there are only splittable uses, go ahead and assume
1787 // that we cover the alloca.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001788 bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00001789
Chandler Carruthf0546402013-07-18 07:15:00 +00001790 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001791 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1792 S, I, WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00001793 return false;
1794
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001795 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1796 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001797 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001798 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1799 S, *SUI, WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001800 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001801
Chandler Carruth92924fd2012-09-24 00:34:20 +00001802 return WholeAllocaOp;
1803}
1804
Chandler Carruthd177f862013-03-20 07:30:36 +00001805static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001806 IntegerType *Ty, uint64_t Offset,
1807 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00001808 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001809 IntegerType *IntTy = cast<IntegerType>(V->getType());
1810 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1811 "Element extends past full value");
1812 uint64_t ShAmt = 8*Offset;
1813 if (DL.isBigEndian())
1814 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001815 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001816 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001817 DEBUG(dbgs() << " shifted: " << *V << "\n");
1818 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001819 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1820 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001821 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001822 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00001823 DEBUG(dbgs() << " trunced: " << *V << "\n");
1824 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001825 return V;
1826}
1827
Chandler Carruthd177f862013-03-20 07:30:36 +00001828static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001829 Value *V, uint64_t Offset, const Twine &Name) {
1830 IntegerType *IntTy = cast<IntegerType>(Old->getType());
1831 IntegerType *Ty = cast<IntegerType>(V->getType());
1832 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1833 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001834 DEBUG(dbgs() << " start: " << *V << "\n");
1835 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001836 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00001837 DEBUG(dbgs() << " extended: " << *V << "\n");
1838 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001839 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1840 "Element store outside of alloca store");
1841 uint64_t ShAmt = 8*Offset;
1842 if (DL.isBigEndian())
1843 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001844 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001845 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001846 DEBUG(dbgs() << " shifted: " << *V << "\n");
1847 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001848
1849 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1850 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1851 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00001852 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001853 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00001854 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001855 }
1856 return V;
1857}
1858
Chandler Carruthd177f862013-03-20 07:30:36 +00001859static Value *extractVector(IRBuilderTy &IRB, Value *V,
Chandler Carruthb6bc8742012-12-17 13:07:30 +00001860 unsigned BeginIndex, unsigned EndIndex,
1861 const Twine &Name) {
1862 VectorType *VecTy = cast<VectorType>(V->getType());
1863 unsigned NumElements = EndIndex - BeginIndex;
1864 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1865
1866 if (NumElements == VecTy->getNumElements())
1867 return V;
1868
1869 if (NumElements == 1) {
1870 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1871 Name + ".extract");
1872 DEBUG(dbgs() << " extract: " << *V << "\n");
1873 return V;
1874 }
1875
1876 SmallVector<Constant*, 8> Mask;
1877 Mask.reserve(NumElements);
1878 for (unsigned i = BeginIndex; i != EndIndex; ++i)
1879 Mask.push_back(IRB.getInt32(i));
1880 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1881 ConstantVector::get(Mask),
1882 Name + ".extract");
1883 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1884 return V;
1885}
1886
Chandler Carruthd177f862013-03-20 07:30:36 +00001887static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00001888 unsigned BeginIndex, const Twine &Name) {
1889 VectorType *VecTy = cast<VectorType>(Old->getType());
1890 assert(VecTy && "Can only insert a vector into a vector");
1891
1892 VectorType *Ty = dyn_cast<VectorType>(V->getType());
1893 if (!Ty) {
1894 // Single element to insert.
1895 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
1896 Name + ".insert");
1897 DEBUG(dbgs() << " insert: " << *V << "\n");
1898 return V;
1899 }
1900
1901 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
1902 "Too many elements!");
1903 if (Ty->getNumElements() == VecTy->getNumElements()) {
1904 assert(V->getType() == VecTy && "Vector type mismatch");
1905 return V;
1906 }
1907 unsigned EndIndex = BeginIndex + Ty->getNumElements();
1908
1909 // When inserting a smaller vector into the larger to store, we first
1910 // use a shuffle vector to widen it with undef elements, and then
1911 // a second shuffle vector to select between the loaded vector and the
1912 // incoming vector.
1913 SmallVector<Constant*, 8> Mask;
1914 Mask.reserve(VecTy->getNumElements());
1915 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1916 if (i >= BeginIndex && i < EndIndex)
1917 Mask.push_back(IRB.getInt32(i - BeginIndex));
1918 else
1919 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
1920 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1921 ConstantVector::get(Mask),
1922 Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00001923 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001924
1925 Mask.clear();
1926 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00001927 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
1928
1929 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
1930
1931 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001932 return V;
1933}
1934
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001935namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001936/// \brief Visitor to rewrite instructions using p particular slice of an alloca
1937/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001938///
1939/// Also implements the rewriting to vector-based accesses when the partition
1940/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1941/// lives here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001942class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001943 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001944 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
1945 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001946
Chandler Carruth90a735d2013-07-19 07:21:28 +00001947 const DataLayout &DL;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001948 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001949 SROA &Pass;
1950 AllocaInst &OldAI, &NewAI;
1951 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00001952 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001953
1954 // If we are rewriting an alloca partition which can be written as pure
1955 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001956 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001957 // - The new alloca is exactly the size of the vector type here.
1958 // - The accesses all either map to the entire vector or to a single
1959 // element.
1960 // - The set of accessing instructions is only one of those handled above
1961 // in isVectorPromotionViable. Generally these are the same access kinds
1962 // which are promotable via mem2reg.
1963 VectorType *VecTy;
1964 Type *ElementTy;
1965 uint64_t ElementSize;
1966
Chandler Carruth92924fd2012-09-24 00:34:20 +00001967 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth435c4e02012-10-15 08:40:30 +00001968 // alloca's integer operations should be widened to this integer type due to
1969 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruth92924fd2012-09-24 00:34:20 +00001970 // integer type will be stored here for easy access during rewriting.
Chandler Carruth435c4e02012-10-15 08:40:30 +00001971 IntegerType *IntTy;
Chandler Carruth92924fd2012-09-24 00:34:20 +00001972
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001973 // The offset of the slice currently being rewritten.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001974 uint64_t BeginOffset, EndOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001975 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001976 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00001977 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001978 Instruction *OldPtr;
1979
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00001980 // Track post-rewrite users which are PHI nodes and Selects.
1981 SmallPtrSetImpl<PHINode *> &PHIUsers;
1982 SmallPtrSetImpl<SelectInst *> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00001983
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001984 // Utility IR builder, whose name prefix is setup for each visited use, and
1985 // the insertion point is set to point to the user.
1986 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001987
1988public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001989 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
1990 AllocaInst &OldAI, AllocaInst &NewAI,
1991 uint64_t NewBeginOffset, uint64_t NewEndOffset,
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00001992 bool IsVectorPromotable, bool IsIntegerPromotable,
1993 SmallPtrSetImpl<PHINode *> &PHIUsers,
1994 SmallPtrSetImpl<SelectInst *> &SelectUsers)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001995 : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthf0546402013-07-18 07:15:00 +00001996 NewAllocaBeginOffset(NewBeginOffset), NewAllocaEndOffset(NewEndOffset),
1997 NewAllocaTy(NewAI.getAllocatedType()),
1998 VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : 0),
1999 ElementTy(VecTy ? VecTy->getElementType() : 0),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002000 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00002001 IntTy(IsIntegerPromotable
2002 ? Type::getIntNTy(
2003 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002004 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Chandler Carruthf0546402013-07-18 07:15:00 +00002005 : 0),
2006 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002007 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002008 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002009 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002010 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002011 "Only multiple-of-8 sized vector elements are viable");
2012 ++NumVectorized;
2013 }
2014 assert((!IsVectorPromotable && !IsIntegerPromotable) ||
2015 IsVectorPromotable != IsIntegerPromotable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002016 }
2017
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002018 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002019 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002020 BeginOffset = I->beginOffset();
2021 EndOffset = I->endOffset();
2022 IsSplittable = I->isSplittable();
2023 IsSplit =
2024 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002025
Chandler Carruthf0546402013-07-18 07:15:00 +00002026 OldUse = I->getUse();
2027 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002028
Chandler Carruthf0546402013-07-18 07:15:00 +00002029 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2030 IRB.SetInsertPoint(OldUserI);
2031 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2032 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2033
2034 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2035 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002036 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002037 return CanSROA;
2038 }
2039
2040private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002041 // Make sure the other visit overloads are visible.
2042 using Base::visit;
2043
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002044 // Every instruction which can end up as a user must have a rewrite rule.
2045 bool visitInstruction(Instruction &I) {
2046 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2047 llvm_unreachable("No rewrite rule for this instruction!");
2048 }
2049
Chandler Carruthf0546402013-07-18 07:15:00 +00002050 Value *getAdjustedAllocaPtr(IRBuilderTy &IRB, uint64_t Offset,
2051 Type *PointerTy) {
2052 assert(Offset >= NewAllocaBeginOffset);
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002053#ifndef NDEBUG
2054 StringRef OldName = OldPtr->getName();
2055 // Skip through the last '.sroa.' component of the name.
2056 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2057 if (LastSROAPrefix != StringRef::npos) {
2058 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2059 // Look for an SROA slice index.
2060 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2061 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2062 // Strip the index and look for the offset.
2063 OldName = OldName.substr(IndexEnd + 1);
2064 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2065 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2066 // Strip the offset.
2067 OldName = OldName.substr(OffsetEnd + 1);
2068 }
2069 }
2070 // Strip any SROA suffixes as well.
2071 OldName = OldName.substr(0, OldName.find(".sroa_"));
2072#endif
Chandler Carruth90a735d2013-07-19 07:21:28 +00002073 return getAdjustedPtr(IRB, DL, &NewAI, APInt(DL.getPointerSizeInBits(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002074 Offset - NewAllocaBeginOffset),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002075 PointerTy,
2076#ifndef NDEBUG
2077 Twine(OldName) + "."
2078#else
2079 Twine()
2080#endif
2081 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002082 }
2083
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002084 /// \brief Compute suitable alignment to access an offset into the new alloca.
2085 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002086 unsigned NewAIAlign = NewAI.getAlignment();
2087 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002088 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth176ca712012-10-01 12:16:54 +00002089 return MinAlign(NewAIAlign, Offset);
2090 }
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002091
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002092 /// \brief Compute suitable alignment to access a type at an offset of the
2093 /// new alloca.
2094 ///
2095 /// \returns zero if the type's ABI alignment is a suitable alignment,
2096 /// otherwise returns the maximal suitable alignment.
2097 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2098 unsigned Align = getOffsetAlign(Offset);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002099 return Align == DL.getABITypeAlignment(Ty) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002100 }
2101
Chandler Carruth845b73c2012-11-21 08:16:30 +00002102 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002103 assert(VecTy && "Can only call getIndex when rewriting a vector");
2104 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2105 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2106 uint32_t Index = RelOffset / ElementSize;
2107 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002108 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002109 }
2110
2111 void deleteIfTriviallyDead(Value *V) {
2112 Instruction *I = cast<Instruction>(V);
2113 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002114 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002115 }
2116
Chandler Carruthf0546402013-07-18 07:15:00 +00002117 Value *rewriteVectorizedLoadInst(uint64_t NewBeginOffset,
2118 uint64_t NewEndOffset) {
2119 unsigned BeginIndex = getIndex(NewBeginOffset);
2120 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002121 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002122
2123 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002124 "load");
2125 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002126 }
2127
Chandler Carruthf0546402013-07-18 07:15:00 +00002128 Value *rewriteIntegerLoad(LoadInst &LI, uint64_t NewBeginOffset,
2129 uint64_t NewEndOffset) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002130 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002131 assert(!LI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002132 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002133 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002134 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002135 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2136 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2137 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002138 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002139 "extract");
Chandler Carruth18db7952012-11-20 01:12:50 +00002140 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002141 }
2142
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002143 bool visitLoadInst(LoadInst &LI) {
2144 DEBUG(dbgs() << " original: " << LI << "\n");
2145 Value *OldOp = LI.getOperand(0);
2146 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002147
Chandler Carruthf0546402013-07-18 07:15:00 +00002148 // Compute the intersecting offset range.
2149 assert(BeginOffset < NewAllocaEndOffset);
2150 assert(EndOffset > NewAllocaBeginOffset);
2151 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2152 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2153
2154 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth3e994a22012-11-20 10:02:19 +00002155
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002156 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), Size * 8)
2157 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002158 bool IsPtrAdjusted = false;
2159 Value *V;
2160 if (VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002161 V = rewriteVectorizedLoadInst(NewBeginOffset, NewEndOffset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002162 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002163 V = rewriteIntegerLoad(LI, NewBeginOffset, NewEndOffset);
2164 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002165 canConvertValue(DL, NewAllocaTy, LI.getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002166 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002167 LI.isVolatile(), "load");
Chandler Carruth18db7952012-11-20 01:12:50 +00002168 } else {
2169 Type *LTy = TargetTy->getPointerTo();
Chandler Carruthf0546402013-07-18 07:15:00 +00002170 V = IRB.CreateAlignedLoad(
2171 getAdjustedAllocaPtr(IRB, NewBeginOffset, LTy),
2172 getOffsetTypeAlign(TargetTy, NewBeginOffset - NewAllocaBeginOffset),
2173 LI.isVolatile(), "load");
Chandler Carruth18db7952012-11-20 01:12:50 +00002174 IsPtrAdjusted = true;
2175 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002176 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002177
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002178 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002179 assert(!LI.isVolatile());
2180 assert(LI.getType()->isIntegerTy() &&
2181 "Only integer type loads and stores are split");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002182 assert(Size < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002183 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002184 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002185 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002186 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002187 // Move the insertion point just past the load so that we can refer to it.
2188 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002189 // Create a placeholder value with the same type as LI to use as the
2190 // basis for the new value. This allows us to replace the uses of LI with
2191 // the computed value, and then replace the placeholder with LI, leaving
2192 // LI only used for this computation.
2193 Value *Placeholder
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002194 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth90a735d2013-07-19 07:21:28 +00002195 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002196 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002197 LI.replaceAllUsesWith(V);
2198 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002199 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002200 } else {
2201 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002202 }
2203
Chandler Carruth18db7952012-11-20 01:12:50 +00002204 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002205 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002206 DEBUG(dbgs() << " to: " << *V << "\n");
2207 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002208 }
2209
Chandler Carruthf0546402013-07-18 07:15:00 +00002210 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2211 uint64_t NewBeginOffset,
2212 uint64_t NewEndOffset) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002213 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002214 unsigned BeginIndex = getIndex(NewBeginOffset);
2215 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002216 assert(EndIndex > BeginIndex && "Empty vector!");
2217 unsigned NumElements = EndIndex - BeginIndex;
2218 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002219 Type *SliceTy =
2220 (NumElements == 1) ? ElementTy
2221 : VectorType::get(ElementTy, NumElements);
2222 if (V->getType() != SliceTy)
2223 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002224
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002225 // Mix in the existing elements.
2226 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2227 "load");
2228 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2229 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002230 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002231 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002232
2233 (void)Store;
2234 DEBUG(dbgs() << " to: " << *Store << "\n");
2235 return true;
2236 }
2237
Chandler Carruthf0546402013-07-18 07:15:00 +00002238 bool rewriteIntegerStore(Value *V, StoreInst &SI,
2239 uint64_t NewBeginOffset, uint64_t NewEndOffset) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002240 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002241 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002242 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002243 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002244 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002245 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002246 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2247 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002248 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002249 "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002250 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002251 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002252 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002253 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002254 (void)Store;
2255 DEBUG(dbgs() << " to: " << *Store << "\n");
2256 return true;
2257 }
2258
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002259 bool visitStoreInst(StoreInst &SI) {
2260 DEBUG(dbgs() << " original: " << SI << "\n");
2261 Value *OldOp = SI.getOperand(1);
2262 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002263
Chandler Carruth18db7952012-11-20 01:12:50 +00002264 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002265
Chandler Carruthac8317f2012-10-04 12:33:50 +00002266 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2267 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002268 if (V->getType()->isPointerTy())
2269 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002270 Pass.PostPromotionWorklist.insert(AI);
2271
Chandler Carruthf0546402013-07-18 07:15:00 +00002272 // Compute the intersecting offset range.
2273 assert(BeginOffset < NewAllocaEndOffset);
2274 assert(EndOffset > NewAllocaBeginOffset);
2275 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2276 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2277
2278 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002279 if (Size < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002280 assert(!SI.isVolatile());
2281 assert(V->getType()->isIntegerTy() &&
2282 "Only integer type loads and stores are split");
2283 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002284 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002285 "Non-byte-multiple bit width");
Chandler Carruth18db7952012-11-20 01:12:50 +00002286 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002287 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002288 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002289 }
2290
Chandler Carruth18db7952012-11-20 01:12:50 +00002291 if (VecTy)
Chandler Carruthf0546402013-07-18 07:15:00 +00002292 return rewriteVectorizedStoreInst(V, SI, OldOp, NewBeginOffset,
2293 NewEndOffset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002294 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthf0546402013-07-18 07:15:00 +00002295 return rewriteIntegerStore(V, SI, NewBeginOffset, NewEndOffset);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002296
Chandler Carruth18db7952012-11-20 01:12:50 +00002297 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002298 if (NewBeginOffset == NewAllocaBeginOffset &&
2299 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002300 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2301 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002302 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2303 SI.isVolatile());
2304 } else {
Chandler Carruthf0546402013-07-18 07:15:00 +00002305 Value *NewPtr = getAdjustedAllocaPtr(IRB, NewBeginOffset,
2306 V->getType()->getPointerTo());
2307 NewSI = IRB.CreateAlignedStore(
Chandler Carruth7625c542014-02-25 11:07:58 +00002308 V, NewPtr, getOffsetTypeAlign(V->getType(),
2309 NewBeginOffset - NewAllocaBeginOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002310 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002311 }
2312 (void)NewSI;
2313 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002314 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002315
2316 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2317 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002318 }
2319
Chandler Carruth514f34f2012-12-17 04:07:30 +00002320 /// \brief Compute an integer value from splatting an i8 across the given
2321 /// number of bytes.
2322 ///
2323 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2324 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002325 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002326 ///
2327 /// \param V The i8 value to splat.
2328 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002329 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002330 assert(Size > 0 && "Expected a positive number of bytes.");
2331 IntegerType *VTy = cast<IntegerType>(V->getType());
2332 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2333 if (Size == 1)
2334 return V;
2335
2336 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002337 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
Chandler Carruth514f34f2012-12-17 04:07:30 +00002338 ConstantExpr::getUDiv(
2339 Constant::getAllOnesValue(SplatIntTy),
2340 ConstantExpr::getZExt(
2341 Constant::getAllOnesValue(V->getType()),
2342 SplatIntTy)),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002343 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002344 return V;
2345 }
2346
Chandler Carruthccca5042012-12-17 04:07:37 +00002347 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002348 Value *getVectorSplat(Value *V, unsigned NumElements) {
2349 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002350 DEBUG(dbgs() << " splat: " << *V << "\n");
2351 return V;
2352 }
2353
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002354 bool visitMemSetInst(MemSetInst &II) {
2355 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002356 assert(II.getRawDest() == OldPtr);
2357
2358 // If the memset has a variable size, it cannot be split, just adjust the
2359 // pointer to the new alloca.
2360 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002361 assert(!IsSplit);
2362 assert(BeginOffset >= NewAllocaBeginOffset);
Chandler Carruth8183a502014-02-25 11:08:02 +00002363 II.setDest(getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002364 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002365 II.setAlignment(ConstantInt::get(CstTy, getOffsetAlign(BeginOffset)));
Chandler Carruth208124f2012-09-26 10:59:22 +00002366
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002367 deleteIfTriviallyDead(OldPtr);
2368 return false;
2369 }
2370
2371 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002372 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002373
2374 Type *AllocaTy = NewAI.getAllocatedType();
2375 Type *ScalarTy = AllocaTy->getScalarType();
2376
Chandler Carruthf0546402013-07-18 07:15:00 +00002377 // Compute the intersecting offset range.
2378 assert(BeginOffset < NewAllocaEndOffset);
2379 assert(EndOffset > NewAllocaBeginOffset);
2380 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2381 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002382 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00002383
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002384 // If this doesn't map cleanly onto the alloca type, and that type isn't
2385 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002386 if (!VecTy && !IntTy &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002387 (BeginOffset > NewAllocaBeginOffset ||
2388 EndOffset < NewAllocaEndOffset ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002389 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002390 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2391 DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002392 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002393 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2394 CallInst *New = IRB.CreateMemSet(
Chandler Carruth8183a502014-02-25 11:08:02 +00002395 getAdjustedAllocaPtr(IRB, NewBeginOffset, OldPtr->getType()),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002396 II.getValue(), Size, getOffsetAlign(SliceOffset), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002397 (void)New;
2398 DEBUG(dbgs() << " to: " << *New << "\n");
2399 return false;
2400 }
2401
2402 // If we can represent this as a simple value, we have to build the actual
2403 // value to store, which requires expanding the byte present in memset to
2404 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002405 // splatting the byte to a sufficiently wide integer, splatting it across
2406 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002407 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002408
Chandler Carruthccca5042012-12-17 04:07:37 +00002409 if (VecTy) {
2410 // If this is a memset of a vectorized alloca, insert it.
2411 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002412
Chandler Carruthf0546402013-07-18 07:15:00 +00002413 unsigned BeginIndex = getIndex(NewBeginOffset);
2414 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002415 assert(EndIndex > BeginIndex && "Empty vector!");
2416 unsigned NumElements = EndIndex - BeginIndex;
2417 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2418
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002419 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002420 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2421 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002422 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002423 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002424
Chandler Carruthce4562b2012-12-17 13:41:21 +00002425 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002426 "oldload");
2427 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002428 } else if (IntTy) {
2429 // If this is a memset on an alloca where we can widen stores, insert the
2430 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002431 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002432
Chandler Carruthf0546402013-07-18 07:15:00 +00002433 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002434 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002435
2436 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2437 EndOffset != NewAllocaBeginOffset)) {
2438 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002439 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002440 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002441 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002442 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002443 } else {
2444 assert(V->getType() == IntTy &&
2445 "Wrong type for an alloca wide integer!");
2446 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002447 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002448 } else {
2449 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002450 assert(NewBeginOffset == NewAllocaBeginOffset);
2451 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002452
Chandler Carruth90a735d2013-07-19 07:21:28 +00002453 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002454 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002455 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002456
Chandler Carruth90a735d2013-07-19 07:21:28 +00002457 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002458 }
2459
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002460 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002461 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002462 (void)New;
2463 DEBUG(dbgs() << " to: " << *New << "\n");
2464 return !II.isVolatile();
2465 }
2466
2467 bool visitMemTransferInst(MemTransferInst &II) {
2468 // Rewriting of memory transfer instructions can be a bit tricky. We break
2469 // them into two categories: split intrinsics and unsplit intrinsics.
2470
2471 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002472
Chandler Carruthf0546402013-07-18 07:15:00 +00002473 // Compute the intersecting offset range.
2474 assert(BeginOffset < NewAllocaEndOffset);
2475 assert(EndOffset > NewAllocaBeginOffset);
2476 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2477 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2478
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002479 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002480 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002481 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002482
Chandler Carruth176ca712012-10-01 12:16:54 +00002483 // Compute the relative offset within the transfer.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002484 unsigned IntPtrWidth = DL.getPointerSizeInBits();
Chandler Carruthf0546402013-07-18 07:15:00 +00002485 APInt RelOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Chandler Carruth176ca712012-10-01 12:16:54 +00002486
2487 unsigned Align = II.getAlignment();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002488 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth176ca712012-10-01 12:16:54 +00002489 if (Align > 1)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002490 Align =
2491 MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2492 MinAlign(II.getAlignment(), getOffsetAlign(SliceOffset)));
Chandler Carruth176ca712012-10-01 12:16:54 +00002493
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002494 // For unsplit intrinsics, we simply modify the source and destination
2495 // pointers in place. This isn't just an optimization, it is a matter of
2496 // correctness. With unsplit intrinsics we may be dealing with transfers
2497 // within a single alloca before SROA ran, or with transfers that have
2498 // a variable length. We may also be dealing with memmove instead of
2499 // memcpy, and so simply updating the pointers is the necessary for us to
2500 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002501 if (!IsSplittable) {
Chandler Carruth8183a502014-02-25 11:08:02 +00002502 Value *AdjustedPtr =
2503 getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002504 if (IsDest)
Chandler Carruth8183a502014-02-25 11:08:02 +00002505 II.setDest(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002506 else
Chandler Carruth8183a502014-02-25 11:08:02 +00002507 II.setSource(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002508
Chandler Carruth208124f2012-09-26 10:59:22 +00002509 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth176ca712012-10-01 12:16:54 +00002510 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruth208124f2012-09-26 10:59:22 +00002511
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002512 DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002513 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002514 return false;
2515 }
2516 // For split transfer intrinsics we have an incredibly useful assurance:
2517 // the source and destination do not reside within the same alloca, and at
2518 // least one of them does not escape. This means that we can replace
2519 // memmove with memcpy, and we don't need to worry about all manner of
2520 // downsides to splitting and transforming the operations.
2521
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002522 // If this doesn't map cleanly onto the alloca type, and that type isn't
2523 // a single value type, just emit a memcpy.
2524 bool EmitMemCpy
Chandler Carruthf0546402013-07-18 07:15:00 +00002525 = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
2526 EndOffset < NewAllocaEndOffset ||
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002527 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002528
2529 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2530 // size hasn't been shrunk based on analysis of the viable range, this is
2531 // a no-op.
2532 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002533 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002534 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002535
2536 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002537 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002538 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002539 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002540 return false;
2541 }
2542 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002543 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002544
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002545 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2546 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002547 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002548 if (AllocaInst *AI
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002549 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2550 assert(AI != &OldAI && AI != &NewAI &&
2551 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002552 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002553 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002554
2555 if (EmitMemCpy) {
Rafael Espindola8eee97d2014-02-14 19:02:01 +00002556 Type *OtherPtrTy = OtherPtr->getType();
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002557
2558 // Compute the other pointer, folding as much as possible to produce
2559 // a single, simple GEP in most cases.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002560 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy,
2561 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002562
Chandler Carruth8183a502014-02-25 11:08:02 +00002563 Value *OurPtr =
2564 getAdjustedAllocaPtr(IRB, NewBeginOffset, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002565 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002566 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002567
2568 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2569 IsDest ? OtherPtr : OurPtr,
Chandler Carruth871ba722012-09-26 10:27:46 +00002570 Size, Align, II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002571 (void)New;
2572 DEBUG(dbgs() << " to: " << *New << "\n");
2573 return false;
2574 }
2575
Chandler Carruth08e5f492012-10-03 08:26:28 +00002576 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2577 // is equivalent to 1, but that isn't true if we end up rewriting this as
2578 // a load or store.
2579 if (!Align)
2580 Align = 1;
2581
Chandler Carruthf0546402013-07-18 07:15:00 +00002582 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2583 NewEndOffset == NewAllocaEndOffset;
2584 uint64_t Size = NewEndOffset - NewBeginOffset;
2585 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2586 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002587 unsigned NumElements = EndIndex - BeginIndex;
2588 IntegerType *SubIntTy
2589 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2590
2591 Type *OtherPtrTy = NewAI.getType();
2592 if (VecTy && !IsWholeAlloca) {
2593 if (NumElements == 1)
2594 OtherPtrTy = VecTy->getElementType();
2595 else
2596 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2597
2598 OtherPtrTy = OtherPtrTy->getPointerTo();
2599 } else if (IntTy && !IsWholeAlloca) {
2600 OtherPtrTy = SubIntTy->getPointerTo();
2601 }
2602
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002603 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy,
2604 OtherPtr->getName() + ".");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002605 Value *DstPtr = &NewAI;
2606 if (!IsDest)
2607 std::swap(SrcPtr, DstPtr);
2608
2609 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002610 if (VecTy && !IsWholeAlloca && !IsDest) {
2611 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002612 "load");
2613 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002614 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002615 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002616 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002617 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002618 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002619 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002620 } else {
Chandler Carruth871ba722012-09-26 10:27:46 +00002621 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002622 "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002623 }
2624
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002625 if (VecTy && !IsWholeAlloca && IsDest) {
2626 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002627 "oldload");
2628 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002629 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002630 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002631 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002632 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002633 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002634 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2635 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002636 }
2637
Chandler Carruth871ba722012-09-26 10:27:46 +00002638 StoreInst *Store = cast<StoreInst>(
2639 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2640 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002641 DEBUG(dbgs() << " to: " << *Store << "\n");
2642 return !II.isVolatile();
2643 }
2644
2645 bool visitIntrinsicInst(IntrinsicInst &II) {
2646 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2647 II.getIntrinsicID() == Intrinsic::lifetime_end);
2648 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002649 assert(II.getArgOperand(1) == OldPtr);
2650
Chandler Carruthf0546402013-07-18 07:15:00 +00002651 // Compute the intersecting offset range.
2652 assert(BeginOffset < NewAllocaEndOffset);
2653 assert(EndOffset > NewAllocaBeginOffset);
2654 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2655 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2656
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002657 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002658 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002659
2660 ConstantInt *Size
2661 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002662 NewEndOffset - NewBeginOffset);
Chandler Carruth8183a502014-02-25 11:08:02 +00002663 Value *Ptr = getAdjustedAllocaPtr(IRB, NewBeginOffset, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002664 Value *New;
2665 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2666 New = IRB.CreateLifetimeStart(Ptr, Size);
2667 else
2668 New = IRB.CreateLifetimeEnd(Ptr, Size);
2669
Edwin Vane82f80d42013-01-29 17:42:24 +00002670 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002671 DEBUG(dbgs() << " to: " << *New << "\n");
2672 return true;
2673 }
2674
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002675 bool visitPHINode(PHINode &PN) {
2676 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00002677 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2678 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002679
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002680 // We would like to compute a new pointer in only one place, but have it be
2681 // as local as possible to the PHI. To do that, we re-use the location of
2682 // the old pointer, which necessarily must be in the right position to
2683 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00002684 IRBuilderTy PtrBuilder(IRB);
2685 PtrBuilder.SetInsertPoint(OldPtr);
2686 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002687
Chandler Carruthf0546402013-07-18 07:15:00 +00002688 Value *NewPtr =
2689 getAdjustedAllocaPtr(PtrBuilder, BeginOffset, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002690 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002691 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002692
Chandler Carruth82a57542012-10-01 10:54:05 +00002693 DEBUG(dbgs() << " to: " << PN << "\n");
2694 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002695
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002696 // PHIs can't be promoted on their own, but often can be speculated. We
2697 // check the speculation outside of the rewriter so that we see the
2698 // fully-rewritten alloca.
2699 PHIUsers.insert(&PN);
2700 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002701 }
2702
2703 bool visitSelectInst(SelectInst &SI) {
2704 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002705 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2706 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00002707 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2708 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002709
Chandler Carruthf0546402013-07-18 07:15:00 +00002710 Value *NewPtr = getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002711 // Replace the operands which were using the old pointer.
2712 if (SI.getOperand(1) == OldPtr)
2713 SI.setOperand(1, NewPtr);
2714 if (SI.getOperand(2) == OldPtr)
2715 SI.setOperand(2, NewPtr);
2716
Chandler Carruth82a57542012-10-01 10:54:05 +00002717 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002718 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002719
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002720 // Selects can't be promoted on their own, but often can be speculated. We
2721 // check the speculation outside of the rewriter so that we see the
2722 // fully-rewritten alloca.
2723 SelectUsers.insert(&SI);
2724 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002725 }
2726
2727};
2728}
2729
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002730namespace {
2731/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2732///
2733/// This pass aggressively rewrites all aggregate loads and stores on
2734/// a particular pointer (or any pointer derived from it which we can identify)
2735/// with scalar loads and stores.
2736class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2737 // Befriend the base class so it can delegate to private visit methods.
2738 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2739
Chandler Carruth90a735d2013-07-19 07:21:28 +00002740 const DataLayout &DL;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002741
2742 /// Queue of pointer uses to analyze and potentially rewrite.
2743 SmallVector<Use *, 8> Queue;
2744
2745 /// Set to prevent us from cycling with phi nodes and loops.
2746 SmallPtrSet<User *, 8> Visited;
2747
2748 /// The current pointer use being rewritten. This is used to dig up the used
2749 /// value (as opposed to the user).
2750 Use *U;
2751
2752public:
Chandler Carruth90a735d2013-07-19 07:21:28 +00002753 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002754
2755 /// Rewrite loads and stores through a pointer and all pointers derived from
2756 /// it.
2757 bool rewrite(Instruction &I) {
2758 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2759 enqueueUsers(I);
2760 bool Changed = false;
2761 while (!Queue.empty()) {
2762 U = Queue.pop_back_val();
2763 Changed |= visit(cast<Instruction>(U->getUser()));
2764 }
2765 return Changed;
2766 }
2767
2768private:
2769 /// Enqueue all the users of the given instruction for further processing.
2770 /// This uses a set to de-duplicate users.
2771 void enqueueUsers(Instruction &I) {
2772 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2773 ++UI)
2774 if (Visited.insert(*UI))
2775 Queue.push_back(&UI.getUse());
2776 }
2777
2778 // Conservative default is to not rewrite anything.
2779 bool visitInstruction(Instruction &I) { return false; }
2780
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002781 /// \brief Generic recursive split emission class.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002782 template <typename Derived>
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002783 class OpSplitter {
2784 protected:
2785 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00002786 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002787 /// The indices which to be used with insert- or extractvalue to select the
2788 /// appropriate value within the aggregate.
2789 SmallVector<unsigned, 4> Indices;
2790 /// The indices to a GEP instruction which will move Ptr to the correct slot
2791 /// within the aggregate.
2792 SmallVector<Value *, 4> GEPIndices;
2793 /// The base pointer of the original op, used as a base for GEPing the
2794 /// split operations.
2795 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002796
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002797 /// Initialize the splitter with an insertion point, Ptr and start with a
2798 /// single zero GEP index.
2799 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002800 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002801
2802 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002803 /// \brief Generic recursive split emission routine.
2804 ///
2805 /// This method recursively splits an aggregate op (load or store) into
2806 /// scalar or vector ops. It splits recursively until it hits a single value
2807 /// and emits that single value operation via the template argument.
2808 ///
2809 /// The logic of this routine relies on GEPs and insertvalue and
2810 /// extractvalue all operating with the same fundamental index list, merely
2811 /// formatted differently (GEPs need actual values).
2812 ///
2813 /// \param Ty The type being split recursively into smaller ops.
2814 /// \param Agg The aggregate value being built up or stored, depending on
2815 /// whether this is splitting a load or a store respectively.
2816 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2817 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002818 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002819
2820 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2821 unsigned OldSize = Indices.size();
2822 (void)OldSize;
2823 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2824 ++Idx) {
2825 assert(Indices.size() == OldSize && "Did not return to the old size");
2826 Indices.push_back(Idx);
2827 GEPIndices.push_back(IRB.getInt32(Idx));
2828 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2829 GEPIndices.pop_back();
2830 Indices.pop_back();
2831 }
2832 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002833 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002834
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002835 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2836 unsigned OldSize = Indices.size();
2837 (void)OldSize;
2838 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2839 ++Idx) {
2840 assert(Indices.size() == OldSize && "Did not return to the old size");
2841 Indices.push_back(Idx);
2842 GEPIndices.push_back(IRB.getInt32(Idx));
2843 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2844 GEPIndices.pop_back();
2845 Indices.pop_back();
2846 }
2847 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002848 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002849
2850 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002851 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002852 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002853
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002854 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002855 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002856 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002857
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002858 /// Emit a leaf load of a single value. This is called at the leaves of the
2859 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002860 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002861 assert(Ty->isSingleValueType());
2862 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00002863 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2864 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002865 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2866 DEBUG(dbgs() << " to: " << *Load << "\n");
2867 }
2868 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002869
2870 bool visitLoadInst(LoadInst &LI) {
2871 assert(LI.getPointerOperand() == *U);
2872 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2873 return false;
2874
2875 // We have an aggregate being loaded, split it apart.
2876 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002877 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002878 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002879 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002880 LI.replaceAllUsesWith(V);
2881 LI.eraseFromParent();
2882 return true;
2883 }
2884
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002885 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002886 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002887 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002888
2889 /// Emit a leaf store of a single value. This is called at the leaves of the
2890 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002891 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002892 assert(Ty->isSingleValueType());
2893 // Extract the single value and store it using the indices.
2894 Value *Store = IRB.CreateStore(
2895 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2896 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2897 (void)Store;
2898 DEBUG(dbgs() << " to: " << *Store << "\n");
2899 }
2900 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002901
2902 bool visitStoreInst(StoreInst &SI) {
2903 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2904 return false;
2905 Value *V = SI.getValueOperand();
2906 if (V->getType()->isSingleValueType())
2907 return false;
2908
2909 // We have an aggregate being stored, split it apart.
2910 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002911 StoreOpSplitter Splitter(&SI, *U);
2912 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002913 SI.eraseFromParent();
2914 return true;
2915 }
2916
2917 bool visitBitCastInst(BitCastInst &BC) {
2918 enqueueUsers(BC);
2919 return false;
2920 }
2921
2922 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2923 enqueueUsers(GEPI);
2924 return false;
2925 }
2926
2927 bool visitPHINode(PHINode &PN) {
2928 enqueueUsers(PN);
2929 return false;
2930 }
2931
2932 bool visitSelectInst(SelectInst &SI) {
2933 enqueueUsers(SI);
2934 return false;
2935 }
2936};
2937}
2938
Chandler Carruthba931992012-10-13 10:49:33 +00002939/// \brief Strip aggregate type wrapping.
2940///
2941/// This removes no-op aggregate types wrapping an underlying type. It will
2942/// strip as many layers of types as it can without changing either the type
2943/// size or the allocated size.
2944static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
2945 if (Ty->isSingleValueType())
2946 return Ty;
2947
2948 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2949 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
2950
2951 Type *InnerTy;
2952 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
2953 InnerTy = ArrTy->getElementType();
2954 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2955 const StructLayout *SL = DL.getStructLayout(STy);
2956 unsigned Index = SL->getElementContainingOffset(0);
2957 InnerTy = STy->getElementType(Index);
2958 } else {
2959 return Ty;
2960 }
2961
2962 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
2963 TypeSize > DL.getTypeSizeInBits(InnerTy))
2964 return Ty;
2965
2966 return stripAggregateTypeWrapping(DL, InnerTy);
2967}
2968
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002969/// \brief Try to find a partition of the aggregate type passed in for a given
2970/// offset and size.
2971///
2972/// This recurses through the aggregate type and tries to compute a subtype
2973/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00002974/// of an array, it will even compute a new array type for that sub-section,
2975/// and the same for structs.
2976///
2977/// Note that this routine is very strict and tries to find a partition of the
2978/// type which produces the *exact* right offset and size. It is not forgiving
2979/// when the size or offset cause either end of type-based partition to be off.
2980/// Also, this is a best-effort routine. It is reasonable to give up and not
2981/// return a type if necessary.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002982static Type *getTypePartition(const DataLayout &DL, Type *Ty,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002983 uint64_t Offset, uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002984 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
2985 return stripAggregateTypeWrapping(DL, Ty);
2986 if (Offset > DL.getTypeAllocSize(Ty) ||
2987 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Chandler Carruth58d05562012-10-25 04:37:07 +00002988 return 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002989
2990 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2991 // We can't partition pointers...
2992 if (SeqTy->isPointerTy())
2993 return 0;
2994
2995 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00002996 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002997 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002998 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002999 if (NumSkippedElements >= ArrTy->getNumElements())
3000 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003001 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003002 if (NumSkippedElements >= VecTy->getNumElements())
3003 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003004 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003005 Offset -= NumSkippedElements * ElementSize;
3006
3007 // First check if we need to recurse.
3008 if (Offset > 0 || Size < ElementSize) {
3009 // Bail if the partition ends in a different array element.
3010 if ((Offset + Size) > ElementSize)
3011 return 0;
3012 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003013 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003014 }
3015 assert(Offset == 0);
3016
3017 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003018 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003019 assert(Size > ElementSize);
3020 uint64_t NumElements = Size / ElementSize;
3021 if (NumElements * ElementSize != Size)
3022 return 0;
3023 return ArrayType::get(ElementTy, NumElements);
3024 }
3025
3026 StructType *STy = dyn_cast<StructType>(Ty);
3027 if (!STy)
3028 return 0;
3029
Chandler Carruth90a735d2013-07-19 07:21:28 +00003030 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003031 if (Offset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003032 return 0;
3033 uint64_t EndOffset = Offset + Size;
3034 if (EndOffset > SL->getSizeInBytes())
3035 return 0;
3036
3037 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003038 Offset -= SL->getElementOffset(Index);
3039
3040 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003041 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003042 if (Offset >= ElementSize)
3043 return 0; // The offset points into alignment padding.
3044
3045 // See if any partition must be contained by the element.
3046 if (Offset > 0 || Size < ElementSize) {
3047 if ((Offset + Size) > ElementSize)
3048 return 0;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003049 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003050 }
3051 assert(Offset == 0);
3052
3053 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003054 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003055
3056 StructType::element_iterator EI = STy->element_begin() + Index,
3057 EE = STy->element_end();
3058 if (EndOffset < SL->getSizeInBytes()) {
3059 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3060 if (Index == EndIndex)
3061 return 0; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003062
3063 // Don't try to form "natural" types if the elements don't line up with the
3064 // expected size.
3065 // FIXME: We could potentially recurse down through the last element in the
3066 // sub-struct to find a natural end point.
3067 if (SL->getElementOffset(EndIndex) != EndOffset)
3068 return 0;
3069
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003070 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003071 EE = STy->element_begin() + EndIndex;
3072 }
3073
3074 // Try to build up a sub-structure.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003075 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003076 STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003077 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003078 if (Size != SubSL->getSizeInBytes())
3079 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003080
Chandler Carruth054a40a2012-09-14 11:08:31 +00003081 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003082}
3083
3084/// \brief Rewrite an alloca partition's users.
3085///
3086/// This routine drives both of the rewriting goals of the SROA pass. It tries
3087/// to rewrite uses of an alloca partition to be conducive for SSA value
3088/// promotion. If the partition needs a new, more refined alloca, this will
3089/// build that new alloca, preserving as much type information as possible, and
3090/// rewrite the uses of the old alloca to point at the new one and have the
3091/// appropriate new offsets. It also evaluates how successful the rewrite was
3092/// at enabling promotion and if it was successful queues the alloca to be
3093/// promoted.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003094bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
3095 AllocaSlices::iterator B, AllocaSlices::iterator E,
3096 int64_t BeginOffset, int64_t EndOffset,
3097 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003098 assert(BeginOffset < EndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003099 uint64_t SliceSize = EndOffset - BeginOffset;
Chandler Carruth82a57542012-10-01 10:54:05 +00003100
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003101 // Try to compute a friendly type for this partition of the alloca. This
3102 // won't always succeed, in which case we fall back to a legal integer type
3103 // or an i8 array of an appropriate size.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003104 Type *SliceTy = 0;
Chandler Carruthf0546402013-07-18 07:15:00 +00003105 if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003106 if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
3107 SliceTy = CommonUseTy;
3108 if (!SliceTy)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003109 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003110 BeginOffset, SliceSize))
3111 SliceTy = TypePartitionTy;
3112 if ((!SliceTy || (SliceTy->isArrayTy() &&
3113 SliceTy->getArrayElementType()->isIntegerTy())) &&
3114 DL->isLegalInteger(SliceSize * 8))
3115 SliceTy = Type::getIntNTy(*C, SliceSize * 8);
3116 if (!SliceTy)
3117 SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
3118 assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
Chandler Carruthf0546402013-07-18 07:15:00 +00003119
3120 bool IsVectorPromotable = isVectorPromotionViable(
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003121 *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
Chandler Carruthf0546402013-07-18 07:15:00 +00003122
3123 bool IsIntegerPromotable =
3124 !IsVectorPromotable &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003125 isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003126
3127 // Check for the case where we're going to rewrite to a new alloca of the
3128 // exact same type as the original, and with the same access offsets. In that
3129 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003130 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003131 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003132 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003133 assert(BeginOffset == 0 &&
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003134 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003135 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003136 // FIXME: We should be able to bail at this point with "nothing changed".
3137 // FIXME: We might want to defer PHI speculation until after here.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003138 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003139 unsigned Alignment = AI.getAlignment();
3140 if (!Alignment) {
3141 // The minimum alignment which users can rely on when the explicit
3142 // alignment is omitted or zero is that required by the ABI for this
3143 // type.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003144 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003145 }
Chandler Carruthf0546402013-07-18 07:15:00 +00003146 Alignment = MinAlign(Alignment, BeginOffset);
Chandler Carruth903790e2012-09-29 10:41:21 +00003147 // If we will get at least this much alignment from the type alone, leave
3148 // the alloca's alignment unconstrained.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003149 if (Alignment <= DL->getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003150 Alignment = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003151 NewAI = new AllocaInst(SliceTy, 0, Alignment,
3152 AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003153 ++NumNewAllocas;
3154 }
3155
3156 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthf0546402013-07-18 07:15:00 +00003157 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3158 << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003159
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003160 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00003161 // promoted allocas. We will reset it to this point if the alloca is not in
3162 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003163 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00003164 unsigned NumUses = 0;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003165 SmallPtrSet<PHINode *, 8> PHIUsers;
3166 SmallPtrSet<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003167
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003168 AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
3169 EndOffset, IsVectorPromotable,
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003170 IsIntegerPromotable, PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00003171 bool Promotable = true;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003172 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
3173 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00003174 SUI != SUE; ++SUI) {
3175 DEBUG(dbgs() << " rewriting split ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003176 DEBUG(S.printSlice(dbgs(), *SUI, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003177 Promotable &= Rewriter.visit(*SUI);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003178 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003179 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003180 for (AllocaSlices::iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003181 DEBUG(dbgs() << " rewriting ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003182 DEBUG(S.printSlice(dbgs(), I, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003183 Promotable &= Rewriter.visit(I);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003184 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003185 }
3186
Chandler Carruth6c321c12013-07-19 10:57:36 +00003187 NumAllocaPartitionUses += NumUses;
3188 MaxUsesPerAllocaPartition =
3189 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003190
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003191 // Now that we've processed all the slices in the new partition, check if any
3192 // PHIs or Selects would block promotion.
3193 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3194 E = PHIUsers.end();
3195 I != E; ++I)
3196 if (!isSafePHIToSpeculate(**I, DL)) {
3197 Promotable = false;
3198 PHIUsers.clear();
3199 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003200 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003201 }
3202 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3203 E = SelectUsers.end();
3204 I != E; ++I)
3205 if (!isSafeSelectToSpeculate(**I, DL)) {
3206 Promotable = false;
3207 PHIUsers.clear();
3208 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003209 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003210 }
3211
3212 if (Promotable) {
3213 if (PHIUsers.empty() && SelectUsers.empty()) {
3214 // Promote the alloca.
3215 PromotableAllocas.push_back(NewAI);
3216 } else {
3217 // If we have either PHIs or Selects to speculate, add them to those
3218 // worklists and re-queue the new alloca so that we promote in on the
3219 // next iteration.
3220 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3221 E = PHIUsers.end();
3222 I != E; ++I)
3223 SpeculatablePHIs.insert(*I);
3224 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3225 E = SelectUsers.end();
3226 I != E; ++I)
3227 SpeculatableSelects.insert(*I);
3228 Worklist.insert(NewAI);
3229 }
3230 } else {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003231 // If we can't promote the alloca, iterate on it to check for new
3232 // refinements exposed by splitting the current alloca. Don't iterate on an
3233 // alloca which didn't actually change and didn't get promoted.
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003234 if (NewAI != &AI)
3235 Worklist.insert(NewAI);
Chandler Carruthac8317f2012-10-04 12:33:50 +00003236
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003237 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003238 while (PostPromotionWorklist.size() > PPWOldSize)
3239 PostPromotionWorklist.pop_back();
Chandler Carruthf0546402013-07-18 07:15:00 +00003240 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003241
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003242 return true;
3243}
3244
Chandler Carruthf0546402013-07-18 07:15:00 +00003245namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003246struct IsSliceEndLessOrEqualTo {
3247 uint64_t UpperBound;
Chandler Carruthf0546402013-07-18 07:15:00 +00003248
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003249 IsSliceEndLessOrEqualTo(uint64_t UpperBound) : UpperBound(UpperBound) {}
Chandler Carruthf0546402013-07-18 07:15:00 +00003250
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003251 bool operator()(const AllocaSlices::iterator &I) {
3252 return I->endOffset() <= UpperBound;
3253 }
3254};
Chandler Carruthf0546402013-07-18 07:15:00 +00003255}
3256
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003257static void
3258removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3259 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003260 if (Offset >= MaxSplitUseEndOffset) {
3261 SplitUses.clear();
3262 MaxSplitUseEndOffset = 0;
3263 return;
3264 }
3265
3266 size_t SplitUsesOldSize = SplitUses.size();
3267 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003268 IsSliceEndLessOrEqualTo(Offset)),
Chandler Carruthf0546402013-07-18 07:15:00 +00003269 SplitUses.end());
3270 if (SplitUsesOldSize == SplitUses.size())
3271 return;
3272
3273 // Recompute the max. While this is linear, so is remove_if.
3274 MaxSplitUseEndOffset = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003275 for (SmallVectorImpl<AllocaSlices::iterator>::iterator
Chandler Carruthf0546402013-07-18 07:15:00 +00003276 SUI = SplitUses.begin(),
3277 SUE = SplitUses.end();
3278 SUI != SUE; ++SUI)
3279 MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
3280}
3281
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003282/// \brief Walks the slices of an alloca and form partitions based on them,
3283/// rewriting each of their uses.
3284bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
3285 if (S.begin() == S.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00003286 return false;
3287
Chandler Carruth6c321c12013-07-19 10:57:36 +00003288 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003289 bool Changed = false;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003290 SmallVector<AllocaSlices::iterator, 4> SplitUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003291 uint64_t MaxSplitUseEndOffset = 0;
3292
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003293 uint64_t BeginOffset = S.begin()->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003294
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003295 for (AllocaSlices::iterator SI = S.begin(), SJ = llvm::next(SI), SE = S.end();
3296 SI != SE; SI = SJ) {
3297 uint64_t MaxEndOffset = SI->endOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003298
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003299 if (!SI->isSplittable()) {
3300 // When we're forming an unsplittable region, it must always start at the
3301 // first slice and will extend through its end.
3302 assert(BeginOffset == SI->beginOffset());
Chandler Carruthf0546402013-07-18 07:15:00 +00003303
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003304 // Form a partition including all of the overlapping slices with this
3305 // unsplittable slice.
3306 while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3307 if (!SJ->isSplittable())
3308 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3309 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003310 }
3311 } else {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003312 assert(SI->isSplittable()); // Established above.
Chandler Carruthf0546402013-07-18 07:15:00 +00003313
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003314 // Collect all of the overlapping splittable slices.
3315 while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3316 SJ->isSplittable()) {
3317 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3318 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003319 }
3320
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003321 // Back up MaxEndOffset and SJ if we ended the span early when
3322 // encountering an unsplittable slice.
3323 if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3324 assert(!SJ->isSplittable());
3325 MaxEndOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003326 }
3327 }
3328
3329 // Check if we have managed to move the end offset forward yet. If so,
3330 // we'll have to rewrite uses and erase old split uses.
3331 if (BeginOffset < MaxEndOffset) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003332 // Rewrite a sequence of overlapping slices.
3333 Changed |=
3334 rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003335 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00003336
3337 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3338 }
3339
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003340 // Accumulate all the splittable slices from the [SI,SJ) region which
Chandler Carruthf0546402013-07-18 07:15:00 +00003341 // overlap going forward.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003342 for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3343 if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3344 SplitUses.push_back(SK);
3345 MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
Chandler Carruthf0546402013-07-18 07:15:00 +00003346 }
3347
3348 // If we're already at the end and we have no split uses, we're done.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003349 if (SJ == SE && SplitUses.empty())
Chandler Carruthf0546402013-07-18 07:15:00 +00003350 break;
3351
3352 // If we have no split uses or no gap in offsets, we're ready to move to
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003353 // the next slice.
3354 if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3355 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003356 continue;
3357 }
3358
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003359 // Even if we have split slices, if the next slice is splittable and the
3360 // split slices reach it, we can simply set up the beginning offset of the
3361 // next iteration to bridge between them.
3362 if (SJ != SE && SJ->isSplittable() &&
3363 MaxSplitUseEndOffset > SJ->beginOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003364 BeginOffset = MaxEndOffset;
3365 continue;
3366 }
3367
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003368 // Otherwise, we have a tail of split slices. Rewrite them with an empty
3369 // range of slices.
Chandler Carruthf0546402013-07-18 07:15:00 +00003370 uint64_t PostSplitEndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003371 SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003372
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003373 Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
3374 SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003375 ++NumPartitions;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003376
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003377 if (SJ == SE)
Chandler Carruthf0546402013-07-18 07:15:00 +00003378 break; // Skip the rest, we don't need to do any cleanup.
3379
3380 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3381 PostSplitEndOffset);
3382
3383 // Now just reset the begin offset for the next iteration.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003384 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003385 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003386
Chandler Carruth6c321c12013-07-19 10:57:36 +00003387 NumAllocaPartitions += NumPartitions;
3388 MaxPartitionsPerAlloca =
3389 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003390
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003391 return Changed;
3392}
3393
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003394/// \brief Clobber a use with undef, deleting the used value if it becomes dead.
3395void SROA::clobberUse(Use &U) {
3396 Value *OldV = U;
3397 // Replace the use with an undef value.
3398 U = UndefValue::get(OldV->getType());
3399
3400 // Check for this making an instruction dead. We have to garbage collect
3401 // all the dead instructions to ensure the uses of any alloca end up being
3402 // minimal.
3403 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3404 if (isInstructionTriviallyDead(OldI)) {
3405 DeadInsts.insert(OldI);
3406 }
3407}
3408
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003409/// \brief Analyze an alloca for SROA.
3410///
3411/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003412/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003413/// rewritten as needed.
3414bool SROA::runOnAlloca(AllocaInst &AI) {
3415 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3416 ++NumAllocasAnalyzed;
3417
3418 // Special case dead allocas, as they're trivial.
3419 if (AI.use_empty()) {
3420 AI.eraseFromParent();
3421 return true;
3422 }
3423
3424 // Skip alloca forms that this analysis can't handle.
3425 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00003426 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003427 return false;
3428
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003429 bool Changed = false;
3430
3431 // First, split any FCA loads and stores touching this alloca to promote
3432 // better splitting and promotion opportunities.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003433 AggLoadStoreRewriter AggRewriter(*DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003434 Changed |= AggRewriter.rewrite(AI);
3435
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003436 // Build the slices using a recursive instruction-visiting builder.
3437 AllocaSlices S(*DL, AI);
3438 DEBUG(S.print(dbgs()));
3439 if (S.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003440 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003441
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003442 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003443 for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
3444 DE = S.dead_user_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003445 DI != DE; ++DI) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003446 // Free up everything used by this instruction.
3447 for (User::op_iterator DOI = (*DI)->op_begin(), DOE = (*DI)->op_end();
3448 DOI != DOE; ++DOI)
3449 clobberUse(*DOI);
3450
3451 // Now replace the uses of this instruction.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003452 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003453
3454 // And mark it for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00003455 DeadInsts.insert(*DI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003456 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003457 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003458 for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
3459 DE = S.dead_op_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003460 DO != DE; ++DO) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003461 clobberUse(**DO);
3462 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003463 }
3464
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003465 // No slices to split. Leave the dead alloca for a later pass to clean up.
3466 if (S.begin() == S.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003467 return Changed;
3468
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003469 Changed |= splitAlloca(AI, S);
Chandler Carruthf0546402013-07-18 07:15:00 +00003470
3471 DEBUG(dbgs() << " Speculating PHIs\n");
3472 while (!SpeculatablePHIs.empty())
3473 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3474
3475 DEBUG(dbgs() << " Speculating Selects\n");
3476 while (!SpeculatableSelects.empty())
3477 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3478
3479 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003480}
3481
Chandler Carruth19450da2012-09-14 10:26:38 +00003482/// \brief Delete the dead instructions accumulated in this run.
3483///
3484/// Recursively deletes the dead instructions we've accumulated. This is done
3485/// at the very end to maximize locality of the recursive delete and to
3486/// minimize the problems of invalidated instruction pointers as such pointers
3487/// are used heavily in the intermediate stages of the algorithm.
3488///
3489/// We also record the alloca instructions deleted here so that they aren't
3490/// subsequently handed to mem2reg to promote.
3491void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003492 while (!DeadInsts.empty()) {
3493 Instruction *I = DeadInsts.pop_back_val();
3494 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3495
Chandler Carruth58d05562012-10-25 04:37:07 +00003496 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3497
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003498 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3499 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3500 // Zero out the operand and see if it becomes trivially dead.
3501 *OI = 0;
3502 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003503 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003504 }
3505
3506 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3507 DeletedAllocas.insert(AI);
3508
3509 ++NumDeleted;
3510 I->eraseFromParent();
3511 }
3512}
3513
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003514static void enqueueUsersInWorklist(Instruction &I,
Chandler Carruth45b136f2013-08-11 01:03:18 +00003515 SmallVectorImpl<Instruction *> &Worklist,
3516 SmallPtrSet<Instruction *, 8> &Visited) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003517 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3518 ++UI)
Chandler Carruth45b136f2013-08-11 01:03:18 +00003519 if (Visited.insert(cast<Instruction>(*UI)))
3520 Worklist.push_back(cast<Instruction>(*UI));
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003521}
3522
Chandler Carruth70b44c52012-09-15 11:43:14 +00003523/// \brief Promote the allocas, using the best available technique.
3524///
3525/// This attempts to promote whatever allocas have been identified as viable in
3526/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3527/// If there is a domtree available, we attempt to promote using the full power
3528/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3529/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003530/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003531bool SROA::promoteAllocas(Function &F) {
3532 if (PromotableAllocas.empty())
3533 return false;
3534
3535 NumPromoted += PromotableAllocas.size();
3536
3537 if (DT && !ForceSSAUpdater) {
3538 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Nick Lewyckyc7776f72013-08-13 22:51:58 +00003539 PromoteMemToReg(PromotableAllocas, *DT);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003540 PromotableAllocas.clear();
3541 return true;
3542 }
3543
3544 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3545 SSAUpdater SSA;
3546 DIBuilder DIB(*F.getParent());
Chandler Carruth45b136f2013-08-11 01:03:18 +00003547 SmallVector<Instruction *, 64> Insts;
Chandler Carruth70b44c52012-09-15 11:43:14 +00003548
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003549 // We need a worklist to walk the uses of each alloca.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003550 SmallVector<Instruction *, 8> Worklist;
3551 SmallPtrSet<Instruction *, 8> Visited;
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003552 SmallVector<Instruction *, 32> DeadInsts;
3553
Chandler Carruth70b44c52012-09-15 11:43:14 +00003554 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3555 AllocaInst *AI = PromotableAllocas[Idx];
Chandler Carruth45b136f2013-08-11 01:03:18 +00003556 Insts.clear();
3557 Worklist.clear();
3558 Visited.clear();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003559
Chandler Carruth45b136f2013-08-11 01:03:18 +00003560 enqueueUsersInWorklist(*AI, Worklist, Visited);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003561
Chandler Carruth45b136f2013-08-11 01:03:18 +00003562 while (!Worklist.empty()) {
3563 Instruction *I = Worklist.pop_back_val();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003564
Chandler Carruth70b44c52012-09-15 11:43:14 +00003565 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3566 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3567 // leading to them) here. Eventually it should use them to optimize the
3568 // scalar values produced.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003569 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003570 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3571 II->getIntrinsicID() == Intrinsic::lifetime_end);
3572 II->eraseFromParent();
3573 continue;
3574 }
3575
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003576 // Push the loads and stores we find onto the list. SROA will already
3577 // have validated that all loads and stores are viable candidates for
3578 // promotion.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003579 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003580 assert(LI->getType() == AI->getAllocatedType());
3581 Insts.push_back(LI);
3582 continue;
3583 }
Chandler Carruth45b136f2013-08-11 01:03:18 +00003584 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003585 assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
3586 Insts.push_back(SI);
3587 continue;
3588 }
3589
3590 // For everything else, we know that only no-op bitcasts and GEPs will
3591 // make it this far, just recurse through them and recall them for later
3592 // removal.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003593 DeadInsts.push_back(I);
3594 enqueueUsersInWorklist(*I, Worklist, Visited);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003595 }
3596 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003597 while (!DeadInsts.empty())
3598 DeadInsts.pop_back_val()->eraseFromParent();
3599 AI->eraseFromParent();
Chandler Carruth70b44c52012-09-15 11:43:14 +00003600 }
3601
3602 PromotableAllocas.clear();
3603 return true;
3604}
3605
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003606namespace {
3607 /// \brief A predicate to test whether an alloca belongs to a set.
3608 class IsAllocaInSet {
3609 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3610 const SetType &Set;
3611
3612 public:
Chandler Carruth3f57b822012-10-03 00:03:00 +00003613 typedef AllocaInst *argument_type;
3614
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003615 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth3f57b822012-10-03 00:03:00 +00003616 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003617 };
3618}
3619
3620bool SROA::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00003621 if (skipOptnoneFunction(F))
3622 return false;
3623
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003624 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3625 C = &F.getContext();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003626 DL = getAnalysisIfAvailable<DataLayout>();
3627 if (!DL) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003628 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3629 return false;
3630 }
Chandler Carruth73523022014-01-13 13:07:17 +00003631 DominatorTreeWrapperPass *DTWP =
3632 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
3633 DT = DTWP ? &DTWP->getDomTree() : 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003634
3635 BasicBlock &EntryBB = F.getEntryBlock();
3636 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3637 I != E; ++I)
3638 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3639 Worklist.insert(AI);
3640
3641 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003642 // A set of deleted alloca instruction pointers which should be removed from
3643 // the list of promotable allocas.
3644 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3645
Chandler Carruthac8317f2012-10-04 12:33:50 +00003646 do {
3647 while (!Worklist.empty()) {
3648 Changed |= runOnAlloca(*Worklist.pop_back_val());
3649 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003650
Chandler Carruthac8317f2012-10-04 12:33:50 +00003651 // Remove the deleted allocas from various lists so that we don't try to
3652 // continue processing them.
3653 if (!DeletedAllocas.empty()) {
3654 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3655 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3656 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3657 PromotableAllocas.end(),
3658 IsAllocaInSet(DeletedAllocas)),
3659 PromotableAllocas.end());
3660 DeletedAllocas.clear();
3661 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003662 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003663
Chandler Carruthac8317f2012-10-04 12:33:50 +00003664 Changed |= promoteAllocas(F);
3665
3666 Worklist = PostPromotionWorklist;
3667 PostPromotionWorklist.clear();
3668 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003669
3670 return Changed;
3671}
3672
3673void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003674 if (RequiresDomTree)
Chandler Carruth73523022014-01-13 13:07:17 +00003675 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003676 AU.setPreservesCFG();
3677}