blob: 5c55143a9b19db4e8941f6fb01e459bbdf01a7f1 [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"
32#include "llvm/Analysis/Dominators.h"
33#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000034#include "llvm/Analysis/PtrUseVisitor.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000036#include "llvm/DIBuilder.h"
37#include "llvm/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Constants.h"
39#include "llvm/IR/DataLayout.h"
40#include "llvm/IR/DerivedTypes.h"
41#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 Carruth1b398ae2012-09-14 09:22:59 +000054#include "llvm/Support/raw_ostream.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000055#include "llvm/Transforms/Utils/Local.h"
56#include "llvm/Transforms/Utils/PromoteMemToReg.h"
57#include "llvm/Transforms/Utils/SSAUpdater.h"
58using namespace llvm;
59
60STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000061STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +000062STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
63STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
64STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000065STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
66STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000067STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000068STATISTIC(NumDeleted, "Number of instructions deleted");
69STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000070
Chandler Carruth70b44c52012-09-15 11:43:14 +000071/// Hidden option to force the pass to not use DomTree and mem2reg, instead
72/// forming SSA values through the SSAUpdater infrastructure.
73static cl::opt<bool>
74ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
75
Chandler Carruth1b398ae2012-09-14 09:22:59 +000076namespace {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000077/// \brief A custom IRBuilder inserter which prefixes all names if they are
78/// preserved.
79template <bool preserveNames = true>
80class IRBuilderPrefixedInserter :
81 public IRBuilderDefaultInserter<preserveNames> {
82 std::string Prefix;
83
84public:
85 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
86
87protected:
88 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
89 BasicBlock::iterator InsertPt) const {
90 IRBuilderDefaultInserter<preserveNames>::InsertHelper(
91 I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
92 }
93};
94
95// Specialization for not preserving the name is trivial.
96template <>
97class IRBuilderPrefixedInserter<false> :
98 public IRBuilderDefaultInserter<false> {
99public:
100 void SetNamePrefix(const Twine &P) {}
101};
102
Chandler Carruthd177f862013-03-20 07:30:36 +0000103/// \brief Provide a typedef for IRBuilder that drops names in release builds.
104#ifndef NDEBUG
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000105typedef llvm::IRBuilder<true, ConstantFolder,
106 IRBuilderPrefixedInserter<true> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000107#else
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000108typedef llvm::IRBuilder<false, ConstantFolder,
109 IRBuilderPrefixedInserter<false> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000110#endif
111}
112
113namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000114/// \brief A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000115///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000116/// This structure represents a slice of an alloca used by some instruction. It
117/// stores both the begin and end offsets of this use, a pointer to the use
118/// itself, and a flag indicating whether we can classify the use as splittable
119/// or not when forming partitions of the alloca.
120class Slice {
Chandler Carruthf74654d2013-03-18 08:36:46 +0000121 /// \brief The beginning offset of the range.
122 uint64_t BeginOffset;
123
124 /// \brief The ending offset, not included in the range.
125 uint64_t EndOffset;
126
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000127 /// \brief Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000128 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000129 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000130
131public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000132 Slice() : BeginOffset(), EndOffset() {}
133 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000134 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000135 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000136
137 uint64_t beginOffset() const { return BeginOffset; }
138 uint64_t endOffset() const { return EndOffset; }
139
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000140 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
141 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000142
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000143 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000144
145 bool isDead() const { return getUse() == 0; }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000146 void kill() { UseAndIsSplittable.setPointer(0); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000147
148 /// \brief Support for ordering ranges.
149 ///
150 /// This provides an ordering over ranges such that start offsets are
151 /// always increasing, and within equal start offsets, the end offsets are
152 /// decreasing. Thus the spanning range comes first in a cluster with the
153 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000154 bool operator<(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000155 if (beginOffset() < RHS.beginOffset()) return true;
156 if (beginOffset() > RHS.beginOffset()) return false;
157 if (isSplittable() != RHS.isSplittable()) return !isSplittable();
158 if (endOffset() > RHS.endOffset()) return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000159 return false;
160 }
161
162 /// \brief Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000163 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000164 uint64_t RHSOffset) {
165 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000166 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000167 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000168 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000169 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000170 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000171
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000172 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000173 return isSplittable() == RHS.isSplittable() &&
174 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000175 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000176 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000177};
Chandler Carruthf0546402013-07-18 07:15:00 +0000178} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000179
180namespace llvm {
Chandler Carruthf0546402013-07-18 07:15:00 +0000181template <typename T> struct isPodLike;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000182template <> struct isPodLike<Slice> {
Chandler Carruthf0546402013-07-18 07:15:00 +0000183 static const bool value = true;
184};
Chandler Carruthf74654d2013-03-18 08:36:46 +0000185}
186
187namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000188/// \brief Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000189///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000190/// This class represents the slices of an alloca which are formed by its
191/// various uses. If a pointer escapes, we can't fully build a representation
192/// for the slices used and we reflect that in this structure. The uses are
193/// stored, sorted by increasing beginning offset and with unsplittable slices
194/// starting at a particular offset before splittable slices.
195class AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000196public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000197 /// \brief Construct the slices of a particular alloca.
198 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000199
200 /// \brief Test whether a pointer to the allocation escapes our analysis.
201 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000202 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000203 /// ignored.
204 bool isEscaped() const { return PointerEscapingInstr; }
205
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000206 /// \brief Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000207 /// @{
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000208 typedef SmallVectorImpl<Slice>::iterator iterator;
209 iterator begin() { return Slices.begin(); }
210 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000211
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000212 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
213 const_iterator begin() const { return Slices.begin(); }
214 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000215 /// @}
216
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000217 /// \brief Allow iterating the dead users for this alloca.
218 ///
219 /// These are instructions which will never actually use the alloca as they
220 /// are outside the allocated range. They are safe to replace with undef and
221 /// delete.
222 /// @{
223 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
224 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
225 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
226 /// @}
227
Chandler Carruth93a21e72012-09-14 10:18:49 +0000228 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000229 ///
230 /// These are operands which have cannot actually be used to refer to the
231 /// alloca as they are outside its range and the user doesn't correct for
232 /// that. These mostly consist of PHI node inputs and the like which we just
233 /// need to replace with undef.
234 /// @{
235 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
236 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
237 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
238 /// @}
239
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000240#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000241 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000242 void printSlice(raw_ostream &OS, const_iterator I,
243 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000244 void printUse(raw_ostream &OS, const_iterator I,
245 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000246 void print(raw_ostream &OS) const;
NAKAMURA Takumi4bbca0b2012-09-14 10:06:10 +0000247 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
248 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000249#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000250
251private:
252 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000253 class SliceBuilder;
254 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000255
Chandler Carruthd31370e2013-07-28 09:05:49 +0000256#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000257 /// \brief Handle to alloca instruction to simplify method interfaces.
258 AllocaInst &AI;
Chandler Carruthd31370e2013-07-28 09:05:49 +0000259#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000260
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000261 /// \brief The instruction responsible for this alloca not having a known set
262 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000263 ///
264 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000265 /// store a pointer to that here and abort trying to form slices of the
266 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000267 Instruction *PointerEscapingInstr;
268
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000269 /// \brief The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000270 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000271 /// We store a vector of the slices formed by uses of the alloca here. This
272 /// vector is sorted by increasing begin offset, and then the unsplittable
273 /// slices before the splittable ones. See the Slice inner class for more
274 /// details.
275 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000276
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000277 /// \brief Instructions which will become dead if we rewrite the alloca.
278 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000279 /// Note that these are not separated by slice. This is because we expect an
280 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
281 /// all these instructions can simply be removed and replaced with undef as
282 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000283 SmallVector<Instruction *, 8> DeadUsers;
284
285 /// \brief Operands which will become dead if we rewrite the alloca.
286 ///
287 /// These are operands that in their particular use can be replaced with
288 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
289 /// to PHI nodes and the like. They aren't entirely dead (there might be
290 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
291 /// want to swap this particular input for undef to simplify the use lists of
292 /// the alloca.
293 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000294};
295}
296
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000297static Value *foldSelectInst(SelectInst &SI) {
298 // If the condition being selected on is a constant or the same value is
299 // being selected between, fold the select. Yes this does (rarely) happen
300 // early on.
301 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
302 return SI.getOperand(1+CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000303 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000304 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000305
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000306 return 0;
307}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000308
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000309/// \brief Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000310///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000311/// This class builds a set of alloca slices by recursively visiting the uses
312/// of an alloca and making a slice for each load and store at each offset.
313class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
314 friend class PtrUseVisitor<SliceBuilder>;
315 friend class InstVisitor<SliceBuilder>;
316 typedef PtrUseVisitor<SliceBuilder> Base;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000317
318 const uint64_t AllocSize;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000319 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000320
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000321 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000322 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
323
324 /// \brief Set to de-duplicate dead instructions found in the use walk.
325 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000326
327public:
Chandler Carruthd31370e2013-07-28 09:05:49 +0000328 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &S)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000329 : PtrUseVisitor<SliceBuilder>(DL),
Chandler Carruthd31370e2013-07-28 09:05:49 +0000330 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), S(S) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000331
332private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000333 void markAsDead(Instruction &I) {
334 if (VisitedDeadInsts.insert(&I))
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000335 S.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000336 }
337
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000338 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000339 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000340 // Completely skip uses which have a zero size or start either before or
341 // past the end of the allocation.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000342 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000343 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000344 << " which has zero size or starts outside of the "
345 << AllocSize << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000346 << " alloca: " << S.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000347 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000348 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000349 }
350
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000351 uint64_t BeginOffset = Offset.getZExtValue();
352 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000353
354 // Clamp the end offset to the end of the allocation. Note that this is
355 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000356 // This may appear superficially to be something we could ignore entirely,
357 // but that is not so! There may be widened loads or PHI-node uses where
358 // some instructions are dead but not others. We can't completely ignore
359 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000360 assert(AllocSize >= BeginOffset); // Established above.
361 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000362 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
363 << " to remain within the " << AllocSize << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000364 << " alloca: " << S.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000365 << " use: " << I << "\n");
366 EndOffset = AllocSize;
367 }
368
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000369 S.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000370 }
371
372 void visitBitCastInst(BitCastInst &BC) {
373 if (BC.use_empty())
374 return markAsDead(BC);
375
376 return Base::visitBitCastInst(BC);
377 }
378
379 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
380 if (GEPI.use_empty())
381 return markAsDead(GEPI);
382
383 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000384 }
385
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000386 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000387 uint64_t Size, bool IsVolatile) {
Chandler Carruth58d05562012-10-25 04:37:07 +0000388 // We allow splitting of loads and stores where the type is an integer type
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000389 // and cover the entire alloca. This prevents us from splitting over
390 // eagerly.
391 // FIXME: In the great blue eventually, we should eagerly split all integer
392 // loads and stores, and then have a separate step that merges adjacent
393 // alloca partitions into a single partition suitable for integer widening.
394 // Or we should skip the merge step and rely on GVN and other passes to
395 // merge adjacent loads and stores that survive mem2reg.
396 bool IsSplittable =
397 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
Chandler Carruth58d05562012-10-25 04:37:07 +0000398
399 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000400 }
401
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000402 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000403 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
404 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000405
406 if (!IsOffsetKnown)
407 return PI.setAborted(&LI);
408
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000409 uint64_t Size = DL.getTypeStoreSize(LI.getType());
410 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000411 }
412
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000413 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000414 Value *ValOp = SI.getValueOperand();
415 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000416 return PI.setEscapedAndAborted(&SI);
417 if (!IsOffsetKnown)
418 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000419
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000420 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
421
422 // If this memory access can be shown to *statically* extend outside the
423 // bounds of of the allocation, it's behavior is undefined, so simply
424 // ignore it. Note that this is more strict than the generic clamping
425 // behavior of insertUse. We also try to handle cases which might run the
426 // risk of overflow.
427 // FIXME: We should instead consider the pointer to have escaped if this
428 // function is being instrumented for addressing bugs or race conditions.
429 if (Offset.isNegative() || Size > AllocSize ||
430 Offset.ugt(AllocSize - Size)) {
431 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
432 << " which extends past the end of the " << AllocSize
433 << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000434 << " alloca: " << S.AI << "\n"
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000435 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000436 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000437 }
438
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000439 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
440 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000441 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000442 }
443
444
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000445 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000446 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000447 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000448 if ((Length && Length->getValue() == 0) ||
449 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
450 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000451 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000452
453 if (!IsOffsetKnown)
454 return PI.setAborted(&II);
455
456 insertUse(II, Offset,
457 Length ? Length->getLimitedValue()
458 : AllocSize - Offset.getLimitedValue(),
459 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000460 }
461
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000462 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000463 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000464 if ((Length && Length->getValue() == 0) ||
465 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000466 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000467 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000468
469 if (!IsOffsetKnown)
470 return PI.setAborted(&II);
471
472 uint64_t RawOffset = Offset.getLimitedValue();
473 uint64_t Size = Length ? Length->getLimitedValue()
474 : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000475
Chandler Carruthf0546402013-07-18 07:15:00 +0000476 // Check for the special case where the same exact value is used for both
477 // source and dest.
478 if (*U == II.getRawDest() && *U == II.getRawSource()) {
479 // For non-volatile transfers this is a no-op.
480 if (!II.isVolatile())
481 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000482
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000483 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000484 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000485
Chandler Carruthf0546402013-07-18 07:15:00 +0000486 // If we have seen both source and destination for a mem transfer, then
487 // they both point to the same alloca.
488 bool Inserted;
489 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
490 llvm::tie(MTPI, Inserted) =
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000491 MemTransferSliceMap.insert(std::make_pair(&II, S.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000492 unsigned PrevIdx = MTPI->second;
493 if (!Inserted) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000494 Slice &PrevP = S.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000495
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000496 // Check if the begin offsets match and this is a non-volatile transfer.
497 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000498 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
499 PrevP.kill();
500 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000501 }
502
503 // Otherwise we have an offset transfer within the same alloca. We can't
504 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000505 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000506 }
507
Chandler Carruthe3899f22013-07-15 17:36:21 +0000508 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000509 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000510
Chandler Carruthf0546402013-07-18 07:15:00 +0000511 // Check that we ended up with a valid index in the map.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000512 assert(S.Slices[PrevIdx].getUse()->getUser() == &II &&
513 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000514 }
515
516 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000517 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000518 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000519 void visitIntrinsicInst(IntrinsicInst &II) {
520 if (!IsOffsetKnown)
521 return PI.setAborted(&II);
522
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000523 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
524 II.getIntrinsicID() == Intrinsic::lifetime_end) {
525 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000526 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
527 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000528 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000529 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000530 }
531
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000532 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000533 }
534
535 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
536 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000537 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000538 // are considered unsplittable and the size is the maximum loaded or stored
539 // size.
540 SmallPtrSet<Instruction *, 4> Visited;
541 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
542 Visited.insert(Root);
543 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruth8b907e82012-09-25 10:03:40 +0000544 // If there are no loads or stores, the access is dead. We mark that as
545 // a size zero access.
546 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000547 do {
548 Instruction *I, *UsedI;
549 llvm::tie(UsedI, I) = Uses.pop_back_val();
550
551 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000552 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000553 continue;
554 }
555 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
556 Value *Op = SI->getOperand(0);
557 if (Op == UsedI)
558 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000559 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000560 continue;
561 }
562
563 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
564 if (!GEP->hasAllZeroIndices())
565 return GEP;
566 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
567 !isa<SelectInst>(I)) {
568 return I;
569 }
570
571 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
572 ++UI)
573 if (Visited.insert(cast<Instruction>(*UI)))
574 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
575 } while (!Uses.empty());
576
577 return 0;
578 }
579
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000580 void visitPHINode(PHINode &PN) {
581 if (PN.use_empty())
Chandler Carruthf0546402013-07-18 07:15:00 +0000582 return markAsDead(PN);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000583 if (!IsOffsetKnown)
584 return PI.setAborted(&PN);
585
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000586 // See if we already have computed info on this node.
Chandler Carruthf0546402013-07-18 07:15:00 +0000587 uint64_t &PHISize = PHIOrSelectSizes[&PN];
588 if (!PHISize) {
589 // This is a new PHI node, check for an unsafe use of the PHI node.
590 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHISize))
591 return PI.setAborted(UnsafeI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000592 }
593
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000594 // For PHI and select operands outside the alloca, we can't nuke the entire
595 // phi or select -- the other side might still be relevant, so we special
596 // case them here and use a separate structure to track the operands
597 // themselves which should be replaced with undef.
Chandler Carruthf0546402013-07-18 07:15:00 +0000598 // FIXME: This should instead be escaped in the event we're instrumenting
599 // for address sanitization.
600 if ((Offset.isNegative() && (-Offset).uge(PHISize)) ||
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000601 (!Offset.isNegative() && Offset.uge(AllocSize))) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000602 S.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000603 return;
604 }
605
Chandler Carruthf0546402013-07-18 07:15:00 +0000606 insertUse(PN, Offset, PHISize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000607 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000608
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000609 void visitSelectInst(SelectInst &SI) {
610 if (SI.use_empty())
611 return markAsDead(SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000612 if (Value *Result = foldSelectInst(SI)) {
Chandler Carruthd31370e2013-07-28 09:05:49 +0000613 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000614 // If the result of the constant fold will be the pointer, recurse
615 // through the select as if we had RAUW'ed it.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000616 enqueueUsers(SI);
Chandler Carruthd31370e2013-07-28 09:05:49 +0000617 else
Chandler Carruth225d4bd2012-09-21 23:36:40 +0000618 // Otherwise the operand to the select is dead, and we can replace it
619 // with undef.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000620 S.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000621
622 return;
623 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000624 if (!IsOffsetKnown)
625 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000626
Chandler Carruthf0546402013-07-18 07:15:00 +0000627 // See if we already have computed info on this node.
628 uint64_t &SelectSize = PHIOrSelectSizes[&SI];
629 if (!SelectSize) {
630 // This is a new Select, check for an unsafe use of it.
631 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectSize))
632 return PI.setAborted(UnsafeI);
633 }
634
635 // For PHI and select operands outside the alloca, we can't nuke the entire
636 // phi or select -- the other side might still be relevant, so we special
637 // case them here and use a separate structure to track the operands
638 // themselves which should be replaced with undef.
639 // FIXME: This should instead be escaped in the event we're instrumenting
640 // for address sanitization.
641 if ((Offset.isNegative() && Offset.uge(SelectSize)) ||
642 (!Offset.isNegative() && Offset.uge(AllocSize))) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000643 S.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +0000644 return;
645 }
646
647 insertUse(SI, Offset, SelectSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000648 }
649
Chandler Carruthf0546402013-07-18 07:15:00 +0000650 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000651 void visitInstruction(Instruction &I) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000652 PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000653 }
654};
655
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000656AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Chandler Carruthd31370e2013-07-28 09:05:49 +0000657 :
658#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
659 AI(AI),
660#endif
661 PointerEscapingInstr(0) {
662 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000663 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000664 if (PtrI.isEscaped() || PtrI.isAborted()) {
665 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000666 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000667 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
668 : PtrI.getAbortingInst();
669 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000670 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000671 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000672
Benjamin Kramer08e50702013-07-20 08:38:34 +0000673 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
674 std::mem_fun_ref(&Slice::isDead)),
675 Slices.end());
676
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000677 // Sort the uses. This arranges for the offsets to be in ascending order,
678 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000679 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000680}
681
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000682#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
683
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000684void AllocaSlices::print(raw_ostream &OS, const_iterator I,
685 StringRef Indent) const {
686 printSlice(OS, I, Indent);
Chandler Carruthf0546402013-07-18 07:15:00 +0000687 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000688}
689
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000690void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
691 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000692 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000693 << " slice #" << (I - begin())
Chandler Carruthf0546402013-07-18 07:15:00 +0000694 << (I->isSplittable() ? " (splittable)" : "") << "\n";
695}
696
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000697void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
698 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000699 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000700}
701
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000702void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000703 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000704 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000705 << " A pointer to this alloca escaped by:\n"
706 << " " << *PointerEscapingInstr << "\n";
707 return;
708 }
709
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000710 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +0000711 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000712 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000713}
714
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000715void AllocaSlices::dump(const_iterator I) const { print(dbgs(), I); }
716void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000717
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000718#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
719
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000720namespace {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000721/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
722///
723/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
724/// the loads and stores of an alloca instruction, as well as updating its
725/// debug information. This is used when a domtree is unavailable and thus
726/// mem2reg in its full form can't be used to handle promotion of allocas to
727/// scalar values.
728class AllocaPromoter : public LoadAndStorePromoter {
729 AllocaInst &AI;
730 DIBuilder &DIB;
731
732 SmallVector<DbgDeclareInst *, 4> DDIs;
733 SmallVector<DbgValueInst *, 4> DVIs;
734
735public:
736 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
737 AllocaInst &AI, DIBuilder &DIB)
738 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
739
740 void run(const SmallVectorImpl<Instruction*> &Insts) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +0000741 // Retain the debug information attached to the alloca for use when
742 // rewriting loads and stores.
Chandler Carruth70b44c52012-09-15 11:43:14 +0000743 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
744 for (Value::use_iterator UI = DebugNode->use_begin(),
745 UE = DebugNode->use_end();
746 UI != UE; ++UI)
747 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
748 DDIs.push_back(DDI);
749 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
750 DVIs.push_back(DVI);
751 }
752
753 LoadAndStorePromoter::run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +0000754
755 // While we have the debug information, clear it off of the alloca. The
756 // caller takes care of deleting the alloca.
Chandler Carruth70b44c52012-09-15 11:43:14 +0000757 while (!DDIs.empty())
758 DDIs.pop_back_val()->eraseFromParent();
759 while (!DVIs.empty())
760 DVIs.pop_back_val()->eraseFromParent();
761 }
762
763 virtual bool isInstInList(Instruction *I,
764 const SmallVectorImpl<Instruction*> &Insts) const {
765 if (LoadInst *LI = dyn_cast<LoadInst>(I))
766 return LI->getOperand(0) == &AI;
767 return cast<StoreInst>(I)->getPointerOperand() == &AI;
768 }
769
770 virtual void updateDebugInfo(Instruction *Inst) const {
Craig Topper31ee5862013-07-03 15:07:05 +0000771 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000772 E = DDIs.end(); I != E; ++I) {
773 DbgDeclareInst *DDI = *I;
774 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
775 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
776 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
777 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
778 }
Craig Topper31ee5862013-07-03 15:07:05 +0000779 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000780 E = DVIs.end(); I != E; ++I) {
781 DbgValueInst *DVI = *I;
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000782 Value *Arg = 0;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000783 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
784 // If an argument is zero extended then use argument directly. The ZExt
785 // may be zapped by an optimization pass in future.
786 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
787 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000788 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000789 Arg = dyn_cast<Argument>(SExt->getOperand(0));
790 if (!Arg)
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000791 Arg = SI->getValueOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000792 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000793 Arg = LI->getPointerOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000794 } else {
795 continue;
796 }
797 Instruction *DbgVal =
798 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
799 Inst);
800 DbgVal->setDebugLoc(DVI->getDebugLoc());
801 }
802 }
803};
804} // end anon namespace
805
806
807namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000808/// \brief An optimization pass providing Scalar Replacement of Aggregates.
809///
810/// This pass takes allocations which can be completely analyzed (that is, they
811/// don't escape) and tries to turn them into scalar SSA values. There are
812/// a few steps to this process.
813///
814/// 1) It takes allocations of aggregates and analyzes the ways in which they
815/// are used to try to split them into smaller allocations, ideally of
816/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000817/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000818/// 2) It will transform accesses into forms which are suitable for SSA value
819/// promotion. This can be replacing a memset with a scalar store of an
820/// integer value, or it can involve speculating operations on a PHI or
821/// select to be a PHI or select of the results.
822/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
823/// onto insert and extract operations on a vector value, and convert them to
824/// this form. By doing so, it will enable promotion of vector aggregates to
825/// SSA vector values.
826class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000827 const bool RequiresDomTree;
828
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000829 LLVMContext *C;
Chandler Carruth90a735d2013-07-19 07:21:28 +0000830 const DataLayout *DL;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000831 DominatorTree *DT;
832
833 /// \brief Worklist of alloca instructions to simplify.
834 ///
835 /// Each alloca in the function is added to this. Each new alloca formed gets
836 /// added to it as well to recursively simplify unless that alloca can be
837 /// directly promoted. Finally, each time we rewrite a use of an alloca other
838 /// the one being actively rewritten, we add it back onto the list if not
839 /// already present to ensure it is re-visited.
840 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
841
842 /// \brief A collection of instructions to delete.
843 /// We try to batch deletions to simplify code and make things a bit more
844 /// efficient.
Chandler Carruth18db7952012-11-20 01:12:50 +0000845 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000846
Chandler Carruthac8317f2012-10-04 12:33:50 +0000847 /// \brief Post-promotion worklist.
848 ///
849 /// Sometimes we discover an alloca which has a high probability of becoming
850 /// viable for SROA after a round of promotion takes place. In those cases,
851 /// the alloca is enqueued here for re-processing.
852 ///
853 /// Note that we have to be very careful to clear allocas out of this list in
854 /// the event they are deleted.
855 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
856
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000857 /// \brief A collection of alloca instructions we can directly promote.
858 std::vector<AllocaInst *> PromotableAllocas;
859
Chandler Carruthf0546402013-07-18 07:15:00 +0000860 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
861 ///
862 /// All of these PHIs have been checked for the safety of speculation and by
863 /// being speculated will allow promoting allocas currently in the promotable
864 /// queue.
865 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
866
867 /// \brief A worklist of select instructions to speculate prior to promoting
868 /// allocas.
869 ///
870 /// All of these select instructions have been checked for the safety of
871 /// speculation and by being speculated will allow promoting allocas
872 /// currently in the promotable queue.
873 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
874
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000875public:
Chandler Carruth70b44c52012-09-15 11:43:14 +0000876 SROA(bool RequiresDomTree = true)
877 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
Chandler Carruth90a735d2013-07-19 07:21:28 +0000878 C(0), DL(0), DT(0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000879 initializeSROAPass(*PassRegistry::getPassRegistry());
880 }
881 bool runOnFunction(Function &F);
882 void getAnalysisUsage(AnalysisUsage &AU) const;
883
884 const char *getPassName() const { return "SROA"; }
885 static char ID;
886
887private:
Chandler Carruth82a57542012-10-01 10:54:05 +0000888 friend class PHIOrSelectSpeculator;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000889 friend class AllocaSliceRewriter;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000890
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000891 bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
892 AllocaSlices::iterator B, AllocaSlices::iterator E,
893 int64_t BeginOffset, int64_t EndOffset,
894 ArrayRef<AllocaSlices::iterator> SplitUses);
895 bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000896 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth19450da2012-09-14 10:26:38 +0000897 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +0000898 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000899};
900}
901
902char SROA::ID = 0;
903
Chandler Carruth70b44c52012-09-15 11:43:14 +0000904FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
905 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000906}
907
908INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
909 false, false)
910INITIALIZE_PASS_DEPENDENCY(DominatorTree)
911INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
912 false, false)
913
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000914/// Walk the range of a partitioning looking for a common type to cover this
915/// sequence of slices.
916static Type *findCommonType(AllocaSlices::const_iterator B,
917 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +0000918 uint64_t EndOffset) {
919 Type *Ty = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000920 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000921 Use *U = I->getUse();
922 if (isa<IntrinsicInst>(*U->getUser()))
923 continue;
924 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
925 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000926
Chandler Carruthf0546402013-07-18 07:15:00 +0000927 Type *UserTy = 0;
928 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser()))
929 UserTy = LI->getType();
930 else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser()))
931 UserTy = SI->getValueOperand()->getType();
932 else
933 return 0; // Bail if we have weird uses.
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000934
Chandler Carruthf0546402013-07-18 07:15:00 +0000935 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
936 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000937 // this for split integer operations where we want to use the type of the
Chandler Carruthf0546402013-07-18 07:15:00 +0000938 // entity causing the split.
939 if (ITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
940 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000941
Chandler Carruthf0546402013-07-18 07:15:00 +0000942 // If we have found an integer type use covering the alloca, use that
943 // regardless of the other types, as integers are often used for a
944 // "bucket
945 // of bits" type.
946 return ITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +0000947 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000948
949 if (Ty && Ty != UserTy)
950 return 0;
951
952 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +0000953 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000954 return Ty;
955}
Chandler Carruthe3899f22013-07-15 17:36:21 +0000956
Chandler Carruthf0546402013-07-18 07:15:00 +0000957/// PHI instructions that use an alloca and are subsequently loaded can be
958/// rewritten to load both input pointers in the pred blocks and then PHI the
959/// results, allowing the load of the alloca to be promoted.
960/// From this:
961/// %P2 = phi [i32* %Alloca, i32* %Other]
962/// %V = load i32* %P2
963/// to:
964/// %V1 = load i32* %Alloca -> will be mem2reg'd
965/// ...
966/// %V2 = load i32* %Other
967/// ...
968/// %V = phi [i32 %V1, i32 %V2]
969///
970/// We can do this to a select if its only uses are loads and if the operands
971/// to the select can be loaded unconditionally.
972///
973/// FIXME: This should be hoisted into a generic utility, likely in
974/// Transforms/Util/Local.h
975static bool isSafePHIToSpeculate(PHINode &PN,
Chandler Carruth90a735d2013-07-19 07:21:28 +0000976 const DataLayout *DL = 0) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000977 // For now, we can only do this promotion if the load is in the same block
978 // as the PHI, and if there are no stores between the phi and load.
979 // TODO: Allow recursive phi users.
980 // TODO: Allow stores.
981 BasicBlock *BB = PN.getParent();
982 unsigned MaxAlign = 0;
983 bool HaveLoad = false;
984 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end(); UI != UE;
985 ++UI) {
986 LoadInst *LI = dyn_cast<LoadInst>(*UI);
987 if (LI == 0 || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +0000988 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +0000989
Chandler Carruthf0546402013-07-18 07:15:00 +0000990 // For now we only allow loads in the same block as the PHI. This is
991 // a common case that happens when instcombine merges two loads through
992 // a PHI.
993 if (LI->getParent() != BB)
994 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +0000995
Chandler Carruthf0546402013-07-18 07:15:00 +0000996 // Ensure that there are no instructions between the PHI and the load that
997 // could store.
998 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
999 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001000 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001001
Chandler Carruthf0546402013-07-18 07:15:00 +00001002 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1003 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001004 }
1005
Chandler Carruthf0546402013-07-18 07:15:00 +00001006 if (!HaveLoad)
1007 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001008
Chandler Carruthf0546402013-07-18 07:15:00 +00001009 // We can only transform this if it is safe to push the loads into the
1010 // predecessor blocks. The only thing to watch out for is that we can't put
1011 // a possibly trapping load in the predecessor if it is a critical edge.
1012 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1013 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1014 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001015
Chandler Carruthf0546402013-07-18 07:15:00 +00001016 // If the value is produced by the terminator of the predecessor (an
1017 // invoke) or it has side-effects, there is no valid place to put a load
1018 // in the predecessor.
1019 if (TI == InVal || TI->mayHaveSideEffects())
1020 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001021
Chandler Carruthf0546402013-07-18 07:15:00 +00001022 // If the predecessor has a single successor, then the edge isn't
1023 // critical.
1024 if (TI->getNumSuccessors() == 1)
1025 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001026
Chandler Carruthf0546402013-07-18 07:15:00 +00001027 // If this pointer is always safe to load, or if we can prove that there
1028 // is already a load in the block, then we can move the load to the pred
1029 // block.
1030 if (InVal->isDereferenceablePointer() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001031 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001032 continue;
1033
1034 return false;
1035 }
1036
1037 return true;
1038}
1039
1040static void speculatePHINodeLoads(PHINode &PN) {
1041 DEBUG(dbgs() << " original: " << PN << "\n");
1042
1043 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1044 IRBuilderTy PHIBuilder(&PN);
1045 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1046 PN.getName() + ".sroa.speculated");
1047
1048 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1049 // matter which one we get and if any differ.
1050 LoadInst *SomeLoad = cast<LoadInst>(*PN.use_begin());
1051 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1052 unsigned Align = SomeLoad->getAlignment();
1053
1054 // Rewrite all loads of the PN to use the new PHI.
1055 while (!PN.use_empty()) {
1056 LoadInst *LI = cast<LoadInst>(*PN.use_begin());
1057 LI->replaceAllUsesWith(NewPN);
1058 LI->eraseFromParent();
1059 }
1060
1061 // Inject loads into all of the pred blocks.
1062 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1063 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1064 TerminatorInst *TI = Pred->getTerminator();
1065 Value *InVal = PN.getIncomingValue(Idx);
1066 IRBuilderTy PredBuilder(TI);
1067
1068 LoadInst *Load = PredBuilder.CreateLoad(
1069 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1070 ++NumLoadsSpeculated;
1071 Load->setAlignment(Align);
1072 if (TBAATag)
1073 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1074 NewPN->addIncoming(Load, Pred);
1075 }
1076
1077 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1078 PN.eraseFromParent();
1079}
1080
1081/// Select instructions that use an alloca and are subsequently loaded can be
1082/// rewritten to load both input pointers and then select between the result,
1083/// allowing the load of the alloca to be promoted.
1084/// From this:
1085/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1086/// %V = load i32* %P2
1087/// to:
1088/// %V1 = load i32* %Alloca -> will be mem2reg'd
1089/// %V2 = load i32* %Other
1090/// %V = select i1 %cond, i32 %V1, i32 %V2
1091///
1092/// We can do this to a select if its only uses are loads and if the operand
1093/// to the select can be loaded unconditionally.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001094static bool isSafeSelectToSpeculate(SelectInst &SI, const DataLayout *DL = 0) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001095 Value *TValue = SI.getTrueValue();
1096 Value *FValue = SI.getFalseValue();
1097 bool TDerefable = TValue->isDereferenceablePointer();
1098 bool FDerefable = FValue->isDereferenceablePointer();
1099
1100 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end(); UI != UE;
1101 ++UI) {
1102 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1103 if (LI == 0 || !LI->isSimple())
1104 return false;
1105
1106 // Both operands to the select need to be dereferencable, either
1107 // absolutely (e.g. allocas) or at this point because we can see other
1108 // accesses to it.
1109 if (!TDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001110 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001111 return false;
1112 if (!FDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001113 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001114 return false;
1115 }
1116
1117 return true;
1118}
1119
1120static void speculateSelectInstLoads(SelectInst &SI) {
1121 DEBUG(dbgs() << " original: " << SI << "\n");
1122
1123 IRBuilderTy IRB(&SI);
1124 Value *TV = SI.getTrueValue();
1125 Value *FV = SI.getFalseValue();
1126 // Replace the loads of the select with a select of two loads.
1127 while (!SI.use_empty()) {
1128 LoadInst *LI = cast<LoadInst>(*SI.use_begin());
1129 assert(LI->isSimple() && "We only speculate simple loads");
1130
1131 IRB.SetInsertPoint(LI);
1132 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001133 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001134 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001135 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001136 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001137
Chandler Carruthf0546402013-07-18 07:15:00 +00001138 // Transfer alignment and TBAA info if present.
1139 TL->setAlignment(LI->getAlignment());
1140 FL->setAlignment(LI->getAlignment());
1141 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1142 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1143 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001144 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001145
1146 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1147 LI->getName() + ".sroa.speculated");
1148
1149 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1150 LI->replaceAllUsesWith(V);
1151 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001152 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001153 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001154}
1155
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001156/// \brief Build a GEP out of a base pointer and indices.
1157///
1158/// This will return the BasePtr if that is valid, or build a new GEP
1159/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001160static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001161 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001162 if (Indices.empty())
1163 return BasePtr;
1164
1165 // A single zero index is a no-op, so check for this and avoid building a GEP
1166 // in that case.
1167 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1168 return BasePtr;
1169
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001170 return IRB.CreateInBoundsGEP(BasePtr, Indices, "idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001171}
1172
1173/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1174/// TargetTy without changing the offset of the pointer.
1175///
1176/// This routine assumes we've already established a properly offset GEP with
1177/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1178/// zero-indices down through type layers until we find one the same as
1179/// TargetTy. If we can't find one with the same type, we at least try to use
1180/// one with the same size. If none of that works, we just produce the GEP as
1181/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001182static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001183 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001184 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001185 if (Ty == TargetTy)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001186 return buildGEP(IRB, BasePtr, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001187
1188 // See if we can descend into a struct and locate a field with the correct
1189 // type.
1190 unsigned NumLayers = 0;
1191 Type *ElementTy = Ty;
1192 do {
1193 if (ElementTy->isPointerTy())
1194 break;
1195 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1196 ElementTy = SeqTy->getElementType();
Chandler Carruth40617f52012-10-17 07:22:16 +00001197 // Note that we use the default address space as this index is over an
1198 // array or a vector, not a pointer.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001199 Indices.push_back(IRB.getInt(APInt(DL.getPointerSizeInBits(0), 0)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001200 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001201 if (STy->element_begin() == STy->element_end())
1202 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001203 ElementTy = *STy->element_begin();
1204 Indices.push_back(IRB.getInt32(0));
1205 } else {
1206 break;
1207 }
1208 ++NumLayers;
1209 } while (ElementTy != TargetTy);
1210 if (ElementTy != TargetTy)
1211 Indices.erase(Indices.end() - NumLayers, Indices.end());
1212
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001213 return buildGEP(IRB, BasePtr, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001214}
1215
1216/// \brief Recursively compute indices for a natural GEP.
1217///
1218/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1219/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001220static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001221 Value *Ptr, Type *Ty, APInt &Offset,
1222 Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001223 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001224 if (Offset == 0)
Chandler Carruth90a735d2013-07-19 07:21:28 +00001225 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001226
1227 // We can't recurse through pointer types.
1228 if (Ty->isPointerTy())
1229 return 0;
1230
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001231 // We try to analyze GEPs over vectors here, but note that these GEPs are
1232 // extremely poorly defined currently. The long-term goal is to remove GEPing
1233 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001234 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001235 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001236 if (ElementSizeInBits % 8)
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001237 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001238 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001239 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001240 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1241 return 0;
1242 Offset -= NumSkippedElements * ElementSize;
1243 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001244 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001245 Offset, TargetTy, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001246 }
1247
1248 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1249 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001250 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001251 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001252 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1253 return 0;
1254
1255 Offset -= NumSkippedElements * ElementSize;
1256 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001257 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001258 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001259 }
1260
1261 StructType *STy = dyn_cast<StructType>(Ty);
1262 if (!STy)
1263 return 0;
1264
Chandler Carruth90a735d2013-07-19 07:21:28 +00001265 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001266 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001267 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001268 return 0;
1269 unsigned Index = SL->getElementContainingOffset(StructOffset);
1270 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1271 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001272 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001273 return 0; // The offset points into alignment padding.
1274
1275 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001276 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001277 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001278}
1279
1280/// \brief Get a natural GEP from a base pointer to a particular offset and
1281/// resulting in a particular type.
1282///
1283/// The goal is to produce a "natural" looking GEP that works with the existing
1284/// composite types to arrive at the appropriate offset and element type for
1285/// a pointer. TargetTy is the element type the returned GEP should point-to if
1286/// possible. We recurse by decreasing Offset, adding the appropriate index to
1287/// Indices, and setting Ty to the result subtype.
1288///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001289/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001290static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001291 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001292 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001293 PointerType *Ty = cast<PointerType>(Ptr->getType());
1294
1295 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1296 // an i8.
1297 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1298 return 0;
1299
1300 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001301 if (!ElementTy->isSized())
1302 return 0; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001303 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001304 if (ElementSize == 0)
1305 return 0; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001306 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001307
1308 Offset -= NumSkippedElements * ElementSize;
1309 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001310 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001311 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001312}
1313
1314/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1315/// resulting pointer has PointerTy.
1316///
1317/// This tries very hard to compute a "natural" GEP which arrives at the offset
1318/// and produces the pointer type desired. Where it cannot, it will try to use
1319/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1320/// fails, it will try to use an existing i8* and GEP to the byte offset and
1321/// bitcast to the type.
1322///
1323/// The strategy for finding the more natural GEPs is to peel off layers of the
1324/// pointer, walking back through bit casts and GEPs, searching for a base
1325/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001326/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001327/// a single GEP as possible, thus making each GEP more independent of the
1328/// surrounding code.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001329static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001330 Value *Ptr, APInt Offset, Type *PointerTy) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001331 // Even though we don't look through PHI nodes, we could be called on an
1332 // instruction in an unreachable block, which may be on a cycle.
1333 SmallPtrSet<Value *, 4> Visited;
1334 Visited.insert(Ptr);
1335 SmallVector<Value *, 4> Indices;
1336
1337 // We may end up computing an offset pointer that has the wrong type. If we
1338 // never are able to compute one directly that has the correct type, we'll
1339 // fall back to it, so keep it around here.
1340 Value *OffsetPtr = 0;
1341
1342 // Remember any i8 pointer we come across to re-use if we need to do a raw
1343 // byte offset.
1344 Value *Int8Ptr = 0;
1345 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1346
1347 Type *TargetTy = PointerTy->getPointerElementType();
1348
1349 do {
1350 // First fold any existing GEPs into the offset.
1351 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1352 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001353 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001354 break;
1355 Offset += GEPOffset;
1356 Ptr = GEP->getPointerOperand();
1357 if (!Visited.insert(Ptr))
1358 break;
1359 }
1360
1361 // See if we can perform a natural GEP here.
1362 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001363 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001364 Indices)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001365 if (P->getType() == PointerTy) {
1366 // Zap any offset pointer that we ended up computing in previous rounds.
1367 if (OffsetPtr && OffsetPtr->use_empty())
1368 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1369 I->eraseFromParent();
1370 return P;
1371 }
1372 if (!OffsetPtr) {
1373 OffsetPtr = P;
1374 }
1375 }
1376
1377 // Stash this pointer if we've found an i8*.
1378 if (Ptr->getType()->isIntegerTy(8)) {
1379 Int8Ptr = Ptr;
1380 Int8PtrOffset = Offset;
1381 }
1382
1383 // Peel off a layer of the pointer and update the offset appropriately.
1384 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1385 Ptr = cast<Operator>(Ptr)->getOperand(0);
1386 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1387 if (GA->mayBeOverridden())
1388 break;
1389 Ptr = GA->getAliasee();
1390 } else {
1391 break;
1392 }
1393 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1394 } while (Visited.insert(Ptr));
1395
1396 if (!OffsetPtr) {
1397 if (!Int8Ptr) {
1398 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001399 "raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001400 Int8PtrOffset = Offset;
1401 }
1402
1403 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1404 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001405 "raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001406 }
1407 Ptr = OffsetPtr;
1408
1409 // On the off chance we were targeting i8*, guard the bitcast here.
1410 if (Ptr->getType() != PointerTy)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001411 Ptr = IRB.CreateBitCast(Ptr, PointerTy, "cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001412
1413 return Ptr;
1414}
1415
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001416/// \brief Test whether we can convert a value from the old to the new type.
1417///
1418/// This predicate should be used to guard calls to convertValue in order to
1419/// ensure that we only try to convert viable values. The strategy is that we
1420/// will peel off single element struct and array wrappings to get to an
1421/// underlying value, and convert that value.
1422static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1423 if (OldTy == NewTy)
1424 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001425 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1426 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1427 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1428 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001429 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1430 return false;
1431 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1432 return false;
1433
1434 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1435 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1436 return true;
1437 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1438 return true;
1439 return false;
1440 }
1441
1442 return true;
1443}
1444
1445/// \brief Generic routine to convert an SSA value to a value of a different
1446/// type.
1447///
1448/// This will try various different casting techniques, such as bitcasts,
1449/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1450/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001451static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001452 Type *Ty) {
1453 assert(canConvertValue(DL, V->getType(), Ty) &&
1454 "Value not convertable to type");
1455 if (V->getType() == Ty)
1456 return V;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001457 if (IntegerType *OldITy = dyn_cast<IntegerType>(V->getType()))
1458 if (IntegerType *NewITy = dyn_cast<IntegerType>(Ty))
1459 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1460 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001461 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1462 return IRB.CreateIntToPtr(V, Ty);
1463 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1464 return IRB.CreatePtrToInt(V, Ty);
1465
1466 return IRB.CreateBitCast(V, Ty);
1467}
1468
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001469/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001470///
1471/// This function is called to test each entry in a partioning which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001472/// for a single slice.
1473static bool isVectorPromotionViableForSlice(
1474 const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
1475 uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
1476 AllocaSlices::const_iterator I) {
1477 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001478 uint64_t BeginOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001479 std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001480 uint64_t BeginIndex = BeginOffset / ElementSize;
1481 if (BeginIndex * ElementSize != BeginOffset ||
1482 BeginIndex >= Ty->getNumElements())
1483 return false;
1484 uint64_t EndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001485 std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001486 uint64_t EndIndex = EndOffset / ElementSize;
1487 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1488 return false;
1489
1490 assert(EndIndex > BeginIndex && "Empty vector!");
1491 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001492 Type *SliceTy =
Chandler Carruthf0546402013-07-18 07:15:00 +00001493 (NumElements == 1) ? Ty->getElementType()
1494 : VectorType::get(Ty->getElementType(), NumElements);
1495
1496 Type *SplitIntTy =
1497 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1498
1499 Use *U = I->getUse();
1500
1501 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1502 if (MI->isVolatile())
1503 return false;
1504 if (!I->isSplittable())
1505 return false; // Skip any unsplittable intrinsics.
1506 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1507 // Disable vector promotion when there are loads or stores of an FCA.
1508 return false;
1509 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1510 if (LI->isVolatile())
1511 return false;
1512 Type *LTy = LI->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001513 if (SliceBeginOffset > I->beginOffset() ||
1514 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001515 assert(LTy->isIntegerTy());
1516 LTy = SplitIntTy;
1517 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001518 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001519 return false;
1520 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1521 if (SI->isVolatile())
1522 return false;
1523 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001524 if (SliceBeginOffset > I->beginOffset() ||
1525 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001526 assert(STy->isIntegerTy());
1527 STy = SplitIntTy;
1528 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001529 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001530 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001531 } else {
1532 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001533 }
1534
1535 return true;
1536}
1537
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001538/// \brief Test whether the given alloca partitioning and range of slices can be
1539/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001540///
1541/// This is a quick test to check whether we can rewrite a particular alloca
1542/// partition (and its newly formed alloca) into a vector alloca with only
1543/// whole-vector loads and stores such that it could be promoted to a vector
1544/// SSA value. We only can ensure this for a limited set of operations, and we
1545/// don't want to do the rewrites unless we are confident that the result will
1546/// be promotable, so we have an early test here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001547static bool
1548isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
1549 uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
1550 AllocaSlices::const_iterator I,
1551 AllocaSlices::const_iterator E,
1552 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001553 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1554 if (!Ty)
1555 return false;
1556
Chandler Carruth90a735d2013-07-19 07:21:28 +00001557 uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001558
1559 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1560 // that aren't byte sized.
1561 if (ElementSize % 8)
1562 return false;
Chandler Carruth90a735d2013-07-19 07:21:28 +00001563 assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
Benjamin Kramerc003a452013-01-01 16:13:35 +00001564 "vector size not a multiple of element size?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001565 ElementSize /= 8;
1566
Chandler Carruthf0546402013-07-18 07:15:00 +00001567 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001568 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1569 SliceEndOffset, Ty, ElementSize, I))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001570 return false;
1571
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001572 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1573 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001574 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001575 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1576 SliceEndOffset, Ty, ElementSize, *SUI))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001577 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001578
1579 return true;
1580}
1581
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001582/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001583///
1584/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001585/// test below on a single slice of the alloca.
1586static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1587 Type *AllocaTy,
1588 uint64_t AllocBeginOffset,
1589 uint64_t Size, AllocaSlices &S,
1590 AllocaSlices::const_iterator I,
1591 bool &WholeAllocaOp) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001592 uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
1593 uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
1594
1595 // We can't reasonably handle cases where the load or store extends past
1596 // the end of the aloca's type and into its padding.
1597 if (RelEnd > Size)
1598 return false;
1599
1600 Use *U = I->getUse();
1601
1602 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1603 if (LI->isVolatile())
1604 return false;
1605 if (RelBegin == 0 && RelEnd == Size)
1606 WholeAllocaOp = true;
1607 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001608 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001609 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001610 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001611 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001612 // Non-integer loads need to be convertible from the alloca type so that
1613 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001614 return false;
1615 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001616 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1617 Type *ValueTy = SI->getValueOperand()->getType();
1618 if (SI->isVolatile())
1619 return false;
1620 if (RelBegin == 0 && RelEnd == Size)
1621 WholeAllocaOp = true;
1622 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001623 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001624 return false;
1625 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001626 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001627 // Non-integer stores need to be convertible to the alloca type so that
1628 // they are promotable.
1629 return false;
1630 }
1631 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1632 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1633 return false;
1634 if (!I->isSplittable())
1635 return false; // Skip any unsplittable intrinsics.
1636 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1637 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1638 II->getIntrinsicID() != Intrinsic::lifetime_end)
1639 return false;
1640 } else {
1641 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001642 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001643
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001644 return true;
1645}
1646
Chandler Carruth435c4e02012-10-15 08:40:30 +00001647/// \brief Test whether the given alloca partition's integer operations can be
1648/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00001649///
Chandler Carruth435c4e02012-10-15 08:40:30 +00001650/// This is a quick test to check whether we can rewrite the integer loads and
1651/// stores to a particular alloca into wider loads and stores and be able to
1652/// promote the resulting alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +00001653static bool
Chandler Carruth90a735d2013-07-19 07:21:28 +00001654isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001655 uint64_t AllocBeginOffset, AllocaSlices &S,
1656 AllocaSlices::const_iterator I,
1657 AllocaSlices::const_iterator E,
1658 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001659 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00001660 // Don't create integer types larger than the maximum bitwidth.
1661 if (SizeInBits > IntegerType::MAX_INT_BITS)
1662 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00001663
1664 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001665 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001666 return false;
1667
Chandler Carruth58d05562012-10-25 04:37:07 +00001668 // We need to ensure that an integer type with the appropriate bitwidth can
1669 // be converted to the alloca type, whatever that is. We don't want to force
1670 // the alloca itself to have an integer type if there is a more suitable one.
1671 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001672 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1673 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00001674 return false;
1675
Chandler Carruth90a735d2013-07-19 07:21:28 +00001676 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
Chandler Carruth435c4e02012-10-15 08:40:30 +00001677
Chandler Carruthf0546402013-07-18 07:15:00 +00001678 // While examining uses, we ensure that the alloca has a covering load or
1679 // store. We don't want to widen the integer operations only to fail to
1680 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00001681 // later). However, if there are only splittable uses, go ahead and assume
1682 // that we cover the alloca.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001683 bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00001684
Chandler Carruthf0546402013-07-18 07:15:00 +00001685 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001686 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1687 S, I, WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00001688 return false;
1689
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001690 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1691 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001692 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001693 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1694 S, *SUI, WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001695 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001696
Chandler Carruth92924fd2012-09-24 00:34:20 +00001697 return WholeAllocaOp;
1698}
1699
Chandler Carruthd177f862013-03-20 07:30:36 +00001700static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001701 IntegerType *Ty, uint64_t Offset,
1702 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00001703 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001704 IntegerType *IntTy = cast<IntegerType>(V->getType());
1705 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1706 "Element extends past full value");
1707 uint64_t ShAmt = 8*Offset;
1708 if (DL.isBigEndian())
1709 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001710 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001711 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001712 DEBUG(dbgs() << " shifted: " << *V << "\n");
1713 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001714 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1715 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001716 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001717 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00001718 DEBUG(dbgs() << " trunced: " << *V << "\n");
1719 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001720 return V;
1721}
1722
Chandler Carruthd177f862013-03-20 07:30:36 +00001723static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001724 Value *V, uint64_t Offset, const Twine &Name) {
1725 IntegerType *IntTy = cast<IntegerType>(Old->getType());
1726 IntegerType *Ty = cast<IntegerType>(V->getType());
1727 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1728 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001729 DEBUG(dbgs() << " start: " << *V << "\n");
1730 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001731 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00001732 DEBUG(dbgs() << " extended: " << *V << "\n");
1733 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001734 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1735 "Element store outside of alloca store");
1736 uint64_t ShAmt = 8*Offset;
1737 if (DL.isBigEndian())
1738 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001739 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001740 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001741 DEBUG(dbgs() << " shifted: " << *V << "\n");
1742 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001743
1744 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1745 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1746 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00001747 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001748 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00001749 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001750 }
1751 return V;
1752}
1753
Chandler Carruthd177f862013-03-20 07:30:36 +00001754static Value *extractVector(IRBuilderTy &IRB, Value *V,
Chandler Carruthb6bc8742012-12-17 13:07:30 +00001755 unsigned BeginIndex, unsigned EndIndex,
1756 const Twine &Name) {
1757 VectorType *VecTy = cast<VectorType>(V->getType());
1758 unsigned NumElements = EndIndex - BeginIndex;
1759 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1760
1761 if (NumElements == VecTy->getNumElements())
1762 return V;
1763
1764 if (NumElements == 1) {
1765 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1766 Name + ".extract");
1767 DEBUG(dbgs() << " extract: " << *V << "\n");
1768 return V;
1769 }
1770
1771 SmallVector<Constant*, 8> Mask;
1772 Mask.reserve(NumElements);
1773 for (unsigned i = BeginIndex; i != EndIndex; ++i)
1774 Mask.push_back(IRB.getInt32(i));
1775 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1776 ConstantVector::get(Mask),
1777 Name + ".extract");
1778 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1779 return V;
1780}
1781
Chandler Carruthd177f862013-03-20 07:30:36 +00001782static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00001783 unsigned BeginIndex, const Twine &Name) {
1784 VectorType *VecTy = cast<VectorType>(Old->getType());
1785 assert(VecTy && "Can only insert a vector into a vector");
1786
1787 VectorType *Ty = dyn_cast<VectorType>(V->getType());
1788 if (!Ty) {
1789 // Single element to insert.
1790 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
1791 Name + ".insert");
1792 DEBUG(dbgs() << " insert: " << *V << "\n");
1793 return V;
1794 }
1795
1796 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
1797 "Too many elements!");
1798 if (Ty->getNumElements() == VecTy->getNumElements()) {
1799 assert(V->getType() == VecTy && "Vector type mismatch");
1800 return V;
1801 }
1802 unsigned EndIndex = BeginIndex + Ty->getNumElements();
1803
1804 // When inserting a smaller vector into the larger to store, we first
1805 // use a shuffle vector to widen it with undef elements, and then
1806 // a second shuffle vector to select between the loaded vector and the
1807 // incoming vector.
1808 SmallVector<Constant*, 8> Mask;
1809 Mask.reserve(VecTy->getNumElements());
1810 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1811 if (i >= BeginIndex && i < EndIndex)
1812 Mask.push_back(IRB.getInt32(i - BeginIndex));
1813 else
1814 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
1815 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1816 ConstantVector::get(Mask),
1817 Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00001818 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001819
1820 Mask.clear();
1821 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00001822 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
1823
1824 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
1825
1826 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001827 return V;
1828}
1829
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001830namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001831/// \brief Visitor to rewrite instructions using p particular slice of an alloca
1832/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001833///
1834/// Also implements the rewriting to vector-based accesses when the partition
1835/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1836/// lives here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001837class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001838 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001839 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
1840 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001841
Chandler Carruth90a735d2013-07-19 07:21:28 +00001842 const DataLayout &DL;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001843 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001844 SROA &Pass;
1845 AllocaInst &OldAI, &NewAI;
1846 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00001847 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001848
1849 // If we are rewriting an alloca partition which can be written as pure
1850 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001851 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001852 // - The new alloca is exactly the size of the vector type here.
1853 // - The accesses all either map to the entire vector or to a single
1854 // element.
1855 // - The set of accessing instructions is only one of those handled above
1856 // in isVectorPromotionViable. Generally these are the same access kinds
1857 // which are promotable via mem2reg.
1858 VectorType *VecTy;
1859 Type *ElementTy;
1860 uint64_t ElementSize;
1861
Chandler Carruth92924fd2012-09-24 00:34:20 +00001862 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth435c4e02012-10-15 08:40:30 +00001863 // alloca's integer operations should be widened to this integer type due to
1864 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruth92924fd2012-09-24 00:34:20 +00001865 // integer type will be stored here for easy access during rewriting.
Chandler Carruth435c4e02012-10-15 08:40:30 +00001866 IntegerType *IntTy;
Chandler Carruth92924fd2012-09-24 00:34:20 +00001867
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001868 // The offset of the slice currently being rewritten.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001869 uint64_t BeginOffset, EndOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001870 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001871 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00001872 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001873 Instruction *OldPtr;
1874
Chandler Carruth83ea1952013-07-24 09:47:28 +00001875 // Output members carrying state about the result of visiting and rewriting
1876 // the slice of the alloca.
1877 bool IsUsedByRewrittenSpeculatableInstructions;
1878
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001879 // Utility IR builder, whose name prefix is setup for each visited use, and
1880 // the insertion point is set to point to the user.
1881 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001882
1883public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001884 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
1885 AllocaInst &OldAI, AllocaInst &NewAI,
1886 uint64_t NewBeginOffset, uint64_t NewEndOffset,
1887 bool IsVectorPromotable = false,
1888 bool IsIntegerPromotable = false)
1889 : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthf0546402013-07-18 07:15:00 +00001890 NewAllocaBeginOffset(NewBeginOffset), NewAllocaEndOffset(NewEndOffset),
1891 NewAllocaTy(NewAI.getAllocatedType()),
1892 VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : 0),
1893 ElementTy(VecTy ? VecTy->getElementType() : 0),
Chandler Carruth90a735d2013-07-19 07:21:28 +00001894 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00001895 IntTy(IsIntegerPromotable
1896 ? Type::getIntNTy(
1897 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00001898 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001899 : 0),
1900 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
Chandler Carruth83ea1952013-07-24 09:47:28 +00001901 OldPtr(), IsUsedByRewrittenSpeculatableInstructions(false),
1902 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001903 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001904 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00001905 "Only multiple-of-8 sized vector elements are viable");
1906 ++NumVectorized;
1907 }
1908 assert((!IsVectorPromotable && !IsIntegerPromotable) ||
1909 IsVectorPromotable != IsIntegerPromotable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001910 }
1911
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001912 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001913 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00001914 BeginOffset = I->beginOffset();
1915 EndOffset = I->endOffset();
1916 IsSplittable = I->isSplittable();
1917 IsSplit =
1918 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001919
Chandler Carruthf0546402013-07-18 07:15:00 +00001920 OldUse = I->getUse();
1921 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001922
Chandler Carruthf0546402013-07-18 07:15:00 +00001923 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
1924 IRB.SetInsertPoint(OldUserI);
1925 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
1926 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
1927
1928 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
1929 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001930 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001931 return CanSROA;
1932 }
1933
Chandler Carruth83ea1952013-07-24 09:47:28 +00001934 /// \brief Query whether this slice is used by speculatable instructions after
1935 /// rewriting.
1936 ///
1937 /// These instructions (PHIs and Selects currently) require the alloca slice
1938 /// to run back through the rewriter. Thus, they are promotable, but not on
1939 /// this iteration. This is distinct from a slice which is unpromotable for
1940 /// some other reason, in which case we don't even want to perform the
1941 /// speculation. This can be querried at any time and reflects whether (at
1942 /// that point) a visit call has rewritten a speculatable instruction on the
1943 /// current slice.
1944 bool isUsedByRewrittenSpeculatableInstructions() const {
1945 return IsUsedByRewrittenSpeculatableInstructions;
1946 }
1947
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001948private:
Chandler Carruthf0546402013-07-18 07:15:00 +00001949 // Make sure the other visit overloads are visible.
1950 using Base::visit;
1951
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001952 // Every instruction which can end up as a user must have a rewrite rule.
1953 bool visitInstruction(Instruction &I) {
1954 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
1955 llvm_unreachable("No rewrite rule for this instruction!");
1956 }
1957
Chandler Carruthf0546402013-07-18 07:15:00 +00001958 Value *getAdjustedAllocaPtr(IRBuilderTy &IRB, uint64_t Offset,
1959 Type *PointerTy) {
1960 assert(Offset >= NewAllocaBeginOffset);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001961 return getAdjustedPtr(IRB, DL, &NewAI, APInt(DL.getPointerSizeInBits(),
Chandler Carruthf0546402013-07-18 07:15:00 +00001962 Offset - NewAllocaBeginOffset),
1963 PointerTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001964 }
1965
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001966 /// \brief Compute suitable alignment to access an offset into the new alloca.
1967 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth176ca712012-10-01 12:16:54 +00001968 unsigned NewAIAlign = NewAI.getAlignment();
1969 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00001970 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth176ca712012-10-01 12:16:54 +00001971 return MinAlign(NewAIAlign, Offset);
1972 }
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001973
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001974 /// \brief Compute suitable alignment to access a type at an offset of the
1975 /// new alloca.
1976 ///
1977 /// \returns zero if the type's ABI alignment is a suitable alignment,
1978 /// otherwise returns the maximal suitable alignment.
1979 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
1980 unsigned Align = getOffsetAlign(Offset);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001981 return Align == DL.getABITypeAlignment(Ty) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001982 }
1983
Chandler Carruth845b73c2012-11-21 08:16:30 +00001984 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001985 assert(VecTy && "Can only call getIndex when rewriting a vector");
1986 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1987 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
1988 uint32_t Index = RelOffset / ElementSize;
1989 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00001990 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001991 }
1992
1993 void deleteIfTriviallyDead(Value *V) {
1994 Instruction *I = cast<Instruction>(V);
1995 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00001996 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001997 }
1998
Chandler Carruthf0546402013-07-18 07:15:00 +00001999 Value *rewriteVectorizedLoadInst(uint64_t NewBeginOffset,
2000 uint64_t NewEndOffset) {
2001 unsigned BeginIndex = getIndex(NewBeginOffset);
2002 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002003 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002004
2005 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002006 "load");
2007 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002008 }
2009
Chandler Carruthf0546402013-07-18 07:15:00 +00002010 Value *rewriteIntegerLoad(LoadInst &LI, uint64_t NewBeginOffset,
2011 uint64_t NewEndOffset) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002012 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002013 assert(!LI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002014 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002015 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002016 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002017 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2018 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2019 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002020 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002021 "extract");
Chandler Carruth18db7952012-11-20 01:12:50 +00002022 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002023 }
2024
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002025 bool visitLoadInst(LoadInst &LI) {
2026 DEBUG(dbgs() << " original: " << LI << "\n");
2027 Value *OldOp = LI.getOperand(0);
2028 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002029
Chandler Carruthf0546402013-07-18 07:15:00 +00002030 // Compute the intersecting offset range.
2031 assert(BeginOffset < NewAllocaEndOffset);
2032 assert(EndOffset > NewAllocaBeginOffset);
2033 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2034 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2035
2036 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth3e994a22012-11-20 10:02:19 +00002037
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002038 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), Size * 8)
2039 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002040 bool IsPtrAdjusted = false;
2041 Value *V;
2042 if (VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002043 V = rewriteVectorizedLoadInst(NewBeginOffset, NewEndOffset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002044 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002045 V = rewriteIntegerLoad(LI, NewBeginOffset, NewEndOffset);
2046 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002047 canConvertValue(DL, NewAllocaTy, LI.getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002048 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002049 LI.isVolatile(), "load");
Chandler Carruth18db7952012-11-20 01:12:50 +00002050 } else {
2051 Type *LTy = TargetTy->getPointerTo();
Chandler Carruthf0546402013-07-18 07:15:00 +00002052 V = IRB.CreateAlignedLoad(
2053 getAdjustedAllocaPtr(IRB, NewBeginOffset, LTy),
2054 getOffsetTypeAlign(TargetTy, NewBeginOffset - NewAllocaBeginOffset),
2055 LI.isVolatile(), "load");
Chandler Carruth18db7952012-11-20 01:12:50 +00002056 IsPtrAdjusted = true;
2057 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002058 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002059
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002060 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002061 assert(!LI.isVolatile());
2062 assert(LI.getType()->isIntegerTy() &&
2063 "Only integer type loads and stores are split");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002064 assert(Size < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002065 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002066 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002067 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002068 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002069 // Move the insertion point just past the load so that we can refer to it.
2070 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002071 // Create a placeholder value with the same type as LI to use as the
2072 // basis for the new value. This allows us to replace the uses of LI with
2073 // the computed value, and then replace the placeholder with LI, leaving
2074 // LI only used for this computation.
2075 Value *Placeholder
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002076 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth90a735d2013-07-19 07:21:28 +00002077 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002078 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002079 LI.replaceAllUsesWith(V);
2080 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002081 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002082 } else {
2083 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002084 }
2085
Chandler Carruth18db7952012-11-20 01:12:50 +00002086 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002087 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002088 DEBUG(dbgs() << " to: " << *V << "\n");
2089 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002090 }
2091
Chandler Carruthf0546402013-07-18 07:15:00 +00002092 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2093 uint64_t NewBeginOffset,
2094 uint64_t NewEndOffset) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002095 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002096 unsigned BeginIndex = getIndex(NewBeginOffset);
2097 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002098 assert(EndIndex > BeginIndex && "Empty vector!");
2099 unsigned NumElements = EndIndex - BeginIndex;
2100 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002101 Type *SliceTy =
2102 (NumElements == 1) ? ElementTy
2103 : VectorType::get(ElementTy, NumElements);
2104 if (V->getType() != SliceTy)
2105 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002106
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002107 // Mix in the existing elements.
2108 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2109 "load");
2110 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2111 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002112 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002113 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002114
2115 (void)Store;
2116 DEBUG(dbgs() << " to: " << *Store << "\n");
2117 return true;
2118 }
2119
Chandler Carruthf0546402013-07-18 07:15:00 +00002120 bool rewriteIntegerStore(Value *V, StoreInst &SI,
2121 uint64_t NewBeginOffset, uint64_t NewEndOffset) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002122 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002123 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002124 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002125 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002126 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002127 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002128 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2129 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002130 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002131 "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002132 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002133 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002134 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002135 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002136 (void)Store;
2137 DEBUG(dbgs() << " to: " << *Store << "\n");
2138 return true;
2139 }
2140
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002141 bool visitStoreInst(StoreInst &SI) {
2142 DEBUG(dbgs() << " original: " << SI << "\n");
2143 Value *OldOp = SI.getOperand(1);
2144 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002145
Chandler Carruth18db7952012-11-20 01:12:50 +00002146 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002147
Chandler Carruthac8317f2012-10-04 12:33:50 +00002148 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2149 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002150 if (V->getType()->isPointerTy())
2151 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002152 Pass.PostPromotionWorklist.insert(AI);
2153
Chandler Carruthf0546402013-07-18 07:15:00 +00002154 // Compute the intersecting offset range.
2155 assert(BeginOffset < NewAllocaEndOffset);
2156 assert(EndOffset > NewAllocaBeginOffset);
2157 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2158 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2159
2160 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002161 if (Size < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002162 assert(!SI.isVolatile());
2163 assert(V->getType()->isIntegerTy() &&
2164 "Only integer type loads and stores are split");
2165 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002166 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002167 "Non-byte-multiple bit width");
Chandler Carruth18db7952012-11-20 01:12:50 +00002168 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002169 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002170 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002171 }
2172
Chandler Carruth18db7952012-11-20 01:12:50 +00002173 if (VecTy)
Chandler Carruthf0546402013-07-18 07:15:00 +00002174 return rewriteVectorizedStoreInst(V, SI, OldOp, NewBeginOffset,
2175 NewEndOffset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002176 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthf0546402013-07-18 07:15:00 +00002177 return rewriteIntegerStore(V, SI, NewBeginOffset, NewEndOffset);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002178
Chandler Carruth18db7952012-11-20 01:12:50 +00002179 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002180 if (NewBeginOffset == NewAllocaBeginOffset &&
2181 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002182 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2183 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002184 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2185 SI.isVolatile());
2186 } else {
Chandler Carruthf0546402013-07-18 07:15:00 +00002187 Value *NewPtr = getAdjustedAllocaPtr(IRB, NewBeginOffset,
2188 V->getType()->getPointerTo());
2189 NewSI = IRB.CreateAlignedStore(
2190 V, NewPtr, getOffsetTypeAlign(
2191 V->getType(), NewBeginOffset - NewAllocaBeginOffset),
2192 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002193 }
2194 (void)NewSI;
2195 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002196 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002197
2198 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2199 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002200 }
2201
Chandler Carruth514f34f2012-12-17 04:07:30 +00002202 /// \brief Compute an integer value from splatting an i8 across the given
2203 /// number of bytes.
2204 ///
2205 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2206 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002207 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002208 ///
2209 /// \param V The i8 value to splat.
2210 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002211 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002212 assert(Size > 0 && "Expected a positive number of bytes.");
2213 IntegerType *VTy = cast<IntegerType>(V->getType());
2214 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2215 if (Size == 1)
2216 return V;
2217
2218 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002219 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
Chandler Carruth514f34f2012-12-17 04:07:30 +00002220 ConstantExpr::getUDiv(
2221 Constant::getAllOnesValue(SplatIntTy),
2222 ConstantExpr::getZExt(
2223 Constant::getAllOnesValue(V->getType()),
2224 SplatIntTy)),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002225 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002226 return V;
2227 }
2228
Chandler Carruthccca5042012-12-17 04:07:37 +00002229 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002230 Value *getVectorSplat(Value *V, unsigned NumElements) {
2231 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002232 DEBUG(dbgs() << " splat: " << *V << "\n");
2233 return V;
2234 }
2235
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002236 bool visitMemSetInst(MemSetInst &II) {
2237 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002238 assert(II.getRawDest() == OldPtr);
2239
2240 // If the memset has a variable size, it cannot be split, just adjust the
2241 // pointer to the new alloca.
2242 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002243 assert(!IsSplit);
2244 assert(BeginOffset >= NewAllocaBeginOffset);
2245 II.setDest(
2246 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002247 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002248 II.setAlignment(ConstantInt::get(CstTy, getOffsetAlign(BeginOffset)));
Chandler Carruth208124f2012-09-26 10:59:22 +00002249
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002250 deleteIfTriviallyDead(OldPtr);
2251 return false;
2252 }
2253
2254 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002255 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002256
2257 Type *AllocaTy = NewAI.getAllocatedType();
2258 Type *ScalarTy = AllocaTy->getScalarType();
2259
Chandler Carruthf0546402013-07-18 07:15:00 +00002260 // Compute the intersecting offset range.
2261 assert(BeginOffset < NewAllocaEndOffset);
2262 assert(EndOffset > NewAllocaBeginOffset);
2263 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2264 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002265 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00002266
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002267 // If this doesn't map cleanly onto the alloca type, and that type isn't
2268 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002269 if (!VecTy && !IntTy &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002270 (BeginOffset > NewAllocaBeginOffset ||
2271 EndOffset < NewAllocaEndOffset ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002272 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002273 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2274 DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002275 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002276 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2277 CallInst *New = IRB.CreateMemSet(
2278 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getRawDest()->getType()),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002279 II.getValue(), Size, getOffsetAlign(SliceOffset), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002280 (void)New;
2281 DEBUG(dbgs() << " to: " << *New << "\n");
2282 return false;
2283 }
2284
2285 // If we can represent this as a simple value, we have to build the actual
2286 // value to store, which requires expanding the byte present in memset to
2287 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002288 // splatting the byte to a sufficiently wide integer, splatting it across
2289 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002290 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002291
Chandler Carruthccca5042012-12-17 04:07:37 +00002292 if (VecTy) {
2293 // If this is a memset of a vectorized alloca, insert it.
2294 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002295
Chandler Carruthf0546402013-07-18 07:15:00 +00002296 unsigned BeginIndex = getIndex(NewBeginOffset);
2297 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002298 assert(EndIndex > BeginIndex && "Empty vector!");
2299 unsigned NumElements = EndIndex - BeginIndex;
2300 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2301
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002302 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002303 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2304 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002305 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002306 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002307
Chandler Carruthce4562b2012-12-17 13:41:21 +00002308 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002309 "oldload");
2310 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002311 } else if (IntTy) {
2312 // If this is a memset on an alloca where we can widen stores, insert the
2313 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002314 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002315
Chandler Carruthf0546402013-07-18 07:15:00 +00002316 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002317 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002318
2319 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2320 EndOffset != NewAllocaBeginOffset)) {
2321 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002322 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002323 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002324 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002325 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002326 } else {
2327 assert(V->getType() == IntTy &&
2328 "Wrong type for an alloca wide integer!");
2329 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002330 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002331 } else {
2332 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002333 assert(NewBeginOffset == NewAllocaBeginOffset);
2334 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002335
Chandler Carruth90a735d2013-07-19 07:21:28 +00002336 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002337 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002338 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002339
Chandler Carruth90a735d2013-07-19 07:21:28 +00002340 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002341 }
2342
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002343 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002344 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002345 (void)New;
2346 DEBUG(dbgs() << " to: " << *New << "\n");
2347 return !II.isVolatile();
2348 }
2349
2350 bool visitMemTransferInst(MemTransferInst &II) {
2351 // Rewriting of memory transfer instructions can be a bit tricky. We break
2352 // them into two categories: split intrinsics and unsplit intrinsics.
2353
2354 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002355
Chandler Carruthf0546402013-07-18 07:15:00 +00002356 // Compute the intersecting offset range.
2357 assert(BeginOffset < NewAllocaEndOffset);
2358 assert(EndOffset > NewAllocaBeginOffset);
2359 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2360 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2361
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002362 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2363 bool IsDest = II.getRawDest() == OldPtr;
2364
Chandler Carruth176ca712012-10-01 12:16:54 +00002365 // Compute the relative offset within the transfer.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002366 unsigned IntPtrWidth = DL.getPointerSizeInBits();
Chandler Carruthf0546402013-07-18 07:15:00 +00002367 APInt RelOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Chandler Carruth176ca712012-10-01 12:16:54 +00002368
2369 unsigned Align = II.getAlignment();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002370 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth176ca712012-10-01 12:16:54 +00002371 if (Align > 1)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002372 Align =
2373 MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2374 MinAlign(II.getAlignment(), getOffsetAlign(SliceOffset)));
Chandler Carruth176ca712012-10-01 12:16:54 +00002375
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002376 // For unsplit intrinsics, we simply modify the source and destination
2377 // pointers in place. This isn't just an optimization, it is a matter of
2378 // correctness. With unsplit intrinsics we may be dealing with transfers
2379 // within a single alloca before SROA ran, or with transfers that have
2380 // a variable length. We may also be dealing with memmove instead of
2381 // memcpy, and so simply updating the pointers is the necessary for us to
2382 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002383 if (!IsSplittable) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002384 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2385 if (IsDest)
Chandler Carruthf0546402013-07-18 07:15:00 +00002386 II.setDest(
2387 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002388 else
Chandler Carruthf0546402013-07-18 07:15:00 +00002389 II.setSource(getAdjustedAllocaPtr(IRB, BeginOffset,
2390 II.getRawSource()->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002391
Chandler Carruth208124f2012-09-26 10:59:22 +00002392 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth176ca712012-10-01 12:16:54 +00002393 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruth208124f2012-09-26 10:59:22 +00002394
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002395 DEBUG(dbgs() << " to: " << II << "\n");
2396 deleteIfTriviallyDead(OldOp);
2397 return false;
2398 }
2399 // For split transfer intrinsics we have an incredibly useful assurance:
2400 // the source and destination do not reside within the same alloca, and at
2401 // least one of them does not escape. This means that we can replace
2402 // memmove with memcpy, and we don't need to worry about all manner of
2403 // downsides to splitting and transforming the operations.
2404
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002405 // If this doesn't map cleanly onto the alloca type, and that type isn't
2406 // a single value type, just emit a memcpy.
2407 bool EmitMemCpy
Chandler Carruthf0546402013-07-18 07:15:00 +00002408 = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
2409 EndOffset < NewAllocaEndOffset ||
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002410 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002411
2412 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2413 // size hasn't been shrunk based on analysis of the viable range, this is
2414 // a no-op.
2415 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002416 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002417 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002418
2419 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002420 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002421 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002422 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002423 return false;
2424 }
2425 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002426 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002427
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002428 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2429 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002430 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002431 if (AllocaInst *AI
2432 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002433 Pass.Worklist.insert(AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002434
2435 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002436 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2437 : II.getRawDest()->getType();
2438
2439 // Compute the other pointer, folding as much as possible to produce
2440 // a single, simple GEP in most cases.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002441 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002442
Chandler Carruthf0546402013-07-18 07:15:00 +00002443 Value *OurPtr = getAdjustedAllocaPtr(
2444 IRB, NewBeginOffset,
2445 IsDest ? II.getRawDest()->getType() : II.getRawSource()->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002446 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002447 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002448
2449 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2450 IsDest ? OtherPtr : OurPtr,
Chandler Carruth871ba722012-09-26 10:27:46 +00002451 Size, Align, II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002452 (void)New;
2453 DEBUG(dbgs() << " to: " << *New << "\n");
2454 return false;
2455 }
2456
Chandler Carruth08e5f492012-10-03 08:26:28 +00002457 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2458 // is equivalent to 1, but that isn't true if we end up rewriting this as
2459 // a load or store.
2460 if (!Align)
2461 Align = 1;
2462
Chandler Carruthf0546402013-07-18 07:15:00 +00002463 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2464 NewEndOffset == NewAllocaEndOffset;
2465 uint64_t Size = NewEndOffset - NewBeginOffset;
2466 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2467 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002468 unsigned NumElements = EndIndex - BeginIndex;
2469 IntegerType *SubIntTy
2470 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2471
2472 Type *OtherPtrTy = NewAI.getType();
2473 if (VecTy && !IsWholeAlloca) {
2474 if (NumElements == 1)
2475 OtherPtrTy = VecTy->getElementType();
2476 else
2477 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2478
2479 OtherPtrTy = OtherPtrTy->getPointerTo();
2480 } else if (IntTy && !IsWholeAlloca) {
2481 OtherPtrTy = SubIntTy->getPointerTo();
2482 }
2483
Chandler Carruth90a735d2013-07-19 07:21:28 +00002484 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002485 Value *DstPtr = &NewAI;
2486 if (!IsDest)
2487 std::swap(SrcPtr, DstPtr);
2488
2489 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002490 if (VecTy && !IsWholeAlloca && !IsDest) {
2491 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002492 "load");
2493 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002494 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002495 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002496 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002497 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002498 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002499 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002500 } else {
Chandler Carruth871ba722012-09-26 10:27:46 +00002501 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002502 "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002503 }
2504
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002505 if (VecTy && !IsWholeAlloca && IsDest) {
2506 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002507 "oldload");
2508 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002509 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002510 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002511 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002512 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002513 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002514 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2515 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002516 }
2517
Chandler Carruth871ba722012-09-26 10:27:46 +00002518 StoreInst *Store = cast<StoreInst>(
2519 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2520 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002521 DEBUG(dbgs() << " to: " << *Store << "\n");
2522 return !II.isVolatile();
2523 }
2524
2525 bool visitIntrinsicInst(IntrinsicInst &II) {
2526 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2527 II.getIntrinsicID() == Intrinsic::lifetime_end);
2528 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002529 assert(II.getArgOperand(1) == OldPtr);
2530
Chandler Carruthf0546402013-07-18 07:15:00 +00002531 // Compute the intersecting offset range.
2532 assert(BeginOffset < NewAllocaEndOffset);
2533 assert(EndOffset > NewAllocaBeginOffset);
2534 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2535 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2536
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002537 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002538 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002539
2540 ConstantInt *Size
2541 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002542 NewEndOffset - NewBeginOffset);
2543 Value *Ptr =
2544 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getArgOperand(1)->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002545 Value *New;
2546 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2547 New = IRB.CreateLifetimeStart(Ptr, Size);
2548 else
2549 New = IRB.CreateLifetimeEnd(Ptr, Size);
2550
Edwin Vane82f80d42013-01-29 17:42:24 +00002551 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002552 DEBUG(dbgs() << " to: " << *New << "\n");
2553 return true;
2554 }
2555
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002556 bool visitPHINode(PHINode &PN) {
2557 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00002558 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2559 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002560
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002561 // We would like to compute a new pointer in only one place, but have it be
2562 // as local as possible to the PHI. To do that, we re-use the location of
2563 // the old pointer, which necessarily must be in the right position to
2564 // dominate the PHI.
Jakub Staszakcb132fa2013-07-22 22:10:43 +00002565 IRBuilderTy PtrBuilder(OldPtr);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002566 PtrBuilder.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) +
2567 ".");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002568
Chandler Carruthf0546402013-07-18 07:15:00 +00002569 Value *NewPtr =
2570 getAdjustedAllocaPtr(PtrBuilder, BeginOffset, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002571 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002572 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002573
Chandler Carruth82a57542012-10-01 10:54:05 +00002574 DEBUG(dbgs() << " to: " << PN << "\n");
2575 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002576
2577 // Check whether we can speculate this PHI node, and if so remember that
Chandler Carruth83ea1952013-07-24 09:47:28 +00002578 // fact and queue it up for another iteration after the speculation
2579 // occurs.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002580 if (isSafePHIToSpeculate(PN, &DL)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002581 Pass.SpeculatablePHIs.insert(&PN);
Chandler Carruth83ea1952013-07-24 09:47:28 +00002582 IsUsedByRewrittenSpeculatableInstructions = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002583 return true;
2584 }
2585
2586 return false; // PHIs can't be promoted on their own.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002587 }
2588
2589 bool visitSelectInst(SelectInst &SI) {
2590 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002591 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2592 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00002593 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2594 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002595
Chandler Carruthf0546402013-07-18 07:15:00 +00002596 Value *NewPtr = getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002597 // Replace the operands which were using the old pointer.
2598 if (SI.getOperand(1) == OldPtr)
2599 SI.setOperand(1, NewPtr);
2600 if (SI.getOperand(2) == OldPtr)
2601 SI.setOperand(2, NewPtr);
2602
Chandler Carruth82a57542012-10-01 10:54:05 +00002603 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002604 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002605
2606 // Check whether we can speculate this select instruction, and if so
Chandler Carruth83ea1952013-07-24 09:47:28 +00002607 // remember that fact and queue it up for another iteration after the
2608 // speculation occurs.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002609 if (isSafeSelectToSpeculate(SI, &DL)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002610 Pass.SpeculatableSelects.insert(&SI);
Chandler Carruth83ea1952013-07-24 09:47:28 +00002611 IsUsedByRewrittenSpeculatableInstructions = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002612 return true;
2613 }
2614
2615 return false; // Selects can't be promoted on their own.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002616 }
2617
2618};
2619}
2620
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002621namespace {
2622/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2623///
2624/// This pass aggressively rewrites all aggregate loads and stores on
2625/// a particular pointer (or any pointer derived from it which we can identify)
2626/// with scalar loads and stores.
2627class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2628 // Befriend the base class so it can delegate to private visit methods.
2629 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2630
Chandler Carruth90a735d2013-07-19 07:21:28 +00002631 const DataLayout &DL;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002632
2633 /// Queue of pointer uses to analyze and potentially rewrite.
2634 SmallVector<Use *, 8> Queue;
2635
2636 /// Set to prevent us from cycling with phi nodes and loops.
2637 SmallPtrSet<User *, 8> Visited;
2638
2639 /// The current pointer use being rewritten. This is used to dig up the used
2640 /// value (as opposed to the user).
2641 Use *U;
2642
2643public:
Chandler Carruth90a735d2013-07-19 07:21:28 +00002644 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002645
2646 /// Rewrite loads and stores through a pointer and all pointers derived from
2647 /// it.
2648 bool rewrite(Instruction &I) {
2649 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2650 enqueueUsers(I);
2651 bool Changed = false;
2652 while (!Queue.empty()) {
2653 U = Queue.pop_back_val();
2654 Changed |= visit(cast<Instruction>(U->getUser()));
2655 }
2656 return Changed;
2657 }
2658
2659private:
2660 /// Enqueue all the users of the given instruction for further processing.
2661 /// This uses a set to de-duplicate users.
2662 void enqueueUsers(Instruction &I) {
2663 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2664 ++UI)
2665 if (Visited.insert(*UI))
2666 Queue.push_back(&UI.getUse());
2667 }
2668
2669 // Conservative default is to not rewrite anything.
2670 bool visitInstruction(Instruction &I) { return false; }
2671
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002672 /// \brief Generic recursive split emission class.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002673 template <typename Derived>
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002674 class OpSplitter {
2675 protected:
2676 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00002677 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002678 /// The indices which to be used with insert- or extractvalue to select the
2679 /// appropriate value within the aggregate.
2680 SmallVector<unsigned, 4> Indices;
2681 /// The indices to a GEP instruction which will move Ptr to the correct slot
2682 /// within the aggregate.
2683 SmallVector<Value *, 4> GEPIndices;
2684 /// The base pointer of the original op, used as a base for GEPing the
2685 /// split operations.
2686 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002687
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002688 /// Initialize the splitter with an insertion point, Ptr and start with a
2689 /// single zero GEP index.
2690 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002691 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002692
2693 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002694 /// \brief Generic recursive split emission routine.
2695 ///
2696 /// This method recursively splits an aggregate op (load or store) into
2697 /// scalar or vector ops. It splits recursively until it hits a single value
2698 /// and emits that single value operation via the template argument.
2699 ///
2700 /// The logic of this routine relies on GEPs and insertvalue and
2701 /// extractvalue all operating with the same fundamental index list, merely
2702 /// formatted differently (GEPs need actual values).
2703 ///
2704 /// \param Ty The type being split recursively into smaller ops.
2705 /// \param Agg The aggregate value being built up or stored, depending on
2706 /// whether this is splitting a load or a store respectively.
2707 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2708 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002709 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002710
2711 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2712 unsigned OldSize = Indices.size();
2713 (void)OldSize;
2714 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2715 ++Idx) {
2716 assert(Indices.size() == OldSize && "Did not return to the old size");
2717 Indices.push_back(Idx);
2718 GEPIndices.push_back(IRB.getInt32(Idx));
2719 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2720 GEPIndices.pop_back();
2721 Indices.pop_back();
2722 }
2723 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002724 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002725
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002726 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2727 unsigned OldSize = Indices.size();
2728 (void)OldSize;
2729 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2730 ++Idx) {
2731 assert(Indices.size() == OldSize && "Did not return to the old size");
2732 Indices.push_back(Idx);
2733 GEPIndices.push_back(IRB.getInt32(Idx));
2734 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2735 GEPIndices.pop_back();
2736 Indices.pop_back();
2737 }
2738 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002739 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002740
2741 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002742 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002743 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002744
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002745 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002746 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002747 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002748
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002749 /// Emit a leaf load of a single value. This is called at the leaves of the
2750 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002751 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002752 assert(Ty->isSingleValueType());
2753 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00002754 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2755 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002756 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2757 DEBUG(dbgs() << " to: " << *Load << "\n");
2758 }
2759 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002760
2761 bool visitLoadInst(LoadInst &LI) {
2762 assert(LI.getPointerOperand() == *U);
2763 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2764 return false;
2765
2766 // We have an aggregate being loaded, split it apart.
2767 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002768 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002769 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002770 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002771 LI.replaceAllUsesWith(V);
2772 LI.eraseFromParent();
2773 return true;
2774 }
2775
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002776 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002777 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002778 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002779
2780 /// Emit a leaf store of a single value. This is called at the leaves of the
2781 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002782 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002783 assert(Ty->isSingleValueType());
2784 // Extract the single value and store it using the indices.
2785 Value *Store = IRB.CreateStore(
2786 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2787 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2788 (void)Store;
2789 DEBUG(dbgs() << " to: " << *Store << "\n");
2790 }
2791 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002792
2793 bool visitStoreInst(StoreInst &SI) {
2794 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2795 return false;
2796 Value *V = SI.getValueOperand();
2797 if (V->getType()->isSingleValueType())
2798 return false;
2799
2800 // We have an aggregate being stored, split it apart.
2801 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002802 StoreOpSplitter Splitter(&SI, *U);
2803 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002804 SI.eraseFromParent();
2805 return true;
2806 }
2807
2808 bool visitBitCastInst(BitCastInst &BC) {
2809 enqueueUsers(BC);
2810 return false;
2811 }
2812
2813 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2814 enqueueUsers(GEPI);
2815 return false;
2816 }
2817
2818 bool visitPHINode(PHINode &PN) {
2819 enqueueUsers(PN);
2820 return false;
2821 }
2822
2823 bool visitSelectInst(SelectInst &SI) {
2824 enqueueUsers(SI);
2825 return false;
2826 }
2827};
2828}
2829
Chandler Carruthba931992012-10-13 10:49:33 +00002830/// \brief Strip aggregate type wrapping.
2831///
2832/// This removes no-op aggregate types wrapping an underlying type. It will
2833/// strip as many layers of types as it can without changing either the type
2834/// size or the allocated size.
2835static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
2836 if (Ty->isSingleValueType())
2837 return Ty;
2838
2839 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2840 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
2841
2842 Type *InnerTy;
2843 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
2844 InnerTy = ArrTy->getElementType();
2845 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2846 const StructLayout *SL = DL.getStructLayout(STy);
2847 unsigned Index = SL->getElementContainingOffset(0);
2848 InnerTy = STy->getElementType(Index);
2849 } else {
2850 return Ty;
2851 }
2852
2853 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
2854 TypeSize > DL.getTypeSizeInBits(InnerTy))
2855 return Ty;
2856
2857 return stripAggregateTypeWrapping(DL, InnerTy);
2858}
2859
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002860/// \brief Try to find a partition of the aggregate type passed in for a given
2861/// offset and size.
2862///
2863/// This recurses through the aggregate type and tries to compute a subtype
2864/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00002865/// of an array, it will even compute a new array type for that sub-section,
2866/// and the same for structs.
2867///
2868/// Note that this routine is very strict and tries to find a partition of the
2869/// type which produces the *exact* right offset and size. It is not forgiving
2870/// when the size or offset cause either end of type-based partition to be off.
2871/// Also, this is a best-effort routine. It is reasonable to give up and not
2872/// return a type if necessary.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002873static Type *getTypePartition(const DataLayout &DL, Type *Ty,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002874 uint64_t Offset, uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002875 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
2876 return stripAggregateTypeWrapping(DL, Ty);
2877 if (Offset > DL.getTypeAllocSize(Ty) ||
2878 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Chandler Carruth58d05562012-10-25 04:37:07 +00002879 return 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002880
2881 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2882 // We can't partition pointers...
2883 if (SeqTy->isPointerTy())
2884 return 0;
2885
2886 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00002887 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002888 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002889 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002890 if (NumSkippedElements >= ArrTy->getNumElements())
2891 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002892 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002893 if (NumSkippedElements >= VecTy->getNumElements())
2894 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002895 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002896 Offset -= NumSkippedElements * ElementSize;
2897
2898 // First check if we need to recurse.
2899 if (Offset > 0 || Size < ElementSize) {
2900 // Bail if the partition ends in a different array element.
2901 if ((Offset + Size) > ElementSize)
2902 return 0;
2903 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002904 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002905 }
2906 assert(Offset == 0);
2907
2908 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002909 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002910 assert(Size > ElementSize);
2911 uint64_t NumElements = Size / ElementSize;
2912 if (NumElements * ElementSize != Size)
2913 return 0;
2914 return ArrayType::get(ElementTy, NumElements);
2915 }
2916
2917 StructType *STy = dyn_cast<StructType>(Ty);
2918 if (!STy)
2919 return 0;
2920
Chandler Carruth90a735d2013-07-19 07:21:28 +00002921 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00002922 if (Offset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002923 return 0;
2924 uint64_t EndOffset = Offset + Size;
2925 if (EndOffset > SL->getSizeInBytes())
2926 return 0;
2927
2928 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002929 Offset -= SL->getElementOffset(Index);
2930
2931 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002932 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002933 if (Offset >= ElementSize)
2934 return 0; // The offset points into alignment padding.
2935
2936 // See if any partition must be contained by the element.
2937 if (Offset > 0 || Size < ElementSize) {
2938 if ((Offset + Size) > ElementSize)
2939 return 0;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002940 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002941 }
2942 assert(Offset == 0);
2943
2944 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002945 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002946
2947 StructType::element_iterator EI = STy->element_begin() + Index,
2948 EE = STy->element_end();
2949 if (EndOffset < SL->getSizeInBytes()) {
2950 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
2951 if (Index == EndIndex)
2952 return 0; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00002953
2954 // Don't try to form "natural" types if the elements don't line up with the
2955 // expected size.
2956 // FIXME: We could potentially recurse down through the last element in the
2957 // sub-struct to find a natural end point.
2958 if (SL->getElementOffset(EndIndex) != EndOffset)
2959 return 0;
2960
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002961 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002962 EE = STy->element_begin() + EndIndex;
2963 }
2964
2965 // Try to build up a sub-structure.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002966 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002967 STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002968 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00002969 if (Size != SubSL->getSizeInBytes())
2970 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002971
Chandler Carruth054a40a2012-09-14 11:08:31 +00002972 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002973}
2974
2975/// \brief Rewrite an alloca partition's users.
2976///
2977/// This routine drives both of the rewriting goals of the SROA pass. It tries
2978/// to rewrite uses of an alloca partition to be conducive for SSA value
2979/// promotion. If the partition needs a new, more refined alloca, this will
2980/// build that new alloca, preserving as much type information as possible, and
2981/// rewrite the uses of the old alloca to point at the new one and have the
2982/// appropriate new offsets. It also evaluates how successful the rewrite was
2983/// at enabling promotion and if it was successful queues the alloca to be
2984/// promoted.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002985bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
2986 AllocaSlices::iterator B, AllocaSlices::iterator E,
2987 int64_t BeginOffset, int64_t EndOffset,
2988 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002989 assert(BeginOffset < EndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002990 uint64_t SliceSize = EndOffset - BeginOffset;
Chandler Carruth82a57542012-10-01 10:54:05 +00002991
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002992 // Try to compute a friendly type for this partition of the alloca. This
2993 // won't always succeed, in which case we fall back to a legal integer type
2994 // or an i8 array of an appropriate size.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002995 Type *SliceTy = 0;
Chandler Carruthf0546402013-07-18 07:15:00 +00002996 if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002997 if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
2998 SliceTy = CommonUseTy;
2999 if (!SliceTy)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003000 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003001 BeginOffset, SliceSize))
3002 SliceTy = TypePartitionTy;
3003 if ((!SliceTy || (SliceTy->isArrayTy() &&
3004 SliceTy->getArrayElementType()->isIntegerTy())) &&
3005 DL->isLegalInteger(SliceSize * 8))
3006 SliceTy = Type::getIntNTy(*C, SliceSize * 8);
3007 if (!SliceTy)
3008 SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
3009 assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
Chandler Carruthf0546402013-07-18 07:15:00 +00003010
3011 bool IsVectorPromotable = isVectorPromotionViable(
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003012 *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
Chandler Carruthf0546402013-07-18 07:15:00 +00003013
3014 bool IsIntegerPromotable =
3015 !IsVectorPromotable &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003016 isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003017
3018 // Check for the case where we're going to rewrite to a new alloca of the
3019 // exact same type as the original, and with the same access offsets. In that
3020 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003021 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003022 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003023 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003024 assert(BeginOffset == 0 &&
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003025 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003026 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003027 // FIXME: We should be able to bail at this point with "nothing changed".
3028 // FIXME: We might want to defer PHI speculation until after here.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003029 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003030 unsigned Alignment = AI.getAlignment();
3031 if (!Alignment) {
3032 // The minimum alignment which users can rely on when the explicit
3033 // alignment is omitted or zero is that required by the ABI for this
3034 // type.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003035 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003036 }
Chandler Carruthf0546402013-07-18 07:15:00 +00003037 Alignment = MinAlign(Alignment, BeginOffset);
Chandler Carruth903790e2012-09-29 10:41:21 +00003038 // If we will get at least this much alignment from the type alone, leave
3039 // the alloca's alignment unconstrained.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003040 if (Alignment <= DL->getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003041 Alignment = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003042 NewAI = new AllocaInst(SliceTy, 0, Alignment,
3043 AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003044 ++NumNewAllocas;
3045 }
3046
3047 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthf0546402013-07-18 07:15:00 +00003048 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3049 << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003050
Chandler Carruthf0546402013-07-18 07:15:00 +00003051 // Track the high watermark on several worklists that are only relevant for
3052 // promoted allocas. We will reset it to this point if the alloca is not in
3053 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003054 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruthf0546402013-07-18 07:15:00 +00003055 unsigned SPOldSize = SpeculatablePHIs.size();
3056 unsigned SSOldSize = SpeculatableSelects.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00003057 unsigned NumUses = 0;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003058
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003059 AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
3060 EndOffset, IsVectorPromotable,
3061 IsIntegerPromotable);
Chandler Carruthf0546402013-07-18 07:15:00 +00003062 bool Promotable = true;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003063 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
3064 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00003065 SUI != SUE; ++SUI) {
3066 DEBUG(dbgs() << " rewriting split ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003067 DEBUG(S.printSlice(dbgs(), *SUI, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003068 Promotable &= Rewriter.visit(*SUI);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003069 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003070 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003071 for (AllocaSlices::iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003072 DEBUG(dbgs() << " rewriting ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003073 DEBUG(S.printSlice(dbgs(), I, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003074 Promotable &= Rewriter.visit(I);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003075 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003076 }
3077
Chandler Carruth6c321c12013-07-19 10:57:36 +00003078 NumAllocaPartitionUses += NumUses;
3079 MaxUsesPerAllocaPartition =
3080 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003081
Chandler Carruth83ea1952013-07-24 09:47:28 +00003082 if (Promotable && !Rewriter.isUsedByRewrittenSpeculatableInstructions()) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003083 DEBUG(dbgs() << " and queuing for promotion\n");
3084 PromotableAllocas.push_back(NewAI);
Chandler Carruth58e25d32013-07-24 12:12:17 +00003085 } else if (NewAI != &AI ||
3086 (Promotable &&
3087 Rewriter.isUsedByRewrittenSpeculatableInstructions())) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003088 // If we can't promote the alloca, iterate on it to check for new
3089 // refinements exposed by splitting the current alloca. Don't iterate on an
3090 // alloca which didn't actually change and didn't get promoted.
Chandler Carruth58e25d32013-07-24 12:12:17 +00003091 //
3092 // Alternatively, if we could promote the alloca but have speculatable
3093 // instructions then we will speculate them after finishing our processing
3094 // of the original alloca. Mark the new one for re-visiting in the next
3095 // iteration so the speculated operations can be rewritten.
3096 //
Chandler Carruthf0546402013-07-18 07:15:00 +00003097 // FIXME: We should actually track whether the rewriter changed anything.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003098 Worklist.insert(NewAI);
3099 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003100
3101 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthf0546402013-07-18 07:15:00 +00003102 if (!Promotable) {
Chandler Carruthac8317f2012-10-04 12:33:50 +00003103 while (PostPromotionWorklist.size() > PPWOldSize)
3104 PostPromotionWorklist.pop_back();
Chandler Carruthf0546402013-07-18 07:15:00 +00003105 while (SpeculatablePHIs.size() > SPOldSize)
3106 SpeculatablePHIs.pop_back();
3107 while (SpeculatableSelects.size() > SSOldSize)
3108 SpeculatableSelects.pop_back();
3109 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003110
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003111 return true;
3112}
3113
Chandler Carruthf0546402013-07-18 07:15:00 +00003114namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003115struct IsSliceEndLessOrEqualTo {
3116 uint64_t UpperBound;
Chandler Carruthf0546402013-07-18 07:15:00 +00003117
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003118 IsSliceEndLessOrEqualTo(uint64_t UpperBound) : UpperBound(UpperBound) {}
Chandler Carruthf0546402013-07-18 07:15:00 +00003119
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003120 bool operator()(const AllocaSlices::iterator &I) {
3121 return I->endOffset() <= UpperBound;
3122 }
3123};
Chandler Carruthf0546402013-07-18 07:15:00 +00003124}
3125
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003126static void
3127removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3128 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003129 if (Offset >= MaxSplitUseEndOffset) {
3130 SplitUses.clear();
3131 MaxSplitUseEndOffset = 0;
3132 return;
3133 }
3134
3135 size_t SplitUsesOldSize = SplitUses.size();
3136 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003137 IsSliceEndLessOrEqualTo(Offset)),
Chandler Carruthf0546402013-07-18 07:15:00 +00003138 SplitUses.end());
3139 if (SplitUsesOldSize == SplitUses.size())
3140 return;
3141
3142 // Recompute the max. While this is linear, so is remove_if.
3143 MaxSplitUseEndOffset = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003144 for (SmallVectorImpl<AllocaSlices::iterator>::iterator
Chandler Carruthf0546402013-07-18 07:15:00 +00003145 SUI = SplitUses.begin(),
3146 SUE = SplitUses.end();
3147 SUI != SUE; ++SUI)
3148 MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
3149}
3150
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003151/// \brief Walks the slices of an alloca and form partitions based on them,
3152/// rewriting each of their uses.
3153bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
3154 if (S.begin() == S.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00003155 return false;
3156
Chandler Carruth6c321c12013-07-19 10:57:36 +00003157 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003158 bool Changed = false;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003159 SmallVector<AllocaSlices::iterator, 4> SplitUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003160 uint64_t MaxSplitUseEndOffset = 0;
3161
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003162 uint64_t BeginOffset = S.begin()->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003163
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003164 for (AllocaSlices::iterator SI = S.begin(), SJ = llvm::next(SI), SE = S.end();
3165 SI != SE; SI = SJ) {
3166 uint64_t MaxEndOffset = SI->endOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003167
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003168 if (!SI->isSplittable()) {
3169 // When we're forming an unsplittable region, it must always start at the
3170 // first slice and will extend through its end.
3171 assert(BeginOffset == SI->beginOffset());
Chandler Carruthf0546402013-07-18 07:15:00 +00003172
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003173 // Form a partition including all of the overlapping slices with this
3174 // unsplittable slice.
3175 while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3176 if (!SJ->isSplittable())
3177 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3178 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003179 }
3180 } else {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003181 assert(SI->isSplittable()); // Established above.
Chandler Carruthf0546402013-07-18 07:15:00 +00003182
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003183 // Collect all of the overlapping splittable slices.
3184 while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3185 SJ->isSplittable()) {
3186 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3187 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003188 }
3189
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003190 // Back up MaxEndOffset and SJ if we ended the span early when
3191 // encountering an unsplittable slice.
3192 if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3193 assert(!SJ->isSplittable());
3194 MaxEndOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003195 }
3196 }
3197
3198 // Check if we have managed to move the end offset forward yet. If so,
3199 // we'll have to rewrite uses and erase old split uses.
3200 if (BeginOffset < MaxEndOffset) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003201 // Rewrite a sequence of overlapping slices.
3202 Changed |=
3203 rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003204 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00003205
3206 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3207 }
3208
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003209 // Accumulate all the splittable slices from the [SI,SJ) region which
Chandler Carruthf0546402013-07-18 07:15:00 +00003210 // overlap going forward.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003211 for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3212 if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3213 SplitUses.push_back(SK);
3214 MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
Chandler Carruthf0546402013-07-18 07:15:00 +00003215 }
3216
3217 // If we're already at the end and we have no split uses, we're done.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003218 if (SJ == SE && SplitUses.empty())
Chandler Carruthf0546402013-07-18 07:15:00 +00003219 break;
3220
3221 // If we have no split uses or no gap in offsets, we're ready to move to
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003222 // the next slice.
3223 if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3224 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003225 continue;
3226 }
3227
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003228 // Even if we have split slices, if the next slice is splittable and the
3229 // split slices reach it, we can simply set up the beginning offset of the
3230 // next iteration to bridge between them.
3231 if (SJ != SE && SJ->isSplittable() &&
3232 MaxSplitUseEndOffset > SJ->beginOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003233 BeginOffset = MaxEndOffset;
3234 continue;
3235 }
3236
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003237 // Otherwise, we have a tail of split slices. Rewrite them with an empty
3238 // range of slices.
Chandler Carruthf0546402013-07-18 07:15:00 +00003239 uint64_t PostSplitEndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003240 SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003241
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003242 Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
3243 SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003244 ++NumPartitions;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003245
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003246 if (SJ == SE)
Chandler Carruthf0546402013-07-18 07:15:00 +00003247 break; // Skip the rest, we don't need to do any cleanup.
3248
3249 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3250 PostSplitEndOffset);
3251
3252 // Now just reset the begin offset for the next iteration.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003253 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003254 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003255
Chandler Carruth6c321c12013-07-19 10:57:36 +00003256 NumAllocaPartitions += NumPartitions;
3257 MaxPartitionsPerAlloca =
3258 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003259
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003260 return Changed;
3261}
3262
3263/// \brief Analyze an alloca for SROA.
3264///
3265/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003266/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003267/// rewritten as needed.
3268bool SROA::runOnAlloca(AllocaInst &AI) {
3269 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3270 ++NumAllocasAnalyzed;
3271
3272 // Special case dead allocas, as they're trivial.
3273 if (AI.use_empty()) {
3274 AI.eraseFromParent();
3275 return true;
3276 }
3277
3278 // Skip alloca forms that this analysis can't handle.
3279 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00003280 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003281 return false;
3282
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003283 bool Changed = false;
3284
3285 // First, split any FCA loads and stores touching this alloca to promote
3286 // better splitting and promotion opportunities.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003287 AggLoadStoreRewriter AggRewriter(*DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003288 Changed |= AggRewriter.rewrite(AI);
3289
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003290 // Build the slices using a recursive instruction-visiting builder.
3291 AllocaSlices S(*DL, AI);
3292 DEBUG(S.print(dbgs()));
3293 if (S.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003294 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003295
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003296 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003297 for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
3298 DE = S.dead_user_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003299 DI != DE; ++DI) {
3300 Changed = true;
3301 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
Chandler Carruth18db7952012-11-20 01:12:50 +00003302 DeadInsts.insert(*DI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003303 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003304 for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
3305 DE = S.dead_op_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003306 DO != DE; ++DO) {
3307 Value *OldV = **DO;
3308 // Clobber the use with an undef value.
3309 **DO = UndefValue::get(OldV->getType());
3310 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3311 if (isInstructionTriviallyDead(OldI)) {
3312 Changed = true;
Chandler Carruth18db7952012-11-20 01:12:50 +00003313 DeadInsts.insert(OldI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003314 }
3315 }
3316
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003317 // No slices to split. Leave the dead alloca for a later pass to clean up.
3318 if (S.begin() == S.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003319 return Changed;
3320
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003321 Changed |= splitAlloca(AI, S);
Chandler Carruthf0546402013-07-18 07:15:00 +00003322
3323 DEBUG(dbgs() << " Speculating PHIs\n");
3324 while (!SpeculatablePHIs.empty())
3325 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3326
3327 DEBUG(dbgs() << " Speculating Selects\n");
3328 while (!SpeculatableSelects.empty())
3329 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3330
3331 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003332}
3333
Chandler Carruth19450da2012-09-14 10:26:38 +00003334/// \brief Delete the dead instructions accumulated in this run.
3335///
3336/// Recursively deletes the dead instructions we've accumulated. This is done
3337/// at the very end to maximize locality of the recursive delete and to
3338/// minimize the problems of invalidated instruction pointers as such pointers
3339/// are used heavily in the intermediate stages of the algorithm.
3340///
3341/// We also record the alloca instructions deleted here so that they aren't
3342/// subsequently handed to mem2reg to promote.
3343void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003344 while (!DeadInsts.empty()) {
3345 Instruction *I = DeadInsts.pop_back_val();
3346 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3347
Chandler Carruth58d05562012-10-25 04:37:07 +00003348 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3349
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003350 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3351 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3352 // Zero out the operand and see if it becomes trivially dead.
3353 *OI = 0;
3354 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003355 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003356 }
3357
3358 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3359 DeletedAllocas.insert(AI);
3360
3361 ++NumDeleted;
3362 I->eraseFromParent();
3363 }
3364}
3365
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003366static void enqueueUsersInWorklist(Instruction &I,
3367 SmallVectorImpl<Use *> &UseWorklist,
3368 SmallPtrSet<Use *, 8> &VisitedUses) {
3369 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3370 ++UI)
3371 if (VisitedUses.insert(&UI.getUse()))
3372 UseWorklist.push_back(&UI.getUse());
3373}
3374
Chandler Carruth70b44c52012-09-15 11:43:14 +00003375/// \brief Promote the allocas, using the best available technique.
3376///
3377/// This attempts to promote whatever allocas have been identified as viable in
3378/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3379/// If there is a domtree available, we attempt to promote using the full power
3380/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3381/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003382/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003383bool SROA::promoteAllocas(Function &F) {
3384 if (PromotableAllocas.empty())
3385 return false;
3386
3387 NumPromoted += PromotableAllocas.size();
3388
3389 if (DT && !ForceSSAUpdater) {
3390 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Chandler Carruthd5b806a2013-07-28 06:43:11 +00003391 PromoteMemToReg(PromotableAllocas, *DT, DL);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003392 PromotableAllocas.clear();
3393 return true;
3394 }
3395
3396 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3397 SSAUpdater SSA;
3398 DIBuilder DIB(*F.getParent());
3399 SmallVector<Instruction*, 64> Insts;
3400
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003401 // We need a worklist to walk the uses of each alloca.
3402 SmallVector<Use *, 8> UseWorklist;
3403 SmallPtrSet<Use *, 8> VisitedUses;
3404 SmallVector<Instruction *, 32> DeadInsts;
3405
Chandler Carruth70b44c52012-09-15 11:43:14 +00003406 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3407 AllocaInst *AI = PromotableAllocas[Idx];
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003408 UseWorklist.clear();
3409 VisitedUses.clear();
3410
3411 enqueueUsersInWorklist(*AI, UseWorklist, VisitedUses);
3412
3413 while (!UseWorklist.empty()) {
3414 Use *U = UseWorklist.pop_back_val();
3415 Instruction &I = *cast<Instruction>(U->getUser());
3416
Chandler Carruth70b44c52012-09-15 11:43:14 +00003417 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3418 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3419 // leading to them) here. Eventually it should use them to optimize the
3420 // scalar values produced.
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003421 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003422 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3423 II->getIntrinsicID() == Intrinsic::lifetime_end);
3424 II->eraseFromParent();
3425 continue;
3426 }
3427
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003428 // Push the loads and stores we find onto the list. SROA will already
3429 // have validated that all loads and stores are viable candidates for
3430 // promotion.
3431 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3432 assert(LI->getType() == AI->getAllocatedType());
3433 Insts.push_back(LI);
3434 continue;
3435 }
3436 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3437 assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
3438 Insts.push_back(SI);
3439 continue;
3440 }
3441
3442 // For everything else, we know that only no-op bitcasts and GEPs will
3443 // make it this far, just recurse through them and recall them for later
3444 // removal.
3445 DeadInsts.push_back(&I);
3446 enqueueUsersInWorklist(I, UseWorklist, VisitedUses);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003447 }
3448 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3449 Insts.clear();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003450 while (!DeadInsts.empty())
3451 DeadInsts.pop_back_val()->eraseFromParent();
3452 AI->eraseFromParent();
Chandler Carruth70b44c52012-09-15 11:43:14 +00003453 }
3454
3455 PromotableAllocas.clear();
3456 return true;
3457}
3458
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003459namespace {
3460 /// \brief A predicate to test whether an alloca belongs to a set.
3461 class IsAllocaInSet {
3462 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3463 const SetType &Set;
3464
3465 public:
Chandler Carruth3f57b822012-10-03 00:03:00 +00003466 typedef AllocaInst *argument_type;
3467
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003468 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth3f57b822012-10-03 00:03:00 +00003469 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003470 };
3471}
3472
3473bool SROA::runOnFunction(Function &F) {
3474 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3475 C = &F.getContext();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003476 DL = getAnalysisIfAvailable<DataLayout>();
3477 if (!DL) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003478 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3479 return false;
3480 }
Chandler Carruth70b44c52012-09-15 11:43:14 +00003481 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003482
3483 BasicBlock &EntryBB = F.getEntryBlock();
3484 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3485 I != E; ++I)
3486 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3487 Worklist.insert(AI);
3488
3489 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003490 // A set of deleted alloca instruction pointers which should be removed from
3491 // the list of promotable allocas.
3492 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3493
Chandler Carruthac8317f2012-10-04 12:33:50 +00003494 do {
3495 while (!Worklist.empty()) {
3496 Changed |= runOnAlloca(*Worklist.pop_back_val());
3497 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003498
Chandler Carruthac8317f2012-10-04 12:33:50 +00003499 // Remove the deleted allocas from various lists so that we don't try to
3500 // continue processing them.
3501 if (!DeletedAllocas.empty()) {
3502 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3503 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3504 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3505 PromotableAllocas.end(),
3506 IsAllocaInSet(DeletedAllocas)),
3507 PromotableAllocas.end());
3508 DeletedAllocas.clear();
3509 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003510 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003511
Chandler Carruthac8317f2012-10-04 12:33:50 +00003512 Changed |= promoteAllocas(F);
3513
3514 Worklist = PostPromotionWorklist;
3515 PostPromotionWorklist.clear();
3516 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003517
3518 return Changed;
3519}
3520
3521void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003522 if (RequiresDomTree)
3523 AU.addRequired<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003524 AU.setPreservesCFG();
3525}