blob: 9f3fc83d129dfc8b8638523eb986d9aff4afc399 [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
Nick Lewyckyc7776f72013-08-13 22:51:58 +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;
Nick Lewyckyc7776f72013-08-13 22:51:58 +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:
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000328 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &S)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000329 : PtrUseVisitor<SliceBuilder>(DL),
Nick Lewyckyc7776f72013-08-13 22:51:58 +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)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +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);
Nick Lewyckyc7776f72013-08-13 22:51:58 +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)
Nick Lewyckyc7776f72013-08-13 22:51:58 +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:
Chandler Carruth45b136f2013-08-11 01:03:18 +0000736 AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
Chandler Carruth70b44c52012-09-15 11:43:14 +0000737 AllocaInst &AI, DIBuilder &DIB)
Chandler Carruth45b136f2013-08-11 01:03:18 +0000738 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
Chandler Carruth70b44c52012-09-15 11:43:14 +0000739
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 {
Chandler Carruthc17283b2013-08-11 01:56:15 +0000765 Value *Ptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000766 if (LoadInst *LI = dyn_cast<LoadInst>(I))
Chandler Carruthc17283b2013-08-11 01:56:15 +0000767 Ptr = LI->getOperand(0);
768 else
769 Ptr = cast<StoreInst>(I)->getPointerOperand();
770
771 // Only used to detect cycles, which will be rare and quickly found as
772 // we're walking up a chain of defs rather than down through uses.
773 SmallPtrSet<Value *, 4> Visited;
774
775 do {
776 if (Ptr == &AI)
777 return true;
778
779 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
780 Ptr = BCI->getOperand(0);
781 else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
782 Ptr = GEPI->getPointerOperand();
783 else
784 return false;
785
786 } while (Visited.insert(Ptr));
787
788 return false;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000789 }
790
791 virtual void updateDebugInfo(Instruction *Inst) const {
Craig Topper31ee5862013-07-03 15:07:05 +0000792 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000793 E = DDIs.end(); I != E; ++I) {
794 DbgDeclareInst *DDI = *I;
795 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
796 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
797 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
798 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
799 }
Craig Topper31ee5862013-07-03 15:07:05 +0000800 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000801 E = DVIs.end(); I != E; ++I) {
802 DbgValueInst *DVI = *I;
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000803 Value *Arg = 0;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000804 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
805 // If an argument is zero extended then use argument directly. The ZExt
806 // may be zapped by an optimization pass in future.
807 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
808 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000809 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000810 Arg = dyn_cast<Argument>(SExt->getOperand(0));
811 if (!Arg)
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000812 Arg = SI->getValueOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000813 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000814 Arg = LI->getPointerOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000815 } else {
816 continue;
817 }
818 Instruction *DbgVal =
819 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
820 Inst);
821 DbgVal->setDebugLoc(DVI->getDebugLoc());
822 }
823 }
824};
825} // end anon namespace
826
827
828namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000829/// \brief An optimization pass providing Scalar Replacement of Aggregates.
830///
831/// This pass takes allocations which can be completely analyzed (that is, they
832/// don't escape) and tries to turn them into scalar SSA values. There are
833/// a few steps to this process.
834///
835/// 1) It takes allocations of aggregates and analyzes the ways in which they
836/// are used to try to split them into smaller allocations, ideally of
837/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000838/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000839/// 2) It will transform accesses into forms which are suitable for SSA value
840/// promotion. This can be replacing a memset with a scalar store of an
841/// integer value, or it can involve speculating operations on a PHI or
842/// select to be a PHI or select of the results.
843/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
844/// onto insert and extract operations on a vector value, and convert them to
845/// this form. By doing so, it will enable promotion of vector aggregates to
846/// SSA vector values.
847class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000848 const bool RequiresDomTree;
849
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000850 LLVMContext *C;
Chandler Carruth90a735d2013-07-19 07:21:28 +0000851 const DataLayout *DL;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000852 DominatorTree *DT;
853
854 /// \brief Worklist of alloca instructions to simplify.
855 ///
856 /// Each alloca in the function is added to this. Each new alloca formed gets
857 /// added to it as well to recursively simplify unless that alloca can be
858 /// directly promoted. Finally, each time we rewrite a use of an alloca other
859 /// the one being actively rewritten, we add it back onto the list if not
860 /// already present to ensure it is re-visited.
861 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
862
863 /// \brief A collection of instructions to delete.
864 /// We try to batch deletions to simplify code and make things a bit more
865 /// efficient.
Chandler Carruth18db7952012-11-20 01:12:50 +0000866 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000867
Chandler Carruthac8317f2012-10-04 12:33:50 +0000868 /// \brief Post-promotion worklist.
869 ///
870 /// Sometimes we discover an alloca which has a high probability of becoming
871 /// viable for SROA after a round of promotion takes place. In those cases,
872 /// the alloca is enqueued here for re-processing.
873 ///
874 /// Note that we have to be very careful to clear allocas out of this list in
875 /// the event they are deleted.
876 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
877
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000878 /// \brief A collection of alloca instructions we can directly promote.
879 std::vector<AllocaInst *> PromotableAllocas;
880
Chandler Carruthf0546402013-07-18 07:15:00 +0000881 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
882 ///
883 /// All of these PHIs have been checked for the safety of speculation and by
884 /// being speculated will allow promoting allocas currently in the promotable
885 /// queue.
886 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
887
888 /// \brief A worklist of select instructions to speculate prior to promoting
889 /// allocas.
890 ///
891 /// All of these select instructions have been checked for the safety of
892 /// speculation and by being speculated will allow promoting allocas
893 /// currently in the promotable queue.
894 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
895
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000896public:
Chandler Carruth70b44c52012-09-15 11:43:14 +0000897 SROA(bool RequiresDomTree = true)
898 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
Chandler Carruth90a735d2013-07-19 07:21:28 +0000899 C(0), DL(0), DT(0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000900 initializeSROAPass(*PassRegistry::getPassRegistry());
901 }
902 bool runOnFunction(Function &F);
903 void getAnalysisUsage(AnalysisUsage &AU) const;
904
905 const char *getPassName() const { return "SROA"; }
906 static char ID;
907
908private:
Chandler Carruth82a57542012-10-01 10:54:05 +0000909 friend class PHIOrSelectSpeculator;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000910 friend class AllocaSliceRewriter;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000911
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000912 bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
913 AllocaSlices::iterator B, AllocaSlices::iterator E,
914 int64_t BeginOffset, int64_t EndOffset,
915 ArrayRef<AllocaSlices::iterator> SplitUses);
916 bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000917 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth19450da2012-09-14 10:26:38 +0000918 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +0000919 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000920};
921}
922
923char SROA::ID = 0;
924
Chandler Carruth70b44c52012-09-15 11:43:14 +0000925FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
926 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000927}
928
929INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
930 false, false)
931INITIALIZE_PASS_DEPENDENCY(DominatorTree)
932INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
933 false, false)
934
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000935/// Walk the range of a partitioning looking for a common type to cover this
936/// sequence of slices.
937static Type *findCommonType(AllocaSlices::const_iterator B,
938 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +0000939 uint64_t EndOffset) {
940 Type *Ty = 0;
Chandler Carrutha1262002013-11-19 09:03:18 +0000941 bool IgnoreNonIntegralTypes = false;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000942 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000943 Use *U = I->getUse();
944 if (isa<IntrinsicInst>(*U->getUser()))
945 continue;
946 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
947 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000948
Chandler Carruthf0546402013-07-18 07:15:00 +0000949 Type *UserTy = 0;
Chandler Carrutha1262002013-11-19 09:03:18 +0000950 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000951 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +0000952 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000953 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +0000954 } else {
955 IgnoreNonIntegralTypes = true; // Give up on anything but an iN type.
956 continue;
957 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000958
Chandler Carruthf0546402013-07-18 07:15:00 +0000959 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
960 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000961 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +0000962 // entity causing the split. Also skip if the type is not a byte width
963 // multiple.
964 if (ITy->getBitWidth() % 8 != 0 ||
965 ITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +0000966 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000967
Chandler Carruthf0546402013-07-18 07:15:00 +0000968 // If we have found an integer type use covering the alloca, use that
Chandler Carrutha1262002013-11-19 09:03:18 +0000969 // regardless of the other types, as integers are often used for
970 // a "bucket of bits" type.
971 //
972 // NB: This *must* be the only return from inside the loop so that the
973 // order of slices doesn't impact the computed type.
Chandler Carruthf0546402013-07-18 07:15:00 +0000974 return ITy;
Chandler Carrutha1262002013-11-19 09:03:18 +0000975 } else if (IgnoreNonIntegralTypes) {
976 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +0000977 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000978
979 if (Ty && Ty != UserTy)
Chandler Carrutha1262002013-11-19 09:03:18 +0000980 IgnoreNonIntegralTypes = true; // Give up on anything but an iN type.
Chandler Carruthf0546402013-07-18 07:15:00 +0000981
982 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +0000983 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000984 return Ty;
985}
Chandler Carruthe3899f22013-07-15 17:36:21 +0000986
Chandler Carruthf0546402013-07-18 07:15:00 +0000987/// PHI instructions that use an alloca and are subsequently loaded can be
988/// rewritten to load both input pointers in the pred blocks and then PHI the
989/// results, allowing the load of the alloca to be promoted.
990/// From this:
991/// %P2 = phi [i32* %Alloca, i32* %Other]
992/// %V = load i32* %P2
993/// to:
994/// %V1 = load i32* %Alloca -> will be mem2reg'd
995/// ...
996/// %V2 = load i32* %Other
997/// ...
998/// %V = phi [i32 %V1, i32 %V2]
999///
1000/// We can do this to a select if its only uses are loads and if the operands
1001/// to the select can be loaded unconditionally.
1002///
1003/// FIXME: This should be hoisted into a generic utility, likely in
1004/// Transforms/Util/Local.h
1005static bool isSafePHIToSpeculate(PHINode &PN,
Chandler Carruth90a735d2013-07-19 07:21:28 +00001006 const DataLayout *DL = 0) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001007 // For now, we can only do this promotion if the load is in the same block
1008 // as the PHI, and if there are no stores between the phi and load.
1009 // TODO: Allow recursive phi users.
1010 // TODO: Allow stores.
1011 BasicBlock *BB = PN.getParent();
1012 unsigned MaxAlign = 0;
1013 bool HaveLoad = false;
1014 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end(); UI != UE;
1015 ++UI) {
1016 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1017 if (LI == 0 || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001018 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001019
Chandler Carruthf0546402013-07-18 07:15:00 +00001020 // For now we only allow loads in the same block as the PHI. This is
1021 // a common case that happens when instcombine merges two loads through
1022 // a PHI.
1023 if (LI->getParent() != BB)
1024 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001025
Chandler Carruthf0546402013-07-18 07:15:00 +00001026 // Ensure that there are no instructions between the PHI and the load that
1027 // could store.
1028 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1029 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001030 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001031
Chandler Carruthf0546402013-07-18 07:15:00 +00001032 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1033 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001034 }
1035
Chandler Carruthf0546402013-07-18 07:15:00 +00001036 if (!HaveLoad)
1037 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001038
Chandler Carruthf0546402013-07-18 07:15:00 +00001039 // We can only transform this if it is safe to push the loads into the
1040 // predecessor blocks. The only thing to watch out for is that we can't put
1041 // a possibly trapping load in the predecessor if it is a critical edge.
1042 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1043 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1044 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001045
Chandler Carruthf0546402013-07-18 07:15:00 +00001046 // If the value is produced by the terminator of the predecessor (an
1047 // invoke) or it has side-effects, there is no valid place to put a load
1048 // in the predecessor.
1049 if (TI == InVal || TI->mayHaveSideEffects())
1050 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001051
Chandler Carruthf0546402013-07-18 07:15:00 +00001052 // If the predecessor has a single successor, then the edge isn't
1053 // critical.
1054 if (TI->getNumSuccessors() == 1)
1055 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001056
Chandler Carruthf0546402013-07-18 07:15:00 +00001057 // If this pointer is always safe to load, or if we can prove that there
1058 // is already a load in the block, then we can move the load to the pred
1059 // block.
1060 if (InVal->isDereferenceablePointer() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001061 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001062 continue;
1063
1064 return false;
1065 }
1066
1067 return true;
1068}
1069
1070static void speculatePHINodeLoads(PHINode &PN) {
1071 DEBUG(dbgs() << " original: " << PN << "\n");
1072
1073 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1074 IRBuilderTy PHIBuilder(&PN);
1075 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1076 PN.getName() + ".sroa.speculated");
1077
1078 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1079 // matter which one we get and if any differ.
1080 LoadInst *SomeLoad = cast<LoadInst>(*PN.use_begin());
1081 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1082 unsigned Align = SomeLoad->getAlignment();
1083
1084 // Rewrite all loads of the PN to use the new PHI.
1085 while (!PN.use_empty()) {
1086 LoadInst *LI = cast<LoadInst>(*PN.use_begin());
1087 LI->replaceAllUsesWith(NewPN);
1088 LI->eraseFromParent();
1089 }
1090
1091 // Inject loads into all of the pred blocks.
1092 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1093 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1094 TerminatorInst *TI = Pred->getTerminator();
1095 Value *InVal = PN.getIncomingValue(Idx);
1096 IRBuilderTy PredBuilder(TI);
1097
1098 LoadInst *Load = PredBuilder.CreateLoad(
1099 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1100 ++NumLoadsSpeculated;
1101 Load->setAlignment(Align);
1102 if (TBAATag)
1103 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1104 NewPN->addIncoming(Load, Pred);
1105 }
1106
1107 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1108 PN.eraseFromParent();
1109}
1110
1111/// Select instructions that use an alloca and are subsequently loaded can be
1112/// rewritten to load both input pointers and then select between the result,
1113/// allowing the load of the alloca to be promoted.
1114/// From this:
1115/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1116/// %V = load i32* %P2
1117/// to:
1118/// %V1 = load i32* %Alloca -> will be mem2reg'd
1119/// %V2 = load i32* %Other
1120/// %V = select i1 %cond, i32 %V1, i32 %V2
1121///
1122/// We can do this to a select if its only uses are loads and if the operand
1123/// to the select can be loaded unconditionally.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001124static bool isSafeSelectToSpeculate(SelectInst &SI, const DataLayout *DL = 0) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001125 Value *TValue = SI.getTrueValue();
1126 Value *FValue = SI.getFalseValue();
1127 bool TDerefable = TValue->isDereferenceablePointer();
1128 bool FDerefable = FValue->isDereferenceablePointer();
1129
1130 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end(); UI != UE;
1131 ++UI) {
1132 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1133 if (LI == 0 || !LI->isSimple())
1134 return false;
1135
1136 // Both operands to the select need to be dereferencable, either
1137 // absolutely (e.g. allocas) or at this point because we can see other
1138 // accesses to it.
1139 if (!TDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001140 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001141 return false;
1142 if (!FDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001143 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001144 return false;
1145 }
1146
1147 return true;
1148}
1149
1150static void speculateSelectInstLoads(SelectInst &SI) {
1151 DEBUG(dbgs() << " original: " << SI << "\n");
1152
1153 IRBuilderTy IRB(&SI);
1154 Value *TV = SI.getTrueValue();
1155 Value *FV = SI.getFalseValue();
1156 // Replace the loads of the select with a select of two loads.
1157 while (!SI.use_empty()) {
1158 LoadInst *LI = cast<LoadInst>(*SI.use_begin());
1159 assert(LI->isSimple() && "We only speculate simple loads");
1160
1161 IRB.SetInsertPoint(LI);
1162 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001163 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001164 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001165 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001166 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001167
Chandler Carruthf0546402013-07-18 07:15:00 +00001168 // Transfer alignment and TBAA info if present.
1169 TL->setAlignment(LI->getAlignment());
1170 FL->setAlignment(LI->getAlignment());
1171 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1172 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1173 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001174 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001175
1176 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1177 LI->getName() + ".sroa.speculated");
1178
1179 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1180 LI->replaceAllUsesWith(V);
1181 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001182 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001183 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001184}
1185
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001186/// \brief Build a GEP out of a base pointer and indices.
1187///
1188/// This will return the BasePtr if that is valid, or build a new GEP
1189/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001190static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001191 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001192 if (Indices.empty())
1193 return BasePtr;
1194
1195 // A single zero index is a no-op, so check for this and avoid building a GEP
1196 // in that case.
1197 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1198 return BasePtr;
1199
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001200 return IRB.CreateInBoundsGEP(BasePtr, Indices, "idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001201}
1202
1203/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1204/// TargetTy without changing the offset of the pointer.
1205///
1206/// This routine assumes we've already established a properly offset GEP with
1207/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1208/// zero-indices down through type layers until we find one the same as
1209/// TargetTy. If we can't find one with the same type, we at least try to use
1210/// one with the same size. If none of that works, we just produce the GEP as
1211/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001212static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001213 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001214 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001215 if (Ty == TargetTy)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001216 return buildGEP(IRB, BasePtr, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001217
1218 // See if we can descend into a struct and locate a field with the correct
1219 // type.
1220 unsigned NumLayers = 0;
1221 Type *ElementTy = Ty;
1222 do {
1223 if (ElementTy->isPointerTy())
1224 break;
1225 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1226 ElementTy = SeqTy->getElementType();
Chandler Carruth40617f52012-10-17 07:22:16 +00001227 // Note that we use the default address space as this index is over an
1228 // array or a vector, not a pointer.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001229 Indices.push_back(IRB.getInt(APInt(DL.getPointerSizeInBits(0), 0)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001230 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001231 if (STy->element_begin() == STy->element_end())
1232 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001233 ElementTy = *STy->element_begin();
1234 Indices.push_back(IRB.getInt32(0));
1235 } else {
1236 break;
1237 }
1238 ++NumLayers;
1239 } while (ElementTy != TargetTy);
1240 if (ElementTy != TargetTy)
1241 Indices.erase(Indices.end() - NumLayers, Indices.end());
1242
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001243 return buildGEP(IRB, BasePtr, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001244}
1245
1246/// \brief Recursively compute indices for a natural GEP.
1247///
1248/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1249/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001250static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001251 Value *Ptr, Type *Ty, APInt &Offset,
1252 Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001253 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001254 if (Offset == 0)
Chandler Carruth90a735d2013-07-19 07:21:28 +00001255 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001256
1257 // We can't recurse through pointer types.
1258 if (Ty->isPointerTy())
1259 return 0;
1260
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001261 // We try to analyze GEPs over vectors here, but note that these GEPs are
1262 // extremely poorly defined currently. The long-term goal is to remove GEPing
1263 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001264 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001265 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001266 if (ElementSizeInBits % 8)
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001267 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001268 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001269 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001270 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1271 return 0;
1272 Offset -= NumSkippedElements * ElementSize;
1273 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001274 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001275 Offset, TargetTy, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001276 }
1277
1278 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1279 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001280 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001281 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001282 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1283 return 0;
1284
1285 Offset -= NumSkippedElements * ElementSize;
1286 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001287 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001288 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001289 }
1290
1291 StructType *STy = dyn_cast<StructType>(Ty);
1292 if (!STy)
1293 return 0;
1294
Chandler Carruth90a735d2013-07-19 07:21:28 +00001295 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001296 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001297 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001298 return 0;
1299 unsigned Index = SL->getElementContainingOffset(StructOffset);
1300 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1301 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001302 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001303 return 0; // The offset points into alignment padding.
1304
1305 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001306 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001307 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001308}
1309
1310/// \brief Get a natural GEP from a base pointer to a particular offset and
1311/// resulting in a particular type.
1312///
1313/// The goal is to produce a "natural" looking GEP that works with the existing
1314/// composite types to arrive at the appropriate offset and element type for
1315/// a pointer. TargetTy is the element type the returned GEP should point-to if
1316/// possible. We recurse by decreasing Offset, adding the appropriate index to
1317/// Indices, and setting Ty to the result subtype.
1318///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001319/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001320static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001321 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001322 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001323 PointerType *Ty = cast<PointerType>(Ptr->getType());
1324
1325 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1326 // an i8.
1327 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1328 return 0;
1329
1330 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001331 if (!ElementTy->isSized())
1332 return 0; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001333 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001334 if (ElementSize == 0)
1335 return 0; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001336 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001337
1338 Offset -= NumSkippedElements * ElementSize;
1339 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001340 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001341 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001342}
1343
1344/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1345/// resulting pointer has PointerTy.
1346///
1347/// This tries very hard to compute a "natural" GEP which arrives at the offset
1348/// and produces the pointer type desired. Where it cannot, it will try to use
1349/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1350/// fails, it will try to use an existing i8* and GEP to the byte offset and
1351/// bitcast to the type.
1352///
1353/// The strategy for finding the more natural GEPs is to peel off layers of the
1354/// pointer, walking back through bit casts and GEPs, searching for a base
1355/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001356/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001357/// a single GEP as possible, thus making each GEP more independent of the
1358/// surrounding code.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001359static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001360 Value *Ptr, APInt Offset, Type *PointerTy) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001361 // Even though we don't look through PHI nodes, we could be called on an
1362 // instruction in an unreachable block, which may be on a cycle.
1363 SmallPtrSet<Value *, 4> Visited;
1364 Visited.insert(Ptr);
1365 SmallVector<Value *, 4> Indices;
1366
1367 // We may end up computing an offset pointer that has the wrong type. If we
1368 // never are able to compute one directly that has the correct type, we'll
1369 // fall back to it, so keep it around here.
1370 Value *OffsetPtr = 0;
1371
1372 // Remember any i8 pointer we come across to re-use if we need to do a raw
1373 // byte offset.
1374 Value *Int8Ptr = 0;
1375 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1376
1377 Type *TargetTy = PointerTy->getPointerElementType();
1378
1379 do {
1380 // First fold any existing GEPs into the offset.
1381 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1382 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001383 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001384 break;
1385 Offset += GEPOffset;
1386 Ptr = GEP->getPointerOperand();
1387 if (!Visited.insert(Ptr))
1388 break;
1389 }
1390
1391 // See if we can perform a natural GEP here.
1392 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001393 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001394 Indices)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001395 if (P->getType() == PointerTy) {
1396 // Zap any offset pointer that we ended up computing in previous rounds.
1397 if (OffsetPtr && OffsetPtr->use_empty())
1398 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1399 I->eraseFromParent();
1400 return P;
1401 }
1402 if (!OffsetPtr) {
1403 OffsetPtr = P;
1404 }
1405 }
1406
1407 // Stash this pointer if we've found an i8*.
1408 if (Ptr->getType()->isIntegerTy(8)) {
1409 Int8Ptr = Ptr;
1410 Int8PtrOffset = Offset;
1411 }
1412
1413 // Peel off a layer of the pointer and update the offset appropriately.
1414 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1415 Ptr = cast<Operator>(Ptr)->getOperand(0);
1416 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1417 if (GA->mayBeOverridden())
1418 break;
1419 Ptr = GA->getAliasee();
1420 } else {
1421 break;
1422 }
1423 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1424 } while (Visited.insert(Ptr));
1425
1426 if (!OffsetPtr) {
1427 if (!Int8Ptr) {
1428 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001429 "raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001430 Int8PtrOffset = Offset;
1431 }
1432
1433 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1434 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001435 "raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001436 }
1437 Ptr = OffsetPtr;
1438
1439 // On the off chance we were targeting i8*, guard the bitcast here.
1440 if (Ptr->getType() != PointerTy)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001441 Ptr = IRB.CreateBitCast(Ptr, PointerTy, "cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001442
1443 return Ptr;
1444}
1445
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001446/// \brief Test whether we can convert a value from the old to the new type.
1447///
1448/// This predicate should be used to guard calls to convertValue in order to
1449/// ensure that we only try to convert viable values. The strategy is that we
1450/// will peel off single element struct and array wrappings to get to an
1451/// underlying value, and convert that value.
1452static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1453 if (OldTy == NewTy)
1454 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001455 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1456 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1457 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1458 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001459 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1460 return false;
1461 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1462 return false;
1463
Benjamin Kramer56262592013-09-22 11:24:58 +00001464 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001465 // of pointers and integers.
1466 OldTy = OldTy->getScalarType();
1467 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001468 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1469 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1470 return true;
1471 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1472 return true;
1473 return false;
1474 }
1475
1476 return true;
1477}
1478
1479/// \brief Generic routine to convert an SSA value to a value of a different
1480/// type.
1481///
1482/// This will try various different casting techniques, such as bitcasts,
1483/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1484/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001485static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001486 Type *NewTy) {
1487 Type *OldTy = V->getType();
1488 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1489
1490 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001491 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001492
1493 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1494 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001495 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1496 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001497
Benjamin Kramer90901a32013-09-21 20:36:04 +00001498 // See if we need inttoptr for this type pair. A cast involving both scalars
1499 // and vectors requires and additional bitcast.
1500 if (OldTy->getScalarType()->isIntegerTy() &&
1501 NewTy->getScalarType()->isPointerTy()) {
1502 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1503 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1504 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1505 NewTy);
1506
1507 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1508 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1509 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1510 NewTy);
1511
1512 return IRB.CreateIntToPtr(V, NewTy);
1513 }
1514
1515 // See if we need ptrtoint for this type pair. A cast involving both scalars
1516 // and vectors requires and additional bitcast.
1517 if (OldTy->getScalarType()->isPointerTy() &&
1518 NewTy->getScalarType()->isIntegerTy()) {
1519 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1520 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1521 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1522 NewTy);
1523
1524 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1525 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1526 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1527 NewTy);
1528
1529 return IRB.CreatePtrToInt(V, NewTy);
1530 }
1531
1532 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001533}
1534
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001535/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001536///
1537/// This function is called to test each entry in a partioning which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001538/// for a single slice.
1539static bool isVectorPromotionViableForSlice(
1540 const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
1541 uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
1542 AllocaSlices::const_iterator I) {
1543 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001544 uint64_t BeginOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001545 std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001546 uint64_t BeginIndex = BeginOffset / ElementSize;
1547 if (BeginIndex * ElementSize != BeginOffset ||
1548 BeginIndex >= Ty->getNumElements())
1549 return false;
1550 uint64_t EndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001551 std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001552 uint64_t EndIndex = EndOffset / ElementSize;
1553 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1554 return false;
1555
1556 assert(EndIndex > BeginIndex && "Empty vector!");
1557 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001558 Type *SliceTy =
Chandler Carruthf0546402013-07-18 07:15:00 +00001559 (NumElements == 1) ? Ty->getElementType()
1560 : VectorType::get(Ty->getElementType(), NumElements);
1561
1562 Type *SplitIntTy =
1563 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1564
1565 Use *U = I->getUse();
1566
1567 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1568 if (MI->isVolatile())
1569 return false;
1570 if (!I->isSplittable())
1571 return false; // Skip any unsplittable intrinsics.
1572 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1573 // Disable vector promotion when there are loads or stores of an FCA.
1574 return false;
1575 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1576 if (LI->isVolatile())
1577 return false;
1578 Type *LTy = LI->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001579 if (SliceBeginOffset > I->beginOffset() ||
1580 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001581 assert(LTy->isIntegerTy());
1582 LTy = SplitIntTy;
1583 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001584 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001585 return false;
1586 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1587 if (SI->isVolatile())
1588 return false;
1589 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001590 if (SliceBeginOffset > I->beginOffset() ||
1591 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001592 assert(STy->isIntegerTy());
1593 STy = SplitIntTy;
1594 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001595 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001596 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001597 } else {
1598 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001599 }
1600
1601 return true;
1602}
1603
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001604/// \brief Test whether the given alloca partitioning and range of slices can be
1605/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001606///
1607/// This is a quick test to check whether we can rewrite a particular alloca
1608/// partition (and its newly formed alloca) into a vector alloca with only
1609/// whole-vector loads and stores such that it could be promoted to a vector
1610/// SSA value. We only can ensure this for a limited set of operations, and we
1611/// don't want to do the rewrites unless we are confident that the result will
1612/// be promotable, so we have an early test here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001613static bool
1614isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
1615 uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
1616 AllocaSlices::const_iterator I,
1617 AllocaSlices::const_iterator E,
1618 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001619 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1620 if (!Ty)
1621 return false;
1622
Chandler Carruth90a735d2013-07-19 07:21:28 +00001623 uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001624
1625 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1626 // that aren't byte sized.
1627 if (ElementSize % 8)
1628 return false;
Chandler Carruth90a735d2013-07-19 07:21:28 +00001629 assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
Benjamin Kramerc003a452013-01-01 16:13:35 +00001630 "vector size not a multiple of element size?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001631 ElementSize /= 8;
1632
Chandler Carruthf0546402013-07-18 07:15:00 +00001633 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001634 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1635 SliceEndOffset, Ty, ElementSize, I))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001636 return false;
1637
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001638 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1639 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001640 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001641 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1642 SliceEndOffset, Ty, ElementSize, *SUI))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001643 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001644
1645 return true;
1646}
1647
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001648/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001649///
1650/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001651/// test below on a single slice of the alloca.
1652static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1653 Type *AllocaTy,
1654 uint64_t AllocBeginOffset,
1655 uint64_t Size, AllocaSlices &S,
1656 AllocaSlices::const_iterator I,
1657 bool &WholeAllocaOp) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001658 uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
1659 uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
1660
1661 // We can't reasonably handle cases where the load or store extends past
1662 // the end of the aloca's type and into its padding.
1663 if (RelEnd > Size)
1664 return false;
1665
1666 Use *U = I->getUse();
1667
1668 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1669 if (LI->isVolatile())
1670 return false;
1671 if (RelBegin == 0 && RelEnd == Size)
1672 WholeAllocaOp = true;
1673 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001674 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001675 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001676 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001677 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001678 // Non-integer loads need to be convertible from the alloca type so that
1679 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001680 return false;
1681 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001682 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1683 Type *ValueTy = SI->getValueOperand()->getType();
1684 if (SI->isVolatile())
1685 return false;
1686 if (RelBegin == 0 && RelEnd == Size)
1687 WholeAllocaOp = true;
1688 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001689 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001690 return false;
1691 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001692 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001693 // Non-integer stores need to be convertible to the alloca type so that
1694 // they are promotable.
1695 return false;
1696 }
1697 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1698 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1699 return false;
1700 if (!I->isSplittable())
1701 return false; // Skip any unsplittable intrinsics.
1702 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1703 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1704 II->getIntrinsicID() != Intrinsic::lifetime_end)
1705 return false;
1706 } else {
1707 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001708 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001709
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001710 return true;
1711}
1712
Chandler Carruth435c4e02012-10-15 08:40:30 +00001713/// \brief Test whether the given alloca partition's integer operations can be
1714/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00001715///
Chandler Carruth435c4e02012-10-15 08:40:30 +00001716/// This is a quick test to check whether we can rewrite the integer loads and
1717/// stores to a particular alloca into wider loads and stores and be able to
1718/// promote the resulting alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +00001719static bool
Chandler Carruth90a735d2013-07-19 07:21:28 +00001720isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001721 uint64_t AllocBeginOffset, AllocaSlices &S,
1722 AllocaSlices::const_iterator I,
1723 AllocaSlices::const_iterator E,
1724 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001725 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00001726 // Don't create integer types larger than the maximum bitwidth.
1727 if (SizeInBits > IntegerType::MAX_INT_BITS)
1728 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00001729
1730 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001731 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001732 return false;
1733
Chandler Carruth58d05562012-10-25 04:37:07 +00001734 // We need to ensure that an integer type with the appropriate bitwidth can
1735 // be converted to the alloca type, whatever that is. We don't want to force
1736 // the alloca itself to have an integer type if there is a more suitable one.
1737 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001738 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1739 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00001740 return false;
1741
Chandler Carruth90a735d2013-07-19 07:21:28 +00001742 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
Chandler Carruth435c4e02012-10-15 08:40:30 +00001743
Chandler Carruthf0546402013-07-18 07:15:00 +00001744 // While examining uses, we ensure that the alloca has a covering load or
1745 // store. We don't want to widen the integer operations only to fail to
1746 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00001747 // later). However, if there are only splittable uses, go ahead and assume
1748 // that we cover the alloca.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001749 bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00001750
Chandler Carruthf0546402013-07-18 07:15:00 +00001751 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001752 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1753 S, I, WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00001754 return false;
1755
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001756 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1757 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001758 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001759 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1760 S, *SUI, WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001761 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001762
Chandler Carruth92924fd2012-09-24 00:34:20 +00001763 return WholeAllocaOp;
1764}
1765
Chandler Carruthd177f862013-03-20 07:30:36 +00001766static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001767 IntegerType *Ty, uint64_t Offset,
1768 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00001769 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001770 IntegerType *IntTy = cast<IntegerType>(V->getType());
1771 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1772 "Element extends past full value");
1773 uint64_t ShAmt = 8*Offset;
1774 if (DL.isBigEndian())
1775 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001776 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001777 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001778 DEBUG(dbgs() << " shifted: " << *V << "\n");
1779 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001780 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1781 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001782 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001783 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00001784 DEBUG(dbgs() << " trunced: " << *V << "\n");
1785 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001786 return V;
1787}
1788
Chandler Carruthd177f862013-03-20 07:30:36 +00001789static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001790 Value *V, uint64_t Offset, const Twine &Name) {
1791 IntegerType *IntTy = cast<IntegerType>(Old->getType());
1792 IntegerType *Ty = cast<IntegerType>(V->getType());
1793 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1794 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001795 DEBUG(dbgs() << " start: " << *V << "\n");
1796 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001797 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00001798 DEBUG(dbgs() << " extended: " << *V << "\n");
1799 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001800 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1801 "Element store outside of alloca store");
1802 uint64_t ShAmt = 8*Offset;
1803 if (DL.isBigEndian())
1804 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001805 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001806 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001807 DEBUG(dbgs() << " shifted: " << *V << "\n");
1808 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001809
1810 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1811 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1812 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00001813 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001814 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00001815 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001816 }
1817 return V;
1818}
1819
Chandler Carruthd177f862013-03-20 07:30:36 +00001820static Value *extractVector(IRBuilderTy &IRB, Value *V,
Chandler Carruthb6bc8742012-12-17 13:07:30 +00001821 unsigned BeginIndex, unsigned EndIndex,
1822 const Twine &Name) {
1823 VectorType *VecTy = cast<VectorType>(V->getType());
1824 unsigned NumElements = EndIndex - BeginIndex;
1825 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1826
1827 if (NumElements == VecTy->getNumElements())
1828 return V;
1829
1830 if (NumElements == 1) {
1831 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1832 Name + ".extract");
1833 DEBUG(dbgs() << " extract: " << *V << "\n");
1834 return V;
1835 }
1836
1837 SmallVector<Constant*, 8> Mask;
1838 Mask.reserve(NumElements);
1839 for (unsigned i = BeginIndex; i != EndIndex; ++i)
1840 Mask.push_back(IRB.getInt32(i));
1841 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1842 ConstantVector::get(Mask),
1843 Name + ".extract");
1844 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1845 return V;
1846}
1847
Chandler Carruthd177f862013-03-20 07:30:36 +00001848static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00001849 unsigned BeginIndex, const Twine &Name) {
1850 VectorType *VecTy = cast<VectorType>(Old->getType());
1851 assert(VecTy && "Can only insert a vector into a vector");
1852
1853 VectorType *Ty = dyn_cast<VectorType>(V->getType());
1854 if (!Ty) {
1855 // Single element to insert.
1856 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
1857 Name + ".insert");
1858 DEBUG(dbgs() << " insert: " << *V << "\n");
1859 return V;
1860 }
1861
1862 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
1863 "Too many elements!");
1864 if (Ty->getNumElements() == VecTy->getNumElements()) {
1865 assert(V->getType() == VecTy && "Vector type mismatch");
1866 return V;
1867 }
1868 unsigned EndIndex = BeginIndex + Ty->getNumElements();
1869
1870 // When inserting a smaller vector into the larger to store, we first
1871 // use a shuffle vector to widen it with undef elements, and then
1872 // a second shuffle vector to select between the loaded vector and the
1873 // incoming vector.
1874 SmallVector<Constant*, 8> Mask;
1875 Mask.reserve(VecTy->getNumElements());
1876 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1877 if (i >= BeginIndex && i < EndIndex)
1878 Mask.push_back(IRB.getInt32(i - BeginIndex));
1879 else
1880 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
1881 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1882 ConstantVector::get(Mask),
1883 Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00001884 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001885
1886 Mask.clear();
1887 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00001888 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
1889
1890 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
1891
1892 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001893 return V;
1894}
1895
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001896namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001897/// \brief Visitor to rewrite instructions using p particular slice of an alloca
1898/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001899///
1900/// Also implements the rewriting to vector-based accesses when the partition
1901/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1902/// lives here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001903class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001904 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001905 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
1906 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001907
Chandler Carruth90a735d2013-07-19 07:21:28 +00001908 const DataLayout &DL;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001909 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001910 SROA &Pass;
1911 AllocaInst &OldAI, &NewAI;
1912 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00001913 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001914
1915 // If we are rewriting an alloca partition which can be written as pure
1916 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001917 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001918 // - The new alloca is exactly the size of the vector type here.
1919 // - The accesses all either map to the entire vector or to a single
1920 // element.
1921 // - The set of accessing instructions is only one of those handled above
1922 // in isVectorPromotionViable. Generally these are the same access kinds
1923 // which are promotable via mem2reg.
1924 VectorType *VecTy;
1925 Type *ElementTy;
1926 uint64_t ElementSize;
1927
Chandler Carruth92924fd2012-09-24 00:34:20 +00001928 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth435c4e02012-10-15 08:40:30 +00001929 // alloca's integer operations should be widened to this integer type due to
1930 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruth92924fd2012-09-24 00:34:20 +00001931 // integer type will be stored here for easy access during rewriting.
Chandler Carruth435c4e02012-10-15 08:40:30 +00001932 IntegerType *IntTy;
Chandler Carruth92924fd2012-09-24 00:34:20 +00001933
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001934 // The offset of the slice currently being rewritten.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001935 uint64_t BeginOffset, EndOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001936 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001937 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00001938 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001939 Instruction *OldPtr;
1940
Chandler Carruth83ea1952013-07-24 09:47:28 +00001941 // Output members carrying state about the result of visiting and rewriting
1942 // the slice of the alloca.
1943 bool IsUsedByRewrittenSpeculatableInstructions;
1944
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001945 // Utility IR builder, whose name prefix is setup for each visited use, and
1946 // the insertion point is set to point to the user.
1947 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001948
1949public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001950 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
1951 AllocaInst &OldAI, AllocaInst &NewAI,
1952 uint64_t NewBeginOffset, uint64_t NewEndOffset,
1953 bool IsVectorPromotable = false,
1954 bool IsIntegerPromotable = false)
1955 : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthf0546402013-07-18 07:15:00 +00001956 NewAllocaBeginOffset(NewBeginOffset), NewAllocaEndOffset(NewEndOffset),
1957 NewAllocaTy(NewAI.getAllocatedType()),
1958 VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : 0),
1959 ElementTy(VecTy ? VecTy->getElementType() : 0),
Chandler Carruth90a735d2013-07-19 07:21:28 +00001960 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00001961 IntTy(IsIntegerPromotable
1962 ? Type::getIntNTy(
1963 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00001964 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001965 : 0),
1966 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
Chandler Carruth83ea1952013-07-24 09:47:28 +00001967 OldPtr(), IsUsedByRewrittenSpeculatableInstructions(false),
1968 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001969 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001970 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00001971 "Only multiple-of-8 sized vector elements are viable");
1972 ++NumVectorized;
1973 }
1974 assert((!IsVectorPromotable && !IsIntegerPromotable) ||
1975 IsVectorPromotable != IsIntegerPromotable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001976 }
1977
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001978 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001979 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00001980 BeginOffset = I->beginOffset();
1981 EndOffset = I->endOffset();
1982 IsSplittable = I->isSplittable();
1983 IsSplit =
1984 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001985
Chandler Carruthf0546402013-07-18 07:15:00 +00001986 OldUse = I->getUse();
1987 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001988
Chandler Carruthf0546402013-07-18 07:15:00 +00001989 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
1990 IRB.SetInsertPoint(OldUserI);
1991 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
1992 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
1993
1994 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
1995 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001996 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001997 return CanSROA;
1998 }
1999
Chandler Carruth83ea1952013-07-24 09:47:28 +00002000 /// \brief Query whether this slice is used by speculatable instructions after
2001 /// rewriting.
2002 ///
2003 /// These instructions (PHIs and Selects currently) require the alloca slice
2004 /// to run back through the rewriter. Thus, they are promotable, but not on
2005 /// this iteration. This is distinct from a slice which is unpromotable for
2006 /// some other reason, in which case we don't even want to perform the
2007 /// speculation. This can be querried at any time and reflects whether (at
2008 /// that point) a visit call has rewritten a speculatable instruction on the
2009 /// current slice.
2010 bool isUsedByRewrittenSpeculatableInstructions() const {
2011 return IsUsedByRewrittenSpeculatableInstructions;
2012 }
2013
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002014private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002015 // Make sure the other visit overloads are visible.
2016 using Base::visit;
2017
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002018 // Every instruction which can end up as a user must have a rewrite rule.
2019 bool visitInstruction(Instruction &I) {
2020 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2021 llvm_unreachable("No rewrite rule for this instruction!");
2022 }
2023
Chandler Carruthf0546402013-07-18 07:15:00 +00002024 Value *getAdjustedAllocaPtr(IRBuilderTy &IRB, uint64_t Offset,
2025 Type *PointerTy) {
2026 assert(Offset >= NewAllocaBeginOffset);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002027 return getAdjustedPtr(IRB, DL, &NewAI, APInt(DL.getPointerSizeInBits(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002028 Offset - NewAllocaBeginOffset),
2029 PointerTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002030 }
2031
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002032 /// \brief Compute suitable alignment to access an offset into the new alloca.
2033 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002034 unsigned NewAIAlign = NewAI.getAlignment();
2035 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002036 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth176ca712012-10-01 12:16:54 +00002037 return MinAlign(NewAIAlign, Offset);
2038 }
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002039
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002040 /// \brief Compute suitable alignment to access a type at an offset of the
2041 /// new alloca.
2042 ///
2043 /// \returns zero if the type's ABI alignment is a suitable alignment,
2044 /// otherwise returns the maximal suitable alignment.
2045 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2046 unsigned Align = getOffsetAlign(Offset);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002047 return Align == DL.getABITypeAlignment(Ty) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002048 }
2049
Chandler Carruth845b73c2012-11-21 08:16:30 +00002050 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002051 assert(VecTy && "Can only call getIndex when rewriting a vector");
2052 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2053 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2054 uint32_t Index = RelOffset / ElementSize;
2055 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002056 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002057 }
2058
2059 void deleteIfTriviallyDead(Value *V) {
2060 Instruction *I = cast<Instruction>(V);
2061 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002062 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002063 }
2064
Chandler Carruthf0546402013-07-18 07:15:00 +00002065 Value *rewriteVectorizedLoadInst(uint64_t NewBeginOffset,
2066 uint64_t NewEndOffset) {
2067 unsigned BeginIndex = getIndex(NewBeginOffset);
2068 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002069 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002070
2071 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002072 "load");
2073 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002074 }
2075
Chandler Carruthf0546402013-07-18 07:15:00 +00002076 Value *rewriteIntegerLoad(LoadInst &LI, uint64_t NewBeginOffset,
2077 uint64_t NewEndOffset) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002078 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002079 assert(!LI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002080 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002081 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002082 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002083 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2084 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2085 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002086 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002087 "extract");
Chandler Carruth18db7952012-11-20 01:12:50 +00002088 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002089 }
2090
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002091 bool visitLoadInst(LoadInst &LI) {
2092 DEBUG(dbgs() << " original: " << LI << "\n");
2093 Value *OldOp = LI.getOperand(0);
2094 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002095
Chandler Carruthf0546402013-07-18 07:15:00 +00002096 // Compute the intersecting offset range.
2097 assert(BeginOffset < NewAllocaEndOffset);
2098 assert(EndOffset > NewAllocaBeginOffset);
2099 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2100 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2101
2102 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth3e994a22012-11-20 10:02:19 +00002103
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002104 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), Size * 8)
2105 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002106 bool IsPtrAdjusted = false;
2107 Value *V;
2108 if (VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002109 V = rewriteVectorizedLoadInst(NewBeginOffset, NewEndOffset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002110 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002111 V = rewriteIntegerLoad(LI, NewBeginOffset, NewEndOffset);
2112 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002113 canConvertValue(DL, NewAllocaTy, LI.getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002114 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002115 LI.isVolatile(), "load");
Chandler Carruth18db7952012-11-20 01:12:50 +00002116 } else {
2117 Type *LTy = TargetTy->getPointerTo();
Chandler Carruthf0546402013-07-18 07:15:00 +00002118 V = IRB.CreateAlignedLoad(
2119 getAdjustedAllocaPtr(IRB, NewBeginOffset, LTy),
2120 getOffsetTypeAlign(TargetTy, NewBeginOffset - NewAllocaBeginOffset),
2121 LI.isVolatile(), "load");
Chandler Carruth18db7952012-11-20 01:12:50 +00002122 IsPtrAdjusted = true;
2123 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002124 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002125
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002126 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002127 assert(!LI.isVolatile());
2128 assert(LI.getType()->isIntegerTy() &&
2129 "Only integer type loads and stores are split");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002130 assert(Size < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002131 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002132 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002133 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002134 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002135 // Move the insertion point just past the load so that we can refer to it.
2136 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002137 // Create a placeholder value with the same type as LI to use as the
2138 // basis for the new value. This allows us to replace the uses of LI with
2139 // the computed value, and then replace the placeholder with LI, leaving
2140 // LI only used for this computation.
2141 Value *Placeholder
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002142 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth90a735d2013-07-19 07:21:28 +00002143 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002144 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002145 LI.replaceAllUsesWith(V);
2146 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002147 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002148 } else {
2149 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002150 }
2151
Chandler Carruth18db7952012-11-20 01:12:50 +00002152 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002153 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002154 DEBUG(dbgs() << " to: " << *V << "\n");
2155 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002156 }
2157
Chandler Carruthf0546402013-07-18 07:15:00 +00002158 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2159 uint64_t NewBeginOffset,
2160 uint64_t NewEndOffset) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002161 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002162 unsigned BeginIndex = getIndex(NewBeginOffset);
2163 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002164 assert(EndIndex > BeginIndex && "Empty vector!");
2165 unsigned NumElements = EndIndex - BeginIndex;
2166 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002167 Type *SliceTy =
2168 (NumElements == 1) ? ElementTy
2169 : VectorType::get(ElementTy, NumElements);
2170 if (V->getType() != SliceTy)
2171 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002172
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002173 // Mix in the existing elements.
2174 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2175 "load");
2176 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2177 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002178 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002179 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002180
2181 (void)Store;
2182 DEBUG(dbgs() << " to: " << *Store << "\n");
2183 return true;
2184 }
2185
Chandler Carruthf0546402013-07-18 07:15:00 +00002186 bool rewriteIntegerStore(Value *V, StoreInst &SI,
2187 uint64_t NewBeginOffset, uint64_t NewEndOffset) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002188 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002189 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002190 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002191 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002192 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002193 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002194 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2195 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002196 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002197 "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002198 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002199 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002200 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002201 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002202 (void)Store;
2203 DEBUG(dbgs() << " to: " << *Store << "\n");
2204 return true;
2205 }
2206
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002207 bool visitStoreInst(StoreInst &SI) {
2208 DEBUG(dbgs() << " original: " << SI << "\n");
2209 Value *OldOp = SI.getOperand(1);
2210 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002211
Chandler Carruth18db7952012-11-20 01:12:50 +00002212 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002213
Chandler Carruthac8317f2012-10-04 12:33:50 +00002214 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2215 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002216 if (V->getType()->isPointerTy())
2217 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002218 Pass.PostPromotionWorklist.insert(AI);
2219
Chandler Carruthf0546402013-07-18 07:15:00 +00002220 // Compute the intersecting offset range.
2221 assert(BeginOffset < NewAllocaEndOffset);
2222 assert(EndOffset > NewAllocaBeginOffset);
2223 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2224 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2225
2226 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002227 if (Size < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002228 assert(!SI.isVolatile());
2229 assert(V->getType()->isIntegerTy() &&
2230 "Only integer type loads and stores are split");
2231 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002232 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002233 "Non-byte-multiple bit width");
Chandler Carruth18db7952012-11-20 01:12:50 +00002234 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002235 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002236 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002237 }
2238
Chandler Carruth18db7952012-11-20 01:12:50 +00002239 if (VecTy)
Chandler Carruthf0546402013-07-18 07:15:00 +00002240 return rewriteVectorizedStoreInst(V, SI, OldOp, NewBeginOffset,
2241 NewEndOffset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002242 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthf0546402013-07-18 07:15:00 +00002243 return rewriteIntegerStore(V, SI, NewBeginOffset, NewEndOffset);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002244
Chandler Carruth18db7952012-11-20 01:12:50 +00002245 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002246 if (NewBeginOffset == NewAllocaBeginOffset &&
2247 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002248 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2249 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002250 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2251 SI.isVolatile());
2252 } else {
Chandler Carruthf0546402013-07-18 07:15:00 +00002253 Value *NewPtr = getAdjustedAllocaPtr(IRB, NewBeginOffset,
2254 V->getType()->getPointerTo());
2255 NewSI = IRB.CreateAlignedStore(
2256 V, NewPtr, getOffsetTypeAlign(
2257 V->getType(), NewBeginOffset - NewAllocaBeginOffset),
2258 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002259 }
2260 (void)NewSI;
2261 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002262 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002263
2264 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2265 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002266 }
2267
Chandler Carruth514f34f2012-12-17 04:07:30 +00002268 /// \brief Compute an integer value from splatting an i8 across the given
2269 /// number of bytes.
2270 ///
2271 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2272 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002273 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002274 ///
2275 /// \param V The i8 value to splat.
2276 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002277 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002278 assert(Size > 0 && "Expected a positive number of bytes.");
2279 IntegerType *VTy = cast<IntegerType>(V->getType());
2280 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2281 if (Size == 1)
2282 return V;
2283
2284 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002285 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
Chandler Carruth514f34f2012-12-17 04:07:30 +00002286 ConstantExpr::getUDiv(
2287 Constant::getAllOnesValue(SplatIntTy),
2288 ConstantExpr::getZExt(
2289 Constant::getAllOnesValue(V->getType()),
2290 SplatIntTy)),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002291 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002292 return V;
2293 }
2294
Chandler Carruthccca5042012-12-17 04:07:37 +00002295 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002296 Value *getVectorSplat(Value *V, unsigned NumElements) {
2297 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002298 DEBUG(dbgs() << " splat: " << *V << "\n");
2299 return V;
2300 }
2301
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002302 bool visitMemSetInst(MemSetInst &II) {
2303 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002304 assert(II.getRawDest() == OldPtr);
2305
2306 // If the memset has a variable size, it cannot be split, just adjust the
2307 // pointer to the new alloca.
2308 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002309 assert(!IsSplit);
2310 assert(BeginOffset >= NewAllocaBeginOffset);
2311 II.setDest(
2312 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002313 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002314 II.setAlignment(ConstantInt::get(CstTy, getOffsetAlign(BeginOffset)));
Chandler Carruth208124f2012-09-26 10:59:22 +00002315
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002316 deleteIfTriviallyDead(OldPtr);
2317 return false;
2318 }
2319
2320 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002321 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002322
2323 Type *AllocaTy = NewAI.getAllocatedType();
2324 Type *ScalarTy = AllocaTy->getScalarType();
2325
Chandler Carruthf0546402013-07-18 07:15:00 +00002326 // Compute the intersecting offset range.
2327 assert(BeginOffset < NewAllocaEndOffset);
2328 assert(EndOffset > NewAllocaBeginOffset);
2329 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2330 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002331 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00002332
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002333 // If this doesn't map cleanly onto the alloca type, and that type isn't
2334 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002335 if (!VecTy && !IntTy &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002336 (BeginOffset > NewAllocaBeginOffset ||
2337 EndOffset < NewAllocaEndOffset ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002338 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002339 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2340 DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002341 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002342 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2343 CallInst *New = IRB.CreateMemSet(
2344 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getRawDest()->getType()),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002345 II.getValue(), Size, getOffsetAlign(SliceOffset), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002346 (void)New;
2347 DEBUG(dbgs() << " to: " << *New << "\n");
2348 return false;
2349 }
2350
2351 // If we can represent this as a simple value, we have to build the actual
2352 // value to store, which requires expanding the byte present in memset to
2353 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002354 // splatting the byte to a sufficiently wide integer, splatting it across
2355 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002356 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002357
Chandler Carruthccca5042012-12-17 04:07:37 +00002358 if (VecTy) {
2359 // If this is a memset of a vectorized alloca, insert it.
2360 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002361
Chandler Carruthf0546402013-07-18 07:15:00 +00002362 unsigned BeginIndex = getIndex(NewBeginOffset);
2363 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002364 assert(EndIndex > BeginIndex && "Empty vector!");
2365 unsigned NumElements = EndIndex - BeginIndex;
2366 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2367
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002368 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002369 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2370 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002371 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002372 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002373
Chandler Carruthce4562b2012-12-17 13:41:21 +00002374 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002375 "oldload");
2376 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002377 } else if (IntTy) {
2378 // If this is a memset on an alloca where we can widen stores, insert the
2379 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002380 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002381
Chandler Carruthf0546402013-07-18 07:15:00 +00002382 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002383 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002384
2385 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2386 EndOffset != NewAllocaBeginOffset)) {
2387 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002388 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002389 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002390 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002391 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002392 } else {
2393 assert(V->getType() == IntTy &&
2394 "Wrong type for an alloca wide integer!");
2395 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002396 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002397 } else {
2398 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002399 assert(NewBeginOffset == NewAllocaBeginOffset);
2400 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002401
Chandler Carruth90a735d2013-07-19 07:21:28 +00002402 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002403 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002404 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002405
Chandler Carruth90a735d2013-07-19 07:21:28 +00002406 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002407 }
2408
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002409 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002410 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002411 (void)New;
2412 DEBUG(dbgs() << " to: " << *New << "\n");
2413 return !II.isVolatile();
2414 }
2415
2416 bool visitMemTransferInst(MemTransferInst &II) {
2417 // Rewriting of memory transfer instructions can be a bit tricky. We break
2418 // them into two categories: split intrinsics and unsplit intrinsics.
2419
2420 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002421
Chandler Carruthf0546402013-07-18 07:15:00 +00002422 // Compute the intersecting offset range.
2423 assert(BeginOffset < NewAllocaEndOffset);
2424 assert(EndOffset > NewAllocaBeginOffset);
2425 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2426 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2427
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002428 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2429 bool IsDest = II.getRawDest() == OldPtr;
2430
Chandler Carruth176ca712012-10-01 12:16:54 +00002431 // Compute the relative offset within the transfer.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002432 unsigned IntPtrWidth = DL.getPointerSizeInBits();
Chandler Carruthf0546402013-07-18 07:15:00 +00002433 APInt RelOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Chandler Carruth176ca712012-10-01 12:16:54 +00002434
2435 unsigned Align = II.getAlignment();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002436 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth176ca712012-10-01 12:16:54 +00002437 if (Align > 1)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002438 Align =
2439 MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2440 MinAlign(II.getAlignment(), getOffsetAlign(SliceOffset)));
Chandler Carruth176ca712012-10-01 12:16:54 +00002441
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002442 // For unsplit intrinsics, we simply modify the source and destination
2443 // pointers in place. This isn't just an optimization, it is a matter of
2444 // correctness. With unsplit intrinsics we may be dealing with transfers
2445 // within a single alloca before SROA ran, or with transfers that have
2446 // a variable length. We may also be dealing with memmove instead of
2447 // memcpy, and so simply updating the pointers is the necessary for us to
2448 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002449 if (!IsSplittable) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002450 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2451 if (IsDest)
Chandler Carruthf0546402013-07-18 07:15:00 +00002452 II.setDest(
2453 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002454 else
Chandler Carruthf0546402013-07-18 07:15:00 +00002455 II.setSource(getAdjustedAllocaPtr(IRB, BeginOffset,
2456 II.getRawSource()->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002457
Chandler Carruth208124f2012-09-26 10:59:22 +00002458 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth176ca712012-10-01 12:16:54 +00002459 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruth208124f2012-09-26 10:59:22 +00002460
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002461 DEBUG(dbgs() << " to: " << II << "\n");
2462 deleteIfTriviallyDead(OldOp);
2463 return false;
2464 }
2465 // For split transfer intrinsics we have an incredibly useful assurance:
2466 // the source and destination do not reside within the same alloca, and at
2467 // least one of them does not escape. This means that we can replace
2468 // memmove with memcpy, and we don't need to worry about all manner of
2469 // downsides to splitting and transforming the operations.
2470
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002471 // If this doesn't map cleanly onto the alloca type, and that type isn't
2472 // a single value type, just emit a memcpy.
2473 bool EmitMemCpy
Chandler Carruthf0546402013-07-18 07:15:00 +00002474 = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
2475 EndOffset < NewAllocaEndOffset ||
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002476 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002477
2478 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2479 // size hasn't been shrunk based on analysis of the viable range, this is
2480 // a no-op.
2481 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002482 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002483 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002484
2485 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002486 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002487 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002488 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002489 return false;
2490 }
2491 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002492 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002493
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002494 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2495 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002496 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002497 if (AllocaInst *AI
2498 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002499 Pass.Worklist.insert(AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002500
2501 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002502 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2503 : II.getRawDest()->getType();
2504
2505 // Compute the other pointer, folding as much as possible to produce
2506 // a single, simple GEP in most cases.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002507 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002508
Chandler Carruthf0546402013-07-18 07:15:00 +00002509 Value *OurPtr = getAdjustedAllocaPtr(
2510 IRB, NewBeginOffset,
2511 IsDest ? II.getRawDest()->getType() : II.getRawSource()->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002512 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002513 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002514
2515 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2516 IsDest ? OtherPtr : OurPtr,
Chandler Carruth871ba722012-09-26 10:27:46 +00002517 Size, Align, II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002518 (void)New;
2519 DEBUG(dbgs() << " to: " << *New << "\n");
2520 return false;
2521 }
2522
Chandler Carruth08e5f492012-10-03 08:26:28 +00002523 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2524 // is equivalent to 1, but that isn't true if we end up rewriting this as
2525 // a load or store.
2526 if (!Align)
2527 Align = 1;
2528
Chandler Carruthf0546402013-07-18 07:15:00 +00002529 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2530 NewEndOffset == NewAllocaEndOffset;
2531 uint64_t Size = NewEndOffset - NewBeginOffset;
2532 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2533 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002534 unsigned NumElements = EndIndex - BeginIndex;
2535 IntegerType *SubIntTy
2536 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2537
2538 Type *OtherPtrTy = NewAI.getType();
2539 if (VecTy && !IsWholeAlloca) {
2540 if (NumElements == 1)
2541 OtherPtrTy = VecTy->getElementType();
2542 else
2543 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2544
2545 OtherPtrTy = OtherPtrTy->getPointerTo();
2546 } else if (IntTy && !IsWholeAlloca) {
2547 OtherPtrTy = SubIntTy->getPointerTo();
2548 }
2549
Chandler Carruth90a735d2013-07-19 07:21:28 +00002550 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002551 Value *DstPtr = &NewAI;
2552 if (!IsDest)
2553 std::swap(SrcPtr, DstPtr);
2554
2555 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002556 if (VecTy && !IsWholeAlloca && !IsDest) {
2557 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002558 "load");
2559 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002560 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002561 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002562 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002563 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002564 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002565 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002566 } else {
Chandler Carruth871ba722012-09-26 10:27:46 +00002567 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002568 "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002569 }
2570
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002571 if (VecTy && !IsWholeAlloca && IsDest) {
2572 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002573 "oldload");
2574 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002575 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002576 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002577 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002578 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002579 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002580 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2581 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002582 }
2583
Chandler Carruth871ba722012-09-26 10:27:46 +00002584 StoreInst *Store = cast<StoreInst>(
2585 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2586 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002587 DEBUG(dbgs() << " to: " << *Store << "\n");
2588 return !II.isVolatile();
2589 }
2590
2591 bool visitIntrinsicInst(IntrinsicInst &II) {
2592 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2593 II.getIntrinsicID() == Intrinsic::lifetime_end);
2594 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002595 assert(II.getArgOperand(1) == OldPtr);
2596
Chandler Carruthf0546402013-07-18 07:15:00 +00002597 // Compute the intersecting offset range.
2598 assert(BeginOffset < NewAllocaEndOffset);
2599 assert(EndOffset > NewAllocaBeginOffset);
2600 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2601 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2602
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002603 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002604 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002605
2606 ConstantInt *Size
2607 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002608 NewEndOffset - NewBeginOffset);
2609 Value *Ptr =
2610 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getArgOperand(1)->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002611 Value *New;
2612 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2613 New = IRB.CreateLifetimeStart(Ptr, Size);
2614 else
2615 New = IRB.CreateLifetimeEnd(Ptr, Size);
2616
Edwin Vane82f80d42013-01-29 17:42:24 +00002617 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002618 DEBUG(dbgs() << " to: " << *New << "\n");
2619 return true;
2620 }
2621
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002622 bool visitPHINode(PHINode &PN) {
2623 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00002624 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2625 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002626
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002627 // We would like to compute a new pointer in only one place, but have it be
2628 // as local as possible to the PHI. To do that, we re-use the location of
2629 // the old pointer, which necessarily must be in the right position to
2630 // dominate the PHI.
Jakub Staszakcb132fa2013-07-22 22:10:43 +00002631 IRBuilderTy PtrBuilder(OldPtr);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002632 PtrBuilder.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) +
2633 ".");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002634
Chandler Carruthf0546402013-07-18 07:15:00 +00002635 Value *NewPtr =
2636 getAdjustedAllocaPtr(PtrBuilder, BeginOffset, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002637 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002638 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002639
Chandler Carruth82a57542012-10-01 10:54:05 +00002640 DEBUG(dbgs() << " to: " << PN << "\n");
2641 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002642
2643 // Check whether we can speculate this PHI node, and if so remember that
Chandler Carruth83ea1952013-07-24 09:47:28 +00002644 // fact and queue it up for another iteration after the speculation
2645 // occurs.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002646 if (isSafePHIToSpeculate(PN, &DL)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002647 Pass.SpeculatablePHIs.insert(&PN);
Chandler Carruth83ea1952013-07-24 09:47:28 +00002648 IsUsedByRewrittenSpeculatableInstructions = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002649 return true;
2650 }
2651
2652 return false; // PHIs can't be promoted on their own.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002653 }
2654
2655 bool visitSelectInst(SelectInst &SI) {
2656 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002657 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2658 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00002659 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2660 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002661
Chandler Carruthf0546402013-07-18 07:15:00 +00002662 Value *NewPtr = getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002663 // Replace the operands which were using the old pointer.
2664 if (SI.getOperand(1) == OldPtr)
2665 SI.setOperand(1, NewPtr);
2666 if (SI.getOperand(2) == OldPtr)
2667 SI.setOperand(2, NewPtr);
2668
Chandler Carruth82a57542012-10-01 10:54:05 +00002669 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002670 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002671
2672 // Check whether we can speculate this select instruction, and if so
Chandler Carruth83ea1952013-07-24 09:47:28 +00002673 // remember that fact and queue it up for another iteration after the
2674 // speculation occurs.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002675 if (isSafeSelectToSpeculate(SI, &DL)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002676 Pass.SpeculatableSelects.insert(&SI);
Chandler Carruth83ea1952013-07-24 09:47:28 +00002677 IsUsedByRewrittenSpeculatableInstructions = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002678 return true;
2679 }
2680
2681 return false; // Selects can't be promoted on their own.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002682 }
2683
2684};
2685}
2686
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002687namespace {
2688/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2689///
2690/// This pass aggressively rewrites all aggregate loads and stores on
2691/// a particular pointer (or any pointer derived from it which we can identify)
2692/// with scalar loads and stores.
2693class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2694 // Befriend the base class so it can delegate to private visit methods.
2695 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2696
Chandler Carruth90a735d2013-07-19 07:21:28 +00002697 const DataLayout &DL;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002698
2699 /// Queue of pointer uses to analyze and potentially rewrite.
2700 SmallVector<Use *, 8> Queue;
2701
2702 /// Set to prevent us from cycling with phi nodes and loops.
2703 SmallPtrSet<User *, 8> Visited;
2704
2705 /// The current pointer use being rewritten. This is used to dig up the used
2706 /// value (as opposed to the user).
2707 Use *U;
2708
2709public:
Chandler Carruth90a735d2013-07-19 07:21:28 +00002710 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002711
2712 /// Rewrite loads and stores through a pointer and all pointers derived from
2713 /// it.
2714 bool rewrite(Instruction &I) {
2715 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2716 enqueueUsers(I);
2717 bool Changed = false;
2718 while (!Queue.empty()) {
2719 U = Queue.pop_back_val();
2720 Changed |= visit(cast<Instruction>(U->getUser()));
2721 }
2722 return Changed;
2723 }
2724
2725private:
2726 /// Enqueue all the users of the given instruction for further processing.
2727 /// This uses a set to de-duplicate users.
2728 void enqueueUsers(Instruction &I) {
2729 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2730 ++UI)
2731 if (Visited.insert(*UI))
2732 Queue.push_back(&UI.getUse());
2733 }
2734
2735 // Conservative default is to not rewrite anything.
2736 bool visitInstruction(Instruction &I) { return false; }
2737
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002738 /// \brief Generic recursive split emission class.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002739 template <typename Derived>
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002740 class OpSplitter {
2741 protected:
2742 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00002743 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002744 /// The indices which to be used with insert- or extractvalue to select the
2745 /// appropriate value within the aggregate.
2746 SmallVector<unsigned, 4> Indices;
2747 /// The indices to a GEP instruction which will move Ptr to the correct slot
2748 /// within the aggregate.
2749 SmallVector<Value *, 4> GEPIndices;
2750 /// The base pointer of the original op, used as a base for GEPing the
2751 /// split operations.
2752 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002753
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002754 /// Initialize the splitter with an insertion point, Ptr and start with a
2755 /// single zero GEP index.
2756 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002757 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002758
2759 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002760 /// \brief Generic recursive split emission routine.
2761 ///
2762 /// This method recursively splits an aggregate op (load or store) into
2763 /// scalar or vector ops. It splits recursively until it hits a single value
2764 /// and emits that single value operation via the template argument.
2765 ///
2766 /// The logic of this routine relies on GEPs and insertvalue and
2767 /// extractvalue all operating with the same fundamental index list, merely
2768 /// formatted differently (GEPs need actual values).
2769 ///
2770 /// \param Ty The type being split recursively into smaller ops.
2771 /// \param Agg The aggregate value being built up or stored, depending on
2772 /// whether this is splitting a load or a store respectively.
2773 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2774 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002775 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002776
2777 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2778 unsigned OldSize = Indices.size();
2779 (void)OldSize;
2780 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2781 ++Idx) {
2782 assert(Indices.size() == OldSize && "Did not return to the old size");
2783 Indices.push_back(Idx);
2784 GEPIndices.push_back(IRB.getInt32(Idx));
2785 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2786 GEPIndices.pop_back();
2787 Indices.pop_back();
2788 }
2789 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002790 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002791
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002792 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2793 unsigned OldSize = Indices.size();
2794 (void)OldSize;
2795 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2796 ++Idx) {
2797 assert(Indices.size() == OldSize && "Did not return to the old size");
2798 Indices.push_back(Idx);
2799 GEPIndices.push_back(IRB.getInt32(Idx));
2800 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2801 GEPIndices.pop_back();
2802 Indices.pop_back();
2803 }
2804 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002805 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002806
2807 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002808 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002809 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002810
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002811 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002812 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002813 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002814
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002815 /// Emit a leaf load of a single value. This is called at the leaves of the
2816 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002817 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002818 assert(Ty->isSingleValueType());
2819 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00002820 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2821 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002822 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2823 DEBUG(dbgs() << " to: " << *Load << "\n");
2824 }
2825 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002826
2827 bool visitLoadInst(LoadInst &LI) {
2828 assert(LI.getPointerOperand() == *U);
2829 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2830 return false;
2831
2832 // We have an aggregate being loaded, split it apart.
2833 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002834 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002835 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002836 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002837 LI.replaceAllUsesWith(V);
2838 LI.eraseFromParent();
2839 return true;
2840 }
2841
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002842 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002843 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002844 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002845
2846 /// Emit a leaf store of a single value. This is called at the leaves of the
2847 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002848 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002849 assert(Ty->isSingleValueType());
2850 // Extract the single value and store it using the indices.
2851 Value *Store = IRB.CreateStore(
2852 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2853 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2854 (void)Store;
2855 DEBUG(dbgs() << " to: " << *Store << "\n");
2856 }
2857 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002858
2859 bool visitStoreInst(StoreInst &SI) {
2860 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2861 return false;
2862 Value *V = SI.getValueOperand();
2863 if (V->getType()->isSingleValueType())
2864 return false;
2865
2866 // We have an aggregate being stored, split it apart.
2867 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002868 StoreOpSplitter Splitter(&SI, *U);
2869 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002870 SI.eraseFromParent();
2871 return true;
2872 }
2873
2874 bool visitBitCastInst(BitCastInst &BC) {
2875 enqueueUsers(BC);
2876 return false;
2877 }
2878
2879 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2880 enqueueUsers(GEPI);
2881 return false;
2882 }
2883
2884 bool visitPHINode(PHINode &PN) {
2885 enqueueUsers(PN);
2886 return false;
2887 }
2888
2889 bool visitSelectInst(SelectInst &SI) {
2890 enqueueUsers(SI);
2891 return false;
2892 }
2893};
2894}
2895
Chandler Carruthba931992012-10-13 10:49:33 +00002896/// \brief Strip aggregate type wrapping.
2897///
2898/// This removes no-op aggregate types wrapping an underlying type. It will
2899/// strip as many layers of types as it can without changing either the type
2900/// size or the allocated size.
2901static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
2902 if (Ty->isSingleValueType())
2903 return Ty;
2904
2905 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2906 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
2907
2908 Type *InnerTy;
2909 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
2910 InnerTy = ArrTy->getElementType();
2911 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2912 const StructLayout *SL = DL.getStructLayout(STy);
2913 unsigned Index = SL->getElementContainingOffset(0);
2914 InnerTy = STy->getElementType(Index);
2915 } else {
2916 return Ty;
2917 }
2918
2919 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
2920 TypeSize > DL.getTypeSizeInBits(InnerTy))
2921 return Ty;
2922
2923 return stripAggregateTypeWrapping(DL, InnerTy);
2924}
2925
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002926/// \brief Try to find a partition of the aggregate type passed in for a given
2927/// offset and size.
2928///
2929/// This recurses through the aggregate type and tries to compute a subtype
2930/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00002931/// of an array, it will even compute a new array type for that sub-section,
2932/// and the same for structs.
2933///
2934/// Note that this routine is very strict and tries to find a partition of the
2935/// type which produces the *exact* right offset and size. It is not forgiving
2936/// when the size or offset cause either end of type-based partition to be off.
2937/// Also, this is a best-effort routine. It is reasonable to give up and not
2938/// return a type if necessary.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002939static Type *getTypePartition(const DataLayout &DL, Type *Ty,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002940 uint64_t Offset, uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002941 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
2942 return stripAggregateTypeWrapping(DL, Ty);
2943 if (Offset > DL.getTypeAllocSize(Ty) ||
2944 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Chandler Carruth58d05562012-10-25 04:37:07 +00002945 return 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002946
2947 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2948 // We can't partition pointers...
2949 if (SeqTy->isPointerTy())
2950 return 0;
2951
2952 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00002953 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002954 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002955 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002956 if (NumSkippedElements >= ArrTy->getNumElements())
2957 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002958 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002959 if (NumSkippedElements >= VecTy->getNumElements())
2960 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002961 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002962 Offset -= NumSkippedElements * ElementSize;
2963
2964 // First check if we need to recurse.
2965 if (Offset > 0 || Size < ElementSize) {
2966 // Bail if the partition ends in a different array element.
2967 if ((Offset + Size) > ElementSize)
2968 return 0;
2969 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002970 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002971 }
2972 assert(Offset == 0);
2973
2974 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002975 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002976 assert(Size > ElementSize);
2977 uint64_t NumElements = Size / ElementSize;
2978 if (NumElements * ElementSize != Size)
2979 return 0;
2980 return ArrayType::get(ElementTy, NumElements);
2981 }
2982
2983 StructType *STy = dyn_cast<StructType>(Ty);
2984 if (!STy)
2985 return 0;
2986
Chandler Carruth90a735d2013-07-19 07:21:28 +00002987 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00002988 if (Offset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002989 return 0;
2990 uint64_t EndOffset = Offset + Size;
2991 if (EndOffset > SL->getSizeInBytes())
2992 return 0;
2993
2994 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002995 Offset -= SL->getElementOffset(Index);
2996
2997 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002998 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002999 if (Offset >= ElementSize)
3000 return 0; // The offset points into alignment padding.
3001
3002 // See if any partition must be contained by the element.
3003 if (Offset > 0 || Size < ElementSize) {
3004 if ((Offset + Size) > ElementSize)
3005 return 0;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003006 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003007 }
3008 assert(Offset == 0);
3009
3010 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003011 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003012
3013 StructType::element_iterator EI = STy->element_begin() + Index,
3014 EE = STy->element_end();
3015 if (EndOffset < SL->getSizeInBytes()) {
3016 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3017 if (Index == EndIndex)
3018 return 0; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003019
3020 // Don't try to form "natural" types if the elements don't line up with the
3021 // expected size.
3022 // FIXME: We could potentially recurse down through the last element in the
3023 // sub-struct to find a natural end point.
3024 if (SL->getElementOffset(EndIndex) != EndOffset)
3025 return 0;
3026
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003027 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003028 EE = STy->element_begin() + EndIndex;
3029 }
3030
3031 // Try to build up a sub-structure.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003032 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003033 STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003034 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003035 if (Size != SubSL->getSizeInBytes())
3036 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003037
Chandler Carruth054a40a2012-09-14 11:08:31 +00003038 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003039}
3040
3041/// \brief Rewrite an alloca partition's users.
3042///
3043/// This routine drives both of the rewriting goals of the SROA pass. It tries
3044/// to rewrite uses of an alloca partition to be conducive for SSA value
3045/// promotion. If the partition needs a new, more refined alloca, this will
3046/// build that new alloca, preserving as much type information as possible, and
3047/// rewrite the uses of the old alloca to point at the new one and have the
3048/// appropriate new offsets. It also evaluates how successful the rewrite was
3049/// at enabling promotion and if it was successful queues the alloca to be
3050/// promoted.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003051bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
3052 AllocaSlices::iterator B, AllocaSlices::iterator E,
3053 int64_t BeginOffset, int64_t EndOffset,
3054 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003055 assert(BeginOffset < EndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003056 uint64_t SliceSize = EndOffset - BeginOffset;
Chandler Carruth82a57542012-10-01 10:54:05 +00003057
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003058 // Try to compute a friendly type for this partition of the alloca. This
3059 // won't always succeed, in which case we fall back to a legal integer type
3060 // or an i8 array of an appropriate size.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003061 Type *SliceTy = 0;
Chandler Carruthf0546402013-07-18 07:15:00 +00003062 if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003063 if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
3064 SliceTy = CommonUseTy;
3065 if (!SliceTy)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003066 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003067 BeginOffset, SliceSize))
3068 SliceTy = TypePartitionTy;
3069 if ((!SliceTy || (SliceTy->isArrayTy() &&
3070 SliceTy->getArrayElementType()->isIntegerTy())) &&
3071 DL->isLegalInteger(SliceSize * 8))
3072 SliceTy = Type::getIntNTy(*C, SliceSize * 8);
3073 if (!SliceTy)
3074 SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
3075 assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
Chandler Carruthf0546402013-07-18 07:15:00 +00003076
3077 bool IsVectorPromotable = isVectorPromotionViable(
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003078 *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
Chandler Carruthf0546402013-07-18 07:15:00 +00003079
3080 bool IsIntegerPromotable =
3081 !IsVectorPromotable &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003082 isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003083
3084 // Check for the case where we're going to rewrite to a new alloca of the
3085 // exact same type as the original, and with the same access offsets. In that
3086 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003087 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003088 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003089 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003090 assert(BeginOffset == 0 &&
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003091 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003092 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003093 // FIXME: We should be able to bail at this point with "nothing changed".
3094 // FIXME: We might want to defer PHI speculation until after here.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003095 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003096 unsigned Alignment = AI.getAlignment();
3097 if (!Alignment) {
3098 // The minimum alignment which users can rely on when the explicit
3099 // alignment is omitted or zero is that required by the ABI for this
3100 // type.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003101 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003102 }
Chandler Carruthf0546402013-07-18 07:15:00 +00003103 Alignment = MinAlign(Alignment, BeginOffset);
Chandler Carruth903790e2012-09-29 10:41:21 +00003104 // If we will get at least this much alignment from the type alone, leave
3105 // the alloca's alignment unconstrained.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003106 if (Alignment <= DL->getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003107 Alignment = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003108 NewAI = new AllocaInst(SliceTy, 0, Alignment,
3109 AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003110 ++NumNewAllocas;
3111 }
3112
3113 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthf0546402013-07-18 07:15:00 +00003114 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3115 << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003116
Chandler Carruthf0546402013-07-18 07:15:00 +00003117 // Track the high watermark on several worklists that are only relevant for
3118 // promoted allocas. We will reset it to this point if the alloca is not in
3119 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003120 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruthf0546402013-07-18 07:15:00 +00003121 unsigned SPOldSize = SpeculatablePHIs.size();
3122 unsigned SSOldSize = SpeculatableSelects.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00003123 unsigned NumUses = 0;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003124
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003125 AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
3126 EndOffset, IsVectorPromotable,
3127 IsIntegerPromotable);
Chandler Carruthf0546402013-07-18 07:15:00 +00003128 bool Promotable = true;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003129 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
3130 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00003131 SUI != SUE; ++SUI) {
3132 DEBUG(dbgs() << " rewriting split ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003133 DEBUG(S.printSlice(dbgs(), *SUI, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003134 Promotable &= Rewriter.visit(*SUI);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003135 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003136 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003137 for (AllocaSlices::iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003138 DEBUG(dbgs() << " rewriting ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003139 DEBUG(S.printSlice(dbgs(), I, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003140 Promotable &= Rewriter.visit(I);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003141 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003142 }
3143
Chandler Carruth6c321c12013-07-19 10:57:36 +00003144 NumAllocaPartitionUses += NumUses;
3145 MaxUsesPerAllocaPartition =
3146 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003147
Chandler Carruth83ea1952013-07-24 09:47:28 +00003148 if (Promotable && !Rewriter.isUsedByRewrittenSpeculatableInstructions()) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003149 DEBUG(dbgs() << " and queuing for promotion\n");
3150 PromotableAllocas.push_back(NewAI);
Chandler Carruth58e25d32013-07-24 12:12:17 +00003151 } else if (NewAI != &AI ||
3152 (Promotable &&
3153 Rewriter.isUsedByRewrittenSpeculatableInstructions())) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003154 // If we can't promote the alloca, iterate on it to check for new
3155 // refinements exposed by splitting the current alloca. Don't iterate on an
3156 // alloca which didn't actually change and didn't get promoted.
Chandler Carruth58e25d32013-07-24 12:12:17 +00003157 //
3158 // Alternatively, if we could promote the alloca but have speculatable
3159 // instructions then we will speculate them after finishing our processing
3160 // of the original alloca. Mark the new one for re-visiting in the next
3161 // iteration so the speculated operations can be rewritten.
3162 //
Chandler Carruthf0546402013-07-18 07:15:00 +00003163 // FIXME: We should actually track whether the rewriter changed anything.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003164 Worklist.insert(NewAI);
3165 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003166
3167 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthf0546402013-07-18 07:15:00 +00003168 if (!Promotable) {
Chandler Carruthac8317f2012-10-04 12:33:50 +00003169 while (PostPromotionWorklist.size() > PPWOldSize)
3170 PostPromotionWorklist.pop_back();
Chandler Carruthf0546402013-07-18 07:15:00 +00003171 while (SpeculatablePHIs.size() > SPOldSize)
3172 SpeculatablePHIs.pop_back();
3173 while (SpeculatableSelects.size() > SSOldSize)
3174 SpeculatableSelects.pop_back();
3175 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003176
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003177 return true;
3178}
3179
Chandler Carruthf0546402013-07-18 07:15:00 +00003180namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003181struct IsSliceEndLessOrEqualTo {
3182 uint64_t UpperBound;
Chandler Carruthf0546402013-07-18 07:15:00 +00003183
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003184 IsSliceEndLessOrEqualTo(uint64_t UpperBound) : UpperBound(UpperBound) {}
Chandler Carruthf0546402013-07-18 07:15:00 +00003185
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003186 bool operator()(const AllocaSlices::iterator &I) {
3187 return I->endOffset() <= UpperBound;
3188 }
3189};
Chandler Carruthf0546402013-07-18 07:15:00 +00003190}
3191
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003192static void
3193removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3194 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003195 if (Offset >= MaxSplitUseEndOffset) {
3196 SplitUses.clear();
3197 MaxSplitUseEndOffset = 0;
3198 return;
3199 }
3200
3201 size_t SplitUsesOldSize = SplitUses.size();
3202 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003203 IsSliceEndLessOrEqualTo(Offset)),
Chandler Carruthf0546402013-07-18 07:15:00 +00003204 SplitUses.end());
3205 if (SplitUsesOldSize == SplitUses.size())
3206 return;
3207
3208 // Recompute the max. While this is linear, so is remove_if.
3209 MaxSplitUseEndOffset = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003210 for (SmallVectorImpl<AllocaSlices::iterator>::iterator
Chandler Carruthf0546402013-07-18 07:15:00 +00003211 SUI = SplitUses.begin(),
3212 SUE = SplitUses.end();
3213 SUI != SUE; ++SUI)
3214 MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
3215}
3216
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003217/// \brief Walks the slices of an alloca and form partitions based on them,
3218/// rewriting each of their uses.
3219bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
3220 if (S.begin() == S.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00003221 return false;
3222
Chandler Carruth6c321c12013-07-19 10:57:36 +00003223 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003224 bool Changed = false;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003225 SmallVector<AllocaSlices::iterator, 4> SplitUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003226 uint64_t MaxSplitUseEndOffset = 0;
3227
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003228 uint64_t BeginOffset = S.begin()->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003229
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003230 for (AllocaSlices::iterator SI = S.begin(), SJ = llvm::next(SI), SE = S.end();
3231 SI != SE; SI = SJ) {
3232 uint64_t MaxEndOffset = SI->endOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003233
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003234 if (!SI->isSplittable()) {
3235 // When we're forming an unsplittable region, it must always start at the
3236 // first slice and will extend through its end.
3237 assert(BeginOffset == SI->beginOffset());
Chandler Carruthf0546402013-07-18 07:15:00 +00003238
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003239 // Form a partition including all of the overlapping slices with this
3240 // unsplittable slice.
3241 while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3242 if (!SJ->isSplittable())
3243 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3244 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003245 }
3246 } else {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003247 assert(SI->isSplittable()); // Established above.
Chandler Carruthf0546402013-07-18 07:15:00 +00003248
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003249 // Collect all of the overlapping splittable slices.
3250 while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3251 SJ->isSplittable()) {
3252 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3253 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003254 }
3255
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003256 // Back up MaxEndOffset and SJ if we ended the span early when
3257 // encountering an unsplittable slice.
3258 if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3259 assert(!SJ->isSplittable());
3260 MaxEndOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003261 }
3262 }
3263
3264 // Check if we have managed to move the end offset forward yet. If so,
3265 // we'll have to rewrite uses and erase old split uses.
3266 if (BeginOffset < MaxEndOffset) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003267 // Rewrite a sequence of overlapping slices.
3268 Changed |=
3269 rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003270 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00003271
3272 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3273 }
3274
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003275 // Accumulate all the splittable slices from the [SI,SJ) region which
Chandler Carruthf0546402013-07-18 07:15:00 +00003276 // overlap going forward.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003277 for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3278 if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3279 SplitUses.push_back(SK);
3280 MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
Chandler Carruthf0546402013-07-18 07:15:00 +00003281 }
3282
3283 // If we're already at the end and we have no split uses, we're done.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003284 if (SJ == SE && SplitUses.empty())
Chandler Carruthf0546402013-07-18 07:15:00 +00003285 break;
3286
3287 // If we have no split uses or no gap in offsets, we're ready to move to
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003288 // the next slice.
3289 if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3290 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003291 continue;
3292 }
3293
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003294 // Even if we have split slices, if the next slice is splittable and the
3295 // split slices reach it, we can simply set up the beginning offset of the
3296 // next iteration to bridge between them.
3297 if (SJ != SE && SJ->isSplittable() &&
3298 MaxSplitUseEndOffset > SJ->beginOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003299 BeginOffset = MaxEndOffset;
3300 continue;
3301 }
3302
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003303 // Otherwise, we have a tail of split slices. Rewrite them with an empty
3304 // range of slices.
Chandler Carruthf0546402013-07-18 07:15:00 +00003305 uint64_t PostSplitEndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003306 SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003307
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003308 Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
3309 SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003310 ++NumPartitions;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003311
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003312 if (SJ == SE)
Chandler Carruthf0546402013-07-18 07:15:00 +00003313 break; // Skip the rest, we don't need to do any cleanup.
3314
3315 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3316 PostSplitEndOffset);
3317
3318 // Now just reset the begin offset for the next iteration.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003319 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003320 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003321
Chandler Carruth6c321c12013-07-19 10:57:36 +00003322 NumAllocaPartitions += NumPartitions;
3323 MaxPartitionsPerAlloca =
3324 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003325
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003326 return Changed;
3327}
3328
3329/// \brief Analyze an alloca for SROA.
3330///
3331/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003332/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003333/// rewritten as needed.
3334bool SROA::runOnAlloca(AllocaInst &AI) {
3335 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3336 ++NumAllocasAnalyzed;
3337
3338 // Special case dead allocas, as they're trivial.
3339 if (AI.use_empty()) {
3340 AI.eraseFromParent();
3341 return true;
3342 }
3343
3344 // Skip alloca forms that this analysis can't handle.
3345 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00003346 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003347 return false;
3348
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003349 bool Changed = false;
3350
3351 // First, split any FCA loads and stores touching this alloca to promote
3352 // better splitting and promotion opportunities.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003353 AggLoadStoreRewriter AggRewriter(*DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003354 Changed |= AggRewriter.rewrite(AI);
3355
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003356 // Build the slices using a recursive instruction-visiting builder.
3357 AllocaSlices S(*DL, AI);
3358 DEBUG(S.print(dbgs()));
3359 if (S.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003360 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003361
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003362 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003363 for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
3364 DE = S.dead_user_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003365 DI != DE; ++DI) {
3366 Changed = true;
3367 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
Chandler Carruth18db7952012-11-20 01:12:50 +00003368 DeadInsts.insert(*DI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003369 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003370 for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
3371 DE = S.dead_op_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003372 DO != DE; ++DO) {
3373 Value *OldV = **DO;
3374 // Clobber the use with an undef value.
3375 **DO = UndefValue::get(OldV->getType());
3376 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3377 if (isInstructionTriviallyDead(OldI)) {
3378 Changed = true;
Chandler Carruth18db7952012-11-20 01:12:50 +00003379 DeadInsts.insert(OldI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003380 }
3381 }
3382
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003383 // No slices to split. Leave the dead alloca for a later pass to clean up.
3384 if (S.begin() == S.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003385 return Changed;
3386
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003387 Changed |= splitAlloca(AI, S);
Chandler Carruthf0546402013-07-18 07:15:00 +00003388
3389 DEBUG(dbgs() << " Speculating PHIs\n");
3390 while (!SpeculatablePHIs.empty())
3391 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3392
3393 DEBUG(dbgs() << " Speculating Selects\n");
3394 while (!SpeculatableSelects.empty())
3395 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3396
3397 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003398}
3399
Chandler Carruth19450da2012-09-14 10:26:38 +00003400/// \brief Delete the dead instructions accumulated in this run.
3401///
3402/// Recursively deletes the dead instructions we've accumulated. This is done
3403/// at the very end to maximize locality of the recursive delete and to
3404/// minimize the problems of invalidated instruction pointers as such pointers
3405/// are used heavily in the intermediate stages of the algorithm.
3406///
3407/// We also record the alloca instructions deleted here so that they aren't
3408/// subsequently handed to mem2reg to promote.
3409void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003410 while (!DeadInsts.empty()) {
3411 Instruction *I = DeadInsts.pop_back_val();
3412 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3413
Chandler Carruth58d05562012-10-25 04:37:07 +00003414 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3415
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003416 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3417 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3418 // Zero out the operand and see if it becomes trivially dead.
3419 *OI = 0;
3420 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003421 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003422 }
3423
3424 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3425 DeletedAllocas.insert(AI);
3426
3427 ++NumDeleted;
3428 I->eraseFromParent();
3429 }
3430}
3431
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003432static void enqueueUsersInWorklist(Instruction &I,
Chandler Carruth45b136f2013-08-11 01:03:18 +00003433 SmallVectorImpl<Instruction *> &Worklist,
3434 SmallPtrSet<Instruction *, 8> &Visited) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003435 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3436 ++UI)
Chandler Carruth45b136f2013-08-11 01:03:18 +00003437 if (Visited.insert(cast<Instruction>(*UI)))
3438 Worklist.push_back(cast<Instruction>(*UI));
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003439}
3440
Chandler Carruth70b44c52012-09-15 11:43:14 +00003441/// \brief Promote the allocas, using the best available technique.
3442///
3443/// This attempts to promote whatever allocas have been identified as viable in
3444/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3445/// If there is a domtree available, we attempt to promote using the full power
3446/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3447/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003448/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003449bool SROA::promoteAllocas(Function &F) {
3450 if (PromotableAllocas.empty())
3451 return false;
3452
3453 NumPromoted += PromotableAllocas.size();
3454
3455 if (DT && !ForceSSAUpdater) {
3456 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Nick Lewyckyc7776f72013-08-13 22:51:58 +00003457 PromoteMemToReg(PromotableAllocas, *DT);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003458 PromotableAllocas.clear();
3459 return true;
3460 }
3461
3462 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3463 SSAUpdater SSA;
3464 DIBuilder DIB(*F.getParent());
Chandler Carruth45b136f2013-08-11 01:03:18 +00003465 SmallVector<Instruction *, 64> Insts;
Chandler Carruth70b44c52012-09-15 11:43:14 +00003466
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003467 // We need a worklist to walk the uses of each alloca.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003468 SmallVector<Instruction *, 8> Worklist;
3469 SmallPtrSet<Instruction *, 8> Visited;
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003470 SmallVector<Instruction *, 32> DeadInsts;
3471
Chandler Carruth70b44c52012-09-15 11:43:14 +00003472 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3473 AllocaInst *AI = PromotableAllocas[Idx];
Chandler Carruth45b136f2013-08-11 01:03:18 +00003474 Insts.clear();
3475 Worklist.clear();
3476 Visited.clear();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003477
Chandler Carruth45b136f2013-08-11 01:03:18 +00003478 enqueueUsersInWorklist(*AI, Worklist, Visited);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003479
Chandler Carruth45b136f2013-08-11 01:03:18 +00003480 while (!Worklist.empty()) {
3481 Instruction *I = Worklist.pop_back_val();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003482
Chandler Carruth70b44c52012-09-15 11:43:14 +00003483 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3484 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3485 // leading to them) here. Eventually it should use them to optimize the
3486 // scalar values produced.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003487 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003488 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3489 II->getIntrinsicID() == Intrinsic::lifetime_end);
3490 II->eraseFromParent();
3491 continue;
3492 }
3493
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003494 // Push the loads and stores we find onto the list. SROA will already
3495 // have validated that all loads and stores are viable candidates for
3496 // promotion.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003497 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003498 assert(LI->getType() == AI->getAllocatedType());
3499 Insts.push_back(LI);
3500 continue;
3501 }
Chandler Carruth45b136f2013-08-11 01:03:18 +00003502 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003503 assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
3504 Insts.push_back(SI);
3505 continue;
3506 }
3507
3508 // For everything else, we know that only no-op bitcasts and GEPs will
3509 // make it this far, just recurse through them and recall them for later
3510 // removal.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003511 DeadInsts.push_back(I);
3512 enqueueUsersInWorklist(*I, Worklist, Visited);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003513 }
3514 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003515 while (!DeadInsts.empty())
3516 DeadInsts.pop_back_val()->eraseFromParent();
3517 AI->eraseFromParent();
Chandler Carruth70b44c52012-09-15 11:43:14 +00003518 }
3519
3520 PromotableAllocas.clear();
3521 return true;
3522}
3523
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003524namespace {
3525 /// \brief A predicate to test whether an alloca belongs to a set.
3526 class IsAllocaInSet {
3527 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3528 const SetType &Set;
3529
3530 public:
Chandler Carruth3f57b822012-10-03 00:03:00 +00003531 typedef AllocaInst *argument_type;
3532
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003533 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth3f57b822012-10-03 00:03:00 +00003534 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003535 };
3536}
3537
3538bool SROA::runOnFunction(Function &F) {
3539 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3540 C = &F.getContext();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003541 DL = getAnalysisIfAvailable<DataLayout>();
3542 if (!DL) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003543 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3544 return false;
3545 }
Chandler Carruth70b44c52012-09-15 11:43:14 +00003546 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003547
3548 BasicBlock &EntryBB = F.getEntryBlock();
3549 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3550 I != E; ++I)
3551 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3552 Worklist.insert(AI);
3553
3554 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003555 // A set of deleted alloca instruction pointers which should be removed from
3556 // the list of promotable allocas.
3557 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3558
Chandler Carruthac8317f2012-10-04 12:33:50 +00003559 do {
3560 while (!Worklist.empty()) {
3561 Changed |= runOnAlloca(*Worklist.pop_back_val());
3562 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003563
Chandler Carruthac8317f2012-10-04 12:33:50 +00003564 // Remove the deleted allocas from various lists so that we don't try to
3565 // continue processing them.
3566 if (!DeletedAllocas.empty()) {
3567 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3568 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3569 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3570 PromotableAllocas.end(),
3571 IsAllocaInSet(DeletedAllocas)),
3572 PromotableAllocas.end());
3573 DeletedAllocas.clear();
3574 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003575 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003576
Chandler Carruthac8317f2012-10-04 12:33:50 +00003577 Changed |= promoteAllocas(F);
3578
3579 Worklist = PostPromotionWorklist;
3580 PostPromotionWorklist.clear();
3581 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003582
3583 return Changed;
3584}
3585
3586void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003587 if (RequiresDomTree)
3588 AU.addRequired<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003589 AU.setPreservesCFG();
3590}