blob: 1a9debfc8a85f6b28d29eb30d067875eb4cf617f [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 Carruth1b398ae2012-09-14 09:22:59 +000050#include "llvm/Support/Debug.h"
51#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000052#include "llvm/Support/MathExtras.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000053#include "llvm/Support/raw_ostream.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000054#include "llvm/Transforms/Utils/Local.h"
55#include "llvm/Transforms/Utils/PromoteMemToReg.h"
56#include "llvm/Transforms/Utils/SSAUpdater.h"
57using namespace llvm;
58
59STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000060STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
61STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions");
62STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses found");
63STATISTIC(MaxPartitionUsesPerAlloca, "Maximum number of partition uses");
64STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
65STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000066STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000067STATISTIC(NumDeleted, "Number of instructions deleted");
68STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000069
Chandler Carruth70b44c52012-09-15 11:43:14 +000070/// Hidden option to force the pass to not use DomTree and mem2reg, instead
71/// forming SSA values through the SSAUpdater infrastructure.
72static cl::opt<bool>
73ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
74
Chandler Carruth1b398ae2012-09-14 09:22:59 +000075namespace {
Chandler Carruthf74654d2013-03-18 08:36:46 +000076/// \brief A common base class for representing a half-open byte range.
77struct ByteRange {
78 /// \brief The beginning offset of the range.
79 uint64_t BeginOffset;
80
81 /// \brief The ending offset, not included in the range.
82 uint64_t EndOffset;
83
84 ByteRange() : BeginOffset(), EndOffset() {}
85 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
86 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
87
88 /// \brief Support for ordering ranges.
89 ///
90 /// This provides an ordering over ranges such that start offsets are
91 /// always increasing, and within equal start offsets, the end offsets are
92 /// decreasing. Thus the spanning range comes first in a cluster with the
93 /// same start position.
94 bool operator<(const ByteRange &RHS) const {
95 if (BeginOffset < RHS.BeginOffset) return true;
96 if (BeginOffset > RHS.BeginOffset) return false;
97 if (EndOffset > RHS.EndOffset) return true;
98 return false;
99 }
100
101 /// \brief Support comparison with a single offset to allow binary searches.
102 friend bool operator<(const ByteRange &LHS, uint64_t RHSOffset) {
103 return LHS.BeginOffset < RHSOffset;
104 }
105
106 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
107 const ByteRange &RHS) {
108 return LHSOffset < RHS.BeginOffset;
109 }
110
111 bool operator==(const ByteRange &RHS) const {
112 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
113 }
114 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
115};
116
117/// \brief A partition of an alloca.
118///
119/// This structure represents a contiguous partition of the alloca. These are
120/// formed by examining the uses of the alloca. During formation, they may
121/// overlap but once an AllocaPartitioning is built, the Partitions within it
122/// are all disjoint.
123struct Partition : public ByteRange {
124 /// \brief Whether this partition is splittable into smaller partitions.
125 ///
126 /// We flag partitions as splittable when they are formed entirely due to
127 /// accesses by trivially splittable operations such as memset and memcpy.
128 bool IsSplittable;
129
130 /// \brief Test whether a partition has been marked as dead.
131 bool isDead() const {
132 if (BeginOffset == UINT64_MAX) {
133 assert(EndOffset == UINT64_MAX);
134 return true;
135 }
136 return false;
137 }
138
139 /// \brief Kill a partition.
140 /// This is accomplished by setting both its beginning and end offset to
141 /// the maximum possible value.
142 void kill() {
143 assert(!isDead() && "He's Dead, Jim!");
144 BeginOffset = EndOffset = UINT64_MAX;
145 }
146
147 Partition() : ByteRange(), IsSplittable() {}
148 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
149 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
150};
151
152/// \brief A particular use of a partition of the alloca.
153///
154/// This structure is used to associate uses of a partition with it. They
155/// mark the range of bytes which are referenced by a particular instruction,
156/// and includes a handle to the user itself and the pointer value in use.
157/// The bounds of these uses are determined by intersecting the bounds of the
158/// memory use itself with a particular partition. As a consequence there is
159/// intentionally overlap between various uses of the same partition.
160class PartitionUse : public ByteRange {
161 /// \brief Combined storage for both the Use* and split state.
162 PointerIntPair<Use*, 1, bool> UsePtrAndIsSplit;
163
164public:
165 PartitionUse() : ByteRange(), UsePtrAndIsSplit() {}
166 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset, Use *U,
167 bool IsSplit)
168 : ByteRange(BeginOffset, EndOffset), UsePtrAndIsSplit(U, IsSplit) {}
169
170 /// \brief The use in question. Provides access to both user and used value.
171 ///
172 /// Note that this may be null if the partition use is *dead*, that is, it
173 /// should be ignored.
174 Use *getUse() const { return UsePtrAndIsSplit.getPointer(); }
175
176 /// \brief Set the use for this partition use range.
177 void setUse(Use *U) { UsePtrAndIsSplit.setPointer(U); }
178
179 /// \brief Whether this use is split across multiple partitions.
180 bool isSplit() const { return UsePtrAndIsSplit.getInt(); }
181};
182}
183
184namespace llvm {
185template <> struct isPodLike<Partition> : llvm::true_type {};
186template <> struct isPodLike<PartitionUse> : llvm::true_type {};
187}
188
189namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000190/// \brief Alloca partitioning representation.
191///
192/// This class represents a partitioning of an alloca into slices, and
193/// information about the nature of uses of each slice of the alloca. The goal
194/// is that this information is sufficient to decide if and how to split the
195/// alloca apart and replace slices with scalars. It is also intended that this
Chandler Carruth93a21e72012-09-14 10:18:49 +0000196/// structure can capture the relevant information needed both to decide about
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000197/// and to enact these transformations.
198class AllocaPartitioning {
199public:
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000200 /// \brief Construct a partitioning of a particular alloca.
201 ///
202 /// Construction does most of the work for partitioning the alloca. This
203 /// performs the necessary walks of users and builds a partitioning from it.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000204 AllocaPartitioning(const DataLayout &TD, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000205
206 /// \brief Test whether a pointer to the allocation escapes our analysis.
207 ///
208 /// If this is true, the partitioning is never fully built and should be
209 /// ignored.
210 bool isEscaped() const { return PointerEscapingInstr; }
211
212 /// \brief Support for iterating over the partitions.
213 /// @{
214 typedef SmallVectorImpl<Partition>::iterator iterator;
215 iterator begin() { return Partitions.begin(); }
216 iterator end() { return Partitions.end(); }
217
218 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
219 const_iterator begin() const { return Partitions.begin(); }
220 const_iterator end() const { return Partitions.end(); }
221 /// @}
222
223 /// \brief Support for iterating over and manipulating a particular
224 /// partition's uses.
225 ///
226 /// The iteration support provided for uses is more limited, but also
227 /// includes some manipulation routines to support rewriting the uses of
228 /// partitions during SROA.
229 /// @{
230 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
231 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
232 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
233 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
234 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000235
236 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
237 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
238 const_use_iterator use_begin(const_iterator I) const {
239 return Uses[I - begin()].begin();
240 }
241 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
242 const_use_iterator use_end(const_iterator I) const {
243 return Uses[I - begin()].end();
244 }
Chandler Carruth3903e052012-10-02 17:49:47 +0000245
246 unsigned use_size(unsigned Idx) const { return Uses[Idx].size(); }
247 unsigned use_size(const_iterator I) const { return Uses[I - begin()].size(); }
248 const PartitionUse &getUse(unsigned PIdx, unsigned UIdx) const {
249 return Uses[PIdx][UIdx];
250 }
251 const PartitionUse &getUse(const_iterator I, unsigned UIdx) const {
252 return Uses[I - begin()][UIdx];
253 }
254
255 void use_push_back(unsigned Idx, const PartitionUse &PU) {
256 Uses[Idx].push_back(PU);
257 }
258 void use_push_back(const_iterator I, const PartitionUse &PU) {
259 Uses[I - begin()].push_back(PU);
260 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000261 /// @}
262
263 /// \brief Allow iterating the dead users for this alloca.
264 ///
265 /// These are instructions which will never actually use the alloca as they
266 /// are outside the allocated range. They are safe to replace with undef and
267 /// delete.
268 /// @{
269 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
270 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
271 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
272 /// @}
273
Chandler Carruth93a21e72012-09-14 10:18:49 +0000274 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000275 ///
276 /// These are operands which have cannot actually be used to refer to the
277 /// alloca as they are outside its range and the user doesn't correct for
278 /// that. These mostly consist of PHI node inputs and the like which we just
279 /// need to replace with undef.
280 /// @{
281 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
282 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
283 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
284 /// @}
285
286 /// \brief MemTransferInst auxiliary data.
287 /// This struct provides some auxiliary data about memory transfer
288 /// intrinsics such as memcpy and memmove. These intrinsics can use two
289 /// different ranges within the same alloca, and provide other challenges to
290 /// correctly represent. We stash extra data to help us untangle this
291 /// after the partitioning is complete.
292 struct MemTransferOffsets {
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000293 /// The destination begin and end offsets when the destination is within
294 /// this alloca. If the end offset is zero the destination is not within
295 /// this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000296 uint64_t DestBegin, DestEnd;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000297
298 /// The source begin and end offsets when the source is within this alloca.
299 /// If the end offset is zero, the source is not within this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000300 uint64_t SourceBegin, SourceEnd;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000301
302 /// Flag for whether an alloca is splittable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000303 bool IsSplittable;
304 };
305 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
306 return MemTransferInstData.lookup(&II);
307 }
308
309 /// \brief Map from a PHI or select operand back to a partition.
310 ///
311 /// When manipulating PHI nodes or selects, they can use more than one
312 /// partition of an alloca. We store a special mapping to allow finding the
313 /// partition referenced by each of these operands, if any.
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000314 iterator findPartitionForPHIOrSelectOperand(Use *U) {
315 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
316 = PHIOrSelectOpMap.find(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000317 if (MapIt == PHIOrSelectOpMap.end())
318 return end();
319
320 return begin() + MapIt->second.first;
321 }
322
323 /// \brief Map from a PHI or select operand back to the specific use of
324 /// a partition.
325 ///
326 /// Similar to mapping these operands back to the partitions, this maps
327 /// directly to the use structure of that partition.
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000328 use_iterator findPartitionUseForPHIOrSelectOperand(Use *U) {
329 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
330 = PHIOrSelectOpMap.find(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000331 assert(MapIt != PHIOrSelectOpMap.end());
332 return Uses[MapIt->second.first].begin() + MapIt->second.second;
333 }
334
335 /// \brief Compute a common type among the uses of a particular partition.
336 ///
337 /// This routines walks all of the uses of a particular partition and tries
338 /// to find a common type between them. Untyped operations such as memset and
339 /// memcpy are ignored.
340 Type *getCommonType(iterator I) const;
341
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000342#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000343 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
344 void printUsers(raw_ostream &OS, const_iterator I,
345 StringRef Indent = " ") const;
346 void print(raw_ostream &OS) const;
NAKAMURA Takumi4bbca0b2012-09-14 10:06:10 +0000347 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
348 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000349#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000350
351private:
352 template <typename DerivedT, typename RetT = void> class BuilderBase;
353 class PartitionBuilder;
354 friend class AllocaPartitioning::PartitionBuilder;
355 class UseBuilder;
356 friend class AllocaPartitioning::UseBuilder;
357
Chandler Carruthb7915f72012-11-20 10:23:07 +0000358#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000359 /// \brief Handle to alloca instruction to simplify method interfaces.
360 AllocaInst &AI;
Benjamin Kramer4622cd72012-09-14 13:08:09 +0000361#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000362
363 /// \brief The instruction responsible for this alloca having no partitioning.
364 ///
365 /// When an instruction (potentially) escapes the pointer to the alloca, we
366 /// store a pointer to that here and abort trying to partition the alloca.
367 /// This will be null if the alloca is partitioned successfully.
368 Instruction *PointerEscapingInstr;
369
370 /// \brief The partitions of the alloca.
371 ///
372 /// We store a vector of the partitions over the alloca here. This vector is
373 /// sorted by increasing begin offset, and then by decreasing end offset. See
Chandler Carruth93a21e72012-09-14 10:18:49 +0000374 /// the Partition inner class for more details. Initially (during
375 /// construction) there are overlaps, but we form a disjoint sequence of
376 /// partitions while finishing construction and a fully constructed object is
377 /// expected to always have this as a disjoint space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000378 SmallVector<Partition, 8> Partitions;
379
380 /// \brief The uses of the partitions.
381 ///
382 /// This is essentially a mapping from each partition to a list of uses of
383 /// that partition. The mapping is done with a Uses vector that has the exact
384 /// same number of entries as the partition vector. Each entry is itself
385 /// a vector of the uses.
386 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
387
388 /// \brief Instructions which will become dead if we rewrite the alloca.
389 ///
390 /// Note that these are not separated by partition. This is because we expect
391 /// a partitioned alloca to be completely rewritten or not rewritten at all.
392 /// If rewritten, all these instructions can simply be removed and replaced
393 /// with undef as they come from outside of the allocated space.
394 SmallVector<Instruction *, 8> DeadUsers;
395
396 /// \brief Operands which will become dead if we rewrite the alloca.
397 ///
398 /// These are operands that in their particular use can be replaced with
399 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
400 /// to PHI nodes and the like. They aren't entirely dead (there might be
401 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
402 /// want to swap this particular input for undef to simplify the use lists of
403 /// the alloca.
404 SmallVector<Use *, 8> DeadOperands;
405
406 /// \brief The underlying storage for auxiliary memcpy and memset info.
407 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
408
409 /// \brief A side datastructure used when building up the partitions and uses.
410 ///
411 /// This mapping is only really used during the initial building of the
412 /// partitioning so that we can retain information about PHI and select nodes
413 /// processed.
414 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
415
416 /// \brief Auxiliary information for particular PHI or select operands.
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000417 SmallDenseMap<Use *, std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000418
419 /// \brief A utility routine called from the constructor.
420 ///
421 /// This does what it says on the tin. It is the key of the alloca partition
422 /// splitting and merging. After it is called we have the desired disjoint
423 /// collection of partitions.
424 void splitAndMergePartitions();
425};
426}
427
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000428static Value *foldSelectInst(SelectInst &SI) {
429 // If the condition being selected on is a constant or the same value is
430 // being selected between, fold the select. Yes this does (rarely) happen
431 // early on.
432 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
433 return SI.getOperand(1+CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000434 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000435 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000436
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000437 return 0;
438}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000439
440/// \brief Builder for the alloca partitioning.
441///
442/// This class builds an alloca partitioning by recursively visiting the uses
443/// of an alloca and splitting the partitions for each load and store at each
444/// offset.
445class AllocaPartitioning::PartitionBuilder
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000446 : public PtrUseVisitor<PartitionBuilder> {
447 friend class PtrUseVisitor<PartitionBuilder>;
448 friend class InstVisitor<PartitionBuilder>;
449 typedef PtrUseVisitor<PartitionBuilder> Base;
450
451 const uint64_t AllocSize;
452 AllocaPartitioning &P;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000453
454 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
455
456public:
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000457 PartitionBuilder(const DataLayout &DL, AllocaInst &AI, AllocaPartitioning &P)
458 : PtrUseVisitor<PartitionBuilder>(DL),
459 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())),
460 P(P) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000461
462private:
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000463 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000464 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000465 // Completely skip uses which have a zero size or start either before or
466 // past the end of the allocation.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000467 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000468 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000469 << " which has zero size or starts outside of the "
470 << AllocSize << " byte alloca:\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000471 << " alloca: " << P.AI << "\n"
472 << " use: " << I << "\n");
473 return;
474 }
475
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000476 uint64_t BeginOffset = Offset.getZExtValue();
477 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000478
479 // Clamp the end offset to the end of the allocation. Note that this is
480 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000481 // This may appear superficially to be something we could ignore entirely,
482 // but that is not so! There may be widened loads or PHI-node uses where
483 // some instructions are dead but not others. We can't completely ignore
484 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000485 assert(AllocSize >= BeginOffset); // Established above.
486 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000487 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
488 << " to remain within the " << AllocSize << " byte alloca:\n"
489 << " alloca: " << P.AI << "\n"
490 << " use: " << I << "\n");
491 EndOffset = AllocSize;
492 }
493
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000494 Partition New(BeginOffset, EndOffset, IsSplittable);
495 P.Partitions.push_back(New);
496 }
497
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000498 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000499 uint64_t Size, bool IsVolatile) {
Chandler Carruth58d05562012-10-25 04:37:07 +0000500 // We allow splitting of loads and stores where the type is an integer type
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000501 // and cover the entire alloca. This prevents us from splitting over
502 // eagerly.
503 // FIXME: In the great blue eventually, we should eagerly split all integer
504 // loads and stores, and then have a separate step that merges adjacent
505 // alloca partitions into a single partition suitable for integer widening.
506 // Or we should skip the merge step and rely on GVN and other passes to
507 // merge adjacent loads and stores that survive mem2reg.
508 bool IsSplittable =
509 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
Chandler Carruth58d05562012-10-25 04:37:07 +0000510
511 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000512 }
513
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000514 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000515 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
516 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000517
518 if (!IsOffsetKnown)
519 return PI.setAborted(&LI);
520
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000521 uint64_t Size = DL.getTypeStoreSize(LI.getType());
522 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000523 }
524
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000525 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000526 Value *ValOp = SI.getValueOperand();
527 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000528 return PI.setEscapedAndAborted(&SI);
529 if (!IsOffsetKnown)
530 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000531
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000532 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
533
534 // If this memory access can be shown to *statically* extend outside the
535 // bounds of of the allocation, it's behavior is undefined, so simply
536 // ignore it. Note that this is more strict than the generic clamping
537 // behavior of insertUse. We also try to handle cases which might run the
538 // risk of overflow.
539 // FIXME: We should instead consider the pointer to have escaped if this
540 // function is being instrumented for addressing bugs or race conditions.
541 if (Offset.isNegative() || Size > AllocSize ||
542 Offset.ugt(AllocSize - Size)) {
543 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
544 << " which extends past the end of the " << AllocSize
545 << " byte alloca:\n"
546 << " alloca: " << P.AI << "\n"
547 << " use: " << SI << "\n");
548 return;
549 }
550
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000551 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
552 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000553 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000554 }
555
556
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000557 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000558 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000559 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000560 if ((Length && Length->getValue() == 0) ||
561 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
562 // Zero-length mem transfer intrinsics can be ignored entirely.
563 return;
564
565 if (!IsOffsetKnown)
566 return PI.setAborted(&II);
567
568 insertUse(II, Offset,
569 Length ? Length->getLimitedValue()
570 : AllocSize - Offset.getLimitedValue(),
571 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000572 }
573
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000574 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000575 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000576 if ((Length && Length->getValue() == 0) ||
577 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000578 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000579 return;
580
581 if (!IsOffsetKnown)
582 return PI.setAborted(&II);
583
584 uint64_t RawOffset = Offset.getLimitedValue();
585 uint64_t Size = Length ? Length->getLimitedValue()
586 : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000587
588 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
589
590 // Only intrinsics with a constant length can be split.
591 Offsets.IsSplittable = Length;
592
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000593 if (*U == II.getRawDest()) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000594 Offsets.DestBegin = RawOffset;
595 Offsets.DestEnd = RawOffset + Size;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000596 }
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000597 if (*U == II.getRawSource()) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000598 Offsets.SourceBegin = RawOffset;
599 Offsets.SourceEnd = RawOffset + Size;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000600 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000601
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000602 // If we have set up end offsets for both the source and the destination,
603 // we have found both sides of this transfer pointing at the same alloca.
604 bool SeenBothEnds = Offsets.SourceEnd && Offsets.DestEnd;
605 if (SeenBothEnds && II.getRawDest() != II.getRawSource()) {
606 unsigned PrevIdx = MemTransferPartitionMap[&II];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000607
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000608 // Check if the begin offsets match and this is a non-volatile transfer.
609 // In that case, we can completely elide the transfer.
610 if (!II.isVolatile() && Offsets.SourceBegin == Offsets.DestBegin) {
611 P.Partitions[PrevIdx].kill();
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000612 return;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000613 }
614
615 // Otherwise we have an offset transfer within the same alloca. We can't
616 // split those.
617 P.Partitions[PrevIdx].IsSplittable = Offsets.IsSplittable = false;
618 } else if (SeenBothEnds) {
619 // Handle the case where this exact use provides both ends of the
620 // operation.
621 assert(II.getRawDest() == II.getRawSource());
622
623 // For non-volatile transfers this is a no-op.
624 if (!II.isVolatile())
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000625 return;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000626
627 // Otherwise just suppress splitting.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000628 Offsets.IsSplittable = false;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000629 }
630
631
632 // Insert the use now that we've fixed up the splittable nature.
633 insertUse(II, Offset, Size, Offsets.IsSplittable);
634
635 // Setup the mapping from intrinsic to partition of we've not seen both
636 // ends of this transfer.
637 if (!SeenBothEnds) {
638 unsigned NewIdx = P.Partitions.size() - 1;
639 bool Inserted
640 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx)).second;
641 assert(Inserted &&
642 "Already have intrinsic in map but haven't seen both ends");
NAKAMURA Takumi605fe782012-10-05 13:56:23 +0000643 (void)Inserted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000644 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000645 }
646
647 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000648 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000649 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000650 void visitIntrinsicInst(IntrinsicInst &II) {
651 if (!IsOffsetKnown)
652 return PI.setAborted(&II);
653
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000654 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
655 II.getIntrinsicID() == Intrinsic::lifetime_end) {
656 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000657 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
658 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000659 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000660 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000661 }
662
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000663 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000664 }
665
666 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
667 // We consider any PHI or select that results in a direct load or store of
668 // the same offset to be a viable use for partitioning purposes. These uses
669 // are considered unsplittable and the size is the maximum loaded or stored
670 // size.
671 SmallPtrSet<Instruction *, 4> Visited;
672 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
673 Visited.insert(Root);
674 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruth8b907e82012-09-25 10:03:40 +0000675 // If there are no loads or stores, the access is dead. We mark that as
676 // a size zero access.
677 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000678 do {
679 Instruction *I, *UsedI;
680 llvm::tie(UsedI, I) = Uses.pop_back_val();
681
682 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000683 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000684 continue;
685 }
686 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
687 Value *Op = SI->getOperand(0);
688 if (Op == UsedI)
689 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000690 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000691 continue;
692 }
693
694 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
695 if (!GEP->hasAllZeroIndices())
696 return GEP;
697 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
698 !isa<SelectInst>(I)) {
699 return I;
700 }
701
702 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
703 ++UI)
704 if (Visited.insert(cast<Instruction>(*UI)))
705 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
706 } while (!Uses.empty());
707
708 return 0;
709 }
710
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000711 void visitPHINode(PHINode &PN) {
712 if (PN.use_empty())
713 return;
714 if (!IsOffsetKnown)
715 return PI.setAborted(&PN);
716
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000717 // See if we already have computed info on this node.
718 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
719 if (PHIInfo.first) {
720 PHIInfo.second = true;
Chandler Carruth97121172012-09-16 19:39:50 +0000721 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000722 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000723 }
724
725 // Check for an unsafe use of the PHI node.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000726 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
727 return PI.setAborted(UnsafeI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000728
Chandler Carruth97121172012-09-16 19:39:50 +0000729 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000730 }
731
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000732 void visitSelectInst(SelectInst &SI) {
733 if (SI.use_empty())
734 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000735 if (Value *Result = foldSelectInst(SI)) {
736 if (Result == *U)
737 // If the result of the constant fold will be the pointer, recurse
738 // through the select as if we had RAUW'ed it.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000739 enqueueUsers(SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000740
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000741 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000742 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000743 if (!IsOffsetKnown)
744 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000745
746 // See if we already have computed info on this node.
747 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
748 if (SelectInfo.first) {
749 SelectInfo.second = true;
Chandler Carruth97121172012-09-16 19:39:50 +0000750 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000751 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000752 }
753
754 // Check for an unsafe use of the PHI node.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000755 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
756 return PI.setAborted(UnsafeI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000757
Chandler Carruth97121172012-09-16 19:39:50 +0000758 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000759 }
760
761 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000762 void visitInstruction(Instruction &I) {
763 PI.setAborted(&I);
764 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000765};
766
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000767/// \brief Use adder for the alloca partitioning.
768///
Chandler Carruth93a21e72012-09-14 10:18:49 +0000769/// This class adds the uses of an alloca to all of the partitions which they
770/// use. For splittable partitions, this can end up doing essentially a linear
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000771/// walk of the partitions, but the number of steps remains bounded by the
772/// total result instruction size:
773/// - The number of partitions is a result of the number unsplittable
774/// instructions using the alloca.
775/// - The number of users of each partition is at worst the total number of
776/// splittable instructions using the alloca.
777/// Thus we will produce N * M instructions in the end, where N are the number
778/// of unsplittable uses and M are the number of splittable. This visitor does
779/// the exact same number of updates to the partitioning.
780///
781/// In the more common case, this visitor will leverage the fact that the
782/// partition space is pre-sorted, and do a logarithmic search for the
783/// partition needed, making the total visit a classical ((N + M) * log(N))
784/// complexity operation.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000785class AllocaPartitioning::UseBuilder : public PtrUseVisitor<UseBuilder> {
786 friend class PtrUseVisitor<UseBuilder>;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000787 friend class InstVisitor<UseBuilder>;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000788 typedef PtrUseVisitor<UseBuilder> Base;
789
790 const uint64_t AllocSize;
791 AllocaPartitioning &P;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000792
793 /// \brief Set to de-duplicate dead instructions found in the use walk.
794 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
795
796public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000797 UseBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000798 : PtrUseVisitor<UseBuilder>(TD),
799 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
800 P(P) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000801
802private:
803 void markAsDead(Instruction &I) {
804 if (VisitedDeadInsts.insert(&I))
805 P.DeadUsers.push_back(&I);
806 }
807
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000808 void insertUse(Instruction &User, const APInt &Offset, uint64_t Size) {
Chandler Carruth8b907e82012-09-25 10:03:40 +0000809 // If the use has a zero size or extends outside of the allocation, record
810 // it as a dead use for elimination later.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000811 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize))
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000812 return markAsDead(User);
813
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000814 uint64_t BeginOffset = Offset.getZExtValue();
815 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000816
817 // Clamp the end offset to the end of the allocation. Note that this is
818 // formulated to handle even the case where "BeginOffset + Size" overflows.
819 assert(AllocSize >= BeginOffset); // Established above.
820 if (Size > AllocSize - BeginOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000821 EndOffset = AllocSize;
822
823 // NB: This only works if we have zero overlapping partitions.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000824 iterator I = std::lower_bound(P.begin(), P.end(), BeginOffset);
825 if (I != P.begin() && llvm::prior(I)->EndOffset > BeginOffset)
826 I = llvm::prior(I);
827 iterator E = P.end();
828 bool IsSplit = llvm::next(I) != E && llvm::next(I)->BeginOffset < EndOffset;
829 for (; I != E && I->BeginOffset < EndOffset; ++I) {
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000830 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000831 std::min(I->EndOffset, EndOffset), U, IsSplit);
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000832 P.use_push_back(I, NewPU);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000833 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000834 P.PHIOrSelectOpMap[U]
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000835 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
836 }
837 }
838
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000839 void visitBitCastInst(BitCastInst &BC) {
840 if (BC.use_empty())
841 return markAsDead(BC);
842
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000843 return Base::visitBitCastInst(BC);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000844 }
845
846 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
847 if (GEPI.use_empty())
848 return markAsDead(GEPI);
849
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000850 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000851 }
852
853 void visitLoadInst(LoadInst &LI) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000854 assert(IsOffsetKnown);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000855 uint64_t Size = DL.getTypeStoreSize(LI.getType());
856 insertUse(LI, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000857 }
858
859 void visitStoreInst(StoreInst &SI) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000860 assert(IsOffsetKnown);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000861 uint64_t Size = DL.getTypeStoreSize(SI.getOperand(0)->getType());
862
863 // If this memory access can be shown to *statically* extend outside the
864 // bounds of of the allocation, it's behavior is undefined, so simply
865 // ignore it. Note that this is more strict than the generic clamping
866 // behavior of insertUse.
867 if (Offset.isNegative() || Size > AllocSize ||
868 Offset.ugt(AllocSize - Size))
869 return markAsDead(SI);
870
871 insertUse(SI, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000872 }
873
874 void visitMemSetInst(MemSetInst &II) {
875 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000876 if ((Length && Length->getValue() == 0) ||
877 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
878 return markAsDead(II);
879
880 assert(IsOffsetKnown);
881 insertUse(II, Offset, Length ? Length->getLimitedValue()
882 : AllocSize - Offset.getLimitedValue());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000883 }
884
885 void visitMemTransferInst(MemTransferInst &II) {
886 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000887 if ((Length && Length->getValue() == 0) ||
888 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000889 return markAsDead(II);
890
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000891 assert(IsOffsetKnown);
892 uint64_t Size = Length ? Length->getLimitedValue()
893 : AllocSize - Offset.getLimitedValue();
894
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000895 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
896 if (!II.isVolatile() && Offsets.DestEnd && Offsets.SourceEnd &&
897 Offsets.DestBegin == Offsets.SourceBegin)
898 return markAsDead(II); // Skip identity transfers without side-effects.
899
Chandler Carruth97121172012-09-16 19:39:50 +0000900 insertUse(II, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000901 }
902
903 void visitIntrinsicInst(IntrinsicInst &II) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000904 assert(IsOffsetKnown);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000905 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
906 II.getIntrinsicID() == Intrinsic::lifetime_end);
907
908 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000909 insertUse(II, Offset, std::min(Length->getLimitedValue(),
910 AllocSize - Offset.getLimitedValue()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000911 }
912
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000913 void insertPHIOrSelect(Instruction &User, const APInt &Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000914 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
915
916 // For PHI and select operands outside the alloca, we can't nuke the entire
917 // phi or select -- the other side might still be relevant, so we special
918 // case them here and use a separate structure to track the operands
919 // themselves which should be replaced with undef.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000920 if ((Offset.isNegative() && Offset.uge(Size)) ||
921 (!Offset.isNegative() && Offset.uge(AllocSize))) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000922 P.DeadOperands.push_back(U);
923 return;
924 }
925
Chandler Carruth97121172012-09-16 19:39:50 +0000926 insertUse(User, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000927 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000928
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000929 void visitPHINode(PHINode &PN) {
930 if (PN.use_empty())
931 return markAsDead(PN);
932
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000933 assert(IsOffsetKnown);
Chandler Carruth97121172012-09-16 19:39:50 +0000934 insertPHIOrSelect(PN, Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000935 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000936
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000937 void visitSelectInst(SelectInst &SI) {
938 if (SI.use_empty())
939 return markAsDead(SI);
940
941 if (Value *Result = foldSelectInst(SI)) {
942 if (Result == *U)
943 // If the result of the constant fold will be the pointer, recurse
944 // through the select as if we had RAUW'ed it.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000945 enqueueUsers(SI);
Chandler Carruth225d4bd2012-09-21 23:36:40 +0000946 else
947 // Otherwise the operand to the select is dead, and we can replace it
948 // with undef.
949 P.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000950
951 return;
952 }
953
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000954 assert(IsOffsetKnown);
Chandler Carruth97121172012-09-16 19:39:50 +0000955 insertPHIOrSelect(SI, Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000956 }
957
958 /// \brief Unreachable, we've already visited the alloca once.
959 void visitInstruction(Instruction &I) {
960 llvm_unreachable("Unhandled instruction in use builder.");
961 }
962};
963
964void AllocaPartitioning::splitAndMergePartitions() {
965 size_t NumDeadPartitions = 0;
966
967 // Track the range of splittable partitions that we pass when accumulating
968 // overlapping unsplittable partitions.
969 uint64_t SplitEndOffset = 0ull;
970
971 Partition New(0ull, 0ull, false);
972
973 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
974 ++j;
975
976 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
977 assert(New.BeginOffset == New.EndOffset);
978 New = Partitions[i];
979 } else {
980 assert(New.IsSplittable);
981 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
982 }
983 assert(New.BeginOffset != New.EndOffset);
984
985 // Scan the overlapping partitions.
986 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
987 // If the new partition we are forming is splittable, stop at the first
988 // unsplittable partition.
989 if (New.IsSplittable && !Partitions[j].IsSplittable)
990 break;
991
992 // Grow the new partition to include any equally splittable range. 'j' is
993 // always equally splittable when New is splittable, but when New is not
994 // splittable, we may subsume some (or part of some) splitable partition
995 // without growing the new one.
996 if (New.IsSplittable == Partitions[j].IsSplittable) {
997 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
998 } else {
999 assert(!New.IsSplittable);
1000 assert(Partitions[j].IsSplittable);
1001 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
1002 }
1003
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001004 Partitions[j].kill();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001005 ++NumDeadPartitions;
1006 ++j;
1007 }
1008
1009 // If the new partition is splittable, chop off the end as soon as the
1010 // unsplittable subsequent partition starts and ensure we eventually cover
1011 // the splittable area.
1012 if (j != e && New.IsSplittable) {
1013 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1014 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1015 }
1016
1017 // Add the new partition if it differs from the original one and is
1018 // non-empty. We can end up with an empty partition here if it was
1019 // splittable but there is an unsplittable one that starts at the same
1020 // offset.
1021 if (New != Partitions[i]) {
1022 if (New.BeginOffset != New.EndOffset)
1023 Partitions.push_back(New);
1024 // Mark the old one for removal.
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001025 Partitions[i].kill();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001026 ++NumDeadPartitions;
1027 }
1028
1029 New.BeginOffset = New.EndOffset;
1030 if (!New.IsSplittable) {
1031 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1032 if (j != e && !Partitions[j].IsSplittable)
1033 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1034 New.IsSplittable = true;
1035 // If there is a trailing splittable partition which won't be fused into
1036 // the next splittable partition go ahead and add it onto the partitions
1037 // list.
1038 if (New.BeginOffset < New.EndOffset &&
1039 (j == e || !Partitions[j].IsSplittable ||
1040 New.EndOffset < Partitions[j].BeginOffset)) {
1041 Partitions.push_back(New);
1042 New.BeginOffset = New.EndOffset = 0ull;
1043 }
1044 }
1045 }
1046
1047 // Re-sort the partitions now that they have been split and merged into
1048 // disjoint set of partitions. Also remove any of the dead partitions we've
1049 // replaced in the process.
1050 std::sort(Partitions.begin(), Partitions.end());
1051 if (NumDeadPartitions) {
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001052 assert(Partitions.back().isDead());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001053 assert((ptrdiff_t)NumDeadPartitions ==
1054 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1055 }
1056 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1057}
1058
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001059AllocaPartitioning::AllocaPartitioning(const DataLayout &TD, AllocaInst &AI)
Benjamin Kramer4622cd72012-09-14 13:08:09 +00001060 :
Chandler Carruthb7915f72012-11-20 10:23:07 +00001061#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Benjamin Kramer4622cd72012-09-14 13:08:09 +00001062 AI(AI),
1063#endif
1064 PointerEscapingInstr(0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001065 PartitionBuilder PB(TD, AI, *this);
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001066 PartitionBuilder::PtrInfo PtrI = PB.visitPtr(AI);
1067 if (PtrI.isEscaped() || PtrI.isAborted()) {
1068 // FIXME: We should sink the escape vs. abort info into the caller nicely,
1069 // possibly by just storing the PtrInfo in the AllocaPartitioning.
1070 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1071 : PtrI.getAbortingInst();
1072 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001073 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001074 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001075
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001076 // Sort the uses. This arranges for the offsets to be in ascending order,
1077 // and the sizes to be in descending order.
1078 std::sort(Partitions.begin(), Partitions.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001079
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001080 // Remove any partitions from the back which are marked as dead.
1081 while (!Partitions.empty() && Partitions.back().isDead())
1082 Partitions.pop_back();
1083
1084 if (Partitions.size() > 1) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001085 // Intersect splittability for all partitions with equal offsets and sizes.
1086 // Then remove all but the first so that we have a sequence of non-equal but
1087 // potentially overlapping partitions.
1088 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1089 I = J) {
1090 ++J;
1091 while (J != E && *I == *J) {
1092 I->IsSplittable &= J->IsSplittable;
1093 ++J;
1094 }
1095 }
1096 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1097 Partitions.end());
1098
1099 // Split splittable and merge unsplittable partitions into a disjoint set
1100 // of partitions over the used space of the allocation.
1101 splitAndMergePartitions();
1102 }
1103
Chandler Carruth5f5b6162013-03-20 06:30:46 +00001104 // Record how many partitions we end up with.
1105 NumAllocaPartitions += Partitions.size();
1106 MaxPartitionsPerAlloca = std::max<unsigned>(Partitions.size(), MaxPartitionsPerAlloca);
1107
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001108 // Now build up the user lists for each of these disjoint partitions by
1109 // re-walking the recursive users of the alloca.
1110 Uses.resize(Partitions.size());
1111 UseBuilder UB(TD, AI, *this);
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001112 PtrI = UB.visitPtr(AI);
1113 assert(!PtrI.isEscaped() && "Previously analyzed pointer now escapes!");
1114 assert(!PtrI.isAborted() && "Early aborted the visit of the pointer.");
Chandler Carruth5f5b6162013-03-20 06:30:46 +00001115
1116 unsigned NumUses = 0;
1117#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
1118 for (unsigned Idx = 0, Size = Uses.size(); Idx != Size; ++Idx)
1119 NumUses += Uses[Idx].size();
Chandler Carruth5f5b6162013-03-20 06:30:46 +00001120#endif
Chandler Carruth0941b662013-03-20 06:47:00 +00001121 NumAllocaPartitionUses += NumUses;
Chandler Carruth5f5b6162013-03-20 06:30:46 +00001122 MaxPartitionUsesPerAlloca = std::max<unsigned>(NumUses, MaxPartitionUsesPerAlloca);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001123}
1124
1125Type *AllocaPartitioning::getCommonType(iterator I) const {
1126 Type *Ty = 0;
1127 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001128 Use *U = UI->getUse();
1129 if (!U)
Chandler Carruth6c3890b2012-10-02 18:57:13 +00001130 continue; // Skip dead uses.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001131 if (isa<IntrinsicInst>(*U->getUser()))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001132 continue;
1133 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
Chandler Carruthd356fd02012-09-18 17:49:37 +00001134 continue;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001135
1136 Type *UserTy = 0;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001137 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser()))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001138 UserTy = LI->getType();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001139 else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser()))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001140 UserTy = SI->getValueOperand()->getType();
Jakub Staszakfd566112013-03-07 22:20:06 +00001141 else
Chandler Carruth58d05562012-10-25 04:37:07 +00001142 return 0; // Bail if we have weird uses.
Chandler Carruth58d05562012-10-25 04:37:07 +00001143
1144 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
1145 // If the type is larger than the partition, skip it. We only encounter
1146 // this for split integer operations where we want to use the type of the
1147 // entity causing the split.
1148 if (ITy->getBitWidth() > (I->EndOffset - I->BeginOffset)*8)
1149 continue;
1150
1151 // If we have found an integer type use covering the alloca, use that
1152 // regardless of the other types, as integers are often used for a "bucket
1153 // of bits" type.
1154 return ITy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001155 }
1156
1157 if (Ty && Ty != UserTy)
1158 return 0;
1159
1160 Ty = UserTy;
1161 }
1162 return Ty;
1163}
1164
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001165#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1166
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001167void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1168 StringRef Indent) const {
1169 OS << Indent << "partition #" << (I - begin())
1170 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1171 << (I->IsSplittable ? " (splittable)" : "")
1172 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1173 << "\n";
1174}
1175
1176void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1177 StringRef Indent) const {
Jakub Staszak3c6583a2013-02-19 22:14:45 +00001178 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001179 if (!UI->getUse())
Chandler Carruth6c3890b2012-10-02 18:57:13 +00001180 continue; // Skip dead uses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001181 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001182 << "used by: " << *UI->getUse()->getUser() << "\n";
1183 if (MemTransferInst *II =
1184 dyn_cast<MemTransferInst>(UI->getUse()->getUser())) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001185 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1186 bool IsDest;
1187 if (!MTO.IsSplittable)
1188 IsDest = UI->BeginOffset == MTO.DestBegin;
1189 else
1190 IsDest = MTO.DestBegin != 0u;
1191 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1192 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1193 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1194 }
1195 }
1196}
1197
1198void AllocaPartitioning::print(raw_ostream &OS) const {
1199 if (PointerEscapingInstr) {
1200 OS << "No partitioning for alloca: " << AI << "\n"
1201 << " A pointer to this alloca escaped by:\n"
1202 << " " << *PointerEscapingInstr << "\n";
1203 return;
1204 }
1205
1206 OS << "Partitioning of alloca: " << AI << "\n";
Jakub Staszakae2fd9c2013-02-19 22:17:58 +00001207 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001208 print(OS, I);
1209 printUsers(OS, I);
1210 }
1211}
1212
1213void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1214void AllocaPartitioning::dump() const { print(dbgs()); }
1215
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001216#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1217
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001218
1219namespace {
Chandler Carruth70b44c52012-09-15 11:43:14 +00001220/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1221///
1222/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1223/// the loads and stores of an alloca instruction, as well as updating its
1224/// debug information. This is used when a domtree is unavailable and thus
1225/// mem2reg in its full form can't be used to handle promotion of allocas to
1226/// scalar values.
1227class AllocaPromoter : public LoadAndStorePromoter {
1228 AllocaInst &AI;
1229 DIBuilder &DIB;
1230
1231 SmallVector<DbgDeclareInst *, 4> DDIs;
1232 SmallVector<DbgValueInst *, 4> DVIs;
1233
1234public:
1235 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1236 AllocaInst &AI, DIBuilder &DIB)
1237 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1238
1239 void run(const SmallVectorImpl<Instruction*> &Insts) {
1240 // Remember which alloca we're promoting (for isInstInList).
1241 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1242 for (Value::use_iterator UI = DebugNode->use_begin(),
1243 UE = DebugNode->use_end();
1244 UI != UE; ++UI)
1245 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1246 DDIs.push_back(DDI);
1247 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1248 DVIs.push_back(DVI);
1249 }
1250
1251 LoadAndStorePromoter::run(Insts);
1252 AI.eraseFromParent();
1253 while (!DDIs.empty())
1254 DDIs.pop_back_val()->eraseFromParent();
1255 while (!DVIs.empty())
1256 DVIs.pop_back_val()->eraseFromParent();
1257 }
1258
1259 virtual bool isInstInList(Instruction *I,
1260 const SmallVectorImpl<Instruction*> &Insts) const {
1261 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1262 return LI->getOperand(0) == &AI;
1263 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1264 }
1265
1266 virtual void updateDebugInfo(Instruction *Inst) const {
1267 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1268 E = DDIs.end(); I != E; ++I) {
1269 DbgDeclareInst *DDI = *I;
1270 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1271 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1272 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1273 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1274 }
1275 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1276 E = DVIs.end(); I != E; ++I) {
1277 DbgValueInst *DVI = *I;
Jakub Staszak3c6583a2013-02-19 22:14:45 +00001278 Value *Arg = 0;
Chandler Carruth70b44c52012-09-15 11:43:14 +00001279 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1280 // If an argument is zero extended then use argument directly. The ZExt
1281 // may be zapped by an optimization pass in future.
1282 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1283 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1284 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1285 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1286 if (!Arg)
1287 Arg = SI->getOperand(0);
1288 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1289 Arg = LI->getOperand(0);
1290 } else {
1291 continue;
1292 }
1293 Instruction *DbgVal =
1294 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1295 Inst);
1296 DbgVal->setDebugLoc(DVI->getDebugLoc());
1297 }
1298 }
1299};
1300} // end anon namespace
1301
1302
1303namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001304/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1305///
1306/// This pass takes allocations which can be completely analyzed (that is, they
1307/// don't escape) and tries to turn them into scalar SSA values. There are
1308/// a few steps to this process.
1309///
1310/// 1) It takes allocations of aggregates and analyzes the ways in which they
1311/// are used to try to split them into smaller allocations, ideally of
1312/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001313/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001314/// 2) It will transform accesses into forms which are suitable for SSA value
1315/// promotion. This can be replacing a memset with a scalar store of an
1316/// integer value, or it can involve speculating operations on a PHI or
1317/// select to be a PHI or select of the results.
1318/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1319/// onto insert and extract operations on a vector value, and convert them to
1320/// this form. By doing so, it will enable promotion of vector aggregates to
1321/// SSA vector values.
1322class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +00001323 const bool RequiresDomTree;
1324
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001325 LLVMContext *C;
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001326 const DataLayout *TD;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001327 DominatorTree *DT;
1328
1329 /// \brief Worklist of alloca instructions to simplify.
1330 ///
1331 /// Each alloca in the function is added to this. Each new alloca formed gets
1332 /// added to it as well to recursively simplify unless that alloca can be
1333 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1334 /// the one being actively rewritten, we add it back onto the list if not
1335 /// already present to ensure it is re-visited.
1336 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1337
1338 /// \brief A collection of instructions to delete.
1339 /// We try to batch deletions to simplify code and make things a bit more
1340 /// efficient.
Chandler Carruth18db7952012-11-20 01:12:50 +00001341 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001342
Chandler Carruthac8317f2012-10-04 12:33:50 +00001343 /// \brief Post-promotion worklist.
1344 ///
1345 /// Sometimes we discover an alloca which has a high probability of becoming
1346 /// viable for SROA after a round of promotion takes place. In those cases,
1347 /// the alloca is enqueued here for re-processing.
1348 ///
1349 /// Note that we have to be very careful to clear allocas out of this list in
1350 /// the event they are deleted.
1351 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
1352
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001353 /// \brief A collection of alloca instructions we can directly promote.
1354 std::vector<AllocaInst *> PromotableAllocas;
1355
1356public:
Chandler Carruth70b44c52012-09-15 11:43:14 +00001357 SROA(bool RequiresDomTree = true)
1358 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1359 C(0), TD(0), DT(0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001360 initializeSROAPass(*PassRegistry::getPassRegistry());
1361 }
1362 bool runOnFunction(Function &F);
1363 void getAnalysisUsage(AnalysisUsage &AU) const;
1364
1365 const char *getPassName() const { return "SROA"; }
1366 static char ID;
1367
1368private:
Chandler Carruth82a57542012-10-01 10:54:05 +00001369 friend class PHIOrSelectSpeculator;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001370 friend class AllocaPartitionRewriter;
1371 friend class AllocaPartitionVectorRewriter;
1372
1373 bool rewriteAllocaPartition(AllocaInst &AI,
1374 AllocaPartitioning &P,
1375 AllocaPartitioning::iterator PI);
1376 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1377 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth19450da2012-09-14 10:26:38 +00001378 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +00001379 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001380};
1381}
1382
1383char SROA::ID = 0;
1384
Chandler Carruth70b44c52012-09-15 11:43:14 +00001385FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1386 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001387}
1388
1389INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1390 false, false)
1391INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1392INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1393 false, false)
1394
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001395namespace {
1396/// \brief Visitor to speculate PHIs and Selects where possible.
1397class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
1398 // Befriend the base class so it can delegate to private visit methods.
1399 friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
1400
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001401 const DataLayout &TD;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001402 AllocaPartitioning &P;
1403 SROA &Pass;
1404
1405public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001406 PHIOrSelectSpeculator(const DataLayout &TD, AllocaPartitioning &P, SROA &Pass)
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001407 : TD(TD), P(P), Pass(Pass) {}
1408
1409 /// \brief Visit the users of an alloca partition and rewrite them.
1410 void visitUsers(AllocaPartitioning::const_iterator PI) {
1411 // Note that we need to use an index here as the underlying vector of uses
1412 // may be grown during speculation. However, we never need to re-visit the
1413 // new uses, and so we can use the initial size bound.
1414 for (unsigned Idx = 0, Size = P.use_size(PI); Idx != Size; ++Idx) {
Chandler Carruthf74654d2013-03-18 08:36:46 +00001415 const PartitionUse &PU = P.getUse(PI, Idx);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001416 if (!PU.getUse())
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001417 continue; // Skip dead use.
1418
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001419 visit(cast<Instruction>(PU.getUse()->getUser()));
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001420 }
1421 }
1422
1423private:
1424 // By default, skip this instruction.
1425 void visitInstruction(Instruction &I) {}
1426
1427 /// PHI instructions that use an alloca and are subsequently loaded can be
1428 /// rewritten to load both input pointers in the pred blocks and then PHI the
1429 /// results, allowing the load of the alloca to be promoted.
1430 /// From this:
1431 /// %P2 = phi [i32* %Alloca, i32* %Other]
1432 /// %V = load i32* %P2
1433 /// to:
1434 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1435 /// ...
1436 /// %V2 = load i32* %Other
1437 /// ...
1438 /// %V = phi [i32 %V1, i32 %V2]
1439 ///
1440 /// We can do this to a select if its only uses are loads and if the operands
1441 /// to the select can be loaded unconditionally.
1442 ///
1443 /// FIXME: This should be hoisted into a generic utility, likely in
1444 /// Transforms/Util/Local.h
1445 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
1446 // For now, we can only do this promotion if the load is in the same block
1447 // as the PHI, and if there are no stores between the phi and load.
1448 // TODO: Allow recursive phi users.
1449 // TODO: Allow stores.
1450 BasicBlock *BB = PN.getParent();
1451 unsigned MaxAlign = 0;
1452 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
1453 UI != UE; ++UI) {
1454 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1455 if (LI == 0 || !LI->isSimple()) return false;
1456
1457 // For now we only allow loads in the same block as the PHI. This is
1458 // a common case that happens when instcombine merges two loads through
1459 // a PHI.
1460 if (LI->getParent() != BB) return false;
1461
1462 // Ensure that there are no instructions between the PHI and the load that
1463 // could store.
1464 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1465 if (BBI->mayWriteToMemory())
1466 return false;
1467
1468 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1469 Loads.push_back(LI);
1470 }
1471
1472 // We can only transform this if it is safe to push the loads into the
1473 // predecessor blocks. The only thing to watch out for is that we can't put
1474 // a possibly trapping load in the predecessor if it is a critical edge.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00001475 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001476 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1477 Value *InVal = PN.getIncomingValue(Idx);
1478
1479 // If the value is produced by the terminator of the predecessor (an
1480 // invoke) or it has side-effects, there is no valid place to put a load
1481 // in the predecessor.
1482 if (TI == InVal || TI->mayHaveSideEffects())
1483 return false;
1484
1485 // If the predecessor has a single successor, then the edge isn't
1486 // critical.
1487 if (TI->getNumSuccessors() == 1)
1488 continue;
1489
1490 // If this pointer is always safe to load, or if we can prove that there
1491 // is already a load in the block, then we can move the load to the pred
1492 // block.
1493 if (InVal->isDereferenceablePointer() ||
1494 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
1495 continue;
1496
1497 return false;
1498 }
1499
1500 return true;
1501 }
1502
1503 void visitPHINode(PHINode &PN) {
1504 DEBUG(dbgs() << " original: " << PN << "\n");
1505
1506 SmallVector<LoadInst *, 4> Loads;
1507 if (!isSafePHIToSpeculate(PN, Loads))
1508 return;
1509
1510 assert(!Loads.empty());
1511
1512 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1513 IRBuilder<> PHIBuilder(&PN);
1514 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1515 PN.getName() + ".sroa.speculated");
1516
1517 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001518 // matter which one we get and if any differ.
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001519 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
1520 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1521 unsigned Align = SomeLoad->getAlignment();
1522
1523 // Rewrite all loads of the PN to use the new PHI.
1524 do {
1525 LoadInst *LI = Loads.pop_back_val();
1526 LI->replaceAllUsesWith(NewPN);
Chandler Carruth18db7952012-11-20 01:12:50 +00001527 Pass.DeadInsts.insert(LI);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001528 } while (!Loads.empty());
1529
1530 // Inject loads into all of the pred blocks.
1531 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1532 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1533 TerminatorInst *TI = Pred->getTerminator();
1534 Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
1535 Value *InVal = PN.getIncomingValue(Idx);
1536 IRBuilder<> PredBuilder(TI);
1537
1538 LoadInst *Load
1539 = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
1540 Pred->getName()));
1541 ++NumLoadsSpeculated;
1542 Load->setAlignment(Align);
1543 if (TBAATag)
1544 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1545 NewPN->addIncoming(Load, Pred);
1546
1547 Instruction *Ptr = dyn_cast<Instruction>(InVal);
1548 if (!Ptr)
1549 // No uses to rewrite.
1550 continue;
1551
1552 // Try to lookup and rewrite any partition uses corresponding to this phi
1553 // input.
1554 AllocaPartitioning::iterator PI
1555 = P.findPartitionForPHIOrSelectOperand(InUse);
1556 if (PI == P.end())
1557 continue;
1558
1559 // Replace the Use in the PartitionUse for this operand with the Use
1560 // inside the load.
1561 AllocaPartitioning::use_iterator UI
1562 = P.findPartitionUseForPHIOrSelectOperand(InUse);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001563 assert(isa<PHINode>(*UI->getUse()->getUser()));
1564 UI->setUse(&Load->getOperandUse(Load->getPointerOperandIndex()));
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001565 }
1566 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1567 }
1568
1569 /// Select instructions that use an alloca and are subsequently loaded can be
1570 /// rewritten to load both input pointers and then select between the result,
1571 /// allowing the load of the alloca to be promoted.
1572 /// From this:
1573 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1574 /// %V = load i32* %P2
1575 /// to:
1576 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1577 /// %V2 = load i32* %Other
1578 /// %V = select i1 %cond, i32 %V1, i32 %V2
1579 ///
1580 /// We can do this to a select if its only uses are loads and if the operand
1581 /// to the select can be loaded unconditionally.
1582 bool isSafeSelectToSpeculate(SelectInst &SI,
1583 SmallVectorImpl<LoadInst *> &Loads) {
1584 Value *TValue = SI.getTrueValue();
1585 Value *FValue = SI.getFalseValue();
1586 bool TDerefable = TValue->isDereferenceablePointer();
1587 bool FDerefable = FValue->isDereferenceablePointer();
1588
1589 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
1590 UI != UE; ++UI) {
1591 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1592 if (LI == 0 || !LI->isSimple()) return false;
1593
1594 // Both operands to the select need to be dereferencable, either
1595 // absolutely (e.g. allocas) or at this point because we can see other
1596 // accesses to it.
1597 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
1598 LI->getAlignment(), &TD))
1599 return false;
1600 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
1601 LI->getAlignment(), &TD))
1602 return false;
1603 Loads.push_back(LI);
1604 }
1605
1606 return true;
1607 }
1608
1609 void visitSelectInst(SelectInst &SI) {
1610 DEBUG(dbgs() << " original: " << SI << "\n");
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001611
1612 // If the select isn't safe to speculate, just use simple logic to emit it.
1613 SmallVector<LoadInst *, 4> Loads;
1614 if (!isSafeSelectToSpeculate(SI, Loads))
1615 return;
1616
Jakub Staszakdb4579d2013-03-07 22:10:33 +00001617 IRBuilder<> IRB(&SI);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001618 Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) };
1619 AllocaPartitioning::iterator PIs[2];
Chandler Carruthf74654d2013-03-18 08:36:46 +00001620 PartitionUse PUs[2];
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001621 for (unsigned i = 0, e = 2; i != e; ++i) {
1622 PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]);
1623 if (PIs[i] != P.end()) {
1624 // If the pointer is within the partitioning, remove the select from
1625 // its uses. We'll add in the new loads below.
1626 AllocaPartitioning::use_iterator UI
1627 = P.findPartitionUseForPHIOrSelectOperand(Ops[i]);
1628 PUs[i] = *UI;
1629 // Clear out the use here so that the offsets into the use list remain
1630 // stable but this use is ignored when rewriting.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001631 UI->setUse(0);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001632 }
1633 }
1634
1635 Value *TV = SI.getTrueValue();
1636 Value *FV = SI.getFalseValue();
1637 // Replace the loads of the select with a select of two loads.
1638 while (!Loads.empty()) {
1639 LoadInst *LI = Loads.pop_back_val();
1640
1641 IRB.SetInsertPoint(LI);
1642 LoadInst *TL =
1643 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1644 LoadInst *FL =
1645 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1646 NumLoadsSpeculated += 2;
1647
1648 // Transfer alignment and TBAA info if present.
1649 TL->setAlignment(LI->getAlignment());
1650 FL->setAlignment(LI->getAlignment());
1651 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1652 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1653 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1654 }
1655
1656 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1657 LI->getName() + ".sroa.speculated");
1658
1659 LoadInst *Loads[2] = { TL, FL };
1660 for (unsigned i = 0, e = 2; i != e; ++i) {
1661 if (PIs[i] != P.end()) {
1662 Use *LoadUse = &Loads[i]->getOperandUse(0);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001663 assert(PUs[i].getUse()->get() == LoadUse->get());
1664 PUs[i].setUse(LoadUse);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001665 P.use_push_back(PIs[i], PUs[i]);
1666 }
1667 }
1668
1669 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1670 LI->replaceAllUsesWith(V);
Chandler Carruth18db7952012-11-20 01:12:50 +00001671 Pass.DeadInsts.insert(LI);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001672 }
1673 }
1674};
1675}
1676
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001677/// \brief Build a GEP out of a base pointer and indices.
1678///
1679/// This will return the BasePtr if that is valid, or build a new GEP
1680/// instruction using the IRBuilder if GEP-ing is needed.
1681static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1682 SmallVectorImpl<Value *> &Indices,
1683 const Twine &Prefix) {
1684 if (Indices.empty())
1685 return BasePtr;
1686
1687 // A single zero index is a no-op, so check for this and avoid building a GEP
1688 // in that case.
1689 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1690 return BasePtr;
1691
1692 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1693}
1694
1695/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1696/// TargetTy without changing the offset of the pointer.
1697///
1698/// This routine assumes we've already established a properly offset GEP with
1699/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1700/// zero-indices down through type layers until we find one the same as
1701/// TargetTy. If we can't find one with the same type, we at least try to use
1702/// one with the same size. If none of that works, we just produce the GEP as
1703/// indicated by Indices to have the correct offset.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001704static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001705 Value *BasePtr, Type *Ty, Type *TargetTy,
1706 SmallVectorImpl<Value *> &Indices,
1707 const Twine &Prefix) {
1708 if (Ty == TargetTy)
1709 return buildGEP(IRB, BasePtr, Indices, Prefix);
1710
1711 // See if we can descend into a struct and locate a field with the correct
1712 // type.
1713 unsigned NumLayers = 0;
1714 Type *ElementTy = Ty;
1715 do {
1716 if (ElementTy->isPointerTy())
1717 break;
1718 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1719 ElementTy = SeqTy->getElementType();
Chandler Carruth40617f52012-10-17 07:22:16 +00001720 // Note that we use the default address space as this index is over an
1721 // array or a vector, not a pointer.
1722 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(0), 0)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001723 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001724 if (STy->element_begin() == STy->element_end())
1725 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001726 ElementTy = *STy->element_begin();
1727 Indices.push_back(IRB.getInt32(0));
1728 } else {
1729 break;
1730 }
1731 ++NumLayers;
1732 } while (ElementTy != TargetTy);
1733 if (ElementTy != TargetTy)
1734 Indices.erase(Indices.end() - NumLayers, Indices.end());
1735
1736 return buildGEP(IRB, BasePtr, Indices, Prefix);
1737}
1738
1739/// \brief Recursively compute indices for a natural GEP.
1740///
1741/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1742/// element types adding appropriate indices for the GEP.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001743static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001744 Value *Ptr, Type *Ty, APInt &Offset,
1745 Type *TargetTy,
1746 SmallVectorImpl<Value *> &Indices,
1747 const Twine &Prefix) {
1748 if (Offset == 0)
1749 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1750
1751 // We can't recurse through pointer types.
1752 if (Ty->isPointerTy())
1753 return 0;
1754
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001755 // We try to analyze GEPs over vectors here, but note that these GEPs are
1756 // extremely poorly defined currently. The long-term goal is to remove GEPing
1757 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001758 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Nadav Rotema5024fc2012-12-18 05:23:31 +00001759 unsigned ElementSizeInBits = TD.getTypeSizeInBits(VecTy->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001760 if (ElementSizeInBits % 8)
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001761 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001762 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001763 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001764 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1765 return 0;
1766 Offset -= NumSkippedElements * ElementSize;
1767 Indices.push_back(IRB.getInt(NumSkippedElements));
1768 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1769 Offset, TargetTy, Indices, Prefix);
1770 }
1771
1772 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1773 Type *ElementTy = ArrTy->getElementType();
1774 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001775 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001776 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1777 return 0;
1778
1779 Offset -= NumSkippedElements * ElementSize;
1780 Indices.push_back(IRB.getInt(NumSkippedElements));
1781 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1782 Indices, Prefix);
1783 }
1784
1785 StructType *STy = dyn_cast<StructType>(Ty);
1786 if (!STy)
1787 return 0;
1788
1789 const StructLayout *SL = TD.getStructLayout(STy);
1790 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001791 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001792 return 0;
1793 unsigned Index = SL->getElementContainingOffset(StructOffset);
1794 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1795 Type *ElementTy = STy->getElementType(Index);
1796 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1797 return 0; // The offset points into alignment padding.
1798
1799 Indices.push_back(IRB.getInt32(Index));
1800 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1801 Indices, Prefix);
1802}
1803
1804/// \brief Get a natural GEP from a base pointer to a particular offset and
1805/// resulting in a particular type.
1806///
1807/// The goal is to produce a "natural" looking GEP that works with the existing
1808/// composite types to arrive at the appropriate offset and element type for
1809/// a pointer. TargetTy is the element type the returned GEP should point-to if
1810/// possible. We recurse by decreasing Offset, adding the appropriate index to
1811/// Indices, and setting Ty to the result subtype.
1812///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001813/// If no natural GEP can be constructed, this function returns null.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001814static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001815 Value *Ptr, APInt Offset, Type *TargetTy,
1816 SmallVectorImpl<Value *> &Indices,
1817 const Twine &Prefix) {
1818 PointerType *Ty = cast<PointerType>(Ptr->getType());
1819
1820 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1821 // an i8.
1822 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1823 return 0;
1824
1825 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001826 if (!ElementTy->isSized())
1827 return 0; // We can't GEP through an unsized element.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001828 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1829 if (ElementSize == 0)
1830 return 0; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001831 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001832
1833 Offset -= NumSkippedElements * ElementSize;
1834 Indices.push_back(IRB.getInt(NumSkippedElements));
1835 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1836 Indices, Prefix);
1837}
1838
1839/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1840/// resulting pointer has PointerTy.
1841///
1842/// This tries very hard to compute a "natural" GEP which arrives at the offset
1843/// and produces the pointer type desired. Where it cannot, it will try to use
1844/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1845/// fails, it will try to use an existing i8* and GEP to the byte offset and
1846/// bitcast to the type.
1847///
1848/// The strategy for finding the more natural GEPs is to peel off layers of the
1849/// pointer, walking back through bit casts and GEPs, searching for a base
1850/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001851/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001852/// a single GEP as possible, thus making each GEP more independent of the
1853/// surrounding code.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001854static Value *getAdjustedPtr(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001855 Value *Ptr, APInt Offset, Type *PointerTy,
1856 const Twine &Prefix) {
1857 // Even though we don't look through PHI nodes, we could be called on an
1858 // instruction in an unreachable block, which may be on a cycle.
1859 SmallPtrSet<Value *, 4> Visited;
1860 Visited.insert(Ptr);
1861 SmallVector<Value *, 4> Indices;
1862
1863 // We may end up computing an offset pointer that has the wrong type. If we
1864 // never are able to compute one directly that has the correct type, we'll
1865 // fall back to it, so keep it around here.
1866 Value *OffsetPtr = 0;
1867
1868 // Remember any i8 pointer we come across to re-use if we need to do a raw
1869 // byte offset.
1870 Value *Int8Ptr = 0;
1871 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1872
1873 Type *TargetTy = PointerTy->getPointerElementType();
1874
1875 do {
1876 // First fold any existing GEPs into the offset.
1877 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1878 APInt GEPOffset(Offset.getBitWidth(), 0);
Nuno Lopesb6ad9822012-12-30 16:25:48 +00001879 if (!GEP->accumulateConstantOffset(TD, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001880 break;
1881 Offset += GEPOffset;
1882 Ptr = GEP->getPointerOperand();
1883 if (!Visited.insert(Ptr))
1884 break;
1885 }
1886
1887 // See if we can perform a natural GEP here.
1888 Indices.clear();
1889 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1890 Indices, Prefix)) {
1891 if (P->getType() == PointerTy) {
1892 // Zap any offset pointer that we ended up computing in previous rounds.
1893 if (OffsetPtr && OffsetPtr->use_empty())
1894 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1895 I->eraseFromParent();
1896 return P;
1897 }
1898 if (!OffsetPtr) {
1899 OffsetPtr = P;
1900 }
1901 }
1902
1903 // Stash this pointer if we've found an i8*.
1904 if (Ptr->getType()->isIntegerTy(8)) {
1905 Int8Ptr = Ptr;
1906 Int8PtrOffset = Offset;
1907 }
1908
1909 // Peel off a layer of the pointer and update the offset appropriately.
1910 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1911 Ptr = cast<Operator>(Ptr)->getOperand(0);
1912 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1913 if (GA->mayBeOverridden())
1914 break;
1915 Ptr = GA->getAliasee();
1916 } else {
1917 break;
1918 }
1919 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1920 } while (Visited.insert(Ptr));
1921
1922 if (!OffsetPtr) {
1923 if (!Int8Ptr) {
1924 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1925 Prefix + ".raw_cast");
1926 Int8PtrOffset = Offset;
1927 }
1928
1929 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1930 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1931 Prefix + ".raw_idx");
1932 }
1933 Ptr = OffsetPtr;
1934
1935 // On the off chance we were targeting i8*, guard the bitcast here.
1936 if (Ptr->getType() != PointerTy)
1937 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
1938
1939 return Ptr;
1940}
1941
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001942/// \brief Test whether we can convert a value from the old to the new type.
1943///
1944/// This predicate should be used to guard calls to convertValue in order to
1945/// ensure that we only try to convert viable values. The strategy is that we
1946/// will peel off single element struct and array wrappings to get to an
1947/// underlying value, and convert that value.
1948static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1949 if (OldTy == NewTy)
1950 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001951 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1952 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1953 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1954 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001955 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1956 return false;
1957 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1958 return false;
1959
1960 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1961 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1962 return true;
1963 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1964 return true;
1965 return false;
1966 }
1967
1968 return true;
1969}
1970
1971/// \brief Generic routine to convert an SSA value to a value of a different
1972/// type.
1973///
1974/// This will try various different casting techniques, such as bitcasts,
1975/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1976/// two types for viability with this routine.
1977static Value *convertValue(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
1978 Type *Ty) {
1979 assert(canConvertValue(DL, V->getType(), Ty) &&
1980 "Value not convertable to type");
1981 if (V->getType() == Ty)
1982 return V;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001983 if (IntegerType *OldITy = dyn_cast<IntegerType>(V->getType()))
1984 if (IntegerType *NewITy = dyn_cast<IntegerType>(Ty))
1985 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1986 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001987 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1988 return IRB.CreateIntToPtr(V, Ty);
1989 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1990 return IRB.CreatePtrToInt(V, Ty);
1991
1992 return IRB.CreateBitCast(V, Ty);
1993}
1994
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001995/// \brief Test whether the given alloca partition can be promoted to a vector.
1996///
1997/// This is a quick test to check whether we can rewrite a particular alloca
1998/// partition (and its newly formed alloca) into a vector alloca with only
1999/// whole-vector loads and stores such that it could be promoted to a vector
2000/// SSA value. We only can ensure this for a limited set of operations, and we
2001/// don't want to do the rewrites unless we are confident that the result will
2002/// be promotable, so we have an early test here.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002003static bool isVectorPromotionViable(const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002004 Type *AllocaTy,
2005 AllocaPartitioning &P,
2006 uint64_t PartitionBeginOffset,
2007 uint64_t PartitionEndOffset,
2008 AllocaPartitioning::const_use_iterator I,
2009 AllocaPartitioning::const_use_iterator E) {
2010 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
2011 if (!Ty)
2012 return false;
2013
Nadav Rotema5024fc2012-12-18 05:23:31 +00002014 uint64_t ElementSize = TD.getTypeSizeInBits(Ty->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002015
2016 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2017 // that aren't byte sized.
2018 if (ElementSize % 8)
2019 return false;
Benjamin Kramerc003a452013-01-01 16:13:35 +00002020 assert((TD.getTypeSizeInBits(Ty) % 8) == 0 &&
2021 "vector size not a multiple of element size?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002022 ElementSize /= 8;
2023
2024 for (; I != E; ++I) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002025 Use *U = I->getUse();
2026 if (!U)
Chandler Carruth6c3890b2012-10-02 18:57:13 +00002027 continue; // Skip dead use.
2028
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002029 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
2030 uint64_t BeginIndex = BeginOffset / ElementSize;
2031 if (BeginIndex * ElementSize != BeginOffset ||
2032 BeginIndex >= Ty->getNumElements())
2033 return false;
2034 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
2035 uint64_t EndIndex = EndOffset / ElementSize;
2036 if (EndIndex * ElementSize != EndOffset ||
2037 EndIndex > Ty->getNumElements())
2038 return false;
2039
Chandler Carruth845b73c2012-11-21 08:16:30 +00002040 assert(EndIndex > BeginIndex && "Empty vector!");
2041 uint64_t NumElements = EndIndex - BeginIndex;
2042 Type *PartitionTy
2043 = (NumElements == 1) ? Ty->getElementType()
2044 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002045
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002046 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002047 if (MI->isVolatile())
2048 return false;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002049 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U->getUser())) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002050 const AllocaPartitioning::MemTransferOffsets &MTO
2051 = P.getMemTransferOffsets(*MTI);
2052 if (!MTO.IsSplittable)
2053 return false;
2054 }
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002055 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002056 // Disable vector promotion when there are loads or stores of an FCA.
2057 return false;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002058 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002059 if (LI->isVolatile())
2060 return false;
Chandler Carruth845b73c2012-11-21 08:16:30 +00002061 if (!canConvertValue(TD, PartitionTy, LI->getType()))
2062 return false;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002063 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002064 if (SI->isVolatile())
2065 return false;
Chandler Carruth845b73c2012-11-21 08:16:30 +00002066 if (!canConvertValue(TD, SI->getValueOperand()->getType(), PartitionTy))
2067 return false;
Chandler Carruth18db7952012-11-20 01:12:50 +00002068 } else {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002069 return false;
2070 }
2071 }
2072 return true;
2073}
2074
Chandler Carruth435c4e02012-10-15 08:40:30 +00002075/// \brief Test whether the given alloca partition's integer operations can be
2076/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002077///
Chandler Carruth435c4e02012-10-15 08:40:30 +00002078/// This is a quick test to check whether we can rewrite the integer loads and
2079/// stores to a particular alloca into wider loads and stores and be able to
2080/// promote the resulting alloca.
2081static bool isIntegerWideningViable(const DataLayout &TD,
2082 Type *AllocaTy,
2083 uint64_t AllocBeginOffset,
2084 AllocaPartitioning &P,
2085 AllocaPartitioning::const_use_iterator I,
2086 AllocaPartitioning::const_use_iterator E) {
2087 uint64_t SizeInBits = TD.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00002088 // Don't create integer types larger than the maximum bitwidth.
2089 if (SizeInBits > IntegerType::MAX_INT_BITS)
2090 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002091
2092 // Don't try to handle allocas with bit-padding.
2093 if (SizeInBits != TD.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002094 return false;
2095
Chandler Carruth58d05562012-10-25 04:37:07 +00002096 // We need to ensure that an integer type with the appropriate bitwidth can
2097 // be converted to the alloca type, whatever that is. We don't want to force
2098 // the alloca itself to have an integer type if there is a more suitable one.
2099 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2100 if (!canConvertValue(TD, AllocaTy, IntTy) ||
2101 !canConvertValue(TD, IntTy, AllocaTy))
2102 return false;
2103
Chandler Carruth435c4e02012-10-15 08:40:30 +00002104 uint64_t Size = TD.getTypeStoreSize(AllocaTy);
2105
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002106 // Check the uses to ensure the uses are (likely) promotable integer uses.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002107 // Also ensure that the alloca has a covering load or store. We don't want
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002108 // to widen the integer operations only to fail to promote due to some other
Chandler Carruth435c4e02012-10-15 08:40:30 +00002109 // unsplittable entry (which we may make splittable later).
Chandler Carruth92924fd2012-09-24 00:34:20 +00002110 bool WholeAllocaOp = false;
2111 for (; I != E; ++I) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002112 Use *U = I->getUse();
2113 if (!U)
Chandler Carruth6c3890b2012-10-02 18:57:13 +00002114 continue; // Skip dead use.
Chandler Carruth43c8b462012-10-04 10:39:28 +00002115
Chandler Carruth435c4e02012-10-15 08:40:30 +00002116 uint64_t RelBegin = I->BeginOffset - AllocBeginOffset;
2117 uint64_t RelEnd = I->EndOffset - AllocBeginOffset;
2118
Chandler Carruth43c8b462012-10-04 10:39:28 +00002119 // We can't reasonably handle cases where the load or store extends past
2120 // the end of the aloca's type and into its padding.
Chandler Carruth435c4e02012-10-15 08:40:30 +00002121 if (RelEnd > Size)
Chandler Carruth43c8b462012-10-04 10:39:28 +00002122 return false;
2123
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002124 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruth435c4e02012-10-15 08:40:30 +00002125 if (LI->isVolatile())
Chandler Carruth92924fd2012-09-24 00:34:20 +00002126 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002127 if (RelBegin == 0 && RelEnd == Size)
Chandler Carruth92924fd2012-09-24 00:34:20 +00002128 WholeAllocaOp = true;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002129 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruthe45f4652012-12-10 00:54:45 +00002130 if (ITy->getBitWidth() < TD.getTypeStoreSizeInBits(ITy))
Chandler Carruth435c4e02012-10-15 08:40:30 +00002131 return false;
2132 continue;
2133 }
2134 // Non-integer loads need to be convertible from the alloca type so that
2135 // they are promotable.
2136 if (RelBegin != 0 || RelEnd != Size ||
2137 !canConvertValue(TD, AllocaTy, LI->getType()))
2138 return false;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002139 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruth435c4e02012-10-15 08:40:30 +00002140 Type *ValueTy = SI->getValueOperand()->getType();
2141 if (SI->isVolatile())
Chandler Carruth92924fd2012-09-24 00:34:20 +00002142 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002143 if (RelBegin == 0 && RelEnd == Size)
Chandler Carruth92924fd2012-09-24 00:34:20 +00002144 WholeAllocaOp = true;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002145 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruthe45f4652012-12-10 00:54:45 +00002146 if (ITy->getBitWidth() < TD.getTypeStoreSizeInBits(ITy))
Chandler Carruth435c4e02012-10-15 08:40:30 +00002147 return false;
2148 continue;
2149 }
2150 // Non-integer stores need to be convertible to the alloca type so that
2151 // they are promotable.
2152 if (RelBegin != 0 || RelEnd != Size ||
2153 !canConvertValue(TD, ValueTy, AllocaTy))
2154 return false;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002155 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
Chandler Carruthe3f41192012-12-17 18:48:07 +00002156 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002157 return false;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002158 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U->getUser())) {
Chandler Carruth92924fd2012-09-24 00:34:20 +00002159 const AllocaPartitioning::MemTransferOffsets &MTO
2160 = P.getMemTransferOffsets(*MTI);
2161 if (!MTO.IsSplittable)
2162 return false;
2163 }
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002164 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
Chandler Carruth435c4e02012-10-15 08:40:30 +00002165 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2166 II->getIntrinsicID() != Intrinsic::lifetime_end)
2167 return false;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002168 } else {
2169 return false;
2170 }
2171 }
2172 return WholeAllocaOp;
2173}
2174
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002175static Value *extractInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2176 IntegerType *Ty, uint64_t Offset,
2177 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002178 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002179 IntegerType *IntTy = cast<IntegerType>(V->getType());
2180 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2181 "Element extends past full value");
2182 uint64_t ShAmt = 8*Offset;
2183 if (DL.isBigEndian())
2184 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002185 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002186 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002187 DEBUG(dbgs() << " shifted: " << *V << "\n");
2188 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002189 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2190 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002191 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002192 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00002193 DEBUG(dbgs() << " trunced: " << *V << "\n");
2194 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002195 return V;
2196}
2197
2198static Value *insertInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *Old,
2199 Value *V, uint64_t Offset, const Twine &Name) {
2200 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2201 IntegerType *Ty = cast<IntegerType>(V->getType());
2202 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2203 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002204 DEBUG(dbgs() << " start: " << *V << "\n");
2205 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002206 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00002207 DEBUG(dbgs() << " extended: " << *V << "\n");
2208 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002209 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2210 "Element store outside of alloca store");
2211 uint64_t ShAmt = 8*Offset;
2212 if (DL.isBigEndian())
2213 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002214 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002215 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002216 DEBUG(dbgs() << " shifted: " << *V << "\n");
2217 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002218
2219 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2220 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2221 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00002222 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002223 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00002224 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002225 }
2226 return V;
2227}
2228
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002229static Value *extractVector(IRBuilder<> &IRB, Value *V,
2230 unsigned BeginIndex, unsigned EndIndex,
2231 const Twine &Name) {
2232 VectorType *VecTy = cast<VectorType>(V->getType());
2233 unsigned NumElements = EndIndex - BeginIndex;
2234 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2235
2236 if (NumElements == VecTy->getNumElements())
2237 return V;
2238
2239 if (NumElements == 1) {
2240 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2241 Name + ".extract");
2242 DEBUG(dbgs() << " extract: " << *V << "\n");
2243 return V;
2244 }
2245
2246 SmallVector<Constant*, 8> Mask;
2247 Mask.reserve(NumElements);
2248 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2249 Mask.push_back(IRB.getInt32(i));
2250 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2251 ConstantVector::get(Mask),
2252 Name + ".extract");
2253 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2254 return V;
2255}
2256
Chandler Carruthce4562b2012-12-17 13:41:21 +00002257static Value *insertVector(IRBuilder<> &IRB, Value *Old, Value *V,
2258 unsigned BeginIndex, const Twine &Name) {
2259 VectorType *VecTy = cast<VectorType>(Old->getType());
2260 assert(VecTy && "Can only insert a vector into a vector");
2261
2262 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2263 if (!Ty) {
2264 // Single element to insert.
2265 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2266 Name + ".insert");
2267 DEBUG(dbgs() << " insert: " << *V << "\n");
2268 return V;
2269 }
2270
2271 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2272 "Too many elements!");
2273 if (Ty->getNumElements() == VecTy->getNumElements()) {
2274 assert(V->getType() == VecTy && "Vector type mismatch");
2275 return V;
2276 }
2277 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2278
2279 // When inserting a smaller vector into the larger to store, we first
2280 // use a shuffle vector to widen it with undef elements, and then
2281 // a second shuffle vector to select between the loaded vector and the
2282 // incoming vector.
2283 SmallVector<Constant*, 8> Mask;
2284 Mask.reserve(VecTy->getNumElements());
2285 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2286 if (i >= BeginIndex && i < EndIndex)
2287 Mask.push_back(IRB.getInt32(i - BeginIndex));
2288 else
2289 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2290 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2291 ConstantVector::get(Mask),
2292 Name + ".expand");
2293 DEBUG(dbgs() << " shuffle1: " << *V << "\n");
2294
2295 Mask.clear();
2296 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2297 if (i >= BeginIndex && i < EndIndex)
2298 Mask.push_back(IRB.getInt32(i));
2299 else
2300 Mask.push_back(IRB.getInt32(i + VecTy->getNumElements()));
2301 V = IRB.CreateShuffleVector(V, Old, ConstantVector::get(Mask),
2302 Name + "insert");
2303 DEBUG(dbgs() << " shuffle2: " << *V << "\n");
2304 return V;
2305}
2306
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002307namespace {
2308/// \brief Visitor to rewrite instructions using a partition of an alloca to
2309/// use a new alloca.
2310///
2311/// Also implements the rewriting to vector-based accesses when the partition
2312/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2313/// lives here.
2314class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
2315 bool> {
2316 // Befriend the base class so it can delegate to private visit methods.
2317 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
2318
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002319 const DataLayout &TD;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002320 AllocaPartitioning &P;
2321 SROA &Pass;
2322 AllocaInst &OldAI, &NewAI;
2323 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002324 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002325
2326 // If we are rewriting an alloca partition which can be written as pure
2327 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002328 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002329 // - The new alloca is exactly the size of the vector type here.
2330 // - The accesses all either map to the entire vector or to a single
2331 // element.
2332 // - The set of accessing instructions is only one of those handled above
2333 // in isVectorPromotionViable. Generally these are the same access kinds
2334 // which are promotable via mem2reg.
2335 VectorType *VecTy;
2336 Type *ElementTy;
2337 uint64_t ElementSize;
2338
Chandler Carruth92924fd2012-09-24 00:34:20 +00002339 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth435c4e02012-10-15 08:40:30 +00002340 // alloca's integer operations should be widened to this integer type due to
2341 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruth92924fd2012-09-24 00:34:20 +00002342 // integer type will be stored here for easy access during rewriting.
Chandler Carruth435c4e02012-10-15 08:40:30 +00002343 IntegerType *IntTy;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002344
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002345 // The offset of the partition user currently being rewritten.
2346 uint64_t BeginOffset, EndOffset;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002347 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002348 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002349 Instruction *OldPtr;
2350
2351 // The name prefix to use when rewriting instructions for this alloca.
2352 std::string NamePrefix;
2353
2354public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002355 AllocaPartitionRewriter(const DataLayout &TD, AllocaPartitioning &P,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002356 AllocaPartitioning::iterator PI,
2357 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
2358 uint64_t NewBeginOffset, uint64_t NewEndOffset)
2359 : TD(TD), P(P), Pass(Pass),
2360 OldAI(OldAI), NewAI(NewAI),
2361 NewAllocaBeginOffset(NewBeginOffset),
2362 NewAllocaEndOffset(NewEndOffset),
Chandler Carruth891fec02012-10-13 02:41:05 +00002363 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruth435c4e02012-10-15 08:40:30 +00002364 VecTy(), ElementTy(), ElementSize(), IntTy(),
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002365 BeginOffset(), EndOffset(), IsSplit(), OldUse(), OldPtr() {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002366 }
2367
2368 /// \brief Visit the users of the alloca partition and rewrite them.
2369 bool visitUsers(AllocaPartitioning::const_use_iterator I,
2370 AllocaPartitioning::const_use_iterator E) {
2371 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
2372 NewAllocaBeginOffset, NewAllocaEndOffset,
2373 I, E)) {
2374 ++NumVectorized;
2375 VecTy = cast<VectorType>(NewAI.getAllocatedType());
2376 ElementTy = VecTy->getElementType();
Nadav Rotema5024fc2012-12-18 05:23:31 +00002377 assert((TD.getTypeSizeInBits(VecTy->getScalarType()) % 8) == 0 &&
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002378 "Only multiple-of-8 sized vector elements are viable");
Nadav Rotema5024fc2012-12-18 05:23:31 +00002379 ElementSize = TD.getTypeSizeInBits(VecTy->getScalarType()) / 8;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002380 } else if (isIntegerWideningViable(TD, NewAI.getAllocatedType(),
2381 NewAllocaBeginOffset, P, I, E)) {
2382 IntTy = Type::getIntNTy(NewAI.getContext(),
2383 TD.getTypeSizeInBits(NewAI.getAllocatedType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002384 }
2385 bool CanSROA = true;
2386 for (; I != E; ++I) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002387 if (!I->getUse())
Chandler Carruth6c3890b2012-10-02 18:57:13 +00002388 continue; // Skip dead uses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002389 BeginOffset = I->BeginOffset;
2390 EndOffset = I->EndOffset;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002391 IsSplit = I->isSplit();
2392 OldUse = I->getUse();
2393 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002394 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002395 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002396 }
2397 if (VecTy) {
2398 assert(CanSROA);
2399 VecTy = 0;
2400 ElementTy = 0;
2401 ElementSize = 0;
2402 }
Chandler Carruth435c4e02012-10-15 08:40:30 +00002403 if (IntTy) {
2404 assert(CanSROA);
2405 IntTy = 0;
2406 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002407 return CanSROA;
2408 }
2409
2410private:
2411 // Every instruction which can end up as a user must have a rewrite rule.
2412 bool visitInstruction(Instruction &I) {
2413 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2414 llvm_unreachable("No rewrite rule for this instruction!");
2415 }
2416
2417 Twine getName(const Twine &Suffix) {
2418 return NamePrefix + Suffix;
2419 }
2420
2421 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
2422 assert(BeginOffset >= NewAllocaBeginOffset);
Chandler Carruth5da3f052012-11-01 09:14:31 +00002423 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002424 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
2425 }
2426
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002427 /// \brief Compute suitable alignment to access an offset into the new alloca.
2428 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002429 unsigned NewAIAlign = NewAI.getAlignment();
2430 if (!NewAIAlign)
2431 NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
2432 return MinAlign(NewAIAlign, Offset);
2433 }
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002434
2435 /// \brief Compute suitable alignment to access this partition of the new
2436 /// alloca.
2437 unsigned getPartitionAlign() {
2438 return getOffsetAlign(BeginOffset - NewAllocaBeginOffset);
Chandler Carruth176ca712012-10-01 12:16:54 +00002439 }
2440
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002441 /// \brief Compute suitable alignment to access a type at an offset of the
2442 /// new alloca.
2443 ///
2444 /// \returns zero if the type's ABI alignment is a suitable alignment,
2445 /// otherwise returns the maximal suitable alignment.
2446 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2447 unsigned Align = getOffsetAlign(Offset);
2448 return Align == TD.getABITypeAlignment(Ty) ? 0 : Align;
2449 }
2450
2451 /// \brief Compute suitable alignment to access a type at the beginning of
2452 /// this partition of the new alloca.
2453 ///
2454 /// See \c getOffsetTypeAlign for details; this routine delegates to it.
2455 unsigned getPartitionTypeAlign(Type *Ty) {
2456 return getOffsetTypeAlign(Ty, BeginOffset - NewAllocaBeginOffset);
Chandler Carruth176ca712012-10-01 12:16:54 +00002457 }
2458
Chandler Carruth845b73c2012-11-21 08:16:30 +00002459 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002460 assert(VecTy && "Can only call getIndex when rewriting a vector");
2461 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2462 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2463 uint32_t Index = RelOffset / ElementSize;
2464 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002465 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002466 }
2467
2468 void deleteIfTriviallyDead(Value *V) {
2469 Instruction *I = cast<Instruction>(V);
2470 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002471 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002472 }
2473
Chandler Carruth769445e2012-12-17 12:50:21 +00002474 Value *rewriteVectorizedLoadInst(IRBuilder<> &IRB) {
2475 unsigned BeginIndex = getIndex(BeginOffset);
2476 unsigned EndIndex = getIndex(EndOffset);
2477 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002478
2479 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2480 getName(".load"));
2481 return extractVector(IRB, V, BeginIndex, EndIndex, getName(".vec"));
Chandler Carruth769445e2012-12-17 12:50:21 +00002482 }
2483
Chandler Carruth18db7952012-11-20 01:12:50 +00002484 Value *rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002485 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002486 assert(!LI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002487 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2488 getName(".load"));
2489 V = convertValue(TD, IRB, V, IntTy);
2490 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2491 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth18db7952012-11-20 01:12:50 +00002492 if (Offset > 0 || EndOffset < NewAllocaEndOffset)
2493 V = extractInteger(TD, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2494 getName(".extract"));
2495 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002496 }
2497
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002498 bool visitLoadInst(LoadInst &LI) {
2499 DEBUG(dbgs() << " original: " << LI << "\n");
2500 Value *OldOp = LI.getOperand(0);
2501 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002502
Chandler Carruth58d05562012-10-25 04:37:07 +00002503 uint64_t Size = EndOffset - BeginOffset;
Chandler Carruth3e994a22012-11-20 10:02:19 +00002504
Jakub Staszakdb4579d2013-03-07 22:10:33 +00002505 IRBuilder<> IRB(&LI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002506 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), Size * 8)
2507 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002508 bool IsPtrAdjusted = false;
2509 Value *V;
2510 if (VecTy) {
Chandler Carruth769445e2012-12-17 12:50:21 +00002511 V = rewriteVectorizedLoadInst(IRB);
Chandler Carruth18db7952012-11-20 01:12:50 +00002512 } else if (IntTy && LI.getType()->isIntegerTy()) {
2513 V = rewriteIntegerLoad(IRB, LI);
2514 } else if (BeginOffset == NewAllocaBeginOffset &&
2515 canConvertValue(TD, NewAllocaTy, LI.getType())) {
2516 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2517 LI.isVolatile(), getName(".load"));
2518 } else {
2519 Type *LTy = TargetTy->getPointerTo();
2520 V = IRB.CreateAlignedLoad(getAdjustedAllocaPtr(IRB, LTy),
2521 getPartitionTypeAlign(TargetTy),
2522 LI.isVolatile(), getName(".load"));
2523 IsPtrAdjusted = true;
2524 }
2525 V = convertValue(TD, IRB, V, TargetTy);
2526
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002527 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002528 assert(!LI.isVolatile());
2529 assert(LI.getType()->isIntegerTy() &&
2530 "Only integer type loads and stores are split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002531 assert(Size < TD.getTypeStoreSize(LI.getType()) &&
2532 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002533 assert(LI.getType()->getIntegerBitWidth() ==
2534 TD.getTypeStoreSizeInBits(LI.getType()) &&
2535 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002536 // Move the insertion point just past the load so that we can refer to it.
2537 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002538 // Create a placeholder value with the same type as LI to use as the
2539 // basis for the new value. This allows us to replace the uses of LI with
2540 // the computed value, and then replace the placeholder with LI, leaving
2541 // LI only used for this computation.
2542 Value *Placeholder
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002543 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth58d05562012-10-25 04:37:07 +00002544 V = insertInteger(TD, IRB, Placeholder, V, BeginOffset,
2545 getName(".insert"));
2546 LI.replaceAllUsesWith(V);
2547 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002548 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002549 } else {
2550 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002551 }
2552
Chandler Carruth18db7952012-11-20 01:12:50 +00002553 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002554 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002555 DEBUG(dbgs() << " to: " << *V << "\n");
2556 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002557 }
2558
Chandler Carruth18db7952012-11-20 01:12:50 +00002559 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, Value *V,
2560 StoreInst &SI, Value *OldOp) {
Chandler Carruth845b73c2012-11-21 08:16:30 +00002561 unsigned BeginIndex = getIndex(BeginOffset);
2562 unsigned EndIndex = getIndex(EndOffset);
2563 assert(EndIndex > BeginIndex && "Empty vector!");
2564 unsigned NumElements = EndIndex - BeginIndex;
2565 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2566 Type *PartitionTy
2567 = (NumElements == 1) ? ElementTy
2568 : VectorType::get(ElementTy, NumElements);
2569 if (V->getType() != PartitionTy)
2570 V = convertValue(TD, IRB, V, PartitionTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002571
Chandler Carrutheae65a52012-12-17 04:07:35 +00002572 // Mix in the existing elements.
Chandler Carruthce4562b2012-12-17 13:41:21 +00002573 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2574 getName(".load"));
2575 V = insertVector(IRB, Old, V, BeginIndex, getName(".vec"));
Chandler Carrutheae65a52012-12-17 04:07:35 +00002576
Chandler Carruth871ba722012-09-26 10:27:46 +00002577 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002578 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002579
2580 (void)Store;
2581 DEBUG(dbgs() << " to: " << *Store << "\n");
2582 return true;
2583 }
2584
Chandler Carruth18db7952012-11-20 01:12:50 +00002585 bool rewriteIntegerStore(IRBuilder<> &IRB, Value *V, StoreInst &SI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002586 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002587 assert(!SI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002588 if (TD.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2589 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2590 getName(".oldload"));
2591 Old = convertValue(TD, IRB, Old, IntTy);
2592 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2593 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2594 V = insertInteger(TD, IRB, Old, SI.getValueOperand(), Offset,
2595 getName(".insert"));
2596 }
2597 V = convertValue(TD, IRB, V, NewAllocaTy);
2598 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002599 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002600 (void)Store;
2601 DEBUG(dbgs() << " to: " << *Store << "\n");
2602 return true;
2603 }
2604
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002605 bool visitStoreInst(StoreInst &SI) {
2606 DEBUG(dbgs() << " original: " << SI << "\n");
2607 Value *OldOp = SI.getOperand(1);
2608 assert(OldOp == OldPtr);
2609 IRBuilder<> IRB(&SI);
2610
Chandler Carruth18db7952012-11-20 01:12:50 +00002611 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002612
Chandler Carruthac8317f2012-10-04 12:33:50 +00002613 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2614 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002615 if (V->getType()->isPointerTy())
2616 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002617 Pass.PostPromotionWorklist.insert(AI);
2618
Chandler Carruth18db7952012-11-20 01:12:50 +00002619 uint64_t Size = EndOffset - BeginOffset;
2620 if (Size < TD.getTypeStoreSize(V->getType())) {
2621 assert(!SI.isVolatile());
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002622 assert(IsSplit && "A seemingly split store isn't splittable");
Chandler Carruth18db7952012-11-20 01:12:50 +00002623 assert(V->getType()->isIntegerTy() &&
2624 "Only integer type loads and stores are split");
2625 assert(V->getType()->getIntegerBitWidth() ==
2626 TD.getTypeStoreSizeInBits(V->getType()) &&
2627 "Non-byte-multiple bit width");
Chandler Carruth18db7952012-11-20 01:12:50 +00002628 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
2629 V = extractInteger(TD, IRB, V, NarrowTy, BeginOffset,
2630 getName(".extract"));
Chandler Carruth891fec02012-10-13 02:41:05 +00002631 }
2632
Chandler Carruth18db7952012-11-20 01:12:50 +00002633 if (VecTy)
2634 return rewriteVectorizedStoreInst(IRB, V, SI, OldOp);
2635 if (IntTy && V->getType()->isIntegerTy())
2636 return rewriteIntegerStore(IRB, V, SI);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002637
Chandler Carruth18db7952012-11-20 01:12:50 +00002638 StoreInst *NewSI;
2639 if (BeginOffset == NewAllocaBeginOffset &&
2640 canConvertValue(TD, V->getType(), NewAllocaTy)) {
2641 V = convertValue(TD, IRB, V, NewAllocaTy);
2642 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2643 SI.isVolatile());
2644 } else {
2645 Value *NewPtr = getAdjustedAllocaPtr(IRB, V->getType()->getPointerTo());
2646 NewSI = IRB.CreateAlignedStore(V, NewPtr,
2647 getPartitionTypeAlign(V->getType()),
2648 SI.isVolatile());
2649 }
2650 (void)NewSI;
2651 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002652 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002653
2654 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2655 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002656 }
2657
Chandler Carruth514f34f2012-12-17 04:07:30 +00002658 /// \brief Compute an integer value from splatting an i8 across the given
2659 /// number of bytes.
2660 ///
2661 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2662 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002663 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002664 ///
2665 /// \param V The i8 value to splat.
2666 /// \param Size The number of bytes in the output (assuming i8 is one byte)
2667 Value *getIntegerSplat(IRBuilder<> &IRB, Value *V, unsigned Size) {
2668 assert(Size > 0 && "Expected a positive number of bytes.");
2669 IntegerType *VTy = cast<IntegerType>(V->getType());
2670 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2671 if (Size == 1)
2672 return V;
2673
2674 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2675 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, getName(".zext")),
2676 ConstantExpr::getUDiv(
2677 Constant::getAllOnesValue(SplatIntTy),
2678 ConstantExpr::getZExt(
2679 Constant::getAllOnesValue(V->getType()),
2680 SplatIntTy)),
2681 getName(".isplat"));
2682 return V;
2683 }
2684
Chandler Carruthccca5042012-12-17 04:07:37 +00002685 /// \brief Compute a vector splat for a given element value.
2686 Value *getVectorSplat(IRBuilder<> &IRB, Value *V, unsigned NumElements) {
Benjamin Kramer614b5e82013-01-01 19:55:16 +00002687 V = IRB.CreateVectorSplat(NumElements, V, NamePrefix);
Chandler Carruthccca5042012-12-17 04:07:37 +00002688 DEBUG(dbgs() << " splat: " << *V << "\n");
2689 return V;
2690 }
2691
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002692 bool visitMemSetInst(MemSetInst &II) {
2693 DEBUG(dbgs() << " original: " << II << "\n");
2694 IRBuilder<> IRB(&II);
2695 assert(II.getRawDest() == OldPtr);
2696
2697 // If the memset has a variable size, it cannot be split, just adjust the
2698 // pointer to the new alloca.
2699 if (!isa<Constant>(II.getLength())) {
2700 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002701 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002702 II.setAlignment(ConstantInt::get(CstTy, getPartitionAlign()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002703
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002704 deleteIfTriviallyDead(OldPtr);
2705 return false;
2706 }
2707
2708 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002709 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002710
2711 Type *AllocaTy = NewAI.getAllocatedType();
2712 Type *ScalarTy = AllocaTy->getScalarType();
2713
2714 // If this doesn't map cleanly onto the alloca type, and that type isn't
2715 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002716 if (!VecTy && !IntTy &&
2717 (BeginOffset != NewAllocaBeginOffset ||
2718 EndOffset != NewAllocaEndOffset ||
2719 !AllocaTy->isSingleValueType() ||
Chandler Carruthccca5042012-12-17 04:07:37 +00002720 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)) ||
2721 TD.getTypeSizeInBits(ScalarTy)%8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002722 Type *SizeTy = II.getLength()->getType();
2723 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002724 CallInst *New
2725 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2726 II.getRawDest()->getType()),
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002727 II.getValue(), Size, getPartitionAlign(),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002728 II.isVolatile());
2729 (void)New;
2730 DEBUG(dbgs() << " to: " << *New << "\n");
2731 return false;
2732 }
2733
2734 // If we can represent this as a simple value, we have to build the actual
2735 // value to store, which requires expanding the byte present in memset to
2736 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002737 // splatting the byte to a sufficiently wide integer, splatting it across
2738 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002739 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002740
Chandler Carruthccca5042012-12-17 04:07:37 +00002741 if (VecTy) {
2742 // If this is a memset of a vectorized alloca, insert it.
2743 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002744
Chandler Carruthccca5042012-12-17 04:07:37 +00002745 unsigned BeginIndex = getIndex(BeginOffset);
2746 unsigned EndIndex = getIndex(EndOffset);
2747 assert(EndIndex > BeginIndex && "Empty vector!");
2748 unsigned NumElements = EndIndex - BeginIndex;
2749 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2750
2751 Value *Splat = getIntegerSplat(IRB, II.getValue(),
2752 TD.getTypeSizeInBits(ElementTy)/8);
Chandler Carruthcacda252012-12-17 14:03:01 +00002753 Splat = convertValue(TD, IRB, Splat, ElementTy);
2754 if (NumElements > 1)
Chandler Carruthccca5042012-12-17 04:07:37 +00002755 Splat = getVectorSplat(IRB, Splat, NumElements);
2756
Chandler Carruthce4562b2012-12-17 13:41:21 +00002757 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2758 getName(".oldload"));
2759 V = insertVector(IRB, Old, Splat, BeginIndex, getName(".vec"));
Chandler Carruthccca5042012-12-17 04:07:37 +00002760 } else if (IntTy) {
2761 // If this is a memset on an alloca where we can widen stores, insert the
2762 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002763 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002764
Benjamin Kramerc003a452013-01-01 16:13:35 +00002765 uint64_t Size = EndOffset - BeginOffset;
Chandler Carruthccca5042012-12-17 04:07:37 +00002766 V = getIntegerSplat(IRB, II.getValue(), Size);
2767
2768 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2769 EndOffset != NewAllocaBeginOffset)) {
2770 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2771 getName(".oldload"));
2772 Old = convertValue(TD, IRB, Old, IntTy);
2773 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2774 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2775 V = insertInteger(TD, IRB, Old, V, Offset, getName(".insert"));
2776 } else {
2777 assert(V->getType() == IntTy &&
2778 "Wrong type for an alloca wide integer!");
2779 }
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002780 V = convertValue(TD, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002781 } else {
2782 // Established these invariants above.
2783 assert(BeginOffset == NewAllocaBeginOffset);
2784 assert(EndOffset == NewAllocaEndOffset);
2785
2786 V = getIntegerSplat(IRB, II.getValue(),
2787 TD.getTypeSizeInBits(ScalarTy)/8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002788 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2789 V = getVectorSplat(IRB, V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002790
2791 V = convertValue(TD, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002792 }
2793
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002794 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002795 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002796 (void)New;
2797 DEBUG(dbgs() << " to: " << *New << "\n");
2798 return !II.isVolatile();
2799 }
2800
2801 bool visitMemTransferInst(MemTransferInst &II) {
2802 // Rewriting of memory transfer instructions can be a bit tricky. We break
2803 // them into two categories: split intrinsics and unsplit intrinsics.
2804
2805 DEBUG(dbgs() << " original: " << II << "\n");
2806 IRBuilder<> IRB(&II);
2807
2808 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2809 bool IsDest = II.getRawDest() == OldPtr;
2810
2811 const AllocaPartitioning::MemTransferOffsets &MTO
2812 = P.getMemTransferOffsets(II);
2813
Chandler Carruth176ca712012-10-01 12:16:54 +00002814 // Compute the relative offset within the transfer.
Chandler Carruth5da3f052012-11-01 09:14:31 +00002815 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chandler Carruth176ca712012-10-01 12:16:54 +00002816 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2817 : MTO.SourceBegin));
2818
2819 unsigned Align = II.getAlignment();
2820 if (Align > 1)
2821 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002822 MinAlign(II.getAlignment(), getPartitionAlign()));
Chandler Carruth176ca712012-10-01 12:16:54 +00002823
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002824 // For unsplit intrinsics, we simply modify the source and destination
2825 // pointers in place. This isn't just an optimization, it is a matter of
2826 // correctness. With unsplit intrinsics we may be dealing with transfers
2827 // within a single alloca before SROA ran, or with transfers that have
2828 // a variable length. We may also be dealing with memmove instead of
2829 // memcpy, and so simply updating the pointers is the necessary for us to
2830 // update both source and dest of a single call.
2831 if (!MTO.IsSplittable) {
2832 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2833 if (IsDest)
2834 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2835 else
2836 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2837
Chandler Carruth208124f2012-09-26 10:59:22 +00002838 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth176ca712012-10-01 12:16:54 +00002839 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruth208124f2012-09-26 10:59:22 +00002840
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002841 DEBUG(dbgs() << " to: " << II << "\n");
2842 deleteIfTriviallyDead(OldOp);
2843 return false;
2844 }
2845 // For split transfer intrinsics we have an incredibly useful assurance:
2846 // the source and destination do not reside within the same alloca, and at
2847 // least one of them does not escape. This means that we can replace
2848 // memmove with memcpy, and we don't need to worry about all manner of
2849 // downsides to splitting and transforming the operations.
2850
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002851 // If this doesn't map cleanly onto the alloca type, and that type isn't
2852 // a single value type, just emit a memcpy.
2853 bool EmitMemCpy
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002854 = !VecTy && !IntTy && (BeginOffset != NewAllocaBeginOffset ||
2855 EndOffset != NewAllocaEndOffset ||
2856 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002857
2858 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2859 // size hasn't been shrunk based on analysis of the viable range, this is
2860 // a no-op.
2861 if (EmitMemCpy && &OldAI == &NewAI) {
2862 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2863 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2864 // Ensure the start lines up.
2865 assert(BeginOffset == OrigBegin);
Benjamin Kramer4622cd72012-09-14 13:08:09 +00002866 (void)OrigBegin;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002867
2868 // Rewrite the size as needed.
2869 if (EndOffset != OrigEnd)
2870 II.setLength(ConstantInt::get(II.getLength()->getType(),
2871 EndOffset - BeginOffset));
2872 return false;
2873 }
2874 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002875 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002876
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002877 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2878 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002879 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002880 if (AllocaInst *AI
2881 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002882 Pass.Worklist.insert(AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002883
2884 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002885 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2886 : II.getRawDest()->getType();
2887
2888 // Compute the other pointer, folding as much as possible to produce
2889 // a single, simple GEP in most cases.
2890 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2891 getName("." + OtherPtr->getName()));
2892
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002893 Value *OurPtr
2894 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2895 : II.getRawSource()->getType());
2896 Type *SizeTy = II.getLength()->getType();
2897 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2898
2899 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2900 IsDest ? OtherPtr : OurPtr,
Chandler Carruth871ba722012-09-26 10:27:46 +00002901 Size, Align, II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002902 (void)New;
2903 DEBUG(dbgs() << " to: " << *New << "\n");
2904 return false;
2905 }
2906
Chandler Carruth08e5f492012-10-03 08:26:28 +00002907 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2908 // is equivalent to 1, but that isn't true if we end up rewriting this as
2909 // a load or store.
2910 if (!Align)
2911 Align = 1;
2912
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002913 bool IsWholeAlloca = BeginOffset == NewAllocaBeginOffset &&
2914 EndOffset == NewAllocaEndOffset;
2915 uint64_t Size = EndOffset - BeginOffset;
2916 unsigned BeginIndex = VecTy ? getIndex(BeginOffset) : 0;
2917 unsigned EndIndex = VecTy ? getIndex(EndOffset) : 0;
2918 unsigned NumElements = EndIndex - BeginIndex;
2919 IntegerType *SubIntTy
2920 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2921
2922 Type *OtherPtrTy = NewAI.getType();
2923 if (VecTy && !IsWholeAlloca) {
2924 if (NumElements == 1)
2925 OtherPtrTy = VecTy->getElementType();
2926 else
2927 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2928
2929 OtherPtrTy = OtherPtrTy->getPointerTo();
2930 } else if (IntTy && !IsWholeAlloca) {
2931 OtherPtrTy = SubIntTy->getPointerTo();
2932 }
2933
2934 Value *SrcPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2935 getName("." + OtherPtr->getName()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002936 Value *DstPtr = &NewAI;
2937 if (!IsDest)
2938 std::swap(SrcPtr, DstPtr);
2939
2940 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002941 if (VecTy && !IsWholeAlloca && !IsDest) {
2942 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2943 getName(".load"));
2944 Src = extractVector(IRB, Src, BeginIndex, EndIndex, getName(".vec"));
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002945 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002946 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2947 getName(".load"));
2948 Src = convertValue(TD, IRB, Src, IntTy);
2949 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2950 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2951 Src = extractInteger(TD, IRB, Src, SubIntTy, Offset, getName(".extract"));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002952 } else {
Chandler Carruth871ba722012-09-26 10:27:46 +00002953 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2954 getName(".copyload"));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002955 }
2956
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002957 if (VecTy && !IsWholeAlloca && IsDest) {
2958 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2959 getName(".oldload"));
2960 Src = insertVector(IRB, Old, Src, BeginIndex, getName(".vec"));
2961 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002962 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2963 getName(".oldload"));
2964 Old = convertValue(TD, IRB, Old, IntTy);
2965 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2966 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2967 Src = insertInteger(TD, IRB, Old, Src, Offset, getName(".insert"));
2968 Src = convertValue(TD, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002969 }
2970
Chandler Carruth871ba722012-09-26 10:27:46 +00002971 StoreInst *Store = cast<StoreInst>(
2972 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2973 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002974 DEBUG(dbgs() << " to: " << *Store << "\n");
2975 return !II.isVolatile();
2976 }
2977
2978 bool visitIntrinsicInst(IntrinsicInst &II) {
2979 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2980 II.getIntrinsicID() == Intrinsic::lifetime_end);
2981 DEBUG(dbgs() << " original: " << II << "\n");
2982 IRBuilder<> IRB(&II);
2983 assert(II.getArgOperand(1) == OldPtr);
2984
2985 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002986 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002987
2988 ConstantInt *Size
2989 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2990 EndOffset - BeginOffset);
2991 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2992 Value *New;
2993 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2994 New = IRB.CreateLifetimeStart(Ptr, Size);
2995 else
2996 New = IRB.CreateLifetimeEnd(Ptr, Size);
2997
Edwin Vane82f80d42013-01-29 17:42:24 +00002998 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002999 DEBUG(dbgs() << " to: " << *New << "\n");
3000 return true;
3001 }
3002
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003003 bool visitPHINode(PHINode &PN) {
3004 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruth82a57542012-10-01 10:54:05 +00003005
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003006 // We would like to compute a new pointer in only one place, but have it be
3007 // as local as possible to the PHI. To do that, we re-use the location of
3008 // the old pointer, which necessarily must be in the right position to
3009 // dominate the PHI.
3010 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
3011
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003012 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00003013 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003014 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003015
Chandler Carruth82a57542012-10-01 10:54:05 +00003016 DEBUG(dbgs() << " to: " << PN << "\n");
3017 deleteIfTriviallyDead(OldPtr);
3018 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003019 }
3020
3021 bool visitSelectInst(SelectInst &SI) {
3022 DEBUG(dbgs() << " original: " << SI << "\n");
3023 IRBuilder<> IRB(&SI);
3024
3025 // Find the operand we need to rewrite here.
3026 bool IsTrueVal = SI.getTrueValue() == OldPtr;
3027 if (IsTrueVal)
3028 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
3029 else
3030 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
Chandler Carruth82a57542012-10-01 10:54:05 +00003031
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003032 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00003033 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
3034 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003035 deleteIfTriviallyDead(OldPtr);
Chandler Carruth82a57542012-10-01 10:54:05 +00003036 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003037 }
3038
3039};
3040}
3041
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003042namespace {
3043/// \brief Visitor to rewrite aggregate loads and stores as scalar.
3044///
3045/// This pass aggressively rewrites all aggregate loads and stores on
3046/// a particular pointer (or any pointer derived from it which we can identify)
3047/// with scalar loads and stores.
3048class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3049 // Befriend the base class so it can delegate to private visit methods.
3050 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3051
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003052 const DataLayout &TD;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003053
3054 /// Queue of pointer uses to analyze and potentially rewrite.
3055 SmallVector<Use *, 8> Queue;
3056
3057 /// Set to prevent us from cycling with phi nodes and loops.
3058 SmallPtrSet<User *, 8> Visited;
3059
3060 /// The current pointer use being rewritten. This is used to dig up the used
3061 /// value (as opposed to the user).
3062 Use *U;
3063
3064public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003065 AggLoadStoreRewriter(const DataLayout &TD) : TD(TD) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003066
3067 /// Rewrite loads and stores through a pointer and all pointers derived from
3068 /// it.
3069 bool rewrite(Instruction &I) {
3070 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3071 enqueueUsers(I);
3072 bool Changed = false;
3073 while (!Queue.empty()) {
3074 U = Queue.pop_back_val();
3075 Changed |= visit(cast<Instruction>(U->getUser()));
3076 }
3077 return Changed;
3078 }
3079
3080private:
3081 /// Enqueue all the users of the given instruction for further processing.
3082 /// This uses a set to de-duplicate users.
3083 void enqueueUsers(Instruction &I) {
3084 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3085 ++UI)
3086 if (Visited.insert(*UI))
3087 Queue.push_back(&UI.getUse());
3088 }
3089
3090 // Conservative default is to not rewrite anything.
3091 bool visitInstruction(Instruction &I) { return false; }
3092
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003093 /// \brief Generic recursive split emission class.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003094 template <typename Derived>
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003095 class OpSplitter {
3096 protected:
3097 /// The builder used to form new instructions.
3098 IRBuilder<> IRB;
3099 /// The indices which to be used with insert- or extractvalue to select the
3100 /// appropriate value within the aggregate.
3101 SmallVector<unsigned, 4> Indices;
3102 /// The indices to a GEP instruction which will move Ptr to the correct slot
3103 /// within the aggregate.
3104 SmallVector<Value *, 4> GEPIndices;
3105 /// The base pointer of the original op, used as a base for GEPing the
3106 /// split operations.
3107 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003108
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003109 /// Initialize the splitter with an insertion point, Ptr and start with a
3110 /// single zero GEP index.
3111 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003112 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003113
3114 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003115 /// \brief Generic recursive split emission routine.
3116 ///
3117 /// This method recursively splits an aggregate op (load or store) into
3118 /// scalar or vector ops. It splits recursively until it hits a single value
3119 /// and emits that single value operation via the template argument.
3120 ///
3121 /// The logic of this routine relies on GEPs and insertvalue and
3122 /// extractvalue all operating with the same fundamental index list, merely
3123 /// formatted differently (GEPs need actual values).
3124 ///
3125 /// \param Ty The type being split recursively into smaller ops.
3126 /// \param Agg The aggregate value being built up or stored, depending on
3127 /// whether this is splitting a load or a store respectively.
3128 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3129 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003130 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003131
3132 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3133 unsigned OldSize = Indices.size();
3134 (void)OldSize;
3135 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3136 ++Idx) {
3137 assert(Indices.size() == OldSize && "Did not return to the old size");
3138 Indices.push_back(Idx);
3139 GEPIndices.push_back(IRB.getInt32(Idx));
3140 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3141 GEPIndices.pop_back();
3142 Indices.pop_back();
3143 }
3144 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003145 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003146
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003147 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3148 unsigned OldSize = Indices.size();
3149 (void)OldSize;
3150 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3151 ++Idx) {
3152 assert(Indices.size() == OldSize && "Did not return to the old size");
3153 Indices.push_back(Idx);
3154 GEPIndices.push_back(IRB.getInt32(Idx));
3155 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3156 GEPIndices.pop_back();
3157 Indices.pop_back();
3158 }
3159 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003160 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003161
3162 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003163 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003164 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003165
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003166 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003167 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00003168 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003169
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003170 /// Emit a leaf load of a single value. This is called at the leaves of the
3171 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003172 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003173 assert(Ty->isSingleValueType());
3174 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00003175 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
3176 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003177 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3178 DEBUG(dbgs() << " to: " << *Load << "\n");
3179 }
3180 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003181
3182 bool visitLoadInst(LoadInst &LI) {
3183 assert(LI.getPointerOperand() == *U);
3184 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3185 return false;
3186
3187 // We have an aggregate being loaded, split it apart.
3188 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003189 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003190 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003191 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003192 LI.replaceAllUsesWith(V);
3193 LI.eraseFromParent();
3194 return true;
3195 }
3196
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003197 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003198 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00003199 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003200
3201 /// Emit a leaf store of a single value. This is called at the leaves of the
3202 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003203 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003204 assert(Ty->isSingleValueType());
3205 // Extract the single value and store it using the indices.
3206 Value *Store = IRB.CreateStore(
3207 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3208 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
3209 (void)Store;
3210 DEBUG(dbgs() << " to: " << *Store << "\n");
3211 }
3212 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003213
3214 bool visitStoreInst(StoreInst &SI) {
3215 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3216 return false;
3217 Value *V = SI.getValueOperand();
3218 if (V->getType()->isSingleValueType())
3219 return false;
3220
3221 // We have an aggregate being stored, split it apart.
3222 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003223 StoreOpSplitter Splitter(&SI, *U);
3224 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003225 SI.eraseFromParent();
3226 return true;
3227 }
3228
3229 bool visitBitCastInst(BitCastInst &BC) {
3230 enqueueUsers(BC);
3231 return false;
3232 }
3233
3234 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3235 enqueueUsers(GEPI);
3236 return false;
3237 }
3238
3239 bool visitPHINode(PHINode &PN) {
3240 enqueueUsers(PN);
3241 return false;
3242 }
3243
3244 bool visitSelectInst(SelectInst &SI) {
3245 enqueueUsers(SI);
3246 return false;
3247 }
3248};
3249}
3250
Chandler Carruthba931992012-10-13 10:49:33 +00003251/// \brief Strip aggregate type wrapping.
3252///
3253/// This removes no-op aggregate types wrapping an underlying type. It will
3254/// strip as many layers of types as it can without changing either the type
3255/// size or the allocated size.
3256static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3257 if (Ty->isSingleValueType())
3258 return Ty;
3259
3260 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3261 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3262
3263 Type *InnerTy;
3264 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3265 InnerTy = ArrTy->getElementType();
3266 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3267 const StructLayout *SL = DL.getStructLayout(STy);
3268 unsigned Index = SL->getElementContainingOffset(0);
3269 InnerTy = STy->getElementType(Index);
3270 } else {
3271 return Ty;
3272 }
3273
3274 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3275 TypeSize > DL.getTypeSizeInBits(InnerTy))
3276 return Ty;
3277
3278 return stripAggregateTypeWrapping(DL, InnerTy);
3279}
3280
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003281/// \brief Try to find a partition of the aggregate type passed in for a given
3282/// offset and size.
3283///
3284/// This recurses through the aggregate type and tries to compute a subtype
3285/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003286/// of an array, it will even compute a new array type for that sub-section,
3287/// and the same for structs.
3288///
3289/// Note that this routine is very strict and tries to find a partition of the
3290/// type which produces the *exact* right offset and size. It is not forgiving
3291/// when the size or offset cause either end of type-based partition to be off.
3292/// Also, this is a best-effort routine. It is reasonable to give up and not
3293/// return a type if necessary.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003294static Type *getTypePartition(const DataLayout &TD, Type *Ty,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003295 uint64_t Offset, uint64_t Size) {
3296 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
Chandler Carruthba931992012-10-13 10:49:33 +00003297 return stripAggregateTypeWrapping(TD, Ty);
Chandler Carruth58d05562012-10-25 04:37:07 +00003298 if (Offset > TD.getTypeAllocSize(Ty) ||
3299 (TD.getTypeAllocSize(Ty) - Offset) < Size)
3300 return 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003301
3302 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3303 // We can't partition pointers...
3304 if (SeqTy->isPointerTy())
3305 return 0;
3306
3307 Type *ElementTy = SeqTy->getElementType();
3308 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3309 uint64_t NumSkippedElements = Offset / ElementSize;
3310 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
3311 if (NumSkippedElements >= ArrTy->getNumElements())
3312 return 0;
3313 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
3314 if (NumSkippedElements >= VecTy->getNumElements())
3315 return 0;
3316 Offset -= NumSkippedElements * ElementSize;
3317
3318 // First check if we need to recurse.
3319 if (Offset > 0 || Size < ElementSize) {
3320 // Bail if the partition ends in a different array element.
3321 if ((Offset + Size) > ElementSize)
3322 return 0;
3323 // Recurse through the element type trying to peel off offset bytes.
3324 return getTypePartition(TD, ElementTy, Offset, Size);
3325 }
3326 assert(Offset == 0);
3327
3328 if (Size == ElementSize)
Chandler Carruthba931992012-10-13 10:49:33 +00003329 return stripAggregateTypeWrapping(TD, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003330 assert(Size > ElementSize);
3331 uint64_t NumElements = Size / ElementSize;
3332 if (NumElements * ElementSize != Size)
3333 return 0;
3334 return ArrayType::get(ElementTy, NumElements);
3335 }
3336
3337 StructType *STy = dyn_cast<StructType>(Ty);
3338 if (!STy)
3339 return 0;
3340
3341 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003342 if (Offset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003343 return 0;
3344 uint64_t EndOffset = Offset + Size;
3345 if (EndOffset > SL->getSizeInBytes())
3346 return 0;
3347
3348 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003349 Offset -= SL->getElementOffset(Index);
3350
3351 Type *ElementTy = STy->getElementType(Index);
3352 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3353 if (Offset >= ElementSize)
3354 return 0; // The offset points into alignment padding.
3355
3356 // See if any partition must be contained by the element.
3357 if (Offset > 0 || Size < ElementSize) {
3358 if ((Offset + Size) > ElementSize)
3359 return 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003360 return getTypePartition(TD, ElementTy, Offset, Size);
3361 }
3362 assert(Offset == 0);
3363
3364 if (Size == ElementSize)
Chandler Carruthba931992012-10-13 10:49:33 +00003365 return stripAggregateTypeWrapping(TD, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003366
3367 StructType::element_iterator EI = STy->element_begin() + Index,
3368 EE = STy->element_end();
3369 if (EndOffset < SL->getSizeInBytes()) {
3370 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3371 if (Index == EndIndex)
3372 return 0; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003373
3374 // Don't try to form "natural" types if the elements don't line up with the
3375 // expected size.
3376 // FIXME: We could potentially recurse down through the last element in the
3377 // sub-struct to find a natural end point.
3378 if (SL->getElementOffset(EndIndex) != EndOffset)
3379 return 0;
3380
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003381 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003382 EE = STy->element_begin() + EndIndex;
3383 }
3384
3385 // Try to build up a sub-structure.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003386 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003387 STy->isPacked());
3388 const StructLayout *SubSL = TD.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003389 if (Size != SubSL->getSizeInBytes())
3390 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003391
Chandler Carruth054a40a2012-09-14 11:08:31 +00003392 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003393}
3394
3395/// \brief Rewrite an alloca partition's users.
3396///
3397/// This routine drives both of the rewriting goals of the SROA pass. It tries
3398/// to rewrite uses of an alloca partition to be conducive for SSA value
3399/// promotion. If the partition needs a new, more refined alloca, this will
3400/// build that new alloca, preserving as much type information as possible, and
3401/// rewrite the uses of the old alloca to point at the new one and have the
3402/// appropriate new offsets. It also evaluates how successful the rewrite was
3403/// at enabling promotion and if it was successful queues the alloca to be
3404/// promoted.
3405bool SROA::rewriteAllocaPartition(AllocaInst &AI,
3406 AllocaPartitioning &P,
3407 AllocaPartitioning::iterator PI) {
3408 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
Chandler Carruth6c3890b2012-10-02 18:57:13 +00003409 bool IsLive = false;
3410 for (AllocaPartitioning::use_iterator UI = P.use_begin(PI),
3411 UE = P.use_end(PI);
3412 UI != UE && !IsLive; ++UI)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00003413 if (UI->getUse())
Chandler Carruth6c3890b2012-10-02 18:57:13 +00003414 IsLive = true;
3415 if (!IsLive)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003416 return false; // No live uses left of this partition.
3417
Chandler Carruth82a57542012-10-01 10:54:05 +00003418 DEBUG(dbgs() << "Speculating PHIs and selects in partition "
3419 << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
3420
3421 PHIOrSelectSpeculator Speculator(*TD, P, *this);
3422 DEBUG(dbgs() << " speculating ");
3423 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carruth3903e052012-10-02 17:49:47 +00003424 Speculator.visitUsers(PI);
Chandler Carruth82a57542012-10-01 10:54:05 +00003425
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003426 // Try to compute a friendly type for this partition of the alloca. This
3427 // won't always succeed, in which case we fall back to a legal integer type
3428 // or an i8 array of an appropriate size.
3429 Type *AllocaTy = 0;
3430 if (Type *PartitionTy = P.getCommonType(PI))
3431 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
3432 AllocaTy = PartitionTy;
3433 if (!AllocaTy)
3434 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3435 PI->BeginOffset, AllocaSize))
3436 AllocaTy = PartitionTy;
3437 if ((!AllocaTy ||
3438 (AllocaTy->isArrayTy() &&
3439 AllocaTy->getArrayElementType()->isIntegerTy())) &&
3440 TD->isLegalInteger(AllocaSize * 8))
3441 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
3442 if (!AllocaTy)
3443 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
Chandler Carruthb0de6dd2012-09-14 10:26:34 +00003444 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003445
3446 // Check for the case where we're going to rewrite to a new alloca of the
3447 // exact same type as the original, and with the same access offsets. In that
3448 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003449 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003450 AllocaInst *NewAI;
3451 if (AllocaTy == AI.getAllocatedType()) {
3452 assert(PI->BeginOffset == 0 &&
3453 "Non-zero begin offset but same alloca type");
3454 assert(PI == P.begin() && "Begin offset is zero on later partition");
3455 NewAI = &AI;
3456 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003457 unsigned Alignment = AI.getAlignment();
3458 if (!Alignment) {
3459 // The minimum alignment which users can rely on when the explicit
3460 // alignment is omitted or zero is that required by the ABI for this
3461 // type.
3462 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3463 }
3464 Alignment = MinAlign(Alignment, PI->BeginOffset);
3465 // If we will get at least this much alignment from the type alone, leave
3466 // the alloca's alignment unconstrained.
3467 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3468 Alignment = 0;
3469 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003470 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3471 &AI);
3472 ++NumNewAllocas;
3473 }
3474
3475 DEBUG(dbgs() << "Rewriting alloca partition "
3476 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3477 << *NewAI << "\n");
3478
Chandler Carruthac8317f2012-10-04 12:33:50 +00003479 // Track the high watermark of the post-promotion worklist. We will reset it
3480 // to this point if the alloca is not in fact scheduled for promotion.
3481 unsigned PPWOldSize = PostPromotionWorklist.size();
3482
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003483 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3484 PI->BeginOffset, PI->EndOffset);
3485 DEBUG(dbgs() << " rewriting ");
3486 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carruthac8317f2012-10-04 12:33:50 +00003487 bool Promotable = Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI));
3488 if (Promotable) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003489 DEBUG(dbgs() << " and queuing for promotion\n");
3490 PromotableAllocas.push_back(NewAI);
3491 } else if (NewAI != &AI) {
3492 // If we can't promote the alloca, iterate on it to check for new
3493 // refinements exposed by splitting the current alloca. Don't iterate on an
3494 // alloca which didn't actually change and didn't get promoted.
3495 Worklist.insert(NewAI);
3496 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003497
3498 // Drop any post-promotion work items if promotion didn't happen.
3499 if (!Promotable)
3500 while (PostPromotionWorklist.size() > PPWOldSize)
3501 PostPromotionWorklist.pop_back();
3502
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003503 return true;
3504}
3505
3506/// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3507bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3508 bool Changed = false;
3509 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3510 ++PI)
3511 Changed |= rewriteAllocaPartition(AI, P, PI);
3512
3513 return Changed;
3514}
3515
3516/// \brief Analyze an alloca for SROA.
3517///
3518/// This analyzes the alloca to ensure we can reason about it, builds
3519/// a partitioning of the alloca, and then hands it off to be split and
3520/// rewritten as needed.
3521bool SROA::runOnAlloca(AllocaInst &AI) {
3522 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3523 ++NumAllocasAnalyzed;
3524
3525 // Special case dead allocas, as they're trivial.
3526 if (AI.use_empty()) {
3527 AI.eraseFromParent();
3528 return true;
3529 }
3530
3531 // Skip alloca forms that this analysis can't handle.
3532 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3533 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3534 return false;
3535
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003536 bool Changed = false;
3537
3538 // First, split any FCA loads and stores touching this alloca to promote
3539 // better splitting and promotion opportunities.
3540 AggLoadStoreRewriter AggRewriter(*TD);
3541 Changed |= AggRewriter.rewrite(AI);
3542
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003543 // Build the partition set using a recursive instruction-visiting builder.
3544 AllocaPartitioning P(*TD, AI);
3545 DEBUG(P.print(dbgs()));
3546 if (P.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003547 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003548
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003549 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003550 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3551 DE = P.dead_user_end();
3552 DI != DE; ++DI) {
3553 Changed = true;
3554 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
Chandler Carruth18db7952012-11-20 01:12:50 +00003555 DeadInsts.insert(*DI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003556 }
3557 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3558 DE = P.dead_op_end();
3559 DO != DE; ++DO) {
3560 Value *OldV = **DO;
3561 // Clobber the use with an undef value.
3562 **DO = UndefValue::get(OldV->getType());
3563 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3564 if (isInstructionTriviallyDead(OldI)) {
3565 Changed = true;
Chandler Carruth18db7952012-11-20 01:12:50 +00003566 DeadInsts.insert(OldI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003567 }
3568 }
3569
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003570 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3571 if (P.begin() == P.end())
3572 return Changed;
3573
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003574 return splitAlloca(AI, P) || Changed;
3575}
3576
Chandler Carruth19450da2012-09-14 10:26:38 +00003577/// \brief Delete the dead instructions accumulated in this run.
3578///
3579/// Recursively deletes the dead instructions we've accumulated. This is done
3580/// at the very end to maximize locality of the recursive delete and to
3581/// minimize the problems of invalidated instruction pointers as such pointers
3582/// are used heavily in the intermediate stages of the algorithm.
3583///
3584/// We also record the alloca instructions deleted here so that they aren't
3585/// subsequently handed to mem2reg to promote.
3586void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003587 while (!DeadInsts.empty()) {
3588 Instruction *I = DeadInsts.pop_back_val();
3589 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3590
Chandler Carruth58d05562012-10-25 04:37:07 +00003591 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3592
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003593 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3594 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3595 // Zero out the operand and see if it becomes trivially dead.
3596 *OI = 0;
3597 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003598 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003599 }
3600
3601 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3602 DeletedAllocas.insert(AI);
3603
3604 ++NumDeleted;
3605 I->eraseFromParent();
3606 }
3607}
3608
Chandler Carruth70b44c52012-09-15 11:43:14 +00003609/// \brief Promote the allocas, using the best available technique.
3610///
3611/// This attempts to promote whatever allocas have been identified as viable in
3612/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3613/// If there is a domtree available, we attempt to promote using the full power
3614/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3615/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003616/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003617bool SROA::promoteAllocas(Function &F) {
3618 if (PromotableAllocas.empty())
3619 return false;
3620
3621 NumPromoted += PromotableAllocas.size();
3622
3623 if (DT && !ForceSSAUpdater) {
3624 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3625 PromoteMemToReg(PromotableAllocas, *DT);
3626 PromotableAllocas.clear();
3627 return true;
3628 }
3629
3630 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3631 SSAUpdater SSA;
3632 DIBuilder DIB(*F.getParent());
3633 SmallVector<Instruction*, 64> Insts;
3634
3635 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3636 AllocaInst *AI = PromotableAllocas[Idx];
3637 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3638 UI != UE;) {
3639 Instruction *I = cast<Instruction>(*UI++);
3640 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3641 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3642 // leading to them) here. Eventually it should use them to optimize the
3643 // scalar values produced.
3644 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3645 assert(onlyUsedByLifetimeMarkers(I) &&
3646 "Found a bitcast used outside of a lifetime marker.");
3647 while (!I->use_empty())
3648 cast<Instruction>(*I->use_begin())->eraseFromParent();
3649 I->eraseFromParent();
3650 continue;
3651 }
3652 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3653 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3654 II->getIntrinsicID() == Intrinsic::lifetime_end);
3655 II->eraseFromParent();
3656 continue;
3657 }
3658
3659 Insts.push_back(I);
3660 }
3661 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3662 Insts.clear();
3663 }
3664
3665 PromotableAllocas.clear();
3666 return true;
3667}
3668
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003669namespace {
3670 /// \brief A predicate to test whether an alloca belongs to a set.
3671 class IsAllocaInSet {
3672 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3673 const SetType &Set;
3674
3675 public:
Chandler Carruth3f57b822012-10-03 00:03:00 +00003676 typedef AllocaInst *argument_type;
3677
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003678 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth3f57b822012-10-03 00:03:00 +00003679 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003680 };
3681}
3682
3683bool SROA::runOnFunction(Function &F) {
3684 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3685 C = &F.getContext();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003686 TD = getAnalysisIfAvailable<DataLayout>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003687 if (!TD) {
3688 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3689 return false;
3690 }
Chandler Carruth70b44c52012-09-15 11:43:14 +00003691 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003692
3693 BasicBlock &EntryBB = F.getEntryBlock();
3694 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3695 I != E; ++I)
3696 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3697 Worklist.insert(AI);
3698
3699 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003700 // A set of deleted alloca instruction pointers which should be removed from
3701 // the list of promotable allocas.
3702 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3703
Chandler Carruthac8317f2012-10-04 12:33:50 +00003704 do {
3705 while (!Worklist.empty()) {
3706 Changed |= runOnAlloca(*Worklist.pop_back_val());
3707 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003708
Chandler Carruthac8317f2012-10-04 12:33:50 +00003709 // Remove the deleted allocas from various lists so that we don't try to
3710 // continue processing them.
3711 if (!DeletedAllocas.empty()) {
3712 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3713 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3714 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3715 PromotableAllocas.end(),
3716 IsAllocaInSet(DeletedAllocas)),
3717 PromotableAllocas.end());
3718 DeletedAllocas.clear();
3719 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003720 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003721
Chandler Carruthac8317f2012-10-04 12:33:50 +00003722 Changed |= promoteAllocas(F);
3723
3724 Worklist = PostPromotionWorklist;
3725 PostPromotionWorklist.clear();
3726 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003727
3728 return Changed;
3729}
3730
3731void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003732 if (RequiresDomTree)
3733 AU.addRequired<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003734 AU.setPreservesCFG();
3735}