blob: 7235c0d6f22e2ada00a6541b07f709665d1bd907 [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");
62STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions");
63STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses found");
64STATISTIC(MaxPartitionUsesPerAlloca, "Maximum number of partition uses");
65STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
66STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000067STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000068STATISTIC(NumDeleted, "Number of instructions deleted");
69STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000070
Chandler Carruth70b44c52012-09-15 11:43:14 +000071/// Hidden option to force the pass to not use DomTree and mem2reg, instead
72/// forming SSA values through the SSAUpdater infrastructure.
73static cl::opt<bool>
74ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
75
Chandler Carruth1b398ae2012-09-14 09:22:59 +000076namespace {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000077/// \brief A custom IRBuilder inserter which prefixes all names if they are
78/// preserved.
79template <bool preserveNames = true>
80class IRBuilderPrefixedInserter :
81 public IRBuilderDefaultInserter<preserveNames> {
82 std::string Prefix;
83
84public:
85 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
86
87protected:
88 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
89 BasicBlock::iterator InsertPt) const {
90 IRBuilderDefaultInserter<preserveNames>::InsertHelper(
91 I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
92 }
93};
94
95// Specialization for not preserving the name is trivial.
96template <>
97class IRBuilderPrefixedInserter<false> :
98 public IRBuilderDefaultInserter<false> {
99public:
100 void SetNamePrefix(const Twine &P) {}
101};
102
Chandler Carruthd177f862013-03-20 07:30:36 +0000103/// \brief Provide a typedef for IRBuilder that drops names in release builds.
104#ifndef NDEBUG
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000105typedef llvm::IRBuilder<true, ConstantFolder,
106 IRBuilderPrefixedInserter<true> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000107#else
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000108typedef llvm::IRBuilder<false, ConstantFolder,
109 IRBuilderPrefixedInserter<false> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000110#endif
111}
112
113namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000114/// \brief A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000115///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000116/// This structure represents a slice of an alloca used by some instruction. It
117/// stores both the begin and end offsets of this use, a pointer to the use
118/// itself, and a flag indicating whether we can classify the use as splittable
119/// or not when forming partitions of the alloca.
120class Slice {
Chandler Carruthf74654d2013-03-18 08:36:46 +0000121 /// \brief The beginning offset of the range.
122 uint64_t BeginOffset;
123
124 /// \brief The ending offset, not included in the range.
125 uint64_t EndOffset;
126
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000127 /// \brief Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000128 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000129 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000130
131public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000132 Slice() : BeginOffset(), EndOffset() {}
133 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000134 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000135 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000136
137 uint64_t beginOffset() const { return BeginOffset; }
138 uint64_t endOffset() const { return EndOffset; }
139
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000140 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
141 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000142
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000143 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000144
145 bool isDead() const { return getUse() == 0; }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000146 void kill() { UseAndIsSplittable.setPointer(0); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000147
148 /// \brief Support for ordering ranges.
149 ///
150 /// This provides an ordering over ranges such that start offsets are
151 /// always increasing, and within equal start offsets, the end offsets are
152 /// decreasing. Thus the spanning range comes first in a cluster with the
153 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000154 bool operator<(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000155 if (beginOffset() < RHS.beginOffset()) return true;
156 if (beginOffset() > RHS.beginOffset()) return false;
157 if (isSplittable() != RHS.isSplittable()) return !isSplittable();
158 if (endOffset() > RHS.endOffset()) return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000159 return false;
160 }
161
162 /// \brief Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000163 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000164 uint64_t RHSOffset) {
165 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000166 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000167 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000168 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000169 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000170 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000171
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000172 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000173 return isSplittable() == RHS.isSplittable() &&
174 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000175 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000176 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000177};
Chandler Carruthf0546402013-07-18 07:15:00 +0000178} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000179
180namespace llvm {
Chandler Carruthf0546402013-07-18 07:15:00 +0000181template <typename T> struct isPodLike;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000182template <> struct isPodLike<Slice> {
Chandler Carruthf0546402013-07-18 07:15:00 +0000183 static const bool value = true;
184};
Chandler Carruthf74654d2013-03-18 08:36:46 +0000185}
186
187namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000188/// \brief Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000189///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000190/// This class represents the slices of an alloca which are formed by its
191/// various uses. If a pointer escapes, we can't fully build a representation
192/// for the slices used and we reflect that in this structure. The uses are
193/// stored, sorted by increasing beginning offset and with unsplittable slices
194/// starting at a particular offset before splittable slices.
195class AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000196public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000197 /// \brief Construct the slices of a particular alloca.
198 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000199
200 /// \brief Test whether a pointer to the allocation escapes our analysis.
201 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000202 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000203 /// ignored.
204 bool isEscaped() const { return PointerEscapingInstr; }
205
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000206 /// \brief Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000207 /// @{
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000208 typedef SmallVectorImpl<Slice>::iterator iterator;
209 iterator begin() { return Slices.begin(); }
210 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000211
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000212 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
213 const_iterator begin() const { return Slices.begin(); }
214 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000215 /// @}
216
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000217 /// \brief Allow iterating the dead users for this alloca.
218 ///
219 /// These are instructions which will never actually use the alloca as they
220 /// are outside the allocated range. They are safe to replace with undef and
221 /// delete.
222 /// @{
223 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
224 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
225 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
226 /// @}
227
Chandler Carruth93a21e72012-09-14 10:18:49 +0000228 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000229 ///
230 /// These are operands which have cannot actually be used to refer to the
231 /// alloca as they are outside its range and the user doesn't correct for
232 /// that. These mostly consist of PHI node inputs and the like which we just
233 /// need to replace with undef.
234 /// @{
235 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
236 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
237 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
238 /// @}
239
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000240#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000241 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000242 void printSlice(raw_ostream &OS, const_iterator I,
243 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000244 void printUse(raw_ostream &OS, const_iterator I,
245 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000246 void print(raw_ostream &OS) const;
NAKAMURA Takumi4bbca0b2012-09-14 10:06:10 +0000247 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
248 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000249#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000250
251private:
252 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000253 class SliceBuilder;
254 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000255
Chandler Carruthb7915f72012-11-20 10:23:07 +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;
Benjamin Kramer4622cd72012-09-14 13:08:09 +0000259#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000260
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000261 /// \brief The instruction responsible for this alloca not having a known set
262 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000263 ///
264 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000265 /// store a pointer to that here and abort trying to form slices of the
266 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000267 Instruction *PointerEscapingInstr;
268
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000269 /// \brief The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000270 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000271 /// We store a vector of the slices formed by uses of the alloca here. This
272 /// vector is sorted by increasing begin offset, and then the unsplittable
273 /// slices before the splittable ones. See the Slice inner class for more
274 /// details.
275 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000276
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000277 /// \brief Instructions which will become dead if we rewrite the alloca.
278 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000279 /// Note that these are not separated by slice. This is because we expect an
280 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
281 /// all these instructions can simply be removed and replaced with undef as
282 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000283 SmallVector<Instruction *, 8> DeadUsers;
284
285 /// \brief Operands which will become dead if we rewrite the alloca.
286 ///
287 /// These are operands that in their particular use can be replaced with
288 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
289 /// to PHI nodes and the like. They aren't entirely dead (there might be
290 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
291 /// want to swap this particular input for undef to simplify the use lists of
292 /// the alloca.
293 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000294};
295}
296
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000297static Value *foldSelectInst(SelectInst &SI) {
298 // If the condition being selected on is a constant or the same value is
299 // being selected between, fold the select. Yes this does (rarely) happen
300 // early on.
301 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
302 return SI.getOperand(1+CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000303 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000304 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000305
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000306 return 0;
307}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000308
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000309/// \brief Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000310///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000311/// This class builds a set of alloca slices by recursively visiting the uses
312/// of an alloca and making a slice for each load and store at each offset.
313class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
314 friend class PtrUseVisitor<SliceBuilder>;
315 friend class InstVisitor<SliceBuilder>;
316 typedef PtrUseVisitor<SliceBuilder> Base;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000317
318 const uint64_t AllocSize;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000319 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000320
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000321 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000322 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
323
324 /// \brief Set to de-duplicate dead instructions found in the use walk.
325 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000326
327public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000328 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &S)
329 : PtrUseVisitor<SliceBuilder>(DL),
330 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
Chandler Carruthf0546402013-07-18 07:15:00 +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)) {
613 if (Result == *U)
614 // If the result of the constant fold will be the pointer, recurse
615 // through the select as if we had RAUW'ed it.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000616 enqueueUsers(SI);
Chandler Carruth225d4bd2012-09-21 23:36:40 +0000617 else
618 // 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 Carruthf0546402013-07-18 07:15:00 +0000656namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000657struct IsSliceDead {
658 bool operator()(const Slice &S) { return S.isDead(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000659};
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000660}
661
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000662AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Benjamin Kramer4622cd72012-09-14 13:08:09 +0000663 :
Chandler Carruthb7915f72012-11-20 10:23:07 +0000664#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Benjamin Kramer4622cd72012-09-14 13:08:09 +0000665 AI(AI),
666#endif
667 PointerEscapingInstr(0) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000668 SliceBuilder PB(DL, AI, *this);
669 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000670 if (PtrI.isEscaped() || PtrI.isAborted()) {
671 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000672 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000673 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
674 : PtrI.getAbortingInst();
675 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000676 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000677 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000678
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000679 // Sort the uses. This arranges for the offsets to be in ascending order,
680 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000681 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000682
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000683 Slices.erase(std::remove_if(Slices.begin(), Slices.end(), IsSliceDead()),
684 Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000685
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000686 // Record how many slices we end up with.
687 NumAllocaPartitions += Slices.size();
688 MaxPartitionsPerAlloca =
689 std::max<unsigned>(Slices.size(), MaxPartitionsPerAlloca);
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000690
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000691 NumAllocaPartitionUses += Slices.size();
Chandler Carruthf0546402013-07-18 07:15:00 +0000692 MaxPartitionUsesPerAlloca =
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000693 std::max<unsigned>(Slices.size(), MaxPartitionUsesPerAlloca);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000694}
695
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000696#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
697
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000698void AllocaSlices::print(raw_ostream &OS, const_iterator I,
699 StringRef Indent) const {
700 printSlice(OS, I, Indent);
Chandler Carruthf0546402013-07-18 07:15:00 +0000701 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000702}
703
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000704void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
705 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000706 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000707 << " slice #" << (I - begin())
Chandler Carruthf0546402013-07-18 07:15:00 +0000708 << (I->isSplittable() ? " (splittable)" : "") << "\n";
709}
710
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000711void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
712 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000713 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000714}
715
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000716void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000717 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000718 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000719 << " A pointer to this alloca escaped by:\n"
720 << " " << *PointerEscapingInstr << "\n";
721 return;
722 }
723
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000724 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +0000725 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000726 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000727}
728
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000729void AllocaSlices::dump(const_iterator I) const { print(dbgs(), I); }
730void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000731
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000732#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
733
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000734namespace {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000735/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
736///
737/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
738/// the loads and stores of an alloca instruction, as well as updating its
739/// debug information. This is used when a domtree is unavailable and thus
740/// mem2reg in its full form can't be used to handle promotion of allocas to
741/// scalar values.
742class AllocaPromoter : public LoadAndStorePromoter {
743 AllocaInst &AI;
744 DIBuilder &DIB;
745
746 SmallVector<DbgDeclareInst *, 4> DDIs;
747 SmallVector<DbgValueInst *, 4> DVIs;
748
749public:
750 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
751 AllocaInst &AI, DIBuilder &DIB)
752 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
753
754 void run(const SmallVectorImpl<Instruction*> &Insts) {
755 // Remember which alloca we're promoting (for isInstInList).
756 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
757 for (Value::use_iterator UI = DebugNode->use_begin(),
758 UE = DebugNode->use_end();
759 UI != UE; ++UI)
760 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
761 DDIs.push_back(DDI);
762 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
763 DVIs.push_back(DVI);
764 }
765
766 LoadAndStorePromoter::run(Insts);
767 AI.eraseFromParent();
768 while (!DDIs.empty())
769 DDIs.pop_back_val()->eraseFromParent();
770 while (!DVIs.empty())
771 DVIs.pop_back_val()->eraseFromParent();
772 }
773
774 virtual bool isInstInList(Instruction *I,
775 const SmallVectorImpl<Instruction*> &Insts) const {
776 if (LoadInst *LI = dyn_cast<LoadInst>(I))
777 return LI->getOperand(0) == &AI;
778 return cast<StoreInst>(I)->getPointerOperand() == &AI;
779 }
780
781 virtual void updateDebugInfo(Instruction *Inst) const {
Craig Topper31ee5862013-07-03 15:07:05 +0000782 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000783 E = DDIs.end(); I != E; ++I) {
784 DbgDeclareInst *DDI = *I;
785 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
786 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
787 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
788 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
789 }
Craig Topper31ee5862013-07-03 15:07:05 +0000790 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000791 E = DVIs.end(); I != E; ++I) {
792 DbgValueInst *DVI = *I;
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000793 Value *Arg = 0;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000794 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
795 // If an argument is zero extended then use argument directly. The ZExt
796 // may be zapped by an optimization pass in future.
797 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
798 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000799 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000800 Arg = dyn_cast<Argument>(SExt->getOperand(0));
801 if (!Arg)
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000802 Arg = SI->getValueOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000803 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000804 Arg = LI->getPointerOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000805 } else {
806 continue;
807 }
808 Instruction *DbgVal =
809 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
810 Inst);
811 DbgVal->setDebugLoc(DVI->getDebugLoc());
812 }
813 }
814};
815} // end anon namespace
816
817
818namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000819/// \brief An optimization pass providing Scalar Replacement of Aggregates.
820///
821/// This pass takes allocations which can be completely analyzed (that is, they
822/// don't escape) and tries to turn them into scalar SSA values. There are
823/// a few steps to this process.
824///
825/// 1) It takes allocations of aggregates and analyzes the ways in which they
826/// are used to try to split them into smaller allocations, ideally of
827/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000828/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000829/// 2) It will transform accesses into forms which are suitable for SSA value
830/// promotion. This can be replacing a memset with a scalar store of an
831/// integer value, or it can involve speculating operations on a PHI or
832/// select to be a PHI or select of the results.
833/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
834/// onto insert and extract operations on a vector value, and convert them to
835/// this form. By doing so, it will enable promotion of vector aggregates to
836/// SSA vector values.
837class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000838 const bool RequiresDomTree;
839
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000840 LLVMContext *C;
Chandler Carruth90a735d2013-07-19 07:21:28 +0000841 const DataLayout *DL;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000842 DominatorTree *DT;
843
844 /// \brief Worklist of alloca instructions to simplify.
845 ///
846 /// Each alloca in the function is added to this. Each new alloca formed gets
847 /// added to it as well to recursively simplify unless that alloca can be
848 /// directly promoted. Finally, each time we rewrite a use of an alloca other
849 /// the one being actively rewritten, we add it back onto the list if not
850 /// already present to ensure it is re-visited.
851 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
852
853 /// \brief A collection of instructions to delete.
854 /// We try to batch deletions to simplify code and make things a bit more
855 /// efficient.
Chandler Carruth18db7952012-11-20 01:12:50 +0000856 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000857
Chandler Carruthac8317f2012-10-04 12:33:50 +0000858 /// \brief Post-promotion worklist.
859 ///
860 /// Sometimes we discover an alloca which has a high probability of becoming
861 /// viable for SROA after a round of promotion takes place. In those cases,
862 /// the alloca is enqueued here for re-processing.
863 ///
864 /// Note that we have to be very careful to clear allocas out of this list in
865 /// the event they are deleted.
866 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
867
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000868 /// \brief A collection of alloca instructions we can directly promote.
869 std::vector<AllocaInst *> PromotableAllocas;
870
Chandler Carruthf0546402013-07-18 07:15:00 +0000871 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
872 ///
873 /// All of these PHIs have been checked for the safety of speculation and by
874 /// being speculated will allow promoting allocas currently in the promotable
875 /// queue.
876 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
877
878 /// \brief A worklist of select instructions to speculate prior to promoting
879 /// allocas.
880 ///
881 /// All of these select instructions have been checked for the safety of
882 /// speculation and by being speculated will allow promoting allocas
883 /// currently in the promotable queue.
884 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
885
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000886public:
Chandler Carruth70b44c52012-09-15 11:43:14 +0000887 SROA(bool RequiresDomTree = true)
888 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
Chandler Carruth90a735d2013-07-19 07:21:28 +0000889 C(0), DL(0), DT(0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000890 initializeSROAPass(*PassRegistry::getPassRegistry());
891 }
892 bool runOnFunction(Function &F);
893 void getAnalysisUsage(AnalysisUsage &AU) const;
894
895 const char *getPassName() const { return "SROA"; }
896 static char ID;
897
898private:
Chandler Carruth82a57542012-10-01 10:54:05 +0000899 friend class PHIOrSelectSpeculator;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000900 friend class AllocaSliceRewriter;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000901
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000902 bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
903 AllocaSlices::iterator B, AllocaSlices::iterator E,
904 int64_t BeginOffset, int64_t EndOffset,
905 ArrayRef<AllocaSlices::iterator> SplitUses);
906 bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000907 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth19450da2012-09-14 10:26:38 +0000908 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +0000909 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000910};
911}
912
913char SROA::ID = 0;
914
Chandler Carruth70b44c52012-09-15 11:43:14 +0000915FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
916 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000917}
918
919INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
920 false, false)
921INITIALIZE_PASS_DEPENDENCY(DominatorTree)
922INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
923 false, false)
924
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000925/// Walk the range of a partitioning looking for a common type to cover this
926/// sequence of slices.
927static Type *findCommonType(AllocaSlices::const_iterator B,
928 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +0000929 uint64_t EndOffset) {
930 Type *Ty = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000931 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000932 Use *U = I->getUse();
933 if (isa<IntrinsicInst>(*U->getUser()))
934 continue;
935 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
936 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000937
Chandler Carruthf0546402013-07-18 07:15:00 +0000938 Type *UserTy = 0;
939 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser()))
940 UserTy = LI->getType();
941 else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser()))
942 UserTy = SI->getValueOperand()->getType();
943 else
944 return 0; // Bail if we have weird uses.
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000945
Chandler Carruthf0546402013-07-18 07:15:00 +0000946 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
947 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000948 // this for split integer operations where we want to use the type of the
Chandler Carruthf0546402013-07-18 07:15:00 +0000949 // entity causing the split.
950 if (ITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
951 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000952
Chandler Carruthf0546402013-07-18 07:15:00 +0000953 // If we have found an integer type use covering the alloca, use that
954 // regardless of the other types, as integers are often used for a
955 // "bucket
956 // of bits" type.
957 return ITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +0000958 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000959
960 if (Ty && Ty != UserTy)
961 return 0;
962
963 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +0000964 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000965 return Ty;
966}
Chandler Carruthe3899f22013-07-15 17:36:21 +0000967
Chandler Carruthf0546402013-07-18 07:15:00 +0000968/// PHI instructions that use an alloca and are subsequently loaded can be
969/// rewritten to load both input pointers in the pred blocks and then PHI the
970/// results, allowing the load of the alloca to be promoted.
971/// From this:
972/// %P2 = phi [i32* %Alloca, i32* %Other]
973/// %V = load i32* %P2
974/// to:
975/// %V1 = load i32* %Alloca -> will be mem2reg'd
976/// ...
977/// %V2 = load i32* %Other
978/// ...
979/// %V = phi [i32 %V1, i32 %V2]
980///
981/// We can do this to a select if its only uses are loads and if the operands
982/// to the select can be loaded unconditionally.
983///
984/// FIXME: This should be hoisted into a generic utility, likely in
985/// Transforms/Util/Local.h
986static bool isSafePHIToSpeculate(PHINode &PN,
Chandler Carruth90a735d2013-07-19 07:21:28 +0000987 const DataLayout *DL = 0) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000988 // For now, we can only do this promotion if the load is in the same block
989 // as the PHI, and if there are no stores between the phi and load.
990 // TODO: Allow recursive phi users.
991 // TODO: Allow stores.
992 BasicBlock *BB = PN.getParent();
993 unsigned MaxAlign = 0;
994 bool HaveLoad = false;
995 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end(); UI != UE;
996 ++UI) {
997 LoadInst *LI = dyn_cast<LoadInst>(*UI);
998 if (LI == 0 || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +0000999 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001000
Chandler Carruthf0546402013-07-18 07:15:00 +00001001 // For now we only allow loads in the same block as the PHI. This is
1002 // a common case that happens when instcombine merges two loads through
1003 // a PHI.
1004 if (LI->getParent() != BB)
1005 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001006
Chandler Carruthf0546402013-07-18 07:15:00 +00001007 // Ensure that there are no instructions between the PHI and the load that
1008 // could store.
1009 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1010 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001011 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001012
Chandler Carruthf0546402013-07-18 07:15:00 +00001013 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1014 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001015 }
1016
Chandler Carruthf0546402013-07-18 07:15:00 +00001017 if (!HaveLoad)
1018 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001019
Chandler Carruthf0546402013-07-18 07:15:00 +00001020 // We can only transform this if it is safe to push the loads into the
1021 // predecessor blocks. The only thing to watch out for is that we can't put
1022 // a possibly trapping load in the predecessor if it is a critical edge.
1023 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1024 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1025 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001026
Chandler Carruthf0546402013-07-18 07:15:00 +00001027 // If the value is produced by the terminator of the predecessor (an
1028 // invoke) or it has side-effects, there is no valid place to put a load
1029 // in the predecessor.
1030 if (TI == InVal || TI->mayHaveSideEffects())
1031 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001032
Chandler Carruthf0546402013-07-18 07:15:00 +00001033 // If the predecessor has a single successor, then the edge isn't
1034 // critical.
1035 if (TI->getNumSuccessors() == 1)
1036 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001037
Chandler Carruthf0546402013-07-18 07:15:00 +00001038 // If this pointer is always safe to load, or if we can prove that there
1039 // is already a load in the block, then we can move the load to the pred
1040 // block.
1041 if (InVal->isDereferenceablePointer() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001042 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001043 continue;
1044
1045 return false;
1046 }
1047
1048 return true;
1049}
1050
1051static void speculatePHINodeLoads(PHINode &PN) {
1052 DEBUG(dbgs() << " original: " << PN << "\n");
1053
1054 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1055 IRBuilderTy PHIBuilder(&PN);
1056 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1057 PN.getName() + ".sroa.speculated");
1058
1059 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1060 // matter which one we get and if any differ.
1061 LoadInst *SomeLoad = cast<LoadInst>(*PN.use_begin());
1062 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1063 unsigned Align = SomeLoad->getAlignment();
1064
1065 // Rewrite all loads of the PN to use the new PHI.
1066 while (!PN.use_empty()) {
1067 LoadInst *LI = cast<LoadInst>(*PN.use_begin());
1068 LI->replaceAllUsesWith(NewPN);
1069 LI->eraseFromParent();
1070 }
1071
1072 // Inject loads into all of the pred blocks.
1073 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1074 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1075 TerminatorInst *TI = Pred->getTerminator();
1076 Value *InVal = PN.getIncomingValue(Idx);
1077 IRBuilderTy PredBuilder(TI);
1078
1079 LoadInst *Load = PredBuilder.CreateLoad(
1080 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1081 ++NumLoadsSpeculated;
1082 Load->setAlignment(Align);
1083 if (TBAATag)
1084 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1085 NewPN->addIncoming(Load, Pred);
1086 }
1087
1088 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1089 PN.eraseFromParent();
1090}
1091
1092/// Select instructions that use an alloca and are subsequently loaded can be
1093/// rewritten to load both input pointers and then select between the result,
1094/// allowing the load of the alloca to be promoted.
1095/// From this:
1096/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1097/// %V = load i32* %P2
1098/// to:
1099/// %V1 = load i32* %Alloca -> will be mem2reg'd
1100/// %V2 = load i32* %Other
1101/// %V = select i1 %cond, i32 %V1, i32 %V2
1102///
1103/// We can do this to a select if its only uses are loads and if the operand
1104/// to the select can be loaded unconditionally.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001105static bool isSafeSelectToSpeculate(SelectInst &SI, const DataLayout *DL = 0) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001106 Value *TValue = SI.getTrueValue();
1107 Value *FValue = SI.getFalseValue();
1108 bool TDerefable = TValue->isDereferenceablePointer();
1109 bool FDerefable = FValue->isDereferenceablePointer();
1110
1111 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end(); UI != UE;
1112 ++UI) {
1113 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1114 if (LI == 0 || !LI->isSimple())
1115 return false;
1116
1117 // Both operands to the select need to be dereferencable, either
1118 // absolutely (e.g. allocas) or at this point because we can see other
1119 // accesses to it.
1120 if (!TDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001121 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001122 return false;
1123 if (!FDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001124 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001125 return false;
1126 }
1127
1128 return true;
1129}
1130
1131static void speculateSelectInstLoads(SelectInst &SI) {
1132 DEBUG(dbgs() << " original: " << SI << "\n");
1133
1134 IRBuilderTy IRB(&SI);
1135 Value *TV = SI.getTrueValue();
1136 Value *FV = SI.getFalseValue();
1137 // Replace the loads of the select with a select of two loads.
1138 while (!SI.use_empty()) {
1139 LoadInst *LI = cast<LoadInst>(*SI.use_begin());
1140 assert(LI->isSimple() && "We only speculate simple loads");
1141
1142 IRB.SetInsertPoint(LI);
1143 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001144 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001145 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001146 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001147 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001148
Chandler Carruthf0546402013-07-18 07:15:00 +00001149 // Transfer alignment and TBAA info if present.
1150 TL->setAlignment(LI->getAlignment());
1151 FL->setAlignment(LI->getAlignment());
1152 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1153 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1154 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001155 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001156
1157 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1158 LI->getName() + ".sroa.speculated");
1159
1160 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1161 LI->replaceAllUsesWith(V);
1162 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001163 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001164 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001165}
1166
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001167/// \brief Build a GEP out of a base pointer and indices.
1168///
1169/// This will return the BasePtr if that is valid, or build a new GEP
1170/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001171static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001172 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001173 if (Indices.empty())
1174 return BasePtr;
1175
1176 // A single zero index is a no-op, so check for this and avoid building a GEP
1177 // in that case.
1178 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1179 return BasePtr;
1180
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001181 return IRB.CreateInBoundsGEP(BasePtr, Indices, "idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001182}
1183
1184/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1185/// TargetTy without changing the offset of the pointer.
1186///
1187/// This routine assumes we've already established a properly offset GEP with
1188/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1189/// zero-indices down through type layers until we find one the same as
1190/// TargetTy. If we can't find one with the same type, we at least try to use
1191/// one with the same size. If none of that works, we just produce the GEP as
1192/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001193static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001194 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001195 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001196 if (Ty == TargetTy)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001197 return buildGEP(IRB, BasePtr, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001198
1199 // See if we can descend into a struct and locate a field with the correct
1200 // type.
1201 unsigned NumLayers = 0;
1202 Type *ElementTy = Ty;
1203 do {
1204 if (ElementTy->isPointerTy())
1205 break;
1206 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1207 ElementTy = SeqTy->getElementType();
Chandler Carruth40617f52012-10-17 07:22:16 +00001208 // Note that we use the default address space as this index is over an
1209 // array or a vector, not a pointer.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001210 Indices.push_back(IRB.getInt(APInt(DL.getPointerSizeInBits(0), 0)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001211 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001212 if (STy->element_begin() == STy->element_end())
1213 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001214 ElementTy = *STy->element_begin();
1215 Indices.push_back(IRB.getInt32(0));
1216 } else {
1217 break;
1218 }
1219 ++NumLayers;
1220 } while (ElementTy != TargetTy);
1221 if (ElementTy != TargetTy)
1222 Indices.erase(Indices.end() - NumLayers, Indices.end());
1223
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001224 return buildGEP(IRB, BasePtr, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001225}
1226
1227/// \brief Recursively compute indices for a natural GEP.
1228///
1229/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1230/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001231static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001232 Value *Ptr, Type *Ty, APInt &Offset,
1233 Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001234 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001235 if (Offset == 0)
Chandler Carruth90a735d2013-07-19 07:21:28 +00001236 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001237
1238 // We can't recurse through pointer types.
1239 if (Ty->isPointerTy())
1240 return 0;
1241
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001242 // We try to analyze GEPs over vectors here, but note that these GEPs are
1243 // extremely poorly defined currently. The long-term goal is to remove GEPing
1244 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001245 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001246 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001247 if (ElementSizeInBits % 8)
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001248 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001249 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001250 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001251 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1252 return 0;
1253 Offset -= NumSkippedElements * ElementSize;
1254 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001255 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001256 Offset, TargetTy, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001257 }
1258
1259 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1260 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001261 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001262 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001263 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1264 return 0;
1265
1266 Offset -= NumSkippedElements * ElementSize;
1267 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001268 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001269 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001270 }
1271
1272 StructType *STy = dyn_cast<StructType>(Ty);
1273 if (!STy)
1274 return 0;
1275
Chandler Carruth90a735d2013-07-19 07:21:28 +00001276 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001277 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001278 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001279 return 0;
1280 unsigned Index = SL->getElementContainingOffset(StructOffset);
1281 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1282 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001283 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001284 return 0; // The offset points into alignment padding.
1285
1286 Indices.push_back(IRB.getInt32(Index));
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/// \brief Get a natural GEP from a base pointer to a particular offset and
1292/// resulting in a particular type.
1293///
1294/// The goal is to produce a "natural" looking GEP that works with the existing
1295/// composite types to arrive at the appropriate offset and element type for
1296/// a pointer. TargetTy is the element type the returned GEP should point-to if
1297/// possible. We recurse by decreasing Offset, adding the appropriate index to
1298/// Indices, and setting Ty to the result subtype.
1299///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001300/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001301static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001302 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001303 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001304 PointerType *Ty = cast<PointerType>(Ptr->getType());
1305
1306 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1307 // an i8.
1308 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1309 return 0;
1310
1311 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001312 if (!ElementTy->isSized())
1313 return 0; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001314 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001315 if (ElementSize == 0)
1316 return 0; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001317 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001318
1319 Offset -= NumSkippedElements * ElementSize;
1320 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001321 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001322 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001323}
1324
1325/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1326/// resulting pointer has PointerTy.
1327///
1328/// This tries very hard to compute a "natural" GEP which arrives at the offset
1329/// and produces the pointer type desired. Where it cannot, it will try to use
1330/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1331/// fails, it will try to use an existing i8* and GEP to the byte offset and
1332/// bitcast to the type.
1333///
1334/// The strategy for finding the more natural GEPs is to peel off layers of the
1335/// pointer, walking back through bit casts and GEPs, searching for a base
1336/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001337/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001338/// a single GEP as possible, thus making each GEP more independent of the
1339/// surrounding code.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001340static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001341 Value *Ptr, APInt Offset, Type *PointerTy) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001342 // Even though we don't look through PHI nodes, we could be called on an
1343 // instruction in an unreachable block, which may be on a cycle.
1344 SmallPtrSet<Value *, 4> Visited;
1345 Visited.insert(Ptr);
1346 SmallVector<Value *, 4> Indices;
1347
1348 // We may end up computing an offset pointer that has the wrong type. If we
1349 // never are able to compute one directly that has the correct type, we'll
1350 // fall back to it, so keep it around here.
1351 Value *OffsetPtr = 0;
1352
1353 // Remember any i8 pointer we come across to re-use if we need to do a raw
1354 // byte offset.
1355 Value *Int8Ptr = 0;
1356 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1357
1358 Type *TargetTy = PointerTy->getPointerElementType();
1359
1360 do {
1361 // First fold any existing GEPs into the offset.
1362 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1363 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001364 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001365 break;
1366 Offset += GEPOffset;
1367 Ptr = GEP->getPointerOperand();
1368 if (!Visited.insert(Ptr))
1369 break;
1370 }
1371
1372 // See if we can perform a natural GEP here.
1373 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001374 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001375 Indices)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001376 if (P->getType() == PointerTy) {
1377 // Zap any offset pointer that we ended up computing in previous rounds.
1378 if (OffsetPtr && OffsetPtr->use_empty())
1379 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1380 I->eraseFromParent();
1381 return P;
1382 }
1383 if (!OffsetPtr) {
1384 OffsetPtr = P;
1385 }
1386 }
1387
1388 // Stash this pointer if we've found an i8*.
1389 if (Ptr->getType()->isIntegerTy(8)) {
1390 Int8Ptr = Ptr;
1391 Int8PtrOffset = Offset;
1392 }
1393
1394 // Peel off a layer of the pointer and update the offset appropriately.
1395 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1396 Ptr = cast<Operator>(Ptr)->getOperand(0);
1397 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1398 if (GA->mayBeOverridden())
1399 break;
1400 Ptr = GA->getAliasee();
1401 } else {
1402 break;
1403 }
1404 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1405 } while (Visited.insert(Ptr));
1406
1407 if (!OffsetPtr) {
1408 if (!Int8Ptr) {
1409 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001410 "raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001411 Int8PtrOffset = Offset;
1412 }
1413
1414 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1415 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001416 "raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001417 }
1418 Ptr = OffsetPtr;
1419
1420 // On the off chance we were targeting i8*, guard the bitcast here.
1421 if (Ptr->getType() != PointerTy)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001422 Ptr = IRB.CreateBitCast(Ptr, PointerTy, "cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001423
1424 return Ptr;
1425}
1426
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001427/// \brief Test whether we can convert a value from the old to the new type.
1428///
1429/// This predicate should be used to guard calls to convertValue in order to
1430/// ensure that we only try to convert viable values. The strategy is that we
1431/// will peel off single element struct and array wrappings to get to an
1432/// underlying value, and convert that value.
1433static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1434 if (OldTy == NewTy)
1435 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001436 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1437 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1438 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1439 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001440 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1441 return false;
1442 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1443 return false;
1444
1445 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1446 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1447 return true;
1448 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1449 return true;
1450 return false;
1451 }
1452
1453 return true;
1454}
1455
1456/// \brief Generic routine to convert an SSA value to a value of a different
1457/// type.
1458///
1459/// This will try various different casting techniques, such as bitcasts,
1460/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1461/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001462static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001463 Type *Ty) {
1464 assert(canConvertValue(DL, V->getType(), Ty) &&
1465 "Value not convertable to type");
1466 if (V->getType() == Ty)
1467 return V;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001468 if (IntegerType *OldITy = dyn_cast<IntegerType>(V->getType()))
1469 if (IntegerType *NewITy = dyn_cast<IntegerType>(Ty))
1470 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1471 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001472 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1473 return IRB.CreateIntToPtr(V, Ty);
1474 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1475 return IRB.CreatePtrToInt(V, Ty);
1476
1477 return IRB.CreateBitCast(V, Ty);
1478}
1479
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001480/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001481///
1482/// This function is called to test each entry in a partioning which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001483/// for a single slice.
1484static bool isVectorPromotionViableForSlice(
1485 const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
1486 uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
1487 AllocaSlices::const_iterator I) {
1488 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001489 uint64_t BeginOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001490 std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001491 uint64_t BeginIndex = BeginOffset / ElementSize;
1492 if (BeginIndex * ElementSize != BeginOffset ||
1493 BeginIndex >= Ty->getNumElements())
1494 return false;
1495 uint64_t EndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001496 std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001497 uint64_t EndIndex = EndOffset / ElementSize;
1498 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1499 return false;
1500
1501 assert(EndIndex > BeginIndex && "Empty vector!");
1502 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001503 Type *SliceTy =
Chandler Carruthf0546402013-07-18 07:15:00 +00001504 (NumElements == 1) ? Ty->getElementType()
1505 : VectorType::get(Ty->getElementType(), NumElements);
1506
1507 Type *SplitIntTy =
1508 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1509
1510 Use *U = I->getUse();
1511
1512 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1513 if (MI->isVolatile())
1514 return false;
1515 if (!I->isSplittable())
1516 return false; // Skip any unsplittable intrinsics.
1517 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1518 // Disable vector promotion when there are loads or stores of an FCA.
1519 return false;
1520 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1521 if (LI->isVolatile())
1522 return false;
1523 Type *LTy = LI->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001524 if (SliceBeginOffset > I->beginOffset() ||
1525 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001526 assert(LTy->isIntegerTy());
1527 LTy = SplitIntTy;
1528 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001529 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001530 return false;
1531 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1532 if (SI->isVolatile())
1533 return false;
1534 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001535 if (SliceBeginOffset > I->beginOffset() ||
1536 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001537 assert(STy->isIntegerTy());
1538 STy = SplitIntTy;
1539 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001540 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001541 return false;
1542 }
1543
1544 return true;
1545}
1546
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001547/// \brief Test whether the given alloca partitioning and range of slices can be
1548/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001549///
1550/// This is a quick test to check whether we can rewrite a particular alloca
1551/// partition (and its newly formed alloca) into a vector alloca with only
1552/// whole-vector loads and stores such that it could be promoted to a vector
1553/// SSA value. We only can ensure this for a limited set of operations, and we
1554/// don't want to do the rewrites unless we are confident that the result will
1555/// be promotable, so we have an early test here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001556static bool
1557isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
1558 uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
1559 AllocaSlices::const_iterator I,
1560 AllocaSlices::const_iterator E,
1561 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001562 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1563 if (!Ty)
1564 return false;
1565
Chandler Carruth90a735d2013-07-19 07:21:28 +00001566 uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001567
1568 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1569 // that aren't byte sized.
1570 if (ElementSize % 8)
1571 return false;
Chandler Carruth90a735d2013-07-19 07:21:28 +00001572 assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
Benjamin Kramerc003a452013-01-01 16:13:35 +00001573 "vector size not a multiple of element size?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001574 ElementSize /= 8;
1575
Chandler Carruthf0546402013-07-18 07:15:00 +00001576 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001577 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1578 SliceEndOffset, Ty, ElementSize, I))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001579 return false;
1580
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001581 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1582 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001583 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001584 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1585 SliceEndOffset, Ty, ElementSize, *SUI))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001586 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001587
1588 return true;
1589}
1590
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001591/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001592///
1593/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001594/// test below on a single slice of the alloca.
1595static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1596 Type *AllocaTy,
1597 uint64_t AllocBeginOffset,
1598 uint64_t Size, AllocaSlices &S,
1599 AllocaSlices::const_iterator I,
1600 bool &WholeAllocaOp) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001601 uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
1602 uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
1603
1604 // We can't reasonably handle cases where the load or store extends past
1605 // the end of the aloca's type and into its padding.
1606 if (RelEnd > Size)
1607 return false;
1608
1609 Use *U = I->getUse();
1610
1611 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1612 if (LI->isVolatile())
1613 return false;
1614 if (RelBegin == 0 && RelEnd == Size)
1615 WholeAllocaOp = true;
1616 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001617 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001618 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001619 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001620 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001621 // Non-integer loads need to be convertible from the alloca type so that
1622 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001623 return false;
1624 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001625 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1626 Type *ValueTy = SI->getValueOperand()->getType();
1627 if (SI->isVolatile())
1628 return false;
1629 if (RelBegin == 0 && RelEnd == Size)
1630 WholeAllocaOp = true;
1631 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001632 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001633 return false;
1634 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001635 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001636 // Non-integer stores need to be convertible to the alloca type so that
1637 // they are promotable.
1638 return false;
1639 }
1640 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1641 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1642 return false;
1643 if (!I->isSplittable())
1644 return false; // Skip any unsplittable intrinsics.
1645 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1646 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1647 II->getIntrinsicID() != Intrinsic::lifetime_end)
1648 return false;
1649 } else {
1650 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001651 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001652
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001653 return true;
1654}
1655
Chandler Carruth435c4e02012-10-15 08:40:30 +00001656/// \brief Test whether the given alloca partition's integer operations can be
1657/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00001658///
Chandler Carruth435c4e02012-10-15 08:40:30 +00001659/// This is a quick test to check whether we can rewrite the integer loads and
1660/// stores to a particular alloca into wider loads and stores and be able to
1661/// promote the resulting alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +00001662static bool
Chandler Carruth90a735d2013-07-19 07:21:28 +00001663isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001664 uint64_t AllocBeginOffset, AllocaSlices &S,
1665 AllocaSlices::const_iterator I,
1666 AllocaSlices::const_iterator E,
1667 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001668 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00001669 // Don't create integer types larger than the maximum bitwidth.
1670 if (SizeInBits > IntegerType::MAX_INT_BITS)
1671 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00001672
1673 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001674 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001675 return false;
1676
Chandler Carruth58d05562012-10-25 04:37:07 +00001677 // We need to ensure that an integer type with the appropriate bitwidth can
1678 // be converted to the alloca type, whatever that is. We don't want to force
1679 // the alloca itself to have an integer type if there is a more suitable one.
1680 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001681 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1682 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00001683 return false;
1684
Chandler Carruth90a735d2013-07-19 07:21:28 +00001685 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
Chandler Carruth435c4e02012-10-15 08:40:30 +00001686
Chandler Carruthf0546402013-07-18 07:15:00 +00001687 // While examining uses, we ensure that the alloca has a covering load or
1688 // store. We don't want to widen the integer operations only to fail to
1689 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00001690 // later). However, if there are only splittable uses, go ahead and assume
1691 // that we cover the alloca.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001692 bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00001693
Chandler Carruthf0546402013-07-18 07:15:00 +00001694 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001695 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1696 S, I, WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00001697 return false;
1698
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001699 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1700 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001701 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001702 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1703 S, *SUI, WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001704 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001705
Chandler Carruth92924fd2012-09-24 00:34:20 +00001706 return WholeAllocaOp;
1707}
1708
Chandler Carruthd177f862013-03-20 07:30:36 +00001709static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001710 IntegerType *Ty, uint64_t Offset,
1711 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00001712 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001713 IntegerType *IntTy = cast<IntegerType>(V->getType());
1714 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1715 "Element extends past full value");
1716 uint64_t ShAmt = 8*Offset;
1717 if (DL.isBigEndian())
1718 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001719 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001720 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001721 DEBUG(dbgs() << " shifted: " << *V << "\n");
1722 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001723 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1724 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001725 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001726 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00001727 DEBUG(dbgs() << " trunced: " << *V << "\n");
1728 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001729 return V;
1730}
1731
Chandler Carruthd177f862013-03-20 07:30:36 +00001732static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001733 Value *V, uint64_t Offset, const Twine &Name) {
1734 IntegerType *IntTy = cast<IntegerType>(Old->getType());
1735 IntegerType *Ty = cast<IntegerType>(V->getType());
1736 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1737 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001738 DEBUG(dbgs() << " start: " << *V << "\n");
1739 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001740 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00001741 DEBUG(dbgs() << " extended: " << *V << "\n");
1742 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001743 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1744 "Element store outside of alloca store");
1745 uint64_t ShAmt = 8*Offset;
1746 if (DL.isBigEndian())
1747 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001748 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001749 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001750 DEBUG(dbgs() << " shifted: " << *V << "\n");
1751 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001752
1753 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1754 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1755 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00001756 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001757 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00001758 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001759 }
1760 return V;
1761}
1762
Chandler Carruthd177f862013-03-20 07:30:36 +00001763static Value *extractVector(IRBuilderTy &IRB, Value *V,
Chandler Carruthb6bc8742012-12-17 13:07:30 +00001764 unsigned BeginIndex, unsigned EndIndex,
1765 const Twine &Name) {
1766 VectorType *VecTy = cast<VectorType>(V->getType());
1767 unsigned NumElements = EndIndex - BeginIndex;
1768 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1769
1770 if (NumElements == VecTy->getNumElements())
1771 return V;
1772
1773 if (NumElements == 1) {
1774 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1775 Name + ".extract");
1776 DEBUG(dbgs() << " extract: " << *V << "\n");
1777 return V;
1778 }
1779
1780 SmallVector<Constant*, 8> Mask;
1781 Mask.reserve(NumElements);
1782 for (unsigned i = BeginIndex; i != EndIndex; ++i)
1783 Mask.push_back(IRB.getInt32(i));
1784 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1785 ConstantVector::get(Mask),
1786 Name + ".extract");
1787 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1788 return V;
1789}
1790
Chandler Carruthd177f862013-03-20 07:30:36 +00001791static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00001792 unsigned BeginIndex, const Twine &Name) {
1793 VectorType *VecTy = cast<VectorType>(Old->getType());
1794 assert(VecTy && "Can only insert a vector into a vector");
1795
1796 VectorType *Ty = dyn_cast<VectorType>(V->getType());
1797 if (!Ty) {
1798 // Single element to insert.
1799 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
1800 Name + ".insert");
1801 DEBUG(dbgs() << " insert: " << *V << "\n");
1802 return V;
1803 }
1804
1805 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
1806 "Too many elements!");
1807 if (Ty->getNumElements() == VecTy->getNumElements()) {
1808 assert(V->getType() == VecTy && "Vector type mismatch");
1809 return V;
1810 }
1811 unsigned EndIndex = BeginIndex + Ty->getNumElements();
1812
1813 // When inserting a smaller vector into the larger to store, we first
1814 // use a shuffle vector to widen it with undef elements, and then
1815 // a second shuffle vector to select between the loaded vector and the
1816 // incoming vector.
1817 SmallVector<Constant*, 8> Mask;
1818 Mask.reserve(VecTy->getNumElements());
1819 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1820 if (i >= BeginIndex && i < EndIndex)
1821 Mask.push_back(IRB.getInt32(i - BeginIndex));
1822 else
1823 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
1824 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1825 ConstantVector::get(Mask),
1826 Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00001827 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001828
1829 Mask.clear();
1830 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00001831 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
1832
1833 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
1834
1835 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001836 return V;
1837}
1838
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001839namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001840/// \brief Visitor to rewrite instructions using p particular slice of an alloca
1841/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001842///
1843/// Also implements the rewriting to vector-based accesses when the partition
1844/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1845/// lives here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001846class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001847 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001848 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
1849 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001850
Chandler Carruth90a735d2013-07-19 07:21:28 +00001851 const DataLayout &DL;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001852 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001853 SROA &Pass;
1854 AllocaInst &OldAI, &NewAI;
1855 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00001856 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001857
1858 // If we are rewriting an alloca partition which can be written as pure
1859 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001860 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001861 // - The new alloca is exactly the size of the vector type here.
1862 // - The accesses all either map to the entire vector or to a single
1863 // element.
1864 // - The set of accessing instructions is only one of those handled above
1865 // in isVectorPromotionViable. Generally these are the same access kinds
1866 // which are promotable via mem2reg.
1867 VectorType *VecTy;
1868 Type *ElementTy;
1869 uint64_t ElementSize;
1870
Chandler Carruth92924fd2012-09-24 00:34:20 +00001871 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth435c4e02012-10-15 08:40:30 +00001872 // alloca's integer operations should be widened to this integer type due to
1873 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruth92924fd2012-09-24 00:34:20 +00001874 // integer type will be stored here for easy access during rewriting.
Chandler Carruth435c4e02012-10-15 08:40:30 +00001875 IntegerType *IntTy;
Chandler Carruth92924fd2012-09-24 00:34:20 +00001876
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001877 // The offset of the slice currently being rewritten.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001878 uint64_t BeginOffset, EndOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001879 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001880 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00001881 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001882 Instruction *OldPtr;
1883
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001884 // Utility IR builder, whose name prefix is setup for each visited use, and
1885 // the insertion point is set to point to the user.
1886 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001887
1888public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001889 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
1890 AllocaInst &OldAI, AllocaInst &NewAI,
1891 uint64_t NewBeginOffset, uint64_t NewEndOffset,
1892 bool IsVectorPromotable = false,
1893 bool IsIntegerPromotable = false)
1894 : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthf0546402013-07-18 07:15:00 +00001895 NewAllocaBeginOffset(NewBeginOffset), NewAllocaEndOffset(NewEndOffset),
1896 NewAllocaTy(NewAI.getAllocatedType()),
1897 VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : 0),
1898 ElementTy(VecTy ? VecTy->getElementType() : 0),
Chandler Carruth90a735d2013-07-19 07:21:28 +00001899 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00001900 IntTy(IsIntegerPromotable
1901 ? Type::getIntNTy(
1902 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00001903 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001904 : 0),
1905 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
1906 OldPtr(), IRB(NewAI.getContext(), ConstantFolder()) {
1907 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001908 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00001909 "Only multiple-of-8 sized vector elements are viable");
1910 ++NumVectorized;
1911 }
1912 assert((!IsVectorPromotable && !IsIntegerPromotable) ||
1913 IsVectorPromotable != IsIntegerPromotable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001914 }
1915
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001916 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001917 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00001918 BeginOffset = I->beginOffset();
1919 EndOffset = I->endOffset();
1920 IsSplittable = I->isSplittable();
1921 IsSplit =
1922 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001923
Chandler Carruthf0546402013-07-18 07:15:00 +00001924 OldUse = I->getUse();
1925 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001926
Chandler Carruthf0546402013-07-18 07:15:00 +00001927 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
1928 IRB.SetInsertPoint(OldUserI);
1929 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
1930 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
1931
1932 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
1933 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001934 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001935 return CanSROA;
1936 }
1937
1938private:
Chandler Carruthf0546402013-07-18 07:15:00 +00001939 // Make sure the other visit overloads are visible.
1940 using Base::visit;
1941
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001942 // Every instruction which can end up as a user must have a rewrite rule.
1943 bool visitInstruction(Instruction &I) {
1944 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
1945 llvm_unreachable("No rewrite rule for this instruction!");
1946 }
1947
Chandler Carruthf0546402013-07-18 07:15:00 +00001948 Value *getAdjustedAllocaPtr(IRBuilderTy &IRB, uint64_t Offset,
1949 Type *PointerTy) {
1950 assert(Offset >= NewAllocaBeginOffset);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001951 return getAdjustedPtr(IRB, DL, &NewAI, APInt(DL.getPointerSizeInBits(),
Chandler Carruthf0546402013-07-18 07:15:00 +00001952 Offset - NewAllocaBeginOffset),
1953 PointerTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001954 }
1955
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001956 /// \brief Compute suitable alignment to access an offset into the new alloca.
1957 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth176ca712012-10-01 12:16:54 +00001958 unsigned NewAIAlign = NewAI.getAlignment();
1959 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00001960 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth176ca712012-10-01 12:16:54 +00001961 return MinAlign(NewAIAlign, Offset);
1962 }
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001963
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001964 /// \brief Compute suitable alignment to access a type at an offset of the
1965 /// new alloca.
1966 ///
1967 /// \returns zero if the type's ABI alignment is a suitable alignment,
1968 /// otherwise returns the maximal suitable alignment.
1969 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
1970 unsigned Align = getOffsetAlign(Offset);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001971 return Align == DL.getABITypeAlignment(Ty) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001972 }
1973
Chandler Carruth845b73c2012-11-21 08:16:30 +00001974 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001975 assert(VecTy && "Can only call getIndex when rewriting a vector");
1976 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1977 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
1978 uint32_t Index = RelOffset / ElementSize;
1979 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00001980 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001981 }
1982
1983 void deleteIfTriviallyDead(Value *V) {
1984 Instruction *I = cast<Instruction>(V);
1985 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00001986 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001987 }
1988
Chandler Carruthf0546402013-07-18 07:15:00 +00001989 Value *rewriteVectorizedLoadInst(uint64_t NewBeginOffset,
1990 uint64_t NewEndOffset) {
1991 unsigned BeginIndex = getIndex(NewBeginOffset);
1992 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00001993 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00001994
1995 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001996 "load");
1997 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00001998 }
1999
Chandler Carruthf0546402013-07-18 07:15:00 +00002000 Value *rewriteIntegerLoad(LoadInst &LI, uint64_t NewBeginOffset,
2001 uint64_t NewEndOffset) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002002 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002003 assert(!LI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002004 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002005 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002006 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002007 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2008 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2009 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002010 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002011 "extract");
Chandler Carruth18db7952012-11-20 01:12:50 +00002012 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002013 }
2014
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002015 bool visitLoadInst(LoadInst &LI) {
2016 DEBUG(dbgs() << " original: " << LI << "\n");
2017 Value *OldOp = LI.getOperand(0);
2018 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002019
Chandler Carruthf0546402013-07-18 07:15:00 +00002020 // Compute the intersecting offset range.
2021 assert(BeginOffset < NewAllocaEndOffset);
2022 assert(EndOffset > NewAllocaBeginOffset);
2023 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2024 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2025
2026 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth3e994a22012-11-20 10:02:19 +00002027
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002028 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), Size * 8)
2029 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002030 bool IsPtrAdjusted = false;
2031 Value *V;
2032 if (VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002033 V = rewriteVectorizedLoadInst(NewBeginOffset, NewEndOffset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002034 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002035 V = rewriteIntegerLoad(LI, NewBeginOffset, NewEndOffset);
2036 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002037 canConvertValue(DL, NewAllocaTy, LI.getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002038 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002039 LI.isVolatile(), "load");
Chandler Carruth18db7952012-11-20 01:12:50 +00002040 } else {
2041 Type *LTy = TargetTy->getPointerTo();
Chandler Carruthf0546402013-07-18 07:15:00 +00002042 V = IRB.CreateAlignedLoad(
2043 getAdjustedAllocaPtr(IRB, NewBeginOffset, LTy),
2044 getOffsetTypeAlign(TargetTy, NewBeginOffset - NewAllocaBeginOffset),
2045 LI.isVolatile(), "load");
Chandler Carruth18db7952012-11-20 01:12:50 +00002046 IsPtrAdjusted = true;
2047 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002048 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002049
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002050 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002051 assert(!LI.isVolatile());
2052 assert(LI.getType()->isIntegerTy() &&
2053 "Only integer type loads and stores are split");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002054 assert(Size < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002055 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002056 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002057 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002058 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002059 // Move the insertion point just past the load so that we can refer to it.
2060 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002061 // Create a placeholder value with the same type as LI to use as the
2062 // basis for the new value. This allows us to replace the uses of LI with
2063 // the computed value, and then replace the placeholder with LI, leaving
2064 // LI only used for this computation.
2065 Value *Placeholder
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002066 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth90a735d2013-07-19 07:21:28 +00002067 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002068 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002069 LI.replaceAllUsesWith(V);
2070 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002071 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002072 } else {
2073 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002074 }
2075
Chandler Carruth18db7952012-11-20 01:12:50 +00002076 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002077 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002078 DEBUG(dbgs() << " to: " << *V << "\n");
2079 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002080 }
2081
Chandler Carruthf0546402013-07-18 07:15:00 +00002082 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2083 uint64_t NewBeginOffset,
2084 uint64_t NewEndOffset) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002085 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002086 unsigned BeginIndex = getIndex(NewBeginOffset);
2087 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002088 assert(EndIndex > BeginIndex && "Empty vector!");
2089 unsigned NumElements = EndIndex - BeginIndex;
2090 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002091 Type *SliceTy =
2092 (NumElements == 1) ? ElementTy
2093 : VectorType::get(ElementTy, NumElements);
2094 if (V->getType() != SliceTy)
2095 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002096
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002097 // Mix in the existing elements.
2098 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2099 "load");
2100 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2101 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002102 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002103 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002104
2105 (void)Store;
2106 DEBUG(dbgs() << " to: " << *Store << "\n");
2107 return true;
2108 }
2109
Chandler Carruthf0546402013-07-18 07:15:00 +00002110 bool rewriteIntegerStore(Value *V, StoreInst &SI,
2111 uint64_t NewBeginOffset, uint64_t NewEndOffset) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002112 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002113 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002114 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002115 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002116 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002117 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002118 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2119 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002120 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002121 "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002122 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002123 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002124 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002125 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002126 (void)Store;
2127 DEBUG(dbgs() << " to: " << *Store << "\n");
2128 return true;
2129 }
2130
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002131 bool visitStoreInst(StoreInst &SI) {
2132 DEBUG(dbgs() << " original: " << SI << "\n");
2133 Value *OldOp = SI.getOperand(1);
2134 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002135
Chandler Carruth18db7952012-11-20 01:12:50 +00002136 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002137
Chandler Carruthac8317f2012-10-04 12:33:50 +00002138 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2139 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002140 if (V->getType()->isPointerTy())
2141 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002142 Pass.PostPromotionWorklist.insert(AI);
2143
Chandler Carruthf0546402013-07-18 07:15:00 +00002144 // Compute the intersecting offset range.
2145 assert(BeginOffset < NewAllocaEndOffset);
2146 assert(EndOffset > NewAllocaBeginOffset);
2147 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2148 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2149
2150 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002151 if (Size < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002152 assert(!SI.isVolatile());
2153 assert(V->getType()->isIntegerTy() &&
2154 "Only integer type loads and stores are split");
2155 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002156 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002157 "Non-byte-multiple bit width");
Chandler Carruth18db7952012-11-20 01:12:50 +00002158 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002159 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002160 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002161 }
2162
Chandler Carruth18db7952012-11-20 01:12:50 +00002163 if (VecTy)
Chandler Carruthf0546402013-07-18 07:15:00 +00002164 return rewriteVectorizedStoreInst(V, SI, OldOp, NewBeginOffset,
2165 NewEndOffset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002166 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthf0546402013-07-18 07:15:00 +00002167 return rewriteIntegerStore(V, SI, NewBeginOffset, NewEndOffset);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002168
Chandler Carruth18db7952012-11-20 01:12:50 +00002169 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002170 if (NewBeginOffset == NewAllocaBeginOffset &&
2171 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002172 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2173 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002174 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2175 SI.isVolatile());
2176 } else {
Chandler Carruthf0546402013-07-18 07:15:00 +00002177 Value *NewPtr = getAdjustedAllocaPtr(IRB, NewBeginOffset,
2178 V->getType()->getPointerTo());
2179 NewSI = IRB.CreateAlignedStore(
2180 V, NewPtr, getOffsetTypeAlign(
2181 V->getType(), NewBeginOffset - NewAllocaBeginOffset),
2182 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002183 }
2184 (void)NewSI;
2185 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002186 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002187
2188 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2189 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002190 }
2191
Chandler Carruth514f34f2012-12-17 04:07:30 +00002192 /// \brief Compute an integer value from splatting an i8 across the given
2193 /// number of bytes.
2194 ///
2195 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2196 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002197 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002198 ///
2199 /// \param V The i8 value to splat.
2200 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002201 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002202 assert(Size > 0 && "Expected a positive number of bytes.");
2203 IntegerType *VTy = cast<IntegerType>(V->getType());
2204 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2205 if (Size == 1)
2206 return V;
2207
2208 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002209 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
Chandler Carruth514f34f2012-12-17 04:07:30 +00002210 ConstantExpr::getUDiv(
2211 Constant::getAllOnesValue(SplatIntTy),
2212 ConstantExpr::getZExt(
2213 Constant::getAllOnesValue(V->getType()),
2214 SplatIntTy)),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002215 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002216 return V;
2217 }
2218
Chandler Carruthccca5042012-12-17 04:07:37 +00002219 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002220 Value *getVectorSplat(Value *V, unsigned NumElements) {
2221 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002222 DEBUG(dbgs() << " splat: " << *V << "\n");
2223 return V;
2224 }
2225
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002226 bool visitMemSetInst(MemSetInst &II) {
2227 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002228 assert(II.getRawDest() == OldPtr);
2229
2230 // If the memset has a variable size, it cannot be split, just adjust the
2231 // pointer to the new alloca.
2232 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002233 assert(!IsSplit);
2234 assert(BeginOffset >= NewAllocaBeginOffset);
2235 II.setDest(
2236 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002237 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002238 II.setAlignment(ConstantInt::get(CstTy, getOffsetAlign(BeginOffset)));
Chandler Carruth208124f2012-09-26 10:59:22 +00002239
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002240 deleteIfTriviallyDead(OldPtr);
2241 return false;
2242 }
2243
2244 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002245 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002246
2247 Type *AllocaTy = NewAI.getAllocatedType();
2248 Type *ScalarTy = AllocaTy->getScalarType();
2249
Chandler Carruthf0546402013-07-18 07:15:00 +00002250 // Compute the intersecting offset range.
2251 assert(BeginOffset < NewAllocaEndOffset);
2252 assert(EndOffset > NewAllocaBeginOffset);
2253 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2254 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002255 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00002256
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002257 // If this doesn't map cleanly onto the alloca type, and that type isn't
2258 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002259 if (!VecTy && !IntTy &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002260 (BeginOffset > NewAllocaBeginOffset ||
2261 EndOffset < NewAllocaEndOffset ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002262 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002263 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2264 DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002265 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002266 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2267 CallInst *New = IRB.CreateMemSet(
2268 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getRawDest()->getType()),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002269 II.getValue(), Size, getOffsetAlign(SliceOffset), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002270 (void)New;
2271 DEBUG(dbgs() << " to: " << *New << "\n");
2272 return false;
2273 }
2274
2275 // If we can represent this as a simple value, we have to build the actual
2276 // value to store, which requires expanding the byte present in memset to
2277 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002278 // splatting the byte to a sufficiently wide integer, splatting it across
2279 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002280 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002281
Chandler Carruthccca5042012-12-17 04:07:37 +00002282 if (VecTy) {
2283 // If this is a memset of a vectorized alloca, insert it.
2284 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002285
Chandler Carruthf0546402013-07-18 07:15:00 +00002286 unsigned BeginIndex = getIndex(NewBeginOffset);
2287 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002288 assert(EndIndex > BeginIndex && "Empty vector!");
2289 unsigned NumElements = EndIndex - BeginIndex;
2290 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2291
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002292 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002293 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2294 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002295 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002296 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002297
Chandler Carruthce4562b2012-12-17 13:41:21 +00002298 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002299 "oldload");
2300 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002301 } else if (IntTy) {
2302 // If this is a memset on an alloca where we can widen stores, insert the
2303 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002304 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002305
Chandler Carruthf0546402013-07-18 07:15:00 +00002306 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002307 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002308
2309 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2310 EndOffset != NewAllocaBeginOffset)) {
2311 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002312 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002313 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002314 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002315 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002316 } else {
2317 assert(V->getType() == IntTy &&
2318 "Wrong type for an alloca wide integer!");
2319 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002320 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002321 } else {
2322 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002323 assert(NewBeginOffset == NewAllocaBeginOffset);
2324 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002325
Chandler Carruth90a735d2013-07-19 07:21:28 +00002326 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002327 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002328 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002329
Chandler Carruth90a735d2013-07-19 07:21:28 +00002330 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002331 }
2332
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002333 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002334 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002335 (void)New;
2336 DEBUG(dbgs() << " to: " << *New << "\n");
2337 return !II.isVolatile();
2338 }
2339
2340 bool visitMemTransferInst(MemTransferInst &II) {
2341 // Rewriting of memory transfer instructions can be a bit tricky. We break
2342 // them into two categories: split intrinsics and unsplit intrinsics.
2343
2344 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002345
Chandler Carruthf0546402013-07-18 07:15:00 +00002346 // Compute the intersecting offset range.
2347 assert(BeginOffset < NewAllocaEndOffset);
2348 assert(EndOffset > NewAllocaBeginOffset);
2349 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2350 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2351
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002352 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2353 bool IsDest = II.getRawDest() == OldPtr;
2354
Chandler Carruth176ca712012-10-01 12:16:54 +00002355 // Compute the relative offset within the transfer.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002356 unsigned IntPtrWidth = DL.getPointerSizeInBits();
Chandler Carruthf0546402013-07-18 07:15:00 +00002357 APInt RelOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Chandler Carruth176ca712012-10-01 12:16:54 +00002358
2359 unsigned Align = II.getAlignment();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002360 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth176ca712012-10-01 12:16:54 +00002361 if (Align > 1)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002362 Align =
2363 MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2364 MinAlign(II.getAlignment(), getOffsetAlign(SliceOffset)));
Chandler Carruth176ca712012-10-01 12:16:54 +00002365
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002366 // For unsplit intrinsics, we simply modify the source and destination
2367 // pointers in place. This isn't just an optimization, it is a matter of
2368 // correctness. With unsplit intrinsics we may be dealing with transfers
2369 // within a single alloca before SROA ran, or with transfers that have
2370 // a variable length. We may also be dealing with memmove instead of
2371 // memcpy, and so simply updating the pointers is the necessary for us to
2372 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002373 if (!IsSplittable) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002374 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2375 if (IsDest)
Chandler Carruthf0546402013-07-18 07:15:00 +00002376 II.setDest(
2377 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002378 else
Chandler Carruthf0546402013-07-18 07:15:00 +00002379 II.setSource(getAdjustedAllocaPtr(IRB, BeginOffset,
2380 II.getRawSource()->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002381
Chandler Carruth208124f2012-09-26 10:59:22 +00002382 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth176ca712012-10-01 12:16:54 +00002383 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruth208124f2012-09-26 10:59:22 +00002384
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002385 DEBUG(dbgs() << " to: " << II << "\n");
2386 deleteIfTriviallyDead(OldOp);
2387 return false;
2388 }
2389 // For split transfer intrinsics we have an incredibly useful assurance:
2390 // the source and destination do not reside within the same alloca, and at
2391 // least one of them does not escape. This means that we can replace
2392 // memmove with memcpy, and we don't need to worry about all manner of
2393 // downsides to splitting and transforming the operations.
2394
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002395 // If this doesn't map cleanly onto the alloca type, and that type isn't
2396 // a single value type, just emit a memcpy.
2397 bool EmitMemCpy
Chandler Carruthf0546402013-07-18 07:15:00 +00002398 = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
2399 EndOffset < NewAllocaEndOffset ||
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002400 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002401
2402 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2403 // size hasn't been shrunk based on analysis of the viable range, this is
2404 // a no-op.
2405 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002406 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002407 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002408
2409 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002410 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002411 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002412 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002413 return false;
2414 }
2415 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002416 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002417
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002418 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2419 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002420 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002421 if (AllocaInst *AI
2422 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002423 Pass.Worklist.insert(AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002424
2425 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002426 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2427 : II.getRawDest()->getType();
2428
2429 // Compute the other pointer, folding as much as possible to produce
2430 // a single, simple GEP in most cases.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002431 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002432
Chandler Carruthf0546402013-07-18 07:15:00 +00002433 Value *OurPtr = getAdjustedAllocaPtr(
2434 IRB, NewBeginOffset,
2435 IsDest ? II.getRawDest()->getType() : II.getRawSource()->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002436 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002437 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002438
2439 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2440 IsDest ? OtherPtr : OurPtr,
Chandler Carruth871ba722012-09-26 10:27:46 +00002441 Size, Align, II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002442 (void)New;
2443 DEBUG(dbgs() << " to: " << *New << "\n");
2444 return false;
2445 }
2446
Chandler Carruth08e5f492012-10-03 08:26:28 +00002447 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2448 // is equivalent to 1, but that isn't true if we end up rewriting this as
2449 // a load or store.
2450 if (!Align)
2451 Align = 1;
2452
Chandler Carruthf0546402013-07-18 07:15:00 +00002453 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2454 NewEndOffset == NewAllocaEndOffset;
2455 uint64_t Size = NewEndOffset - NewBeginOffset;
2456 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2457 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002458 unsigned NumElements = EndIndex - BeginIndex;
2459 IntegerType *SubIntTy
2460 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2461
2462 Type *OtherPtrTy = NewAI.getType();
2463 if (VecTy && !IsWholeAlloca) {
2464 if (NumElements == 1)
2465 OtherPtrTy = VecTy->getElementType();
2466 else
2467 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2468
2469 OtherPtrTy = OtherPtrTy->getPointerTo();
2470 } else if (IntTy && !IsWholeAlloca) {
2471 OtherPtrTy = SubIntTy->getPointerTo();
2472 }
2473
Chandler Carruth90a735d2013-07-19 07:21:28 +00002474 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002475 Value *DstPtr = &NewAI;
2476 if (!IsDest)
2477 std::swap(SrcPtr, DstPtr);
2478
2479 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002480 if (VecTy && !IsWholeAlloca && !IsDest) {
2481 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002482 "load");
2483 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002484 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002485 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002486 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002487 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002488 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002489 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002490 } else {
Chandler Carruth871ba722012-09-26 10:27:46 +00002491 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002492 "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002493 }
2494
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002495 if (VecTy && !IsWholeAlloca && IsDest) {
2496 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002497 "oldload");
2498 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002499 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002500 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002501 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002502 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002503 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002504 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2505 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002506 }
2507
Chandler Carruth871ba722012-09-26 10:27:46 +00002508 StoreInst *Store = cast<StoreInst>(
2509 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2510 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002511 DEBUG(dbgs() << " to: " << *Store << "\n");
2512 return !II.isVolatile();
2513 }
2514
2515 bool visitIntrinsicInst(IntrinsicInst &II) {
2516 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2517 II.getIntrinsicID() == Intrinsic::lifetime_end);
2518 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002519 assert(II.getArgOperand(1) == OldPtr);
2520
Chandler Carruthf0546402013-07-18 07:15:00 +00002521 // Compute the intersecting offset range.
2522 assert(BeginOffset < NewAllocaEndOffset);
2523 assert(EndOffset > NewAllocaBeginOffset);
2524 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2525 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2526
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002527 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002528 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002529
2530 ConstantInt *Size
2531 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002532 NewEndOffset - NewBeginOffset);
2533 Value *Ptr =
2534 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getArgOperand(1)->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002535 Value *New;
2536 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2537 New = IRB.CreateLifetimeStart(Ptr, Size);
2538 else
2539 New = IRB.CreateLifetimeEnd(Ptr, Size);
2540
Edwin Vane82f80d42013-01-29 17:42:24 +00002541 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002542 DEBUG(dbgs() << " to: " << *New << "\n");
2543 return true;
2544 }
2545
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002546 bool visitPHINode(PHINode &PN) {
2547 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00002548 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2549 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002550
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002551 // We would like to compute a new pointer in only one place, but have it be
2552 // as local as possible to the PHI. To do that, we re-use the location of
2553 // the old pointer, which necessarily must be in the right position to
2554 // dominate the PHI.
Chandler Carruthd177f862013-03-20 07:30:36 +00002555 IRBuilderTy PtrBuilder(cast<Instruction>(OldPtr));
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002556 PtrBuilder.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) +
2557 ".");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002558
Chandler Carruthf0546402013-07-18 07:15:00 +00002559 Value *NewPtr =
2560 getAdjustedAllocaPtr(PtrBuilder, BeginOffset, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002561 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002562 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002563
Chandler Carruth82a57542012-10-01 10:54:05 +00002564 DEBUG(dbgs() << " to: " << PN << "\n");
2565 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002566
2567 // Check whether we can speculate this PHI node, and if so remember that
2568 // fact and return that this alloca remains viable for promotion to an SSA
2569 // value.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002570 if (isSafePHIToSpeculate(PN, &DL)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002571 Pass.SpeculatablePHIs.insert(&PN);
2572 return true;
2573 }
2574
2575 return false; // PHIs can't be promoted on their own.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002576 }
2577
2578 bool visitSelectInst(SelectInst &SI) {
2579 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002580 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2581 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00002582 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2583 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002584
Chandler Carruthf0546402013-07-18 07:15:00 +00002585 Value *NewPtr = getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002586 // Replace the operands which were using the old pointer.
2587 if (SI.getOperand(1) == OldPtr)
2588 SI.setOperand(1, NewPtr);
2589 if (SI.getOperand(2) == OldPtr)
2590 SI.setOperand(2, NewPtr);
2591
Chandler Carruth82a57542012-10-01 10:54:05 +00002592 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002593 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002594
2595 // Check whether we can speculate this select instruction, and if so
2596 // remember that fact and return that this alloca remains viable for
2597 // promotion to an SSA value.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002598 if (isSafeSelectToSpeculate(SI, &DL)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002599 Pass.SpeculatableSelects.insert(&SI);
2600 return true;
2601 }
2602
2603 return false; // Selects can't be promoted on their own.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002604 }
2605
2606};
2607}
2608
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002609namespace {
2610/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2611///
2612/// This pass aggressively rewrites all aggregate loads and stores on
2613/// a particular pointer (or any pointer derived from it which we can identify)
2614/// with scalar loads and stores.
2615class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2616 // Befriend the base class so it can delegate to private visit methods.
2617 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2618
Chandler Carruth90a735d2013-07-19 07:21:28 +00002619 const DataLayout &DL;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002620
2621 /// Queue of pointer uses to analyze and potentially rewrite.
2622 SmallVector<Use *, 8> Queue;
2623
2624 /// Set to prevent us from cycling with phi nodes and loops.
2625 SmallPtrSet<User *, 8> Visited;
2626
2627 /// The current pointer use being rewritten. This is used to dig up the used
2628 /// value (as opposed to the user).
2629 Use *U;
2630
2631public:
Chandler Carruth90a735d2013-07-19 07:21:28 +00002632 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002633
2634 /// Rewrite loads and stores through a pointer and all pointers derived from
2635 /// it.
2636 bool rewrite(Instruction &I) {
2637 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2638 enqueueUsers(I);
2639 bool Changed = false;
2640 while (!Queue.empty()) {
2641 U = Queue.pop_back_val();
2642 Changed |= visit(cast<Instruction>(U->getUser()));
2643 }
2644 return Changed;
2645 }
2646
2647private:
2648 /// Enqueue all the users of the given instruction for further processing.
2649 /// This uses a set to de-duplicate users.
2650 void enqueueUsers(Instruction &I) {
2651 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2652 ++UI)
2653 if (Visited.insert(*UI))
2654 Queue.push_back(&UI.getUse());
2655 }
2656
2657 // Conservative default is to not rewrite anything.
2658 bool visitInstruction(Instruction &I) { return false; }
2659
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002660 /// \brief Generic recursive split emission class.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002661 template <typename Derived>
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002662 class OpSplitter {
2663 protected:
2664 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00002665 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002666 /// The indices which to be used with insert- or extractvalue to select the
2667 /// appropriate value within the aggregate.
2668 SmallVector<unsigned, 4> Indices;
2669 /// The indices to a GEP instruction which will move Ptr to the correct slot
2670 /// within the aggregate.
2671 SmallVector<Value *, 4> GEPIndices;
2672 /// The base pointer of the original op, used as a base for GEPing the
2673 /// split operations.
2674 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002675
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002676 /// Initialize the splitter with an insertion point, Ptr and start with a
2677 /// single zero GEP index.
2678 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002679 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002680
2681 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002682 /// \brief Generic recursive split emission routine.
2683 ///
2684 /// This method recursively splits an aggregate op (load or store) into
2685 /// scalar or vector ops. It splits recursively until it hits a single value
2686 /// and emits that single value operation via the template argument.
2687 ///
2688 /// The logic of this routine relies on GEPs and insertvalue and
2689 /// extractvalue all operating with the same fundamental index list, merely
2690 /// formatted differently (GEPs need actual values).
2691 ///
2692 /// \param Ty The type being split recursively into smaller ops.
2693 /// \param Agg The aggregate value being built up or stored, depending on
2694 /// whether this is splitting a load or a store respectively.
2695 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2696 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002697 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002698
2699 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2700 unsigned OldSize = Indices.size();
2701 (void)OldSize;
2702 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2703 ++Idx) {
2704 assert(Indices.size() == OldSize && "Did not return to the old size");
2705 Indices.push_back(Idx);
2706 GEPIndices.push_back(IRB.getInt32(Idx));
2707 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2708 GEPIndices.pop_back();
2709 Indices.pop_back();
2710 }
2711 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002712 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002713
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002714 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2715 unsigned OldSize = Indices.size();
2716 (void)OldSize;
2717 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2718 ++Idx) {
2719 assert(Indices.size() == OldSize && "Did not return to the old size");
2720 Indices.push_back(Idx);
2721 GEPIndices.push_back(IRB.getInt32(Idx));
2722 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2723 GEPIndices.pop_back();
2724 Indices.pop_back();
2725 }
2726 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002727 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002728
2729 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002730 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002731 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002732
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002733 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002734 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002735 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002736
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002737 /// Emit a leaf load of a single value. This is called at the leaves of the
2738 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002739 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002740 assert(Ty->isSingleValueType());
2741 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00002742 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2743 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002744 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2745 DEBUG(dbgs() << " to: " << *Load << "\n");
2746 }
2747 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002748
2749 bool visitLoadInst(LoadInst &LI) {
2750 assert(LI.getPointerOperand() == *U);
2751 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2752 return false;
2753
2754 // We have an aggregate being loaded, split it apart.
2755 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002756 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002757 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002758 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002759 LI.replaceAllUsesWith(V);
2760 LI.eraseFromParent();
2761 return true;
2762 }
2763
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002764 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002765 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002766 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002767
2768 /// Emit a leaf store of a single value. This is called at the leaves of the
2769 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002770 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002771 assert(Ty->isSingleValueType());
2772 // Extract the single value and store it using the indices.
2773 Value *Store = IRB.CreateStore(
2774 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2775 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2776 (void)Store;
2777 DEBUG(dbgs() << " to: " << *Store << "\n");
2778 }
2779 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002780
2781 bool visitStoreInst(StoreInst &SI) {
2782 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2783 return false;
2784 Value *V = SI.getValueOperand();
2785 if (V->getType()->isSingleValueType())
2786 return false;
2787
2788 // We have an aggregate being stored, split it apart.
2789 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002790 StoreOpSplitter Splitter(&SI, *U);
2791 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002792 SI.eraseFromParent();
2793 return true;
2794 }
2795
2796 bool visitBitCastInst(BitCastInst &BC) {
2797 enqueueUsers(BC);
2798 return false;
2799 }
2800
2801 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2802 enqueueUsers(GEPI);
2803 return false;
2804 }
2805
2806 bool visitPHINode(PHINode &PN) {
2807 enqueueUsers(PN);
2808 return false;
2809 }
2810
2811 bool visitSelectInst(SelectInst &SI) {
2812 enqueueUsers(SI);
2813 return false;
2814 }
2815};
2816}
2817
Chandler Carruthba931992012-10-13 10:49:33 +00002818/// \brief Strip aggregate type wrapping.
2819///
2820/// This removes no-op aggregate types wrapping an underlying type. It will
2821/// strip as many layers of types as it can without changing either the type
2822/// size or the allocated size.
2823static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
2824 if (Ty->isSingleValueType())
2825 return Ty;
2826
2827 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2828 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
2829
2830 Type *InnerTy;
2831 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
2832 InnerTy = ArrTy->getElementType();
2833 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2834 const StructLayout *SL = DL.getStructLayout(STy);
2835 unsigned Index = SL->getElementContainingOffset(0);
2836 InnerTy = STy->getElementType(Index);
2837 } else {
2838 return Ty;
2839 }
2840
2841 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
2842 TypeSize > DL.getTypeSizeInBits(InnerTy))
2843 return Ty;
2844
2845 return stripAggregateTypeWrapping(DL, InnerTy);
2846}
2847
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002848/// \brief Try to find a partition of the aggregate type passed in for a given
2849/// offset and size.
2850///
2851/// This recurses through the aggregate type and tries to compute a subtype
2852/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00002853/// of an array, it will even compute a new array type for that sub-section,
2854/// and the same for structs.
2855///
2856/// Note that this routine is very strict and tries to find a partition of the
2857/// type which produces the *exact* right offset and size. It is not forgiving
2858/// when the size or offset cause either end of type-based partition to be off.
2859/// Also, this is a best-effort routine. It is reasonable to give up and not
2860/// return a type if necessary.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002861static Type *getTypePartition(const DataLayout &DL, Type *Ty,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002862 uint64_t Offset, uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002863 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
2864 return stripAggregateTypeWrapping(DL, Ty);
2865 if (Offset > DL.getTypeAllocSize(Ty) ||
2866 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Chandler Carruth58d05562012-10-25 04:37:07 +00002867 return 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002868
2869 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2870 // We can't partition pointers...
2871 if (SeqTy->isPointerTy())
2872 return 0;
2873
2874 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00002875 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002876 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002877 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002878 if (NumSkippedElements >= ArrTy->getNumElements())
2879 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002880 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002881 if (NumSkippedElements >= VecTy->getNumElements())
2882 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002883 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002884 Offset -= NumSkippedElements * ElementSize;
2885
2886 // First check if we need to recurse.
2887 if (Offset > 0 || Size < ElementSize) {
2888 // Bail if the partition ends in a different array element.
2889 if ((Offset + Size) > ElementSize)
2890 return 0;
2891 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002892 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002893 }
2894 assert(Offset == 0);
2895
2896 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002897 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002898 assert(Size > ElementSize);
2899 uint64_t NumElements = Size / ElementSize;
2900 if (NumElements * ElementSize != Size)
2901 return 0;
2902 return ArrayType::get(ElementTy, NumElements);
2903 }
2904
2905 StructType *STy = dyn_cast<StructType>(Ty);
2906 if (!STy)
2907 return 0;
2908
Chandler Carruth90a735d2013-07-19 07:21:28 +00002909 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00002910 if (Offset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002911 return 0;
2912 uint64_t EndOffset = Offset + Size;
2913 if (EndOffset > SL->getSizeInBytes())
2914 return 0;
2915
2916 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002917 Offset -= SL->getElementOffset(Index);
2918
2919 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002920 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002921 if (Offset >= ElementSize)
2922 return 0; // The offset points into alignment padding.
2923
2924 // See if any partition must be contained by the element.
2925 if (Offset > 0 || Size < ElementSize) {
2926 if ((Offset + Size) > ElementSize)
2927 return 0;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002928 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002929 }
2930 assert(Offset == 0);
2931
2932 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002933 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002934
2935 StructType::element_iterator EI = STy->element_begin() + Index,
2936 EE = STy->element_end();
2937 if (EndOffset < SL->getSizeInBytes()) {
2938 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
2939 if (Index == EndIndex)
2940 return 0; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00002941
2942 // Don't try to form "natural" types if the elements don't line up with the
2943 // expected size.
2944 // FIXME: We could potentially recurse down through the last element in the
2945 // sub-struct to find a natural end point.
2946 if (SL->getElementOffset(EndIndex) != EndOffset)
2947 return 0;
2948
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002949 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002950 EE = STy->element_begin() + EndIndex;
2951 }
2952
2953 // Try to build up a sub-structure.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002954 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002955 STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002956 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00002957 if (Size != SubSL->getSizeInBytes())
2958 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002959
Chandler Carruth054a40a2012-09-14 11:08:31 +00002960 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002961}
2962
2963/// \brief Rewrite an alloca partition's users.
2964///
2965/// This routine drives both of the rewriting goals of the SROA pass. It tries
2966/// to rewrite uses of an alloca partition to be conducive for SSA value
2967/// promotion. If the partition needs a new, more refined alloca, this will
2968/// build that new alloca, preserving as much type information as possible, and
2969/// rewrite the uses of the old alloca to point at the new one and have the
2970/// appropriate new offsets. It also evaluates how successful the rewrite was
2971/// at enabling promotion and if it was successful queues the alloca to be
2972/// promoted.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002973bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
2974 AllocaSlices::iterator B, AllocaSlices::iterator E,
2975 int64_t BeginOffset, int64_t EndOffset,
2976 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002977 assert(BeginOffset < EndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002978 uint64_t SliceSize = EndOffset - BeginOffset;
Chandler Carruth82a57542012-10-01 10:54:05 +00002979
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002980 // Try to compute a friendly type for this partition of the alloca. This
2981 // won't always succeed, in which case we fall back to a legal integer type
2982 // or an i8 array of an appropriate size.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002983 Type *SliceTy = 0;
Chandler Carruthf0546402013-07-18 07:15:00 +00002984 if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002985 if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
2986 SliceTy = CommonUseTy;
2987 if (!SliceTy)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002988 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002989 BeginOffset, SliceSize))
2990 SliceTy = TypePartitionTy;
2991 if ((!SliceTy || (SliceTy->isArrayTy() &&
2992 SliceTy->getArrayElementType()->isIntegerTy())) &&
2993 DL->isLegalInteger(SliceSize * 8))
2994 SliceTy = Type::getIntNTy(*C, SliceSize * 8);
2995 if (!SliceTy)
2996 SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
2997 assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
Chandler Carruthf0546402013-07-18 07:15:00 +00002998
2999 bool IsVectorPromotable = isVectorPromotionViable(
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003000 *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
Chandler Carruthf0546402013-07-18 07:15:00 +00003001
3002 bool IsIntegerPromotable =
3003 !IsVectorPromotable &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003004 isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003005
3006 // Check for the case where we're going to rewrite to a new alloca of the
3007 // exact same type as the original, and with the same access offsets. In that
3008 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003009 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003010 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003011 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003012 assert(BeginOffset == 0 &&
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003013 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003014 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003015 // FIXME: We should be able to bail at this point with "nothing changed".
3016 // FIXME: We might want to defer PHI speculation until after here.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003017 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003018 unsigned Alignment = AI.getAlignment();
3019 if (!Alignment) {
3020 // The minimum alignment which users can rely on when the explicit
3021 // alignment is omitted or zero is that required by the ABI for this
3022 // type.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003023 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003024 }
Chandler Carruthf0546402013-07-18 07:15:00 +00003025 Alignment = MinAlign(Alignment, BeginOffset);
Chandler Carruth903790e2012-09-29 10:41:21 +00003026 // If we will get at least this much alignment from the type alone, leave
3027 // the alloca's alignment unconstrained.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003028 if (Alignment <= DL->getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003029 Alignment = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003030 NewAI = new AllocaInst(SliceTy, 0, Alignment,
3031 AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003032 ++NumNewAllocas;
3033 }
3034
3035 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthf0546402013-07-18 07:15:00 +00003036 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3037 << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003038
Chandler Carruthf0546402013-07-18 07:15:00 +00003039 // Track the high watermark on several worklists that are only relevant for
3040 // promoted allocas. We will reset it to this point if the alloca is not in
3041 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003042 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruthf0546402013-07-18 07:15:00 +00003043 unsigned SPOldSize = SpeculatablePHIs.size();
3044 unsigned SSOldSize = SpeculatableSelects.size();
Chandler Carruthac8317f2012-10-04 12:33:50 +00003045
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003046 AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
3047 EndOffset, IsVectorPromotable,
3048 IsIntegerPromotable);
Chandler Carruthf0546402013-07-18 07:15:00 +00003049 bool Promotable = true;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003050 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
3051 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00003052 SUI != SUE; ++SUI) {
3053 DEBUG(dbgs() << " rewriting split ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003054 DEBUG(S.printSlice(dbgs(), *SUI, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003055 Promotable &= Rewriter.visit(*SUI);
3056 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003057 for (AllocaSlices::iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003058 DEBUG(dbgs() << " rewriting ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003059 DEBUG(S.printSlice(dbgs(), I, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003060 Promotable &= Rewriter.visit(I);
3061 }
3062
3063 if (Promotable && (SpeculatablePHIs.size() > SPOldSize ||
3064 SpeculatableSelects.size() > SSOldSize)) {
3065 // If we have a promotable alloca except for some unspeculated loads below
3066 // PHIs or Selects, iterate once. We will speculate the loads and on the
3067 // next iteration rewrite them into a promotable form.
3068 Worklist.insert(NewAI);
3069 } else if (Promotable) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003070 DEBUG(dbgs() << " and queuing for promotion\n");
3071 PromotableAllocas.push_back(NewAI);
3072 } else if (NewAI != &AI) {
3073 // If we can't promote the alloca, iterate on it to check for new
3074 // refinements exposed by splitting the current alloca. Don't iterate on an
3075 // alloca which didn't actually change and didn't get promoted.
Chandler Carruthf0546402013-07-18 07:15:00 +00003076 // FIXME: We should actually track whether the rewriter changed anything.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003077 Worklist.insert(NewAI);
3078 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003079
3080 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthf0546402013-07-18 07:15:00 +00003081 if (!Promotable) {
Chandler Carruthac8317f2012-10-04 12:33:50 +00003082 while (PostPromotionWorklist.size() > PPWOldSize)
3083 PostPromotionWorklist.pop_back();
Chandler Carruthf0546402013-07-18 07:15:00 +00003084 while (SpeculatablePHIs.size() > SPOldSize)
3085 SpeculatablePHIs.pop_back();
3086 while (SpeculatableSelects.size() > SSOldSize)
3087 SpeculatableSelects.pop_back();
3088 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003089
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003090 return true;
3091}
3092
Chandler Carruthf0546402013-07-18 07:15:00 +00003093namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003094struct IsSliceEndLessOrEqualTo {
3095 uint64_t UpperBound;
Chandler Carruthf0546402013-07-18 07:15:00 +00003096
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003097 IsSliceEndLessOrEqualTo(uint64_t UpperBound) : UpperBound(UpperBound) {}
Chandler Carruthf0546402013-07-18 07:15:00 +00003098
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003099 bool operator()(const AllocaSlices::iterator &I) {
3100 return I->endOffset() <= UpperBound;
3101 }
3102};
Chandler Carruthf0546402013-07-18 07:15:00 +00003103}
3104
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003105static void
3106removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3107 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003108 if (Offset >= MaxSplitUseEndOffset) {
3109 SplitUses.clear();
3110 MaxSplitUseEndOffset = 0;
3111 return;
3112 }
3113
3114 size_t SplitUsesOldSize = SplitUses.size();
3115 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003116 IsSliceEndLessOrEqualTo(Offset)),
Chandler Carruthf0546402013-07-18 07:15:00 +00003117 SplitUses.end());
3118 if (SplitUsesOldSize == SplitUses.size())
3119 return;
3120
3121 // Recompute the max. While this is linear, so is remove_if.
3122 MaxSplitUseEndOffset = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003123 for (SmallVectorImpl<AllocaSlices::iterator>::iterator
Chandler Carruthf0546402013-07-18 07:15:00 +00003124 SUI = SplitUses.begin(),
3125 SUE = SplitUses.end();
3126 SUI != SUE; ++SUI)
3127 MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
3128}
3129
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003130/// \brief Walks the slices of an alloca and form partitions based on them,
3131/// rewriting each of their uses.
3132bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
3133 if (S.begin() == S.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00003134 return false;
3135
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003136 bool Changed = false;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003137 SmallVector<AllocaSlices::iterator, 4> SplitUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003138 uint64_t MaxSplitUseEndOffset = 0;
3139
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003140 uint64_t BeginOffset = S.begin()->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003141
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003142 for (AllocaSlices::iterator SI = S.begin(), SJ = llvm::next(SI), SE = S.end();
3143 SI != SE; SI = SJ) {
3144 uint64_t MaxEndOffset = SI->endOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003145
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003146 if (!SI->isSplittable()) {
3147 // When we're forming an unsplittable region, it must always start at the
3148 // first slice and will extend through its end.
3149 assert(BeginOffset == SI->beginOffset());
Chandler Carruthf0546402013-07-18 07:15:00 +00003150
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003151 // Form a partition including all of the overlapping slices with this
3152 // unsplittable slice.
3153 while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3154 if (!SJ->isSplittable())
3155 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3156 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003157 }
3158 } else {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003159 assert(SI->isSplittable()); // Established above.
Chandler Carruthf0546402013-07-18 07:15:00 +00003160
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003161 // Collect all of the overlapping splittable slices.
3162 while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3163 SJ->isSplittable()) {
3164 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3165 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003166 }
3167
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003168 // Back up MaxEndOffset and SJ if we ended the span early when
3169 // encountering an unsplittable slice.
3170 if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3171 assert(!SJ->isSplittable());
3172 MaxEndOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003173 }
3174 }
3175
3176 // Check if we have managed to move the end offset forward yet. If so,
3177 // we'll have to rewrite uses and erase old split uses.
3178 if (BeginOffset < MaxEndOffset) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003179 // Rewrite a sequence of overlapping slices.
3180 Changed |=
3181 rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
Chandler Carruthf0546402013-07-18 07:15:00 +00003182
3183 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3184 }
3185
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003186 // Accumulate all the splittable slices from the [SI,SJ) region which
Chandler Carruthf0546402013-07-18 07:15:00 +00003187 // overlap going forward.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003188 for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3189 if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3190 SplitUses.push_back(SK);
3191 MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
Chandler Carruthf0546402013-07-18 07:15:00 +00003192 }
3193
3194 // If we're already at the end and we have no split uses, we're done.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003195 if (SJ == SE && SplitUses.empty())
Chandler Carruthf0546402013-07-18 07:15:00 +00003196 break;
3197
3198 // If we have no split uses or no gap in offsets, we're ready to move to
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003199 // the next slice.
3200 if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3201 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003202 continue;
3203 }
3204
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003205 // Even if we have split slices, if the next slice is splittable and the
3206 // split slices reach it, we can simply set up the beginning offset of the
3207 // next iteration to bridge between them.
3208 if (SJ != SE && SJ->isSplittable() &&
3209 MaxSplitUseEndOffset > SJ->beginOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003210 BeginOffset = MaxEndOffset;
3211 continue;
3212 }
3213
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003214 // Otherwise, we have a tail of split slices. Rewrite them with an empty
3215 // range of slices.
Chandler Carruthf0546402013-07-18 07:15:00 +00003216 uint64_t PostSplitEndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003217 SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003218
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003219 Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
3220 SplitUses);
3221 if (SJ == SE)
Chandler Carruthf0546402013-07-18 07:15:00 +00003222 break; // Skip the rest, we don't need to do any cleanup.
3223
3224 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3225 PostSplitEndOffset);
3226
3227 // Now just reset the begin offset for the next iteration.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003228 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003229 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003230
3231 return Changed;
3232}
3233
3234/// \brief Analyze an alloca for SROA.
3235///
3236/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003237/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003238/// rewritten as needed.
3239bool SROA::runOnAlloca(AllocaInst &AI) {
3240 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3241 ++NumAllocasAnalyzed;
3242
3243 // Special case dead allocas, as they're trivial.
3244 if (AI.use_empty()) {
3245 AI.eraseFromParent();
3246 return true;
3247 }
3248
3249 // Skip alloca forms that this analysis can't handle.
3250 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00003251 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003252 return false;
3253
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003254 bool Changed = false;
3255
3256 // First, split any FCA loads and stores touching this alloca to promote
3257 // better splitting and promotion opportunities.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003258 AggLoadStoreRewriter AggRewriter(*DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003259 Changed |= AggRewriter.rewrite(AI);
3260
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003261 // Build the slices using a recursive instruction-visiting builder.
3262 AllocaSlices S(*DL, AI);
3263 DEBUG(S.print(dbgs()));
3264 if (S.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003265 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003266
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003267 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003268 for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
3269 DE = S.dead_user_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003270 DI != DE; ++DI) {
3271 Changed = true;
3272 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
Chandler Carruth18db7952012-11-20 01:12:50 +00003273 DeadInsts.insert(*DI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003274 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003275 for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
3276 DE = S.dead_op_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003277 DO != DE; ++DO) {
3278 Value *OldV = **DO;
3279 // Clobber the use with an undef value.
3280 **DO = UndefValue::get(OldV->getType());
3281 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3282 if (isInstructionTriviallyDead(OldI)) {
3283 Changed = true;
Chandler Carruth18db7952012-11-20 01:12:50 +00003284 DeadInsts.insert(OldI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003285 }
3286 }
3287
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003288 // No slices to split. Leave the dead alloca for a later pass to clean up.
3289 if (S.begin() == S.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003290 return Changed;
3291
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003292 Changed |= splitAlloca(AI, S);
Chandler Carruthf0546402013-07-18 07:15:00 +00003293
3294 DEBUG(dbgs() << " Speculating PHIs\n");
3295 while (!SpeculatablePHIs.empty())
3296 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3297
3298 DEBUG(dbgs() << " Speculating Selects\n");
3299 while (!SpeculatableSelects.empty())
3300 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3301
3302 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003303}
3304
Chandler Carruth19450da2012-09-14 10:26:38 +00003305/// \brief Delete the dead instructions accumulated in this run.
3306///
3307/// Recursively deletes the dead instructions we've accumulated. This is done
3308/// at the very end to maximize locality of the recursive delete and to
3309/// minimize the problems of invalidated instruction pointers as such pointers
3310/// are used heavily in the intermediate stages of the algorithm.
3311///
3312/// We also record the alloca instructions deleted here so that they aren't
3313/// subsequently handed to mem2reg to promote.
3314void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003315 while (!DeadInsts.empty()) {
3316 Instruction *I = DeadInsts.pop_back_val();
3317 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3318
Chandler Carruth58d05562012-10-25 04:37:07 +00003319 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3320
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003321 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3322 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3323 // Zero out the operand and see if it becomes trivially dead.
3324 *OI = 0;
3325 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003326 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003327 }
3328
3329 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3330 DeletedAllocas.insert(AI);
3331
3332 ++NumDeleted;
3333 I->eraseFromParent();
3334 }
3335}
3336
Chandler Carruth70b44c52012-09-15 11:43:14 +00003337/// \brief Promote the allocas, using the best available technique.
3338///
3339/// This attempts to promote whatever allocas have been identified as viable in
3340/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3341/// If there is a domtree available, we attempt to promote using the full power
3342/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3343/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003344/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003345bool SROA::promoteAllocas(Function &F) {
3346 if (PromotableAllocas.empty())
3347 return false;
3348
3349 NumPromoted += PromotableAllocas.size();
3350
3351 if (DT && !ForceSSAUpdater) {
3352 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3353 PromoteMemToReg(PromotableAllocas, *DT);
3354 PromotableAllocas.clear();
3355 return true;
3356 }
3357
3358 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3359 SSAUpdater SSA;
3360 DIBuilder DIB(*F.getParent());
3361 SmallVector<Instruction*, 64> Insts;
3362
3363 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3364 AllocaInst *AI = PromotableAllocas[Idx];
3365 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3366 UI != UE;) {
3367 Instruction *I = cast<Instruction>(*UI++);
3368 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3369 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3370 // leading to them) here. Eventually it should use them to optimize the
3371 // scalar values produced.
3372 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3373 assert(onlyUsedByLifetimeMarkers(I) &&
3374 "Found a bitcast used outside of a lifetime marker.");
3375 while (!I->use_empty())
3376 cast<Instruction>(*I->use_begin())->eraseFromParent();
3377 I->eraseFromParent();
3378 continue;
3379 }
3380 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3381 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3382 II->getIntrinsicID() == Intrinsic::lifetime_end);
3383 II->eraseFromParent();
3384 continue;
3385 }
3386
3387 Insts.push_back(I);
3388 }
3389 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3390 Insts.clear();
3391 }
3392
3393 PromotableAllocas.clear();
3394 return true;
3395}
3396
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003397namespace {
3398 /// \brief A predicate to test whether an alloca belongs to a set.
3399 class IsAllocaInSet {
3400 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3401 const SetType &Set;
3402
3403 public:
Chandler Carruth3f57b822012-10-03 00:03:00 +00003404 typedef AllocaInst *argument_type;
3405
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003406 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth3f57b822012-10-03 00:03:00 +00003407 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003408 };
3409}
3410
3411bool SROA::runOnFunction(Function &F) {
3412 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3413 C = &F.getContext();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003414 DL = getAnalysisIfAvailable<DataLayout>();
3415 if (!DL) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003416 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3417 return false;
3418 }
Chandler Carruth70b44c52012-09-15 11:43:14 +00003419 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003420
3421 BasicBlock &EntryBB = F.getEntryBlock();
3422 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3423 I != E; ++I)
3424 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3425 Worklist.insert(AI);
3426
3427 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003428 // A set of deleted alloca instruction pointers which should be removed from
3429 // the list of promotable allocas.
3430 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3431
Chandler Carruthac8317f2012-10-04 12:33:50 +00003432 do {
3433 while (!Worklist.empty()) {
3434 Changed |= runOnAlloca(*Worklist.pop_back_val());
3435 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003436
Chandler Carruthac8317f2012-10-04 12:33:50 +00003437 // Remove the deleted allocas from various lists so that we don't try to
3438 // continue processing them.
3439 if (!DeletedAllocas.empty()) {
3440 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3441 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3442 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3443 PromotableAllocas.end(),
3444 IsAllocaInSet(DeletedAllocas)),
3445 PromotableAllocas.end());
3446 DeletedAllocas.clear();
3447 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003448 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003449
Chandler Carruthac8317f2012-10-04 12:33:50 +00003450 Changed |= promoteAllocas(F);
3451
3452 Worklist = PostPromotionWorklist;
3453 PostPromotionWorklist.clear();
3454 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003455
3456 return Changed;
3457}
3458
3459void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003460 if (RequiresDomTree)
3461 AU.addRequired<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003462 AU.setPreservesCFG();
3463}