blob: 420417187fadf764ae971a648ff680b818f90d2a [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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000028#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SetVector.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/Analysis/Dominators.h"
33#include "llvm/Analysis/Loads.h"
Chandler Carruthed90ed02012-12-10 08:28:39 +000034#include "llvm/Analysis/PtrUseVisitor.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000035#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000036#include "llvm/DIBuilder.h"
37#include "llvm/DebugInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000038#include "llvm/IR/Constants.h"
39#include "llvm/IR/DataLayout.h"
40#include "llvm/IR/DerivedTypes.h"
41#include "llvm/IR/Function.h"
42#include "llvm/IR/IRBuilder.h"
43#include "llvm/IR/Instructions.h"
44#include "llvm/IR/IntrinsicInst.h"
45#include "llvm/IR/LLVMContext.h"
46#include "llvm/IR/Module.h"
47#include "llvm/IR/Operator.h"
Chandler Carruth84bcf932012-11-30 03:08:41 +000048#include "llvm/InstVisitor.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000049#include "llvm/Pass.h"
Chandler Carruth1c8db502012-09-15 11:43:14 +000050#include "llvm/Support/CommandLine.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000051#include "llvm/Support/Debug.h"
52#include "llvm/Support/ErrorHandling.h"
53#include "llvm/Support/GetElementPtrTypeIterator.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000054#include "llvm/Support/MathExtras.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000055#include "llvm/Support/raw_ostream.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000056#include "llvm/Transforms/Utils/Local.h"
57#include "llvm/Transforms/Utils/PromoteMemToReg.h"
58#include "llvm/Transforms/Utils/SSAUpdater.h"
59using namespace llvm;
60
61STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
62STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
63STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
64STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
65STATISTIC(NumDeleted, "Number of instructions deleted");
66STATISTIC(NumVectorized, "Number of vectorized aggregates");
67
Chandler Carruth1c8db502012-09-15 11:43:14 +000068/// Hidden option to force the pass to not use DomTree and mem2reg, instead
69/// forming SSA values through the SSAUpdater infrastructure.
70static cl::opt<bool>
71ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
72
Chandler Carruth713aa942012-09-14 09:22:59 +000073namespace {
74/// \brief Alloca partitioning representation.
75///
76/// This class represents a partitioning of an alloca into slices, and
77/// information about the nature of uses of each slice of the alloca. The goal
78/// is that this information is sufficient to decide if and how to split the
79/// alloca apart and replace slices with scalars. It is also intended that this
Chandler Carruth7f5bede2012-09-14 10:18:49 +000080/// structure can capture the relevant information needed both to decide about
Chandler Carruth713aa942012-09-14 09:22:59 +000081/// and to enact these transformations.
82class AllocaPartitioning {
83public:
84 /// \brief A common base class for representing a half-open byte range.
85 struct ByteRange {
86 /// \brief The beginning offset of the range.
87 uint64_t BeginOffset;
88
89 /// \brief The ending offset, not included in the range.
90 uint64_t EndOffset;
91
92 ByteRange() : BeginOffset(), EndOffset() {}
93 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
94 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
95
96 /// \brief Support for ordering ranges.
97 ///
98 /// This provides an ordering over ranges such that start offsets are
99 /// always increasing, and within equal start offsets, the end offsets are
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000100 /// decreasing. Thus the spanning range comes first in a cluster with the
Chandler Carruth713aa942012-09-14 09:22:59 +0000101 /// same start position.
102 bool operator<(const ByteRange &RHS) const {
103 if (BeginOffset < RHS.BeginOffset) return true;
104 if (BeginOffset > RHS.BeginOffset) return false;
105 if (EndOffset > RHS.EndOffset) return true;
106 return false;
107 }
108
109 /// \brief Support comparison with a single offset to allow binary searches.
Benjamin Kramer2d1c2a22012-09-17 16:42:36 +0000110 friend bool operator<(const ByteRange &LHS, uint64_t RHSOffset) {
111 return LHS.BeginOffset < RHSOffset;
112 }
113
114 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
115 const ByteRange &RHS) {
116 return LHSOffset < RHS.BeginOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000117 }
118
119 bool operator==(const ByteRange &RHS) const {
120 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
121 }
122 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
123 };
124
125 /// \brief A partition of an alloca.
126 ///
127 /// This structure represents a contiguous partition of the alloca. These are
128 /// formed by examining the uses of the alloca. During formation, they may
129 /// overlap but once an AllocaPartitioning is built, the Partitions within it
130 /// are all disjoint.
131 struct Partition : public ByteRange {
132 /// \brief Whether this partition is splittable into smaller partitions.
133 ///
134 /// We flag partitions as splittable when they are formed entirely due to
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000135 /// accesses by trivially splittable operations such as memset and memcpy.
Chandler Carruth713aa942012-09-14 09:22:59 +0000136 bool IsSplittable;
137
Chandler Carruthfca3f402012-10-05 01:29:09 +0000138 /// \brief Test whether a partition has been marked as dead.
139 bool isDead() const {
140 if (BeginOffset == UINT64_MAX) {
141 assert(EndOffset == UINT64_MAX);
142 return true;
143 }
144 return false;
145 }
146
147 /// \brief Kill a partition.
148 /// This is accomplished by setting both its beginning and end offset to
149 /// the maximum possible value.
150 void kill() {
151 assert(!isDead() && "He's Dead, Jim!");
152 BeginOffset = EndOffset = UINT64_MAX;
153 }
154
Chandler Carruth713aa942012-09-14 09:22:59 +0000155 Partition() : ByteRange(), IsSplittable() {}
156 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
157 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
158 };
159
160 /// \brief A particular use of a partition of the alloca.
161 ///
162 /// This structure is used to associate uses of a partition with it. They
163 /// mark the range of bytes which are referenced by a particular instruction,
164 /// and includes a handle to the user itself and the pointer value in use.
165 /// The bounds of these uses are determined by intersecting the bounds of the
166 /// memory use itself with a particular partition. As a consequence there is
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000167 /// intentionally overlap between various uses of the same partition.
Chandler Carruth713aa942012-09-14 09:22:59 +0000168 struct PartitionUse : public ByteRange {
Chandler Carruth77c12702012-10-01 01:49:22 +0000169 /// \brief The use in question. Provides access to both user and used value.
Chandler Carruthfdb15852012-10-02 18:57:13 +0000170 ///
171 /// Note that this may be null if the partition use is *dead*, that is, it
172 /// should be ignored.
173 Use *U;
Chandler Carruth713aa942012-09-14 09:22:59 +0000174
Chandler Carruth77c12702012-10-01 01:49:22 +0000175 PartitionUse() : ByteRange(), U() {}
176 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset, Use *U)
177 : ByteRange(BeginOffset, EndOffset), U(U) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000178 };
179
180 /// \brief Construct a partitioning of a particular alloca.
181 ///
182 /// Construction does most of the work for partitioning the alloca. This
183 /// performs the necessary walks of users and builds a partitioning from it.
Micah Villmow3574eca2012-10-08 16:38:25 +0000184 AllocaPartitioning(const DataLayout &TD, AllocaInst &AI);
Chandler Carruth713aa942012-09-14 09:22:59 +0000185
186 /// \brief Test whether a pointer to the allocation escapes our analysis.
187 ///
188 /// If this is true, the partitioning is never fully built and should be
189 /// ignored.
190 bool isEscaped() const { return PointerEscapingInstr; }
191
192 /// \brief Support for iterating over the partitions.
193 /// @{
194 typedef SmallVectorImpl<Partition>::iterator iterator;
195 iterator begin() { return Partitions.begin(); }
196 iterator end() { return Partitions.end(); }
197
198 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
199 const_iterator begin() const { return Partitions.begin(); }
200 const_iterator end() const { return Partitions.end(); }
201 /// @}
202
203 /// \brief Support for iterating over and manipulating a particular
204 /// partition's uses.
205 ///
206 /// The iteration support provided for uses is more limited, but also
207 /// includes some manipulation routines to support rewriting the uses of
208 /// partitions during SROA.
209 /// @{
210 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
211 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
212 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
213 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
214 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
Chandler Carruth713aa942012-09-14 09:22:59 +0000215
216 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
217 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
218 const_use_iterator use_begin(const_iterator I) const {
219 return Uses[I - begin()].begin();
220 }
221 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
222 const_use_iterator use_end(const_iterator I) const {
223 return Uses[I - begin()].end();
224 }
Chandler Carrutha346f462012-10-02 17:49:47 +0000225
226 unsigned use_size(unsigned Idx) const { return Uses[Idx].size(); }
227 unsigned use_size(const_iterator I) const { return Uses[I - begin()].size(); }
228 const PartitionUse &getUse(unsigned PIdx, unsigned UIdx) const {
229 return Uses[PIdx][UIdx];
230 }
231 const PartitionUse &getUse(const_iterator I, unsigned UIdx) const {
232 return Uses[I - begin()][UIdx];
233 }
234
235 void use_push_back(unsigned Idx, const PartitionUse &PU) {
236 Uses[Idx].push_back(PU);
237 }
238 void use_push_back(const_iterator I, const PartitionUse &PU) {
239 Uses[I - begin()].push_back(PU);
240 }
Chandler Carruth713aa942012-09-14 09:22:59 +0000241 /// @}
242
243 /// \brief Allow iterating the dead users for this alloca.
244 ///
245 /// These are instructions which will never actually use the alloca as they
246 /// are outside the allocated range. They are safe to replace with undef and
247 /// delete.
248 /// @{
249 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
250 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
251 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
252 /// @}
253
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000254 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth713aa942012-09-14 09:22:59 +0000255 ///
256 /// These are operands which have cannot actually be used to refer to the
257 /// alloca as they are outside its range and the user doesn't correct for
258 /// that. These mostly consist of PHI node inputs and the like which we just
259 /// need to replace with undef.
260 /// @{
261 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
262 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
263 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
264 /// @}
265
266 /// \brief MemTransferInst auxiliary data.
267 /// This struct provides some auxiliary data about memory transfer
268 /// intrinsics such as memcpy and memmove. These intrinsics can use two
269 /// different ranges within the same alloca, and provide other challenges to
270 /// correctly represent. We stash extra data to help us untangle this
271 /// after the partitioning is complete.
272 struct MemTransferOffsets {
Chandler Carruthfca3f402012-10-05 01:29:09 +0000273 /// The destination begin and end offsets when the destination is within
274 /// this alloca. If the end offset is zero the destination is not within
275 /// this alloca.
Chandler Carruth713aa942012-09-14 09:22:59 +0000276 uint64_t DestBegin, DestEnd;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000277
278 /// The source begin and end offsets when the source is within this alloca.
279 /// If the end offset is zero, the source is not within this alloca.
Chandler Carruth713aa942012-09-14 09:22:59 +0000280 uint64_t SourceBegin, SourceEnd;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000281
282 /// Flag for whether an alloca is splittable.
Chandler Carruth713aa942012-09-14 09:22:59 +0000283 bool IsSplittable;
284 };
285 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
286 return MemTransferInstData.lookup(&II);
287 }
288
289 /// \brief Map from a PHI or select operand back to a partition.
290 ///
291 /// When manipulating PHI nodes or selects, they can use more than one
292 /// partition of an alloca. We store a special mapping to allow finding the
293 /// partition referenced by each of these operands, if any.
Chandler Carruth77c12702012-10-01 01:49:22 +0000294 iterator findPartitionForPHIOrSelectOperand(Use *U) {
295 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
296 = PHIOrSelectOpMap.find(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000297 if (MapIt == PHIOrSelectOpMap.end())
298 return end();
299
300 return begin() + MapIt->second.first;
301 }
302
303 /// \brief Map from a PHI or select operand back to the specific use of
304 /// a partition.
305 ///
306 /// Similar to mapping these operands back to the partitions, this maps
307 /// directly to the use structure of that partition.
Chandler Carruth77c12702012-10-01 01:49:22 +0000308 use_iterator findPartitionUseForPHIOrSelectOperand(Use *U) {
309 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
310 = PHIOrSelectOpMap.find(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000311 assert(MapIt != PHIOrSelectOpMap.end());
312 return Uses[MapIt->second.first].begin() + MapIt->second.second;
313 }
314
315 /// \brief Compute a common type among the uses of a particular partition.
316 ///
317 /// This routines walks all of the uses of a particular partition and tries
318 /// to find a common type between them. Untyped operations such as memset and
319 /// memcpy are ignored.
320 Type *getCommonType(iterator I) const;
321
Chandler Carruthba13d2e2012-09-14 10:18:51 +0000322#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth713aa942012-09-14 09:22:59 +0000323 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
324 void printUsers(raw_ostream &OS, const_iterator I,
325 StringRef Indent = " ") const;
326 void print(raw_ostream &OS) const;
NAKAMURA Takumiad9f5b82012-09-14 10:06:10 +0000327 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
328 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
Chandler Carruthba13d2e2012-09-14 10:18:51 +0000329#endif
Chandler Carruth713aa942012-09-14 09:22:59 +0000330
331private:
332 template <typename DerivedT, typename RetT = void> class BuilderBase;
333 class PartitionBuilder;
334 friend class AllocaPartitioning::PartitionBuilder;
335 class UseBuilder;
336 friend class AllocaPartitioning::UseBuilder;
337
Chandler Carruth3a902d02012-11-20 10:23:07 +0000338#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth713aa942012-09-14 09:22:59 +0000339 /// \brief Handle to alloca instruction to simplify method interfaces.
340 AllocaInst &AI;
Benjamin Kramerd0807692012-09-14 13:08:09 +0000341#endif
Chandler Carruth713aa942012-09-14 09:22:59 +0000342
343 /// \brief The instruction responsible for this alloca having no partitioning.
344 ///
345 /// When an instruction (potentially) escapes the pointer to the alloca, we
346 /// store a pointer to that here and abort trying to partition the alloca.
347 /// This will be null if the alloca is partitioned successfully.
348 Instruction *PointerEscapingInstr;
349
350 /// \brief The partitions of the alloca.
351 ///
352 /// We store a vector of the partitions over the alloca here. This vector is
353 /// sorted by increasing begin offset, and then by decreasing end offset. See
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000354 /// the Partition inner class for more details. Initially (during
355 /// construction) there are overlaps, but we form a disjoint sequence of
356 /// partitions while finishing construction and a fully constructed object is
357 /// expected to always have this as a disjoint space.
Chandler Carruth713aa942012-09-14 09:22:59 +0000358 SmallVector<Partition, 8> Partitions;
359
360 /// \brief The uses of the partitions.
361 ///
362 /// This is essentially a mapping from each partition to a list of uses of
363 /// that partition. The mapping is done with a Uses vector that has the exact
364 /// same number of entries as the partition vector. Each entry is itself
365 /// a vector of the uses.
366 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
367
368 /// \brief Instructions which will become dead if we rewrite the alloca.
369 ///
370 /// Note that these are not separated by partition. This is because we expect
371 /// a partitioned alloca to be completely rewritten or not rewritten at all.
372 /// If rewritten, all these instructions can simply be removed and replaced
373 /// with undef as they come from outside of the allocated space.
374 SmallVector<Instruction *, 8> DeadUsers;
375
376 /// \brief Operands which will become dead if we rewrite the alloca.
377 ///
378 /// These are operands that in their particular use can be replaced with
379 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
380 /// to PHI nodes and the like. They aren't entirely dead (there might be
381 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
382 /// want to swap this particular input for undef to simplify the use lists of
383 /// the alloca.
384 SmallVector<Use *, 8> DeadOperands;
385
386 /// \brief The underlying storage for auxiliary memcpy and memset info.
387 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
388
389 /// \brief A side datastructure used when building up the partitions and uses.
390 ///
391 /// This mapping is only really used during the initial building of the
392 /// partitioning so that we can retain information about PHI and select nodes
393 /// processed.
394 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
395
396 /// \brief Auxiliary information for particular PHI or select operands.
Chandler Carruth77c12702012-10-01 01:49:22 +0000397 SmallDenseMap<Use *, std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
Chandler Carruth713aa942012-09-14 09:22:59 +0000398
399 /// \brief A utility routine called from the constructor.
400 ///
401 /// This does what it says on the tin. It is the key of the alloca partition
402 /// splitting and merging. After it is called we have the desired disjoint
403 /// collection of partitions.
404 void splitAndMergePartitions();
405};
406}
407
Chandler Carruthed90ed02012-12-10 08:28:39 +0000408static Value *foldSelectInst(SelectInst &SI) {
409 // If the condition being selected on is a constant or the same value is
410 // being selected between, fold the select. Yes this does (rarely) happen
411 // early on.
412 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
413 return SI.getOperand(1+CI->isZero());
414 if (SI.getOperand(1) == SI.getOperand(2)) {
415 return SI.getOperand(1);
Chandler Carruth713aa942012-09-14 09:22:59 +0000416 }
Chandler Carruthed90ed02012-12-10 08:28:39 +0000417 return 0;
418}
Chandler Carruth713aa942012-09-14 09:22:59 +0000419
420/// \brief Builder for the alloca partitioning.
421///
422/// This class builds an alloca partitioning by recursively visiting the uses
423/// of an alloca and splitting the partitions for each load and store at each
424/// offset.
425class AllocaPartitioning::PartitionBuilder
Chandler Carruthed90ed02012-12-10 08:28:39 +0000426 : public PtrUseVisitor<PartitionBuilder> {
427 friend class PtrUseVisitor<PartitionBuilder>;
428 friend class InstVisitor<PartitionBuilder>;
429 typedef PtrUseVisitor<PartitionBuilder> Base;
430
431 const uint64_t AllocSize;
432 AllocaPartitioning &P;
Chandler Carruth713aa942012-09-14 09:22:59 +0000433
434 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
435
436public:
Chandler Carruthed90ed02012-12-10 08:28:39 +0000437 PartitionBuilder(const DataLayout &DL, AllocaInst &AI, AllocaPartitioning &P)
438 : PtrUseVisitor<PartitionBuilder>(DL),
439 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())),
440 P(P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000441
442private:
Chandler Carruthed90ed02012-12-10 08:28:39 +0000443 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth63392ea2012-09-16 19:39:50 +0000444 bool IsSplittable = false) {
Chandler Carruthe74a4a72012-12-03 10:59:55 +0000445 // Completely skip uses which have a zero size or start either before or
446 // past the end of the allocation.
Chandler Carruthed90ed02012-12-10 08:28:39 +0000447 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize)) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000448 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthe74a4a72012-12-03 10:59:55 +0000449 << " which has zero size or starts outside of the "
450 << AllocSize << " byte alloca:\n"
Chandler Carruth713aa942012-09-14 09:22:59 +0000451 << " alloca: " << P.AI << "\n"
452 << " use: " << I << "\n");
453 return;
454 }
455
Chandler Carruthed90ed02012-12-10 08:28:39 +0000456 uint64_t BeginOffset = Offset.getZExtValue();
457 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruth02e92a02012-09-23 11:43:14 +0000458
459 // Clamp the end offset to the end of the allocation. Note that this is
460 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carruth17679292012-11-20 10:02:19 +0000461 // NOTE! This may appear superficially to be something we could ignore
462 // entirely, but that is not so! There may be PHI-node uses where some
463 // instructions are dead but not others. We can't completely ignore the
464 // PHI node, and so have to record at least the information here.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000465 assert(AllocSize >= BeginOffset); // Established above.
466 if (Size > AllocSize - BeginOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000467 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
468 << " to remain within the " << AllocSize << " byte alloca:\n"
469 << " alloca: " << P.AI << "\n"
470 << " use: " << I << "\n");
471 EndOffset = AllocSize;
472 }
473
Chandler Carruth713aa942012-09-14 09:22:59 +0000474 Partition New(BeginOffset, EndOffset, IsSplittable);
475 P.Partitions.push_back(New);
476 }
477
Chandler Carruthed90ed02012-12-10 08:28:39 +0000478 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha2b88162012-10-25 04:37:07 +0000479 bool IsVolatile) {
Chandler Carruthed90ed02012-12-10 08:28:39 +0000480 uint64_t Size = DL.getTypeStoreSize(Ty);
Chandler Carruth713aa942012-09-14 09:22:59 +0000481
482 // If this memory access can be shown to *statically* extend outside the
483 // bounds of of the allocation, it's behavior is undefined, so simply
484 // ignore it. Note that this is more strict than the generic clamping
485 // behavior of insertUse. We also try to handle cases which might run the
486 // risk of overflow.
487 // FIXME: We should instead consider the pointer to have escaped if this
488 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruthed90ed02012-12-10 08:28:39 +0000489 if (Offset.isNegative() || Size > AllocSize ||
490 Offset.ugt(AllocSize - Size)) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000491 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
492 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
493 << " which extends past the end of the " << AllocSize
494 << " byte alloca:\n"
495 << " alloca: " << P.AI << "\n"
496 << " use: " << I << "\n");
Chandler Carruthed90ed02012-12-10 08:28:39 +0000497 return;
Chandler Carruth713aa942012-09-14 09:22:59 +0000498 }
499
Chandler Carrutha2b88162012-10-25 04:37:07 +0000500 // We allow splitting of loads and stores where the type is an integer type
501 // and which cover the entire alloca. Such integer loads and stores
502 // often require decomposition into fine grained loads and stores.
503 bool IsSplittable = false;
504 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
505 IsSplittable = !IsVolatile && ITy->getBitWidth() == AllocSize*8;
506
507 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth713aa942012-09-14 09:22:59 +0000508 }
509
Chandler Carruthed90ed02012-12-10 08:28:39 +0000510 void visitLoadInst(LoadInst &LI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000511 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
512 "All simple FCA loads should have been pre-split");
Chandler Carruthed90ed02012-12-10 08:28:39 +0000513
514 if (!IsOffsetKnown)
515 return PI.setAborted(&LI);
516
Chandler Carrutha2b88162012-10-25 04:37:07 +0000517 return handleLoadOrStore(LI.getType(), LI, Offset, LI.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +0000518 }
519
Chandler Carruthed90ed02012-12-10 08:28:39 +0000520 void visitStoreInst(StoreInst &SI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000521 Value *ValOp = SI.getValueOperand();
522 if (ValOp == *U)
Chandler Carruthed90ed02012-12-10 08:28:39 +0000523 return PI.setEscapedAndAborted(&SI);
524 if (!IsOffsetKnown)
525 return PI.setAborted(&SI);
Chandler Carruth713aa942012-09-14 09:22:59 +0000526
Chandler Carruthc370acd2012-09-18 12:57:43 +0000527 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
528 "All simple FCA stores should have been pre-split");
Chandler Carruthed90ed02012-12-10 08:28:39 +0000529 handleLoadOrStore(ValOp->getType(), SI, Offset, SI.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +0000530 }
531
532
Chandler Carruthed90ed02012-12-10 08:28:39 +0000533 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb3dd9a12012-09-14 10:26:34 +0000534 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth713aa942012-09-14 09:22:59 +0000535 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthed90ed02012-12-10 08:28:39 +0000536 if ((Length && Length->getValue() == 0) ||
537 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
538 // Zero-length mem transfer intrinsics can be ignored entirely.
539 return;
540
541 if (!IsOffsetKnown)
542 return PI.setAborted(&II);
543
544 insertUse(II, Offset,
545 Length ? Length->getLimitedValue()
546 : AllocSize - Offset.getLimitedValue(),
547 (bool)Length);
Chandler Carruth713aa942012-09-14 09:22:59 +0000548 }
549
Chandler Carruthed90ed02012-12-10 08:28:39 +0000550 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000551 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthed90ed02012-12-10 08:28:39 +0000552 if ((Length && Length->getValue() == 0) ||
553 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
Chandler Carruth713aa942012-09-14 09:22:59 +0000554 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthed90ed02012-12-10 08:28:39 +0000555 return;
556
557 if (!IsOffsetKnown)
558 return PI.setAborted(&II);
559
560 uint64_t RawOffset = Offset.getLimitedValue();
561 uint64_t Size = Length ? Length->getLimitedValue()
562 : AllocSize - RawOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000563
564 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
565
566 // Only intrinsics with a constant length can be split.
567 Offsets.IsSplittable = Length;
568
Chandler Carruthfca3f402012-10-05 01:29:09 +0000569 if (*U == II.getRawDest()) {
Chandler Carruthed90ed02012-12-10 08:28:39 +0000570 Offsets.DestBegin = RawOffset;
571 Offsets.DestEnd = RawOffset + Size;
Chandler Carruth713aa942012-09-14 09:22:59 +0000572 }
Chandler Carruthfca3f402012-10-05 01:29:09 +0000573 if (*U == II.getRawSource()) {
Chandler Carruthed90ed02012-12-10 08:28:39 +0000574 Offsets.SourceBegin = RawOffset;
575 Offsets.SourceEnd = RawOffset + Size;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000576 }
Chandler Carruth713aa942012-09-14 09:22:59 +0000577
Chandler Carruthfca3f402012-10-05 01:29:09 +0000578 // If we have set up end offsets for both the source and the destination,
579 // we have found both sides of this transfer pointing at the same alloca.
580 bool SeenBothEnds = Offsets.SourceEnd && Offsets.DestEnd;
581 if (SeenBothEnds && II.getRawDest() != II.getRawSource()) {
582 unsigned PrevIdx = MemTransferPartitionMap[&II];
Chandler Carruth713aa942012-09-14 09:22:59 +0000583
Chandler Carruthfca3f402012-10-05 01:29:09 +0000584 // Check if the begin offsets match and this is a non-volatile transfer.
585 // In that case, we can completely elide the transfer.
586 if (!II.isVolatile() && Offsets.SourceBegin == Offsets.DestBegin) {
587 P.Partitions[PrevIdx].kill();
Chandler Carruthed90ed02012-12-10 08:28:39 +0000588 return;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000589 }
590
591 // Otherwise we have an offset transfer within the same alloca. We can't
592 // split those.
593 P.Partitions[PrevIdx].IsSplittable = Offsets.IsSplittable = false;
594 } else if (SeenBothEnds) {
595 // Handle the case where this exact use provides both ends of the
596 // operation.
597 assert(II.getRawDest() == II.getRawSource());
598
599 // For non-volatile transfers this is a no-op.
600 if (!II.isVolatile())
Chandler Carruthed90ed02012-12-10 08:28:39 +0000601 return;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000602
603 // Otherwise just suppress splitting.
Chandler Carruth713aa942012-09-14 09:22:59 +0000604 Offsets.IsSplittable = false;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000605 }
606
607
608 // Insert the use now that we've fixed up the splittable nature.
609 insertUse(II, Offset, Size, Offsets.IsSplittable);
610
611 // Setup the mapping from intrinsic to partition of we've not seen both
612 // ends of this transfer.
613 if (!SeenBothEnds) {
614 unsigned NewIdx = P.Partitions.size() - 1;
615 bool Inserted
616 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx)).second;
617 assert(Inserted &&
618 "Already have intrinsic in map but haven't seen both ends");
NAKAMURA Takumi0559d312012-10-05 13:56:23 +0000619 (void)Inserted;
Chandler Carruth713aa942012-09-14 09:22:59 +0000620 }
Chandler Carruth713aa942012-09-14 09:22:59 +0000621 }
622
623 // Disable SRoA for any intrinsics except for lifetime invariants.
Chandler Carruth50754f02012-09-14 10:26:36 +0000624 // FIXME: What about debug instrinsics? This matches old behavior, but
625 // doesn't make sense.
Chandler Carruthed90ed02012-12-10 08:28:39 +0000626 void visitIntrinsicInst(IntrinsicInst &II) {
627 if (!IsOffsetKnown)
628 return PI.setAborted(&II);
629
Chandler Carruth713aa942012-09-14 09:22:59 +0000630 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
631 II.getIntrinsicID() == Intrinsic::lifetime_end) {
632 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthed90ed02012-12-10 08:28:39 +0000633 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
634 Length->getLimitedValue());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000635 insertUse(II, Offset, Size, true);
Chandler Carruthed90ed02012-12-10 08:28:39 +0000636 return;
Chandler Carruth713aa942012-09-14 09:22:59 +0000637 }
638
Chandler Carruthed90ed02012-12-10 08:28:39 +0000639 Base::visitIntrinsicInst(II);
Chandler Carruth713aa942012-09-14 09:22:59 +0000640 }
641
642 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
643 // We consider any PHI or select that results in a direct load or store of
644 // the same offset to be a viable use for partitioning purposes. These uses
645 // are considered unsplittable and the size is the maximum loaded or stored
646 // size.
647 SmallPtrSet<Instruction *, 4> Visited;
648 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
649 Visited.insert(Root);
650 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruthc3034632012-09-25 10:03:40 +0000651 // If there are no loads or stores, the access is dead. We mark that as
652 // a size zero access.
653 Size = 0;
Chandler Carruth713aa942012-09-14 09:22:59 +0000654 do {
655 Instruction *I, *UsedI;
656 llvm::tie(UsedI, I) = Uses.pop_back_val();
657
658 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthed90ed02012-12-10 08:28:39 +0000659 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth713aa942012-09-14 09:22:59 +0000660 continue;
661 }
662 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
663 Value *Op = SI->getOperand(0);
664 if (Op == UsedI)
665 return SI;
Chandler Carruthed90ed02012-12-10 08:28:39 +0000666 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth713aa942012-09-14 09:22:59 +0000667 continue;
668 }
669
670 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
671 if (!GEP->hasAllZeroIndices())
672 return GEP;
673 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
674 !isa<SelectInst>(I)) {
675 return I;
676 }
677
678 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
679 ++UI)
680 if (Visited.insert(cast<Instruction>(*UI)))
681 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
682 } while (!Uses.empty());
683
684 return 0;
685 }
686
Chandler Carruthed90ed02012-12-10 08:28:39 +0000687 void visitPHINode(PHINode &PN) {
688 if (PN.use_empty())
689 return;
690 if (!IsOffsetKnown)
691 return PI.setAborted(&PN);
692
Chandler Carruth713aa942012-09-14 09:22:59 +0000693 // See if we already have computed info on this node.
694 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
695 if (PHIInfo.first) {
696 PHIInfo.second = true;
Chandler Carruth63392ea2012-09-16 19:39:50 +0000697 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruthed90ed02012-12-10 08:28:39 +0000698 return;
Chandler Carruth713aa942012-09-14 09:22:59 +0000699 }
700
701 // Check for an unsafe use of the PHI node.
Chandler Carruthed90ed02012-12-10 08:28:39 +0000702 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
703 return PI.setAborted(UnsafeI);
Chandler Carruth713aa942012-09-14 09:22:59 +0000704
Chandler Carruth63392ea2012-09-16 19:39:50 +0000705 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000706 }
707
Chandler Carruthed90ed02012-12-10 08:28:39 +0000708 void visitSelectInst(SelectInst &SI) {
709 if (SI.use_empty())
710 return;
Chandler Carruth713aa942012-09-14 09:22:59 +0000711 if (Value *Result = foldSelectInst(SI)) {
712 if (Result == *U)
713 // If the result of the constant fold will be the pointer, recurse
714 // through the select as if we had RAUW'ed it.
Chandler Carruthed90ed02012-12-10 08:28:39 +0000715 enqueueUsers(SI);
Chandler Carruth713aa942012-09-14 09:22:59 +0000716
Chandler Carruthed90ed02012-12-10 08:28:39 +0000717 return;
Chandler Carruth713aa942012-09-14 09:22:59 +0000718 }
Chandler Carruthed90ed02012-12-10 08:28:39 +0000719 if (!IsOffsetKnown)
720 return PI.setAborted(&SI);
Chandler Carruth713aa942012-09-14 09:22:59 +0000721
722 // See if we already have computed info on this node.
723 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
724 if (SelectInfo.first) {
725 SelectInfo.second = true;
Chandler Carruth63392ea2012-09-16 19:39:50 +0000726 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruthed90ed02012-12-10 08:28:39 +0000727 return;
Chandler Carruth713aa942012-09-14 09:22:59 +0000728 }
729
730 // Check for an unsafe use of the PHI node.
Chandler Carruthed90ed02012-12-10 08:28:39 +0000731 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
732 return PI.setAborted(UnsafeI);
Chandler Carruth713aa942012-09-14 09:22:59 +0000733
Chandler Carruth63392ea2012-09-16 19:39:50 +0000734 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000735 }
736
737 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruthed90ed02012-12-10 08:28:39 +0000738 void visitInstruction(Instruction &I) {
739 PI.setAborted(&I);
740 }
Chandler Carruth713aa942012-09-14 09:22:59 +0000741};
742
Chandler Carruth713aa942012-09-14 09:22:59 +0000743/// \brief Use adder for the alloca partitioning.
744///
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000745/// This class adds the uses of an alloca to all of the partitions which they
746/// use. For splittable partitions, this can end up doing essentially a linear
Chandler Carruth713aa942012-09-14 09:22:59 +0000747/// walk of the partitions, but the number of steps remains bounded by the
748/// total result instruction size:
749/// - The number of partitions is a result of the number unsplittable
750/// instructions using the alloca.
751/// - The number of users of each partition is at worst the total number of
752/// splittable instructions using the alloca.
753/// Thus we will produce N * M instructions in the end, where N are the number
754/// of unsplittable uses and M are the number of splittable. This visitor does
755/// the exact same number of updates to the partitioning.
756///
757/// In the more common case, this visitor will leverage the fact that the
758/// partition space is pre-sorted, and do a logarithmic search for the
759/// partition needed, making the total visit a classical ((N + M) * log(N))
760/// complexity operation.
Chandler Carruthed90ed02012-12-10 08:28:39 +0000761class AllocaPartitioning::UseBuilder : public PtrUseVisitor<UseBuilder> {
762 friend class PtrUseVisitor<UseBuilder>;
Chandler Carruth713aa942012-09-14 09:22:59 +0000763 friend class InstVisitor<UseBuilder>;
Chandler Carruthed90ed02012-12-10 08:28:39 +0000764 typedef PtrUseVisitor<UseBuilder> Base;
765
766 const uint64_t AllocSize;
767 AllocaPartitioning &P;
Chandler Carruth713aa942012-09-14 09:22:59 +0000768
769 /// \brief Set to de-duplicate dead instructions found in the use walk.
770 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
771
772public:
Micah Villmow3574eca2012-10-08 16:38:25 +0000773 UseBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruthed90ed02012-12-10 08:28:39 +0000774 : PtrUseVisitor<UseBuilder>(TD),
775 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
776 P(P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000777
778private:
779 void markAsDead(Instruction &I) {
780 if (VisitedDeadInsts.insert(&I))
781 P.DeadUsers.push_back(&I);
782 }
783
Chandler Carruthed90ed02012-12-10 08:28:39 +0000784 void insertUse(Instruction &User, const APInt &Offset, uint64_t Size) {
Chandler Carruthc3034632012-09-25 10:03:40 +0000785 // If the use has a zero size or extends outside of the allocation, record
786 // it as a dead use for elimination later.
Chandler Carruthed90ed02012-12-10 08:28:39 +0000787 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize))
Chandler Carruth713aa942012-09-14 09:22:59 +0000788 return markAsDead(User);
789
Chandler Carruthed90ed02012-12-10 08:28:39 +0000790 uint64_t BeginOffset = Offset.getZExtValue();
791 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruth02e92a02012-09-23 11:43:14 +0000792
793 // Clamp the end offset to the end of the allocation. Note that this is
794 // formulated to handle even the case where "BeginOffset + Size" overflows.
795 assert(AllocSize >= BeginOffset); // Established above.
796 if (Size > AllocSize - BeginOffset)
Chandler Carruth713aa942012-09-14 09:22:59 +0000797 EndOffset = AllocSize;
798
799 // NB: This only works if we have zero overlapping partitions.
800 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
801 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
802 B = llvm::prior(B);
803 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
804 ++I) {
Chandler Carruth77c12702012-10-01 01:49:22 +0000805 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
806 std::min(I->EndOffset, EndOffset), U);
807 P.use_push_back(I, NewPU);
Chandler Carruth713aa942012-09-14 09:22:59 +0000808 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
Chandler Carruth77c12702012-10-01 01:49:22 +0000809 P.PHIOrSelectOpMap[U]
Chandler Carruth713aa942012-09-14 09:22:59 +0000810 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
811 }
812 }
813
Chandler Carruthed90ed02012-12-10 08:28:39 +0000814 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset) {
815 uint64_t Size = DL.getTypeStoreSize(Ty);
Chandler Carruth713aa942012-09-14 09:22:59 +0000816
817 // If this memory access can be shown to *statically* extend outside the
818 // bounds of of the allocation, it's behavior is undefined, so simply
819 // ignore it. Note that this is more strict than the generic clamping
820 // behavior of insertUse.
Chandler Carruthed90ed02012-12-10 08:28:39 +0000821 if (Offset.isNegative() || Size > AllocSize ||
822 Offset.ugt(AllocSize - Size))
Chandler Carruth713aa942012-09-14 09:22:59 +0000823 return markAsDead(I);
824
Chandler Carruth63392ea2012-09-16 19:39:50 +0000825 insertUse(I, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000826 }
827
828 void visitBitCastInst(BitCastInst &BC) {
829 if (BC.use_empty())
830 return markAsDead(BC);
831
Chandler Carruthed90ed02012-12-10 08:28:39 +0000832 return Base::visitBitCastInst(BC);
Chandler Carruth713aa942012-09-14 09:22:59 +0000833 }
834
835 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
836 if (GEPI.use_empty())
837 return markAsDead(GEPI);
838
Chandler Carruthed90ed02012-12-10 08:28:39 +0000839 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth713aa942012-09-14 09:22:59 +0000840 }
841
842 void visitLoadInst(LoadInst &LI) {
Chandler Carruthed90ed02012-12-10 08:28:39 +0000843 assert(IsOffsetKnown);
Chandler Carruth63392ea2012-09-16 19:39:50 +0000844 handleLoadOrStore(LI.getType(), LI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000845 }
846
847 void visitStoreInst(StoreInst &SI) {
Chandler Carruthed90ed02012-12-10 08:28:39 +0000848 assert(IsOffsetKnown);
Chandler Carruth63392ea2012-09-16 19:39:50 +0000849 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000850 }
851
852 void visitMemSetInst(MemSetInst &II) {
853 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthed90ed02012-12-10 08:28:39 +0000854 if ((Length && Length->getValue() == 0) ||
855 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
856 return markAsDead(II);
857
858 assert(IsOffsetKnown);
859 insertUse(II, Offset, Length ? Length->getLimitedValue()
860 : AllocSize - Offset.getLimitedValue());
Chandler Carruth713aa942012-09-14 09:22:59 +0000861 }
862
863 void visitMemTransferInst(MemTransferInst &II) {
864 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthed90ed02012-12-10 08:28:39 +0000865 if ((Length && Length->getValue() == 0) ||
866 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
Chandler Carruthfca3f402012-10-05 01:29:09 +0000867 return markAsDead(II);
868
Chandler Carruthed90ed02012-12-10 08:28:39 +0000869 assert(IsOffsetKnown);
870 uint64_t Size = Length ? Length->getLimitedValue()
871 : AllocSize - Offset.getLimitedValue();
872
Chandler Carruthfca3f402012-10-05 01:29:09 +0000873 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
874 if (!II.isVolatile() && Offsets.DestEnd && Offsets.SourceEnd &&
875 Offsets.DestBegin == Offsets.SourceBegin)
876 return markAsDead(II); // Skip identity transfers without side-effects.
877
Chandler Carruth63392ea2012-09-16 19:39:50 +0000878 insertUse(II, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000879 }
880
881 void visitIntrinsicInst(IntrinsicInst &II) {
Chandler Carruthed90ed02012-12-10 08:28:39 +0000882 assert(IsOffsetKnown);
Chandler Carruth713aa942012-09-14 09:22:59 +0000883 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
884 II.getIntrinsicID() == Intrinsic::lifetime_end);
885
886 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthed90ed02012-12-10 08:28:39 +0000887 insertUse(II, Offset, std::min(Length->getLimitedValue(),
888 AllocSize - Offset.getLimitedValue()));
Chandler Carruth713aa942012-09-14 09:22:59 +0000889 }
890
Chandler Carruthed90ed02012-12-10 08:28:39 +0000891 void insertPHIOrSelect(Instruction &User, const APInt &Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000892 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
893
894 // For PHI and select operands outside the alloca, we can't nuke the entire
895 // phi or select -- the other side might still be relevant, so we special
896 // case them here and use a separate structure to track the operands
897 // themselves which should be replaced with undef.
Chandler Carruthed90ed02012-12-10 08:28:39 +0000898 if ((Offset.isNegative() && Offset.uge(Size)) ||
899 (!Offset.isNegative() && Offset.uge(AllocSize))) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000900 P.DeadOperands.push_back(U);
901 return;
902 }
903
Chandler Carruth63392ea2012-09-16 19:39:50 +0000904 insertUse(User, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000905 }
Chandler Carruthed90ed02012-12-10 08:28:39 +0000906
Chandler Carruth713aa942012-09-14 09:22:59 +0000907 void visitPHINode(PHINode &PN) {
908 if (PN.use_empty())
909 return markAsDead(PN);
910
Chandler Carruthed90ed02012-12-10 08:28:39 +0000911 assert(IsOffsetKnown);
Chandler Carruth63392ea2012-09-16 19:39:50 +0000912 insertPHIOrSelect(PN, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000913 }
Chandler Carruthed90ed02012-12-10 08:28:39 +0000914
Chandler Carruth713aa942012-09-14 09:22:59 +0000915 void visitSelectInst(SelectInst &SI) {
916 if (SI.use_empty())
917 return markAsDead(SI);
918
919 if (Value *Result = foldSelectInst(SI)) {
920 if (Result == *U)
921 // If the result of the constant fold will be the pointer, recurse
922 // through the select as if we had RAUW'ed it.
Chandler Carruthed90ed02012-12-10 08:28:39 +0000923 enqueueUsers(SI);
Chandler Carruthd54a6b52012-09-21 23:36:40 +0000924 else
925 // Otherwise the operand to the select is dead, and we can replace it
926 // with undef.
927 P.DeadOperands.push_back(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000928
929 return;
930 }
931
Chandler Carruthed90ed02012-12-10 08:28:39 +0000932 assert(IsOffsetKnown);
Chandler Carruth63392ea2012-09-16 19:39:50 +0000933 insertPHIOrSelect(SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000934 }
935
936 /// \brief Unreachable, we've already visited the alloca once.
937 void visitInstruction(Instruction &I) {
938 llvm_unreachable("Unhandled instruction in use builder.");
939 }
940};
941
942void AllocaPartitioning::splitAndMergePartitions() {
943 size_t NumDeadPartitions = 0;
944
945 // Track the range of splittable partitions that we pass when accumulating
946 // overlapping unsplittable partitions.
947 uint64_t SplitEndOffset = 0ull;
948
949 Partition New(0ull, 0ull, false);
950
951 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
952 ++j;
953
954 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
955 assert(New.BeginOffset == New.EndOffset);
956 New = Partitions[i];
957 } else {
958 assert(New.IsSplittable);
959 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
960 }
961 assert(New.BeginOffset != New.EndOffset);
962
963 // Scan the overlapping partitions.
964 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
965 // If the new partition we are forming is splittable, stop at the first
966 // unsplittable partition.
967 if (New.IsSplittable && !Partitions[j].IsSplittable)
968 break;
969
970 // Grow the new partition to include any equally splittable range. 'j' is
971 // always equally splittable when New is splittable, but when New is not
972 // splittable, we may subsume some (or part of some) splitable partition
973 // without growing the new one.
974 if (New.IsSplittable == Partitions[j].IsSplittable) {
975 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
976 } else {
977 assert(!New.IsSplittable);
978 assert(Partitions[j].IsSplittable);
979 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
980 }
981
Chandler Carruthfca3f402012-10-05 01:29:09 +0000982 Partitions[j].kill();
Chandler Carruth713aa942012-09-14 09:22:59 +0000983 ++NumDeadPartitions;
984 ++j;
985 }
986
987 // If the new partition is splittable, chop off the end as soon as the
988 // unsplittable subsequent partition starts and ensure we eventually cover
989 // the splittable area.
990 if (j != e && New.IsSplittable) {
991 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
992 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
993 }
994
995 // Add the new partition if it differs from the original one and is
996 // non-empty. We can end up with an empty partition here if it was
997 // splittable but there is an unsplittable one that starts at the same
998 // offset.
999 if (New != Partitions[i]) {
1000 if (New.BeginOffset != New.EndOffset)
1001 Partitions.push_back(New);
1002 // Mark the old one for removal.
Chandler Carruthfca3f402012-10-05 01:29:09 +00001003 Partitions[i].kill();
Chandler Carruth713aa942012-09-14 09:22:59 +00001004 ++NumDeadPartitions;
1005 }
1006
1007 New.BeginOffset = New.EndOffset;
1008 if (!New.IsSplittable) {
1009 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1010 if (j != e && !Partitions[j].IsSplittable)
1011 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1012 New.IsSplittable = true;
1013 // If there is a trailing splittable partition which won't be fused into
1014 // the next splittable partition go ahead and add it onto the partitions
1015 // list.
1016 if (New.BeginOffset < New.EndOffset &&
1017 (j == e || !Partitions[j].IsSplittable ||
1018 New.EndOffset < Partitions[j].BeginOffset)) {
1019 Partitions.push_back(New);
1020 New.BeginOffset = New.EndOffset = 0ull;
1021 }
1022 }
1023 }
1024
1025 // Re-sort the partitions now that they have been split and merged into
1026 // disjoint set of partitions. Also remove any of the dead partitions we've
1027 // replaced in the process.
1028 std::sort(Partitions.begin(), Partitions.end());
1029 if (NumDeadPartitions) {
Chandler Carruthfca3f402012-10-05 01:29:09 +00001030 assert(Partitions.back().isDead());
Chandler Carruth713aa942012-09-14 09:22:59 +00001031 assert((ptrdiff_t)NumDeadPartitions ==
1032 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1033 }
1034 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1035}
1036
Micah Villmow3574eca2012-10-08 16:38:25 +00001037AllocaPartitioning::AllocaPartitioning(const DataLayout &TD, AllocaInst &AI)
Benjamin Kramerd0807692012-09-14 13:08:09 +00001038 :
Chandler Carruth3a902d02012-11-20 10:23:07 +00001039#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Benjamin Kramerd0807692012-09-14 13:08:09 +00001040 AI(AI),
1041#endif
1042 PointerEscapingInstr(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001043 PartitionBuilder PB(TD, AI, *this);
Chandler Carruthed90ed02012-12-10 08:28:39 +00001044 PartitionBuilder::PtrInfo PtrI = PB.visitPtr(AI);
1045 if (PtrI.isEscaped() || PtrI.isAborted()) {
1046 // FIXME: We should sink the escape vs. abort info into the caller nicely,
1047 // possibly by just storing the PtrInfo in the AllocaPartitioning.
1048 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1049 : PtrI.getAbortingInst();
1050 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth713aa942012-09-14 09:22:59 +00001051 return;
Chandler Carruthed90ed02012-12-10 08:28:39 +00001052 }
Chandler Carruth713aa942012-09-14 09:22:59 +00001053
Chandler Carruthfca3f402012-10-05 01:29:09 +00001054 // Sort the uses. This arranges for the offsets to be in ascending order,
1055 // and the sizes to be in descending order.
1056 std::sort(Partitions.begin(), Partitions.end());
Chandler Carruth713aa942012-09-14 09:22:59 +00001057
Chandler Carruthfca3f402012-10-05 01:29:09 +00001058 // Remove any partitions from the back which are marked as dead.
1059 while (!Partitions.empty() && Partitions.back().isDead())
1060 Partitions.pop_back();
1061
1062 if (Partitions.size() > 1) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001063 // Intersect splittability for all partitions with equal offsets and sizes.
1064 // Then remove all but the first so that we have a sequence of non-equal but
1065 // potentially overlapping partitions.
1066 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1067 I = J) {
1068 ++J;
1069 while (J != E && *I == *J) {
1070 I->IsSplittable &= J->IsSplittable;
1071 ++J;
1072 }
1073 }
1074 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1075 Partitions.end());
1076
1077 // Split splittable and merge unsplittable partitions into a disjoint set
1078 // of partitions over the used space of the allocation.
1079 splitAndMergePartitions();
1080 }
1081
1082 // Now build up the user lists for each of these disjoint partitions by
1083 // re-walking the recursive users of the alloca.
1084 Uses.resize(Partitions.size());
1085 UseBuilder UB(TD, AI, *this);
Chandler Carruthed90ed02012-12-10 08:28:39 +00001086 PtrI = UB.visitPtr(AI);
1087 assert(!PtrI.isEscaped() && "Previously analyzed pointer now escapes!");
1088 assert(!PtrI.isAborted() && "Early aborted the visit of the pointer.");
Chandler Carruth713aa942012-09-14 09:22:59 +00001089}
1090
1091Type *AllocaPartitioning::getCommonType(iterator I) const {
1092 Type *Ty = 0;
1093 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00001094 if (!UI->U)
1095 continue; // Skip dead uses.
Chandler Carruth77c12702012-10-01 01:49:22 +00001096 if (isa<IntrinsicInst>(*UI->U->getUser()))
Chandler Carruth713aa942012-09-14 09:22:59 +00001097 continue;
1098 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
Chandler Carruth7c8df7a2012-09-18 17:49:37 +00001099 continue;
Chandler Carruth713aa942012-09-14 09:22:59 +00001100
1101 Type *UserTy = 0;
Chandler Carruth77c12702012-10-01 01:49:22 +00001102 if (LoadInst *LI = dyn_cast<LoadInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001103 UserTy = LI->getType();
Chandler Carruth77c12702012-10-01 01:49:22 +00001104 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001105 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha2b88162012-10-25 04:37:07 +00001106 } else {
1107 return 0; // Bail if we have weird uses.
1108 }
1109
1110 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
1111 // If the type is larger than the partition, skip it. We only encounter
1112 // this for split integer operations where we want to use the type of the
1113 // entity causing the split.
1114 if (ITy->getBitWidth() > (I->EndOffset - I->BeginOffset)*8)
1115 continue;
1116
1117 // If we have found an integer type use covering the alloca, use that
1118 // regardless of the other types, as integers are often used for a "bucket
1119 // of bits" type.
1120 return ITy;
Chandler Carruth713aa942012-09-14 09:22:59 +00001121 }
1122
1123 if (Ty && Ty != UserTy)
1124 return 0;
1125
1126 Ty = UserTy;
1127 }
1128 return Ty;
1129}
1130
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001131#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1132
Chandler Carruth713aa942012-09-14 09:22:59 +00001133void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1134 StringRef Indent) const {
1135 OS << Indent << "partition #" << (I - begin())
1136 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1137 << (I->IsSplittable ? " (splittable)" : "")
1138 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1139 << "\n";
1140}
1141
1142void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1143 StringRef Indent) const {
1144 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1145 UI != UE; ++UI) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00001146 if (!UI->U)
1147 continue; // Skip dead uses.
Chandler Carruth713aa942012-09-14 09:22:59 +00001148 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
Chandler Carruth77c12702012-10-01 01:49:22 +00001149 << "used by: " << *UI->U->getUser() << "\n";
1150 if (MemTransferInst *II = dyn_cast<MemTransferInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001151 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1152 bool IsDest;
1153 if (!MTO.IsSplittable)
1154 IsDest = UI->BeginOffset == MTO.DestBegin;
1155 else
1156 IsDest = MTO.DestBegin != 0u;
1157 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1158 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1159 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1160 }
1161 }
1162}
1163
1164void AllocaPartitioning::print(raw_ostream &OS) const {
1165 if (PointerEscapingInstr) {
1166 OS << "No partitioning for alloca: " << AI << "\n"
1167 << " A pointer to this alloca escaped by:\n"
1168 << " " << *PointerEscapingInstr << "\n";
1169 return;
1170 }
1171
1172 OS << "Partitioning of alloca: " << AI << "\n";
1173 unsigned Num = 0;
1174 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1175 print(OS, I);
1176 printUsers(OS, I);
1177 }
1178}
1179
1180void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1181void AllocaPartitioning::dump() const { print(dbgs()); }
1182
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001183#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1184
Chandler Carruth713aa942012-09-14 09:22:59 +00001185
1186namespace {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001187/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1188///
1189/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1190/// the loads and stores of an alloca instruction, as well as updating its
1191/// debug information. This is used when a domtree is unavailable and thus
1192/// mem2reg in its full form can't be used to handle promotion of allocas to
1193/// scalar values.
1194class AllocaPromoter : public LoadAndStorePromoter {
1195 AllocaInst &AI;
1196 DIBuilder &DIB;
1197
1198 SmallVector<DbgDeclareInst *, 4> DDIs;
1199 SmallVector<DbgValueInst *, 4> DVIs;
1200
1201public:
1202 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1203 AllocaInst &AI, DIBuilder &DIB)
1204 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1205
1206 void run(const SmallVectorImpl<Instruction*> &Insts) {
1207 // Remember which alloca we're promoting (for isInstInList).
1208 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1209 for (Value::use_iterator UI = DebugNode->use_begin(),
1210 UE = DebugNode->use_end();
1211 UI != UE; ++UI)
1212 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1213 DDIs.push_back(DDI);
1214 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1215 DVIs.push_back(DVI);
1216 }
1217
1218 LoadAndStorePromoter::run(Insts);
1219 AI.eraseFromParent();
1220 while (!DDIs.empty())
1221 DDIs.pop_back_val()->eraseFromParent();
1222 while (!DVIs.empty())
1223 DVIs.pop_back_val()->eraseFromParent();
1224 }
1225
1226 virtual bool isInstInList(Instruction *I,
1227 const SmallVectorImpl<Instruction*> &Insts) const {
1228 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1229 return LI->getOperand(0) == &AI;
1230 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1231 }
1232
1233 virtual void updateDebugInfo(Instruction *Inst) const {
1234 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1235 E = DDIs.end(); I != E; ++I) {
1236 DbgDeclareInst *DDI = *I;
1237 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1238 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1239 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1240 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1241 }
1242 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1243 E = DVIs.end(); I != E; ++I) {
1244 DbgValueInst *DVI = *I;
1245 Value *Arg = NULL;
1246 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1247 // If an argument is zero extended then use argument directly. The ZExt
1248 // may be zapped by an optimization pass in future.
1249 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1250 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1251 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1252 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1253 if (!Arg)
1254 Arg = SI->getOperand(0);
1255 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1256 Arg = LI->getOperand(0);
1257 } else {
1258 continue;
1259 }
1260 Instruction *DbgVal =
1261 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1262 Inst);
1263 DbgVal->setDebugLoc(DVI->getDebugLoc());
1264 }
1265 }
1266};
1267} // end anon namespace
1268
1269
1270namespace {
Chandler Carruth713aa942012-09-14 09:22:59 +00001271/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1272///
1273/// This pass takes allocations which can be completely analyzed (that is, they
1274/// don't escape) and tries to turn them into scalar SSA values. There are
1275/// a few steps to this process.
1276///
1277/// 1) It takes allocations of aggregates and analyzes the ways in which they
1278/// are used to try to split them into smaller allocations, ideally of
1279/// a single scalar data type. It will split up memcpy and memset accesses
1280/// as necessary and try to isolate invidual scalar accesses.
1281/// 2) It will transform accesses into forms which are suitable for SSA value
1282/// promotion. This can be replacing a memset with a scalar store of an
1283/// integer value, or it can involve speculating operations on a PHI or
1284/// select to be a PHI or select of the results.
1285/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1286/// onto insert and extract operations on a vector value, and convert them to
1287/// this form. By doing so, it will enable promotion of vector aggregates to
1288/// SSA vector values.
1289class SROA : public FunctionPass {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001290 const bool RequiresDomTree;
1291
Chandler Carruth713aa942012-09-14 09:22:59 +00001292 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +00001293 const DataLayout *TD;
Chandler Carruth713aa942012-09-14 09:22:59 +00001294 DominatorTree *DT;
1295
1296 /// \brief Worklist of alloca instructions to simplify.
1297 ///
1298 /// Each alloca in the function is added to this. Each new alloca formed gets
1299 /// added to it as well to recursively simplify unless that alloca can be
1300 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1301 /// the one being actively rewritten, we add it back onto the list if not
1302 /// already present to ensure it is re-visited.
1303 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1304
1305 /// \brief A collection of instructions to delete.
1306 /// We try to batch deletions to simplify code and make things a bit more
1307 /// efficient.
Chandler Carruthf5837aa2012-11-20 01:12:50 +00001308 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth713aa942012-09-14 09:22:59 +00001309
Chandler Carruthb2d98c22012-10-04 12:33:50 +00001310 /// \brief Post-promotion worklist.
1311 ///
1312 /// Sometimes we discover an alloca which has a high probability of becoming
1313 /// viable for SROA after a round of promotion takes place. In those cases,
1314 /// the alloca is enqueued here for re-processing.
1315 ///
1316 /// Note that we have to be very careful to clear allocas out of this list in
1317 /// the event they are deleted.
1318 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
1319
Chandler Carruth713aa942012-09-14 09:22:59 +00001320 /// \brief A collection of alloca instructions we can directly promote.
1321 std::vector<AllocaInst *> PromotableAllocas;
1322
1323public:
Chandler Carruth1c8db502012-09-15 11:43:14 +00001324 SROA(bool RequiresDomTree = true)
1325 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1326 C(0), TD(0), DT(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001327 initializeSROAPass(*PassRegistry::getPassRegistry());
1328 }
1329 bool runOnFunction(Function &F);
1330 void getAnalysisUsage(AnalysisUsage &AU) const;
1331
1332 const char *getPassName() const { return "SROA"; }
1333 static char ID;
1334
1335private:
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00001336 friend class PHIOrSelectSpeculator;
Chandler Carruth713aa942012-09-14 09:22:59 +00001337 friend class AllocaPartitionRewriter;
1338 friend class AllocaPartitionVectorRewriter;
1339
1340 bool rewriteAllocaPartition(AllocaInst &AI,
1341 AllocaPartitioning &P,
1342 AllocaPartitioning::iterator PI);
1343 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1344 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth8615cd22012-09-14 10:26:38 +00001345 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth1c8db502012-09-15 11:43:14 +00001346 bool promoteAllocas(Function &F);
Chandler Carruth713aa942012-09-14 09:22:59 +00001347};
1348}
1349
1350char SROA::ID = 0;
1351
Chandler Carruth1c8db502012-09-15 11:43:14 +00001352FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1353 return new SROA(RequiresDomTree);
Chandler Carruth713aa942012-09-14 09:22:59 +00001354}
1355
1356INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1357 false, false)
1358INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1359INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1360 false, false)
1361
Chandler Carruth0e9da582012-10-05 01:29:06 +00001362namespace {
1363/// \brief Visitor to speculate PHIs and Selects where possible.
1364class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
1365 // Befriend the base class so it can delegate to private visit methods.
1366 friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
1367
Micah Villmow3574eca2012-10-08 16:38:25 +00001368 const DataLayout &TD;
Chandler Carruth0e9da582012-10-05 01:29:06 +00001369 AllocaPartitioning &P;
1370 SROA &Pass;
1371
1372public:
Micah Villmow3574eca2012-10-08 16:38:25 +00001373 PHIOrSelectSpeculator(const DataLayout &TD, AllocaPartitioning &P, SROA &Pass)
Chandler Carruth0e9da582012-10-05 01:29:06 +00001374 : TD(TD), P(P), Pass(Pass) {}
1375
1376 /// \brief Visit the users of an alloca partition and rewrite them.
1377 void visitUsers(AllocaPartitioning::const_iterator PI) {
1378 // Note that we need to use an index here as the underlying vector of uses
1379 // may be grown during speculation. However, we never need to re-visit the
1380 // new uses, and so we can use the initial size bound.
1381 for (unsigned Idx = 0, Size = P.use_size(PI); Idx != Size; ++Idx) {
1382 const AllocaPartitioning::PartitionUse &PU = P.getUse(PI, Idx);
1383 if (!PU.U)
1384 continue; // Skip dead use.
1385
1386 visit(cast<Instruction>(PU.U->getUser()));
1387 }
1388 }
1389
1390private:
1391 // By default, skip this instruction.
1392 void visitInstruction(Instruction &I) {}
1393
1394 /// PHI instructions that use an alloca and are subsequently loaded can be
1395 /// rewritten to load both input pointers in the pred blocks and then PHI the
1396 /// results, allowing the load of the alloca to be promoted.
1397 /// From this:
1398 /// %P2 = phi [i32* %Alloca, i32* %Other]
1399 /// %V = load i32* %P2
1400 /// to:
1401 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1402 /// ...
1403 /// %V2 = load i32* %Other
1404 /// ...
1405 /// %V = phi [i32 %V1, i32 %V2]
1406 ///
1407 /// We can do this to a select if its only uses are loads and if the operands
1408 /// to the select can be loaded unconditionally.
1409 ///
1410 /// FIXME: This should be hoisted into a generic utility, likely in
1411 /// Transforms/Util/Local.h
1412 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
1413 // For now, we can only do this promotion if the load is in the same block
1414 // as the PHI, and if there are no stores between the phi and load.
1415 // TODO: Allow recursive phi users.
1416 // TODO: Allow stores.
1417 BasicBlock *BB = PN.getParent();
1418 unsigned MaxAlign = 0;
1419 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
1420 UI != UE; ++UI) {
1421 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1422 if (LI == 0 || !LI->isSimple()) return false;
1423
1424 // For now we only allow loads in the same block as the PHI. This is
1425 // a common case that happens when instcombine merges two loads through
1426 // a PHI.
1427 if (LI->getParent() != BB) return false;
1428
1429 // Ensure that there are no instructions between the PHI and the load that
1430 // could store.
1431 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1432 if (BBI->mayWriteToMemory())
1433 return false;
1434
1435 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1436 Loads.push_back(LI);
1437 }
1438
1439 // We can only transform this if it is safe to push the loads into the
1440 // predecessor blocks. The only thing to watch out for is that we can't put
1441 // a possibly trapping load in the predecessor if it is a critical edge.
1442 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
1443 ++Idx) {
1444 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1445 Value *InVal = PN.getIncomingValue(Idx);
1446
1447 // If the value is produced by the terminator of the predecessor (an
1448 // invoke) or it has side-effects, there is no valid place to put a load
1449 // in the predecessor.
1450 if (TI == InVal || TI->mayHaveSideEffects())
1451 return false;
1452
1453 // If the predecessor has a single successor, then the edge isn't
1454 // critical.
1455 if (TI->getNumSuccessors() == 1)
1456 continue;
1457
1458 // If this pointer is always safe to load, or if we can prove that there
1459 // is already a load in the block, then we can move the load to the pred
1460 // block.
1461 if (InVal->isDereferenceablePointer() ||
1462 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
1463 continue;
1464
1465 return false;
1466 }
1467
1468 return true;
1469 }
1470
1471 void visitPHINode(PHINode &PN) {
1472 DEBUG(dbgs() << " original: " << PN << "\n");
1473
1474 SmallVector<LoadInst *, 4> Loads;
1475 if (!isSafePHIToSpeculate(PN, Loads))
1476 return;
1477
1478 assert(!Loads.empty());
1479
1480 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1481 IRBuilder<> PHIBuilder(&PN);
1482 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1483 PN.getName() + ".sroa.speculated");
1484
1485 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1486 // matter which one we get and if any differ, it doesn't matter.
1487 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
1488 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1489 unsigned Align = SomeLoad->getAlignment();
1490
1491 // Rewrite all loads of the PN to use the new PHI.
1492 do {
1493 LoadInst *LI = Loads.pop_back_val();
1494 LI->replaceAllUsesWith(NewPN);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00001495 Pass.DeadInsts.insert(LI);
Chandler Carruth0e9da582012-10-05 01:29:06 +00001496 } while (!Loads.empty());
1497
1498 // Inject loads into all of the pred blocks.
1499 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1500 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1501 TerminatorInst *TI = Pred->getTerminator();
1502 Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
1503 Value *InVal = PN.getIncomingValue(Idx);
1504 IRBuilder<> PredBuilder(TI);
1505
1506 LoadInst *Load
1507 = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
1508 Pred->getName()));
1509 ++NumLoadsSpeculated;
1510 Load->setAlignment(Align);
1511 if (TBAATag)
1512 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1513 NewPN->addIncoming(Load, Pred);
1514
1515 Instruction *Ptr = dyn_cast<Instruction>(InVal);
1516 if (!Ptr)
1517 // No uses to rewrite.
1518 continue;
1519
1520 // Try to lookup and rewrite any partition uses corresponding to this phi
1521 // input.
1522 AllocaPartitioning::iterator PI
1523 = P.findPartitionForPHIOrSelectOperand(InUse);
1524 if (PI == P.end())
1525 continue;
1526
1527 // Replace the Use in the PartitionUse for this operand with the Use
1528 // inside the load.
1529 AllocaPartitioning::use_iterator UI
1530 = P.findPartitionUseForPHIOrSelectOperand(InUse);
1531 assert(isa<PHINode>(*UI->U->getUser()));
1532 UI->U = &Load->getOperandUse(Load->getPointerOperandIndex());
1533 }
1534 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1535 }
1536
1537 /// Select instructions that use an alloca and are subsequently loaded can be
1538 /// rewritten to load both input pointers and then select between the result,
1539 /// allowing the load of the alloca to be promoted.
1540 /// From this:
1541 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1542 /// %V = load i32* %P2
1543 /// to:
1544 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1545 /// %V2 = load i32* %Other
1546 /// %V = select i1 %cond, i32 %V1, i32 %V2
1547 ///
1548 /// We can do this to a select if its only uses are loads and if the operand
1549 /// to the select can be loaded unconditionally.
1550 bool isSafeSelectToSpeculate(SelectInst &SI,
1551 SmallVectorImpl<LoadInst *> &Loads) {
1552 Value *TValue = SI.getTrueValue();
1553 Value *FValue = SI.getFalseValue();
1554 bool TDerefable = TValue->isDereferenceablePointer();
1555 bool FDerefable = FValue->isDereferenceablePointer();
1556
1557 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
1558 UI != UE; ++UI) {
1559 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1560 if (LI == 0 || !LI->isSimple()) return false;
1561
1562 // Both operands to the select need to be dereferencable, either
1563 // absolutely (e.g. allocas) or at this point because we can see other
1564 // accesses to it.
1565 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
1566 LI->getAlignment(), &TD))
1567 return false;
1568 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
1569 LI->getAlignment(), &TD))
1570 return false;
1571 Loads.push_back(LI);
1572 }
1573
1574 return true;
1575 }
1576
1577 void visitSelectInst(SelectInst &SI) {
1578 DEBUG(dbgs() << " original: " << SI << "\n");
1579 IRBuilder<> IRB(&SI);
1580
1581 // If the select isn't safe to speculate, just use simple logic to emit it.
1582 SmallVector<LoadInst *, 4> Loads;
1583 if (!isSafeSelectToSpeculate(SI, Loads))
1584 return;
1585
1586 Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) };
1587 AllocaPartitioning::iterator PIs[2];
1588 AllocaPartitioning::PartitionUse PUs[2];
1589 for (unsigned i = 0, e = 2; i != e; ++i) {
1590 PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]);
1591 if (PIs[i] != P.end()) {
1592 // If the pointer is within the partitioning, remove the select from
1593 // its uses. We'll add in the new loads below.
1594 AllocaPartitioning::use_iterator UI
1595 = P.findPartitionUseForPHIOrSelectOperand(Ops[i]);
1596 PUs[i] = *UI;
1597 // Clear out the use here so that the offsets into the use list remain
1598 // stable but this use is ignored when rewriting.
1599 UI->U = 0;
1600 }
1601 }
1602
1603 Value *TV = SI.getTrueValue();
1604 Value *FV = SI.getFalseValue();
1605 // Replace the loads of the select with a select of two loads.
1606 while (!Loads.empty()) {
1607 LoadInst *LI = Loads.pop_back_val();
1608
1609 IRB.SetInsertPoint(LI);
1610 LoadInst *TL =
1611 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1612 LoadInst *FL =
1613 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1614 NumLoadsSpeculated += 2;
1615
1616 // Transfer alignment and TBAA info if present.
1617 TL->setAlignment(LI->getAlignment());
1618 FL->setAlignment(LI->getAlignment());
1619 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1620 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1621 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1622 }
1623
1624 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1625 LI->getName() + ".sroa.speculated");
1626
1627 LoadInst *Loads[2] = { TL, FL };
1628 for (unsigned i = 0, e = 2; i != e; ++i) {
1629 if (PIs[i] != P.end()) {
1630 Use *LoadUse = &Loads[i]->getOperandUse(0);
1631 assert(PUs[i].U->get() == LoadUse->get());
1632 PUs[i].U = LoadUse;
1633 P.use_push_back(PIs[i], PUs[i]);
1634 }
1635 }
1636
1637 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1638 LI->replaceAllUsesWith(V);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00001639 Pass.DeadInsts.insert(LI);
Chandler Carruth0e9da582012-10-05 01:29:06 +00001640 }
1641 }
1642};
1643}
1644
Chandler Carruth713aa942012-09-14 09:22:59 +00001645/// \brief Build a GEP out of a base pointer and indices.
1646///
1647/// This will return the BasePtr if that is valid, or build a new GEP
1648/// instruction using the IRBuilder if GEP-ing is needed.
1649static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1650 SmallVectorImpl<Value *> &Indices,
1651 const Twine &Prefix) {
1652 if (Indices.empty())
1653 return BasePtr;
1654
1655 // A single zero index is a no-op, so check for this and avoid building a GEP
1656 // in that case.
1657 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1658 return BasePtr;
1659
1660 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1661}
1662
1663/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1664/// TargetTy without changing the offset of the pointer.
1665///
1666/// This routine assumes we've already established a properly offset GEP with
1667/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1668/// zero-indices down through type layers until we find one the same as
1669/// TargetTy. If we can't find one with the same type, we at least try to use
1670/// one with the same size. If none of that works, we just produce the GEP as
1671/// indicated by Indices to have the correct offset.
Micah Villmow3574eca2012-10-08 16:38:25 +00001672static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001673 Value *BasePtr, Type *Ty, Type *TargetTy,
1674 SmallVectorImpl<Value *> &Indices,
1675 const Twine &Prefix) {
1676 if (Ty == TargetTy)
1677 return buildGEP(IRB, BasePtr, Indices, Prefix);
1678
1679 // See if we can descend into a struct and locate a field with the correct
1680 // type.
1681 unsigned NumLayers = 0;
1682 Type *ElementTy = Ty;
1683 do {
1684 if (ElementTy->isPointerTy())
1685 break;
1686 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1687 ElementTy = SeqTy->getElementType();
Chandler Carruth020d9d52012-10-17 07:22:16 +00001688 // Note that we use the default address space as this index is over an
1689 // array or a vector, not a pointer.
1690 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(0), 0)));
Chandler Carruth713aa942012-09-14 09:22:59 +00001691 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth2fdb25b2012-10-09 01:58:35 +00001692 if (STy->element_begin() == STy->element_end())
1693 break; // Nothing left to descend into.
Chandler Carruth713aa942012-09-14 09:22:59 +00001694 ElementTy = *STy->element_begin();
1695 Indices.push_back(IRB.getInt32(0));
1696 } else {
1697 break;
1698 }
1699 ++NumLayers;
1700 } while (ElementTy != TargetTy);
1701 if (ElementTy != TargetTy)
1702 Indices.erase(Indices.end() - NumLayers, Indices.end());
1703
1704 return buildGEP(IRB, BasePtr, Indices, Prefix);
1705}
1706
1707/// \brief Recursively compute indices for a natural GEP.
1708///
1709/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1710/// element types adding appropriate indices for the GEP.
Micah Villmow3574eca2012-10-08 16:38:25 +00001711static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001712 Value *Ptr, Type *Ty, APInt &Offset,
1713 Type *TargetTy,
1714 SmallVectorImpl<Value *> &Indices,
1715 const Twine &Prefix) {
1716 if (Offset == 0)
1717 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1718
1719 // We can't recurse through pointer types.
1720 if (Ty->isPointerTy())
1721 return 0;
1722
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001723 // We try to analyze GEPs over vectors here, but note that these GEPs are
1724 // extremely poorly defined currently. The long-term goal is to remove GEPing
1725 // over a vector from the IR completely.
Chandler Carruth713aa942012-09-14 09:22:59 +00001726 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Nadav Roteme21708e2012-12-18 05:23:31 +00001727 unsigned ElementSizeInBits = TD.getTypeSizeInBits(VecTy->getScalarType());
Chandler Carruth713aa942012-09-14 09:22:59 +00001728 if (ElementSizeInBits % 8)
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001729 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth713aa942012-09-14 09:22:59 +00001730 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth02bf98a2012-10-17 09:23:48 +00001731 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00001732 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1733 return 0;
1734 Offset -= NumSkippedElements * ElementSize;
1735 Indices.push_back(IRB.getInt(NumSkippedElements));
1736 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1737 Offset, TargetTy, Indices, Prefix);
1738 }
1739
1740 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1741 Type *ElementTy = ArrTy->getElementType();
1742 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
Chandler Carruth02bf98a2012-10-17 09:23:48 +00001743 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00001744 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1745 return 0;
1746
1747 Offset -= NumSkippedElements * ElementSize;
1748 Indices.push_back(IRB.getInt(NumSkippedElements));
1749 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1750 Indices, Prefix);
1751 }
1752
1753 StructType *STy = dyn_cast<StructType>(Ty);
1754 if (!STy)
1755 return 0;
1756
1757 const StructLayout *SL = TD.getStructLayout(STy);
1758 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthad41dcf2012-09-14 10:30:42 +00001759 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00001760 return 0;
1761 unsigned Index = SL->getElementContainingOffset(StructOffset);
1762 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1763 Type *ElementTy = STy->getElementType(Index);
1764 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1765 return 0; // The offset points into alignment padding.
1766
1767 Indices.push_back(IRB.getInt32(Index));
1768 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1769 Indices, Prefix);
1770}
1771
1772/// \brief Get a natural GEP from a base pointer to a particular offset and
1773/// resulting in a particular type.
1774///
1775/// The goal is to produce a "natural" looking GEP that works with the existing
1776/// composite types to arrive at the appropriate offset and element type for
1777/// a pointer. TargetTy is the element type the returned GEP should point-to if
1778/// possible. We recurse by decreasing Offset, adding the appropriate index to
1779/// Indices, and setting Ty to the result subtype.
1780///
Chandler Carruth7f5bede2012-09-14 10:18:49 +00001781/// If no natural GEP can be constructed, this function returns null.
Micah Villmow3574eca2012-10-08 16:38:25 +00001782static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001783 Value *Ptr, APInt Offset, Type *TargetTy,
1784 SmallVectorImpl<Value *> &Indices,
1785 const Twine &Prefix) {
1786 PointerType *Ty = cast<PointerType>(Ptr->getType());
1787
1788 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1789 // an i8.
1790 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1791 return 0;
1792
1793 Type *ElementTy = Ty->getElementType();
Chandler Carruth38f35fd2012-09-18 22:37:19 +00001794 if (!ElementTy->isSized())
1795 return 0; // We can't GEP through an unsized element.
Chandler Carruth713aa942012-09-14 09:22:59 +00001796 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1797 if (ElementSize == 0)
1798 return 0; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth02bf98a2012-10-17 09:23:48 +00001799 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00001800
1801 Offset -= NumSkippedElements * ElementSize;
1802 Indices.push_back(IRB.getInt(NumSkippedElements));
1803 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1804 Indices, Prefix);
1805}
1806
1807/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1808/// resulting pointer has PointerTy.
1809///
1810/// This tries very hard to compute a "natural" GEP which arrives at the offset
1811/// and produces the pointer type desired. Where it cannot, it will try to use
1812/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1813/// fails, it will try to use an existing i8* and GEP to the byte offset and
1814/// bitcast to the type.
1815///
1816/// The strategy for finding the more natural GEPs is to peel off layers of the
1817/// pointer, walking back through bit casts and GEPs, searching for a base
1818/// pointer from which we can compute a natural GEP with the desired
1819/// properities. The algorithm tries to fold as many constant indices into
1820/// a single GEP as possible, thus making each GEP more independent of the
1821/// surrounding code.
Micah Villmow3574eca2012-10-08 16:38:25 +00001822static Value *getAdjustedPtr(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001823 Value *Ptr, APInt Offset, Type *PointerTy,
1824 const Twine &Prefix) {
1825 // Even though we don't look through PHI nodes, we could be called on an
1826 // instruction in an unreachable block, which may be on a cycle.
1827 SmallPtrSet<Value *, 4> Visited;
1828 Visited.insert(Ptr);
1829 SmallVector<Value *, 4> Indices;
1830
1831 // We may end up computing an offset pointer that has the wrong type. If we
1832 // never are able to compute one directly that has the correct type, we'll
1833 // fall back to it, so keep it around here.
1834 Value *OffsetPtr = 0;
1835
1836 // Remember any i8 pointer we come across to re-use if we need to do a raw
1837 // byte offset.
1838 Value *Int8Ptr = 0;
1839 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1840
1841 Type *TargetTy = PointerTy->getPointerElementType();
1842
1843 do {
1844 // First fold any existing GEPs into the offset.
1845 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1846 APInt GEPOffset(Offset.getBitWidth(), 0);
Nuno Lopes98281a22012-12-30 16:25:48 +00001847 if (!GEP->accumulateConstantOffset(TD, GEPOffset))
Chandler Carruth713aa942012-09-14 09:22:59 +00001848 break;
1849 Offset += GEPOffset;
1850 Ptr = GEP->getPointerOperand();
1851 if (!Visited.insert(Ptr))
1852 break;
1853 }
1854
1855 // See if we can perform a natural GEP here.
1856 Indices.clear();
1857 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1858 Indices, Prefix)) {
1859 if (P->getType() == PointerTy) {
1860 // Zap any offset pointer that we ended up computing in previous rounds.
1861 if (OffsetPtr && OffsetPtr->use_empty())
1862 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1863 I->eraseFromParent();
1864 return P;
1865 }
1866 if (!OffsetPtr) {
1867 OffsetPtr = P;
1868 }
1869 }
1870
1871 // Stash this pointer if we've found an i8*.
1872 if (Ptr->getType()->isIntegerTy(8)) {
1873 Int8Ptr = Ptr;
1874 Int8PtrOffset = Offset;
1875 }
1876
1877 // Peel off a layer of the pointer and update the offset appropriately.
1878 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1879 Ptr = cast<Operator>(Ptr)->getOperand(0);
1880 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1881 if (GA->mayBeOverridden())
1882 break;
1883 Ptr = GA->getAliasee();
1884 } else {
1885 break;
1886 }
1887 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1888 } while (Visited.insert(Ptr));
1889
1890 if (!OffsetPtr) {
1891 if (!Int8Ptr) {
1892 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1893 Prefix + ".raw_cast");
1894 Int8PtrOffset = Offset;
1895 }
1896
1897 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1898 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1899 Prefix + ".raw_idx");
1900 }
1901 Ptr = OffsetPtr;
1902
1903 // On the off chance we were targeting i8*, guard the bitcast here.
1904 if (Ptr->getType() != PointerTy)
1905 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
1906
1907 return Ptr;
1908}
1909
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00001910/// \brief Test whether we can convert a value from the old to the new type.
1911///
1912/// This predicate should be used to guard calls to convertValue in order to
1913/// ensure that we only try to convert viable values. The strategy is that we
1914/// will peel off single element struct and array wrappings to get to an
1915/// underlying value, and convert that value.
1916static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1917 if (OldTy == NewTy)
1918 return true;
1919 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1920 return false;
1921 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1922 return false;
1923
1924 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1925 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1926 return true;
1927 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1928 return true;
1929 return false;
1930 }
1931
1932 return true;
1933}
1934
1935/// \brief Generic routine to convert an SSA value to a value of a different
1936/// type.
1937///
1938/// This will try various different casting techniques, such as bitcasts,
1939/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1940/// two types for viability with this routine.
1941static Value *convertValue(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
1942 Type *Ty) {
1943 assert(canConvertValue(DL, V->getType(), Ty) &&
1944 "Value not convertable to type");
1945 if (V->getType() == Ty)
1946 return V;
1947 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1948 return IRB.CreateIntToPtr(V, Ty);
1949 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1950 return IRB.CreatePtrToInt(V, Ty);
1951
1952 return IRB.CreateBitCast(V, Ty);
1953}
1954
Chandler Carruth713aa942012-09-14 09:22:59 +00001955/// \brief Test whether the given alloca partition can be promoted to a vector.
1956///
1957/// This is a quick test to check whether we can rewrite a particular alloca
1958/// partition (and its newly formed alloca) into a vector alloca with only
1959/// whole-vector loads and stores such that it could be promoted to a vector
1960/// SSA value. We only can ensure this for a limited set of operations, and we
1961/// don't want to do the rewrites unless we are confident that the result will
1962/// be promotable, so we have an early test here.
Micah Villmow3574eca2012-10-08 16:38:25 +00001963static bool isVectorPromotionViable(const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001964 Type *AllocaTy,
1965 AllocaPartitioning &P,
1966 uint64_t PartitionBeginOffset,
1967 uint64_t PartitionEndOffset,
1968 AllocaPartitioning::const_use_iterator I,
1969 AllocaPartitioning::const_use_iterator E) {
1970 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1971 if (!Ty)
1972 return false;
1973
Nadav Roteme21708e2012-12-18 05:23:31 +00001974 uint64_t ElementSize = TD.getTypeSizeInBits(Ty->getScalarType());
Chandler Carruth713aa942012-09-14 09:22:59 +00001975
1976 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1977 // that aren't byte sized.
1978 if (ElementSize % 8)
1979 return false;
Benjamin Kramer0ea4c3d2013-01-01 16:13:35 +00001980 assert((TD.getTypeSizeInBits(Ty) % 8) == 0 &&
1981 "vector size not a multiple of element size?");
Chandler Carruth713aa942012-09-14 09:22:59 +00001982 ElementSize /= 8;
1983
1984 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00001985 if (!I->U)
1986 continue; // Skip dead use.
1987
Chandler Carruth713aa942012-09-14 09:22:59 +00001988 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
1989 uint64_t BeginIndex = BeginOffset / ElementSize;
1990 if (BeginIndex * ElementSize != BeginOffset ||
1991 BeginIndex >= Ty->getNumElements())
1992 return false;
1993 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
1994 uint64_t EndIndex = EndOffset / ElementSize;
1995 if (EndIndex * ElementSize != EndOffset ||
1996 EndIndex > Ty->getNumElements())
1997 return false;
1998
Chandler Carruth07df7652012-11-21 08:16:30 +00001999 assert(EndIndex > BeginIndex && "Empty vector!");
2000 uint64_t NumElements = EndIndex - BeginIndex;
2001 Type *PartitionTy
2002 = (NumElements == 1) ? Ty->getElementType()
2003 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruth713aa942012-09-14 09:22:59 +00002004
Chandler Carruth77c12702012-10-01 01:49:22 +00002005 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002006 if (MI->isVolatile())
2007 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002008 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002009 const AllocaPartitioning::MemTransferOffsets &MTO
2010 = P.getMemTransferOffsets(*MTI);
2011 if (!MTO.IsSplittable)
2012 return false;
2013 }
Chandler Carruth77c12702012-10-01 01:49:22 +00002014 } else if (I->U->get()->getType()->getPointerElementType()->isStructTy()) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002015 // Disable vector promotion when there are loads or stores of an FCA.
2016 return false;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002017 } else if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
2018 if (LI->isVolatile())
2019 return false;
Chandler Carruth07df7652012-11-21 08:16:30 +00002020 if (!canConvertValue(TD, PartitionTy, LI->getType()))
2021 return false;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002022 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
2023 if (SI->isVolatile())
2024 return false;
Chandler Carruth07df7652012-11-21 08:16:30 +00002025 if (!canConvertValue(TD, SI->getValueOperand()->getType(), PartitionTy))
2026 return false;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002027 } else {
Chandler Carruth713aa942012-09-14 09:22:59 +00002028 return false;
2029 }
2030 }
2031 return true;
2032}
2033
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002034/// \brief Test whether the given alloca partition's integer operations can be
2035/// widened to promotable ones.
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002036///
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002037/// This is a quick test to check whether we can rewrite the integer loads and
2038/// stores to a particular alloca into wider loads and stores and be able to
2039/// promote the resulting alloca.
2040static bool isIntegerWideningViable(const DataLayout &TD,
2041 Type *AllocaTy,
2042 uint64_t AllocBeginOffset,
2043 AllocaPartitioning &P,
2044 AllocaPartitioning::const_use_iterator I,
2045 AllocaPartitioning::const_use_iterator E) {
2046 uint64_t SizeInBits = TD.getTypeSizeInBits(AllocaTy);
Benjamin Kramer5bded752012-12-01 11:53:32 +00002047 // Don't create integer types larger than the maximum bitwidth.
2048 if (SizeInBits > IntegerType::MAX_INT_BITS)
2049 return false;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002050
2051 // Don't try to handle allocas with bit-padding.
2052 if (SizeInBits != TD.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002053 return false;
2054
Chandler Carrutha2b88162012-10-25 04:37:07 +00002055 // We need to ensure that an integer type with the appropriate bitwidth can
2056 // be converted to the alloca type, whatever that is. We don't want to force
2057 // the alloca itself to have an integer type if there is a more suitable one.
2058 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2059 if (!canConvertValue(TD, AllocaTy, IntTy) ||
2060 !canConvertValue(TD, IntTy, AllocaTy))
2061 return false;
2062
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002063 uint64_t Size = TD.getTypeStoreSize(AllocaTy);
2064
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002065 // Check the uses to ensure the uses are (likely) promoteable integer uses.
2066 // Also ensure that the alloca has a covering load or store. We don't want
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002067 // to widen the integer operotains only to fail to promote due to some other
2068 // unsplittable entry (which we may make splittable later).
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002069 bool WholeAllocaOp = false;
2070 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00002071 if (!I->U)
2072 continue; // Skip dead use.
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002073
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002074 uint64_t RelBegin = I->BeginOffset - AllocBeginOffset;
2075 uint64_t RelEnd = I->EndOffset - AllocBeginOffset;
2076
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002077 // We can't reasonably handle cases where the load or store extends past
2078 // the end of the aloca's type and into its padding.
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002079 if (RelEnd > Size)
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002080 return false;
2081
Chandler Carruth77c12702012-10-01 01:49:22 +00002082 if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002083 if (LI->isVolatile())
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002084 return false;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002085 if (RelBegin == 0 && RelEnd == Size)
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002086 WholeAllocaOp = true;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002087 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth3d9afa82012-12-10 00:54:45 +00002088 if (ITy->getBitWidth() < TD.getTypeStoreSizeInBits(ITy))
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002089 return false;
2090 continue;
2091 }
2092 // Non-integer loads need to be convertible from the alloca type so that
2093 // they are promotable.
2094 if (RelBegin != 0 || RelEnd != Size ||
2095 !canConvertValue(TD, AllocaTy, LI->getType()))
2096 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002097 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002098 Type *ValueTy = SI->getValueOperand()->getType();
2099 if (SI->isVolatile())
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002100 return false;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002101 if (RelBegin == 0 && RelEnd == Size)
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002102 WholeAllocaOp = true;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002103 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth3d9afa82012-12-10 00:54:45 +00002104 if (ITy->getBitWidth() < TD.getTypeStoreSizeInBits(ITy))
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002105 return false;
2106 continue;
2107 }
2108 // Non-integer stores need to be convertible to the alloca type so that
2109 // they are promotable.
2110 if (RelBegin != 0 || RelEnd != Size ||
2111 !canConvertValue(TD, ValueTy, AllocaTy))
2112 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002113 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
Chandler Carruthb0de1e32012-12-17 18:48:07 +00002114 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002115 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002116 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002117 const AllocaPartitioning::MemTransferOffsets &MTO
2118 = P.getMemTransferOffsets(*MTI);
2119 if (!MTO.IsSplittable)
2120 return false;
2121 }
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002122 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->U->getUser())) {
2123 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2124 II->getIntrinsicID() != Intrinsic::lifetime_end)
2125 return false;
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002126 } else {
2127 return false;
2128 }
2129 }
2130 return WholeAllocaOp;
2131}
2132
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002133static Value *extractInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2134 IntegerType *Ty, uint64_t Offset,
2135 const Twine &Name) {
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002136 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002137 IntegerType *IntTy = cast<IntegerType>(V->getType());
2138 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2139 "Element extends past full value");
2140 uint64_t ShAmt = 8*Offset;
2141 if (DL.isBigEndian())
2142 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002143 if (ShAmt) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002144 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002145 DEBUG(dbgs() << " shifted: " << *V << "\n");
2146 }
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002147 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2148 "Cannot extract to a larger integer!");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002149 if (Ty != IntTy) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002150 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002151 DEBUG(dbgs() << " trunced: " << *V << "\n");
2152 }
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002153 return V;
2154}
2155
2156static Value *insertInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *Old,
2157 Value *V, uint64_t Offset, const Twine &Name) {
2158 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2159 IntegerType *Ty = cast<IntegerType>(V->getType());
2160 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2161 "Cannot insert a larger integer!");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002162 DEBUG(dbgs() << " start: " << *V << "\n");
2163 if (Ty != IntTy) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002164 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002165 DEBUG(dbgs() << " extended: " << *V << "\n");
2166 }
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002167 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2168 "Element store outside of alloca store");
2169 uint64_t ShAmt = 8*Offset;
2170 if (DL.isBigEndian())
2171 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002172 if (ShAmt) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002173 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002174 DEBUG(dbgs() << " shifted: " << *V << "\n");
2175 }
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002176
2177 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2178 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2179 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002180 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002181 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002182 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002183 }
2184 return V;
2185}
2186
Chandler Carruth5c531eb2012-12-17 13:07:30 +00002187static Value *extractVector(IRBuilder<> &IRB, Value *V,
2188 unsigned BeginIndex, unsigned EndIndex,
2189 const Twine &Name) {
2190 VectorType *VecTy = cast<VectorType>(V->getType());
2191 unsigned NumElements = EndIndex - BeginIndex;
2192 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2193
2194 if (NumElements == VecTy->getNumElements())
2195 return V;
2196
2197 if (NumElements == 1) {
2198 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2199 Name + ".extract");
2200 DEBUG(dbgs() << " extract: " << *V << "\n");
2201 return V;
2202 }
2203
2204 SmallVector<Constant*, 8> Mask;
2205 Mask.reserve(NumElements);
2206 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2207 Mask.push_back(IRB.getInt32(i));
2208 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2209 ConstantVector::get(Mask),
2210 Name + ".extract");
2211 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2212 return V;
2213}
2214
Chandler Carruth7f7d2012012-12-17 13:41:21 +00002215static Value *insertVector(IRBuilder<> &IRB, Value *Old, Value *V,
2216 unsigned BeginIndex, const Twine &Name) {
2217 VectorType *VecTy = cast<VectorType>(Old->getType());
2218 assert(VecTy && "Can only insert a vector into a vector");
2219
2220 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2221 if (!Ty) {
2222 // Single element to insert.
2223 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2224 Name + ".insert");
2225 DEBUG(dbgs() << " insert: " << *V << "\n");
2226 return V;
2227 }
2228
2229 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2230 "Too many elements!");
2231 if (Ty->getNumElements() == VecTy->getNumElements()) {
2232 assert(V->getType() == VecTy && "Vector type mismatch");
2233 return V;
2234 }
2235 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2236
2237 // When inserting a smaller vector into the larger to store, we first
2238 // use a shuffle vector to widen it with undef elements, and then
2239 // a second shuffle vector to select between the loaded vector and the
2240 // incoming vector.
2241 SmallVector<Constant*, 8> Mask;
2242 Mask.reserve(VecTy->getNumElements());
2243 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2244 if (i >= BeginIndex && i < EndIndex)
2245 Mask.push_back(IRB.getInt32(i - BeginIndex));
2246 else
2247 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2248 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2249 ConstantVector::get(Mask),
2250 Name + ".expand");
2251 DEBUG(dbgs() << " shuffle1: " << *V << "\n");
2252
2253 Mask.clear();
2254 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2255 if (i >= BeginIndex && i < EndIndex)
2256 Mask.push_back(IRB.getInt32(i));
2257 else
2258 Mask.push_back(IRB.getInt32(i + VecTy->getNumElements()));
2259 V = IRB.CreateShuffleVector(V, Old, ConstantVector::get(Mask),
2260 Name + "insert");
2261 DEBUG(dbgs() << " shuffle2: " << *V << "\n");
2262 return V;
2263}
2264
Chandler Carruth713aa942012-09-14 09:22:59 +00002265namespace {
2266/// \brief Visitor to rewrite instructions using a partition of an alloca to
2267/// use a new alloca.
2268///
2269/// Also implements the rewriting to vector-based accesses when the partition
2270/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2271/// lives here.
2272class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
2273 bool> {
2274 // Befriend the base class so it can delegate to private visit methods.
2275 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
2276
Micah Villmow3574eca2012-10-08 16:38:25 +00002277 const DataLayout &TD;
Chandler Carruth713aa942012-09-14 09:22:59 +00002278 AllocaPartitioning &P;
2279 SROA &Pass;
2280 AllocaInst &OldAI, &NewAI;
2281 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth520eeae2012-10-13 02:41:05 +00002282 Type *NewAllocaTy;
Chandler Carruth713aa942012-09-14 09:22:59 +00002283
2284 // If we are rewriting an alloca partition which can be written as pure
2285 // vector operations, we stash extra information here. When VecTy is
2286 // non-null, we have some strict guarantees about the rewriten alloca:
2287 // - The new alloca is exactly the size of the vector type here.
2288 // - The accesses all either map to the entire vector or to a single
2289 // element.
2290 // - The set of accessing instructions is only one of those handled above
2291 // in isVectorPromotionViable. Generally these are the same access kinds
2292 // which are promotable via mem2reg.
2293 VectorType *VecTy;
2294 Type *ElementTy;
2295 uint64_t ElementSize;
2296
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002297 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002298 // alloca's integer operations should be widened to this integer type due to
2299 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002300 // integer type will be stored here for easy access during rewriting.
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002301 IntegerType *IntTy;
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002302
Chandler Carruth713aa942012-09-14 09:22:59 +00002303 // The offset of the partition user currently being rewritten.
2304 uint64_t BeginOffset, EndOffset;
Chandler Carruth77c12702012-10-01 01:49:22 +00002305 Use *OldUse;
Chandler Carruth713aa942012-09-14 09:22:59 +00002306 Instruction *OldPtr;
2307
2308 // The name prefix to use when rewriting instructions for this alloca.
2309 std::string NamePrefix;
2310
2311public:
Micah Villmow3574eca2012-10-08 16:38:25 +00002312 AllocaPartitionRewriter(const DataLayout &TD, AllocaPartitioning &P,
Chandler Carruth713aa942012-09-14 09:22:59 +00002313 AllocaPartitioning::iterator PI,
2314 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
2315 uint64_t NewBeginOffset, uint64_t NewEndOffset)
2316 : TD(TD), P(P), Pass(Pass),
2317 OldAI(OldAI), NewAI(NewAI),
2318 NewAllocaBeginOffset(NewBeginOffset),
2319 NewAllocaEndOffset(NewEndOffset),
Chandler Carruth520eeae2012-10-13 02:41:05 +00002320 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002321 VecTy(), ElementTy(), ElementSize(), IntTy(),
Chandler Carruth713aa942012-09-14 09:22:59 +00002322 BeginOffset(), EndOffset() {
2323 }
2324
2325 /// \brief Visit the users of the alloca partition and rewrite them.
2326 bool visitUsers(AllocaPartitioning::const_use_iterator I,
2327 AllocaPartitioning::const_use_iterator E) {
2328 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
2329 NewAllocaBeginOffset, NewAllocaEndOffset,
2330 I, E)) {
2331 ++NumVectorized;
2332 VecTy = cast<VectorType>(NewAI.getAllocatedType());
2333 ElementTy = VecTy->getElementType();
Nadav Roteme21708e2012-12-18 05:23:31 +00002334 assert((TD.getTypeSizeInBits(VecTy->getScalarType()) % 8) == 0 &&
Chandler Carruth713aa942012-09-14 09:22:59 +00002335 "Only multiple-of-8 sized vector elements are viable");
Nadav Roteme21708e2012-12-18 05:23:31 +00002336 ElementSize = TD.getTypeSizeInBits(VecTy->getScalarType()) / 8;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002337 } else if (isIntegerWideningViable(TD, NewAI.getAllocatedType(),
2338 NewAllocaBeginOffset, P, I, E)) {
2339 IntTy = Type::getIntNTy(NewAI.getContext(),
2340 TD.getTypeSizeInBits(NewAI.getAllocatedType()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002341 }
2342 bool CanSROA = true;
2343 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00002344 if (!I->U)
2345 continue; // Skip dead uses.
Chandler Carruth713aa942012-09-14 09:22:59 +00002346 BeginOffset = I->BeginOffset;
2347 EndOffset = I->EndOffset;
Chandler Carruth77c12702012-10-01 01:49:22 +00002348 OldUse = I->U;
2349 OldPtr = cast<Instruction>(I->U->get());
Chandler Carruth713aa942012-09-14 09:22:59 +00002350 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
Chandler Carruth77c12702012-10-01 01:49:22 +00002351 CanSROA &= visit(cast<Instruction>(I->U->getUser()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002352 }
2353 if (VecTy) {
2354 assert(CanSROA);
2355 VecTy = 0;
2356 ElementTy = 0;
2357 ElementSize = 0;
2358 }
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002359 if (IntTy) {
2360 assert(CanSROA);
2361 IntTy = 0;
2362 }
Chandler Carruth713aa942012-09-14 09:22:59 +00002363 return CanSROA;
2364 }
2365
2366private:
2367 // Every instruction which can end up as a user must have a rewrite rule.
2368 bool visitInstruction(Instruction &I) {
2369 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2370 llvm_unreachable("No rewrite rule for this instruction!");
2371 }
2372
2373 Twine getName(const Twine &Suffix) {
2374 return NamePrefix + Suffix;
2375 }
2376
2377 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
2378 assert(BeginOffset >= NewAllocaBeginOffset);
Chandler Carruth426c2bf2012-11-01 09:14:31 +00002379 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002380 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
2381 }
2382
Chandler Carruthf710fb12012-10-03 08:14:02 +00002383 /// \brief Compute suitable alignment to access an offset into the new alloca.
2384 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth673850a2012-10-01 12:16:54 +00002385 unsigned NewAIAlign = NewAI.getAlignment();
2386 if (!NewAIAlign)
2387 NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
2388 return MinAlign(NewAIAlign, Offset);
2389 }
Chandler Carruthf710fb12012-10-03 08:14:02 +00002390
2391 /// \brief Compute suitable alignment to access this partition of the new
2392 /// alloca.
2393 unsigned getPartitionAlign() {
2394 return getOffsetAlign(BeginOffset - NewAllocaBeginOffset);
Chandler Carruth673850a2012-10-01 12:16:54 +00002395 }
2396
Chandler Carruthf710fb12012-10-03 08:14:02 +00002397 /// \brief Compute suitable alignment to access a type at an offset of the
2398 /// new alloca.
2399 ///
2400 /// \returns zero if the type's ABI alignment is a suitable alignment,
2401 /// otherwise returns the maximal suitable alignment.
2402 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2403 unsigned Align = getOffsetAlign(Offset);
2404 return Align == TD.getABITypeAlignment(Ty) ? 0 : Align;
2405 }
2406
2407 /// \brief Compute suitable alignment to access a type at the beginning of
2408 /// this partition of the new alloca.
2409 ///
2410 /// See \c getOffsetTypeAlign for details; this routine delegates to it.
2411 unsigned getPartitionTypeAlign(Type *Ty) {
2412 return getOffsetTypeAlign(Ty, BeginOffset - NewAllocaBeginOffset);
Chandler Carruth673850a2012-10-01 12:16:54 +00002413 }
2414
Chandler Carruth07df7652012-11-21 08:16:30 +00002415 unsigned getIndex(uint64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002416 assert(VecTy && "Can only call getIndex when rewriting a vector");
2417 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2418 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2419 uint32_t Index = RelOffset / ElementSize;
2420 assert(Index * ElementSize == RelOffset);
Chandler Carruth07df7652012-11-21 08:16:30 +00002421 return Index;
Chandler Carruth713aa942012-09-14 09:22:59 +00002422 }
2423
2424 void deleteIfTriviallyDead(Value *V) {
2425 Instruction *I = cast<Instruction>(V);
2426 if (isInstructionTriviallyDead(I))
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002427 Pass.DeadInsts.insert(I);
Chandler Carruth713aa942012-09-14 09:22:59 +00002428 }
2429
Chandler Carruth8ab1efd2012-12-17 12:50:21 +00002430 Value *rewriteVectorizedLoadInst(IRBuilder<> &IRB) {
2431 unsigned BeginIndex = getIndex(BeginOffset);
2432 unsigned EndIndex = getIndex(EndOffset);
2433 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruth5c531eb2012-12-17 13:07:30 +00002434
2435 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2436 getName(".load"));
2437 return extractVector(IRB, V, BeginIndex, EndIndex, getName(".vec"));
Chandler Carruth8ab1efd2012-12-17 12:50:21 +00002438 }
2439
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002440 Value *rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002441 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002442 assert(!LI.isVolatile());
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002443 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2444 getName(".load"));
2445 V = convertValue(TD, IRB, V, IntTy);
2446 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2447 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002448 if (Offset > 0 || EndOffset < NewAllocaEndOffset)
2449 V = extractInteger(TD, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2450 getName(".extract"));
2451 return V;
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002452 }
2453
Chandler Carruth713aa942012-09-14 09:22:59 +00002454 bool visitLoadInst(LoadInst &LI) {
2455 DEBUG(dbgs() << " original: " << LI << "\n");
2456 Value *OldOp = LI.getOperand(0);
2457 assert(OldOp == OldPtr);
2458 IRBuilder<> IRB(&LI);
2459
Chandler Carrutha2b88162012-10-25 04:37:07 +00002460 uint64_t Size = EndOffset - BeginOffset;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002461 bool IsSplitIntLoad = Size < TD.getTypeStoreSize(LI.getType());
Chandler Carruth17679292012-11-20 10:02:19 +00002462
2463 // If this memory access can be shown to *statically* extend outside the
2464 // bounds of the original allocation it's behavior is undefined. Rather
2465 // than trying to transform it, just replace it with undef.
2466 // FIXME: We should do something more clever for functions being
2467 // instrumented by asan.
2468 // FIXME: Eventually, once ASan and friends can flush out bugs here, this
2469 // should be transformed to a load of null making it unreachable.
2470 uint64_t OldAllocSize = TD.getTypeAllocSize(OldAI.getAllocatedType());
2471 if (TD.getTypeStoreSize(LI.getType()) > OldAllocSize) {
2472 LI.replaceAllUsesWith(UndefValue::get(LI.getType()));
2473 Pass.DeadInsts.insert(&LI);
2474 deleteIfTriviallyDead(OldOp);
2475 DEBUG(dbgs() << " to: undef!!\n");
2476 return true;
2477 }
2478
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002479 Type *TargetTy = IsSplitIntLoad ? Type::getIntNTy(LI.getContext(), Size * 8)
2480 : LI.getType();
2481 bool IsPtrAdjusted = false;
2482 Value *V;
2483 if (VecTy) {
Chandler Carruth8ab1efd2012-12-17 12:50:21 +00002484 V = rewriteVectorizedLoadInst(IRB);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002485 } else if (IntTy && LI.getType()->isIntegerTy()) {
2486 V = rewriteIntegerLoad(IRB, LI);
2487 } else if (BeginOffset == NewAllocaBeginOffset &&
2488 canConvertValue(TD, NewAllocaTy, LI.getType())) {
2489 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2490 LI.isVolatile(), getName(".load"));
2491 } else {
2492 Type *LTy = TargetTy->getPointerTo();
2493 V = IRB.CreateAlignedLoad(getAdjustedAllocaPtr(IRB, LTy),
2494 getPartitionTypeAlign(TargetTy),
2495 LI.isVolatile(), getName(".load"));
2496 IsPtrAdjusted = true;
2497 }
2498 V = convertValue(TD, IRB, V, TargetTy);
2499
2500 if (IsSplitIntLoad) {
Chandler Carrutha2b88162012-10-25 04:37:07 +00002501 assert(!LI.isVolatile());
2502 assert(LI.getType()->isIntegerTy() &&
2503 "Only integer type loads and stores are split");
2504 assert(LI.getType()->getIntegerBitWidth() ==
2505 TD.getTypeStoreSizeInBits(LI.getType()) &&
2506 "Non-byte-multiple bit width");
2507 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth70dace32012-10-30 20:52:40 +00002508 TD.getTypeAllocSizeInBits(OldAI.getAllocatedType()) &&
Chandler Carrutha2b88162012-10-25 04:37:07 +00002509 "Only alloca-wide loads can be split and recomposed");
Chandler Carrutha2b88162012-10-25 04:37:07 +00002510 // Move the insertion point just past the load so that we can refer to it.
2511 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
Chandler Carrutha2b88162012-10-25 04:37:07 +00002512 // Create a placeholder value with the same type as LI to use as the
2513 // basis for the new value. This allows us to replace the uses of LI with
2514 // the computed value, and then replace the placeholder with LI, leaving
2515 // LI only used for this computation.
2516 Value *Placeholder
Jakub Staszak5801ff92012-11-01 01:10:43 +00002517 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carrutha2b88162012-10-25 04:37:07 +00002518 V = insertInteger(TD, IRB, Placeholder, V, BeginOffset,
2519 getName(".insert"));
2520 LI.replaceAllUsesWith(V);
2521 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak5801ff92012-11-01 01:10:43 +00002522 delete Placeholder;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002523 } else {
2524 LI.replaceAllUsesWith(V);
Chandler Carrutha2b88162012-10-25 04:37:07 +00002525 }
2526
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002527 Pass.DeadInsts.insert(&LI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002528 deleteIfTriviallyDead(OldOp);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002529 DEBUG(dbgs() << " to: " << *V << "\n");
2530 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth713aa942012-09-14 09:22:59 +00002531 }
2532
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002533 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, Value *V,
2534 StoreInst &SI, Value *OldOp) {
Chandler Carruth07df7652012-11-21 08:16:30 +00002535 unsigned BeginIndex = getIndex(BeginOffset);
2536 unsigned EndIndex = getIndex(EndOffset);
2537 assert(EndIndex > BeginIndex && "Empty vector!");
2538 unsigned NumElements = EndIndex - BeginIndex;
2539 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2540 Type *PartitionTy
2541 = (NumElements == 1) ? ElementTy
2542 : VectorType::get(ElementTy, NumElements);
2543 if (V->getType() != PartitionTy)
2544 V = convertValue(TD, IRB, V, PartitionTy);
Chandler Carruth07df7652012-11-21 08:16:30 +00002545
Chandler Carruthd6e43972012-12-17 04:07:35 +00002546 // Mix in the existing elements.
Chandler Carruth7f7d2012012-12-17 13:41:21 +00002547 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2548 getName(".load"));
2549 V = insertVector(IRB, Old, V, BeginIndex, getName(".vec"));
Chandler Carruthd6e43972012-12-17 04:07:35 +00002550
Chandler Carruth81b001a2012-09-26 10:27:46 +00002551 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002552 Pass.DeadInsts.insert(&SI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002553
2554 (void)Store;
2555 DEBUG(dbgs() << " to: " << *Store << "\n");
2556 return true;
2557 }
2558
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002559 bool rewriteIntegerStore(IRBuilder<> &IRB, Value *V, StoreInst &SI) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002560 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002561 assert(!SI.isVolatile());
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002562 if (TD.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2563 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2564 getName(".oldload"));
2565 Old = convertValue(TD, IRB, Old, IntTy);
2566 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2567 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2568 V = insertInteger(TD, IRB, Old, SI.getValueOperand(), Offset,
2569 getName(".insert"));
2570 }
2571 V = convertValue(TD, IRB, V, NewAllocaTy);
2572 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002573 Pass.DeadInsts.insert(&SI);
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002574 (void)Store;
2575 DEBUG(dbgs() << " to: " << *Store << "\n");
2576 return true;
2577 }
2578
Chandler Carruth713aa942012-09-14 09:22:59 +00002579 bool visitStoreInst(StoreInst &SI) {
2580 DEBUG(dbgs() << " original: " << SI << "\n");
2581 Value *OldOp = SI.getOperand(1);
2582 assert(OldOp == OldPtr);
2583 IRBuilder<> IRB(&SI);
2584
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002585 Value *V = SI.getValueOperand();
Chandler Carruth520eeae2012-10-13 02:41:05 +00002586
Chandler Carruthb2d98c22012-10-04 12:33:50 +00002587 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2588 // alloca that should be re-examined after promoting this alloca.
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002589 if (V->getType()->isPointerTy())
2590 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthb2d98c22012-10-04 12:33:50 +00002591 Pass.PostPromotionWorklist.insert(AI);
2592
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002593 uint64_t Size = EndOffset - BeginOffset;
2594 if (Size < TD.getTypeStoreSize(V->getType())) {
2595 assert(!SI.isVolatile());
2596 assert(V->getType()->isIntegerTy() &&
2597 "Only integer type loads and stores are split");
2598 assert(V->getType()->getIntegerBitWidth() ==
2599 TD.getTypeStoreSizeInBits(V->getType()) &&
2600 "Non-byte-multiple bit width");
2601 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth19820052012-12-15 09:26:06 +00002602 TD.getTypeAllocSizeInBits(OldAI.getAllocatedType()) &&
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002603 "Only alloca-wide stores can be split and recomposed");
2604 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
2605 V = extractInteger(TD, IRB, V, NarrowTy, BeginOffset,
2606 getName(".extract"));
Chandler Carruth520eeae2012-10-13 02:41:05 +00002607 }
2608
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002609 if (VecTy)
2610 return rewriteVectorizedStoreInst(IRB, V, SI, OldOp);
2611 if (IntTy && V->getType()->isIntegerTy())
2612 return rewriteIntegerStore(IRB, V, SI);
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002613
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002614 StoreInst *NewSI;
2615 if (BeginOffset == NewAllocaBeginOffset &&
2616 canConvertValue(TD, V->getType(), NewAllocaTy)) {
2617 V = convertValue(TD, IRB, V, NewAllocaTy);
2618 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2619 SI.isVolatile());
2620 } else {
2621 Value *NewPtr = getAdjustedAllocaPtr(IRB, V->getType()->getPointerTo());
2622 NewSI = IRB.CreateAlignedStore(V, NewPtr,
2623 getPartitionTypeAlign(V->getType()),
2624 SI.isVolatile());
2625 }
2626 (void)NewSI;
2627 Pass.DeadInsts.insert(&SI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002628 deleteIfTriviallyDead(OldOp);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002629
2630 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2631 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth713aa942012-09-14 09:22:59 +00002632 }
2633
Chandler Carruth225d25d2012-12-17 04:07:30 +00002634 /// \brief Compute an integer value from splatting an i8 across the given
2635 /// number of bytes.
2636 ///
2637 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2638 /// call this routine.
2639 /// FIXME: Heed the abvice above.
2640 ///
2641 /// \param V The i8 value to splat.
2642 /// \param Size The number of bytes in the output (assuming i8 is one byte)
2643 Value *getIntegerSplat(IRBuilder<> &IRB, Value *V, unsigned Size) {
2644 assert(Size > 0 && "Expected a positive number of bytes.");
2645 IntegerType *VTy = cast<IntegerType>(V->getType());
2646 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2647 if (Size == 1)
2648 return V;
2649
2650 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2651 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, getName(".zext")),
2652 ConstantExpr::getUDiv(
2653 Constant::getAllOnesValue(SplatIntTy),
2654 ConstantExpr::getZExt(
2655 Constant::getAllOnesValue(V->getType()),
2656 SplatIntTy)),
2657 getName(".isplat"));
2658 return V;
2659 }
2660
Chandler Carruth17c84ea2012-12-17 04:07:37 +00002661 /// \brief Compute a vector splat for a given element value.
2662 Value *getVectorSplat(IRBuilder<> &IRB, Value *V, unsigned NumElements) {
Benjamin Kramer6c307492013-01-01 19:55:16 +00002663 V = IRB.CreateVectorSplat(NumElements, V, NamePrefix);
Chandler Carruth17c84ea2012-12-17 04:07:37 +00002664 DEBUG(dbgs() << " splat: " << *V << "\n");
2665 return V;
2666 }
2667
Chandler Carruth713aa942012-09-14 09:22:59 +00002668 bool visitMemSetInst(MemSetInst &II) {
2669 DEBUG(dbgs() << " original: " << II << "\n");
2670 IRBuilder<> IRB(&II);
2671 assert(II.getRawDest() == OldPtr);
2672
2673 // If the memset has a variable size, it cannot be split, just adjust the
2674 // pointer to the new alloca.
2675 if (!isa<Constant>(II.getLength())) {
2676 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002677 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthf710fb12012-10-03 08:14:02 +00002678 II.setAlignment(ConstantInt::get(CstTy, getPartitionAlign()));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002679
Chandler Carruth713aa942012-09-14 09:22:59 +00002680 deleteIfTriviallyDead(OldPtr);
2681 return false;
2682 }
2683
2684 // Record this instruction for deletion.
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002685 Pass.DeadInsts.insert(&II);
Chandler Carruth713aa942012-09-14 09:22:59 +00002686
2687 Type *AllocaTy = NewAI.getAllocatedType();
2688 Type *ScalarTy = AllocaTy->getScalarType();
2689
2690 // If this doesn't map cleanly onto the alloca type, and that type isn't
2691 // a single value type, just emit a memset.
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002692 if (!VecTy && !IntTy &&
2693 (BeginOffset != NewAllocaBeginOffset ||
2694 EndOffset != NewAllocaEndOffset ||
2695 !AllocaTy->isSingleValueType() ||
Chandler Carruth17c84ea2012-12-17 04:07:37 +00002696 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)) ||
2697 TD.getTypeSizeInBits(ScalarTy)%8 != 0)) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002698 Type *SizeTy = II.getLength()->getType();
2699 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002700 CallInst *New
2701 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2702 II.getRawDest()->getType()),
Chandler Carruthf710fb12012-10-03 08:14:02 +00002703 II.getValue(), Size, getPartitionAlign(),
Chandler Carruth713aa942012-09-14 09:22:59 +00002704 II.isVolatile());
2705 (void)New;
2706 DEBUG(dbgs() << " to: " << *New << "\n");
2707 return false;
2708 }
2709
2710 // If we can represent this as a simple value, we have to build the actual
2711 // value to store, which requires expanding the byte present in memset to
2712 // a sensible representation for the alloca type. This is essentially
Chandler Carruth17c84ea2012-12-17 04:07:37 +00002713 // splatting the byte to a sufficiently wide integer, splatting it across
2714 // any desired vector width, and bitcasting to the final type.
Benjamin Kramer0ea4c3d2013-01-01 16:13:35 +00002715 Value *V;
Chandler Carruth713aa942012-09-14 09:22:59 +00002716
Chandler Carruth17c84ea2012-12-17 04:07:37 +00002717 if (VecTy) {
2718 // If this is a memset of a vectorized alloca, insert it.
2719 assert(ElementTy == ScalarTy);
Chandler Carruth713aa942012-09-14 09:22:59 +00002720
Chandler Carruth17c84ea2012-12-17 04:07:37 +00002721 unsigned BeginIndex = getIndex(BeginOffset);
2722 unsigned EndIndex = getIndex(EndOffset);
2723 assert(EndIndex > BeginIndex && "Empty vector!");
2724 unsigned NumElements = EndIndex - BeginIndex;
2725 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2726
2727 Value *Splat = getIntegerSplat(IRB, II.getValue(),
2728 TD.getTypeSizeInBits(ElementTy)/8);
Chandler Carruth8bbff232012-12-17 14:03:01 +00002729 Splat = convertValue(TD, IRB, Splat, ElementTy);
2730 if (NumElements > 1)
Chandler Carruth17c84ea2012-12-17 04:07:37 +00002731 Splat = getVectorSplat(IRB, Splat, NumElements);
2732
Chandler Carruth7f7d2012012-12-17 13:41:21 +00002733 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2734 getName(".oldload"));
2735 V = insertVector(IRB, Old, Splat, BeginIndex, getName(".vec"));
Chandler Carruth17c84ea2012-12-17 04:07:37 +00002736 } else if (IntTy) {
2737 // If this is a memset on an alloca where we can widen stores, insert the
2738 // set integer.
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002739 assert(!II.isVolatile());
Chandler Carruth17c84ea2012-12-17 04:07:37 +00002740
Benjamin Kramer0ea4c3d2013-01-01 16:13:35 +00002741 uint64_t Size = EndOffset - BeginOffset;
Chandler Carruth17c84ea2012-12-17 04:07:37 +00002742 V = getIntegerSplat(IRB, II.getValue(), Size);
2743
2744 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2745 EndOffset != NewAllocaBeginOffset)) {
2746 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2747 getName(".oldload"));
2748 Old = convertValue(TD, IRB, Old, IntTy);
2749 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2750 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2751 V = insertInteger(TD, IRB, Old, V, Offset, getName(".insert"));
2752 } else {
2753 assert(V->getType() == IntTy &&
2754 "Wrong type for an alloca wide integer!");
2755 }
Chandler Carruth5814a882012-12-17 13:51:03 +00002756 V = convertValue(TD, IRB, V, AllocaTy);
Chandler Carruth17c84ea2012-12-17 04:07:37 +00002757 } else {
2758 // Established these invariants above.
2759 assert(BeginOffset == NewAllocaBeginOffset);
2760 assert(EndOffset == NewAllocaEndOffset);
2761
2762 V = getIntegerSplat(IRB, II.getValue(),
2763 TD.getTypeSizeInBits(ScalarTy)/8);
Chandler Carruth17c84ea2012-12-17 04:07:37 +00002764 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2765 V = getVectorSplat(IRB, V, AllocaVecTy->getNumElements());
Chandler Carruth5814a882012-12-17 13:51:03 +00002766
2767 V = convertValue(TD, IRB, V, AllocaTy);
Chandler Carruth713aa942012-09-14 09:22:59 +00002768 }
2769
Chandler Carruth5814a882012-12-17 13:51:03 +00002770 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth81b001a2012-09-26 10:27:46 +00002771 II.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +00002772 (void)New;
2773 DEBUG(dbgs() << " to: " << *New << "\n");
2774 return !II.isVolatile();
2775 }
2776
2777 bool visitMemTransferInst(MemTransferInst &II) {
2778 // Rewriting of memory transfer instructions can be a bit tricky. We break
2779 // them into two categories: split intrinsics and unsplit intrinsics.
2780
2781 DEBUG(dbgs() << " original: " << II << "\n");
2782 IRBuilder<> IRB(&II);
2783
2784 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2785 bool IsDest = II.getRawDest() == OldPtr;
2786
2787 const AllocaPartitioning::MemTransferOffsets &MTO
2788 = P.getMemTransferOffsets(II);
2789
Chandler Carruth673850a2012-10-01 12:16:54 +00002790 // Compute the relative offset within the transfer.
Chandler Carruth426c2bf2012-11-01 09:14:31 +00002791 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chandler Carruth673850a2012-10-01 12:16:54 +00002792 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2793 : MTO.SourceBegin));
2794
2795 unsigned Align = II.getAlignment();
2796 if (Align > 1)
2797 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
Chandler Carruthf710fb12012-10-03 08:14:02 +00002798 MinAlign(II.getAlignment(), getPartitionAlign()));
Chandler Carruth673850a2012-10-01 12:16:54 +00002799
Chandler Carruth713aa942012-09-14 09:22:59 +00002800 // For unsplit intrinsics, we simply modify the source and destination
2801 // pointers in place. This isn't just an optimization, it is a matter of
2802 // correctness. With unsplit intrinsics we may be dealing with transfers
2803 // within a single alloca before SROA ran, or with transfers that have
2804 // a variable length. We may also be dealing with memmove instead of
2805 // memcpy, and so simply updating the pointers is the necessary for us to
2806 // update both source and dest of a single call.
2807 if (!MTO.IsSplittable) {
2808 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2809 if (IsDest)
2810 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2811 else
2812 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2813
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002814 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth673850a2012-10-01 12:16:54 +00002815 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002816
Chandler Carruth713aa942012-09-14 09:22:59 +00002817 DEBUG(dbgs() << " to: " << II << "\n");
2818 deleteIfTriviallyDead(OldOp);
2819 return false;
2820 }
2821 // For split transfer intrinsics we have an incredibly useful assurance:
2822 // the source and destination do not reside within the same alloca, and at
2823 // least one of them does not escape. This means that we can replace
2824 // memmove with memcpy, and we don't need to worry about all manner of
2825 // downsides to splitting and transforming the operations.
2826
Chandler Carruth713aa942012-09-14 09:22:59 +00002827 // If this doesn't map cleanly onto the alloca type, and that type isn't
2828 // a single value type, just emit a memcpy.
2829 bool EmitMemCpy
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002830 = !VecTy && !IntTy && (BeginOffset != NewAllocaBeginOffset ||
2831 EndOffset != NewAllocaEndOffset ||
2832 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth713aa942012-09-14 09:22:59 +00002833
2834 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2835 // size hasn't been shrunk based on analysis of the viable range, this is
2836 // a no-op.
2837 if (EmitMemCpy && &OldAI == &NewAI) {
2838 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2839 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2840 // Ensure the start lines up.
2841 assert(BeginOffset == OrigBegin);
Benjamin Kramerd0807692012-09-14 13:08:09 +00002842 (void)OrigBegin;
Chandler Carruth713aa942012-09-14 09:22:59 +00002843
2844 // Rewrite the size as needed.
2845 if (EndOffset != OrigEnd)
2846 II.setLength(ConstantInt::get(II.getLength()->getType(),
2847 EndOffset - BeginOffset));
2848 return false;
2849 }
2850 // Record this instruction for deletion.
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002851 Pass.DeadInsts.insert(&II);
Chandler Carruth713aa942012-09-14 09:22:59 +00002852
Chandler Carruth713aa942012-09-14 09:22:59 +00002853 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2854 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth99a54942012-12-17 14:51:24 +00002855 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth713aa942012-09-14 09:22:59 +00002856 if (AllocaInst *AI
2857 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Chandler Carruthb3dca3f2012-09-26 07:41:40 +00002858 Pass.Worklist.insert(AI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002859
2860 if (EmitMemCpy) {
Chandler Carruth99a54942012-12-17 14:51:24 +00002861 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2862 : II.getRawDest()->getType();
2863
2864 // Compute the other pointer, folding as much as possible to produce
2865 // a single, simple GEP in most cases.
2866 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2867 getName("." + OtherPtr->getName()));
2868
Chandler Carruth713aa942012-09-14 09:22:59 +00002869 Value *OurPtr
2870 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2871 : II.getRawSource()->getType());
2872 Type *SizeTy = II.getLength()->getType();
2873 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2874
2875 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2876 IsDest ? OtherPtr : OurPtr,
Chandler Carruth81b001a2012-09-26 10:27:46 +00002877 Size, Align, II.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +00002878 (void)New;
2879 DEBUG(dbgs() << " to: " << *New << "\n");
2880 return false;
2881 }
2882
Chandler Carruth322e9ba2012-10-03 08:26:28 +00002883 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2884 // is equivalent to 1, but that isn't true if we end up rewriting this as
2885 // a load or store.
2886 if (!Align)
2887 Align = 1;
2888
Chandler Carruth99a54942012-12-17 14:51:24 +00002889 bool IsWholeAlloca = BeginOffset == NewAllocaBeginOffset &&
2890 EndOffset == NewAllocaEndOffset;
2891 uint64_t Size = EndOffset - BeginOffset;
2892 unsigned BeginIndex = VecTy ? getIndex(BeginOffset) : 0;
2893 unsigned EndIndex = VecTy ? getIndex(EndOffset) : 0;
2894 unsigned NumElements = EndIndex - BeginIndex;
2895 IntegerType *SubIntTy
2896 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2897
2898 Type *OtherPtrTy = NewAI.getType();
2899 if (VecTy && !IsWholeAlloca) {
2900 if (NumElements == 1)
2901 OtherPtrTy = VecTy->getElementType();
2902 else
2903 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2904
2905 OtherPtrTy = OtherPtrTy->getPointerTo();
2906 } else if (IntTy && !IsWholeAlloca) {
2907 OtherPtrTy = SubIntTy->getPointerTo();
2908 }
2909
2910 Value *SrcPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2911 getName("." + OtherPtr->getName()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002912 Value *DstPtr = &NewAI;
2913 if (!IsDest)
2914 std::swap(SrcPtr, DstPtr);
2915
2916 Value *Src;
Chandler Carruth99a54942012-12-17 14:51:24 +00002917 if (VecTy && !IsWholeAlloca && !IsDest) {
2918 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2919 getName(".load"));
2920 Src = extractVector(IRB, Src, BeginIndex, EndIndex, getName(".vec"));
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002921 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002922 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2923 getName(".load"));
2924 Src = convertValue(TD, IRB, Src, IntTy);
2925 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2926 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2927 Src = extractInteger(TD, IRB, Src, SubIntTy, Offset, getName(".extract"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002928 } else {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002929 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2930 getName(".copyload"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002931 }
2932
Chandler Carruth99a54942012-12-17 14:51:24 +00002933 if (VecTy && !IsWholeAlloca && IsDest) {
2934 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2935 getName(".oldload"));
2936 Src = insertVector(IRB, Old, Src, BeginIndex, getName(".vec"));
2937 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002938 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2939 getName(".oldload"));
2940 Old = convertValue(TD, IRB, Old, IntTy);
2941 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2942 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2943 Src = insertInteger(TD, IRB, Old, Src, Offset, getName(".insert"));
2944 Src = convertValue(TD, IRB, Src, NewAllocaTy);
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002945 }
2946
Chandler Carruth81b001a2012-09-26 10:27:46 +00002947 StoreInst *Store = cast<StoreInst>(
2948 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2949 (void)Store;
Chandler Carruth713aa942012-09-14 09:22:59 +00002950 DEBUG(dbgs() << " to: " << *Store << "\n");
2951 return !II.isVolatile();
2952 }
2953
2954 bool visitIntrinsicInst(IntrinsicInst &II) {
2955 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2956 II.getIntrinsicID() == Intrinsic::lifetime_end);
2957 DEBUG(dbgs() << " original: " << II << "\n");
2958 IRBuilder<> IRB(&II);
2959 assert(II.getArgOperand(1) == OldPtr);
2960
2961 // Record this instruction for deletion.
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002962 Pass.DeadInsts.insert(&II);
Chandler Carruth713aa942012-09-14 09:22:59 +00002963
2964 ConstantInt *Size
2965 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2966 EndOffset - BeginOffset);
2967 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2968 Value *New;
2969 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2970 New = IRB.CreateLifetimeStart(Ptr, Size);
2971 else
2972 New = IRB.CreateLifetimeEnd(Ptr, Size);
2973
2974 DEBUG(dbgs() << " to: " << *New << "\n");
2975 return true;
2976 }
2977
Chandler Carruth713aa942012-09-14 09:22:59 +00002978 bool visitPHINode(PHINode &PN) {
2979 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002980
Chandler Carruth713aa942012-09-14 09:22:59 +00002981 // We would like to compute a new pointer in only one place, but have it be
2982 // as local as possible to the PHI. To do that, we re-use the location of
2983 // the old pointer, which necessarily must be in the right position to
2984 // dominate the PHI.
2985 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2986
Chandler Carruth713aa942012-09-14 09:22:59 +00002987 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002988 // Replace the operands which were using the old pointer.
Benjamin Kramer2a132422012-10-20 12:04:57 +00002989 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth713aa942012-09-14 09:22:59 +00002990
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002991 DEBUG(dbgs() << " to: " << PN << "\n");
2992 deleteIfTriviallyDead(OldPtr);
2993 return false;
Chandler Carruth713aa942012-09-14 09:22:59 +00002994 }
2995
2996 bool visitSelectInst(SelectInst &SI) {
2997 DEBUG(dbgs() << " original: " << SI << "\n");
2998 IRBuilder<> IRB(&SI);
2999
3000 // Find the operand we need to rewrite here.
3001 bool IsTrueVal = SI.getTrueValue() == OldPtr;
3002 if (IsTrueVal)
3003 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
3004 else
3005 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003006
Chandler Carruth713aa942012-09-14 09:22:59 +00003007 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003008 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
3009 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth713aa942012-09-14 09:22:59 +00003010 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003011 return false;
Chandler Carruth713aa942012-09-14 09:22:59 +00003012 }
3013
3014};
3015}
3016
Chandler Carruthc370acd2012-09-18 12:57:43 +00003017namespace {
3018/// \brief Visitor to rewrite aggregate loads and stores as scalar.
3019///
3020/// This pass aggressively rewrites all aggregate loads and stores on
3021/// a particular pointer (or any pointer derived from it which we can identify)
3022/// with scalar loads and stores.
3023class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3024 // Befriend the base class so it can delegate to private visit methods.
3025 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3026
Micah Villmow3574eca2012-10-08 16:38:25 +00003027 const DataLayout &TD;
Chandler Carruthc370acd2012-09-18 12:57:43 +00003028
3029 /// Queue of pointer uses to analyze and potentially rewrite.
3030 SmallVector<Use *, 8> Queue;
3031
3032 /// Set to prevent us from cycling with phi nodes and loops.
3033 SmallPtrSet<User *, 8> Visited;
3034
3035 /// The current pointer use being rewritten. This is used to dig up the used
3036 /// value (as opposed to the user).
3037 Use *U;
3038
3039public:
Micah Villmow3574eca2012-10-08 16:38:25 +00003040 AggLoadStoreRewriter(const DataLayout &TD) : TD(TD) {}
Chandler Carruthc370acd2012-09-18 12:57:43 +00003041
3042 /// Rewrite loads and stores through a pointer and all pointers derived from
3043 /// it.
3044 bool rewrite(Instruction &I) {
3045 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3046 enqueueUsers(I);
3047 bool Changed = false;
3048 while (!Queue.empty()) {
3049 U = Queue.pop_back_val();
3050 Changed |= visit(cast<Instruction>(U->getUser()));
3051 }
3052 return Changed;
3053 }
3054
3055private:
3056 /// Enqueue all the users of the given instruction for further processing.
3057 /// This uses a set to de-duplicate users.
3058 void enqueueUsers(Instruction &I) {
3059 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3060 ++UI)
3061 if (Visited.insert(*UI))
3062 Queue.push_back(&UI.getUse());
3063 }
3064
3065 // Conservative default is to not rewrite anything.
3066 bool visitInstruction(Instruction &I) { return false; }
3067
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003068 /// \brief Generic recursive split emission class.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003069 template <typename Derived>
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003070 class OpSplitter {
3071 protected:
3072 /// The builder used to form new instructions.
3073 IRBuilder<> IRB;
3074 /// The indices which to be used with insert- or extractvalue to select the
3075 /// appropriate value within the aggregate.
3076 SmallVector<unsigned, 4> Indices;
3077 /// The indices to a GEP instruction which will move Ptr to the correct slot
3078 /// within the aggregate.
3079 SmallVector<Value *, 4> GEPIndices;
3080 /// The base pointer of the original op, used as a base for GEPing the
3081 /// split operations.
3082 Value *Ptr;
Chandler Carruthc370acd2012-09-18 12:57:43 +00003083
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003084 /// Initialize the splitter with an insertion point, Ptr and start with a
3085 /// single zero GEP index.
3086 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003087 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003088
3089 public:
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003090 /// \brief Generic recursive split emission routine.
3091 ///
3092 /// This method recursively splits an aggregate op (load or store) into
3093 /// scalar or vector ops. It splits recursively until it hits a single value
3094 /// and emits that single value operation via the template argument.
3095 ///
3096 /// The logic of this routine relies on GEPs and insertvalue and
3097 /// extractvalue all operating with the same fundamental index list, merely
3098 /// formatted differently (GEPs need actual values).
3099 ///
3100 /// \param Ty The type being split recursively into smaller ops.
3101 /// \param Agg The aggregate value being built up or stored, depending on
3102 /// whether this is splitting a load or a store respectively.
3103 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3104 if (Ty->isSingleValueType())
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003105 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003106
3107 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3108 unsigned OldSize = Indices.size();
3109 (void)OldSize;
3110 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3111 ++Idx) {
3112 assert(Indices.size() == OldSize && "Did not return to the old size");
3113 Indices.push_back(Idx);
3114 GEPIndices.push_back(IRB.getInt32(Idx));
3115 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3116 GEPIndices.pop_back();
3117 Indices.pop_back();
3118 }
3119 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00003120 }
Chandler Carruthc370acd2012-09-18 12:57:43 +00003121
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003122 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3123 unsigned OldSize = Indices.size();
3124 (void)OldSize;
3125 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3126 ++Idx) {
3127 assert(Indices.size() == OldSize && "Did not return to the old size");
3128 Indices.push_back(Idx);
3129 GEPIndices.push_back(IRB.getInt32(Idx));
3130 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3131 GEPIndices.pop_back();
3132 Indices.pop_back();
3133 }
3134 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00003135 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003136
3137 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruthc370acd2012-09-18 12:57:43 +00003138 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003139 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00003140
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003141 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003142 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00003143 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruthc370acd2012-09-18 12:57:43 +00003144
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003145 /// Emit a leaf load of a single value. This is called at the leaves of the
3146 /// recursive emission to actually load values.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003147 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003148 assert(Ty->isSingleValueType());
3149 // Load the single value and insert it using the indices.
3150 Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices,
3151 Name + ".gep"),
3152 Name + ".load");
3153 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3154 DEBUG(dbgs() << " to: " << *Load << "\n");
3155 }
3156 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00003157
3158 bool visitLoadInst(LoadInst &LI) {
3159 assert(LI.getPointerOperand() == *U);
3160 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3161 return false;
3162
3163 // We have an aggregate being loaded, split it apart.
3164 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003165 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruthc370acd2012-09-18 12:57:43 +00003166 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003167 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00003168 LI.replaceAllUsesWith(V);
3169 LI.eraseFromParent();
3170 return true;
3171 }
3172
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003173 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003174 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00003175 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003176
3177 /// Emit a leaf store of a single value. This is called at the leaves of the
3178 /// recursive emission to actually produce stores.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003179 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003180 assert(Ty->isSingleValueType());
3181 // Extract the single value and store it using the indices.
3182 Value *Store = IRB.CreateStore(
3183 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3184 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
3185 (void)Store;
3186 DEBUG(dbgs() << " to: " << *Store << "\n");
3187 }
3188 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00003189
3190 bool visitStoreInst(StoreInst &SI) {
3191 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3192 return false;
3193 Value *V = SI.getValueOperand();
3194 if (V->getType()->isSingleValueType())
3195 return false;
3196
3197 // We have an aggregate being stored, split it apart.
3198 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003199 StoreOpSplitter Splitter(&SI, *U);
3200 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00003201 SI.eraseFromParent();
3202 return true;
3203 }
3204
3205 bool visitBitCastInst(BitCastInst &BC) {
3206 enqueueUsers(BC);
3207 return false;
3208 }
3209
3210 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3211 enqueueUsers(GEPI);
3212 return false;
3213 }
3214
3215 bool visitPHINode(PHINode &PN) {
3216 enqueueUsers(PN);
3217 return false;
3218 }
3219
3220 bool visitSelectInst(SelectInst &SI) {
3221 enqueueUsers(SI);
3222 return false;
3223 }
3224};
3225}
3226
Chandler Carruth07525a62012-10-13 10:49:33 +00003227/// \brief Strip aggregate type wrapping.
3228///
3229/// This removes no-op aggregate types wrapping an underlying type. It will
3230/// strip as many layers of types as it can without changing either the type
3231/// size or the allocated size.
3232static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3233 if (Ty->isSingleValueType())
3234 return Ty;
3235
3236 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3237 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3238
3239 Type *InnerTy;
3240 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3241 InnerTy = ArrTy->getElementType();
3242 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3243 const StructLayout *SL = DL.getStructLayout(STy);
3244 unsigned Index = SL->getElementContainingOffset(0);
3245 InnerTy = STy->getElementType(Index);
3246 } else {
3247 return Ty;
3248 }
3249
3250 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3251 TypeSize > DL.getTypeSizeInBits(InnerTy))
3252 return Ty;
3253
3254 return stripAggregateTypeWrapping(DL, InnerTy);
3255}
3256
Chandler Carruth713aa942012-09-14 09:22:59 +00003257/// \brief Try to find a partition of the aggregate type passed in for a given
3258/// offset and size.
3259///
3260/// This recurses through the aggregate type and tries to compute a subtype
3261/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth6b547a22012-09-14 11:08:31 +00003262/// of an array, it will even compute a new array type for that sub-section,
3263/// and the same for structs.
3264///
3265/// Note that this routine is very strict and tries to find a partition of the
3266/// type which produces the *exact* right offset and size. It is not forgiving
3267/// when the size or offset cause either end of type-based partition to be off.
3268/// Also, this is a best-effort routine. It is reasonable to give up and not
3269/// return a type if necessary.
Micah Villmow3574eca2012-10-08 16:38:25 +00003270static Type *getTypePartition(const DataLayout &TD, Type *Ty,
Chandler Carruth713aa942012-09-14 09:22:59 +00003271 uint64_t Offset, uint64_t Size) {
3272 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
Chandler Carruth07525a62012-10-13 10:49:33 +00003273 return stripAggregateTypeWrapping(TD, Ty);
Chandler Carrutha2b88162012-10-25 04:37:07 +00003274 if (Offset > TD.getTypeAllocSize(Ty) ||
3275 (TD.getTypeAllocSize(Ty) - Offset) < Size)
3276 return 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00003277
3278 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3279 // We can't partition pointers...
3280 if (SeqTy->isPointerTy())
3281 return 0;
3282
3283 Type *ElementTy = SeqTy->getElementType();
3284 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3285 uint64_t NumSkippedElements = Offset / ElementSize;
3286 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
3287 if (NumSkippedElements >= ArrTy->getNumElements())
3288 return 0;
3289 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
3290 if (NumSkippedElements >= VecTy->getNumElements())
3291 return 0;
3292 Offset -= NumSkippedElements * ElementSize;
3293
3294 // First check if we need to recurse.
3295 if (Offset > 0 || Size < ElementSize) {
3296 // Bail if the partition ends in a different array element.
3297 if ((Offset + Size) > ElementSize)
3298 return 0;
3299 // Recurse through the element type trying to peel off offset bytes.
3300 return getTypePartition(TD, ElementTy, Offset, Size);
3301 }
3302 assert(Offset == 0);
3303
3304 if (Size == ElementSize)
Chandler Carruth07525a62012-10-13 10:49:33 +00003305 return stripAggregateTypeWrapping(TD, ElementTy);
Chandler Carruth713aa942012-09-14 09:22:59 +00003306 assert(Size > ElementSize);
3307 uint64_t NumElements = Size / ElementSize;
3308 if (NumElements * ElementSize != Size)
3309 return 0;
3310 return ArrayType::get(ElementTy, NumElements);
3311 }
3312
3313 StructType *STy = dyn_cast<StructType>(Ty);
3314 if (!STy)
3315 return 0;
3316
3317 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00003318 if (Offset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00003319 return 0;
3320 uint64_t EndOffset = Offset + Size;
3321 if (EndOffset > SL->getSizeInBytes())
3322 return 0;
3323
3324 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +00003325 Offset -= SL->getElementOffset(Index);
3326
3327 Type *ElementTy = STy->getElementType(Index);
3328 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3329 if (Offset >= ElementSize)
3330 return 0; // The offset points into alignment padding.
3331
3332 // See if any partition must be contained by the element.
3333 if (Offset > 0 || Size < ElementSize) {
3334 if ((Offset + Size) > ElementSize)
3335 return 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00003336 return getTypePartition(TD, ElementTy, Offset, Size);
3337 }
3338 assert(Offset == 0);
3339
3340 if (Size == ElementSize)
Chandler Carruth07525a62012-10-13 10:49:33 +00003341 return stripAggregateTypeWrapping(TD, ElementTy);
Chandler Carruth713aa942012-09-14 09:22:59 +00003342
3343 StructType::element_iterator EI = STy->element_begin() + Index,
3344 EE = STy->element_end();
3345 if (EndOffset < SL->getSizeInBytes()) {
3346 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3347 if (Index == EndIndex)
3348 return 0; // Within a single element and its padding.
Chandler Carruth6b547a22012-09-14 11:08:31 +00003349
3350 // Don't try to form "natural" types if the elements don't line up with the
3351 // expected size.
3352 // FIXME: We could potentially recurse down through the last element in the
3353 // sub-struct to find a natural end point.
3354 if (SL->getElementOffset(EndIndex) != EndOffset)
3355 return 0;
3356
Chandler Carruth713aa942012-09-14 09:22:59 +00003357 assert(Index < EndIndex);
Chandler Carruth713aa942012-09-14 09:22:59 +00003358 EE = STy->element_begin() + EndIndex;
3359 }
3360
3361 // Try to build up a sub-structure.
Benjamin Kramer2a132422012-10-20 12:04:57 +00003362 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth713aa942012-09-14 09:22:59 +00003363 STy->isPacked());
3364 const StructLayout *SubSL = TD.getStructLayout(SubTy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00003365 if (Size != SubSL->getSizeInBytes())
3366 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth713aa942012-09-14 09:22:59 +00003367
Chandler Carruth6b547a22012-09-14 11:08:31 +00003368 return SubTy;
Chandler Carruth713aa942012-09-14 09:22:59 +00003369}
3370
3371/// \brief Rewrite an alloca partition's users.
3372///
3373/// This routine drives both of the rewriting goals of the SROA pass. It tries
3374/// to rewrite uses of an alloca partition to be conducive for SSA value
3375/// promotion. If the partition needs a new, more refined alloca, this will
3376/// build that new alloca, preserving as much type information as possible, and
3377/// rewrite the uses of the old alloca to point at the new one and have the
3378/// appropriate new offsets. It also evaluates how successful the rewrite was
3379/// at enabling promotion and if it was successful queues the alloca to be
3380/// promoted.
3381bool SROA::rewriteAllocaPartition(AllocaInst &AI,
3382 AllocaPartitioning &P,
3383 AllocaPartitioning::iterator PI) {
3384 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
Chandler Carruthfdb15852012-10-02 18:57:13 +00003385 bool IsLive = false;
3386 for (AllocaPartitioning::use_iterator UI = P.use_begin(PI),
3387 UE = P.use_end(PI);
3388 UI != UE && !IsLive; ++UI)
3389 if (UI->U)
3390 IsLive = true;
3391 if (!IsLive)
Chandler Carruth713aa942012-09-14 09:22:59 +00003392 return false; // No live uses left of this partition.
3393
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003394 DEBUG(dbgs() << "Speculating PHIs and selects in partition "
3395 << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
3396
3397 PHIOrSelectSpeculator Speculator(*TD, P, *this);
3398 DEBUG(dbgs() << " speculating ");
3399 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carrutha346f462012-10-02 17:49:47 +00003400 Speculator.visitUsers(PI);
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003401
Chandler Carruth713aa942012-09-14 09:22:59 +00003402 // Try to compute a friendly type for this partition of the alloca. This
3403 // won't always succeed, in which case we fall back to a legal integer type
3404 // or an i8 array of an appropriate size.
3405 Type *AllocaTy = 0;
3406 if (Type *PartitionTy = P.getCommonType(PI))
3407 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
3408 AllocaTy = PartitionTy;
3409 if (!AllocaTy)
3410 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3411 PI->BeginOffset, AllocaSize))
3412 AllocaTy = PartitionTy;
3413 if ((!AllocaTy ||
3414 (AllocaTy->isArrayTy() &&
3415 AllocaTy->getArrayElementType()->isIntegerTy())) &&
3416 TD->isLegalInteger(AllocaSize * 8))
3417 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
3418 if (!AllocaTy)
3419 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
Chandler Carruthb3dd9a12012-09-14 10:26:34 +00003420 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00003421
3422 // Check for the case where we're going to rewrite to a new alloca of the
3423 // exact same type as the original, and with the same access offsets. In that
3424 // case, re-use the existing alloca, but still run through the rewriter to
3425 // performe phi and select speculation.
3426 AllocaInst *NewAI;
3427 if (AllocaTy == AI.getAllocatedType()) {
3428 assert(PI->BeginOffset == 0 &&
3429 "Non-zero begin offset but same alloca type");
3430 assert(PI == P.begin() && "Begin offset is zero on later partition");
3431 NewAI = &AI;
3432 } else {
Chandler Carruthb67c9a52012-09-29 10:41:21 +00003433 unsigned Alignment = AI.getAlignment();
3434 if (!Alignment) {
3435 // The minimum alignment which users can rely on when the explicit
3436 // alignment is omitted or zero is that required by the ABI for this
3437 // type.
3438 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3439 }
3440 Alignment = MinAlign(Alignment, PI->BeginOffset);
3441 // If we will get at least this much alignment from the type alone, leave
3442 // the alloca's alignment unconstrained.
3443 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3444 Alignment = 0;
3445 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
Chandler Carruth713aa942012-09-14 09:22:59 +00003446 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3447 &AI);
3448 ++NumNewAllocas;
3449 }
3450
3451 DEBUG(dbgs() << "Rewriting alloca partition "
3452 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3453 << *NewAI << "\n");
3454
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003455 // Track the high watermark of the post-promotion worklist. We will reset it
3456 // to this point if the alloca is not in fact scheduled for promotion.
3457 unsigned PPWOldSize = PostPromotionWorklist.size();
3458
Chandler Carruth713aa942012-09-14 09:22:59 +00003459 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3460 PI->BeginOffset, PI->EndOffset);
3461 DEBUG(dbgs() << " rewriting ");
3462 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003463 bool Promotable = Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI));
3464 if (Promotable) {
Chandler Carruth713aa942012-09-14 09:22:59 +00003465 DEBUG(dbgs() << " and queuing for promotion\n");
3466 PromotableAllocas.push_back(NewAI);
3467 } else if (NewAI != &AI) {
3468 // If we can't promote the alloca, iterate on it to check for new
3469 // refinements exposed by splitting the current alloca. Don't iterate on an
3470 // alloca which didn't actually change and didn't get promoted.
3471 Worklist.insert(NewAI);
3472 }
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003473
3474 // Drop any post-promotion work items if promotion didn't happen.
3475 if (!Promotable)
3476 while (PostPromotionWorklist.size() > PPWOldSize)
3477 PostPromotionWorklist.pop_back();
3478
Chandler Carruth713aa942012-09-14 09:22:59 +00003479 return true;
3480}
3481
3482/// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3483bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3484 bool Changed = false;
3485 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3486 ++PI)
3487 Changed |= rewriteAllocaPartition(AI, P, PI);
3488
3489 return Changed;
3490}
3491
3492/// \brief Analyze an alloca for SROA.
3493///
3494/// This analyzes the alloca to ensure we can reason about it, builds
3495/// a partitioning of the alloca, and then hands it off to be split and
3496/// rewritten as needed.
3497bool SROA::runOnAlloca(AllocaInst &AI) {
3498 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3499 ++NumAllocasAnalyzed;
3500
3501 // Special case dead allocas, as they're trivial.
3502 if (AI.use_empty()) {
3503 AI.eraseFromParent();
3504 return true;
3505 }
3506
3507 // Skip alloca forms that this analysis can't handle.
3508 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3509 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3510 return false;
3511
Chandler Carruthc370acd2012-09-18 12:57:43 +00003512 bool Changed = false;
3513
3514 // First, split any FCA loads and stores touching this alloca to promote
3515 // better splitting and promotion opportunities.
3516 AggLoadStoreRewriter AggRewriter(*TD);
3517 Changed |= AggRewriter.rewrite(AI);
3518
Chandler Carruth713aa942012-09-14 09:22:59 +00003519 // Build the partition set using a recursive instruction-visiting builder.
3520 AllocaPartitioning P(*TD, AI);
3521 DEBUG(P.print(dbgs()));
3522 if (P.isEscaped())
Chandler Carruthc370acd2012-09-18 12:57:43 +00003523 return Changed;
Chandler Carruth713aa942012-09-14 09:22:59 +00003524
Chandler Carruth713aa942012-09-14 09:22:59 +00003525 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth713aa942012-09-14 09:22:59 +00003526 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3527 DE = P.dead_user_end();
3528 DI != DE; ++DI) {
3529 Changed = true;
3530 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
Chandler Carruthf5837aa2012-11-20 01:12:50 +00003531 DeadInsts.insert(*DI);
Chandler Carruth713aa942012-09-14 09:22:59 +00003532 }
3533 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3534 DE = P.dead_op_end();
3535 DO != DE; ++DO) {
3536 Value *OldV = **DO;
3537 // Clobber the use with an undef value.
3538 **DO = UndefValue::get(OldV->getType());
3539 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3540 if (isInstructionTriviallyDead(OldI)) {
3541 Changed = true;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00003542 DeadInsts.insert(OldI);
Chandler Carruth713aa942012-09-14 09:22:59 +00003543 }
3544 }
3545
Chandler Carruthfca3f402012-10-05 01:29:09 +00003546 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3547 if (P.begin() == P.end())
3548 return Changed;
3549
Chandler Carruth713aa942012-09-14 09:22:59 +00003550 return splitAlloca(AI, P) || Changed;
3551}
3552
Chandler Carruth8615cd22012-09-14 10:26:38 +00003553/// \brief Delete the dead instructions accumulated in this run.
3554///
3555/// Recursively deletes the dead instructions we've accumulated. This is done
3556/// at the very end to maximize locality of the recursive delete and to
3557/// minimize the problems of invalidated instruction pointers as such pointers
3558/// are used heavily in the intermediate stages of the algorithm.
3559///
3560/// We also record the alloca instructions deleted here so that they aren't
3561/// subsequently handed to mem2reg to promote.
3562void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth713aa942012-09-14 09:22:59 +00003563 while (!DeadInsts.empty()) {
3564 Instruction *I = DeadInsts.pop_back_val();
3565 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3566
Chandler Carrutha2b88162012-10-25 04:37:07 +00003567 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3568
Chandler Carruth713aa942012-09-14 09:22:59 +00003569 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3570 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3571 // Zero out the operand and see if it becomes trivially dead.
3572 *OI = 0;
3573 if (isInstructionTriviallyDead(U))
Chandler Carruthf5837aa2012-11-20 01:12:50 +00003574 DeadInsts.insert(U);
Chandler Carruth713aa942012-09-14 09:22:59 +00003575 }
3576
3577 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3578 DeletedAllocas.insert(AI);
3579
3580 ++NumDeleted;
3581 I->eraseFromParent();
3582 }
3583}
3584
Chandler Carruth1c8db502012-09-15 11:43:14 +00003585/// \brief Promote the allocas, using the best available technique.
3586///
3587/// This attempts to promote whatever allocas have been identified as viable in
3588/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3589/// If there is a domtree available, we attempt to promote using the full power
3590/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3591/// based on the SSAUpdater utilities. This function returns whether any
3592/// promotion occured.
3593bool SROA::promoteAllocas(Function &F) {
3594 if (PromotableAllocas.empty())
3595 return false;
3596
3597 NumPromoted += PromotableAllocas.size();
3598
3599 if (DT && !ForceSSAUpdater) {
3600 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3601 PromoteMemToReg(PromotableAllocas, *DT);
3602 PromotableAllocas.clear();
3603 return true;
3604 }
3605
3606 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3607 SSAUpdater SSA;
3608 DIBuilder DIB(*F.getParent());
3609 SmallVector<Instruction*, 64> Insts;
3610
3611 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3612 AllocaInst *AI = PromotableAllocas[Idx];
3613 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3614 UI != UE;) {
3615 Instruction *I = cast<Instruction>(*UI++);
3616 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3617 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3618 // leading to them) here. Eventually it should use them to optimize the
3619 // scalar values produced.
3620 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3621 assert(onlyUsedByLifetimeMarkers(I) &&
3622 "Found a bitcast used outside of a lifetime marker.");
3623 while (!I->use_empty())
3624 cast<Instruction>(*I->use_begin())->eraseFromParent();
3625 I->eraseFromParent();
3626 continue;
3627 }
3628 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3629 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3630 II->getIntrinsicID() == Intrinsic::lifetime_end);
3631 II->eraseFromParent();
3632 continue;
3633 }
3634
3635 Insts.push_back(I);
3636 }
3637 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3638 Insts.clear();
3639 }
3640
3641 PromotableAllocas.clear();
3642 return true;
3643}
3644
Chandler Carruth713aa942012-09-14 09:22:59 +00003645namespace {
3646 /// \brief A predicate to test whether an alloca belongs to a set.
3647 class IsAllocaInSet {
3648 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3649 const SetType &Set;
3650
3651 public:
Chandler Carruth75eac5f2012-10-03 00:03:00 +00003652 typedef AllocaInst *argument_type;
3653
Chandler Carruth713aa942012-09-14 09:22:59 +00003654 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth75eac5f2012-10-03 00:03:00 +00003655 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth713aa942012-09-14 09:22:59 +00003656 };
3657}
3658
3659bool SROA::runOnFunction(Function &F) {
3660 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3661 C = &F.getContext();
Micah Villmow3574eca2012-10-08 16:38:25 +00003662 TD = getAnalysisIfAvailable<DataLayout>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003663 if (!TD) {
3664 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3665 return false;
3666 }
Chandler Carruth1c8db502012-09-15 11:43:14 +00003667 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003668
3669 BasicBlock &EntryBB = F.getEntryBlock();
3670 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3671 I != E; ++I)
3672 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3673 Worklist.insert(AI);
3674
3675 bool Changed = false;
Chandler Carruth8615cd22012-09-14 10:26:38 +00003676 // A set of deleted alloca instruction pointers which should be removed from
3677 // the list of promotable allocas.
3678 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3679
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003680 do {
3681 while (!Worklist.empty()) {
3682 Changed |= runOnAlloca(*Worklist.pop_back_val());
3683 deleteDeadInstructions(DeletedAllocas);
Chandler Carruth5c5b3cf2012-10-02 22:46:45 +00003684
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003685 // Remove the deleted allocas from various lists so that we don't try to
3686 // continue processing them.
3687 if (!DeletedAllocas.empty()) {
3688 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3689 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3690 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3691 PromotableAllocas.end(),
3692 IsAllocaInSet(DeletedAllocas)),
3693 PromotableAllocas.end());
3694 DeletedAllocas.clear();
3695 }
Chandler Carruth713aa942012-09-14 09:22:59 +00003696 }
Chandler Carruth713aa942012-09-14 09:22:59 +00003697
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003698 Changed |= promoteAllocas(F);
3699
3700 Worklist = PostPromotionWorklist;
3701 PostPromotionWorklist.clear();
3702 } while (!Worklist.empty());
Chandler Carruth713aa942012-09-14 09:22:59 +00003703
3704 return Changed;
3705}
3706
3707void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth1c8db502012-09-15 11:43:14 +00003708 if (RequiresDomTree)
3709 AU.addRequired<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003710 AU.setPreservesCFG();
3711}