blob: 68d5d3f01a05f15ae394bd89df0102e795da36d6 [file] [log] [blame]
Chandler Carruth713aa942012-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"
28#include "llvm/Constants.h"
29#include "llvm/DIBuilder.h"
30#include "llvm/DebugInfo.h"
31#include "llvm/DerivedTypes.h"
32#include "llvm/Function.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000033#include "llvm/IRBuilder.h"
Chandler Carruth84bcf932012-11-30 03:08:41 +000034#include "llvm/InstVisitor.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000035#include "llvm/Instructions.h"
36#include "llvm/IntrinsicInst.h"
37#include "llvm/LLVMContext.h"
38#include "llvm/Module.h"
39#include "llvm/Operator.h"
40#include "llvm/Pass.h"
41#include "llvm/ADT/SetVector.h"
42#include "llvm/ADT/SmallVector.h"
43#include "llvm/ADT/Statistic.h"
44#include "llvm/ADT/STLExtras.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000045#include "llvm/Analysis/Dominators.h"
46#include "llvm/Analysis/Loads.h"
47#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1c8db502012-09-15 11:43:14 +000048#include "llvm/Support/CommandLine.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000049#include "llvm/Support/Debug.h"
50#include "llvm/Support/ErrorHandling.h"
51#include "llvm/Support/GetElementPtrTypeIterator.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000052#include "llvm/Support/MathExtras.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000053#include "llvm/Support/raw_ostream.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000054#include "llvm/DataLayout.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000055#include "llvm/Transforms/Utils/Local.h"
56#include "llvm/Transforms/Utils/PromoteMemToReg.h"
57#include "llvm/Transforms/Utils/SSAUpdater.h"
58using namespace llvm;
59
60STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
61STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
62STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
63STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
64STATISTIC(NumDeleted, "Number of instructions deleted");
65STATISTIC(NumVectorized, "Number of vectorized aggregates");
66
Chandler Carruth1c8db502012-09-15 11:43:14 +000067/// Hidden option to force the pass to not use DomTree and mem2reg, instead
68/// forming SSA values through the SSAUpdater infrastructure.
69static cl::opt<bool>
70ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
71
Chandler Carruth713aa942012-09-14 09:22:59 +000072namespace {
73/// \brief Alloca partitioning representation.
74///
75/// This class represents a partitioning of an alloca into slices, and
76/// information about the nature of uses of each slice of the alloca. The goal
77/// is that this information is sufficient to decide if and how to split the
78/// alloca apart and replace slices with scalars. It is also intended that this
Chandler Carruth7f5bede2012-09-14 10:18:49 +000079/// structure can capture the relevant information needed both to decide about
Chandler Carruth713aa942012-09-14 09:22:59 +000080/// and to enact these transformations.
81class AllocaPartitioning {
82public:
83 /// \brief A common base class for representing a half-open byte range.
84 struct ByteRange {
85 /// \brief The beginning offset of the range.
86 uint64_t BeginOffset;
87
88 /// \brief The ending offset, not included in the range.
89 uint64_t EndOffset;
90
91 ByteRange() : BeginOffset(), EndOffset() {}
92 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
93 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
94
95 /// \brief Support for ordering ranges.
96 ///
97 /// This provides an ordering over ranges such that start offsets are
98 /// always increasing, and within equal start offsets, the end offsets are
Chandler Carruth7f5bede2012-09-14 10:18:49 +000099 /// decreasing. Thus the spanning range comes first in a cluster with the
Chandler Carruth713aa942012-09-14 09:22:59 +0000100 /// same start position.
101 bool operator<(const ByteRange &RHS) const {
102 if (BeginOffset < RHS.BeginOffset) return true;
103 if (BeginOffset > RHS.BeginOffset) return false;
104 if (EndOffset > RHS.EndOffset) return true;
105 return false;
106 }
107
108 /// \brief Support comparison with a single offset to allow binary searches.
Benjamin Kramer2d1c2a22012-09-17 16:42:36 +0000109 friend bool operator<(const ByteRange &LHS, uint64_t RHSOffset) {
110 return LHS.BeginOffset < RHSOffset;
111 }
112
113 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
114 const ByteRange &RHS) {
115 return LHSOffset < RHS.BeginOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000116 }
117
118 bool operator==(const ByteRange &RHS) const {
119 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
120 }
121 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
122 };
123
124 /// \brief A partition of an alloca.
125 ///
126 /// This structure represents a contiguous partition of the alloca. These are
127 /// formed by examining the uses of the alloca. During formation, they may
128 /// overlap but once an AllocaPartitioning is built, the Partitions within it
129 /// are all disjoint.
130 struct Partition : public ByteRange {
131 /// \brief Whether this partition is splittable into smaller partitions.
132 ///
133 /// We flag partitions as splittable when they are formed entirely due to
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000134 /// accesses by trivially splittable operations such as memset and memcpy.
Chandler Carruth713aa942012-09-14 09:22:59 +0000135 bool IsSplittable;
136
Chandler Carruthfca3f402012-10-05 01:29:09 +0000137 /// \brief Test whether a partition has been marked as dead.
138 bool isDead() const {
139 if (BeginOffset == UINT64_MAX) {
140 assert(EndOffset == UINT64_MAX);
141 return true;
142 }
143 return false;
144 }
145
146 /// \brief Kill a partition.
147 /// This is accomplished by setting both its beginning and end offset to
148 /// the maximum possible value.
149 void kill() {
150 assert(!isDead() && "He's Dead, Jim!");
151 BeginOffset = EndOffset = UINT64_MAX;
152 }
153
Chandler Carruth713aa942012-09-14 09:22:59 +0000154 Partition() : ByteRange(), IsSplittable() {}
155 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
156 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
157 };
158
159 /// \brief A particular use of a partition of the alloca.
160 ///
161 /// This structure is used to associate uses of a partition with it. They
162 /// mark the range of bytes which are referenced by a particular instruction,
163 /// and includes a handle to the user itself and the pointer value in use.
164 /// The bounds of these uses are determined by intersecting the bounds of the
165 /// memory use itself with a particular partition. As a consequence there is
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000166 /// intentionally overlap between various uses of the same partition.
Chandler Carruth713aa942012-09-14 09:22:59 +0000167 struct PartitionUse : public ByteRange {
Chandler Carruth77c12702012-10-01 01:49:22 +0000168 /// \brief The use in question. Provides access to both user and used value.
Chandler Carruthfdb15852012-10-02 18:57:13 +0000169 ///
170 /// Note that this may be null if the partition use is *dead*, that is, it
171 /// should be ignored.
172 Use *U;
Chandler Carruth713aa942012-09-14 09:22:59 +0000173
Chandler Carruth77c12702012-10-01 01:49:22 +0000174 PartitionUse() : ByteRange(), U() {}
175 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset, Use *U)
176 : ByteRange(BeginOffset, EndOffset), U(U) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000177 };
178
179 /// \brief Construct a partitioning of a particular alloca.
180 ///
181 /// Construction does most of the work for partitioning the alloca. This
182 /// performs the necessary walks of users and builds a partitioning from it.
Micah Villmow3574eca2012-10-08 16:38:25 +0000183 AllocaPartitioning(const DataLayout &TD, AllocaInst &AI);
Chandler Carruth713aa942012-09-14 09:22:59 +0000184
185 /// \brief Test whether a pointer to the allocation escapes our analysis.
186 ///
187 /// If this is true, the partitioning is never fully built and should be
188 /// ignored.
189 bool isEscaped() const { return PointerEscapingInstr; }
190
191 /// \brief Support for iterating over the partitions.
192 /// @{
193 typedef SmallVectorImpl<Partition>::iterator iterator;
194 iterator begin() { return Partitions.begin(); }
195 iterator end() { return Partitions.end(); }
196
197 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
198 const_iterator begin() const { return Partitions.begin(); }
199 const_iterator end() const { return Partitions.end(); }
200 /// @}
201
202 /// \brief Support for iterating over and manipulating a particular
203 /// partition's uses.
204 ///
205 /// The iteration support provided for uses is more limited, but also
206 /// includes some manipulation routines to support rewriting the uses of
207 /// partitions during SROA.
208 /// @{
209 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
210 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
211 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
212 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
213 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
Chandler Carruth713aa942012-09-14 09:22:59 +0000214
215 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
216 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
217 const_use_iterator use_begin(const_iterator I) const {
218 return Uses[I - begin()].begin();
219 }
220 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
221 const_use_iterator use_end(const_iterator I) const {
222 return Uses[I - begin()].end();
223 }
Chandler Carrutha346f462012-10-02 17:49:47 +0000224
225 unsigned use_size(unsigned Idx) const { return Uses[Idx].size(); }
226 unsigned use_size(const_iterator I) const { return Uses[I - begin()].size(); }
227 const PartitionUse &getUse(unsigned PIdx, unsigned UIdx) const {
228 return Uses[PIdx][UIdx];
229 }
230 const PartitionUse &getUse(const_iterator I, unsigned UIdx) const {
231 return Uses[I - begin()][UIdx];
232 }
233
234 void use_push_back(unsigned Idx, const PartitionUse &PU) {
235 Uses[Idx].push_back(PU);
236 }
237 void use_push_back(const_iterator I, const PartitionUse &PU) {
238 Uses[I - begin()].push_back(PU);
239 }
Chandler Carruth713aa942012-09-14 09:22:59 +0000240 /// @}
241
242 /// \brief Allow iterating the dead users for this alloca.
243 ///
244 /// These are instructions which will never actually use the alloca as they
245 /// are outside the allocated range. They are safe to replace with undef and
246 /// delete.
247 /// @{
248 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
249 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
250 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
251 /// @}
252
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000253 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth713aa942012-09-14 09:22:59 +0000254 ///
255 /// These are operands which have cannot actually be used to refer to the
256 /// alloca as they are outside its range and the user doesn't correct for
257 /// that. These mostly consist of PHI node inputs and the like which we just
258 /// need to replace with undef.
259 /// @{
260 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
261 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
262 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
263 /// @}
264
265 /// \brief MemTransferInst auxiliary data.
266 /// This struct provides some auxiliary data about memory transfer
267 /// intrinsics such as memcpy and memmove. These intrinsics can use two
268 /// different ranges within the same alloca, and provide other challenges to
269 /// correctly represent. We stash extra data to help us untangle this
270 /// after the partitioning is complete.
271 struct MemTransferOffsets {
Chandler Carruthfca3f402012-10-05 01:29:09 +0000272 /// The destination begin and end offsets when the destination is within
273 /// this alloca. If the end offset is zero the destination is not within
274 /// this alloca.
Chandler Carruth713aa942012-09-14 09:22:59 +0000275 uint64_t DestBegin, DestEnd;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000276
277 /// The source begin and end offsets when the source is within this alloca.
278 /// If the end offset is zero, the source is not within this alloca.
Chandler Carruth713aa942012-09-14 09:22:59 +0000279 uint64_t SourceBegin, SourceEnd;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000280
281 /// Flag for whether an alloca is splittable.
Chandler Carruth713aa942012-09-14 09:22:59 +0000282 bool IsSplittable;
283 };
284 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
285 return MemTransferInstData.lookup(&II);
286 }
287
288 /// \brief Map from a PHI or select operand back to a partition.
289 ///
290 /// When manipulating PHI nodes or selects, they can use more than one
291 /// partition of an alloca. We store a special mapping to allow finding the
292 /// partition referenced by each of these operands, if any.
Chandler Carruth77c12702012-10-01 01:49:22 +0000293 iterator findPartitionForPHIOrSelectOperand(Use *U) {
294 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
295 = PHIOrSelectOpMap.find(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000296 if (MapIt == PHIOrSelectOpMap.end())
297 return end();
298
299 return begin() + MapIt->second.first;
300 }
301
302 /// \brief Map from a PHI or select operand back to the specific use of
303 /// a partition.
304 ///
305 /// Similar to mapping these operands back to the partitions, this maps
306 /// directly to the use structure of that partition.
Chandler Carruth77c12702012-10-01 01:49:22 +0000307 use_iterator findPartitionUseForPHIOrSelectOperand(Use *U) {
308 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
309 = PHIOrSelectOpMap.find(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000310 assert(MapIt != PHIOrSelectOpMap.end());
311 return Uses[MapIt->second.first].begin() + MapIt->second.second;
312 }
313
314 /// \brief Compute a common type among the uses of a particular partition.
315 ///
316 /// This routines walks all of the uses of a particular partition and tries
317 /// to find a common type between them. Untyped operations such as memset and
318 /// memcpy are ignored.
319 Type *getCommonType(iterator I) const;
320
Chandler Carruthba13d2e2012-09-14 10:18:51 +0000321#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth713aa942012-09-14 09:22:59 +0000322 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
323 void printUsers(raw_ostream &OS, const_iterator I,
324 StringRef Indent = " ") const;
325 void print(raw_ostream &OS) const;
NAKAMURA Takumiad9f5b82012-09-14 10:06:10 +0000326 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
327 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
Chandler Carruthba13d2e2012-09-14 10:18:51 +0000328#endif
Chandler Carruth713aa942012-09-14 09:22:59 +0000329
330private:
331 template <typename DerivedT, typename RetT = void> class BuilderBase;
332 class PartitionBuilder;
333 friend class AllocaPartitioning::PartitionBuilder;
334 class UseBuilder;
335 friend class AllocaPartitioning::UseBuilder;
336
Chandler Carruth3a902d02012-11-20 10:23:07 +0000337#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth713aa942012-09-14 09:22:59 +0000338 /// \brief Handle to alloca instruction to simplify method interfaces.
339 AllocaInst &AI;
Benjamin Kramerd0807692012-09-14 13:08:09 +0000340#endif
Chandler Carruth713aa942012-09-14 09:22:59 +0000341
342 /// \brief The instruction responsible for this alloca having no partitioning.
343 ///
344 /// When an instruction (potentially) escapes the pointer to the alloca, we
345 /// store a pointer to that here and abort trying to partition the alloca.
346 /// This will be null if the alloca is partitioned successfully.
347 Instruction *PointerEscapingInstr;
348
349 /// \brief The partitions of the alloca.
350 ///
351 /// We store a vector of the partitions over the alloca here. This vector is
352 /// sorted by increasing begin offset, and then by decreasing end offset. See
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000353 /// the Partition inner class for more details. Initially (during
354 /// construction) there are overlaps, but we form a disjoint sequence of
355 /// partitions while finishing construction and a fully constructed object is
356 /// expected to always have this as a disjoint space.
Chandler Carruth713aa942012-09-14 09:22:59 +0000357 SmallVector<Partition, 8> Partitions;
358
359 /// \brief The uses of the partitions.
360 ///
361 /// This is essentially a mapping from each partition to a list of uses of
362 /// that partition. The mapping is done with a Uses vector that has the exact
363 /// same number of entries as the partition vector. Each entry is itself
364 /// a vector of the uses.
365 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
366
367 /// \brief Instructions which will become dead if we rewrite the alloca.
368 ///
369 /// Note that these are not separated by partition. This is because we expect
370 /// a partitioned alloca to be completely rewritten or not rewritten at all.
371 /// If rewritten, all these instructions can simply be removed and replaced
372 /// with undef as they come from outside of the allocated space.
373 SmallVector<Instruction *, 8> DeadUsers;
374
375 /// \brief Operands which will become dead if we rewrite the alloca.
376 ///
377 /// These are operands that in their particular use can be replaced with
378 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
379 /// to PHI nodes and the like. They aren't entirely dead (there might be
380 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
381 /// want to swap this particular input for undef to simplify the use lists of
382 /// the alloca.
383 SmallVector<Use *, 8> DeadOperands;
384
385 /// \brief The underlying storage for auxiliary memcpy and memset info.
386 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
387
388 /// \brief A side datastructure used when building up the partitions and uses.
389 ///
390 /// This mapping is only really used during the initial building of the
391 /// partitioning so that we can retain information about PHI and select nodes
392 /// processed.
393 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
394
395 /// \brief Auxiliary information for particular PHI or select operands.
Chandler Carruth77c12702012-10-01 01:49:22 +0000396 SmallDenseMap<Use *, std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
Chandler Carruth713aa942012-09-14 09:22:59 +0000397
398 /// \brief A utility routine called from the constructor.
399 ///
400 /// This does what it says on the tin. It is the key of the alloca partition
401 /// splitting and merging. After it is called we have the desired disjoint
402 /// collection of partitions.
403 void splitAndMergePartitions();
404};
405}
406
407template <typename DerivedT, typename RetT>
408class AllocaPartitioning::BuilderBase
409 : public InstVisitor<DerivedT, RetT> {
410public:
Micah Villmow3574eca2012-10-08 16:38:25 +0000411 BuilderBase(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth713aa942012-09-14 09:22:59 +0000412 : TD(TD),
413 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
414 P(P) {
415 enqueueUsers(AI, 0);
416 }
417
418protected:
Micah Villmow3574eca2012-10-08 16:38:25 +0000419 const DataLayout &TD;
Chandler Carruth713aa942012-09-14 09:22:59 +0000420 const uint64_t AllocSize;
421 AllocaPartitioning &P;
422
Chandler Carruth77c12702012-10-01 01:49:22 +0000423 SmallPtrSet<Use *, 8> VisitedUses;
424
Chandler Carruth713aa942012-09-14 09:22:59 +0000425 struct OffsetUse {
426 Use *U;
Chandler Carruth02e92a02012-09-23 11:43:14 +0000427 int64_t Offset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000428 };
429 SmallVector<OffsetUse, 8> Queue;
430
431 // The active offset and use while visiting.
432 Use *U;
Chandler Carruth02e92a02012-09-23 11:43:14 +0000433 int64_t Offset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000434
Chandler Carruth02e92a02012-09-23 11:43:14 +0000435 void enqueueUsers(Instruction &I, int64_t UserOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000436 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
437 UI != UE; ++UI) {
Chandler Carruth77c12702012-10-01 01:49:22 +0000438 if (VisitedUses.insert(&UI.getUse())) {
439 OffsetUse OU = { &UI.getUse(), UserOffset };
440 Queue.push_back(OU);
441 }
Chandler Carruth713aa942012-09-14 09:22:59 +0000442 }
443 }
444
Chandler Carruth02e92a02012-09-23 11:43:14 +0000445 bool computeConstantGEPOffset(GetElementPtrInst &GEPI, int64_t &GEPOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000446 GEPOffset = Offset;
447 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
448 GTI != GTE; ++GTI) {
449 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
450 if (!OpC)
451 return false;
452 if (OpC->isZero())
453 continue;
454
455 // Handle a struct index, which adds its field offset to the pointer.
456 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
457 unsigned ElementIdx = OpC->getZExtValue();
458 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth02e92a02012-09-23 11:43:14 +0000459 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
460 // Check that we can continue to model this GEP in a signed 64-bit offset.
461 if (ElementOffset > INT64_MAX ||
462 (GEPOffset >= 0 &&
463 ((uint64_t)GEPOffset + ElementOffset) > INT64_MAX)) {
464 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
465 << "what can be represented in an int64_t!\n"
466 << " alloca: " << P.AI << "\n");
467 return false;
468 }
469 if (GEPOffset < 0)
470 GEPOffset = ElementOffset + (uint64_t)-GEPOffset;
471 else
472 GEPOffset += ElementOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000473 continue;
474 }
475
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000476 APInt Index = OpC->getValue().sextOrTrunc(TD.getPointerSizeInBits());
Chandler Carruth02e92a02012-09-23 11:43:14 +0000477 Index *= APInt(Index.getBitWidth(),
478 TD.getTypeAllocSize(GTI.getIndexedType()));
479 Index += APInt(Index.getBitWidth(), (uint64_t)GEPOffset,
480 /*isSigned*/true);
481 // Check if the result can be stored in our int64_t offset.
482 if (!Index.isSignedIntN(sizeof(GEPOffset) * 8)) {
483 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
484 << "what can be represented in an int64_t!\n"
485 << " alloca: " << P.AI << "\n");
486 return false;
487 }
488
489 GEPOffset = Index.getSExtValue();
Chandler Carruth713aa942012-09-14 09:22:59 +0000490 }
491 return true;
492 }
493
494 Value *foldSelectInst(SelectInst &SI) {
495 // If the condition being selected on is a constant or the same value is
496 // being selected between, fold the select. Yes this does (rarely) happen
497 // early on.
498 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
499 return SI.getOperand(1+CI->isZero());
500 if (SI.getOperand(1) == SI.getOperand(2)) {
501 assert(*U == SI.getOperand(1));
502 return SI.getOperand(1);
503 }
504 return 0;
505 }
506};
507
508/// \brief Builder for the alloca partitioning.
509///
510/// This class builds an alloca partitioning by recursively visiting the uses
511/// of an alloca and splitting the partitions for each load and store at each
512/// offset.
513class AllocaPartitioning::PartitionBuilder
514 : public BuilderBase<PartitionBuilder, bool> {
515 friend class InstVisitor<PartitionBuilder, bool>;
516
517 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
518
519public:
Micah Villmow3574eca2012-10-08 16:38:25 +0000520 PartitionBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000521 : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000522
523 /// \brief Run the builder over the allocation.
524 bool operator()() {
525 // Note that we have to re-evaluate size on each trip through the loop as
526 // the queue grows at the tail.
527 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
528 U = Queue[Idx].U;
529 Offset = Queue[Idx].Offset;
530 if (!visit(cast<Instruction>(U->getUser())))
531 return false;
532 }
533 return true;
534 }
535
536private:
537 bool markAsEscaping(Instruction &I) {
538 P.PointerEscapingInstr = &I;
539 return false;
540 }
541
Chandler Carruth02e92a02012-09-23 11:43:14 +0000542 void insertUse(Instruction &I, int64_t Offset, uint64_t Size,
Chandler Carruth63392ea2012-09-16 19:39:50 +0000543 bool IsSplittable = false) {
Chandler Carruthc3034632012-09-25 10:03:40 +0000544 // Completely skip uses which have a zero size or don't overlap the
545 // allocation.
546 if (Size == 0 ||
547 (Offset >= 0 && (uint64_t)Offset >= AllocSize) ||
Chandler Carruth02e92a02012-09-23 11:43:14 +0000548 (Offset < 0 && (uint64_t)-Offset >= Size)) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000549 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
550 << " which starts past the end of the " << AllocSize
551 << " byte alloca:\n"
552 << " alloca: " << P.AI << "\n"
553 << " use: " << I << "\n");
554 return;
555 }
556
Chandler Carruth02e92a02012-09-23 11:43:14 +0000557 // Clamp the start to the beginning of the allocation.
558 if (Offset < 0) {
559 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
560 << " to start at the beginning of the alloca:\n"
561 << " alloca: " << P.AI << "\n"
562 << " use: " << I << "\n");
563 Size -= (uint64_t)-Offset;
564 Offset = 0;
565 }
566
567 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
568
569 // Clamp the end offset to the end of the allocation. Note that this is
570 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carruth17679292012-11-20 10:02:19 +0000571 // NOTE! This may appear superficially to be something we could ignore
572 // entirely, but that is not so! There may be PHI-node uses where some
573 // instructions are dead but not others. We can't completely ignore the
574 // PHI node, and so have to record at least the information here.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000575 assert(AllocSize >= BeginOffset); // Established above.
576 if (Size > AllocSize - BeginOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000577 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
578 << " to remain within the " << AllocSize << " byte alloca:\n"
579 << " alloca: " << P.AI << "\n"
580 << " use: " << I << "\n");
581 EndOffset = AllocSize;
582 }
583
Chandler Carruth713aa942012-09-14 09:22:59 +0000584 Partition New(BeginOffset, EndOffset, IsSplittable);
585 P.Partitions.push_back(New);
586 }
587
Chandler Carrutha2b88162012-10-25 04:37:07 +0000588 bool handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset,
589 bool IsVolatile) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000590 uint64_t Size = TD.getTypeStoreSize(Ty);
591
592 // If this memory access can be shown to *statically* extend outside the
593 // bounds of of the allocation, it's behavior is undefined, so simply
594 // ignore it. Note that this is more strict than the generic clamping
595 // behavior of insertUse. We also try to handle cases which might run the
596 // risk of overflow.
597 // FIXME: We should instead consider the pointer to have escaped if this
598 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000599 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
600 Size > (AllocSize - (uint64_t)Offset)) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000601 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
602 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
603 << " which extends past the end of the " << AllocSize
604 << " byte alloca:\n"
605 << " alloca: " << P.AI << "\n"
606 << " use: " << I << "\n");
607 return true;
608 }
609
Chandler Carrutha2b88162012-10-25 04:37:07 +0000610 // We allow splitting of loads and stores where the type is an integer type
611 // and which cover the entire alloca. Such integer loads and stores
612 // often require decomposition into fine grained loads and stores.
613 bool IsSplittable = false;
614 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
615 IsSplittable = !IsVolatile && ITy->getBitWidth() == AllocSize*8;
616
617 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth713aa942012-09-14 09:22:59 +0000618 return true;
619 }
620
621 bool visitBitCastInst(BitCastInst &BC) {
622 enqueueUsers(BC, Offset);
623 return true;
624 }
625
626 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
Chandler Carruth02e92a02012-09-23 11:43:14 +0000627 int64_t GEPOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000628 if (!computeConstantGEPOffset(GEPI, GEPOffset))
629 return markAsEscaping(GEPI);
630
631 enqueueUsers(GEPI, GEPOffset);
632 return true;
633 }
634
635 bool visitLoadInst(LoadInst &LI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000636 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
637 "All simple FCA loads should have been pre-split");
Chandler Carrutha2b88162012-10-25 04:37:07 +0000638 return handleLoadOrStore(LI.getType(), LI, Offset, LI.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +0000639 }
640
641 bool visitStoreInst(StoreInst &SI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000642 Value *ValOp = SI.getValueOperand();
643 if (ValOp == *U)
Chandler Carruth713aa942012-09-14 09:22:59 +0000644 return markAsEscaping(SI);
645
Chandler Carruthc370acd2012-09-18 12:57:43 +0000646 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
647 "All simple FCA stores should have been pre-split");
Chandler Carrutha2b88162012-10-25 04:37:07 +0000648 return handleLoadOrStore(ValOp->getType(), SI, Offset, SI.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +0000649 }
650
651
652 bool visitMemSetInst(MemSetInst &II) {
Chandler Carruthb3dd9a12012-09-14 10:26:34 +0000653 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth713aa942012-09-14 09:22:59 +0000654 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000655 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
656 insertUse(II, Offset, Size, Length);
Chandler Carruth713aa942012-09-14 09:22:59 +0000657 return true;
658 }
659
660 bool visitMemTransferInst(MemTransferInst &II) {
661 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
662 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
663 if (!Size)
664 // Zero-length mem transfer intrinsics can be ignored entirely.
665 return true;
666
667 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
668
669 // Only intrinsics with a constant length can be split.
670 Offsets.IsSplittable = Length;
671
Chandler Carruthfca3f402012-10-05 01:29:09 +0000672 if (*U == II.getRawDest()) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000673 Offsets.DestBegin = Offset;
674 Offsets.DestEnd = Offset + Size;
675 }
Chandler Carruthfca3f402012-10-05 01:29:09 +0000676 if (*U == II.getRawSource()) {
677 Offsets.SourceBegin = Offset;
678 Offsets.SourceEnd = Offset + Size;
679 }
Chandler Carruth713aa942012-09-14 09:22:59 +0000680
Chandler Carruthfca3f402012-10-05 01:29:09 +0000681 // If we have set up end offsets for both the source and the destination,
682 // we have found both sides of this transfer pointing at the same alloca.
683 bool SeenBothEnds = Offsets.SourceEnd && Offsets.DestEnd;
684 if (SeenBothEnds && II.getRawDest() != II.getRawSource()) {
685 unsigned PrevIdx = MemTransferPartitionMap[&II];
Chandler Carruth713aa942012-09-14 09:22:59 +0000686
Chandler Carruthfca3f402012-10-05 01:29:09 +0000687 // Check if the begin offsets match and this is a non-volatile transfer.
688 // In that case, we can completely elide the transfer.
689 if (!II.isVolatile() && Offsets.SourceBegin == Offsets.DestBegin) {
690 P.Partitions[PrevIdx].kill();
691 return true;
692 }
693
694 // Otherwise we have an offset transfer within the same alloca. We can't
695 // split those.
696 P.Partitions[PrevIdx].IsSplittable = Offsets.IsSplittable = false;
697 } else if (SeenBothEnds) {
698 // Handle the case where this exact use provides both ends of the
699 // operation.
700 assert(II.getRawDest() == II.getRawSource());
701
702 // For non-volatile transfers this is a no-op.
703 if (!II.isVolatile())
704 return true;
705
706 // Otherwise just suppress splitting.
Chandler Carruth713aa942012-09-14 09:22:59 +0000707 Offsets.IsSplittable = false;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000708 }
709
710
711 // Insert the use now that we've fixed up the splittable nature.
712 insertUse(II, Offset, Size, Offsets.IsSplittable);
713
714 // Setup the mapping from intrinsic to partition of we've not seen both
715 // ends of this transfer.
716 if (!SeenBothEnds) {
717 unsigned NewIdx = P.Partitions.size() - 1;
718 bool Inserted
719 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx)).second;
720 assert(Inserted &&
721 "Already have intrinsic in map but haven't seen both ends");
NAKAMURA Takumi0559d312012-10-05 13:56:23 +0000722 (void)Inserted;
Chandler Carruth713aa942012-09-14 09:22:59 +0000723 }
724
725 return true;
726 }
727
728 // Disable SRoA for any intrinsics except for lifetime invariants.
Chandler Carruth50754f02012-09-14 10:26:36 +0000729 // FIXME: What about debug instrinsics? This matches old behavior, but
730 // doesn't make sense.
Chandler Carruth713aa942012-09-14 09:22:59 +0000731 bool visitIntrinsicInst(IntrinsicInst &II) {
732 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
733 II.getIntrinsicID() == Intrinsic::lifetime_end) {
734 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
735 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000736 insertUse(II, Offset, Size, true);
Chandler Carruth713aa942012-09-14 09:22:59 +0000737 return true;
738 }
739
740 return markAsEscaping(II);
741 }
742
743 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
744 // We consider any PHI or select that results in a direct load or store of
745 // the same offset to be a viable use for partitioning purposes. These uses
746 // are considered unsplittable and the size is the maximum loaded or stored
747 // size.
748 SmallPtrSet<Instruction *, 4> Visited;
749 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
750 Visited.insert(Root);
751 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruthc3034632012-09-25 10:03:40 +0000752 // If there are no loads or stores, the access is dead. We mark that as
753 // a size zero access.
754 Size = 0;
Chandler Carruth713aa942012-09-14 09:22:59 +0000755 do {
756 Instruction *I, *UsedI;
757 llvm::tie(UsedI, I) = Uses.pop_back_val();
758
759 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
760 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
761 continue;
762 }
763 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
764 Value *Op = SI->getOperand(0);
765 if (Op == UsedI)
766 return SI;
767 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
768 continue;
769 }
770
771 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
772 if (!GEP->hasAllZeroIndices())
773 return GEP;
774 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
775 !isa<SelectInst>(I)) {
776 return I;
777 }
778
779 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
780 ++UI)
781 if (Visited.insert(cast<Instruction>(*UI)))
782 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
783 } while (!Uses.empty());
784
785 return 0;
786 }
787
788 bool visitPHINode(PHINode &PN) {
789 // See if we already have computed info on this node.
790 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
791 if (PHIInfo.first) {
792 PHIInfo.second = true;
Chandler Carruth63392ea2012-09-16 19:39:50 +0000793 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000794 return true;
795 }
796
797 // Check for an unsafe use of the PHI node.
798 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
799 return markAsEscaping(*EscapingI);
800
Chandler Carruth63392ea2012-09-16 19:39:50 +0000801 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000802 return true;
803 }
804
805 bool visitSelectInst(SelectInst &SI) {
806 if (Value *Result = foldSelectInst(SI)) {
807 if (Result == *U)
808 // If the result of the constant fold will be the pointer, recurse
809 // through the select as if we had RAUW'ed it.
810 enqueueUsers(SI, Offset);
811
812 return true;
813 }
814
815 // See if we already have computed info on this node.
816 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
817 if (SelectInfo.first) {
818 SelectInfo.second = true;
Chandler Carruth63392ea2012-09-16 19:39:50 +0000819 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000820 return true;
821 }
822
823 // Check for an unsafe use of the PHI node.
824 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
825 return markAsEscaping(*EscapingI);
826
Chandler Carruth63392ea2012-09-16 19:39:50 +0000827 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000828 return true;
829 }
830
831 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
832 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
833};
834
835
836/// \brief Use adder for the alloca partitioning.
837///
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000838/// This class adds the uses of an alloca to all of the partitions which they
839/// use. For splittable partitions, this can end up doing essentially a linear
Chandler Carruth713aa942012-09-14 09:22:59 +0000840/// walk of the partitions, but the number of steps remains bounded by the
841/// total result instruction size:
842/// - The number of partitions is a result of the number unsplittable
843/// instructions using the alloca.
844/// - The number of users of each partition is at worst the total number of
845/// splittable instructions using the alloca.
846/// Thus we will produce N * M instructions in the end, where N are the number
847/// of unsplittable uses and M are the number of splittable. This visitor does
848/// the exact same number of updates to the partitioning.
849///
850/// In the more common case, this visitor will leverage the fact that the
851/// partition space is pre-sorted, and do a logarithmic search for the
852/// partition needed, making the total visit a classical ((N + M) * log(N))
853/// complexity operation.
854class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
855 friend class InstVisitor<UseBuilder>;
856
857 /// \brief Set to de-duplicate dead instructions found in the use walk.
858 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
859
860public:
Micah Villmow3574eca2012-10-08 16:38:25 +0000861 UseBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000862 : BuilderBase<UseBuilder>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000863
864 /// \brief Run the builder over the allocation.
865 void operator()() {
866 // Note that we have to re-evaluate size on each trip through the loop as
867 // the queue grows at the tail.
868 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
869 U = Queue[Idx].U;
870 Offset = Queue[Idx].Offset;
871 this->visit(cast<Instruction>(U->getUser()));
872 }
873 }
874
875private:
876 void markAsDead(Instruction &I) {
877 if (VisitedDeadInsts.insert(&I))
878 P.DeadUsers.push_back(&I);
879 }
880
Chandler Carruth02e92a02012-09-23 11:43:14 +0000881 void insertUse(Instruction &User, int64_t Offset, uint64_t Size) {
Chandler Carruthc3034632012-09-25 10:03:40 +0000882 // If the use has a zero size or extends outside of the allocation, record
883 // it as a dead use for elimination later.
884 if (Size == 0 || (uint64_t)Offset >= AllocSize ||
Chandler Carruth02e92a02012-09-23 11:43:14 +0000885 (Offset < 0 && (uint64_t)-Offset >= Size))
Chandler Carruth713aa942012-09-14 09:22:59 +0000886 return markAsDead(User);
887
Chandler Carruth02e92a02012-09-23 11:43:14 +0000888 // Clamp the start to the beginning of the allocation.
889 if (Offset < 0) {
890 Size -= (uint64_t)-Offset;
891 Offset = 0;
892 }
893
894 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
895
896 // Clamp the end offset to the end of the allocation. Note that this is
897 // formulated to handle even the case where "BeginOffset + Size" overflows.
898 assert(AllocSize >= BeginOffset); // Established above.
899 if (Size > AllocSize - BeginOffset)
Chandler Carruth713aa942012-09-14 09:22:59 +0000900 EndOffset = AllocSize;
901
902 // NB: This only works if we have zero overlapping partitions.
903 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
904 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
905 B = llvm::prior(B);
906 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
907 ++I) {
Chandler Carruth77c12702012-10-01 01:49:22 +0000908 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
909 std::min(I->EndOffset, EndOffset), U);
910 P.use_push_back(I, NewPU);
Chandler Carruth713aa942012-09-14 09:22:59 +0000911 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
Chandler Carruth77c12702012-10-01 01:49:22 +0000912 P.PHIOrSelectOpMap[U]
Chandler Carruth713aa942012-09-14 09:22:59 +0000913 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
914 }
915 }
916
Chandler Carruth02e92a02012-09-23 11:43:14 +0000917 void handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000918 uint64_t Size = TD.getTypeStoreSize(Ty);
919
920 // If this memory access can be shown to *statically* extend outside the
921 // bounds of of the allocation, it's behavior is undefined, so simply
922 // ignore it. Note that this is more strict than the generic clamping
923 // behavior of insertUse.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000924 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
925 Size > (AllocSize - (uint64_t)Offset))
Chandler Carruth713aa942012-09-14 09:22:59 +0000926 return markAsDead(I);
927
Chandler Carruth63392ea2012-09-16 19:39:50 +0000928 insertUse(I, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000929 }
930
931 void visitBitCastInst(BitCastInst &BC) {
932 if (BC.use_empty())
933 return markAsDead(BC);
934
935 enqueueUsers(BC, Offset);
936 }
937
938 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
939 if (GEPI.use_empty())
940 return markAsDead(GEPI);
941
Chandler Carruth02e92a02012-09-23 11:43:14 +0000942 int64_t GEPOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000943 if (!computeConstantGEPOffset(GEPI, GEPOffset))
944 llvm_unreachable("Unable to compute constant offset for use");
945
946 enqueueUsers(GEPI, GEPOffset);
947 }
948
949 void visitLoadInst(LoadInst &LI) {
Chandler Carruth63392ea2012-09-16 19:39:50 +0000950 handleLoadOrStore(LI.getType(), LI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000951 }
952
953 void visitStoreInst(StoreInst &SI) {
Chandler Carruth63392ea2012-09-16 19:39:50 +0000954 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000955 }
956
957 void visitMemSetInst(MemSetInst &II) {
958 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000959 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
960 insertUse(II, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000961 }
962
963 void visitMemTransferInst(MemTransferInst &II) {
964 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000965 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000966 if (!Size)
967 return markAsDead(II);
968
969 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
970 if (!II.isVolatile() && Offsets.DestEnd && Offsets.SourceEnd &&
971 Offsets.DestBegin == Offsets.SourceBegin)
972 return markAsDead(II); // Skip identity transfers without side-effects.
973
Chandler Carruth63392ea2012-09-16 19:39:50 +0000974 insertUse(II, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000975 }
976
977 void visitIntrinsicInst(IntrinsicInst &II) {
978 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
979 II.getIntrinsicID() == Intrinsic::lifetime_end);
980
981 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruth63392ea2012-09-16 19:39:50 +0000982 insertUse(II, Offset,
983 std::min(AllocSize - Offset, Length->getLimitedValue()));
Chandler Carruth713aa942012-09-14 09:22:59 +0000984 }
985
Chandler Carruth63392ea2012-09-16 19:39:50 +0000986 void insertPHIOrSelect(Instruction &User, uint64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000987 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
988
989 // For PHI and select operands outside the alloca, we can't nuke the entire
990 // phi or select -- the other side might still be relevant, so we special
991 // case them here and use a separate structure to track the operands
992 // themselves which should be replaced with undef.
993 if (Offset >= AllocSize) {
994 P.DeadOperands.push_back(U);
995 return;
996 }
997
Chandler Carruth63392ea2012-09-16 19:39:50 +0000998 insertUse(User, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000999 }
1000 void visitPHINode(PHINode &PN) {
1001 if (PN.use_empty())
1002 return markAsDead(PN);
1003
Chandler Carruth63392ea2012-09-16 19:39:50 +00001004 insertPHIOrSelect(PN, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +00001005 }
1006 void visitSelectInst(SelectInst &SI) {
1007 if (SI.use_empty())
1008 return markAsDead(SI);
1009
1010 if (Value *Result = foldSelectInst(SI)) {
1011 if (Result == *U)
1012 // If the result of the constant fold will be the pointer, recurse
1013 // through the select as if we had RAUW'ed it.
1014 enqueueUsers(SI, Offset);
Chandler Carruthd54a6b52012-09-21 23:36:40 +00001015 else
1016 // Otherwise the operand to the select is dead, and we can replace it
1017 // with undef.
1018 P.DeadOperands.push_back(U);
Chandler Carruth713aa942012-09-14 09:22:59 +00001019
1020 return;
1021 }
1022
Chandler Carruth63392ea2012-09-16 19:39:50 +00001023 insertPHIOrSelect(SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +00001024 }
1025
1026 /// \brief Unreachable, we've already visited the alloca once.
1027 void visitInstruction(Instruction &I) {
1028 llvm_unreachable("Unhandled instruction in use builder.");
1029 }
1030};
1031
1032void AllocaPartitioning::splitAndMergePartitions() {
1033 size_t NumDeadPartitions = 0;
1034
1035 // Track the range of splittable partitions that we pass when accumulating
1036 // overlapping unsplittable partitions.
1037 uint64_t SplitEndOffset = 0ull;
1038
1039 Partition New(0ull, 0ull, false);
1040
1041 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
1042 ++j;
1043
1044 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
1045 assert(New.BeginOffset == New.EndOffset);
1046 New = Partitions[i];
1047 } else {
1048 assert(New.IsSplittable);
1049 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
1050 }
1051 assert(New.BeginOffset != New.EndOffset);
1052
1053 // Scan the overlapping partitions.
1054 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
1055 // If the new partition we are forming is splittable, stop at the first
1056 // unsplittable partition.
1057 if (New.IsSplittable && !Partitions[j].IsSplittable)
1058 break;
1059
1060 // Grow the new partition to include any equally splittable range. 'j' is
1061 // always equally splittable when New is splittable, but when New is not
1062 // splittable, we may subsume some (or part of some) splitable partition
1063 // without growing the new one.
1064 if (New.IsSplittable == Partitions[j].IsSplittable) {
1065 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
1066 } else {
1067 assert(!New.IsSplittable);
1068 assert(Partitions[j].IsSplittable);
1069 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
1070 }
1071
Chandler Carruthfca3f402012-10-05 01:29:09 +00001072 Partitions[j].kill();
Chandler Carruth713aa942012-09-14 09:22:59 +00001073 ++NumDeadPartitions;
1074 ++j;
1075 }
1076
1077 // If the new partition is splittable, chop off the end as soon as the
1078 // unsplittable subsequent partition starts and ensure we eventually cover
1079 // the splittable area.
1080 if (j != e && New.IsSplittable) {
1081 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1082 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1083 }
1084
1085 // Add the new partition if it differs from the original one and is
1086 // non-empty. We can end up with an empty partition here if it was
1087 // splittable but there is an unsplittable one that starts at the same
1088 // offset.
1089 if (New != Partitions[i]) {
1090 if (New.BeginOffset != New.EndOffset)
1091 Partitions.push_back(New);
1092 // Mark the old one for removal.
Chandler Carruthfca3f402012-10-05 01:29:09 +00001093 Partitions[i].kill();
Chandler Carruth713aa942012-09-14 09:22:59 +00001094 ++NumDeadPartitions;
1095 }
1096
1097 New.BeginOffset = New.EndOffset;
1098 if (!New.IsSplittable) {
1099 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1100 if (j != e && !Partitions[j].IsSplittable)
1101 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1102 New.IsSplittable = true;
1103 // If there is a trailing splittable partition which won't be fused into
1104 // the next splittable partition go ahead and add it onto the partitions
1105 // list.
1106 if (New.BeginOffset < New.EndOffset &&
1107 (j == e || !Partitions[j].IsSplittable ||
1108 New.EndOffset < Partitions[j].BeginOffset)) {
1109 Partitions.push_back(New);
1110 New.BeginOffset = New.EndOffset = 0ull;
1111 }
1112 }
1113 }
1114
1115 // Re-sort the partitions now that they have been split and merged into
1116 // disjoint set of partitions. Also remove any of the dead partitions we've
1117 // replaced in the process.
1118 std::sort(Partitions.begin(), Partitions.end());
1119 if (NumDeadPartitions) {
Chandler Carruthfca3f402012-10-05 01:29:09 +00001120 assert(Partitions.back().isDead());
Chandler Carruth713aa942012-09-14 09:22:59 +00001121 assert((ptrdiff_t)NumDeadPartitions ==
1122 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1123 }
1124 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1125}
1126
Micah Villmow3574eca2012-10-08 16:38:25 +00001127AllocaPartitioning::AllocaPartitioning(const DataLayout &TD, AllocaInst &AI)
Benjamin Kramerd0807692012-09-14 13:08:09 +00001128 :
Chandler Carruth3a902d02012-11-20 10:23:07 +00001129#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Benjamin Kramerd0807692012-09-14 13:08:09 +00001130 AI(AI),
1131#endif
1132 PointerEscapingInstr(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001133 PartitionBuilder PB(TD, AI, *this);
1134 if (!PB())
1135 return;
1136
Chandler Carruthfca3f402012-10-05 01:29:09 +00001137 // Sort the uses. This arranges for the offsets to be in ascending order,
1138 // and the sizes to be in descending order.
1139 std::sort(Partitions.begin(), Partitions.end());
Chandler Carruth713aa942012-09-14 09:22:59 +00001140
Chandler Carruthfca3f402012-10-05 01:29:09 +00001141 // Remove any partitions from the back which are marked as dead.
1142 while (!Partitions.empty() && Partitions.back().isDead())
1143 Partitions.pop_back();
1144
1145 if (Partitions.size() > 1) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001146 // Intersect splittability for all partitions with equal offsets and sizes.
1147 // Then remove all but the first so that we have a sequence of non-equal but
1148 // potentially overlapping partitions.
1149 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1150 I = J) {
1151 ++J;
1152 while (J != E && *I == *J) {
1153 I->IsSplittable &= J->IsSplittable;
1154 ++J;
1155 }
1156 }
1157 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1158 Partitions.end());
1159
1160 // Split splittable and merge unsplittable partitions into a disjoint set
1161 // of partitions over the used space of the allocation.
1162 splitAndMergePartitions();
1163 }
1164
1165 // Now build up the user lists for each of these disjoint partitions by
1166 // re-walking the recursive users of the alloca.
1167 Uses.resize(Partitions.size());
1168 UseBuilder UB(TD, AI, *this);
1169 UB();
Chandler Carruth713aa942012-09-14 09:22:59 +00001170}
1171
1172Type *AllocaPartitioning::getCommonType(iterator I) const {
1173 Type *Ty = 0;
1174 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00001175 if (!UI->U)
1176 continue; // Skip dead uses.
Chandler Carruth77c12702012-10-01 01:49:22 +00001177 if (isa<IntrinsicInst>(*UI->U->getUser()))
Chandler Carruth713aa942012-09-14 09:22:59 +00001178 continue;
1179 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
Chandler Carruth7c8df7a2012-09-18 17:49:37 +00001180 continue;
Chandler Carruth713aa942012-09-14 09:22:59 +00001181
1182 Type *UserTy = 0;
Chandler Carruth77c12702012-10-01 01:49:22 +00001183 if (LoadInst *LI = dyn_cast<LoadInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001184 UserTy = LI->getType();
Chandler Carruth77c12702012-10-01 01:49:22 +00001185 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001186 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha2b88162012-10-25 04:37:07 +00001187 } else {
1188 return 0; // Bail if we have weird uses.
1189 }
1190
1191 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
1192 // If the type is larger than the partition, skip it. We only encounter
1193 // this for split integer operations where we want to use the type of the
1194 // entity causing the split.
1195 if (ITy->getBitWidth() > (I->EndOffset - I->BeginOffset)*8)
1196 continue;
1197
1198 // If we have found an integer type use covering the alloca, use that
1199 // regardless of the other types, as integers are often used for a "bucket
1200 // of bits" type.
1201 return ITy;
Chandler Carruth713aa942012-09-14 09:22:59 +00001202 }
1203
1204 if (Ty && Ty != UserTy)
1205 return 0;
1206
1207 Ty = UserTy;
1208 }
1209 return Ty;
1210}
1211
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001212#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1213
Chandler Carruth713aa942012-09-14 09:22:59 +00001214void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1215 StringRef Indent) const {
1216 OS << Indent << "partition #" << (I - begin())
1217 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1218 << (I->IsSplittable ? " (splittable)" : "")
1219 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1220 << "\n";
1221}
1222
1223void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1224 StringRef Indent) const {
1225 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1226 UI != UE; ++UI) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00001227 if (!UI->U)
1228 continue; // Skip dead uses.
Chandler Carruth713aa942012-09-14 09:22:59 +00001229 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
Chandler Carruth77c12702012-10-01 01:49:22 +00001230 << "used by: " << *UI->U->getUser() << "\n";
1231 if (MemTransferInst *II = dyn_cast<MemTransferInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001232 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1233 bool IsDest;
1234 if (!MTO.IsSplittable)
1235 IsDest = UI->BeginOffset == MTO.DestBegin;
1236 else
1237 IsDest = MTO.DestBegin != 0u;
1238 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1239 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1240 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1241 }
1242 }
1243}
1244
1245void AllocaPartitioning::print(raw_ostream &OS) const {
1246 if (PointerEscapingInstr) {
1247 OS << "No partitioning for alloca: " << AI << "\n"
1248 << " A pointer to this alloca escaped by:\n"
1249 << " " << *PointerEscapingInstr << "\n";
1250 return;
1251 }
1252
1253 OS << "Partitioning of alloca: " << AI << "\n";
1254 unsigned Num = 0;
1255 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1256 print(OS, I);
1257 printUsers(OS, I);
1258 }
1259}
1260
1261void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1262void AllocaPartitioning::dump() const { print(dbgs()); }
1263
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001264#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1265
Chandler Carruth713aa942012-09-14 09:22:59 +00001266
1267namespace {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001268/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1269///
1270/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1271/// the loads and stores of an alloca instruction, as well as updating its
1272/// debug information. This is used when a domtree is unavailable and thus
1273/// mem2reg in its full form can't be used to handle promotion of allocas to
1274/// scalar values.
1275class AllocaPromoter : public LoadAndStorePromoter {
1276 AllocaInst &AI;
1277 DIBuilder &DIB;
1278
1279 SmallVector<DbgDeclareInst *, 4> DDIs;
1280 SmallVector<DbgValueInst *, 4> DVIs;
1281
1282public:
1283 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1284 AllocaInst &AI, DIBuilder &DIB)
1285 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1286
1287 void run(const SmallVectorImpl<Instruction*> &Insts) {
1288 // Remember which alloca we're promoting (for isInstInList).
1289 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1290 for (Value::use_iterator UI = DebugNode->use_begin(),
1291 UE = DebugNode->use_end();
1292 UI != UE; ++UI)
1293 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1294 DDIs.push_back(DDI);
1295 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1296 DVIs.push_back(DVI);
1297 }
1298
1299 LoadAndStorePromoter::run(Insts);
1300 AI.eraseFromParent();
1301 while (!DDIs.empty())
1302 DDIs.pop_back_val()->eraseFromParent();
1303 while (!DVIs.empty())
1304 DVIs.pop_back_val()->eraseFromParent();
1305 }
1306
1307 virtual bool isInstInList(Instruction *I,
1308 const SmallVectorImpl<Instruction*> &Insts) const {
1309 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1310 return LI->getOperand(0) == &AI;
1311 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1312 }
1313
1314 virtual void updateDebugInfo(Instruction *Inst) const {
1315 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1316 E = DDIs.end(); I != E; ++I) {
1317 DbgDeclareInst *DDI = *I;
1318 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1319 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1320 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1321 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1322 }
1323 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1324 E = DVIs.end(); I != E; ++I) {
1325 DbgValueInst *DVI = *I;
1326 Value *Arg = NULL;
1327 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1328 // If an argument is zero extended then use argument directly. The ZExt
1329 // may be zapped by an optimization pass in future.
1330 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1331 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1332 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1333 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1334 if (!Arg)
1335 Arg = SI->getOperand(0);
1336 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1337 Arg = LI->getOperand(0);
1338 } else {
1339 continue;
1340 }
1341 Instruction *DbgVal =
1342 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1343 Inst);
1344 DbgVal->setDebugLoc(DVI->getDebugLoc());
1345 }
1346 }
1347};
1348} // end anon namespace
1349
1350
1351namespace {
Chandler Carruth713aa942012-09-14 09:22:59 +00001352/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1353///
1354/// This pass takes allocations which can be completely analyzed (that is, they
1355/// don't escape) and tries to turn them into scalar SSA values. There are
1356/// a few steps to this process.
1357///
1358/// 1) It takes allocations of aggregates and analyzes the ways in which they
1359/// are used to try to split them into smaller allocations, ideally of
1360/// a single scalar data type. It will split up memcpy and memset accesses
1361/// as necessary and try to isolate invidual scalar accesses.
1362/// 2) It will transform accesses into forms which are suitable for SSA value
1363/// promotion. This can be replacing a memset with a scalar store of an
1364/// integer value, or it can involve speculating operations on a PHI or
1365/// select to be a PHI or select of the results.
1366/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1367/// onto insert and extract operations on a vector value, and convert them to
1368/// this form. By doing so, it will enable promotion of vector aggregates to
1369/// SSA vector values.
1370class SROA : public FunctionPass {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001371 const bool RequiresDomTree;
1372
Chandler Carruth713aa942012-09-14 09:22:59 +00001373 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +00001374 const DataLayout *TD;
Chandler Carruth713aa942012-09-14 09:22:59 +00001375 DominatorTree *DT;
1376
1377 /// \brief Worklist of alloca instructions to simplify.
1378 ///
1379 /// Each alloca in the function is added to this. Each new alloca formed gets
1380 /// added to it as well to recursively simplify unless that alloca can be
1381 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1382 /// the one being actively rewritten, we add it back onto the list if not
1383 /// already present to ensure it is re-visited.
1384 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1385
1386 /// \brief A collection of instructions to delete.
1387 /// We try to batch deletions to simplify code and make things a bit more
1388 /// efficient.
Chandler Carruthf5837aa2012-11-20 01:12:50 +00001389 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth713aa942012-09-14 09:22:59 +00001390
Chandler Carruthb2d98c22012-10-04 12:33:50 +00001391 /// \brief Post-promotion worklist.
1392 ///
1393 /// Sometimes we discover an alloca which has a high probability of becoming
1394 /// viable for SROA after a round of promotion takes place. In those cases,
1395 /// the alloca is enqueued here for re-processing.
1396 ///
1397 /// Note that we have to be very careful to clear allocas out of this list in
1398 /// the event they are deleted.
1399 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
1400
Chandler Carruth713aa942012-09-14 09:22:59 +00001401 /// \brief A collection of alloca instructions we can directly promote.
1402 std::vector<AllocaInst *> PromotableAllocas;
1403
1404public:
Chandler Carruth1c8db502012-09-15 11:43:14 +00001405 SROA(bool RequiresDomTree = true)
1406 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1407 C(0), TD(0), DT(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001408 initializeSROAPass(*PassRegistry::getPassRegistry());
1409 }
1410 bool runOnFunction(Function &F);
1411 void getAnalysisUsage(AnalysisUsage &AU) const;
1412
1413 const char *getPassName() const { return "SROA"; }
1414 static char ID;
1415
1416private:
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00001417 friend class PHIOrSelectSpeculator;
Chandler Carruth713aa942012-09-14 09:22:59 +00001418 friend class AllocaPartitionRewriter;
1419 friend class AllocaPartitionVectorRewriter;
1420
1421 bool rewriteAllocaPartition(AllocaInst &AI,
1422 AllocaPartitioning &P,
1423 AllocaPartitioning::iterator PI);
1424 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1425 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth8615cd22012-09-14 10:26:38 +00001426 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth1c8db502012-09-15 11:43:14 +00001427 bool promoteAllocas(Function &F);
Chandler Carruth713aa942012-09-14 09:22:59 +00001428};
1429}
1430
1431char SROA::ID = 0;
1432
Chandler Carruth1c8db502012-09-15 11:43:14 +00001433FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1434 return new SROA(RequiresDomTree);
Chandler Carruth713aa942012-09-14 09:22:59 +00001435}
1436
1437INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1438 false, false)
1439INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1440INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1441 false, false)
1442
Chandler Carruth0e9da582012-10-05 01:29:06 +00001443namespace {
1444/// \brief Visitor to speculate PHIs and Selects where possible.
1445class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
1446 // Befriend the base class so it can delegate to private visit methods.
1447 friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
1448
Micah Villmow3574eca2012-10-08 16:38:25 +00001449 const DataLayout &TD;
Chandler Carruth0e9da582012-10-05 01:29:06 +00001450 AllocaPartitioning &P;
1451 SROA &Pass;
1452
1453public:
Micah Villmow3574eca2012-10-08 16:38:25 +00001454 PHIOrSelectSpeculator(const DataLayout &TD, AllocaPartitioning &P, SROA &Pass)
Chandler Carruth0e9da582012-10-05 01:29:06 +00001455 : TD(TD), P(P), Pass(Pass) {}
1456
1457 /// \brief Visit the users of an alloca partition and rewrite them.
1458 void visitUsers(AllocaPartitioning::const_iterator PI) {
1459 // Note that we need to use an index here as the underlying vector of uses
1460 // may be grown during speculation. However, we never need to re-visit the
1461 // new uses, and so we can use the initial size bound.
1462 for (unsigned Idx = 0, Size = P.use_size(PI); Idx != Size; ++Idx) {
1463 const AllocaPartitioning::PartitionUse &PU = P.getUse(PI, Idx);
1464 if (!PU.U)
1465 continue; // Skip dead use.
1466
1467 visit(cast<Instruction>(PU.U->getUser()));
1468 }
1469 }
1470
1471private:
1472 // By default, skip this instruction.
1473 void visitInstruction(Instruction &I) {}
1474
1475 /// PHI instructions that use an alloca and are subsequently loaded can be
1476 /// rewritten to load both input pointers in the pred blocks and then PHI the
1477 /// results, allowing the load of the alloca to be promoted.
1478 /// From this:
1479 /// %P2 = phi [i32* %Alloca, i32* %Other]
1480 /// %V = load i32* %P2
1481 /// to:
1482 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1483 /// ...
1484 /// %V2 = load i32* %Other
1485 /// ...
1486 /// %V = phi [i32 %V1, i32 %V2]
1487 ///
1488 /// We can do this to a select if its only uses are loads and if the operands
1489 /// to the select can be loaded unconditionally.
1490 ///
1491 /// FIXME: This should be hoisted into a generic utility, likely in
1492 /// Transforms/Util/Local.h
1493 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
1494 // For now, we can only do this promotion if the load is in the same block
1495 // as the PHI, and if there are no stores between the phi and load.
1496 // TODO: Allow recursive phi users.
1497 // TODO: Allow stores.
1498 BasicBlock *BB = PN.getParent();
1499 unsigned MaxAlign = 0;
1500 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
1501 UI != UE; ++UI) {
1502 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1503 if (LI == 0 || !LI->isSimple()) return false;
1504
1505 // For now we only allow loads in the same block as the PHI. This is
1506 // a common case that happens when instcombine merges two loads through
1507 // a PHI.
1508 if (LI->getParent() != BB) return false;
1509
1510 // Ensure that there are no instructions between the PHI and the load that
1511 // could store.
1512 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1513 if (BBI->mayWriteToMemory())
1514 return false;
1515
1516 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1517 Loads.push_back(LI);
1518 }
1519
1520 // We can only transform this if it is safe to push the loads into the
1521 // predecessor blocks. The only thing to watch out for is that we can't put
1522 // a possibly trapping load in the predecessor if it is a critical edge.
1523 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
1524 ++Idx) {
1525 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1526 Value *InVal = PN.getIncomingValue(Idx);
1527
1528 // If the value is produced by the terminator of the predecessor (an
1529 // invoke) or it has side-effects, there is no valid place to put a load
1530 // in the predecessor.
1531 if (TI == InVal || TI->mayHaveSideEffects())
1532 return false;
1533
1534 // If the predecessor has a single successor, then the edge isn't
1535 // critical.
1536 if (TI->getNumSuccessors() == 1)
1537 continue;
1538
1539 // If this pointer is always safe to load, or if we can prove that there
1540 // is already a load in the block, then we can move the load to the pred
1541 // block.
1542 if (InVal->isDereferenceablePointer() ||
1543 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
1544 continue;
1545
1546 return false;
1547 }
1548
1549 return true;
1550 }
1551
1552 void visitPHINode(PHINode &PN) {
1553 DEBUG(dbgs() << " original: " << PN << "\n");
1554
1555 SmallVector<LoadInst *, 4> Loads;
1556 if (!isSafePHIToSpeculate(PN, Loads))
1557 return;
1558
1559 assert(!Loads.empty());
1560
1561 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1562 IRBuilder<> PHIBuilder(&PN);
1563 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1564 PN.getName() + ".sroa.speculated");
1565
1566 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1567 // matter which one we get and if any differ, it doesn't matter.
1568 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
1569 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1570 unsigned Align = SomeLoad->getAlignment();
1571
1572 // Rewrite all loads of the PN to use the new PHI.
1573 do {
1574 LoadInst *LI = Loads.pop_back_val();
1575 LI->replaceAllUsesWith(NewPN);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00001576 Pass.DeadInsts.insert(LI);
Chandler Carruth0e9da582012-10-05 01:29:06 +00001577 } while (!Loads.empty());
1578
1579 // Inject loads into all of the pred blocks.
1580 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1581 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1582 TerminatorInst *TI = Pred->getTerminator();
1583 Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
1584 Value *InVal = PN.getIncomingValue(Idx);
1585 IRBuilder<> PredBuilder(TI);
1586
1587 LoadInst *Load
1588 = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
1589 Pred->getName()));
1590 ++NumLoadsSpeculated;
1591 Load->setAlignment(Align);
1592 if (TBAATag)
1593 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1594 NewPN->addIncoming(Load, Pred);
1595
1596 Instruction *Ptr = dyn_cast<Instruction>(InVal);
1597 if (!Ptr)
1598 // No uses to rewrite.
1599 continue;
1600
1601 // Try to lookup and rewrite any partition uses corresponding to this phi
1602 // input.
1603 AllocaPartitioning::iterator PI
1604 = P.findPartitionForPHIOrSelectOperand(InUse);
1605 if (PI == P.end())
1606 continue;
1607
1608 // Replace the Use in the PartitionUse for this operand with the Use
1609 // inside the load.
1610 AllocaPartitioning::use_iterator UI
1611 = P.findPartitionUseForPHIOrSelectOperand(InUse);
1612 assert(isa<PHINode>(*UI->U->getUser()));
1613 UI->U = &Load->getOperandUse(Load->getPointerOperandIndex());
1614 }
1615 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1616 }
1617
1618 /// Select instructions that use an alloca and are subsequently loaded can be
1619 /// rewritten to load both input pointers and then select between the result,
1620 /// allowing the load of the alloca to be promoted.
1621 /// From this:
1622 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1623 /// %V = load i32* %P2
1624 /// to:
1625 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1626 /// %V2 = load i32* %Other
1627 /// %V = select i1 %cond, i32 %V1, i32 %V2
1628 ///
1629 /// We can do this to a select if its only uses are loads and if the operand
1630 /// to the select can be loaded unconditionally.
1631 bool isSafeSelectToSpeculate(SelectInst &SI,
1632 SmallVectorImpl<LoadInst *> &Loads) {
1633 Value *TValue = SI.getTrueValue();
1634 Value *FValue = SI.getFalseValue();
1635 bool TDerefable = TValue->isDereferenceablePointer();
1636 bool FDerefable = FValue->isDereferenceablePointer();
1637
1638 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
1639 UI != UE; ++UI) {
1640 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1641 if (LI == 0 || !LI->isSimple()) return false;
1642
1643 // Both operands to the select need to be dereferencable, either
1644 // absolutely (e.g. allocas) or at this point because we can see other
1645 // accesses to it.
1646 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
1647 LI->getAlignment(), &TD))
1648 return false;
1649 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
1650 LI->getAlignment(), &TD))
1651 return false;
1652 Loads.push_back(LI);
1653 }
1654
1655 return true;
1656 }
1657
1658 void visitSelectInst(SelectInst &SI) {
1659 DEBUG(dbgs() << " original: " << SI << "\n");
1660 IRBuilder<> IRB(&SI);
1661
1662 // If the select isn't safe to speculate, just use simple logic to emit it.
1663 SmallVector<LoadInst *, 4> Loads;
1664 if (!isSafeSelectToSpeculate(SI, Loads))
1665 return;
1666
1667 Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) };
1668 AllocaPartitioning::iterator PIs[2];
1669 AllocaPartitioning::PartitionUse PUs[2];
1670 for (unsigned i = 0, e = 2; i != e; ++i) {
1671 PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]);
1672 if (PIs[i] != P.end()) {
1673 // If the pointer is within the partitioning, remove the select from
1674 // its uses. We'll add in the new loads below.
1675 AllocaPartitioning::use_iterator UI
1676 = P.findPartitionUseForPHIOrSelectOperand(Ops[i]);
1677 PUs[i] = *UI;
1678 // Clear out the use here so that the offsets into the use list remain
1679 // stable but this use is ignored when rewriting.
1680 UI->U = 0;
1681 }
1682 }
1683
1684 Value *TV = SI.getTrueValue();
1685 Value *FV = SI.getFalseValue();
1686 // Replace the loads of the select with a select of two loads.
1687 while (!Loads.empty()) {
1688 LoadInst *LI = Loads.pop_back_val();
1689
1690 IRB.SetInsertPoint(LI);
1691 LoadInst *TL =
1692 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1693 LoadInst *FL =
1694 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1695 NumLoadsSpeculated += 2;
1696
1697 // Transfer alignment and TBAA info if present.
1698 TL->setAlignment(LI->getAlignment());
1699 FL->setAlignment(LI->getAlignment());
1700 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1701 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1702 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1703 }
1704
1705 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1706 LI->getName() + ".sroa.speculated");
1707
1708 LoadInst *Loads[2] = { TL, FL };
1709 for (unsigned i = 0, e = 2; i != e; ++i) {
1710 if (PIs[i] != P.end()) {
1711 Use *LoadUse = &Loads[i]->getOperandUse(0);
1712 assert(PUs[i].U->get() == LoadUse->get());
1713 PUs[i].U = LoadUse;
1714 P.use_push_back(PIs[i], PUs[i]);
1715 }
1716 }
1717
1718 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1719 LI->replaceAllUsesWith(V);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00001720 Pass.DeadInsts.insert(LI);
Chandler Carruth0e9da582012-10-05 01:29:06 +00001721 }
1722 }
1723};
1724}
1725
Chandler Carruth713aa942012-09-14 09:22:59 +00001726/// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1727///
1728/// If the provided GEP is all-constant, the total byte offset formed by the
1729/// GEP is computed and Offset is set to it. If the GEP has any non-constant
1730/// operands, the function returns false and the value of Offset is unmodified.
Micah Villmow3574eca2012-10-08 16:38:25 +00001731static bool accumulateGEPOffsets(const DataLayout &TD, GEPOperator &GEP,
Chandler Carruth713aa942012-09-14 09:22:59 +00001732 APInt &Offset) {
1733 APInt GEPOffset(Offset.getBitWidth(), 0);
1734 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1735 GTI != GTE; ++GTI) {
1736 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1737 if (!OpC)
1738 return false;
1739 if (OpC->isZero()) continue;
1740
1741 // Handle a struct index, which adds its field offset to the pointer.
1742 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1743 unsigned ElementIdx = OpC->getZExtValue();
1744 const StructLayout *SL = TD.getStructLayout(STy);
1745 GEPOffset += APInt(Offset.getBitWidth(),
1746 SL->getElementOffset(ElementIdx));
1747 continue;
1748 }
1749
1750 APInt TypeSize(Offset.getBitWidth(),
1751 TD.getTypeAllocSize(GTI.getIndexedType()));
1752 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1753 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1754 "vector element size is not a multiple of 8, cannot GEP over it");
1755 TypeSize = VTy->getScalarSizeInBits() / 8;
1756 }
1757
1758 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1759 }
1760 Offset = GEPOffset;
1761 return true;
1762}
1763
1764/// \brief Build a GEP out of a base pointer and indices.
1765///
1766/// This will return the BasePtr if that is valid, or build a new GEP
1767/// instruction using the IRBuilder if GEP-ing is needed.
1768static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1769 SmallVectorImpl<Value *> &Indices,
1770 const Twine &Prefix) {
1771 if (Indices.empty())
1772 return BasePtr;
1773
1774 // A single zero index is a no-op, so check for this and avoid building a GEP
1775 // in that case.
1776 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1777 return BasePtr;
1778
1779 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1780}
1781
1782/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1783/// TargetTy without changing the offset of the pointer.
1784///
1785/// This routine assumes we've already established a properly offset GEP with
1786/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1787/// zero-indices down through type layers until we find one the same as
1788/// TargetTy. If we can't find one with the same type, we at least try to use
1789/// one with the same size. If none of that works, we just produce the GEP as
1790/// indicated by Indices to have the correct offset.
Micah Villmow3574eca2012-10-08 16:38:25 +00001791static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001792 Value *BasePtr, Type *Ty, Type *TargetTy,
1793 SmallVectorImpl<Value *> &Indices,
1794 const Twine &Prefix) {
1795 if (Ty == TargetTy)
1796 return buildGEP(IRB, BasePtr, Indices, Prefix);
1797
1798 // See if we can descend into a struct and locate a field with the correct
1799 // type.
1800 unsigned NumLayers = 0;
1801 Type *ElementTy = Ty;
1802 do {
1803 if (ElementTy->isPointerTy())
1804 break;
1805 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1806 ElementTy = SeqTy->getElementType();
Chandler Carruth020d9d52012-10-17 07:22:16 +00001807 // Note that we use the default address space as this index is over an
1808 // array or a vector, not a pointer.
1809 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(0), 0)));
Chandler Carruth713aa942012-09-14 09:22:59 +00001810 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth2fdb25b2012-10-09 01:58:35 +00001811 if (STy->element_begin() == STy->element_end())
1812 break; // Nothing left to descend into.
Chandler Carruth713aa942012-09-14 09:22:59 +00001813 ElementTy = *STy->element_begin();
1814 Indices.push_back(IRB.getInt32(0));
1815 } else {
1816 break;
1817 }
1818 ++NumLayers;
1819 } while (ElementTy != TargetTy);
1820 if (ElementTy != TargetTy)
1821 Indices.erase(Indices.end() - NumLayers, Indices.end());
1822
1823 return buildGEP(IRB, BasePtr, Indices, Prefix);
1824}
1825
1826/// \brief Recursively compute indices for a natural GEP.
1827///
1828/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1829/// element types adding appropriate indices for the GEP.
Micah Villmow3574eca2012-10-08 16:38:25 +00001830static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001831 Value *Ptr, Type *Ty, APInt &Offset,
1832 Type *TargetTy,
1833 SmallVectorImpl<Value *> &Indices,
1834 const Twine &Prefix) {
1835 if (Offset == 0)
1836 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1837
1838 // We can't recurse through pointer types.
1839 if (Ty->isPointerTy())
1840 return 0;
1841
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001842 // We try to analyze GEPs over vectors here, but note that these GEPs are
1843 // extremely poorly defined currently. The long-term goal is to remove GEPing
1844 // over a vector from the IR completely.
Chandler Carruth713aa942012-09-14 09:22:59 +00001845 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1846 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1847 if (ElementSizeInBits % 8)
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001848 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth713aa942012-09-14 09:22:59 +00001849 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth02bf98a2012-10-17 09:23:48 +00001850 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00001851 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1852 return 0;
1853 Offset -= NumSkippedElements * ElementSize;
1854 Indices.push_back(IRB.getInt(NumSkippedElements));
1855 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1856 Offset, TargetTy, Indices, Prefix);
1857 }
1858
1859 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1860 Type *ElementTy = ArrTy->getElementType();
1861 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
Chandler Carruth02bf98a2012-10-17 09:23:48 +00001862 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00001863 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1864 return 0;
1865
1866 Offset -= NumSkippedElements * ElementSize;
1867 Indices.push_back(IRB.getInt(NumSkippedElements));
1868 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1869 Indices, Prefix);
1870 }
1871
1872 StructType *STy = dyn_cast<StructType>(Ty);
1873 if (!STy)
1874 return 0;
1875
1876 const StructLayout *SL = TD.getStructLayout(STy);
1877 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthad41dcf2012-09-14 10:30:42 +00001878 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00001879 return 0;
1880 unsigned Index = SL->getElementContainingOffset(StructOffset);
1881 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1882 Type *ElementTy = STy->getElementType(Index);
1883 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1884 return 0; // The offset points into alignment padding.
1885
1886 Indices.push_back(IRB.getInt32(Index));
1887 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1888 Indices, Prefix);
1889}
1890
1891/// \brief Get a natural GEP from a base pointer to a particular offset and
1892/// resulting in a particular type.
1893///
1894/// The goal is to produce a "natural" looking GEP that works with the existing
1895/// composite types to arrive at the appropriate offset and element type for
1896/// a pointer. TargetTy is the element type the returned GEP should point-to if
1897/// possible. We recurse by decreasing Offset, adding the appropriate index to
1898/// Indices, and setting Ty to the result subtype.
1899///
Chandler Carruth7f5bede2012-09-14 10:18:49 +00001900/// If no natural GEP can be constructed, this function returns null.
Micah Villmow3574eca2012-10-08 16:38:25 +00001901static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001902 Value *Ptr, APInt Offset, Type *TargetTy,
1903 SmallVectorImpl<Value *> &Indices,
1904 const Twine &Prefix) {
1905 PointerType *Ty = cast<PointerType>(Ptr->getType());
1906
1907 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1908 // an i8.
1909 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1910 return 0;
1911
1912 Type *ElementTy = Ty->getElementType();
Chandler Carruth38f35fd2012-09-18 22:37:19 +00001913 if (!ElementTy->isSized())
1914 return 0; // We can't GEP through an unsized element.
Chandler Carruth713aa942012-09-14 09:22:59 +00001915 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1916 if (ElementSize == 0)
1917 return 0; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth02bf98a2012-10-17 09:23:48 +00001918 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00001919
1920 Offset -= NumSkippedElements * ElementSize;
1921 Indices.push_back(IRB.getInt(NumSkippedElements));
1922 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1923 Indices, Prefix);
1924}
1925
1926/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1927/// resulting pointer has PointerTy.
1928///
1929/// This tries very hard to compute a "natural" GEP which arrives at the offset
1930/// and produces the pointer type desired. Where it cannot, it will try to use
1931/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1932/// fails, it will try to use an existing i8* and GEP to the byte offset and
1933/// bitcast to the type.
1934///
1935/// The strategy for finding the more natural GEPs is to peel off layers of the
1936/// pointer, walking back through bit casts and GEPs, searching for a base
1937/// pointer from which we can compute a natural GEP with the desired
1938/// properities. The algorithm tries to fold as many constant indices into
1939/// a single GEP as possible, thus making each GEP more independent of the
1940/// surrounding code.
Micah Villmow3574eca2012-10-08 16:38:25 +00001941static Value *getAdjustedPtr(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001942 Value *Ptr, APInt Offset, Type *PointerTy,
1943 const Twine &Prefix) {
1944 // Even though we don't look through PHI nodes, we could be called on an
1945 // instruction in an unreachable block, which may be on a cycle.
1946 SmallPtrSet<Value *, 4> Visited;
1947 Visited.insert(Ptr);
1948 SmallVector<Value *, 4> Indices;
1949
1950 // We may end up computing an offset pointer that has the wrong type. If we
1951 // never are able to compute one directly that has the correct type, we'll
1952 // fall back to it, so keep it around here.
1953 Value *OffsetPtr = 0;
1954
1955 // Remember any i8 pointer we come across to re-use if we need to do a raw
1956 // byte offset.
1957 Value *Int8Ptr = 0;
1958 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1959
1960 Type *TargetTy = PointerTy->getPointerElementType();
1961
1962 do {
1963 // First fold any existing GEPs into the offset.
1964 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1965 APInt GEPOffset(Offset.getBitWidth(), 0);
1966 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1967 break;
1968 Offset += GEPOffset;
1969 Ptr = GEP->getPointerOperand();
1970 if (!Visited.insert(Ptr))
1971 break;
1972 }
1973
1974 // See if we can perform a natural GEP here.
1975 Indices.clear();
1976 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1977 Indices, Prefix)) {
1978 if (P->getType() == PointerTy) {
1979 // Zap any offset pointer that we ended up computing in previous rounds.
1980 if (OffsetPtr && OffsetPtr->use_empty())
1981 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1982 I->eraseFromParent();
1983 return P;
1984 }
1985 if (!OffsetPtr) {
1986 OffsetPtr = P;
1987 }
1988 }
1989
1990 // Stash this pointer if we've found an i8*.
1991 if (Ptr->getType()->isIntegerTy(8)) {
1992 Int8Ptr = Ptr;
1993 Int8PtrOffset = Offset;
1994 }
1995
1996 // Peel off a layer of the pointer and update the offset appropriately.
1997 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1998 Ptr = cast<Operator>(Ptr)->getOperand(0);
1999 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2000 if (GA->mayBeOverridden())
2001 break;
2002 Ptr = GA->getAliasee();
2003 } else {
2004 break;
2005 }
2006 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
2007 } while (Visited.insert(Ptr));
2008
2009 if (!OffsetPtr) {
2010 if (!Int8Ptr) {
2011 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
2012 Prefix + ".raw_cast");
2013 Int8PtrOffset = Offset;
2014 }
2015
2016 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
2017 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
2018 Prefix + ".raw_idx");
2019 }
2020 Ptr = OffsetPtr;
2021
2022 // On the off chance we were targeting i8*, guard the bitcast here.
2023 if (Ptr->getType() != PointerTy)
2024 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
2025
2026 return Ptr;
2027}
2028
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00002029/// \brief Test whether we can convert a value from the old to the new type.
2030///
2031/// This predicate should be used to guard calls to convertValue in order to
2032/// ensure that we only try to convert viable values. The strategy is that we
2033/// will peel off single element struct and array wrappings to get to an
2034/// underlying value, and convert that value.
2035static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
2036 if (OldTy == NewTy)
2037 return true;
2038 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
2039 return false;
2040 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
2041 return false;
2042
2043 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
2044 if (NewTy->isPointerTy() && OldTy->isPointerTy())
2045 return true;
2046 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
2047 return true;
2048 return false;
2049 }
2050
2051 return true;
2052}
2053
2054/// \brief Generic routine to convert an SSA value to a value of a different
2055/// type.
2056///
2057/// This will try various different casting techniques, such as bitcasts,
2058/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
2059/// two types for viability with this routine.
2060static Value *convertValue(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2061 Type *Ty) {
2062 assert(canConvertValue(DL, V->getType(), Ty) &&
2063 "Value not convertable to type");
2064 if (V->getType() == Ty)
2065 return V;
2066 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
2067 return IRB.CreateIntToPtr(V, Ty);
2068 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
2069 return IRB.CreatePtrToInt(V, Ty);
2070
2071 return IRB.CreateBitCast(V, Ty);
2072}
2073
Chandler Carruth713aa942012-09-14 09:22:59 +00002074/// \brief Test whether the given alloca partition can be promoted to a vector.
2075///
2076/// This is a quick test to check whether we can rewrite a particular alloca
2077/// partition (and its newly formed alloca) into a vector alloca with only
2078/// whole-vector loads and stores such that it could be promoted to a vector
2079/// SSA value. We only can ensure this for a limited set of operations, and we
2080/// don't want to do the rewrites unless we are confident that the result will
2081/// be promotable, so we have an early test here.
Micah Villmow3574eca2012-10-08 16:38:25 +00002082static bool isVectorPromotionViable(const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00002083 Type *AllocaTy,
2084 AllocaPartitioning &P,
2085 uint64_t PartitionBeginOffset,
2086 uint64_t PartitionEndOffset,
2087 AllocaPartitioning::const_use_iterator I,
2088 AllocaPartitioning::const_use_iterator E) {
2089 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
2090 if (!Ty)
2091 return false;
2092
2093 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
2094 uint64_t ElementSize = Ty->getScalarSizeInBits();
2095
2096 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2097 // that aren't byte sized.
2098 if (ElementSize % 8)
2099 return false;
2100 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
2101 VecSize /= 8;
2102 ElementSize /= 8;
2103
2104 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00002105 if (!I->U)
2106 continue; // Skip dead use.
2107
Chandler Carruth713aa942012-09-14 09:22:59 +00002108 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
2109 uint64_t BeginIndex = BeginOffset / ElementSize;
2110 if (BeginIndex * ElementSize != BeginOffset ||
2111 BeginIndex >= Ty->getNumElements())
2112 return false;
2113 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
2114 uint64_t EndIndex = EndOffset / ElementSize;
2115 if (EndIndex * ElementSize != EndOffset ||
2116 EndIndex > Ty->getNumElements())
2117 return false;
2118
Chandler Carruth07df7652012-11-21 08:16:30 +00002119 assert(EndIndex > BeginIndex && "Empty vector!");
2120 uint64_t NumElements = EndIndex - BeginIndex;
2121 Type *PartitionTy
2122 = (NumElements == 1) ? Ty->getElementType()
2123 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruth713aa942012-09-14 09:22:59 +00002124
Chandler Carruth77c12702012-10-01 01:49:22 +00002125 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002126 if (MI->isVolatile())
2127 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002128 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002129 const AllocaPartitioning::MemTransferOffsets &MTO
2130 = P.getMemTransferOffsets(*MTI);
2131 if (!MTO.IsSplittable)
2132 return false;
2133 }
Chandler Carruth77c12702012-10-01 01:49:22 +00002134 } else if (I->U->get()->getType()->getPointerElementType()->isStructTy()) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002135 // Disable vector promotion when there are loads or stores of an FCA.
2136 return false;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002137 } else if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
2138 if (LI->isVolatile())
2139 return false;
Chandler Carruth07df7652012-11-21 08:16:30 +00002140 if (!canConvertValue(TD, PartitionTy, LI->getType()))
2141 return false;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002142 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
2143 if (SI->isVolatile())
2144 return false;
Chandler Carruth07df7652012-11-21 08:16:30 +00002145 if (!canConvertValue(TD, SI->getValueOperand()->getType(), PartitionTy))
2146 return false;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002147 } else {
Chandler Carruth713aa942012-09-14 09:22:59 +00002148 return false;
2149 }
2150 }
2151 return true;
2152}
2153
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002154/// \brief Test whether the given alloca partition's integer operations can be
2155/// widened to promotable ones.
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002156///
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002157/// This is a quick test to check whether we can rewrite the integer loads and
2158/// stores to a particular alloca into wider loads and stores and be able to
2159/// promote the resulting alloca.
2160static bool isIntegerWideningViable(const DataLayout &TD,
2161 Type *AllocaTy,
2162 uint64_t AllocBeginOffset,
2163 AllocaPartitioning &P,
2164 AllocaPartitioning::const_use_iterator I,
2165 AllocaPartitioning::const_use_iterator E) {
2166 uint64_t SizeInBits = TD.getTypeSizeInBits(AllocaTy);
Benjamin Kramer5bded752012-12-01 11:53:32 +00002167 // Don't create integer types larger than the maximum bitwidth.
2168 if (SizeInBits > IntegerType::MAX_INT_BITS)
2169 return false;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002170
2171 // Don't try to handle allocas with bit-padding.
2172 if (SizeInBits != TD.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002173 return false;
2174
Chandler Carrutha2b88162012-10-25 04:37:07 +00002175 // We need to ensure that an integer type with the appropriate bitwidth can
2176 // be converted to the alloca type, whatever that is. We don't want to force
2177 // the alloca itself to have an integer type if there is a more suitable one.
2178 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2179 if (!canConvertValue(TD, AllocaTy, IntTy) ||
2180 !canConvertValue(TD, IntTy, AllocaTy))
2181 return false;
2182
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002183 uint64_t Size = TD.getTypeStoreSize(AllocaTy);
2184
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002185 // Check the uses to ensure the uses are (likely) promoteable integer uses.
2186 // Also ensure that the alloca has a covering load or store. We don't want
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002187 // to widen the integer operotains only to fail to promote due to some other
2188 // unsplittable entry (which we may make splittable later).
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002189 bool WholeAllocaOp = false;
2190 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00002191 if (!I->U)
2192 continue; // Skip dead use.
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002193
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002194 uint64_t RelBegin = I->BeginOffset - AllocBeginOffset;
2195 uint64_t RelEnd = I->EndOffset - AllocBeginOffset;
2196
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002197 // We can't reasonably handle cases where the load or store extends past
2198 // the end of the aloca's type and into its padding.
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002199 if (RelEnd > Size)
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002200 return false;
2201
Chandler Carruth77c12702012-10-01 01:49:22 +00002202 if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002203 if (LI->isVolatile())
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002204 return false;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002205 if (RelBegin == 0 && RelEnd == Size)
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002206 WholeAllocaOp = true;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002207 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2208 if (ITy->getBitWidth() < TD.getTypeStoreSize(ITy))
2209 return false;
2210 continue;
2211 }
2212 // Non-integer loads need to be convertible from the alloca type so that
2213 // they are promotable.
2214 if (RelBegin != 0 || RelEnd != Size ||
2215 !canConvertValue(TD, AllocaTy, LI->getType()))
2216 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002217 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002218 Type *ValueTy = SI->getValueOperand()->getType();
2219 if (SI->isVolatile())
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002220 return false;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002221 if (RelBegin == 0 && RelEnd == Size)
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002222 WholeAllocaOp = true;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002223 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2224 if (ITy->getBitWidth() < TD.getTypeStoreSize(ITy))
2225 return false;
2226 continue;
2227 }
2228 // Non-integer stores need to be convertible to the alloca type so that
2229 // they are promotable.
2230 if (RelBegin != 0 || RelEnd != Size ||
2231 !canConvertValue(TD, ValueTy, AllocaTy))
2232 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002233 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002234 if (MI->isVolatile())
2235 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002236 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002237 const AllocaPartitioning::MemTransferOffsets &MTO
2238 = P.getMemTransferOffsets(*MTI);
2239 if (!MTO.IsSplittable)
2240 return false;
2241 }
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002242 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->U->getUser())) {
2243 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2244 II->getIntrinsicID() != Intrinsic::lifetime_end)
2245 return false;
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002246 } else {
2247 return false;
2248 }
2249 }
2250 return WholeAllocaOp;
2251}
2252
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002253static Value *extractInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2254 IntegerType *Ty, uint64_t Offset,
2255 const Twine &Name) {
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002256 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002257 IntegerType *IntTy = cast<IntegerType>(V->getType());
2258 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2259 "Element extends past full value");
2260 uint64_t ShAmt = 8*Offset;
2261 if (DL.isBigEndian())
2262 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002263 if (ShAmt) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002264 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002265 DEBUG(dbgs() << " shifted: " << *V << "\n");
2266 }
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002267 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2268 "Cannot extract to a larger integer!");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002269 if (Ty != IntTy) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002270 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002271 DEBUG(dbgs() << " trunced: " << *V << "\n");
2272 }
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002273 return V;
2274}
2275
2276static Value *insertInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *Old,
2277 Value *V, uint64_t Offset, const Twine &Name) {
2278 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2279 IntegerType *Ty = cast<IntegerType>(V->getType());
2280 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2281 "Cannot insert a larger integer!");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002282 DEBUG(dbgs() << " start: " << *V << "\n");
2283 if (Ty != IntTy) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002284 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002285 DEBUG(dbgs() << " extended: " << *V << "\n");
2286 }
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002287 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2288 "Element store outside of alloca store");
2289 uint64_t ShAmt = 8*Offset;
2290 if (DL.isBigEndian())
2291 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002292 if (ShAmt) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002293 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002294 DEBUG(dbgs() << " shifted: " << *V << "\n");
2295 }
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002296
2297 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2298 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2299 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002300 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002301 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002302 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002303 }
2304 return V;
2305}
2306
Chandler Carruth713aa942012-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 Villmow3574eca2012-10-08 16:38:25 +00002319 const DataLayout &TD;
Chandler Carruth713aa942012-09-14 09:22:59 +00002320 AllocaPartitioning &P;
2321 SROA &Pass;
2322 AllocaInst &OldAI, &NewAI;
2323 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth520eeae2012-10-13 02:41:05 +00002324 Type *NewAllocaTy;
Chandler Carruth713aa942012-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
2328 // non-null, we have some strict guarantees about the rewriten alloca:
2329 // - 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 Carruthbc4021f2012-09-24 00:34:20 +00002339 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth81ff90d2012-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 Carruthbc4021f2012-09-24 00:34:20 +00002342 // integer type will be stored here for easy access during rewriting.
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002343 IntegerType *IntTy;
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002344
Chandler Carruth713aa942012-09-14 09:22:59 +00002345 // The offset of the partition user currently being rewritten.
2346 uint64_t BeginOffset, EndOffset;
Chandler Carruth77c12702012-10-01 01:49:22 +00002347 Use *OldUse;
Chandler Carruth713aa942012-09-14 09:22:59 +00002348 Instruction *OldPtr;
2349
2350 // The name prefix to use when rewriting instructions for this alloca.
2351 std::string NamePrefix;
2352
2353public:
Micah Villmow3574eca2012-10-08 16:38:25 +00002354 AllocaPartitionRewriter(const DataLayout &TD, AllocaPartitioning &P,
Chandler Carruth713aa942012-09-14 09:22:59 +00002355 AllocaPartitioning::iterator PI,
2356 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
2357 uint64_t NewBeginOffset, uint64_t NewEndOffset)
2358 : TD(TD), P(P), Pass(Pass),
2359 OldAI(OldAI), NewAI(NewAI),
2360 NewAllocaBeginOffset(NewBeginOffset),
2361 NewAllocaEndOffset(NewEndOffset),
Chandler Carruth520eeae2012-10-13 02:41:05 +00002362 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002363 VecTy(), ElementTy(), ElementSize(), IntTy(),
Chandler Carruth713aa942012-09-14 09:22:59 +00002364 BeginOffset(), EndOffset() {
2365 }
2366
2367 /// \brief Visit the users of the alloca partition and rewrite them.
2368 bool visitUsers(AllocaPartitioning::const_use_iterator I,
2369 AllocaPartitioning::const_use_iterator E) {
2370 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
2371 NewAllocaBeginOffset, NewAllocaEndOffset,
2372 I, E)) {
2373 ++NumVectorized;
2374 VecTy = cast<VectorType>(NewAI.getAllocatedType());
2375 ElementTy = VecTy->getElementType();
2376 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
2377 "Only multiple-of-8 sized vector elements are viable");
2378 ElementSize = VecTy->getScalarSizeInBits() / 8;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002379 } else if (isIntegerWideningViable(TD, NewAI.getAllocatedType(),
2380 NewAllocaBeginOffset, P, I, E)) {
2381 IntTy = Type::getIntNTy(NewAI.getContext(),
2382 TD.getTypeSizeInBits(NewAI.getAllocatedType()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002383 }
2384 bool CanSROA = true;
2385 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00002386 if (!I->U)
2387 continue; // Skip dead uses.
Chandler Carruth713aa942012-09-14 09:22:59 +00002388 BeginOffset = I->BeginOffset;
2389 EndOffset = I->EndOffset;
Chandler Carruth77c12702012-10-01 01:49:22 +00002390 OldUse = I->U;
2391 OldPtr = cast<Instruction>(I->U->get());
Chandler Carruth713aa942012-09-14 09:22:59 +00002392 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
Chandler Carruth77c12702012-10-01 01:49:22 +00002393 CanSROA &= visit(cast<Instruction>(I->U->getUser()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002394 }
2395 if (VecTy) {
2396 assert(CanSROA);
2397 VecTy = 0;
2398 ElementTy = 0;
2399 ElementSize = 0;
2400 }
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002401 if (IntTy) {
2402 assert(CanSROA);
2403 IntTy = 0;
2404 }
Chandler Carruth713aa942012-09-14 09:22:59 +00002405 return CanSROA;
2406 }
2407
2408private:
2409 // Every instruction which can end up as a user must have a rewrite rule.
2410 bool visitInstruction(Instruction &I) {
2411 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2412 llvm_unreachable("No rewrite rule for this instruction!");
2413 }
2414
2415 Twine getName(const Twine &Suffix) {
2416 return NamePrefix + Suffix;
2417 }
2418
2419 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
2420 assert(BeginOffset >= NewAllocaBeginOffset);
Chandler Carruth426c2bf2012-11-01 09:14:31 +00002421 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002422 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
2423 }
2424
Chandler Carruthf710fb12012-10-03 08:14:02 +00002425 /// \brief Compute suitable alignment to access an offset into the new alloca.
2426 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth673850a2012-10-01 12:16:54 +00002427 unsigned NewAIAlign = NewAI.getAlignment();
2428 if (!NewAIAlign)
2429 NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
2430 return MinAlign(NewAIAlign, Offset);
2431 }
Chandler Carruthf710fb12012-10-03 08:14:02 +00002432
2433 /// \brief Compute suitable alignment to access this partition of the new
2434 /// alloca.
2435 unsigned getPartitionAlign() {
2436 return getOffsetAlign(BeginOffset - NewAllocaBeginOffset);
Chandler Carruth673850a2012-10-01 12:16:54 +00002437 }
2438
Chandler Carruthf710fb12012-10-03 08:14:02 +00002439 /// \brief Compute suitable alignment to access a type at an offset of the
2440 /// new alloca.
2441 ///
2442 /// \returns zero if the type's ABI alignment is a suitable alignment,
2443 /// otherwise returns the maximal suitable alignment.
2444 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2445 unsigned Align = getOffsetAlign(Offset);
2446 return Align == TD.getABITypeAlignment(Ty) ? 0 : Align;
2447 }
2448
2449 /// \brief Compute suitable alignment to access a type at the beginning of
2450 /// this partition of the new alloca.
2451 ///
2452 /// See \c getOffsetTypeAlign for details; this routine delegates to it.
2453 unsigned getPartitionTypeAlign(Type *Ty) {
2454 return getOffsetTypeAlign(Ty, BeginOffset - NewAllocaBeginOffset);
Chandler Carruth673850a2012-10-01 12:16:54 +00002455 }
2456
Chandler Carruth07df7652012-11-21 08:16:30 +00002457 unsigned getIndex(uint64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002458 assert(VecTy && "Can only call getIndex when rewriting a vector");
2459 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2460 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2461 uint32_t Index = RelOffset / ElementSize;
2462 assert(Index * ElementSize == RelOffset);
Chandler Carruth07df7652012-11-21 08:16:30 +00002463 return Index;
Chandler Carruth713aa942012-09-14 09:22:59 +00002464 }
2465
2466 void deleteIfTriviallyDead(Value *V) {
2467 Instruction *I = cast<Instruction>(V);
2468 if (isInstructionTriviallyDead(I))
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002469 Pass.DeadInsts.insert(I);
Chandler Carruth713aa942012-09-14 09:22:59 +00002470 }
2471
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002472 Value *rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
2473 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2474 getName(".load"));
Chandler Carruth07df7652012-11-21 08:16:30 +00002475 unsigned BeginIndex = getIndex(BeginOffset);
2476 unsigned EndIndex = getIndex(EndOffset);
2477 assert(EndIndex > BeginIndex && "Empty vector!");
2478 unsigned NumElements = EndIndex - BeginIndex;
2479 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2480 if (NumElements == 1) {
2481 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002482 getName(".extract"));
Chandler Carruth07df7652012-11-21 08:16:30 +00002483 DEBUG(dbgs() << " extract: " << *V << "\n");
2484 } else if (NumElements < VecTy->getNumElements()) {
2485 SmallVector<Constant*, 8> Mask;
2486 Mask.reserve(NumElements);
2487 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2488 Mask.push_back(IRB.getInt32(i));
2489 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2490 ConstantVector::get(Mask),
2491 getName(".extract"));
2492 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruth713aa942012-09-14 09:22:59 +00002493 }
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002494 return V;
Chandler Carruth713aa942012-09-14 09:22:59 +00002495 }
2496
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002497 Value *rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002498 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002499 assert(!LI.isVolatile());
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002500 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2501 getName(".load"));
2502 V = convertValue(TD, IRB, V, IntTy);
2503 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2504 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002505 if (Offset > 0 || EndOffset < NewAllocaEndOffset)
2506 V = extractInteger(TD, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2507 getName(".extract"));
2508 return V;
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002509 }
2510
Chandler Carruth713aa942012-09-14 09:22:59 +00002511 bool visitLoadInst(LoadInst &LI) {
2512 DEBUG(dbgs() << " original: " << LI << "\n");
2513 Value *OldOp = LI.getOperand(0);
2514 assert(OldOp == OldPtr);
2515 IRBuilder<> IRB(&LI);
2516
Chandler Carrutha2b88162012-10-25 04:37:07 +00002517 uint64_t Size = EndOffset - BeginOffset;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002518 bool IsSplitIntLoad = Size < TD.getTypeStoreSize(LI.getType());
Chandler Carruth17679292012-11-20 10:02:19 +00002519
2520 // If this memory access can be shown to *statically* extend outside the
2521 // bounds of the original allocation it's behavior is undefined. Rather
2522 // than trying to transform it, just replace it with undef.
2523 // FIXME: We should do something more clever for functions being
2524 // instrumented by asan.
2525 // FIXME: Eventually, once ASan and friends can flush out bugs here, this
2526 // should be transformed to a load of null making it unreachable.
2527 uint64_t OldAllocSize = TD.getTypeAllocSize(OldAI.getAllocatedType());
2528 if (TD.getTypeStoreSize(LI.getType()) > OldAllocSize) {
2529 LI.replaceAllUsesWith(UndefValue::get(LI.getType()));
2530 Pass.DeadInsts.insert(&LI);
2531 deleteIfTriviallyDead(OldOp);
2532 DEBUG(dbgs() << " to: undef!!\n");
2533 return true;
2534 }
2535
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002536 Type *TargetTy = IsSplitIntLoad ? Type::getIntNTy(LI.getContext(), Size * 8)
2537 : LI.getType();
2538 bool IsPtrAdjusted = false;
2539 Value *V;
2540 if (VecTy) {
2541 V = rewriteVectorizedLoadInst(IRB, LI, OldOp);
2542 } else if (IntTy && LI.getType()->isIntegerTy()) {
2543 V = rewriteIntegerLoad(IRB, LI);
2544 } else if (BeginOffset == NewAllocaBeginOffset &&
2545 canConvertValue(TD, NewAllocaTy, LI.getType())) {
2546 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2547 LI.isVolatile(), getName(".load"));
2548 } else {
2549 Type *LTy = TargetTy->getPointerTo();
2550 V = IRB.CreateAlignedLoad(getAdjustedAllocaPtr(IRB, LTy),
2551 getPartitionTypeAlign(TargetTy),
2552 LI.isVolatile(), getName(".load"));
2553 IsPtrAdjusted = true;
2554 }
2555 V = convertValue(TD, IRB, V, TargetTy);
2556
2557 if (IsSplitIntLoad) {
Chandler Carrutha2b88162012-10-25 04:37:07 +00002558 assert(!LI.isVolatile());
2559 assert(LI.getType()->isIntegerTy() &&
2560 "Only integer type loads and stores are split");
2561 assert(LI.getType()->getIntegerBitWidth() ==
2562 TD.getTypeStoreSizeInBits(LI.getType()) &&
2563 "Non-byte-multiple bit width");
2564 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth70dace32012-10-30 20:52:40 +00002565 TD.getTypeAllocSizeInBits(OldAI.getAllocatedType()) &&
Chandler Carrutha2b88162012-10-25 04:37:07 +00002566 "Only alloca-wide loads can be split and recomposed");
Chandler Carrutha2b88162012-10-25 04:37:07 +00002567 // Move the insertion point just past the load so that we can refer to it.
2568 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
Chandler Carrutha2b88162012-10-25 04:37:07 +00002569 // Create a placeholder value with the same type as LI to use as the
2570 // basis for the new value. This allows us to replace the uses of LI with
2571 // the computed value, and then replace the placeholder with LI, leaving
2572 // LI only used for this computation.
2573 Value *Placeholder
Jakub Staszak5801ff92012-11-01 01:10:43 +00002574 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carrutha2b88162012-10-25 04:37:07 +00002575 V = insertInteger(TD, IRB, Placeholder, V, BeginOffset,
2576 getName(".insert"));
2577 LI.replaceAllUsesWith(V);
2578 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak5801ff92012-11-01 01:10:43 +00002579 delete Placeholder;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002580 } else {
2581 LI.replaceAllUsesWith(V);
Chandler Carrutha2b88162012-10-25 04:37:07 +00002582 }
2583
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002584 Pass.DeadInsts.insert(&LI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002585 deleteIfTriviallyDead(OldOp);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002586 DEBUG(dbgs() << " to: " << *V << "\n");
2587 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth713aa942012-09-14 09:22:59 +00002588 }
2589
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002590 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, Value *V,
2591 StoreInst &SI, Value *OldOp) {
Chandler Carruth07df7652012-11-21 08:16:30 +00002592 unsigned BeginIndex = getIndex(BeginOffset);
2593 unsigned EndIndex = getIndex(EndOffset);
2594 assert(EndIndex > BeginIndex && "Empty vector!");
2595 unsigned NumElements = EndIndex - BeginIndex;
2596 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2597 Type *PartitionTy
2598 = (NumElements == 1) ? ElementTy
2599 : VectorType::get(ElementTy, NumElements);
2600 if (V->getType() != PartitionTy)
2601 V = convertValue(TD, IRB, V, PartitionTy);
2602 if (NumElements < VecTy->getNumElements()) {
2603 // We need to mix in the existing elements.
Chandler Carruth81b001a2012-09-26 10:27:46 +00002604 LoadInst *LI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2605 getName(".load"));
Chandler Carruth07df7652012-11-21 08:16:30 +00002606 if (NumElements == 1) {
2607 V = IRB.CreateInsertElement(LI, V, IRB.getInt32(BeginIndex),
2608 getName(".insert"));
2609 DEBUG(dbgs() << " insert: " << *V << "\n");
2610 } else {
2611 // When inserting a smaller vector into the larger to store, we first
2612 // use a shuffle vector to widen it with undef elements, and then
2613 // a second shuffle vector to select between the loaded vector and the
2614 // incoming vector.
2615 SmallVector<Constant*, 8> Mask;
2616 Mask.reserve(VecTy->getNumElements());
2617 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2618 if (i >= BeginIndex && i < EndIndex)
2619 Mask.push_back(IRB.getInt32(i - BeginIndex));
2620 else
2621 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2622 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2623 ConstantVector::get(Mask),
2624 getName(".expand"));
2625 DEBUG(dbgs() << " shuffle1: " << *V << "\n");
2626
2627 Mask.clear();
2628 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2629 if (i >= BeginIndex && i < EndIndex)
2630 Mask.push_back(IRB.getInt32(i));
2631 else
2632 Mask.push_back(IRB.getInt32(i + VecTy->getNumElements()));
2633 V = IRB.CreateShuffleVector(V, LI, ConstantVector::get(Mask),
2634 getName("insert"));
2635 DEBUG(dbgs() << " shuffle2: " << *V << "\n");
2636 }
2637 } else {
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00002638 V = convertValue(TD, IRB, V, VecTy);
Chandler Carruth713aa942012-09-14 09:22:59 +00002639 }
Chandler Carruth81b001a2012-09-26 10:27:46 +00002640 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002641 Pass.DeadInsts.insert(&SI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002642
2643 (void)Store;
2644 DEBUG(dbgs() << " to: " << *Store << "\n");
2645 return true;
2646 }
2647
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002648 bool rewriteIntegerStore(IRBuilder<> &IRB, Value *V, StoreInst &SI) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002649 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002650 assert(!SI.isVolatile());
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002651 if (TD.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2652 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2653 getName(".oldload"));
2654 Old = convertValue(TD, IRB, Old, IntTy);
2655 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2656 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2657 V = insertInteger(TD, IRB, Old, SI.getValueOperand(), Offset,
2658 getName(".insert"));
2659 }
2660 V = convertValue(TD, IRB, V, NewAllocaTy);
2661 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002662 Pass.DeadInsts.insert(&SI);
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002663 (void)Store;
2664 DEBUG(dbgs() << " to: " << *Store << "\n");
2665 return true;
2666 }
2667
Chandler Carruth713aa942012-09-14 09:22:59 +00002668 bool visitStoreInst(StoreInst &SI) {
2669 DEBUG(dbgs() << " original: " << SI << "\n");
2670 Value *OldOp = SI.getOperand(1);
2671 assert(OldOp == OldPtr);
2672 IRBuilder<> IRB(&SI);
2673
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002674 Value *V = SI.getValueOperand();
Chandler Carruth520eeae2012-10-13 02:41:05 +00002675
Chandler Carruthb2d98c22012-10-04 12:33:50 +00002676 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2677 // alloca that should be re-examined after promoting this alloca.
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002678 if (V->getType()->isPointerTy())
2679 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthb2d98c22012-10-04 12:33:50 +00002680 Pass.PostPromotionWorklist.insert(AI);
2681
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002682 uint64_t Size = EndOffset - BeginOffset;
2683 if (Size < TD.getTypeStoreSize(V->getType())) {
2684 assert(!SI.isVolatile());
2685 assert(V->getType()->isIntegerTy() &&
2686 "Only integer type loads and stores are split");
2687 assert(V->getType()->getIntegerBitWidth() ==
2688 TD.getTypeStoreSizeInBits(V->getType()) &&
2689 "Non-byte-multiple bit width");
2690 assert(V->getType()->getIntegerBitWidth() ==
2691 TD.getTypeSizeInBits(OldAI.getAllocatedType()) &&
2692 "Only alloca-wide stores can be split and recomposed");
2693 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
2694 V = extractInteger(TD, IRB, V, NarrowTy, BeginOffset,
2695 getName(".extract"));
Chandler Carruth520eeae2012-10-13 02:41:05 +00002696 }
2697
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002698 if (VecTy)
2699 return rewriteVectorizedStoreInst(IRB, V, SI, OldOp);
2700 if (IntTy && V->getType()->isIntegerTy())
2701 return rewriteIntegerStore(IRB, V, SI);
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002702
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002703 StoreInst *NewSI;
2704 if (BeginOffset == NewAllocaBeginOffset &&
2705 canConvertValue(TD, V->getType(), NewAllocaTy)) {
2706 V = convertValue(TD, IRB, V, NewAllocaTy);
2707 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2708 SI.isVolatile());
2709 } else {
2710 Value *NewPtr = getAdjustedAllocaPtr(IRB, V->getType()->getPointerTo());
2711 NewSI = IRB.CreateAlignedStore(V, NewPtr,
2712 getPartitionTypeAlign(V->getType()),
2713 SI.isVolatile());
2714 }
2715 (void)NewSI;
2716 Pass.DeadInsts.insert(&SI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002717 deleteIfTriviallyDead(OldOp);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002718
2719 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2720 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth713aa942012-09-14 09:22:59 +00002721 }
2722
2723 bool visitMemSetInst(MemSetInst &II) {
2724 DEBUG(dbgs() << " original: " << II << "\n");
2725 IRBuilder<> IRB(&II);
2726 assert(II.getRawDest() == OldPtr);
2727
2728 // If the memset has a variable size, it cannot be split, just adjust the
2729 // pointer to the new alloca.
2730 if (!isa<Constant>(II.getLength())) {
2731 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002732 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthf710fb12012-10-03 08:14:02 +00002733 II.setAlignment(ConstantInt::get(CstTy, getPartitionAlign()));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002734
Chandler Carruth713aa942012-09-14 09:22:59 +00002735 deleteIfTriviallyDead(OldPtr);
2736 return false;
2737 }
2738
2739 // Record this instruction for deletion.
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002740 Pass.DeadInsts.insert(&II);
Chandler Carruth713aa942012-09-14 09:22:59 +00002741
2742 Type *AllocaTy = NewAI.getAllocatedType();
2743 Type *ScalarTy = AllocaTy->getScalarType();
2744
2745 // If this doesn't map cleanly onto the alloca type, and that type isn't
2746 // a single value type, just emit a memset.
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002747 if (!VecTy && !IntTy &&
2748 (BeginOffset != NewAllocaBeginOffset ||
2749 EndOffset != NewAllocaEndOffset ||
2750 !AllocaTy->isSingleValueType() ||
2751 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002752 Type *SizeTy = II.getLength()->getType();
2753 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002754 CallInst *New
2755 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2756 II.getRawDest()->getType()),
Chandler Carruthf710fb12012-10-03 08:14:02 +00002757 II.getValue(), Size, getPartitionAlign(),
Chandler Carruth713aa942012-09-14 09:22:59 +00002758 II.isVolatile());
2759 (void)New;
2760 DEBUG(dbgs() << " to: " << *New << "\n");
2761 return false;
2762 }
2763
2764 // If we can represent this as a simple value, we have to build the actual
2765 // value to store, which requires expanding the byte present in memset to
2766 // a sensible representation for the alloca type. This is essentially
2767 // splatting the byte to a sufficiently wide integer, bitcasting to the
2768 // desired scalar type, and splatting it across any desired vector type.
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002769 uint64_t Size = EndOffset - BeginOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +00002770 Value *V = II.getValue();
2771 IntegerType *VTy = cast<IntegerType>(V->getType());
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002772 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2773 if (Size*8 > VTy->getBitWidth())
2774 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, getName(".zext")),
Chandler Carruth713aa942012-09-14 09:22:59 +00002775 ConstantExpr::getUDiv(
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002776 Constant::getAllOnesValue(SplatIntTy),
Chandler Carruth713aa942012-09-14 09:22:59 +00002777 ConstantExpr::getZExt(
2778 Constant::getAllOnesValue(V->getType()),
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002779 SplatIntTy)),
Chandler Carruth713aa942012-09-14 09:22:59 +00002780 getName(".isplat"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002781
2782 // If this is an element-wide memset of a vectorizable alloca, insert it.
2783 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
2784 EndOffset < NewAllocaEndOffset)) {
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002785 if (V->getType() != ScalarTy)
2786 V = convertValue(TD, IRB, V, ScalarTy);
Chandler Carruth81b001a2012-09-26 10:27:46 +00002787 StoreInst *Store = IRB.CreateAlignedStore(
2788 IRB.CreateInsertElement(IRB.CreateAlignedLoad(&NewAI,
2789 NewAI.getAlignment(),
2790 getName(".load")),
Chandler Carruth07df7652012-11-21 08:16:30 +00002791 V, IRB.getInt32(getIndex(BeginOffset)),
Chandler Carruth713aa942012-09-14 09:22:59 +00002792 getName(".insert")),
Chandler Carruth81b001a2012-09-26 10:27:46 +00002793 &NewAI, NewAI.getAlignment());
Chandler Carruth713aa942012-09-14 09:22:59 +00002794 (void)Store;
2795 DEBUG(dbgs() << " to: " << *Store << "\n");
2796 return true;
2797 }
2798
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002799 // If this is a memset on an alloca where we can widen stores, insert the
2800 // set integer.
2801 if (IntTy && (BeginOffset > NewAllocaBeginOffset ||
2802 EndOffset < NewAllocaEndOffset)) {
2803 assert(!II.isVolatile());
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002804 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2805 getName(".oldload"));
2806 Old = convertValue(TD, IRB, Old, IntTy);
2807 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2808 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2809 V = insertInteger(TD, IRB, Old, V, Offset, getName(".insert"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002810 }
2811
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002812 if (V->getType() != AllocaTy)
2813 V = convertValue(TD, IRB, V, AllocaTy);
2814
Chandler Carruth81b001a2012-09-26 10:27:46 +00002815 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2816 II.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +00002817 (void)New;
2818 DEBUG(dbgs() << " to: " << *New << "\n");
2819 return !II.isVolatile();
2820 }
2821
2822 bool visitMemTransferInst(MemTransferInst &II) {
2823 // Rewriting of memory transfer instructions can be a bit tricky. We break
2824 // them into two categories: split intrinsics and unsplit intrinsics.
2825
2826 DEBUG(dbgs() << " original: " << II << "\n");
2827 IRBuilder<> IRB(&II);
2828
2829 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2830 bool IsDest = II.getRawDest() == OldPtr;
2831
2832 const AllocaPartitioning::MemTransferOffsets &MTO
2833 = P.getMemTransferOffsets(II);
2834
Chandler Carruth673850a2012-10-01 12:16:54 +00002835 // Compute the relative offset within the transfer.
Chandler Carruth426c2bf2012-11-01 09:14:31 +00002836 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chandler Carruth673850a2012-10-01 12:16:54 +00002837 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2838 : MTO.SourceBegin));
2839
2840 unsigned Align = II.getAlignment();
2841 if (Align > 1)
2842 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
Chandler Carruthf710fb12012-10-03 08:14:02 +00002843 MinAlign(II.getAlignment(), getPartitionAlign()));
Chandler Carruth673850a2012-10-01 12:16:54 +00002844
Chandler Carruth713aa942012-09-14 09:22:59 +00002845 // For unsplit intrinsics, we simply modify the source and destination
2846 // pointers in place. This isn't just an optimization, it is a matter of
2847 // correctness. With unsplit intrinsics we may be dealing with transfers
2848 // within a single alloca before SROA ran, or with transfers that have
2849 // a variable length. We may also be dealing with memmove instead of
2850 // memcpy, and so simply updating the pointers is the necessary for us to
2851 // update both source and dest of a single call.
2852 if (!MTO.IsSplittable) {
2853 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2854 if (IsDest)
2855 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2856 else
2857 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2858
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002859 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth673850a2012-10-01 12:16:54 +00002860 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002861
Chandler Carruth713aa942012-09-14 09:22:59 +00002862 DEBUG(dbgs() << " to: " << II << "\n");
2863 deleteIfTriviallyDead(OldOp);
2864 return false;
2865 }
2866 // For split transfer intrinsics we have an incredibly useful assurance:
2867 // the source and destination do not reside within the same alloca, and at
2868 // least one of them does not escape. This means that we can replace
2869 // memmove with memcpy, and we don't need to worry about all manner of
2870 // downsides to splitting and transforming the operations.
2871
Chandler Carruth713aa942012-09-14 09:22:59 +00002872 // If this doesn't map cleanly onto the alloca type, and that type isn't
2873 // a single value type, just emit a memcpy.
2874 bool EmitMemCpy
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002875 = !VecTy && !IntTy && (BeginOffset != NewAllocaBeginOffset ||
2876 EndOffset != NewAllocaEndOffset ||
2877 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth713aa942012-09-14 09:22:59 +00002878
2879 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2880 // size hasn't been shrunk based on analysis of the viable range, this is
2881 // a no-op.
2882 if (EmitMemCpy && &OldAI == &NewAI) {
2883 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2884 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2885 // Ensure the start lines up.
2886 assert(BeginOffset == OrigBegin);
Benjamin Kramerd0807692012-09-14 13:08:09 +00002887 (void)OrigBegin;
Chandler Carruth713aa942012-09-14 09:22:59 +00002888
2889 // Rewrite the size as needed.
2890 if (EndOffset != OrigEnd)
2891 II.setLength(ConstantInt::get(II.getLength()->getType(),
2892 EndOffset - BeginOffset));
2893 return false;
2894 }
2895 // Record this instruction for deletion.
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002896 Pass.DeadInsts.insert(&II);
Chandler Carruth713aa942012-09-14 09:22:59 +00002897
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002898 bool IsWholeAlloca = BeginOffset == NewAllocaBeginOffset &&
2899 EndOffset == NewAllocaEndOffset;
2900 bool IsVectorElement = VecTy && !IsWholeAlloca;
2901 uint64_t Size = EndOffset - BeginOffset;
2902 IntegerType *SubIntTy
2903 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00002904
2905 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2906 : II.getRawDest()->getType();
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002907 if (!EmitMemCpy) {
2908 if (IsVectorElement)
Micah Villmowb8bce922012-10-24 17:25:11 +00002909 OtherPtrTy = VecTy->getElementType()->getPointerTo();
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002910 else if (IntTy && !IsWholeAlloca)
Micah Villmowb8bce922012-10-24 17:25:11 +00002911 OtherPtrTy = SubIntTy->getPointerTo();
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002912 else
2913 OtherPtrTy = NewAI.getType();
2914 }
Chandler Carruth713aa942012-09-14 09:22:59 +00002915
2916 // Compute the other pointer, folding as much as possible to produce
2917 // a single, simple GEP in most cases.
2918 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2919 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2920 getName("." + OtherPtr->getName()));
2921
2922 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2923 // alloca that should be re-examined after rewriting this instruction.
2924 if (AllocaInst *AI
2925 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Chandler Carruthb3dca3f2012-09-26 07:41:40 +00002926 Pass.Worklist.insert(AI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002927
2928 if (EmitMemCpy) {
2929 Value *OurPtr
2930 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2931 : II.getRawSource()->getType());
2932 Type *SizeTy = II.getLength()->getType();
2933 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2934
2935 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2936 IsDest ? OtherPtr : OurPtr,
Chandler Carruth81b001a2012-09-26 10:27:46 +00002937 Size, Align, II.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +00002938 (void)New;
2939 DEBUG(dbgs() << " to: " << *New << "\n");
2940 return false;
2941 }
2942
Chandler Carruth322e9ba2012-10-03 08:26:28 +00002943 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2944 // is equivalent to 1, but that isn't true if we end up rewriting this as
2945 // a load or store.
2946 if (!Align)
2947 Align = 1;
2948
Chandler Carruth713aa942012-09-14 09:22:59 +00002949 Value *SrcPtr = OtherPtr;
2950 Value *DstPtr = &NewAI;
2951 if (!IsDest)
2952 std::swap(SrcPtr, DstPtr);
2953
2954 Value *Src;
2955 if (IsVectorElement && !IsDest) {
2956 // We have to extract rather than load.
Chandler Carruth81b001a2012-09-26 10:27:46 +00002957 Src = IRB.CreateExtractElement(
2958 IRB.CreateAlignedLoad(SrcPtr, Align, getName(".copyload")),
Chandler Carruth07df7652012-11-21 08:16:30 +00002959 IRB.getInt32(getIndex(BeginOffset)),
Chandler Carruth81b001a2012-09-26 10:27:46 +00002960 getName(".copyextract"));
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002961 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002962 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2963 getName(".load"));
2964 Src = convertValue(TD, IRB, Src, IntTy);
2965 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2966 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2967 Src = extractInteger(TD, IRB, Src, SubIntTy, Offset, getName(".extract"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002968 } else {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002969 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2970 getName(".copyload"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002971 }
2972
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002973 if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002974 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2975 getName(".oldload"));
2976 Old = convertValue(TD, IRB, Old, IntTy);
2977 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2978 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2979 Src = insertInteger(TD, IRB, Old, Src, Offset, getName(".insert"));
2980 Src = convertValue(TD, IRB, Src, NewAllocaTy);
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002981 }
2982
Chandler Carruth713aa942012-09-14 09:22:59 +00002983 if (IsVectorElement && IsDest) {
2984 // We have to insert into a loaded copy before storing.
Chandler Carruth81b001a2012-09-26 10:27:46 +00002985 Src = IRB.CreateInsertElement(
2986 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
Chandler Carruth07df7652012-11-21 08:16:30 +00002987 Src, IRB.getInt32(getIndex(BeginOffset)),
Chandler Carruth81b001a2012-09-26 10:27:46 +00002988 getName(".insert"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002989 }
2990
Chandler Carruth81b001a2012-09-26 10:27:46 +00002991 StoreInst *Store = cast<StoreInst>(
2992 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2993 (void)Store;
Chandler Carruth713aa942012-09-14 09:22:59 +00002994 DEBUG(dbgs() << " to: " << *Store << "\n");
2995 return !II.isVolatile();
2996 }
2997
2998 bool visitIntrinsicInst(IntrinsicInst &II) {
2999 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
3000 II.getIntrinsicID() == Intrinsic::lifetime_end);
3001 DEBUG(dbgs() << " original: " << II << "\n");
3002 IRBuilder<> IRB(&II);
3003 assert(II.getArgOperand(1) == OldPtr);
3004
3005 // Record this instruction for deletion.
Chandler Carruthf5837aa2012-11-20 01:12:50 +00003006 Pass.DeadInsts.insert(&II);
Chandler Carruth713aa942012-09-14 09:22:59 +00003007
3008 ConstantInt *Size
3009 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
3010 EndOffset - BeginOffset);
3011 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
3012 Value *New;
3013 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3014 New = IRB.CreateLifetimeStart(Ptr, Size);
3015 else
3016 New = IRB.CreateLifetimeEnd(Ptr, Size);
3017
3018 DEBUG(dbgs() << " to: " << *New << "\n");
3019 return true;
3020 }
3021
Chandler Carruth713aa942012-09-14 09:22:59 +00003022 bool visitPHINode(PHINode &PN) {
3023 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003024
Chandler Carruth713aa942012-09-14 09:22:59 +00003025 // We would like to compute a new pointer in only one place, but have it be
3026 // as local as possible to the PHI. To do that, we re-use the location of
3027 // the old pointer, which necessarily must be in the right position to
3028 // dominate the PHI.
3029 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
3030
Chandler Carruth713aa942012-09-14 09:22:59 +00003031 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003032 // Replace the operands which were using the old pointer.
Benjamin Kramer2a132422012-10-20 12:04:57 +00003033 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth713aa942012-09-14 09:22:59 +00003034
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003035 DEBUG(dbgs() << " to: " << PN << "\n");
3036 deleteIfTriviallyDead(OldPtr);
3037 return false;
Chandler Carruth713aa942012-09-14 09:22:59 +00003038 }
3039
3040 bool visitSelectInst(SelectInst &SI) {
3041 DEBUG(dbgs() << " original: " << SI << "\n");
3042 IRBuilder<> IRB(&SI);
3043
3044 // Find the operand we need to rewrite here.
3045 bool IsTrueVal = SI.getTrueValue() == OldPtr;
3046 if (IsTrueVal)
3047 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
3048 else
3049 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003050
Chandler Carruth713aa942012-09-14 09:22:59 +00003051 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003052 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
3053 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth713aa942012-09-14 09:22:59 +00003054 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003055 return false;
Chandler Carruth713aa942012-09-14 09:22:59 +00003056 }
3057
3058};
3059}
3060
Chandler Carruthc370acd2012-09-18 12:57:43 +00003061namespace {
3062/// \brief Visitor to rewrite aggregate loads and stores as scalar.
3063///
3064/// This pass aggressively rewrites all aggregate loads and stores on
3065/// a particular pointer (or any pointer derived from it which we can identify)
3066/// with scalar loads and stores.
3067class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3068 // Befriend the base class so it can delegate to private visit methods.
3069 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3070
Micah Villmow3574eca2012-10-08 16:38:25 +00003071 const DataLayout &TD;
Chandler Carruthc370acd2012-09-18 12:57:43 +00003072
3073 /// Queue of pointer uses to analyze and potentially rewrite.
3074 SmallVector<Use *, 8> Queue;
3075
3076 /// Set to prevent us from cycling with phi nodes and loops.
3077 SmallPtrSet<User *, 8> Visited;
3078
3079 /// The current pointer use being rewritten. This is used to dig up the used
3080 /// value (as opposed to the user).
3081 Use *U;
3082
3083public:
Micah Villmow3574eca2012-10-08 16:38:25 +00003084 AggLoadStoreRewriter(const DataLayout &TD) : TD(TD) {}
Chandler Carruthc370acd2012-09-18 12:57:43 +00003085
3086 /// Rewrite loads and stores through a pointer and all pointers derived from
3087 /// it.
3088 bool rewrite(Instruction &I) {
3089 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3090 enqueueUsers(I);
3091 bool Changed = false;
3092 while (!Queue.empty()) {
3093 U = Queue.pop_back_val();
3094 Changed |= visit(cast<Instruction>(U->getUser()));
3095 }
3096 return Changed;
3097 }
3098
3099private:
3100 /// Enqueue all the users of the given instruction for further processing.
3101 /// This uses a set to de-duplicate users.
3102 void enqueueUsers(Instruction &I) {
3103 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3104 ++UI)
3105 if (Visited.insert(*UI))
3106 Queue.push_back(&UI.getUse());
3107 }
3108
3109 // Conservative default is to not rewrite anything.
3110 bool visitInstruction(Instruction &I) { return false; }
3111
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003112 /// \brief Generic recursive split emission class.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003113 template <typename Derived>
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003114 class OpSplitter {
3115 protected:
3116 /// The builder used to form new instructions.
3117 IRBuilder<> IRB;
3118 /// The indices which to be used with insert- or extractvalue to select the
3119 /// appropriate value within the aggregate.
3120 SmallVector<unsigned, 4> Indices;
3121 /// The indices to a GEP instruction which will move Ptr to the correct slot
3122 /// within the aggregate.
3123 SmallVector<Value *, 4> GEPIndices;
3124 /// The base pointer of the original op, used as a base for GEPing the
3125 /// split operations.
3126 Value *Ptr;
Chandler Carruthc370acd2012-09-18 12:57:43 +00003127
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003128 /// Initialize the splitter with an insertion point, Ptr and start with a
3129 /// single zero GEP index.
3130 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003131 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003132
3133 public:
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003134 /// \brief Generic recursive split emission routine.
3135 ///
3136 /// This method recursively splits an aggregate op (load or store) into
3137 /// scalar or vector ops. It splits recursively until it hits a single value
3138 /// and emits that single value operation via the template argument.
3139 ///
3140 /// The logic of this routine relies on GEPs and insertvalue and
3141 /// extractvalue all operating with the same fundamental index list, merely
3142 /// formatted differently (GEPs need actual values).
3143 ///
3144 /// \param Ty The type being split recursively into smaller ops.
3145 /// \param Agg The aggregate value being built up or stored, depending on
3146 /// whether this is splitting a load or a store respectively.
3147 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3148 if (Ty->isSingleValueType())
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003149 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003150
3151 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3152 unsigned OldSize = Indices.size();
3153 (void)OldSize;
3154 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3155 ++Idx) {
3156 assert(Indices.size() == OldSize && "Did not return to the old size");
3157 Indices.push_back(Idx);
3158 GEPIndices.push_back(IRB.getInt32(Idx));
3159 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3160 GEPIndices.pop_back();
3161 Indices.pop_back();
3162 }
3163 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00003164 }
Chandler Carruthc370acd2012-09-18 12:57:43 +00003165
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003166 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3167 unsigned OldSize = Indices.size();
3168 (void)OldSize;
3169 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3170 ++Idx) {
3171 assert(Indices.size() == OldSize && "Did not return to the old size");
3172 Indices.push_back(Idx);
3173 GEPIndices.push_back(IRB.getInt32(Idx));
3174 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3175 GEPIndices.pop_back();
3176 Indices.pop_back();
3177 }
3178 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00003179 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003180
3181 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruthc370acd2012-09-18 12:57:43 +00003182 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003183 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00003184
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003185 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003186 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00003187 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruthc370acd2012-09-18 12:57:43 +00003188
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003189 /// Emit a leaf load of a single value. This is called at the leaves of the
3190 /// recursive emission to actually load values.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003191 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003192 assert(Ty->isSingleValueType());
3193 // Load the single value and insert it using the indices.
3194 Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices,
3195 Name + ".gep"),
3196 Name + ".load");
3197 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3198 DEBUG(dbgs() << " to: " << *Load << "\n");
3199 }
3200 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00003201
3202 bool visitLoadInst(LoadInst &LI) {
3203 assert(LI.getPointerOperand() == *U);
3204 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3205 return false;
3206
3207 // We have an aggregate being loaded, split it apart.
3208 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003209 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruthc370acd2012-09-18 12:57:43 +00003210 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003211 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00003212 LI.replaceAllUsesWith(V);
3213 LI.eraseFromParent();
3214 return true;
3215 }
3216
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003217 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003218 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00003219 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003220
3221 /// Emit a leaf store of a single value. This is called at the leaves of the
3222 /// recursive emission to actually produce stores.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003223 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003224 assert(Ty->isSingleValueType());
3225 // Extract the single value and store it using the indices.
3226 Value *Store = IRB.CreateStore(
3227 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3228 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
3229 (void)Store;
3230 DEBUG(dbgs() << " to: " << *Store << "\n");
3231 }
3232 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00003233
3234 bool visitStoreInst(StoreInst &SI) {
3235 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3236 return false;
3237 Value *V = SI.getValueOperand();
3238 if (V->getType()->isSingleValueType())
3239 return false;
3240
3241 // We have an aggregate being stored, split it apart.
3242 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003243 StoreOpSplitter Splitter(&SI, *U);
3244 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00003245 SI.eraseFromParent();
3246 return true;
3247 }
3248
3249 bool visitBitCastInst(BitCastInst &BC) {
3250 enqueueUsers(BC);
3251 return false;
3252 }
3253
3254 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3255 enqueueUsers(GEPI);
3256 return false;
3257 }
3258
3259 bool visitPHINode(PHINode &PN) {
3260 enqueueUsers(PN);
3261 return false;
3262 }
3263
3264 bool visitSelectInst(SelectInst &SI) {
3265 enqueueUsers(SI);
3266 return false;
3267 }
3268};
3269}
3270
Chandler Carruth07525a62012-10-13 10:49:33 +00003271/// \brief Strip aggregate type wrapping.
3272///
3273/// This removes no-op aggregate types wrapping an underlying type. It will
3274/// strip as many layers of types as it can without changing either the type
3275/// size or the allocated size.
3276static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3277 if (Ty->isSingleValueType())
3278 return Ty;
3279
3280 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3281 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3282
3283 Type *InnerTy;
3284 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3285 InnerTy = ArrTy->getElementType();
3286 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3287 const StructLayout *SL = DL.getStructLayout(STy);
3288 unsigned Index = SL->getElementContainingOffset(0);
3289 InnerTy = STy->getElementType(Index);
3290 } else {
3291 return Ty;
3292 }
3293
3294 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3295 TypeSize > DL.getTypeSizeInBits(InnerTy))
3296 return Ty;
3297
3298 return stripAggregateTypeWrapping(DL, InnerTy);
3299}
3300
Chandler Carruth713aa942012-09-14 09:22:59 +00003301/// \brief Try to find a partition of the aggregate type passed in for a given
3302/// offset and size.
3303///
3304/// This recurses through the aggregate type and tries to compute a subtype
3305/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth6b547a22012-09-14 11:08:31 +00003306/// of an array, it will even compute a new array type for that sub-section,
3307/// and the same for structs.
3308///
3309/// Note that this routine is very strict and tries to find a partition of the
3310/// type which produces the *exact* right offset and size. It is not forgiving
3311/// when the size or offset cause either end of type-based partition to be off.
3312/// Also, this is a best-effort routine. It is reasonable to give up and not
3313/// return a type if necessary.
Micah Villmow3574eca2012-10-08 16:38:25 +00003314static Type *getTypePartition(const DataLayout &TD, Type *Ty,
Chandler Carruth713aa942012-09-14 09:22:59 +00003315 uint64_t Offset, uint64_t Size) {
3316 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
Chandler Carruth07525a62012-10-13 10:49:33 +00003317 return stripAggregateTypeWrapping(TD, Ty);
Chandler Carrutha2b88162012-10-25 04:37:07 +00003318 if (Offset > TD.getTypeAllocSize(Ty) ||
3319 (TD.getTypeAllocSize(Ty) - Offset) < Size)
3320 return 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00003321
3322 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3323 // We can't partition pointers...
3324 if (SeqTy->isPointerTy())
3325 return 0;
3326
3327 Type *ElementTy = SeqTy->getElementType();
3328 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3329 uint64_t NumSkippedElements = Offset / ElementSize;
3330 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
3331 if (NumSkippedElements >= ArrTy->getNumElements())
3332 return 0;
3333 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
3334 if (NumSkippedElements >= VecTy->getNumElements())
3335 return 0;
3336 Offset -= NumSkippedElements * ElementSize;
3337
3338 // First check if we need to recurse.
3339 if (Offset > 0 || Size < ElementSize) {
3340 // Bail if the partition ends in a different array element.
3341 if ((Offset + Size) > ElementSize)
3342 return 0;
3343 // Recurse through the element type trying to peel off offset bytes.
3344 return getTypePartition(TD, ElementTy, Offset, Size);
3345 }
3346 assert(Offset == 0);
3347
3348 if (Size == ElementSize)
Chandler Carruth07525a62012-10-13 10:49:33 +00003349 return stripAggregateTypeWrapping(TD, ElementTy);
Chandler Carruth713aa942012-09-14 09:22:59 +00003350 assert(Size > ElementSize);
3351 uint64_t NumElements = Size / ElementSize;
3352 if (NumElements * ElementSize != Size)
3353 return 0;
3354 return ArrayType::get(ElementTy, NumElements);
3355 }
3356
3357 StructType *STy = dyn_cast<StructType>(Ty);
3358 if (!STy)
3359 return 0;
3360
3361 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00003362 if (Offset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00003363 return 0;
3364 uint64_t EndOffset = Offset + Size;
3365 if (EndOffset > SL->getSizeInBytes())
3366 return 0;
3367
3368 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +00003369 Offset -= SL->getElementOffset(Index);
3370
3371 Type *ElementTy = STy->getElementType(Index);
3372 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3373 if (Offset >= ElementSize)
3374 return 0; // The offset points into alignment padding.
3375
3376 // See if any partition must be contained by the element.
3377 if (Offset > 0 || Size < ElementSize) {
3378 if ((Offset + Size) > ElementSize)
3379 return 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00003380 return getTypePartition(TD, ElementTy, Offset, Size);
3381 }
3382 assert(Offset == 0);
3383
3384 if (Size == ElementSize)
Chandler Carruth07525a62012-10-13 10:49:33 +00003385 return stripAggregateTypeWrapping(TD, ElementTy);
Chandler Carruth713aa942012-09-14 09:22:59 +00003386
3387 StructType::element_iterator EI = STy->element_begin() + Index,
3388 EE = STy->element_end();
3389 if (EndOffset < SL->getSizeInBytes()) {
3390 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3391 if (Index == EndIndex)
3392 return 0; // Within a single element and its padding.
Chandler Carruth6b547a22012-09-14 11:08:31 +00003393
3394 // Don't try to form "natural" types if the elements don't line up with the
3395 // expected size.
3396 // FIXME: We could potentially recurse down through the last element in the
3397 // sub-struct to find a natural end point.
3398 if (SL->getElementOffset(EndIndex) != EndOffset)
3399 return 0;
3400
Chandler Carruth713aa942012-09-14 09:22:59 +00003401 assert(Index < EndIndex);
Chandler Carruth713aa942012-09-14 09:22:59 +00003402 EE = STy->element_begin() + EndIndex;
3403 }
3404
3405 // Try to build up a sub-structure.
Benjamin Kramer2a132422012-10-20 12:04:57 +00003406 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth713aa942012-09-14 09:22:59 +00003407 STy->isPacked());
3408 const StructLayout *SubSL = TD.getStructLayout(SubTy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00003409 if (Size != SubSL->getSizeInBytes())
3410 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth713aa942012-09-14 09:22:59 +00003411
Chandler Carruth6b547a22012-09-14 11:08:31 +00003412 return SubTy;
Chandler Carruth713aa942012-09-14 09:22:59 +00003413}
3414
3415/// \brief Rewrite an alloca partition's users.
3416///
3417/// This routine drives both of the rewriting goals of the SROA pass. It tries
3418/// to rewrite uses of an alloca partition to be conducive for SSA value
3419/// promotion. If the partition needs a new, more refined alloca, this will
3420/// build that new alloca, preserving as much type information as possible, and
3421/// rewrite the uses of the old alloca to point at the new one and have the
3422/// appropriate new offsets. It also evaluates how successful the rewrite was
3423/// at enabling promotion and if it was successful queues the alloca to be
3424/// promoted.
3425bool SROA::rewriteAllocaPartition(AllocaInst &AI,
3426 AllocaPartitioning &P,
3427 AllocaPartitioning::iterator PI) {
3428 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
Chandler Carruthfdb15852012-10-02 18:57:13 +00003429 bool IsLive = false;
3430 for (AllocaPartitioning::use_iterator UI = P.use_begin(PI),
3431 UE = P.use_end(PI);
3432 UI != UE && !IsLive; ++UI)
3433 if (UI->U)
3434 IsLive = true;
3435 if (!IsLive)
Chandler Carruth713aa942012-09-14 09:22:59 +00003436 return false; // No live uses left of this partition.
3437
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003438 DEBUG(dbgs() << "Speculating PHIs and selects in partition "
3439 << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
3440
3441 PHIOrSelectSpeculator Speculator(*TD, P, *this);
3442 DEBUG(dbgs() << " speculating ");
3443 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carrutha346f462012-10-02 17:49:47 +00003444 Speculator.visitUsers(PI);
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003445
Chandler Carruth713aa942012-09-14 09:22:59 +00003446 // Try to compute a friendly type for this partition of the alloca. This
3447 // won't always succeed, in which case we fall back to a legal integer type
3448 // or an i8 array of an appropriate size.
3449 Type *AllocaTy = 0;
3450 if (Type *PartitionTy = P.getCommonType(PI))
3451 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
3452 AllocaTy = PartitionTy;
3453 if (!AllocaTy)
3454 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3455 PI->BeginOffset, AllocaSize))
3456 AllocaTy = PartitionTy;
3457 if ((!AllocaTy ||
3458 (AllocaTy->isArrayTy() &&
3459 AllocaTy->getArrayElementType()->isIntegerTy())) &&
3460 TD->isLegalInteger(AllocaSize * 8))
3461 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
3462 if (!AllocaTy)
3463 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
Chandler Carruthb3dd9a12012-09-14 10:26:34 +00003464 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00003465
3466 // Check for the case where we're going to rewrite to a new alloca of the
3467 // exact same type as the original, and with the same access offsets. In that
3468 // case, re-use the existing alloca, but still run through the rewriter to
3469 // performe phi and select speculation.
3470 AllocaInst *NewAI;
3471 if (AllocaTy == AI.getAllocatedType()) {
3472 assert(PI->BeginOffset == 0 &&
3473 "Non-zero begin offset but same alloca type");
3474 assert(PI == P.begin() && "Begin offset is zero on later partition");
3475 NewAI = &AI;
3476 } else {
Chandler Carruthb67c9a52012-09-29 10:41:21 +00003477 unsigned Alignment = AI.getAlignment();
3478 if (!Alignment) {
3479 // The minimum alignment which users can rely on when the explicit
3480 // alignment is omitted or zero is that required by the ABI for this
3481 // type.
3482 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3483 }
3484 Alignment = MinAlign(Alignment, PI->BeginOffset);
3485 // If we will get at least this much alignment from the type alone, leave
3486 // the alloca's alignment unconstrained.
3487 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3488 Alignment = 0;
3489 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
Chandler Carruth713aa942012-09-14 09:22:59 +00003490 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3491 &AI);
3492 ++NumNewAllocas;
3493 }
3494
3495 DEBUG(dbgs() << "Rewriting alloca partition "
3496 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3497 << *NewAI << "\n");
3498
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003499 // Track the high watermark of the post-promotion worklist. We will reset it
3500 // to this point if the alloca is not in fact scheduled for promotion.
3501 unsigned PPWOldSize = PostPromotionWorklist.size();
3502
Chandler Carruth713aa942012-09-14 09:22:59 +00003503 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3504 PI->BeginOffset, PI->EndOffset);
3505 DEBUG(dbgs() << " rewriting ");
3506 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003507 bool Promotable = Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI));
3508 if (Promotable) {
Chandler Carruth713aa942012-09-14 09:22:59 +00003509 DEBUG(dbgs() << " and queuing for promotion\n");
3510 PromotableAllocas.push_back(NewAI);
3511 } else if (NewAI != &AI) {
3512 // If we can't promote the alloca, iterate on it to check for new
3513 // refinements exposed by splitting the current alloca. Don't iterate on an
3514 // alloca which didn't actually change and didn't get promoted.
3515 Worklist.insert(NewAI);
3516 }
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003517
3518 // Drop any post-promotion work items if promotion didn't happen.
3519 if (!Promotable)
3520 while (PostPromotionWorklist.size() > PPWOldSize)
3521 PostPromotionWorklist.pop_back();
3522
Chandler Carruth713aa942012-09-14 09:22:59 +00003523 return true;
3524}
3525
3526/// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3527bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3528 bool Changed = false;
3529 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3530 ++PI)
3531 Changed |= rewriteAllocaPartition(AI, P, PI);
3532
3533 return Changed;
3534}
3535
3536/// \brief Analyze an alloca for SROA.
3537///
3538/// This analyzes the alloca to ensure we can reason about it, builds
3539/// a partitioning of the alloca, and then hands it off to be split and
3540/// rewritten as needed.
3541bool SROA::runOnAlloca(AllocaInst &AI) {
3542 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3543 ++NumAllocasAnalyzed;
3544
3545 // Special case dead allocas, as they're trivial.
3546 if (AI.use_empty()) {
3547 AI.eraseFromParent();
3548 return true;
3549 }
3550
3551 // Skip alloca forms that this analysis can't handle.
3552 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3553 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3554 return false;
3555
Chandler Carruthc370acd2012-09-18 12:57:43 +00003556 bool Changed = false;
3557
3558 // First, split any FCA loads and stores touching this alloca to promote
3559 // better splitting and promotion opportunities.
3560 AggLoadStoreRewriter AggRewriter(*TD);
3561 Changed |= AggRewriter.rewrite(AI);
3562
Chandler Carruth713aa942012-09-14 09:22:59 +00003563 // Build the partition set using a recursive instruction-visiting builder.
3564 AllocaPartitioning P(*TD, AI);
3565 DEBUG(P.print(dbgs()));
3566 if (P.isEscaped())
Chandler Carruthc370acd2012-09-18 12:57:43 +00003567 return Changed;
Chandler Carruth713aa942012-09-14 09:22:59 +00003568
Chandler Carruth713aa942012-09-14 09:22:59 +00003569 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth713aa942012-09-14 09:22:59 +00003570 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3571 DE = P.dead_user_end();
3572 DI != DE; ++DI) {
3573 Changed = true;
3574 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
Chandler Carruthf5837aa2012-11-20 01:12:50 +00003575 DeadInsts.insert(*DI);
Chandler Carruth713aa942012-09-14 09:22:59 +00003576 }
3577 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3578 DE = P.dead_op_end();
3579 DO != DE; ++DO) {
3580 Value *OldV = **DO;
3581 // Clobber the use with an undef value.
3582 **DO = UndefValue::get(OldV->getType());
3583 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3584 if (isInstructionTriviallyDead(OldI)) {
3585 Changed = true;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00003586 DeadInsts.insert(OldI);
Chandler Carruth713aa942012-09-14 09:22:59 +00003587 }
3588 }
3589
Chandler Carruthfca3f402012-10-05 01:29:09 +00003590 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3591 if (P.begin() == P.end())
3592 return Changed;
3593
Chandler Carruth713aa942012-09-14 09:22:59 +00003594 return splitAlloca(AI, P) || Changed;
3595}
3596
Chandler Carruth8615cd22012-09-14 10:26:38 +00003597/// \brief Delete the dead instructions accumulated in this run.
3598///
3599/// Recursively deletes the dead instructions we've accumulated. This is done
3600/// at the very end to maximize locality of the recursive delete and to
3601/// minimize the problems of invalidated instruction pointers as such pointers
3602/// are used heavily in the intermediate stages of the algorithm.
3603///
3604/// We also record the alloca instructions deleted here so that they aren't
3605/// subsequently handed to mem2reg to promote.
3606void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth713aa942012-09-14 09:22:59 +00003607 while (!DeadInsts.empty()) {
3608 Instruction *I = DeadInsts.pop_back_val();
3609 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3610
Chandler Carrutha2b88162012-10-25 04:37:07 +00003611 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3612
Chandler Carruth713aa942012-09-14 09:22:59 +00003613 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3614 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3615 // Zero out the operand and see if it becomes trivially dead.
3616 *OI = 0;
3617 if (isInstructionTriviallyDead(U))
Chandler Carruthf5837aa2012-11-20 01:12:50 +00003618 DeadInsts.insert(U);
Chandler Carruth713aa942012-09-14 09:22:59 +00003619 }
3620
3621 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3622 DeletedAllocas.insert(AI);
3623
3624 ++NumDeleted;
3625 I->eraseFromParent();
3626 }
3627}
3628
Chandler Carruth1c8db502012-09-15 11:43:14 +00003629/// \brief Promote the allocas, using the best available technique.
3630///
3631/// This attempts to promote whatever allocas have been identified as viable in
3632/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3633/// If there is a domtree available, we attempt to promote using the full power
3634/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3635/// based on the SSAUpdater utilities. This function returns whether any
3636/// promotion occured.
3637bool SROA::promoteAllocas(Function &F) {
3638 if (PromotableAllocas.empty())
3639 return false;
3640
3641 NumPromoted += PromotableAllocas.size();
3642
3643 if (DT && !ForceSSAUpdater) {
3644 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3645 PromoteMemToReg(PromotableAllocas, *DT);
3646 PromotableAllocas.clear();
3647 return true;
3648 }
3649
3650 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3651 SSAUpdater SSA;
3652 DIBuilder DIB(*F.getParent());
3653 SmallVector<Instruction*, 64> Insts;
3654
3655 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3656 AllocaInst *AI = PromotableAllocas[Idx];
3657 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3658 UI != UE;) {
3659 Instruction *I = cast<Instruction>(*UI++);
3660 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3661 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3662 // leading to them) here. Eventually it should use them to optimize the
3663 // scalar values produced.
3664 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3665 assert(onlyUsedByLifetimeMarkers(I) &&
3666 "Found a bitcast used outside of a lifetime marker.");
3667 while (!I->use_empty())
3668 cast<Instruction>(*I->use_begin())->eraseFromParent();
3669 I->eraseFromParent();
3670 continue;
3671 }
3672 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3673 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3674 II->getIntrinsicID() == Intrinsic::lifetime_end);
3675 II->eraseFromParent();
3676 continue;
3677 }
3678
3679 Insts.push_back(I);
3680 }
3681 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3682 Insts.clear();
3683 }
3684
3685 PromotableAllocas.clear();
3686 return true;
3687}
3688
Chandler Carruth713aa942012-09-14 09:22:59 +00003689namespace {
3690 /// \brief A predicate to test whether an alloca belongs to a set.
3691 class IsAllocaInSet {
3692 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3693 const SetType &Set;
3694
3695 public:
Chandler Carruth75eac5f2012-10-03 00:03:00 +00003696 typedef AllocaInst *argument_type;
3697
Chandler Carruth713aa942012-09-14 09:22:59 +00003698 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth75eac5f2012-10-03 00:03:00 +00003699 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth713aa942012-09-14 09:22:59 +00003700 };
3701}
3702
3703bool SROA::runOnFunction(Function &F) {
3704 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3705 C = &F.getContext();
Micah Villmow3574eca2012-10-08 16:38:25 +00003706 TD = getAnalysisIfAvailable<DataLayout>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003707 if (!TD) {
3708 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3709 return false;
3710 }
Chandler Carruth1c8db502012-09-15 11:43:14 +00003711 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003712
3713 BasicBlock &EntryBB = F.getEntryBlock();
3714 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3715 I != E; ++I)
3716 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3717 Worklist.insert(AI);
3718
3719 bool Changed = false;
Chandler Carruth8615cd22012-09-14 10:26:38 +00003720 // A set of deleted alloca instruction pointers which should be removed from
3721 // the list of promotable allocas.
3722 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3723
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003724 do {
3725 while (!Worklist.empty()) {
3726 Changed |= runOnAlloca(*Worklist.pop_back_val());
3727 deleteDeadInstructions(DeletedAllocas);
Chandler Carruth5c5b3cf2012-10-02 22:46:45 +00003728
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003729 // Remove the deleted allocas from various lists so that we don't try to
3730 // continue processing them.
3731 if (!DeletedAllocas.empty()) {
3732 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3733 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3734 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3735 PromotableAllocas.end(),
3736 IsAllocaInSet(DeletedAllocas)),
3737 PromotableAllocas.end());
3738 DeletedAllocas.clear();
3739 }
Chandler Carruth713aa942012-09-14 09:22:59 +00003740 }
Chandler Carruth713aa942012-09-14 09:22:59 +00003741
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003742 Changed |= promoteAllocas(F);
3743
3744 Worklist = PostPromotionWorklist;
3745 PostPromotionWorklist.clear();
3746 } while (!Worklist.empty());
Chandler Carruth713aa942012-09-14 09:22:59 +00003747
3748 return Changed;
3749}
3750
3751void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth1c8db502012-09-15 11:43:14 +00003752 if (RequiresDomTree)
3753 AU.addRequired<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003754 AU.setPreservesCFG();
3755}