blob: d35c3b5e836d169197420597cc578a2d0bb2dcb8 [file] [log] [blame]
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This transformation implements the well known scalar replacement of
11/// aggregates transformation. It tries to identify promotable elements of an
12/// aggregate alloca, and promote them to registers. It will also try to
13/// convert uses of an element (or set of elements) of an alloca into a vector
14/// or bitfield-style integer scalar if appropriate.
15///
16/// It works to do this with minimal slicing of the alloca so that regions
17/// which are merely transferred in and out of external memory remain unchanged
18/// and are not decomposed to scalar code.
19///
20/// Because this also performs alloca promotion, it can be thought of as also
21/// serving the purpose of SSA formation. The algorithm iterates on the
22/// function until all opportunities for promotion have been realized.
23///
24//===----------------------------------------------------------------------===//
25
26#define DEBUG_TYPE "sroa"
27#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SetVector.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/Analysis/Dominators.h"
33#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000034#include "llvm/Analysis/PtrUseVisitor.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000036#include "llvm/DIBuilder.h"
37#include "llvm/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Constants.h"
39#include "llvm/IR/DataLayout.h"
40#include "llvm/IR/DerivedTypes.h"
41#include "llvm/IR/Function.h"
42#include "llvm/IR/IRBuilder.h"
43#include "llvm/IR/Instructions.h"
44#include "llvm/IR/IntrinsicInst.h"
45#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/Operator.h"
Chandler Carruthdbd69582012-11-30 03:08:41 +000047#include "llvm/InstVisitor.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000048#include "llvm/Pass.h"
Chandler Carruth70b44c52012-09-15 11:43:14 +000049#include "llvm/Support/CommandLine.h"
Chandler Carruthf0546402013-07-18 07:15:00 +000050#include "llvm/Support/Compiler.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000051#include "llvm/Support/Debug.h"
52#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000053#include "llvm/Support/MathExtras.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000054#include "llvm/Support/raw_ostream.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000055#include "llvm/Transforms/Utils/Local.h"
56#include "llvm/Transforms/Utils/PromoteMemToReg.h"
57#include "llvm/Transforms/Utils/SSAUpdater.h"
58using namespace llvm;
59
60STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000061STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +000062STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
63STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
64STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000065STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
66STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000067STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000068STATISTIC(NumDeleted, "Number of instructions deleted");
69STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000070
Chandler Carruth70b44c52012-09-15 11:43:14 +000071/// Hidden option to force the pass to not use DomTree and mem2reg, instead
72/// forming SSA values through the SSAUpdater infrastructure.
73static cl::opt<bool>
74ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
75
Chandler Carruth1b398ae2012-09-14 09:22:59 +000076namespace {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000077/// \brief A custom IRBuilder inserter which prefixes all names if they are
78/// preserved.
79template <bool preserveNames = true>
80class IRBuilderPrefixedInserter :
81 public IRBuilderDefaultInserter<preserveNames> {
82 std::string Prefix;
83
84public:
85 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
86
87protected:
88 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
89 BasicBlock::iterator InsertPt) const {
90 IRBuilderDefaultInserter<preserveNames>::InsertHelper(
91 I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
92 }
93};
94
95// Specialization for not preserving the name is trivial.
96template <>
97class IRBuilderPrefixedInserter<false> :
98 public IRBuilderDefaultInserter<false> {
99public:
100 void SetNamePrefix(const Twine &P) {}
101};
102
Chandler Carruthd177f862013-03-20 07:30:36 +0000103/// \brief Provide a typedef for IRBuilder that drops names in release builds.
104#ifndef NDEBUG
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000105typedef llvm::IRBuilder<true, ConstantFolder,
106 IRBuilderPrefixedInserter<true> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000107#else
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000108typedef llvm::IRBuilder<false, ConstantFolder,
109 IRBuilderPrefixedInserter<false> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000110#endif
111}
112
113namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000114/// \brief A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000115///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000116/// This structure represents a slice of an alloca used by some instruction. It
117/// stores both the begin and end offsets of this use, a pointer to the use
118/// itself, and a flag indicating whether we can classify the use as splittable
119/// or not when forming partitions of the alloca.
120class Slice {
Chandler Carruthf74654d2013-03-18 08:36:46 +0000121 /// \brief The beginning offset of the range.
122 uint64_t BeginOffset;
123
124 /// \brief The ending offset, not included in the range.
125 uint64_t EndOffset;
126
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000127 /// \brief Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000128 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000129 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000130
131public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000132 Slice() : BeginOffset(), EndOffset() {}
133 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000134 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000135 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000136
137 uint64_t beginOffset() const { return BeginOffset; }
138 uint64_t endOffset() const { return EndOffset; }
139
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000140 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
141 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000142
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000143 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000144
145 bool isDead() const { return getUse() == 0; }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000146 void kill() { UseAndIsSplittable.setPointer(0); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000147
148 /// \brief Support for ordering ranges.
149 ///
150 /// This provides an ordering over ranges such that start offsets are
151 /// always increasing, and within equal start offsets, the end offsets are
152 /// decreasing. Thus the spanning range comes first in a cluster with the
153 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000154 bool operator<(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000155 if (beginOffset() < RHS.beginOffset()) return true;
156 if (beginOffset() > RHS.beginOffset()) return false;
157 if (isSplittable() != RHS.isSplittable()) return !isSplittable();
158 if (endOffset() > RHS.endOffset()) return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000159 return false;
160 }
161
162 /// \brief Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000163 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000164 uint64_t RHSOffset) {
165 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000166 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000167 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000168 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000169 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000170 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000171
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000172 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000173 return isSplittable() == RHS.isSplittable() &&
174 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000175 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000176 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000177};
Chandler Carruthf0546402013-07-18 07:15:00 +0000178} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000179
180namespace llvm {
Chandler Carruthf0546402013-07-18 07:15:00 +0000181template <typename T> struct isPodLike;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000182template <> struct isPodLike<Slice> {
Chandler Carruthf0546402013-07-18 07:15:00 +0000183 static const bool value = true;
184};
Chandler Carruthf74654d2013-03-18 08:36:46 +0000185}
186
187namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000188/// \brief Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000189///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000190/// This class represents the slices of an alloca which are formed by its
191/// various uses. If a pointer escapes, we can't fully build a representation
192/// for the slices used and we reflect that in this structure. The uses are
193/// stored, sorted by increasing beginning offset and with unsplittable slices
194/// starting at a particular offset before splittable slices.
195class AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000196public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000197 /// \brief Construct the slices of a particular alloca.
198 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000199
200 /// \brief Test whether a pointer to the allocation escapes our analysis.
201 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000202 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000203 /// ignored.
204 bool isEscaped() const { return PointerEscapingInstr; }
205
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000206 /// \brief Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000207 /// @{
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000208 typedef SmallVectorImpl<Slice>::iterator iterator;
209 iterator begin() { return Slices.begin(); }
210 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000211
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000212 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
213 const_iterator begin() const { return Slices.begin(); }
214 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000215 /// @}
216
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000217 /// \brief Allow iterating the dead users for this alloca.
218 ///
219 /// These are instructions which will never actually use the alloca as they
220 /// are outside the allocated range. They are safe to replace with undef and
221 /// delete.
222 /// @{
223 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
224 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
225 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
226 /// @}
227
Chandler Carruth93a21e72012-09-14 10:18:49 +0000228 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000229 ///
230 /// These are operands which have cannot actually be used to refer to the
231 /// alloca as they are outside its range and the user doesn't correct for
232 /// that. These mostly consist of PHI node inputs and the like which we just
233 /// need to replace with undef.
234 /// @{
235 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
236 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
237 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
238 /// @}
239
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000240#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000241 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000242 void printSlice(raw_ostream &OS, const_iterator I,
243 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000244 void printUse(raw_ostream &OS, const_iterator I,
245 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000246 void print(raw_ostream &OS) const;
NAKAMURA Takumi4bbca0b2012-09-14 10:06:10 +0000247 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
248 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000249#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000250
251private:
252 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000253 class SliceBuilder;
254 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000255
Chandler Carruthd31370e2013-07-28 09:05:49 +0000256#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000257 /// \brief Handle to alloca instruction to simplify method interfaces.
258 AllocaInst &AI;
Chandler Carruthd31370e2013-07-28 09:05:49 +0000259#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000260
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000261 /// \brief The instruction responsible for this alloca not having a known set
262 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000263 ///
264 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000265 /// store a pointer to that here and abort trying to form slices of the
266 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000267 Instruction *PointerEscapingInstr;
268
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000269 /// \brief The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000270 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000271 /// We store a vector of the slices formed by uses of the alloca here. This
272 /// vector is sorted by increasing begin offset, and then the unsplittable
273 /// slices before the splittable ones. See the Slice inner class for more
274 /// details.
275 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000276
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000277 /// \brief Instructions which will become dead if we rewrite the alloca.
278 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000279 /// Note that these are not separated by slice. This is because we expect an
280 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
281 /// all these instructions can simply be removed and replaced with undef as
282 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000283 SmallVector<Instruction *, 8> DeadUsers;
284
285 /// \brief Operands which will become dead if we rewrite the alloca.
286 ///
287 /// These are operands that in their particular use can be replaced with
288 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
289 /// to PHI nodes and the like. They aren't entirely dead (there might be
290 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
291 /// want to swap this particular input for undef to simplify the use lists of
292 /// the alloca.
293 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000294};
295}
296
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000297static Value *foldSelectInst(SelectInst &SI) {
298 // If the condition being selected on is a constant or the same value is
299 // being selected between, fold the select. Yes this does (rarely) happen
300 // early on.
301 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
302 return SI.getOperand(1+CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000303 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000304 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000305
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000306 return 0;
307}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000308
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000309/// \brief Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000310///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000311/// This class builds a set of alloca slices by recursively visiting the uses
312/// of an alloca and making a slice for each load and store at each offset.
313class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
314 friend class PtrUseVisitor<SliceBuilder>;
315 friend class InstVisitor<SliceBuilder>;
316 typedef PtrUseVisitor<SliceBuilder> Base;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000317
318 const uint64_t AllocSize;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000319 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000320
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000321 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000322 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
323
324 /// \brief Set to de-duplicate dead instructions found in the use walk.
325 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000326
327public:
Chandler Carruthd31370e2013-07-28 09:05:49 +0000328 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &S)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000329 : PtrUseVisitor<SliceBuilder>(DL),
Chandler Carruthd31370e2013-07-28 09:05:49 +0000330 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), S(S) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000331
332private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000333 void markAsDead(Instruction &I) {
334 if (VisitedDeadInsts.insert(&I))
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000335 S.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000336 }
337
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000338 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000339 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000340 // Completely skip uses which have a zero size or start either before or
341 // past the end of the allocation.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000342 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000343 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000344 << " which has zero size or starts outside of the "
345 << AllocSize << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000346 << " alloca: " << S.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000347 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000348 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000349 }
350
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000351 uint64_t BeginOffset = Offset.getZExtValue();
352 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000353
354 // Clamp the end offset to the end of the allocation. Note that this is
355 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000356 // This may appear superficially to be something we could ignore entirely,
357 // but that is not so! There may be widened loads or PHI-node uses where
358 // some instructions are dead but not others. We can't completely ignore
359 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000360 assert(AllocSize >= BeginOffset); // Established above.
361 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000362 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
363 << " to remain within the " << AllocSize << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000364 << " alloca: " << S.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000365 << " use: " << I << "\n");
366 EndOffset = AllocSize;
367 }
368
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000369 S.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000370 }
371
372 void visitBitCastInst(BitCastInst &BC) {
373 if (BC.use_empty())
374 return markAsDead(BC);
375
376 return Base::visitBitCastInst(BC);
377 }
378
379 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
380 if (GEPI.use_empty())
381 return markAsDead(GEPI);
382
383 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000384 }
385
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000386 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000387 uint64_t Size, bool IsVolatile) {
Chandler Carruth58d05562012-10-25 04:37:07 +0000388 // We allow splitting of loads and stores where the type is an integer type
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000389 // and cover the entire alloca. This prevents us from splitting over
390 // eagerly.
391 // FIXME: In the great blue eventually, we should eagerly split all integer
392 // loads and stores, and then have a separate step that merges adjacent
393 // alloca partitions into a single partition suitable for integer widening.
394 // Or we should skip the merge step and rely on GVN and other passes to
395 // merge adjacent loads and stores that survive mem2reg.
396 bool IsSplittable =
397 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
Chandler Carruth58d05562012-10-25 04:37:07 +0000398
399 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000400 }
401
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000402 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000403 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
404 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000405
406 if (!IsOffsetKnown)
407 return PI.setAborted(&LI);
408
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000409 uint64_t Size = DL.getTypeStoreSize(LI.getType());
410 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000411 }
412
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000413 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000414 Value *ValOp = SI.getValueOperand();
415 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000416 return PI.setEscapedAndAborted(&SI);
417 if (!IsOffsetKnown)
418 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000419
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000420 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
421
422 // If this memory access can be shown to *statically* extend outside the
423 // bounds of of the allocation, it's behavior is undefined, so simply
424 // ignore it. Note that this is more strict than the generic clamping
425 // behavior of insertUse. We also try to handle cases which might run the
426 // risk of overflow.
427 // FIXME: We should instead consider the pointer to have escaped if this
428 // function is being instrumented for addressing bugs or race conditions.
429 if (Offset.isNegative() || Size > AllocSize ||
430 Offset.ugt(AllocSize - Size)) {
431 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
432 << " which extends past the end of the " << AllocSize
433 << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000434 << " alloca: " << S.AI << "\n"
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000435 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000436 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000437 }
438
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000439 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
440 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000441 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000442 }
443
444
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000445 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000446 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000447 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000448 if ((Length && Length->getValue() == 0) ||
449 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
450 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000451 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000452
453 if (!IsOffsetKnown)
454 return PI.setAborted(&II);
455
456 insertUse(II, Offset,
457 Length ? Length->getLimitedValue()
458 : AllocSize - Offset.getLimitedValue(),
459 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000460 }
461
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000462 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000463 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000464 if ((Length && Length->getValue() == 0) ||
465 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000466 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000467 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000468
469 if (!IsOffsetKnown)
470 return PI.setAborted(&II);
471
472 uint64_t RawOffset = Offset.getLimitedValue();
473 uint64_t Size = Length ? Length->getLimitedValue()
474 : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000475
Chandler Carruthf0546402013-07-18 07:15:00 +0000476 // Check for the special case where the same exact value is used for both
477 // source and dest.
478 if (*U == II.getRawDest() && *U == II.getRawSource()) {
479 // For non-volatile transfers this is a no-op.
480 if (!II.isVolatile())
481 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000482
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000483 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000484 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000485
Chandler Carruthf0546402013-07-18 07:15:00 +0000486 // If we have seen both source and destination for a mem transfer, then
487 // they both point to the same alloca.
488 bool Inserted;
489 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
490 llvm::tie(MTPI, Inserted) =
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000491 MemTransferSliceMap.insert(std::make_pair(&II, S.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000492 unsigned PrevIdx = MTPI->second;
493 if (!Inserted) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000494 Slice &PrevP = S.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000495
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000496 // Check if the begin offsets match and this is a non-volatile transfer.
497 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000498 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
499 PrevP.kill();
500 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000501 }
502
503 // Otherwise we have an offset transfer within the same alloca. We can't
504 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000505 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000506 }
507
Chandler Carruthe3899f22013-07-15 17:36:21 +0000508 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000509 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000510
Chandler Carruthf0546402013-07-18 07:15:00 +0000511 // Check that we ended up with a valid index in the map.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000512 assert(S.Slices[PrevIdx].getUse()->getUser() == &II &&
513 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000514 }
515
516 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000517 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000518 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000519 void visitIntrinsicInst(IntrinsicInst &II) {
520 if (!IsOffsetKnown)
521 return PI.setAborted(&II);
522
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000523 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
524 II.getIntrinsicID() == Intrinsic::lifetime_end) {
525 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000526 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
527 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000528 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000529 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000530 }
531
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000532 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000533 }
534
535 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
536 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000537 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000538 // are considered unsplittable and the size is the maximum loaded or stored
539 // size.
540 SmallPtrSet<Instruction *, 4> Visited;
541 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
542 Visited.insert(Root);
543 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruth8b907e82012-09-25 10:03:40 +0000544 // If there are no loads or stores, the access is dead. We mark that as
545 // a size zero access.
546 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000547 do {
548 Instruction *I, *UsedI;
549 llvm::tie(UsedI, I) = Uses.pop_back_val();
550
551 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000552 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000553 continue;
554 }
555 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
556 Value *Op = SI->getOperand(0);
557 if (Op == UsedI)
558 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000559 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000560 continue;
561 }
562
563 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
564 if (!GEP->hasAllZeroIndices())
565 return GEP;
566 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
567 !isa<SelectInst>(I)) {
568 return I;
569 }
570
571 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
572 ++UI)
573 if (Visited.insert(cast<Instruction>(*UI)))
574 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
575 } while (!Uses.empty());
576
577 return 0;
578 }
579
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000580 void visitPHINode(PHINode &PN) {
581 if (PN.use_empty())
Chandler Carruthf0546402013-07-18 07:15:00 +0000582 return markAsDead(PN);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000583 if (!IsOffsetKnown)
584 return PI.setAborted(&PN);
585
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000586 // See if we already have computed info on this node.
Chandler Carruthf0546402013-07-18 07:15:00 +0000587 uint64_t &PHISize = PHIOrSelectSizes[&PN];
588 if (!PHISize) {
589 // This is a new PHI node, check for an unsafe use of the PHI node.
590 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHISize))
591 return PI.setAborted(UnsafeI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000592 }
593
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000594 // For PHI and select operands outside the alloca, we can't nuke the entire
595 // phi or select -- the other side might still be relevant, so we special
596 // case them here and use a separate structure to track the operands
597 // themselves which should be replaced with undef.
Chandler Carruthf0546402013-07-18 07:15:00 +0000598 // FIXME: This should instead be escaped in the event we're instrumenting
599 // for address sanitization.
600 if ((Offset.isNegative() && (-Offset).uge(PHISize)) ||
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000601 (!Offset.isNegative() && Offset.uge(AllocSize))) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000602 S.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000603 return;
604 }
605
Chandler Carruthf0546402013-07-18 07:15:00 +0000606 insertUse(PN, Offset, PHISize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000607 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000608
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000609 void visitSelectInst(SelectInst &SI) {
610 if (SI.use_empty())
611 return markAsDead(SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000612 if (Value *Result = foldSelectInst(SI)) {
Chandler Carruthd31370e2013-07-28 09:05:49 +0000613 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000614 // If the result of the constant fold will be the pointer, recurse
615 // through the select as if we had RAUW'ed it.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000616 enqueueUsers(SI);
Chandler Carruthd31370e2013-07-28 09:05:49 +0000617 else
Chandler Carruth225d4bd2012-09-21 23:36:40 +0000618 // Otherwise the operand to the select is dead, and we can replace it
619 // with undef.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000620 S.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000621
622 return;
623 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000624 if (!IsOffsetKnown)
625 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000626
Chandler Carruthf0546402013-07-18 07:15:00 +0000627 // See if we already have computed info on this node.
628 uint64_t &SelectSize = PHIOrSelectSizes[&SI];
629 if (!SelectSize) {
630 // This is a new Select, check for an unsafe use of it.
631 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectSize))
632 return PI.setAborted(UnsafeI);
633 }
634
635 // For PHI and select operands outside the alloca, we can't nuke the entire
636 // phi or select -- the other side might still be relevant, so we special
637 // case them here and use a separate structure to track the operands
638 // themselves which should be replaced with undef.
639 // FIXME: This should instead be escaped in the event we're instrumenting
640 // for address sanitization.
641 if ((Offset.isNegative() && Offset.uge(SelectSize)) ||
642 (!Offset.isNegative() && Offset.uge(AllocSize))) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000643 S.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +0000644 return;
645 }
646
647 insertUse(SI, Offset, SelectSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000648 }
649
Chandler Carruthf0546402013-07-18 07:15:00 +0000650 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000651 void visitInstruction(Instruction &I) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000652 PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000653 }
654};
655
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000656AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Chandler Carruthd31370e2013-07-28 09:05:49 +0000657 :
658#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
659 AI(AI),
660#endif
661 PointerEscapingInstr(0) {
662 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000663 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000664 if (PtrI.isEscaped() || PtrI.isAborted()) {
665 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000666 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000667 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
668 : PtrI.getAbortingInst();
669 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000670 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000671 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000672
Benjamin Kramer08e50702013-07-20 08:38:34 +0000673 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
674 std::mem_fun_ref(&Slice::isDead)),
675 Slices.end());
676
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000677 // Sort the uses. This arranges for the offsets to be in ascending order,
678 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000679 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000680}
681
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000682#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
683
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000684void AllocaSlices::print(raw_ostream &OS, const_iterator I,
685 StringRef Indent) const {
686 printSlice(OS, I, Indent);
Chandler Carruthf0546402013-07-18 07:15:00 +0000687 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000688}
689
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000690void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
691 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000692 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000693 << " slice #" << (I - begin())
Chandler Carruthf0546402013-07-18 07:15:00 +0000694 << (I->isSplittable() ? " (splittable)" : "") << "\n";
695}
696
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000697void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
698 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000699 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000700}
701
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000702void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000703 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000704 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000705 << " A pointer to this alloca escaped by:\n"
706 << " " << *PointerEscapingInstr << "\n";
707 return;
708 }
709
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000710 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +0000711 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000712 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000713}
714
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000715void AllocaSlices::dump(const_iterator I) const { print(dbgs(), I); }
716void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000717
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000718#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
719
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000720namespace {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000721/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
722///
723/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
724/// the loads and stores of an alloca instruction, as well as updating its
725/// debug information. This is used when a domtree is unavailable and thus
726/// mem2reg in its full form can't be used to handle promotion of allocas to
727/// scalar values.
728class AllocaPromoter : public LoadAndStorePromoter {
729 AllocaInst &AI;
730 DIBuilder &DIB;
731
732 SmallVector<DbgDeclareInst *, 4> DDIs;
733 SmallVector<DbgValueInst *, 4> DVIs;
734
735public:
Chandler Carruth45b136f2013-08-11 01:03:18 +0000736 AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
Chandler Carruth70b44c52012-09-15 11:43:14 +0000737 AllocaInst &AI, DIBuilder &DIB)
Chandler Carruth45b136f2013-08-11 01:03:18 +0000738 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
Chandler Carruth70b44c52012-09-15 11:43:14 +0000739
740 void run(const SmallVectorImpl<Instruction*> &Insts) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +0000741 // Retain the debug information attached to the alloca for use when
742 // rewriting loads and stores.
Chandler Carruth70b44c52012-09-15 11:43:14 +0000743 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
744 for (Value::use_iterator UI = DebugNode->use_begin(),
745 UE = DebugNode->use_end();
746 UI != UE; ++UI)
747 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
748 DDIs.push_back(DDI);
749 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
750 DVIs.push_back(DVI);
751 }
752
753 LoadAndStorePromoter::run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +0000754
755 // While we have the debug information, clear it off of the alloca. The
756 // caller takes care of deleting the alloca.
Chandler Carruth70b44c52012-09-15 11:43:14 +0000757 while (!DDIs.empty())
758 DDIs.pop_back_val()->eraseFromParent();
759 while (!DVIs.empty())
760 DVIs.pop_back_val()->eraseFromParent();
761 }
762
763 virtual bool isInstInList(Instruction *I,
764 const SmallVectorImpl<Instruction*> &Insts) const {
Chandler Carruthc17283b2013-08-11 01:56:15 +0000765 Value *Ptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000766 if (LoadInst *LI = dyn_cast<LoadInst>(I))
Chandler Carruthc17283b2013-08-11 01:56:15 +0000767 Ptr = LI->getOperand(0);
768 else
769 Ptr = cast<StoreInst>(I)->getPointerOperand();
770
771 // Only used to detect cycles, which will be rare and quickly found as
772 // we're walking up a chain of defs rather than down through uses.
773 SmallPtrSet<Value *, 4> Visited;
774
775 do {
776 if (Ptr == &AI)
777 return true;
778
779 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
780 Ptr = BCI->getOperand(0);
781 else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
782 Ptr = GEPI->getPointerOperand();
783 else
784 return false;
785
786 } while (Visited.insert(Ptr));
787
788 return false;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000789 }
790
791 virtual void updateDebugInfo(Instruction *Inst) const {
Craig Topper31ee5862013-07-03 15:07:05 +0000792 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000793 E = DDIs.end(); I != E; ++I) {
794 DbgDeclareInst *DDI = *I;
795 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
796 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
797 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
798 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
799 }
Craig Topper31ee5862013-07-03 15:07:05 +0000800 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000801 E = DVIs.end(); I != E; ++I) {
802 DbgValueInst *DVI = *I;
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000803 Value *Arg = 0;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000804 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
805 // If an argument is zero extended then use argument directly. The ZExt
806 // may be zapped by an optimization pass in future.
807 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
808 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000809 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000810 Arg = dyn_cast<Argument>(SExt->getOperand(0));
811 if (!Arg)
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000812 Arg = SI->getValueOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000813 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000814 Arg = LI->getPointerOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000815 } else {
816 continue;
817 }
818 Instruction *DbgVal =
819 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
820 Inst);
821 DbgVal->setDebugLoc(DVI->getDebugLoc());
822 }
823 }
824};
825} // end anon namespace
826
827
828namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000829/// \brief An optimization pass providing Scalar Replacement of Aggregates.
830///
831/// This pass takes allocations which can be completely analyzed (that is, they
832/// don't escape) and tries to turn them into scalar SSA values. There are
833/// a few steps to this process.
834///
835/// 1) It takes allocations of aggregates and analyzes the ways in which they
836/// are used to try to split them into smaller allocations, ideally of
837/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000838/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000839/// 2) It will transform accesses into forms which are suitable for SSA value
840/// promotion. This can be replacing a memset with a scalar store of an
841/// integer value, or it can involve speculating operations on a PHI or
842/// select to be a PHI or select of the results.
843/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
844/// onto insert and extract operations on a vector value, and convert them to
845/// this form. By doing so, it will enable promotion of vector aggregates to
846/// SSA vector values.
847class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000848 const bool RequiresDomTree;
849
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000850 LLVMContext *C;
Chandler Carruth90a735d2013-07-19 07:21:28 +0000851 const DataLayout *DL;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000852 DominatorTree *DT;
853
854 /// \brief Worklist of alloca instructions to simplify.
855 ///
856 /// Each alloca in the function is added to this. Each new alloca formed gets
857 /// added to it as well to recursively simplify unless that alloca can be
858 /// directly promoted. Finally, each time we rewrite a use of an alloca other
859 /// the one being actively rewritten, we add it back onto the list if not
860 /// already present to ensure it is re-visited.
861 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
862
863 /// \brief A collection of instructions to delete.
864 /// We try to batch deletions to simplify code and make things a bit more
865 /// efficient.
Chandler Carruth18db7952012-11-20 01:12:50 +0000866 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000867
Chandler Carruthac8317f2012-10-04 12:33:50 +0000868 /// \brief Post-promotion worklist.
869 ///
870 /// Sometimes we discover an alloca which has a high probability of becoming
871 /// viable for SROA after a round of promotion takes place. In those cases,
872 /// the alloca is enqueued here for re-processing.
873 ///
874 /// Note that we have to be very careful to clear allocas out of this list in
875 /// the event they are deleted.
876 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
877
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000878 /// \brief A collection of alloca instructions we can directly promote.
879 std::vector<AllocaInst *> PromotableAllocas;
880
Chandler Carruthf0546402013-07-18 07:15:00 +0000881 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
882 ///
883 /// All of these PHIs have been checked for the safety of speculation and by
884 /// being speculated will allow promoting allocas currently in the promotable
885 /// queue.
886 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
887
888 /// \brief A worklist of select instructions to speculate prior to promoting
889 /// allocas.
890 ///
891 /// All of these select instructions have been checked for the safety of
892 /// speculation and by being speculated will allow promoting allocas
893 /// currently in the promotable queue.
894 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
895
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000896public:
Chandler Carruth70b44c52012-09-15 11:43:14 +0000897 SROA(bool RequiresDomTree = true)
898 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
Chandler Carruth90a735d2013-07-19 07:21:28 +0000899 C(0), DL(0), DT(0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000900 initializeSROAPass(*PassRegistry::getPassRegistry());
901 }
902 bool runOnFunction(Function &F);
903 void getAnalysisUsage(AnalysisUsage &AU) const;
904
905 const char *getPassName() const { return "SROA"; }
906 static char ID;
907
908private:
Chandler Carruth82a57542012-10-01 10:54:05 +0000909 friend class PHIOrSelectSpeculator;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000910 friend class AllocaSliceRewriter;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000911
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000912 bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
913 AllocaSlices::iterator B, AllocaSlices::iterator E,
914 int64_t BeginOffset, int64_t EndOffset,
915 ArrayRef<AllocaSlices::iterator> SplitUses);
916 bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000917 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth19450da2012-09-14 10:26:38 +0000918 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +0000919 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000920};
921}
922
923char SROA::ID = 0;
924
Chandler Carruth70b44c52012-09-15 11:43:14 +0000925FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
926 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000927}
928
929INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
930 false, false)
931INITIALIZE_PASS_DEPENDENCY(DominatorTree)
932INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
933 false, false)
934
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000935/// Walk the range of a partitioning looking for a common type to cover this
936/// sequence of slices.
937static Type *findCommonType(AllocaSlices::const_iterator B,
938 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +0000939 uint64_t EndOffset) {
940 Type *Ty = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000941 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000942 Use *U = I->getUse();
943 if (isa<IntrinsicInst>(*U->getUser()))
944 continue;
945 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
946 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000947
Chandler Carruthf0546402013-07-18 07:15:00 +0000948 Type *UserTy = 0;
949 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser()))
950 UserTy = LI->getType();
951 else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser()))
952 UserTy = SI->getValueOperand()->getType();
953 else
954 return 0; // Bail if we have weird uses.
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000955
Chandler Carruthf0546402013-07-18 07:15:00 +0000956 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
957 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000958 // this for split integer operations where we want to use the type of the
Chandler Carruthf0546402013-07-18 07:15:00 +0000959 // entity causing the split.
960 if (ITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
961 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000962
Chandler Carruthf0546402013-07-18 07:15:00 +0000963 // If we have found an integer type use covering the alloca, use that
964 // regardless of the other types, as integers are often used for a
965 // "bucket
966 // of bits" type.
967 return ITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +0000968 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000969
970 if (Ty && Ty != UserTy)
971 return 0;
972
973 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +0000974 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000975 return Ty;
976}
Chandler Carruthe3899f22013-07-15 17:36:21 +0000977
Chandler Carruthf0546402013-07-18 07:15:00 +0000978/// PHI instructions that use an alloca and are subsequently loaded can be
979/// rewritten to load both input pointers in the pred blocks and then PHI the
980/// results, allowing the load of the alloca to be promoted.
981/// From this:
982/// %P2 = phi [i32* %Alloca, i32* %Other]
983/// %V = load i32* %P2
984/// to:
985/// %V1 = load i32* %Alloca -> will be mem2reg'd
986/// ...
987/// %V2 = load i32* %Other
988/// ...
989/// %V = phi [i32 %V1, i32 %V2]
990///
991/// We can do this to a select if its only uses are loads and if the operands
992/// to the select can be loaded unconditionally.
993///
994/// FIXME: This should be hoisted into a generic utility, likely in
995/// Transforms/Util/Local.h
996static bool isSafePHIToSpeculate(PHINode &PN,
Chandler Carruth90a735d2013-07-19 07:21:28 +0000997 const DataLayout *DL = 0) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000998 // For now, we can only do this promotion if the load is in the same block
999 // as the PHI, and if there are no stores between the phi and load.
1000 // TODO: Allow recursive phi users.
1001 // TODO: Allow stores.
1002 BasicBlock *BB = PN.getParent();
1003 unsigned MaxAlign = 0;
1004 bool HaveLoad = false;
1005 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end(); UI != UE;
1006 ++UI) {
1007 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1008 if (LI == 0 || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001009 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001010
Chandler Carruthf0546402013-07-18 07:15:00 +00001011 // For now we only allow loads in the same block as the PHI. This is
1012 // a common case that happens when instcombine merges two loads through
1013 // a PHI.
1014 if (LI->getParent() != BB)
1015 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001016
Chandler Carruthf0546402013-07-18 07:15:00 +00001017 // Ensure that there are no instructions between the PHI and the load that
1018 // could store.
1019 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1020 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001021 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001022
Chandler Carruthf0546402013-07-18 07:15:00 +00001023 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1024 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001025 }
1026
Chandler Carruthf0546402013-07-18 07:15:00 +00001027 if (!HaveLoad)
1028 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001029
Chandler Carruthf0546402013-07-18 07:15:00 +00001030 // We can only transform this if it is safe to push the loads into the
1031 // predecessor blocks. The only thing to watch out for is that we can't put
1032 // a possibly trapping load in the predecessor if it is a critical edge.
1033 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1034 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1035 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001036
Chandler Carruthf0546402013-07-18 07:15:00 +00001037 // If the value is produced by the terminator of the predecessor (an
1038 // invoke) or it has side-effects, there is no valid place to put a load
1039 // in the predecessor.
1040 if (TI == InVal || TI->mayHaveSideEffects())
1041 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001042
Chandler Carruthf0546402013-07-18 07:15:00 +00001043 // If the predecessor has a single successor, then the edge isn't
1044 // critical.
1045 if (TI->getNumSuccessors() == 1)
1046 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001047
Chandler Carruthf0546402013-07-18 07:15:00 +00001048 // If this pointer is always safe to load, or if we can prove that there
1049 // is already a load in the block, then we can move the load to the pred
1050 // block.
1051 if (InVal->isDereferenceablePointer() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001052 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001053 continue;
1054
1055 return false;
1056 }
1057
1058 return true;
1059}
1060
1061static void speculatePHINodeLoads(PHINode &PN) {
1062 DEBUG(dbgs() << " original: " << PN << "\n");
1063
1064 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1065 IRBuilderTy PHIBuilder(&PN);
1066 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1067 PN.getName() + ".sroa.speculated");
1068
1069 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1070 // matter which one we get and if any differ.
1071 LoadInst *SomeLoad = cast<LoadInst>(*PN.use_begin());
1072 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1073 unsigned Align = SomeLoad->getAlignment();
1074
1075 // Rewrite all loads of the PN to use the new PHI.
1076 while (!PN.use_empty()) {
1077 LoadInst *LI = cast<LoadInst>(*PN.use_begin());
1078 LI->replaceAllUsesWith(NewPN);
1079 LI->eraseFromParent();
1080 }
1081
1082 // Inject loads into all of the pred blocks.
1083 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1084 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1085 TerminatorInst *TI = Pred->getTerminator();
1086 Value *InVal = PN.getIncomingValue(Idx);
1087 IRBuilderTy PredBuilder(TI);
1088
1089 LoadInst *Load = PredBuilder.CreateLoad(
1090 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1091 ++NumLoadsSpeculated;
1092 Load->setAlignment(Align);
1093 if (TBAATag)
1094 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1095 NewPN->addIncoming(Load, Pred);
1096 }
1097
1098 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1099 PN.eraseFromParent();
1100}
1101
1102/// Select instructions that use an alloca and are subsequently loaded can be
1103/// rewritten to load both input pointers and then select between the result,
1104/// allowing the load of the alloca to be promoted.
1105/// From this:
1106/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1107/// %V = load i32* %P2
1108/// to:
1109/// %V1 = load i32* %Alloca -> will be mem2reg'd
1110/// %V2 = load i32* %Other
1111/// %V = select i1 %cond, i32 %V1, i32 %V2
1112///
1113/// We can do this to a select if its only uses are loads and if the operand
1114/// to the select can be loaded unconditionally.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001115static bool isSafeSelectToSpeculate(SelectInst &SI, const DataLayout *DL = 0) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001116 Value *TValue = SI.getTrueValue();
1117 Value *FValue = SI.getFalseValue();
1118 bool TDerefable = TValue->isDereferenceablePointer();
1119 bool FDerefable = FValue->isDereferenceablePointer();
1120
1121 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end(); UI != UE;
1122 ++UI) {
1123 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1124 if (LI == 0 || !LI->isSimple())
1125 return false;
1126
1127 // Both operands to the select need to be dereferencable, either
1128 // absolutely (e.g. allocas) or at this point because we can see other
1129 // accesses to it.
1130 if (!TDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001131 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001132 return false;
1133 if (!FDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001134 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001135 return false;
1136 }
1137
1138 return true;
1139}
1140
1141static void speculateSelectInstLoads(SelectInst &SI) {
1142 DEBUG(dbgs() << " original: " << SI << "\n");
1143
1144 IRBuilderTy IRB(&SI);
1145 Value *TV = SI.getTrueValue();
1146 Value *FV = SI.getFalseValue();
1147 // Replace the loads of the select with a select of two loads.
1148 while (!SI.use_empty()) {
1149 LoadInst *LI = cast<LoadInst>(*SI.use_begin());
1150 assert(LI->isSimple() && "We only speculate simple loads");
1151
1152 IRB.SetInsertPoint(LI);
1153 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001154 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001155 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001156 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001157 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001158
Chandler Carruthf0546402013-07-18 07:15:00 +00001159 // Transfer alignment and TBAA info if present.
1160 TL->setAlignment(LI->getAlignment());
1161 FL->setAlignment(LI->getAlignment());
1162 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1163 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1164 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001165 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001166
1167 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1168 LI->getName() + ".sroa.speculated");
1169
1170 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1171 LI->replaceAllUsesWith(V);
1172 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001173 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001174 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001175}
1176
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001177/// \brief Build a GEP out of a base pointer and indices.
1178///
1179/// This will return the BasePtr if that is valid, or build a new GEP
1180/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001181static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001182 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001183 if (Indices.empty())
1184 return BasePtr;
1185
1186 // A single zero index is a no-op, so check for this and avoid building a GEP
1187 // in that case.
1188 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1189 return BasePtr;
1190
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001191 return IRB.CreateInBoundsGEP(BasePtr, Indices, "idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001192}
1193
1194/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1195/// TargetTy without changing the offset of the pointer.
1196///
1197/// This routine assumes we've already established a properly offset GEP with
1198/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1199/// zero-indices down through type layers until we find one the same as
1200/// TargetTy. If we can't find one with the same type, we at least try to use
1201/// one with the same size. If none of that works, we just produce the GEP as
1202/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001203static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001204 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001205 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001206 if (Ty == TargetTy)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001207 return buildGEP(IRB, BasePtr, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001208
1209 // See if we can descend into a struct and locate a field with the correct
1210 // type.
1211 unsigned NumLayers = 0;
1212 Type *ElementTy = Ty;
1213 do {
1214 if (ElementTy->isPointerTy())
1215 break;
1216 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1217 ElementTy = SeqTy->getElementType();
Chandler Carruth40617f52012-10-17 07:22:16 +00001218 // Note that we use the default address space as this index is over an
1219 // array or a vector, not a pointer.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001220 Indices.push_back(IRB.getInt(APInt(DL.getPointerSizeInBits(0), 0)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001221 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001222 if (STy->element_begin() == STy->element_end())
1223 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001224 ElementTy = *STy->element_begin();
1225 Indices.push_back(IRB.getInt32(0));
1226 } else {
1227 break;
1228 }
1229 ++NumLayers;
1230 } while (ElementTy != TargetTy);
1231 if (ElementTy != TargetTy)
1232 Indices.erase(Indices.end() - NumLayers, Indices.end());
1233
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001234 return buildGEP(IRB, BasePtr, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001235}
1236
1237/// \brief Recursively compute indices for a natural GEP.
1238///
1239/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1240/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001241static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001242 Value *Ptr, Type *Ty, APInt &Offset,
1243 Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001244 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001245 if (Offset == 0)
Chandler Carruth90a735d2013-07-19 07:21:28 +00001246 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001247
1248 // We can't recurse through pointer types.
1249 if (Ty->isPointerTy())
1250 return 0;
1251
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001252 // We try to analyze GEPs over vectors here, but note that these GEPs are
1253 // extremely poorly defined currently. The long-term goal is to remove GEPing
1254 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001255 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001256 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001257 if (ElementSizeInBits % 8)
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001258 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001259 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001260 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001261 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1262 return 0;
1263 Offset -= NumSkippedElements * ElementSize;
1264 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001265 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001266 Offset, TargetTy, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001267 }
1268
1269 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1270 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001271 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001272 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001273 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1274 return 0;
1275
1276 Offset -= NumSkippedElements * ElementSize;
1277 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001278 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001279 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001280 }
1281
1282 StructType *STy = dyn_cast<StructType>(Ty);
1283 if (!STy)
1284 return 0;
1285
Chandler Carruth90a735d2013-07-19 07:21:28 +00001286 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001287 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001288 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001289 return 0;
1290 unsigned Index = SL->getElementContainingOffset(StructOffset);
1291 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1292 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001293 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001294 return 0; // The offset points into alignment padding.
1295
1296 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001297 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001298 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001299}
1300
1301/// \brief Get a natural GEP from a base pointer to a particular offset and
1302/// resulting in a particular type.
1303///
1304/// The goal is to produce a "natural" looking GEP that works with the existing
1305/// composite types to arrive at the appropriate offset and element type for
1306/// a pointer. TargetTy is the element type the returned GEP should point-to if
1307/// possible. We recurse by decreasing Offset, adding the appropriate index to
1308/// Indices, and setting Ty to the result subtype.
1309///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001310/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001311static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001312 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001313 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001314 PointerType *Ty = cast<PointerType>(Ptr->getType());
1315
1316 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1317 // an i8.
1318 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1319 return 0;
1320
1321 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001322 if (!ElementTy->isSized())
1323 return 0; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001324 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001325 if (ElementSize == 0)
1326 return 0; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001327 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001328
1329 Offset -= NumSkippedElements * ElementSize;
1330 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001331 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001332 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001333}
1334
1335/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1336/// resulting pointer has PointerTy.
1337///
1338/// This tries very hard to compute a "natural" GEP which arrives at the offset
1339/// and produces the pointer type desired. Where it cannot, it will try to use
1340/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1341/// fails, it will try to use an existing i8* and GEP to the byte offset and
1342/// bitcast to the type.
1343///
1344/// The strategy for finding the more natural GEPs is to peel off layers of the
1345/// pointer, walking back through bit casts and GEPs, searching for a base
1346/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001347/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001348/// a single GEP as possible, thus making each GEP more independent of the
1349/// surrounding code.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001350static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001351 Value *Ptr, APInt Offset, Type *PointerTy) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001352 // Even though we don't look through PHI nodes, we could be called on an
1353 // instruction in an unreachable block, which may be on a cycle.
1354 SmallPtrSet<Value *, 4> Visited;
1355 Visited.insert(Ptr);
1356 SmallVector<Value *, 4> Indices;
1357
1358 // We may end up computing an offset pointer that has the wrong type. If we
1359 // never are able to compute one directly that has the correct type, we'll
1360 // fall back to it, so keep it around here.
1361 Value *OffsetPtr = 0;
1362
1363 // Remember any i8 pointer we come across to re-use if we need to do a raw
1364 // byte offset.
1365 Value *Int8Ptr = 0;
1366 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1367
1368 Type *TargetTy = PointerTy->getPointerElementType();
1369
1370 do {
1371 // First fold any existing GEPs into the offset.
1372 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1373 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001374 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001375 break;
1376 Offset += GEPOffset;
1377 Ptr = GEP->getPointerOperand();
1378 if (!Visited.insert(Ptr))
1379 break;
1380 }
1381
1382 // See if we can perform a natural GEP here.
1383 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001384 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001385 Indices)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001386 if (P->getType() == PointerTy) {
1387 // Zap any offset pointer that we ended up computing in previous rounds.
1388 if (OffsetPtr && OffsetPtr->use_empty())
1389 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1390 I->eraseFromParent();
1391 return P;
1392 }
1393 if (!OffsetPtr) {
1394 OffsetPtr = P;
1395 }
1396 }
1397
1398 // Stash this pointer if we've found an i8*.
1399 if (Ptr->getType()->isIntegerTy(8)) {
1400 Int8Ptr = Ptr;
1401 Int8PtrOffset = Offset;
1402 }
1403
1404 // Peel off a layer of the pointer and update the offset appropriately.
1405 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1406 Ptr = cast<Operator>(Ptr)->getOperand(0);
1407 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1408 if (GA->mayBeOverridden())
1409 break;
1410 Ptr = GA->getAliasee();
1411 } else {
1412 break;
1413 }
1414 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1415 } while (Visited.insert(Ptr));
1416
1417 if (!OffsetPtr) {
1418 if (!Int8Ptr) {
1419 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001420 "raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001421 Int8PtrOffset = Offset;
1422 }
1423
1424 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1425 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001426 "raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001427 }
1428 Ptr = OffsetPtr;
1429
1430 // On the off chance we were targeting i8*, guard the bitcast here.
1431 if (Ptr->getType() != PointerTy)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001432 Ptr = IRB.CreateBitCast(Ptr, PointerTy, "cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001433
1434 return Ptr;
1435}
1436
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001437/// \brief Test whether we can convert a value from the old to the new type.
1438///
1439/// This predicate should be used to guard calls to convertValue in order to
1440/// ensure that we only try to convert viable values. The strategy is that we
1441/// will peel off single element struct and array wrappings to get to an
1442/// underlying value, and convert that value.
1443static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1444 if (OldTy == NewTy)
1445 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001446 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1447 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1448 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1449 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001450 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1451 return false;
1452 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1453 return false;
1454
1455 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1456 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1457 return true;
1458 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1459 return true;
1460 return false;
1461 }
1462
1463 return true;
1464}
1465
1466/// \brief Generic routine to convert an SSA value to a value of a different
1467/// type.
1468///
1469/// This will try various different casting techniques, such as bitcasts,
1470/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1471/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001472static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001473 Type *Ty) {
1474 assert(canConvertValue(DL, V->getType(), Ty) &&
1475 "Value not convertable to type");
1476 if (V->getType() == Ty)
1477 return V;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001478 if (IntegerType *OldITy = dyn_cast<IntegerType>(V->getType()))
1479 if (IntegerType *NewITy = dyn_cast<IntegerType>(Ty))
1480 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1481 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001482 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1483 return IRB.CreateIntToPtr(V, Ty);
1484 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1485 return IRB.CreatePtrToInt(V, Ty);
1486
1487 return IRB.CreateBitCast(V, Ty);
1488}
1489
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001490/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001491///
1492/// This function is called to test each entry in a partioning which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001493/// for a single slice.
1494static bool isVectorPromotionViableForSlice(
1495 const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
1496 uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
1497 AllocaSlices::const_iterator I) {
1498 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001499 uint64_t BeginOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001500 std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001501 uint64_t BeginIndex = BeginOffset / ElementSize;
1502 if (BeginIndex * ElementSize != BeginOffset ||
1503 BeginIndex >= Ty->getNumElements())
1504 return false;
1505 uint64_t EndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001506 std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001507 uint64_t EndIndex = EndOffset / ElementSize;
1508 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1509 return false;
1510
1511 assert(EndIndex > BeginIndex && "Empty vector!");
1512 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001513 Type *SliceTy =
Chandler Carruthf0546402013-07-18 07:15:00 +00001514 (NumElements == 1) ? Ty->getElementType()
1515 : VectorType::get(Ty->getElementType(), NumElements);
1516
1517 Type *SplitIntTy =
1518 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1519
1520 Use *U = I->getUse();
1521
1522 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1523 if (MI->isVolatile())
1524 return false;
1525 if (!I->isSplittable())
1526 return false; // Skip any unsplittable intrinsics.
1527 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1528 // Disable vector promotion when there are loads or stores of an FCA.
1529 return false;
1530 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1531 if (LI->isVolatile())
1532 return false;
1533 Type *LTy = LI->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001534 if (SliceBeginOffset > I->beginOffset() ||
1535 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001536 assert(LTy->isIntegerTy());
1537 LTy = SplitIntTy;
1538 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001539 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001540 return false;
1541 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1542 if (SI->isVolatile())
1543 return false;
1544 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001545 if (SliceBeginOffset > I->beginOffset() ||
1546 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001547 assert(STy->isIntegerTy());
1548 STy = SplitIntTy;
1549 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001550 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001551 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001552 } else {
1553 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001554 }
1555
1556 return true;
1557}
1558
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001559/// \brief Test whether the given alloca partitioning and range of slices can be
1560/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001561///
1562/// This is a quick test to check whether we can rewrite a particular alloca
1563/// partition (and its newly formed alloca) into a vector alloca with only
1564/// whole-vector loads and stores such that it could be promoted to a vector
1565/// SSA value. We only can ensure this for a limited set of operations, and we
1566/// don't want to do the rewrites unless we are confident that the result will
1567/// be promotable, so we have an early test here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001568static bool
1569isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
1570 uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
1571 AllocaSlices::const_iterator I,
1572 AllocaSlices::const_iterator E,
1573 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001574 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1575 if (!Ty)
1576 return false;
1577
Chandler Carruth90a735d2013-07-19 07:21:28 +00001578 uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001579
1580 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1581 // that aren't byte sized.
1582 if (ElementSize % 8)
1583 return false;
Chandler Carruth90a735d2013-07-19 07:21:28 +00001584 assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
Benjamin Kramerc003a452013-01-01 16:13:35 +00001585 "vector size not a multiple of element size?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001586 ElementSize /= 8;
1587
Chandler Carruthf0546402013-07-18 07:15:00 +00001588 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001589 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1590 SliceEndOffset, Ty, ElementSize, I))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001591 return false;
1592
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001593 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1594 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001595 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001596 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1597 SliceEndOffset, Ty, ElementSize, *SUI))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001598 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001599
1600 return true;
1601}
1602
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001603/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001604///
1605/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001606/// test below on a single slice of the alloca.
1607static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1608 Type *AllocaTy,
1609 uint64_t AllocBeginOffset,
1610 uint64_t Size, AllocaSlices &S,
1611 AllocaSlices::const_iterator I,
1612 bool &WholeAllocaOp) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001613 uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
1614 uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
1615
1616 // We can't reasonably handle cases where the load or store extends past
1617 // the end of the aloca's type and into its padding.
1618 if (RelEnd > Size)
1619 return false;
1620
1621 Use *U = I->getUse();
1622
1623 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1624 if (LI->isVolatile())
1625 return false;
1626 if (RelBegin == 0 && RelEnd == Size)
1627 WholeAllocaOp = true;
1628 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001629 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001630 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001631 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001632 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001633 // Non-integer loads need to be convertible from the alloca type so that
1634 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001635 return false;
1636 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001637 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1638 Type *ValueTy = SI->getValueOperand()->getType();
1639 if (SI->isVolatile())
1640 return false;
1641 if (RelBegin == 0 && RelEnd == Size)
1642 WholeAllocaOp = true;
1643 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001644 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001645 return false;
1646 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001647 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001648 // Non-integer stores need to be convertible to the alloca type so that
1649 // they are promotable.
1650 return false;
1651 }
1652 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1653 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1654 return false;
1655 if (!I->isSplittable())
1656 return false; // Skip any unsplittable intrinsics.
1657 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1658 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1659 II->getIntrinsicID() != Intrinsic::lifetime_end)
1660 return false;
1661 } else {
1662 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001663 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001664
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001665 return true;
1666}
1667
Chandler Carruth435c4e02012-10-15 08:40:30 +00001668/// \brief Test whether the given alloca partition's integer operations can be
1669/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00001670///
Chandler Carruth435c4e02012-10-15 08:40:30 +00001671/// This is a quick test to check whether we can rewrite the integer loads and
1672/// stores to a particular alloca into wider loads and stores and be able to
1673/// promote the resulting alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +00001674static bool
Chandler Carruth90a735d2013-07-19 07:21:28 +00001675isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001676 uint64_t AllocBeginOffset, AllocaSlices &S,
1677 AllocaSlices::const_iterator I,
1678 AllocaSlices::const_iterator E,
1679 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001680 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00001681 // Don't create integer types larger than the maximum bitwidth.
1682 if (SizeInBits > IntegerType::MAX_INT_BITS)
1683 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00001684
1685 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001686 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001687 return false;
1688
Chandler Carruth58d05562012-10-25 04:37:07 +00001689 // We need to ensure that an integer type with the appropriate bitwidth can
1690 // be converted to the alloca type, whatever that is. We don't want to force
1691 // the alloca itself to have an integer type if there is a more suitable one.
1692 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001693 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1694 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00001695 return false;
1696
Chandler Carruth90a735d2013-07-19 07:21:28 +00001697 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
Chandler Carruth435c4e02012-10-15 08:40:30 +00001698
Chandler Carruthf0546402013-07-18 07:15:00 +00001699 // While examining uses, we ensure that the alloca has a covering load or
1700 // store. We don't want to widen the integer operations only to fail to
1701 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00001702 // later). However, if there are only splittable uses, go ahead and assume
1703 // that we cover the alloca.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001704 bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00001705
Chandler Carruthf0546402013-07-18 07:15:00 +00001706 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001707 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1708 S, I, WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00001709 return false;
1710
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001711 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1712 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001713 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001714 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1715 S, *SUI, WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001716 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001717
Chandler Carruth92924fd2012-09-24 00:34:20 +00001718 return WholeAllocaOp;
1719}
1720
Chandler Carruthd177f862013-03-20 07:30:36 +00001721static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001722 IntegerType *Ty, uint64_t Offset,
1723 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00001724 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001725 IntegerType *IntTy = cast<IntegerType>(V->getType());
1726 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1727 "Element extends past full value");
1728 uint64_t ShAmt = 8*Offset;
1729 if (DL.isBigEndian())
1730 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001731 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001732 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001733 DEBUG(dbgs() << " shifted: " << *V << "\n");
1734 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001735 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1736 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001737 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001738 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00001739 DEBUG(dbgs() << " trunced: " << *V << "\n");
1740 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001741 return V;
1742}
1743
Chandler Carruthd177f862013-03-20 07:30:36 +00001744static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001745 Value *V, uint64_t Offset, const Twine &Name) {
1746 IntegerType *IntTy = cast<IntegerType>(Old->getType());
1747 IntegerType *Ty = cast<IntegerType>(V->getType());
1748 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1749 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001750 DEBUG(dbgs() << " start: " << *V << "\n");
1751 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001752 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00001753 DEBUG(dbgs() << " extended: " << *V << "\n");
1754 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001755 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1756 "Element store outside of alloca store");
1757 uint64_t ShAmt = 8*Offset;
1758 if (DL.isBigEndian())
1759 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001760 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001761 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001762 DEBUG(dbgs() << " shifted: " << *V << "\n");
1763 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001764
1765 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1766 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1767 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00001768 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001769 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00001770 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001771 }
1772 return V;
1773}
1774
Chandler Carruthd177f862013-03-20 07:30:36 +00001775static Value *extractVector(IRBuilderTy &IRB, Value *V,
Chandler Carruthb6bc8742012-12-17 13:07:30 +00001776 unsigned BeginIndex, unsigned EndIndex,
1777 const Twine &Name) {
1778 VectorType *VecTy = cast<VectorType>(V->getType());
1779 unsigned NumElements = EndIndex - BeginIndex;
1780 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1781
1782 if (NumElements == VecTy->getNumElements())
1783 return V;
1784
1785 if (NumElements == 1) {
1786 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1787 Name + ".extract");
1788 DEBUG(dbgs() << " extract: " << *V << "\n");
1789 return V;
1790 }
1791
1792 SmallVector<Constant*, 8> Mask;
1793 Mask.reserve(NumElements);
1794 for (unsigned i = BeginIndex; i != EndIndex; ++i)
1795 Mask.push_back(IRB.getInt32(i));
1796 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1797 ConstantVector::get(Mask),
1798 Name + ".extract");
1799 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1800 return V;
1801}
1802
Chandler Carruthd177f862013-03-20 07:30:36 +00001803static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00001804 unsigned BeginIndex, const Twine &Name) {
1805 VectorType *VecTy = cast<VectorType>(Old->getType());
1806 assert(VecTy && "Can only insert a vector into a vector");
1807
1808 VectorType *Ty = dyn_cast<VectorType>(V->getType());
1809 if (!Ty) {
1810 // Single element to insert.
1811 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
1812 Name + ".insert");
1813 DEBUG(dbgs() << " insert: " << *V << "\n");
1814 return V;
1815 }
1816
1817 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
1818 "Too many elements!");
1819 if (Ty->getNumElements() == VecTy->getNumElements()) {
1820 assert(V->getType() == VecTy && "Vector type mismatch");
1821 return V;
1822 }
1823 unsigned EndIndex = BeginIndex + Ty->getNumElements();
1824
1825 // When inserting a smaller vector into the larger to store, we first
1826 // use a shuffle vector to widen it with undef elements, and then
1827 // a second shuffle vector to select between the loaded vector and the
1828 // incoming vector.
1829 SmallVector<Constant*, 8> Mask;
1830 Mask.reserve(VecTy->getNumElements());
1831 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1832 if (i >= BeginIndex && i < EndIndex)
1833 Mask.push_back(IRB.getInt32(i - BeginIndex));
1834 else
1835 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
1836 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1837 ConstantVector::get(Mask),
1838 Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00001839 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001840
1841 Mask.clear();
1842 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00001843 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
1844
1845 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
1846
1847 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001848 return V;
1849}
1850
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001851namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001852/// \brief Visitor to rewrite instructions using p particular slice of an alloca
1853/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001854///
1855/// Also implements the rewriting to vector-based accesses when the partition
1856/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1857/// lives here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001858class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001859 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001860 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
1861 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001862
Chandler Carruth90a735d2013-07-19 07:21:28 +00001863 const DataLayout &DL;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001864 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001865 SROA &Pass;
1866 AllocaInst &OldAI, &NewAI;
1867 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00001868 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001869
1870 // If we are rewriting an alloca partition which can be written as pure
1871 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001872 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001873 // - The new alloca is exactly the size of the vector type here.
1874 // - The accesses all either map to the entire vector or to a single
1875 // element.
1876 // - The set of accessing instructions is only one of those handled above
1877 // in isVectorPromotionViable. Generally these are the same access kinds
1878 // which are promotable via mem2reg.
1879 VectorType *VecTy;
1880 Type *ElementTy;
1881 uint64_t ElementSize;
1882
Chandler Carruth92924fd2012-09-24 00:34:20 +00001883 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth435c4e02012-10-15 08:40:30 +00001884 // alloca's integer operations should be widened to this integer type due to
1885 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruth92924fd2012-09-24 00:34:20 +00001886 // integer type will be stored here for easy access during rewriting.
Chandler Carruth435c4e02012-10-15 08:40:30 +00001887 IntegerType *IntTy;
Chandler Carruth92924fd2012-09-24 00:34:20 +00001888
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001889 // The offset of the slice currently being rewritten.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001890 uint64_t BeginOffset, EndOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001891 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001892 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00001893 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001894 Instruction *OldPtr;
1895
Chandler Carruth83ea1952013-07-24 09:47:28 +00001896 // Output members carrying state about the result of visiting and rewriting
1897 // the slice of the alloca.
1898 bool IsUsedByRewrittenSpeculatableInstructions;
1899
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001900 // Utility IR builder, whose name prefix is setup for each visited use, and
1901 // the insertion point is set to point to the user.
1902 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001903
1904public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001905 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
1906 AllocaInst &OldAI, AllocaInst &NewAI,
1907 uint64_t NewBeginOffset, uint64_t NewEndOffset,
1908 bool IsVectorPromotable = false,
1909 bool IsIntegerPromotable = false)
1910 : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthf0546402013-07-18 07:15:00 +00001911 NewAllocaBeginOffset(NewBeginOffset), NewAllocaEndOffset(NewEndOffset),
1912 NewAllocaTy(NewAI.getAllocatedType()),
1913 VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : 0),
1914 ElementTy(VecTy ? VecTy->getElementType() : 0),
Chandler Carruth90a735d2013-07-19 07:21:28 +00001915 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00001916 IntTy(IsIntegerPromotable
1917 ? Type::getIntNTy(
1918 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00001919 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001920 : 0),
1921 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
Chandler Carruth83ea1952013-07-24 09:47:28 +00001922 OldPtr(), IsUsedByRewrittenSpeculatableInstructions(false),
1923 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001924 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001925 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00001926 "Only multiple-of-8 sized vector elements are viable");
1927 ++NumVectorized;
1928 }
1929 assert((!IsVectorPromotable && !IsIntegerPromotable) ||
1930 IsVectorPromotable != IsIntegerPromotable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001931 }
1932
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001933 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001934 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00001935 BeginOffset = I->beginOffset();
1936 EndOffset = I->endOffset();
1937 IsSplittable = I->isSplittable();
1938 IsSplit =
1939 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001940
Chandler Carruthf0546402013-07-18 07:15:00 +00001941 OldUse = I->getUse();
1942 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001943
Chandler Carruthf0546402013-07-18 07:15:00 +00001944 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
1945 IRB.SetInsertPoint(OldUserI);
1946 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
1947 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
1948
1949 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
1950 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001951 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001952 return CanSROA;
1953 }
1954
Chandler Carruth83ea1952013-07-24 09:47:28 +00001955 /// \brief Query whether this slice is used by speculatable instructions after
1956 /// rewriting.
1957 ///
1958 /// These instructions (PHIs and Selects currently) require the alloca slice
1959 /// to run back through the rewriter. Thus, they are promotable, but not on
1960 /// this iteration. This is distinct from a slice which is unpromotable for
1961 /// some other reason, in which case we don't even want to perform the
1962 /// speculation. This can be querried at any time and reflects whether (at
1963 /// that point) a visit call has rewritten a speculatable instruction on the
1964 /// current slice.
1965 bool isUsedByRewrittenSpeculatableInstructions() const {
1966 return IsUsedByRewrittenSpeculatableInstructions;
1967 }
1968
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001969private:
Chandler Carruthf0546402013-07-18 07:15:00 +00001970 // Make sure the other visit overloads are visible.
1971 using Base::visit;
1972
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001973 // Every instruction which can end up as a user must have a rewrite rule.
1974 bool visitInstruction(Instruction &I) {
1975 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
1976 llvm_unreachable("No rewrite rule for this instruction!");
1977 }
1978
Chandler Carruthf0546402013-07-18 07:15:00 +00001979 Value *getAdjustedAllocaPtr(IRBuilderTy &IRB, uint64_t Offset,
1980 Type *PointerTy) {
1981 assert(Offset >= NewAllocaBeginOffset);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001982 return getAdjustedPtr(IRB, DL, &NewAI, APInt(DL.getPointerSizeInBits(),
Chandler Carruthf0546402013-07-18 07:15:00 +00001983 Offset - NewAllocaBeginOffset),
1984 PointerTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001985 }
1986
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001987 /// \brief Compute suitable alignment to access an offset into the new alloca.
1988 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth176ca712012-10-01 12:16:54 +00001989 unsigned NewAIAlign = NewAI.getAlignment();
1990 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00001991 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth176ca712012-10-01 12:16:54 +00001992 return MinAlign(NewAIAlign, Offset);
1993 }
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001994
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001995 /// \brief Compute suitable alignment to access a type at an offset of the
1996 /// new alloca.
1997 ///
1998 /// \returns zero if the type's ABI alignment is a suitable alignment,
1999 /// otherwise returns the maximal suitable alignment.
2000 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2001 unsigned Align = getOffsetAlign(Offset);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002002 return Align == DL.getABITypeAlignment(Ty) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002003 }
2004
Chandler Carruth845b73c2012-11-21 08:16:30 +00002005 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002006 assert(VecTy && "Can only call getIndex when rewriting a vector");
2007 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2008 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2009 uint32_t Index = RelOffset / ElementSize;
2010 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002011 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002012 }
2013
2014 void deleteIfTriviallyDead(Value *V) {
2015 Instruction *I = cast<Instruction>(V);
2016 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002017 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002018 }
2019
Chandler Carruthf0546402013-07-18 07:15:00 +00002020 Value *rewriteVectorizedLoadInst(uint64_t NewBeginOffset,
2021 uint64_t NewEndOffset) {
2022 unsigned BeginIndex = getIndex(NewBeginOffset);
2023 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002024 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002025
2026 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002027 "load");
2028 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002029 }
2030
Chandler Carruthf0546402013-07-18 07:15:00 +00002031 Value *rewriteIntegerLoad(LoadInst &LI, uint64_t NewBeginOffset,
2032 uint64_t NewEndOffset) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002033 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002034 assert(!LI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002035 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002036 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002037 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002038 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2039 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2040 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002041 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002042 "extract");
Chandler Carruth18db7952012-11-20 01:12:50 +00002043 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002044 }
2045
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002046 bool visitLoadInst(LoadInst &LI) {
2047 DEBUG(dbgs() << " original: " << LI << "\n");
2048 Value *OldOp = LI.getOperand(0);
2049 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002050
Chandler Carruthf0546402013-07-18 07:15:00 +00002051 // Compute the intersecting offset range.
2052 assert(BeginOffset < NewAllocaEndOffset);
2053 assert(EndOffset > NewAllocaBeginOffset);
2054 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2055 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2056
2057 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth3e994a22012-11-20 10:02:19 +00002058
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002059 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), Size * 8)
2060 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002061 bool IsPtrAdjusted = false;
2062 Value *V;
2063 if (VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002064 V = rewriteVectorizedLoadInst(NewBeginOffset, NewEndOffset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002065 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002066 V = rewriteIntegerLoad(LI, NewBeginOffset, NewEndOffset);
2067 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002068 canConvertValue(DL, NewAllocaTy, LI.getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002069 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002070 LI.isVolatile(), "load");
Chandler Carruth18db7952012-11-20 01:12:50 +00002071 } else {
2072 Type *LTy = TargetTy->getPointerTo();
Chandler Carruthf0546402013-07-18 07:15:00 +00002073 V = IRB.CreateAlignedLoad(
2074 getAdjustedAllocaPtr(IRB, NewBeginOffset, LTy),
2075 getOffsetTypeAlign(TargetTy, NewBeginOffset - NewAllocaBeginOffset),
2076 LI.isVolatile(), "load");
Chandler Carruth18db7952012-11-20 01:12:50 +00002077 IsPtrAdjusted = true;
2078 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002079 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002080
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002081 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002082 assert(!LI.isVolatile());
2083 assert(LI.getType()->isIntegerTy() &&
2084 "Only integer type loads and stores are split");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002085 assert(Size < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002086 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002087 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002088 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002089 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002090 // Move the insertion point just past the load so that we can refer to it.
2091 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002092 // Create a placeholder value with the same type as LI to use as the
2093 // basis for the new value. This allows us to replace the uses of LI with
2094 // the computed value, and then replace the placeholder with LI, leaving
2095 // LI only used for this computation.
2096 Value *Placeholder
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002097 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth90a735d2013-07-19 07:21:28 +00002098 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002099 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002100 LI.replaceAllUsesWith(V);
2101 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002102 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002103 } else {
2104 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002105 }
2106
Chandler Carruth18db7952012-11-20 01:12:50 +00002107 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002108 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002109 DEBUG(dbgs() << " to: " << *V << "\n");
2110 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002111 }
2112
Chandler Carruthf0546402013-07-18 07:15:00 +00002113 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2114 uint64_t NewBeginOffset,
2115 uint64_t NewEndOffset) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002116 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002117 unsigned BeginIndex = getIndex(NewBeginOffset);
2118 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002119 assert(EndIndex > BeginIndex && "Empty vector!");
2120 unsigned NumElements = EndIndex - BeginIndex;
2121 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002122 Type *SliceTy =
2123 (NumElements == 1) ? ElementTy
2124 : VectorType::get(ElementTy, NumElements);
2125 if (V->getType() != SliceTy)
2126 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002127
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002128 // Mix in the existing elements.
2129 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2130 "load");
2131 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2132 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002133 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002134 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002135
2136 (void)Store;
2137 DEBUG(dbgs() << " to: " << *Store << "\n");
2138 return true;
2139 }
2140
Chandler Carruthf0546402013-07-18 07:15:00 +00002141 bool rewriteIntegerStore(Value *V, StoreInst &SI,
2142 uint64_t NewBeginOffset, uint64_t NewEndOffset) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002143 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002144 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002145 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002146 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002147 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002148 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002149 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2150 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002151 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002152 "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002153 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002154 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002155 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002156 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002157 (void)Store;
2158 DEBUG(dbgs() << " to: " << *Store << "\n");
2159 return true;
2160 }
2161
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002162 bool visitStoreInst(StoreInst &SI) {
2163 DEBUG(dbgs() << " original: " << SI << "\n");
2164 Value *OldOp = SI.getOperand(1);
2165 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002166
Chandler Carruth18db7952012-11-20 01:12:50 +00002167 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002168
Chandler Carruthac8317f2012-10-04 12:33:50 +00002169 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2170 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002171 if (V->getType()->isPointerTy())
2172 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002173 Pass.PostPromotionWorklist.insert(AI);
2174
Chandler Carruthf0546402013-07-18 07:15:00 +00002175 // Compute the intersecting offset range.
2176 assert(BeginOffset < NewAllocaEndOffset);
2177 assert(EndOffset > NewAllocaBeginOffset);
2178 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2179 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2180
2181 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002182 if (Size < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002183 assert(!SI.isVolatile());
2184 assert(V->getType()->isIntegerTy() &&
2185 "Only integer type loads and stores are split");
2186 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002187 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002188 "Non-byte-multiple bit width");
Chandler Carruth18db7952012-11-20 01:12:50 +00002189 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002190 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002191 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002192 }
2193
Chandler Carruth18db7952012-11-20 01:12:50 +00002194 if (VecTy)
Chandler Carruthf0546402013-07-18 07:15:00 +00002195 return rewriteVectorizedStoreInst(V, SI, OldOp, NewBeginOffset,
2196 NewEndOffset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002197 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthf0546402013-07-18 07:15:00 +00002198 return rewriteIntegerStore(V, SI, NewBeginOffset, NewEndOffset);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002199
Chandler Carruth18db7952012-11-20 01:12:50 +00002200 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002201 if (NewBeginOffset == NewAllocaBeginOffset &&
2202 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002203 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2204 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002205 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2206 SI.isVolatile());
2207 } else {
Chandler Carruthf0546402013-07-18 07:15:00 +00002208 Value *NewPtr = getAdjustedAllocaPtr(IRB, NewBeginOffset,
2209 V->getType()->getPointerTo());
2210 NewSI = IRB.CreateAlignedStore(
2211 V, NewPtr, getOffsetTypeAlign(
2212 V->getType(), NewBeginOffset - NewAllocaBeginOffset),
2213 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002214 }
2215 (void)NewSI;
2216 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002217 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002218
2219 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2220 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002221 }
2222
Chandler Carruth514f34f2012-12-17 04:07:30 +00002223 /// \brief Compute an integer value from splatting an i8 across the given
2224 /// number of bytes.
2225 ///
2226 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2227 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002228 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002229 ///
2230 /// \param V The i8 value to splat.
2231 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002232 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002233 assert(Size > 0 && "Expected a positive number of bytes.");
2234 IntegerType *VTy = cast<IntegerType>(V->getType());
2235 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2236 if (Size == 1)
2237 return V;
2238
2239 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002240 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
Chandler Carruth514f34f2012-12-17 04:07:30 +00002241 ConstantExpr::getUDiv(
2242 Constant::getAllOnesValue(SplatIntTy),
2243 ConstantExpr::getZExt(
2244 Constant::getAllOnesValue(V->getType()),
2245 SplatIntTy)),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002246 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002247 return V;
2248 }
2249
Chandler Carruthccca5042012-12-17 04:07:37 +00002250 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002251 Value *getVectorSplat(Value *V, unsigned NumElements) {
2252 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002253 DEBUG(dbgs() << " splat: " << *V << "\n");
2254 return V;
2255 }
2256
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002257 bool visitMemSetInst(MemSetInst &II) {
2258 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002259 assert(II.getRawDest() == OldPtr);
2260
2261 // If the memset has a variable size, it cannot be split, just adjust the
2262 // pointer to the new alloca.
2263 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002264 assert(!IsSplit);
2265 assert(BeginOffset >= NewAllocaBeginOffset);
2266 II.setDest(
2267 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002268 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002269 II.setAlignment(ConstantInt::get(CstTy, getOffsetAlign(BeginOffset)));
Chandler Carruth208124f2012-09-26 10:59:22 +00002270
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002271 deleteIfTriviallyDead(OldPtr);
2272 return false;
2273 }
2274
2275 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002276 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002277
2278 Type *AllocaTy = NewAI.getAllocatedType();
2279 Type *ScalarTy = AllocaTy->getScalarType();
2280
Chandler Carruthf0546402013-07-18 07:15:00 +00002281 // Compute the intersecting offset range.
2282 assert(BeginOffset < NewAllocaEndOffset);
2283 assert(EndOffset > NewAllocaBeginOffset);
2284 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2285 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002286 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00002287
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002288 // If this doesn't map cleanly onto the alloca type, and that type isn't
2289 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002290 if (!VecTy && !IntTy &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002291 (BeginOffset > NewAllocaBeginOffset ||
2292 EndOffset < NewAllocaEndOffset ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002293 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002294 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2295 DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002296 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002297 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2298 CallInst *New = IRB.CreateMemSet(
2299 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getRawDest()->getType()),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002300 II.getValue(), Size, getOffsetAlign(SliceOffset), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002301 (void)New;
2302 DEBUG(dbgs() << " to: " << *New << "\n");
2303 return false;
2304 }
2305
2306 // If we can represent this as a simple value, we have to build the actual
2307 // value to store, which requires expanding the byte present in memset to
2308 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002309 // splatting the byte to a sufficiently wide integer, splatting it across
2310 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002311 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002312
Chandler Carruthccca5042012-12-17 04:07:37 +00002313 if (VecTy) {
2314 // If this is a memset of a vectorized alloca, insert it.
2315 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002316
Chandler Carruthf0546402013-07-18 07:15:00 +00002317 unsigned BeginIndex = getIndex(NewBeginOffset);
2318 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002319 assert(EndIndex > BeginIndex && "Empty vector!");
2320 unsigned NumElements = EndIndex - BeginIndex;
2321 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2322
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002323 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002324 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2325 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002326 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002327 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002328
Chandler Carruthce4562b2012-12-17 13:41:21 +00002329 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002330 "oldload");
2331 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002332 } else if (IntTy) {
2333 // If this is a memset on an alloca where we can widen stores, insert the
2334 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002335 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002336
Chandler Carruthf0546402013-07-18 07:15:00 +00002337 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002338 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002339
2340 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2341 EndOffset != NewAllocaBeginOffset)) {
2342 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002343 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002344 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002345 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002346 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002347 } else {
2348 assert(V->getType() == IntTy &&
2349 "Wrong type for an alloca wide integer!");
2350 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002351 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002352 } else {
2353 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002354 assert(NewBeginOffset == NewAllocaBeginOffset);
2355 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002356
Chandler Carruth90a735d2013-07-19 07:21:28 +00002357 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002358 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002359 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002360
Chandler Carruth90a735d2013-07-19 07:21:28 +00002361 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002362 }
2363
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002364 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002365 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002366 (void)New;
2367 DEBUG(dbgs() << " to: " << *New << "\n");
2368 return !II.isVolatile();
2369 }
2370
2371 bool visitMemTransferInst(MemTransferInst &II) {
2372 // Rewriting of memory transfer instructions can be a bit tricky. We break
2373 // them into two categories: split intrinsics and unsplit intrinsics.
2374
2375 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002376
Chandler Carruthf0546402013-07-18 07:15:00 +00002377 // Compute the intersecting offset range.
2378 assert(BeginOffset < NewAllocaEndOffset);
2379 assert(EndOffset > NewAllocaBeginOffset);
2380 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2381 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2382
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002383 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2384 bool IsDest = II.getRawDest() == OldPtr;
2385
Chandler Carruth176ca712012-10-01 12:16:54 +00002386 // Compute the relative offset within the transfer.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002387 unsigned IntPtrWidth = DL.getPointerSizeInBits();
Chandler Carruthf0546402013-07-18 07:15:00 +00002388 APInt RelOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Chandler Carruth176ca712012-10-01 12:16:54 +00002389
2390 unsigned Align = II.getAlignment();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002391 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth176ca712012-10-01 12:16:54 +00002392 if (Align > 1)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002393 Align =
2394 MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2395 MinAlign(II.getAlignment(), getOffsetAlign(SliceOffset)));
Chandler Carruth176ca712012-10-01 12:16:54 +00002396
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002397 // For unsplit intrinsics, we simply modify the source and destination
2398 // pointers in place. This isn't just an optimization, it is a matter of
2399 // correctness. With unsplit intrinsics we may be dealing with transfers
2400 // within a single alloca before SROA ran, or with transfers that have
2401 // a variable length. We may also be dealing with memmove instead of
2402 // memcpy, and so simply updating the pointers is the necessary for us to
2403 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002404 if (!IsSplittable) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002405 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2406 if (IsDest)
Chandler Carruthf0546402013-07-18 07:15:00 +00002407 II.setDest(
2408 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002409 else
Chandler Carruthf0546402013-07-18 07:15:00 +00002410 II.setSource(getAdjustedAllocaPtr(IRB, BeginOffset,
2411 II.getRawSource()->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002412
Chandler Carruth208124f2012-09-26 10:59:22 +00002413 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth176ca712012-10-01 12:16:54 +00002414 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruth208124f2012-09-26 10:59:22 +00002415
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002416 DEBUG(dbgs() << " to: " << II << "\n");
2417 deleteIfTriviallyDead(OldOp);
2418 return false;
2419 }
2420 // For split transfer intrinsics we have an incredibly useful assurance:
2421 // the source and destination do not reside within the same alloca, and at
2422 // least one of them does not escape. This means that we can replace
2423 // memmove with memcpy, and we don't need to worry about all manner of
2424 // downsides to splitting and transforming the operations.
2425
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002426 // If this doesn't map cleanly onto the alloca type, and that type isn't
2427 // a single value type, just emit a memcpy.
2428 bool EmitMemCpy
Chandler Carruthf0546402013-07-18 07:15:00 +00002429 = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
2430 EndOffset < NewAllocaEndOffset ||
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002431 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002432
2433 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2434 // size hasn't been shrunk based on analysis of the viable range, this is
2435 // a no-op.
2436 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002437 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002438 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002439
2440 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002441 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002442 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002443 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002444 return false;
2445 }
2446 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002447 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002448
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002449 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2450 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002451 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002452 if (AllocaInst *AI
2453 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002454 Pass.Worklist.insert(AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002455
2456 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002457 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2458 : II.getRawDest()->getType();
2459
2460 // Compute the other pointer, folding as much as possible to produce
2461 // a single, simple GEP in most cases.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002462 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002463
Chandler Carruthf0546402013-07-18 07:15:00 +00002464 Value *OurPtr = getAdjustedAllocaPtr(
2465 IRB, NewBeginOffset,
2466 IsDest ? II.getRawDest()->getType() : II.getRawSource()->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002467 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002468 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002469
2470 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2471 IsDest ? OtherPtr : OurPtr,
Chandler Carruth871ba722012-09-26 10:27:46 +00002472 Size, Align, II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002473 (void)New;
2474 DEBUG(dbgs() << " to: " << *New << "\n");
2475 return false;
2476 }
2477
Chandler Carruth08e5f492012-10-03 08:26:28 +00002478 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2479 // is equivalent to 1, but that isn't true if we end up rewriting this as
2480 // a load or store.
2481 if (!Align)
2482 Align = 1;
2483
Chandler Carruthf0546402013-07-18 07:15:00 +00002484 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2485 NewEndOffset == NewAllocaEndOffset;
2486 uint64_t Size = NewEndOffset - NewBeginOffset;
2487 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2488 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002489 unsigned NumElements = EndIndex - BeginIndex;
2490 IntegerType *SubIntTy
2491 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2492
2493 Type *OtherPtrTy = NewAI.getType();
2494 if (VecTy && !IsWholeAlloca) {
2495 if (NumElements == 1)
2496 OtherPtrTy = VecTy->getElementType();
2497 else
2498 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2499
2500 OtherPtrTy = OtherPtrTy->getPointerTo();
2501 } else if (IntTy && !IsWholeAlloca) {
2502 OtherPtrTy = SubIntTy->getPointerTo();
2503 }
2504
Chandler Carruth90a735d2013-07-19 07:21:28 +00002505 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002506 Value *DstPtr = &NewAI;
2507 if (!IsDest)
2508 std::swap(SrcPtr, DstPtr);
2509
2510 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002511 if (VecTy && !IsWholeAlloca && !IsDest) {
2512 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002513 "load");
2514 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002515 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002516 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002517 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002518 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002519 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002520 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002521 } else {
Chandler Carruth871ba722012-09-26 10:27:46 +00002522 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002523 "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002524 }
2525
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002526 if (VecTy && !IsWholeAlloca && IsDest) {
2527 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002528 "oldload");
2529 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002530 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002531 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002532 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002533 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002534 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002535 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2536 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002537 }
2538
Chandler Carruth871ba722012-09-26 10:27:46 +00002539 StoreInst *Store = cast<StoreInst>(
2540 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2541 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002542 DEBUG(dbgs() << " to: " << *Store << "\n");
2543 return !II.isVolatile();
2544 }
2545
2546 bool visitIntrinsicInst(IntrinsicInst &II) {
2547 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2548 II.getIntrinsicID() == Intrinsic::lifetime_end);
2549 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002550 assert(II.getArgOperand(1) == OldPtr);
2551
Chandler Carruthf0546402013-07-18 07:15:00 +00002552 // Compute the intersecting offset range.
2553 assert(BeginOffset < NewAllocaEndOffset);
2554 assert(EndOffset > NewAllocaBeginOffset);
2555 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2556 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2557
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002558 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002559 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002560
2561 ConstantInt *Size
2562 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002563 NewEndOffset - NewBeginOffset);
2564 Value *Ptr =
2565 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getArgOperand(1)->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002566 Value *New;
2567 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2568 New = IRB.CreateLifetimeStart(Ptr, Size);
2569 else
2570 New = IRB.CreateLifetimeEnd(Ptr, Size);
2571
Edwin Vane82f80d42013-01-29 17:42:24 +00002572 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002573 DEBUG(dbgs() << " to: " << *New << "\n");
2574 return true;
2575 }
2576
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002577 bool visitPHINode(PHINode &PN) {
2578 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00002579 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2580 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002581
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002582 // We would like to compute a new pointer in only one place, but have it be
2583 // as local as possible to the PHI. To do that, we re-use the location of
2584 // the old pointer, which necessarily must be in the right position to
2585 // dominate the PHI.
Jakub Staszakcb132fa2013-07-22 22:10:43 +00002586 IRBuilderTy PtrBuilder(OldPtr);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002587 PtrBuilder.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) +
2588 ".");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002589
Chandler Carruthf0546402013-07-18 07:15:00 +00002590 Value *NewPtr =
2591 getAdjustedAllocaPtr(PtrBuilder, BeginOffset, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002592 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002593 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002594
Chandler Carruth82a57542012-10-01 10:54:05 +00002595 DEBUG(dbgs() << " to: " << PN << "\n");
2596 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002597
2598 // Check whether we can speculate this PHI node, and if so remember that
Chandler Carruth83ea1952013-07-24 09:47:28 +00002599 // fact and queue it up for another iteration after the speculation
2600 // occurs.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002601 if (isSafePHIToSpeculate(PN, &DL)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002602 Pass.SpeculatablePHIs.insert(&PN);
Chandler Carruth83ea1952013-07-24 09:47:28 +00002603 IsUsedByRewrittenSpeculatableInstructions = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002604 return true;
2605 }
2606
2607 return false; // PHIs can't be promoted on their own.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002608 }
2609
2610 bool visitSelectInst(SelectInst &SI) {
2611 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002612 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2613 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00002614 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2615 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002616
Chandler Carruthf0546402013-07-18 07:15:00 +00002617 Value *NewPtr = getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002618 // Replace the operands which were using the old pointer.
2619 if (SI.getOperand(1) == OldPtr)
2620 SI.setOperand(1, NewPtr);
2621 if (SI.getOperand(2) == OldPtr)
2622 SI.setOperand(2, NewPtr);
2623
Chandler Carruth82a57542012-10-01 10:54:05 +00002624 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002625 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002626
2627 // Check whether we can speculate this select instruction, and if so
Chandler Carruth83ea1952013-07-24 09:47:28 +00002628 // remember that fact and queue it up for another iteration after the
2629 // speculation occurs.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002630 if (isSafeSelectToSpeculate(SI, &DL)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002631 Pass.SpeculatableSelects.insert(&SI);
Chandler Carruth83ea1952013-07-24 09:47:28 +00002632 IsUsedByRewrittenSpeculatableInstructions = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002633 return true;
2634 }
2635
2636 return false; // Selects can't be promoted on their own.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002637 }
2638
2639};
2640}
2641
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002642namespace {
2643/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2644///
2645/// This pass aggressively rewrites all aggregate loads and stores on
2646/// a particular pointer (or any pointer derived from it which we can identify)
2647/// with scalar loads and stores.
2648class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2649 // Befriend the base class so it can delegate to private visit methods.
2650 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2651
Chandler Carruth90a735d2013-07-19 07:21:28 +00002652 const DataLayout &DL;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002653
2654 /// Queue of pointer uses to analyze and potentially rewrite.
2655 SmallVector<Use *, 8> Queue;
2656
2657 /// Set to prevent us from cycling with phi nodes and loops.
2658 SmallPtrSet<User *, 8> Visited;
2659
2660 /// The current pointer use being rewritten. This is used to dig up the used
2661 /// value (as opposed to the user).
2662 Use *U;
2663
2664public:
Chandler Carruth90a735d2013-07-19 07:21:28 +00002665 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002666
2667 /// Rewrite loads and stores through a pointer and all pointers derived from
2668 /// it.
2669 bool rewrite(Instruction &I) {
2670 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2671 enqueueUsers(I);
2672 bool Changed = false;
2673 while (!Queue.empty()) {
2674 U = Queue.pop_back_val();
2675 Changed |= visit(cast<Instruction>(U->getUser()));
2676 }
2677 return Changed;
2678 }
2679
2680private:
2681 /// Enqueue all the users of the given instruction for further processing.
2682 /// This uses a set to de-duplicate users.
2683 void enqueueUsers(Instruction &I) {
2684 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2685 ++UI)
2686 if (Visited.insert(*UI))
2687 Queue.push_back(&UI.getUse());
2688 }
2689
2690 // Conservative default is to not rewrite anything.
2691 bool visitInstruction(Instruction &I) { return false; }
2692
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002693 /// \brief Generic recursive split emission class.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002694 template <typename Derived>
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002695 class OpSplitter {
2696 protected:
2697 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00002698 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002699 /// The indices which to be used with insert- or extractvalue to select the
2700 /// appropriate value within the aggregate.
2701 SmallVector<unsigned, 4> Indices;
2702 /// The indices to a GEP instruction which will move Ptr to the correct slot
2703 /// within the aggregate.
2704 SmallVector<Value *, 4> GEPIndices;
2705 /// The base pointer of the original op, used as a base for GEPing the
2706 /// split operations.
2707 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002708
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002709 /// Initialize the splitter with an insertion point, Ptr and start with a
2710 /// single zero GEP index.
2711 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002712 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002713
2714 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002715 /// \brief Generic recursive split emission routine.
2716 ///
2717 /// This method recursively splits an aggregate op (load or store) into
2718 /// scalar or vector ops. It splits recursively until it hits a single value
2719 /// and emits that single value operation via the template argument.
2720 ///
2721 /// The logic of this routine relies on GEPs and insertvalue and
2722 /// extractvalue all operating with the same fundamental index list, merely
2723 /// formatted differently (GEPs need actual values).
2724 ///
2725 /// \param Ty The type being split recursively into smaller ops.
2726 /// \param Agg The aggregate value being built up or stored, depending on
2727 /// whether this is splitting a load or a store respectively.
2728 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2729 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002730 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002731
2732 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2733 unsigned OldSize = Indices.size();
2734 (void)OldSize;
2735 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2736 ++Idx) {
2737 assert(Indices.size() == OldSize && "Did not return to the old size");
2738 Indices.push_back(Idx);
2739 GEPIndices.push_back(IRB.getInt32(Idx));
2740 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2741 GEPIndices.pop_back();
2742 Indices.pop_back();
2743 }
2744 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002745 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002746
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002747 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2748 unsigned OldSize = Indices.size();
2749 (void)OldSize;
2750 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2751 ++Idx) {
2752 assert(Indices.size() == OldSize && "Did not return to the old size");
2753 Indices.push_back(Idx);
2754 GEPIndices.push_back(IRB.getInt32(Idx));
2755 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2756 GEPIndices.pop_back();
2757 Indices.pop_back();
2758 }
2759 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002760 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002761
2762 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002763 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002764 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002765
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002766 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002767 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002768 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002769
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002770 /// Emit a leaf load of a single value. This is called at the leaves of the
2771 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002772 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002773 assert(Ty->isSingleValueType());
2774 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00002775 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2776 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002777 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2778 DEBUG(dbgs() << " to: " << *Load << "\n");
2779 }
2780 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002781
2782 bool visitLoadInst(LoadInst &LI) {
2783 assert(LI.getPointerOperand() == *U);
2784 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2785 return false;
2786
2787 // We have an aggregate being loaded, split it apart.
2788 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002789 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002790 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002791 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002792 LI.replaceAllUsesWith(V);
2793 LI.eraseFromParent();
2794 return true;
2795 }
2796
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002797 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002798 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002799 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002800
2801 /// Emit a leaf store of a single value. This is called at the leaves of the
2802 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002803 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002804 assert(Ty->isSingleValueType());
2805 // Extract the single value and store it using the indices.
2806 Value *Store = IRB.CreateStore(
2807 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2808 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2809 (void)Store;
2810 DEBUG(dbgs() << " to: " << *Store << "\n");
2811 }
2812 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002813
2814 bool visitStoreInst(StoreInst &SI) {
2815 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2816 return false;
2817 Value *V = SI.getValueOperand();
2818 if (V->getType()->isSingleValueType())
2819 return false;
2820
2821 // We have an aggregate being stored, split it apart.
2822 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002823 StoreOpSplitter Splitter(&SI, *U);
2824 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002825 SI.eraseFromParent();
2826 return true;
2827 }
2828
2829 bool visitBitCastInst(BitCastInst &BC) {
2830 enqueueUsers(BC);
2831 return false;
2832 }
2833
2834 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2835 enqueueUsers(GEPI);
2836 return false;
2837 }
2838
2839 bool visitPHINode(PHINode &PN) {
2840 enqueueUsers(PN);
2841 return false;
2842 }
2843
2844 bool visitSelectInst(SelectInst &SI) {
2845 enqueueUsers(SI);
2846 return false;
2847 }
2848};
2849}
2850
Chandler Carruthba931992012-10-13 10:49:33 +00002851/// \brief Strip aggregate type wrapping.
2852///
2853/// This removes no-op aggregate types wrapping an underlying type. It will
2854/// strip as many layers of types as it can without changing either the type
2855/// size or the allocated size.
2856static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
2857 if (Ty->isSingleValueType())
2858 return Ty;
2859
2860 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2861 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
2862
2863 Type *InnerTy;
2864 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
2865 InnerTy = ArrTy->getElementType();
2866 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2867 const StructLayout *SL = DL.getStructLayout(STy);
2868 unsigned Index = SL->getElementContainingOffset(0);
2869 InnerTy = STy->getElementType(Index);
2870 } else {
2871 return Ty;
2872 }
2873
2874 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
2875 TypeSize > DL.getTypeSizeInBits(InnerTy))
2876 return Ty;
2877
2878 return stripAggregateTypeWrapping(DL, InnerTy);
2879}
2880
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002881/// \brief Try to find a partition of the aggregate type passed in for a given
2882/// offset and size.
2883///
2884/// This recurses through the aggregate type and tries to compute a subtype
2885/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00002886/// of an array, it will even compute a new array type for that sub-section,
2887/// and the same for structs.
2888///
2889/// Note that this routine is very strict and tries to find a partition of the
2890/// type which produces the *exact* right offset and size. It is not forgiving
2891/// when the size or offset cause either end of type-based partition to be off.
2892/// Also, this is a best-effort routine. It is reasonable to give up and not
2893/// return a type if necessary.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002894static Type *getTypePartition(const DataLayout &DL, Type *Ty,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002895 uint64_t Offset, uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002896 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
2897 return stripAggregateTypeWrapping(DL, Ty);
2898 if (Offset > DL.getTypeAllocSize(Ty) ||
2899 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Chandler Carruth58d05562012-10-25 04:37:07 +00002900 return 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002901
2902 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2903 // We can't partition pointers...
2904 if (SeqTy->isPointerTy())
2905 return 0;
2906
2907 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00002908 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002909 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002910 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002911 if (NumSkippedElements >= ArrTy->getNumElements())
2912 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002913 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002914 if (NumSkippedElements >= VecTy->getNumElements())
2915 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002916 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002917 Offset -= NumSkippedElements * ElementSize;
2918
2919 // First check if we need to recurse.
2920 if (Offset > 0 || Size < ElementSize) {
2921 // Bail if the partition ends in a different array element.
2922 if ((Offset + Size) > ElementSize)
2923 return 0;
2924 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002925 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002926 }
2927 assert(Offset == 0);
2928
2929 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002930 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002931 assert(Size > ElementSize);
2932 uint64_t NumElements = Size / ElementSize;
2933 if (NumElements * ElementSize != Size)
2934 return 0;
2935 return ArrayType::get(ElementTy, NumElements);
2936 }
2937
2938 StructType *STy = dyn_cast<StructType>(Ty);
2939 if (!STy)
2940 return 0;
2941
Chandler Carruth90a735d2013-07-19 07:21:28 +00002942 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00002943 if (Offset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002944 return 0;
2945 uint64_t EndOffset = Offset + Size;
2946 if (EndOffset > SL->getSizeInBytes())
2947 return 0;
2948
2949 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002950 Offset -= SL->getElementOffset(Index);
2951
2952 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002953 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002954 if (Offset >= ElementSize)
2955 return 0; // The offset points into alignment padding.
2956
2957 // See if any partition must be contained by the element.
2958 if (Offset > 0 || Size < ElementSize) {
2959 if ((Offset + Size) > ElementSize)
2960 return 0;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002961 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002962 }
2963 assert(Offset == 0);
2964
2965 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002966 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002967
2968 StructType::element_iterator EI = STy->element_begin() + Index,
2969 EE = STy->element_end();
2970 if (EndOffset < SL->getSizeInBytes()) {
2971 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
2972 if (Index == EndIndex)
2973 return 0; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00002974
2975 // Don't try to form "natural" types if the elements don't line up with the
2976 // expected size.
2977 // FIXME: We could potentially recurse down through the last element in the
2978 // sub-struct to find a natural end point.
2979 if (SL->getElementOffset(EndIndex) != EndOffset)
2980 return 0;
2981
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002982 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002983 EE = STy->element_begin() + EndIndex;
2984 }
2985
2986 // Try to build up a sub-structure.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002987 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002988 STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002989 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00002990 if (Size != SubSL->getSizeInBytes())
2991 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002992
Chandler Carruth054a40a2012-09-14 11:08:31 +00002993 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002994}
2995
2996/// \brief Rewrite an alloca partition's users.
2997///
2998/// This routine drives both of the rewriting goals of the SROA pass. It tries
2999/// to rewrite uses of an alloca partition to be conducive for SSA value
3000/// promotion. If the partition needs a new, more refined alloca, this will
3001/// build that new alloca, preserving as much type information as possible, and
3002/// rewrite the uses of the old alloca to point at the new one and have the
3003/// appropriate new offsets. It also evaluates how successful the rewrite was
3004/// at enabling promotion and if it was successful queues the alloca to be
3005/// promoted.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003006bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
3007 AllocaSlices::iterator B, AllocaSlices::iterator E,
3008 int64_t BeginOffset, int64_t EndOffset,
3009 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003010 assert(BeginOffset < EndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003011 uint64_t SliceSize = EndOffset - BeginOffset;
Chandler Carruth82a57542012-10-01 10:54:05 +00003012
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003013 // Try to compute a friendly type for this partition of the alloca. This
3014 // won't always succeed, in which case we fall back to a legal integer type
3015 // or an i8 array of an appropriate size.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003016 Type *SliceTy = 0;
Chandler Carruthf0546402013-07-18 07:15:00 +00003017 if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003018 if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
3019 SliceTy = CommonUseTy;
3020 if (!SliceTy)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003021 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003022 BeginOffset, SliceSize))
3023 SliceTy = TypePartitionTy;
3024 if ((!SliceTy || (SliceTy->isArrayTy() &&
3025 SliceTy->getArrayElementType()->isIntegerTy())) &&
3026 DL->isLegalInteger(SliceSize * 8))
3027 SliceTy = Type::getIntNTy(*C, SliceSize * 8);
3028 if (!SliceTy)
3029 SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
3030 assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
Chandler Carruthf0546402013-07-18 07:15:00 +00003031
3032 bool IsVectorPromotable = isVectorPromotionViable(
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003033 *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
Chandler Carruthf0546402013-07-18 07:15:00 +00003034
3035 bool IsIntegerPromotable =
3036 !IsVectorPromotable &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003037 isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003038
3039 // Check for the case where we're going to rewrite to a new alloca of the
3040 // exact same type as the original, and with the same access offsets. In that
3041 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003042 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003043 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003044 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003045 assert(BeginOffset == 0 &&
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003046 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003047 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003048 // FIXME: We should be able to bail at this point with "nothing changed".
3049 // FIXME: We might want to defer PHI speculation until after here.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003050 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003051 unsigned Alignment = AI.getAlignment();
3052 if (!Alignment) {
3053 // The minimum alignment which users can rely on when the explicit
3054 // alignment is omitted or zero is that required by the ABI for this
3055 // type.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003056 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003057 }
Chandler Carruthf0546402013-07-18 07:15:00 +00003058 Alignment = MinAlign(Alignment, BeginOffset);
Chandler Carruth903790e2012-09-29 10:41:21 +00003059 // If we will get at least this much alignment from the type alone, leave
3060 // the alloca's alignment unconstrained.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003061 if (Alignment <= DL->getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003062 Alignment = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003063 NewAI = new AllocaInst(SliceTy, 0, Alignment,
3064 AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003065 ++NumNewAllocas;
3066 }
3067
3068 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthf0546402013-07-18 07:15:00 +00003069 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3070 << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003071
Chandler Carruthf0546402013-07-18 07:15:00 +00003072 // Track the high watermark on several worklists that are only relevant for
3073 // promoted allocas. We will reset it to this point if the alloca is not in
3074 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003075 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruthf0546402013-07-18 07:15:00 +00003076 unsigned SPOldSize = SpeculatablePHIs.size();
3077 unsigned SSOldSize = SpeculatableSelects.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00003078 unsigned NumUses = 0;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003079
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003080 AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
3081 EndOffset, IsVectorPromotable,
3082 IsIntegerPromotable);
Chandler Carruthf0546402013-07-18 07:15:00 +00003083 bool Promotable = true;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003084 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
3085 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00003086 SUI != SUE; ++SUI) {
3087 DEBUG(dbgs() << " rewriting split ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003088 DEBUG(S.printSlice(dbgs(), *SUI, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003089 Promotable &= Rewriter.visit(*SUI);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003090 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003091 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003092 for (AllocaSlices::iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003093 DEBUG(dbgs() << " rewriting ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003094 DEBUG(S.printSlice(dbgs(), I, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003095 Promotable &= Rewriter.visit(I);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003096 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003097 }
3098
Chandler Carruth6c321c12013-07-19 10:57:36 +00003099 NumAllocaPartitionUses += NumUses;
3100 MaxUsesPerAllocaPartition =
3101 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003102
Chandler Carruth83ea1952013-07-24 09:47:28 +00003103 if (Promotable && !Rewriter.isUsedByRewrittenSpeculatableInstructions()) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003104 DEBUG(dbgs() << " and queuing for promotion\n");
3105 PromotableAllocas.push_back(NewAI);
Chandler Carruth58e25d32013-07-24 12:12:17 +00003106 } else if (NewAI != &AI ||
3107 (Promotable &&
3108 Rewriter.isUsedByRewrittenSpeculatableInstructions())) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003109 // If we can't promote the alloca, iterate on it to check for new
3110 // refinements exposed by splitting the current alloca. Don't iterate on an
3111 // alloca which didn't actually change and didn't get promoted.
Chandler Carruth58e25d32013-07-24 12:12:17 +00003112 //
3113 // Alternatively, if we could promote the alloca but have speculatable
3114 // instructions then we will speculate them after finishing our processing
3115 // of the original alloca. Mark the new one for re-visiting in the next
3116 // iteration so the speculated operations can be rewritten.
3117 //
Chandler Carruthf0546402013-07-18 07:15:00 +00003118 // FIXME: We should actually track whether the rewriter changed anything.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003119 Worklist.insert(NewAI);
3120 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003121
3122 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthf0546402013-07-18 07:15:00 +00003123 if (!Promotable) {
Chandler Carruthac8317f2012-10-04 12:33:50 +00003124 while (PostPromotionWorklist.size() > PPWOldSize)
3125 PostPromotionWorklist.pop_back();
Chandler Carruthf0546402013-07-18 07:15:00 +00003126 while (SpeculatablePHIs.size() > SPOldSize)
3127 SpeculatablePHIs.pop_back();
3128 while (SpeculatableSelects.size() > SSOldSize)
3129 SpeculatableSelects.pop_back();
3130 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003131
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003132 return true;
3133}
3134
Chandler Carruthf0546402013-07-18 07:15:00 +00003135namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003136struct IsSliceEndLessOrEqualTo {
3137 uint64_t UpperBound;
Chandler Carruthf0546402013-07-18 07:15:00 +00003138
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003139 IsSliceEndLessOrEqualTo(uint64_t UpperBound) : UpperBound(UpperBound) {}
Chandler Carruthf0546402013-07-18 07:15:00 +00003140
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003141 bool operator()(const AllocaSlices::iterator &I) {
3142 return I->endOffset() <= UpperBound;
3143 }
3144};
Chandler Carruthf0546402013-07-18 07:15:00 +00003145}
3146
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003147static void
3148removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3149 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003150 if (Offset >= MaxSplitUseEndOffset) {
3151 SplitUses.clear();
3152 MaxSplitUseEndOffset = 0;
3153 return;
3154 }
3155
3156 size_t SplitUsesOldSize = SplitUses.size();
3157 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003158 IsSliceEndLessOrEqualTo(Offset)),
Chandler Carruthf0546402013-07-18 07:15:00 +00003159 SplitUses.end());
3160 if (SplitUsesOldSize == SplitUses.size())
3161 return;
3162
3163 // Recompute the max. While this is linear, so is remove_if.
3164 MaxSplitUseEndOffset = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003165 for (SmallVectorImpl<AllocaSlices::iterator>::iterator
Chandler Carruthf0546402013-07-18 07:15:00 +00003166 SUI = SplitUses.begin(),
3167 SUE = SplitUses.end();
3168 SUI != SUE; ++SUI)
3169 MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
3170}
3171
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003172/// \brief Walks the slices of an alloca and form partitions based on them,
3173/// rewriting each of their uses.
3174bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
3175 if (S.begin() == S.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00003176 return false;
3177
Chandler Carruth6c321c12013-07-19 10:57:36 +00003178 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003179 bool Changed = false;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003180 SmallVector<AllocaSlices::iterator, 4> SplitUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003181 uint64_t MaxSplitUseEndOffset = 0;
3182
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003183 uint64_t BeginOffset = S.begin()->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003184
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003185 for (AllocaSlices::iterator SI = S.begin(), SJ = llvm::next(SI), SE = S.end();
3186 SI != SE; SI = SJ) {
3187 uint64_t MaxEndOffset = SI->endOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003188
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003189 if (!SI->isSplittable()) {
3190 // When we're forming an unsplittable region, it must always start at the
3191 // first slice and will extend through its end.
3192 assert(BeginOffset == SI->beginOffset());
Chandler Carruthf0546402013-07-18 07:15:00 +00003193
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003194 // Form a partition including all of the overlapping slices with this
3195 // unsplittable slice.
3196 while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3197 if (!SJ->isSplittable())
3198 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3199 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003200 }
3201 } else {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003202 assert(SI->isSplittable()); // Established above.
Chandler Carruthf0546402013-07-18 07:15:00 +00003203
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003204 // Collect all of the overlapping splittable slices.
3205 while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3206 SJ->isSplittable()) {
3207 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3208 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003209 }
3210
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003211 // Back up MaxEndOffset and SJ if we ended the span early when
3212 // encountering an unsplittable slice.
3213 if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3214 assert(!SJ->isSplittable());
3215 MaxEndOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003216 }
3217 }
3218
3219 // Check if we have managed to move the end offset forward yet. If so,
3220 // we'll have to rewrite uses and erase old split uses.
3221 if (BeginOffset < MaxEndOffset) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003222 // Rewrite a sequence of overlapping slices.
3223 Changed |=
3224 rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003225 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00003226
3227 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3228 }
3229
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003230 // Accumulate all the splittable slices from the [SI,SJ) region which
Chandler Carruthf0546402013-07-18 07:15:00 +00003231 // overlap going forward.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003232 for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3233 if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3234 SplitUses.push_back(SK);
3235 MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
Chandler Carruthf0546402013-07-18 07:15:00 +00003236 }
3237
3238 // If we're already at the end and we have no split uses, we're done.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003239 if (SJ == SE && SplitUses.empty())
Chandler Carruthf0546402013-07-18 07:15:00 +00003240 break;
3241
3242 // If we have no split uses or no gap in offsets, we're ready to move to
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003243 // the next slice.
3244 if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3245 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003246 continue;
3247 }
3248
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003249 // Even if we have split slices, if the next slice is splittable and the
3250 // split slices reach it, we can simply set up the beginning offset of the
3251 // next iteration to bridge between them.
3252 if (SJ != SE && SJ->isSplittable() &&
3253 MaxSplitUseEndOffset > SJ->beginOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003254 BeginOffset = MaxEndOffset;
3255 continue;
3256 }
3257
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003258 // Otherwise, we have a tail of split slices. Rewrite them with an empty
3259 // range of slices.
Chandler Carruthf0546402013-07-18 07:15:00 +00003260 uint64_t PostSplitEndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003261 SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003262
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003263 Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
3264 SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003265 ++NumPartitions;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003266
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003267 if (SJ == SE)
Chandler Carruthf0546402013-07-18 07:15:00 +00003268 break; // Skip the rest, we don't need to do any cleanup.
3269
3270 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3271 PostSplitEndOffset);
3272
3273 // Now just reset the begin offset for the next iteration.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003274 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003275 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003276
Chandler Carruth6c321c12013-07-19 10:57:36 +00003277 NumAllocaPartitions += NumPartitions;
3278 MaxPartitionsPerAlloca =
3279 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003280
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003281 return Changed;
3282}
3283
3284/// \brief Analyze an alloca for SROA.
3285///
3286/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003287/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003288/// rewritten as needed.
3289bool SROA::runOnAlloca(AllocaInst &AI) {
3290 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3291 ++NumAllocasAnalyzed;
3292
3293 // Special case dead allocas, as they're trivial.
3294 if (AI.use_empty()) {
3295 AI.eraseFromParent();
3296 return true;
3297 }
3298
3299 // Skip alloca forms that this analysis can't handle.
3300 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00003301 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003302 return false;
3303
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003304 bool Changed = false;
3305
3306 // First, split any FCA loads and stores touching this alloca to promote
3307 // better splitting and promotion opportunities.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003308 AggLoadStoreRewriter AggRewriter(*DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003309 Changed |= AggRewriter.rewrite(AI);
3310
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003311 // Build the slices using a recursive instruction-visiting builder.
3312 AllocaSlices S(*DL, AI);
3313 DEBUG(S.print(dbgs()));
3314 if (S.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003315 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003316
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003317 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003318 for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
3319 DE = S.dead_user_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003320 DI != DE; ++DI) {
3321 Changed = true;
3322 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
Chandler Carruth18db7952012-11-20 01:12:50 +00003323 DeadInsts.insert(*DI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003324 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003325 for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
3326 DE = S.dead_op_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003327 DO != DE; ++DO) {
3328 Value *OldV = **DO;
3329 // Clobber the use with an undef value.
3330 **DO = UndefValue::get(OldV->getType());
3331 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3332 if (isInstructionTriviallyDead(OldI)) {
3333 Changed = true;
Chandler Carruth18db7952012-11-20 01:12:50 +00003334 DeadInsts.insert(OldI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003335 }
3336 }
3337
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003338 // No slices to split. Leave the dead alloca for a later pass to clean up.
3339 if (S.begin() == S.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003340 return Changed;
3341
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003342 Changed |= splitAlloca(AI, S);
Chandler Carruthf0546402013-07-18 07:15:00 +00003343
3344 DEBUG(dbgs() << " Speculating PHIs\n");
3345 while (!SpeculatablePHIs.empty())
3346 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3347
3348 DEBUG(dbgs() << " Speculating Selects\n");
3349 while (!SpeculatableSelects.empty())
3350 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3351
3352 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003353}
3354
Chandler Carruth19450da2012-09-14 10:26:38 +00003355/// \brief Delete the dead instructions accumulated in this run.
3356///
3357/// Recursively deletes the dead instructions we've accumulated. This is done
3358/// at the very end to maximize locality of the recursive delete and to
3359/// minimize the problems of invalidated instruction pointers as such pointers
3360/// are used heavily in the intermediate stages of the algorithm.
3361///
3362/// We also record the alloca instructions deleted here so that they aren't
3363/// subsequently handed to mem2reg to promote.
3364void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003365 while (!DeadInsts.empty()) {
3366 Instruction *I = DeadInsts.pop_back_val();
3367 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3368
Chandler Carruth58d05562012-10-25 04:37:07 +00003369 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3370
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003371 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3372 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3373 // Zero out the operand and see if it becomes trivially dead.
3374 *OI = 0;
3375 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003376 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003377 }
3378
3379 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3380 DeletedAllocas.insert(AI);
3381
3382 ++NumDeleted;
3383 I->eraseFromParent();
3384 }
3385}
3386
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003387static void enqueueUsersInWorklist(Instruction &I,
Chandler Carruth45b136f2013-08-11 01:03:18 +00003388 SmallVectorImpl<Instruction *> &Worklist,
3389 SmallPtrSet<Instruction *, 8> &Visited) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003390 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3391 ++UI)
Chandler Carruth45b136f2013-08-11 01:03:18 +00003392 if (Visited.insert(cast<Instruction>(*UI)))
3393 Worklist.push_back(cast<Instruction>(*UI));
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003394}
3395
Chandler Carruth70b44c52012-09-15 11:43:14 +00003396/// \brief Promote the allocas, using the best available technique.
3397///
3398/// This attempts to promote whatever allocas have been identified as viable in
3399/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3400/// If there is a domtree available, we attempt to promote using the full power
3401/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3402/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003403/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003404bool SROA::promoteAllocas(Function &F) {
3405 if (PromotableAllocas.empty())
3406 return false;
3407
3408 NumPromoted += PromotableAllocas.size();
3409
3410 if (DT && !ForceSSAUpdater) {
3411 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Chandler Carruthd5b806a2013-07-28 06:43:11 +00003412 PromoteMemToReg(PromotableAllocas, *DT, DL);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003413 PromotableAllocas.clear();
3414 return true;
3415 }
3416
3417 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3418 SSAUpdater SSA;
3419 DIBuilder DIB(*F.getParent());
Chandler Carruth45b136f2013-08-11 01:03:18 +00003420 SmallVector<Instruction *, 64> Insts;
Chandler Carruth70b44c52012-09-15 11:43:14 +00003421
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003422 // We need a worklist to walk the uses of each alloca.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003423 SmallVector<Instruction *, 8> Worklist;
3424 SmallPtrSet<Instruction *, 8> Visited;
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003425 SmallVector<Instruction *, 32> DeadInsts;
3426
Chandler Carruth70b44c52012-09-15 11:43:14 +00003427 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3428 AllocaInst *AI = PromotableAllocas[Idx];
Chandler Carruth45b136f2013-08-11 01:03:18 +00003429 Insts.clear();
3430 Worklist.clear();
3431 Visited.clear();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003432
Chandler Carruth45b136f2013-08-11 01:03:18 +00003433 enqueueUsersInWorklist(*AI, Worklist, Visited);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003434
Chandler Carruth45b136f2013-08-11 01:03:18 +00003435 while (!Worklist.empty()) {
3436 Instruction *I = Worklist.pop_back_val();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003437
Chandler Carruth70b44c52012-09-15 11:43:14 +00003438 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3439 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3440 // leading to them) here. Eventually it should use them to optimize the
3441 // scalar values produced.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003442 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003443 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3444 II->getIntrinsicID() == Intrinsic::lifetime_end);
3445 II->eraseFromParent();
3446 continue;
3447 }
3448
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003449 // Push the loads and stores we find onto the list. SROA will already
3450 // have validated that all loads and stores are viable candidates for
3451 // promotion.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003452 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003453 assert(LI->getType() == AI->getAllocatedType());
3454 Insts.push_back(LI);
3455 continue;
3456 }
Chandler Carruth45b136f2013-08-11 01:03:18 +00003457 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003458 assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
3459 Insts.push_back(SI);
3460 continue;
3461 }
3462
3463 // For everything else, we know that only no-op bitcasts and GEPs will
3464 // make it this far, just recurse through them and recall them for later
3465 // removal.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003466 DeadInsts.push_back(I);
3467 enqueueUsersInWorklist(*I, Worklist, Visited);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003468 }
3469 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003470 while (!DeadInsts.empty())
3471 DeadInsts.pop_back_val()->eraseFromParent();
3472 AI->eraseFromParent();
Chandler Carruth70b44c52012-09-15 11:43:14 +00003473 }
3474
3475 PromotableAllocas.clear();
3476 return true;
3477}
3478
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003479namespace {
3480 /// \brief A predicate to test whether an alloca belongs to a set.
3481 class IsAllocaInSet {
3482 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3483 const SetType &Set;
3484
3485 public:
Chandler Carruth3f57b822012-10-03 00:03:00 +00003486 typedef AllocaInst *argument_type;
3487
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003488 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth3f57b822012-10-03 00:03:00 +00003489 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003490 };
3491}
3492
3493bool SROA::runOnFunction(Function &F) {
3494 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3495 C = &F.getContext();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003496 DL = getAnalysisIfAvailable<DataLayout>();
3497 if (!DL) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003498 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3499 return false;
3500 }
Chandler Carruth70b44c52012-09-15 11:43:14 +00003501 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003502
3503 BasicBlock &EntryBB = F.getEntryBlock();
3504 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3505 I != E; ++I)
3506 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3507 Worklist.insert(AI);
3508
3509 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003510 // A set of deleted alloca instruction pointers which should be removed from
3511 // the list of promotable allocas.
3512 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3513
Chandler Carruthac8317f2012-10-04 12:33:50 +00003514 do {
3515 while (!Worklist.empty()) {
3516 Changed |= runOnAlloca(*Worklist.pop_back_val());
3517 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003518
Chandler Carruthac8317f2012-10-04 12:33:50 +00003519 // Remove the deleted allocas from various lists so that we don't try to
3520 // continue processing them.
3521 if (!DeletedAllocas.empty()) {
3522 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3523 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3524 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3525 PromotableAllocas.end(),
3526 IsAllocaInSet(DeletedAllocas)),
3527 PromotableAllocas.end());
3528 DeletedAllocas.clear();
3529 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003530 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003531
Chandler Carruthac8317f2012-10-04 12:33:50 +00003532 Changed |= promoteAllocas(F);
3533
3534 Worklist = PostPromotionWorklist;
3535 PostPromotionWorklist.clear();
3536 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003537
3538 return Changed;
3539}
3540
3541void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003542 if (RequiresDomTree)
3543 AU.addRequired<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003544 AU.setPreservesCFG();
3545}