blob: 8231c8b2dfa276931af25ac608803386dd2f7697 [file] [log] [blame]
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This transformation implements the well known scalar replacement of
11/// aggregates transformation. It tries to identify promotable elements of an
12/// aggregate alloca, and promote them to registers. It will also try to
13/// convert uses of an element (or set of elements) of an alloca into a vector
14/// or bitfield-style integer scalar if appropriate.
15///
16/// It works to do this with minimal slicing of the alloca so that regions
17/// which are merely transferred in and out of external memory remain unchanged
18/// and are not decomposed to scalar code.
19///
20/// Because this also performs alloca promotion, it can be thought of as also
21/// serving the purpose of SSA formation. The algorithm iterates on the
22/// function until all opportunities for promotion have been realized.
23///
24//===----------------------------------------------------------------------===//
25
26#define DEBUG_TYPE "sroa"
27#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SetVector.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/Analysis/Dominators.h"
33#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000034#include "llvm/Analysis/PtrUseVisitor.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000036#include "llvm/DIBuilder.h"
37#include "llvm/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Constants.h"
39#include "llvm/IR/DataLayout.h"
40#include "llvm/IR/DerivedTypes.h"
41#include "llvm/IR/Function.h"
42#include "llvm/IR/IRBuilder.h"
43#include "llvm/IR/Instructions.h"
44#include "llvm/IR/IntrinsicInst.h"
45#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/Operator.h"
Chandler Carruthdbd69582012-11-30 03:08:41 +000047#include "llvm/InstVisitor.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000048#include "llvm/Pass.h"
Chandler Carruth70b44c52012-09-15 11:43:14 +000049#include "llvm/Support/CommandLine.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000050#include "llvm/Support/Debug.h"
51#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000052#include "llvm/Support/MathExtras.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000053#include "llvm/Support/raw_ostream.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000054#include "llvm/Transforms/Utils/Local.h"
55#include "llvm/Transforms/Utils/PromoteMemToReg.h"
56#include "llvm/Transforms/Utils/SSAUpdater.h"
57using namespace llvm;
58
59STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
60STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
61STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
62STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
63STATISTIC(NumDeleted, "Number of instructions deleted");
64STATISTIC(NumVectorized, "Number of vectorized aggregates");
65
Chandler Carruth70b44c52012-09-15 11:43:14 +000066/// Hidden option to force the pass to not use DomTree and mem2reg, instead
67/// forming SSA values through the SSAUpdater infrastructure.
68static cl::opt<bool>
69ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
70
Chandler Carruth1b398ae2012-09-14 09:22:59 +000071namespace {
72/// \brief Alloca partitioning representation.
73///
74/// This class represents a partitioning of an alloca into slices, and
75/// information about the nature of uses of each slice of the alloca. The goal
76/// is that this information is sufficient to decide if and how to split the
77/// alloca apart and replace slices with scalars. It is also intended that this
Chandler Carruth93a21e72012-09-14 10:18:49 +000078/// structure can capture the relevant information needed both to decide about
Chandler Carruth1b398ae2012-09-14 09:22:59 +000079/// and to enact these transformations.
80class AllocaPartitioning {
81public:
82 /// \brief A common base class for representing a half-open byte range.
83 struct ByteRange {
84 /// \brief The beginning offset of the range.
85 uint64_t BeginOffset;
86
87 /// \brief The ending offset, not included in the range.
88 uint64_t EndOffset;
89
90 ByteRange() : BeginOffset(), EndOffset() {}
91 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
92 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
93
94 /// \brief Support for ordering ranges.
95 ///
96 /// This provides an ordering over ranges such that start offsets are
97 /// always increasing, and within equal start offsets, the end offsets are
Chandler Carruth93a21e72012-09-14 10:18:49 +000098 /// decreasing. Thus the spanning range comes first in a cluster with the
Chandler Carruth1b398ae2012-09-14 09:22:59 +000099 /// same start position.
100 bool operator<(const ByteRange &RHS) const {
101 if (BeginOffset < RHS.BeginOffset) return true;
102 if (BeginOffset > RHS.BeginOffset) return false;
103 if (EndOffset > RHS.EndOffset) return true;
104 return false;
105 }
106
107 /// \brief Support comparison with a single offset to allow binary searches.
Benjamin Kramer02a4dff2012-09-17 16:42:36 +0000108 friend bool operator<(const ByteRange &LHS, uint64_t RHSOffset) {
109 return LHS.BeginOffset < RHSOffset;
110 }
111
112 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
113 const ByteRange &RHS) {
114 return LHSOffset < RHS.BeginOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000115 }
116
117 bool operator==(const ByteRange &RHS) const {
118 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
119 }
120 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
121 };
122
123 /// \brief A partition of an alloca.
124 ///
125 /// This structure represents a contiguous partition of the alloca. These are
126 /// formed by examining the uses of the alloca. During formation, they may
127 /// overlap but once an AllocaPartitioning is built, the Partitions within it
128 /// are all disjoint.
129 struct Partition : public ByteRange {
130 /// \brief Whether this partition is splittable into smaller partitions.
131 ///
132 /// We flag partitions as splittable when they are formed entirely due to
Chandler Carruth93a21e72012-09-14 10:18:49 +0000133 /// accesses by trivially splittable operations such as memset and memcpy.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000134 bool IsSplittable;
135
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000136 /// \brief Test whether a partition has been marked as dead.
137 bool isDead() const {
138 if (BeginOffset == UINT64_MAX) {
139 assert(EndOffset == UINT64_MAX);
140 return true;
141 }
142 return false;
143 }
144
145 /// \brief Kill a partition.
146 /// This is accomplished by setting both its beginning and end offset to
147 /// the maximum possible value.
148 void kill() {
149 assert(!isDead() && "He's Dead, Jim!");
150 BeginOffset = EndOffset = UINT64_MAX;
151 }
152
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000153 Partition() : ByteRange(), IsSplittable() {}
154 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
155 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
156 };
157
158 /// \brief A particular use of a partition of the alloca.
159 ///
160 /// This structure is used to associate uses of a partition with it. They
161 /// mark the range of bytes which are referenced by a particular instruction,
162 /// and includes a handle to the user itself and the pointer value in use.
163 /// The bounds of these uses are determined by intersecting the bounds of the
164 /// memory use itself with a particular partition. As a consequence there is
Chandler Carruth93a21e72012-09-14 10:18:49 +0000165 /// intentionally overlap between various uses of the same partition.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000166 struct PartitionUse : public ByteRange {
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000167 /// \brief The use in question. Provides access to both user and used value.
Chandler Carruth6c3890b2012-10-02 18:57:13 +0000168 ///
169 /// Note that this may be null if the partition use is *dead*, that is, it
170 /// should be ignored.
171 Use *U;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000172
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000173 PartitionUse() : ByteRange(), U() {}
174 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset, Use *U)
175 : ByteRange(BeginOffset, EndOffset), U(U) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000176 };
177
178 /// \brief Construct a partitioning of a particular alloca.
179 ///
180 /// Construction does most of the work for partitioning the alloca. This
181 /// performs the necessary walks of users and builds a partitioning from it.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000182 AllocaPartitioning(const DataLayout &TD, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000183
184 /// \brief Test whether a pointer to the allocation escapes our analysis.
185 ///
186 /// If this is true, the partitioning is never fully built and should be
187 /// ignored.
188 bool isEscaped() const { return PointerEscapingInstr; }
189
190 /// \brief Support for iterating over the partitions.
191 /// @{
192 typedef SmallVectorImpl<Partition>::iterator iterator;
193 iterator begin() { return Partitions.begin(); }
194 iterator end() { return Partitions.end(); }
195
196 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
197 const_iterator begin() const { return Partitions.begin(); }
198 const_iterator end() const { return Partitions.end(); }
199 /// @}
200
201 /// \brief Support for iterating over and manipulating a particular
202 /// partition's uses.
203 ///
204 /// The iteration support provided for uses is more limited, but also
205 /// includes some manipulation routines to support rewriting the uses of
206 /// partitions during SROA.
207 /// @{
208 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
209 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
210 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
211 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
212 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000213
214 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
215 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
216 const_use_iterator use_begin(const_iterator I) const {
217 return Uses[I - begin()].begin();
218 }
219 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
220 const_use_iterator use_end(const_iterator I) const {
221 return Uses[I - begin()].end();
222 }
Chandler Carruth3903e052012-10-02 17:49:47 +0000223
224 unsigned use_size(unsigned Idx) const { return Uses[Idx].size(); }
225 unsigned use_size(const_iterator I) const { return Uses[I - begin()].size(); }
226 const PartitionUse &getUse(unsigned PIdx, unsigned UIdx) const {
227 return Uses[PIdx][UIdx];
228 }
229 const PartitionUse &getUse(const_iterator I, unsigned UIdx) const {
230 return Uses[I - begin()][UIdx];
231 }
232
233 void use_push_back(unsigned Idx, const PartitionUse &PU) {
234 Uses[Idx].push_back(PU);
235 }
236 void use_push_back(const_iterator I, const PartitionUse &PU) {
237 Uses[I - begin()].push_back(PU);
238 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000239 /// @}
240
241 /// \brief Allow iterating the dead users for this alloca.
242 ///
243 /// These are instructions which will never actually use the alloca as they
244 /// are outside the allocated range. They are safe to replace with undef and
245 /// delete.
246 /// @{
247 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
248 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
249 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
250 /// @}
251
Chandler Carruth93a21e72012-09-14 10:18:49 +0000252 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000253 ///
254 /// These are operands which have cannot actually be used to refer to the
255 /// alloca as they are outside its range and the user doesn't correct for
256 /// that. These mostly consist of PHI node inputs and the like which we just
257 /// need to replace with undef.
258 /// @{
259 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
260 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
261 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
262 /// @}
263
264 /// \brief MemTransferInst auxiliary data.
265 /// This struct provides some auxiliary data about memory transfer
266 /// intrinsics such as memcpy and memmove. These intrinsics can use two
267 /// different ranges within the same alloca, and provide other challenges to
268 /// correctly represent. We stash extra data to help us untangle this
269 /// after the partitioning is complete.
270 struct MemTransferOffsets {
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000271 /// The destination begin and end offsets when the destination is within
272 /// this alloca. If the end offset is zero the destination is not within
273 /// this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000274 uint64_t DestBegin, DestEnd;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000275
276 /// The source begin and end offsets when the source is within this alloca.
277 /// If the end offset is zero, the source is not within this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000278 uint64_t SourceBegin, SourceEnd;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000279
280 /// Flag for whether an alloca is splittable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000281 bool IsSplittable;
282 };
283 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
284 return MemTransferInstData.lookup(&II);
285 }
286
287 /// \brief Map from a PHI or select operand back to a partition.
288 ///
289 /// When manipulating PHI nodes or selects, they can use more than one
290 /// partition of an alloca. We store a special mapping to allow finding the
291 /// partition referenced by each of these operands, if any.
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000292 iterator findPartitionForPHIOrSelectOperand(Use *U) {
293 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
294 = PHIOrSelectOpMap.find(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000295 if (MapIt == PHIOrSelectOpMap.end())
296 return end();
297
298 return begin() + MapIt->second.first;
299 }
300
301 /// \brief Map from a PHI or select operand back to the specific use of
302 /// a partition.
303 ///
304 /// Similar to mapping these operands back to the partitions, this maps
305 /// directly to the use structure of that partition.
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000306 use_iterator findPartitionUseForPHIOrSelectOperand(Use *U) {
307 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
308 = PHIOrSelectOpMap.find(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000309 assert(MapIt != PHIOrSelectOpMap.end());
310 return Uses[MapIt->second.first].begin() + MapIt->second.second;
311 }
312
313 /// \brief Compute a common type among the uses of a particular partition.
314 ///
315 /// This routines walks all of the uses of a particular partition and tries
316 /// to find a common type between them. Untyped operations such as memset and
317 /// memcpy are ignored.
318 Type *getCommonType(iterator I) const;
319
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000320#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000321 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
322 void printUsers(raw_ostream &OS, const_iterator I,
323 StringRef Indent = " ") const;
324 void print(raw_ostream &OS) const;
NAKAMURA Takumi4bbca0b2012-09-14 10:06:10 +0000325 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
326 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000327#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000328
329private:
330 template <typename DerivedT, typename RetT = void> class BuilderBase;
331 class PartitionBuilder;
332 friend class AllocaPartitioning::PartitionBuilder;
333 class UseBuilder;
334 friend class AllocaPartitioning::UseBuilder;
335
Chandler Carruthb7915f72012-11-20 10:23:07 +0000336#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000337 /// \brief Handle to alloca instruction to simplify method interfaces.
338 AllocaInst &AI;
Benjamin Kramer4622cd72012-09-14 13:08:09 +0000339#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000340
341 /// \brief The instruction responsible for this alloca having no partitioning.
342 ///
343 /// When an instruction (potentially) escapes the pointer to the alloca, we
344 /// store a pointer to that here and abort trying to partition the alloca.
345 /// This will be null if the alloca is partitioned successfully.
346 Instruction *PointerEscapingInstr;
347
348 /// \brief The partitions of the alloca.
349 ///
350 /// We store a vector of the partitions over the alloca here. This vector is
351 /// sorted by increasing begin offset, and then by decreasing end offset. See
Chandler Carruth93a21e72012-09-14 10:18:49 +0000352 /// the Partition inner class for more details. Initially (during
353 /// construction) there are overlaps, but we form a disjoint sequence of
354 /// partitions while finishing construction and a fully constructed object is
355 /// expected to always have this as a disjoint space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000356 SmallVector<Partition, 8> Partitions;
357
358 /// \brief The uses of the partitions.
359 ///
360 /// This is essentially a mapping from each partition to a list of uses of
361 /// that partition. The mapping is done with a Uses vector that has the exact
362 /// same number of entries as the partition vector. Each entry is itself
363 /// a vector of the uses.
364 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
365
366 /// \brief Instructions which will become dead if we rewrite the alloca.
367 ///
368 /// Note that these are not separated by partition. This is because we expect
369 /// a partitioned alloca to be completely rewritten or not rewritten at all.
370 /// If rewritten, all these instructions can simply be removed and replaced
371 /// with undef as they come from outside of the allocated space.
372 SmallVector<Instruction *, 8> DeadUsers;
373
374 /// \brief Operands which will become dead if we rewrite the alloca.
375 ///
376 /// These are operands that in their particular use can be replaced with
377 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
378 /// to PHI nodes and the like. They aren't entirely dead (there might be
379 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
380 /// want to swap this particular input for undef to simplify the use lists of
381 /// the alloca.
382 SmallVector<Use *, 8> DeadOperands;
383
384 /// \brief The underlying storage for auxiliary memcpy and memset info.
385 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
386
387 /// \brief A side datastructure used when building up the partitions and uses.
388 ///
389 /// This mapping is only really used during the initial building of the
390 /// partitioning so that we can retain information about PHI and select nodes
391 /// processed.
392 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
393
394 /// \brief Auxiliary information for particular PHI or select operands.
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000395 SmallDenseMap<Use *, std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000396
397 /// \brief A utility routine called from the constructor.
398 ///
399 /// This does what it says on the tin. It is the key of the alloca partition
400 /// splitting and merging. After it is called we have the desired disjoint
401 /// collection of partitions.
402 void splitAndMergePartitions();
403};
404}
405
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000406static Value *foldSelectInst(SelectInst &SI) {
407 // If the condition being selected on is a constant or the same value is
408 // being selected between, fold the select. Yes this does (rarely) happen
409 // early on.
410 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
411 return SI.getOperand(1+CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000412 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000413 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000414
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000415 return 0;
416}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000417
418/// \brief Builder for the alloca partitioning.
419///
420/// This class builds an alloca partitioning by recursively visiting the uses
421/// of an alloca and splitting the partitions for each load and store at each
422/// offset.
423class AllocaPartitioning::PartitionBuilder
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000424 : public PtrUseVisitor<PartitionBuilder> {
425 friend class PtrUseVisitor<PartitionBuilder>;
426 friend class InstVisitor<PartitionBuilder>;
427 typedef PtrUseVisitor<PartitionBuilder> Base;
428
429 const uint64_t AllocSize;
430 AllocaPartitioning &P;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000431
432 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
433
434public:
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000435 PartitionBuilder(const DataLayout &DL, AllocaInst &AI, AllocaPartitioning &P)
436 : PtrUseVisitor<PartitionBuilder>(DL),
437 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())),
438 P(P) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000439
440private:
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000441 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000442 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000443 // Completely skip uses which have a zero size or start either before or
444 // past the end of the allocation.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000445 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000446 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000447 << " which has zero size or starts outside of the "
448 << AllocSize << " byte alloca:\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000449 << " alloca: " << P.AI << "\n"
450 << " use: " << I << "\n");
451 return;
452 }
453
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000454 uint64_t BeginOffset = Offset.getZExtValue();
455 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000456
457 // Clamp the end offset to the end of the allocation. Note that this is
458 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carruth3e994a22012-11-20 10:02:19 +0000459 // NOTE! This may appear superficially to be something we could ignore
460 // entirely, but that is not so! There may be PHI-node uses where some
461 // instructions are dead but not others. We can't completely ignore the
462 // PHI node, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000463 assert(AllocSize >= BeginOffset); // Established above.
464 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000465 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
466 << " to remain within the " << AllocSize << " byte alloca:\n"
467 << " alloca: " << P.AI << "\n"
468 << " use: " << I << "\n");
469 EndOffset = AllocSize;
470 }
471
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000472 Partition New(BeginOffset, EndOffset, IsSplittable);
473 P.Partitions.push_back(New);
474 }
475
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000476 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carruth58d05562012-10-25 04:37:07 +0000477 bool IsVolatile) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000478 uint64_t Size = DL.getTypeStoreSize(Ty);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000479
480 // If this memory access can be shown to *statically* extend outside the
481 // bounds of of the allocation, it's behavior is undefined, so simply
482 // ignore it. Note that this is more strict than the generic clamping
483 // behavior of insertUse. We also try to handle cases which might run the
484 // risk of overflow.
485 // FIXME: We should instead consider the pointer to have escaped if this
486 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000487 if (Offset.isNegative() || Size > AllocSize ||
488 Offset.ugt(AllocSize - Size)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000489 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
490 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
491 << " which extends past the end of the " << AllocSize
492 << " byte alloca:\n"
493 << " alloca: " << P.AI << "\n"
494 << " use: " << I << "\n");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000495 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000496 }
497
Chandler Carruth58d05562012-10-25 04:37:07 +0000498 // We allow splitting of loads and stores where the type is an integer type
499 // and which cover the entire alloca. Such integer loads and stores
500 // often require decomposition into fine grained loads and stores.
501 bool IsSplittable = false;
502 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
503 IsSplittable = !IsVolatile && ITy->getBitWidth() == AllocSize*8;
504
505 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000506 }
507
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000508 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000509 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
510 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000511
512 if (!IsOffsetKnown)
513 return PI.setAborted(&LI);
514
Chandler Carruth58d05562012-10-25 04:37:07 +0000515 return handleLoadOrStore(LI.getType(), LI, Offset, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000516 }
517
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000518 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000519 Value *ValOp = SI.getValueOperand();
520 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000521 return PI.setEscapedAndAborted(&SI);
522 if (!IsOffsetKnown)
523 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000524
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000525 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
526 "All simple FCA stores should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000527 handleLoadOrStore(ValOp->getType(), SI, Offset, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000528 }
529
530
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000531 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000532 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000533 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000534 if ((Length && Length->getValue() == 0) ||
535 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
536 // Zero-length mem transfer intrinsics can be ignored entirely.
537 return;
538
539 if (!IsOffsetKnown)
540 return PI.setAborted(&II);
541
542 insertUse(II, Offset,
543 Length ? Length->getLimitedValue()
544 : AllocSize - Offset.getLimitedValue(),
545 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000546 }
547
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000548 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000549 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000550 if ((Length && Length->getValue() == 0) ||
551 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000552 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000553 return;
554
555 if (!IsOffsetKnown)
556 return PI.setAborted(&II);
557
558 uint64_t RawOffset = Offset.getLimitedValue();
559 uint64_t Size = Length ? Length->getLimitedValue()
560 : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000561
562 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
563
564 // Only intrinsics with a constant length can be split.
565 Offsets.IsSplittable = Length;
566
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000567 if (*U == II.getRawDest()) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000568 Offsets.DestBegin = RawOffset;
569 Offsets.DestEnd = RawOffset + Size;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000570 }
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000571 if (*U == II.getRawSource()) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000572 Offsets.SourceBegin = RawOffset;
573 Offsets.SourceEnd = RawOffset + Size;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000574 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000575
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000576 // If we have set up end offsets for both the source and the destination,
577 // we have found both sides of this transfer pointing at the same alloca.
578 bool SeenBothEnds = Offsets.SourceEnd && Offsets.DestEnd;
579 if (SeenBothEnds && II.getRawDest() != II.getRawSource()) {
580 unsigned PrevIdx = MemTransferPartitionMap[&II];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000581
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000582 // Check if the begin offsets match and this is a non-volatile transfer.
583 // In that case, we can completely elide the transfer.
584 if (!II.isVolatile() && Offsets.SourceBegin == Offsets.DestBegin) {
585 P.Partitions[PrevIdx].kill();
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000586 return;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000587 }
588
589 // Otherwise we have an offset transfer within the same alloca. We can't
590 // split those.
591 P.Partitions[PrevIdx].IsSplittable = Offsets.IsSplittable = false;
592 } else if (SeenBothEnds) {
593 // Handle the case where this exact use provides both ends of the
594 // operation.
595 assert(II.getRawDest() == II.getRawSource());
596
597 // For non-volatile transfers this is a no-op.
598 if (!II.isVolatile())
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000599 return;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000600
601 // Otherwise just suppress splitting.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000602 Offsets.IsSplittable = false;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000603 }
604
605
606 // Insert the use now that we've fixed up the splittable nature.
607 insertUse(II, Offset, Size, Offsets.IsSplittable);
608
609 // Setup the mapping from intrinsic to partition of we've not seen both
610 // ends of this transfer.
611 if (!SeenBothEnds) {
612 unsigned NewIdx = P.Partitions.size() - 1;
613 bool Inserted
614 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx)).second;
615 assert(Inserted &&
616 "Already have intrinsic in map but haven't seen both ends");
NAKAMURA Takumi605fe782012-10-05 13:56:23 +0000617 (void)Inserted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000618 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000619 }
620
621 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000622 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000623 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000624 void visitIntrinsicInst(IntrinsicInst &II) {
625 if (!IsOffsetKnown)
626 return PI.setAborted(&II);
627
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000628 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
629 II.getIntrinsicID() == Intrinsic::lifetime_end) {
630 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000631 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
632 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000633 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000634 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000635 }
636
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000637 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000638 }
639
640 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
641 // We consider any PHI or select that results in a direct load or store of
642 // the same offset to be a viable use for partitioning purposes. These uses
643 // are considered unsplittable and the size is the maximum loaded or stored
644 // size.
645 SmallPtrSet<Instruction *, 4> Visited;
646 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
647 Visited.insert(Root);
648 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruth8b907e82012-09-25 10:03:40 +0000649 // If there are no loads or stores, the access is dead. We mark that as
650 // a size zero access.
651 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000652 do {
653 Instruction *I, *UsedI;
654 llvm::tie(UsedI, I) = Uses.pop_back_val();
655
656 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000657 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000658 continue;
659 }
660 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
661 Value *Op = SI->getOperand(0);
662 if (Op == UsedI)
663 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000664 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000665 continue;
666 }
667
668 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
669 if (!GEP->hasAllZeroIndices())
670 return GEP;
671 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
672 !isa<SelectInst>(I)) {
673 return I;
674 }
675
676 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
677 ++UI)
678 if (Visited.insert(cast<Instruction>(*UI)))
679 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
680 } while (!Uses.empty());
681
682 return 0;
683 }
684
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000685 void visitPHINode(PHINode &PN) {
686 if (PN.use_empty())
687 return;
688 if (!IsOffsetKnown)
689 return PI.setAborted(&PN);
690
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000691 // See if we already have computed info on this node.
692 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
693 if (PHIInfo.first) {
694 PHIInfo.second = true;
Chandler Carruth97121172012-09-16 19:39:50 +0000695 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000696 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000697 }
698
699 // Check for an unsafe use of the PHI node.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000700 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
701 return PI.setAborted(UnsafeI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000702
Chandler Carruth97121172012-09-16 19:39:50 +0000703 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000704 }
705
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000706 void visitSelectInst(SelectInst &SI) {
707 if (SI.use_empty())
708 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000709 if (Value *Result = foldSelectInst(SI)) {
710 if (Result == *U)
711 // If the result of the constant fold will be the pointer, recurse
712 // through the select as if we had RAUW'ed it.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000713 enqueueUsers(SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000714
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000715 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000716 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000717 if (!IsOffsetKnown)
718 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000719
720 // See if we already have computed info on this node.
721 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
722 if (SelectInfo.first) {
723 SelectInfo.second = true;
Chandler Carruth97121172012-09-16 19:39:50 +0000724 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000725 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000726 }
727
728 // Check for an unsafe use of the PHI node.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000729 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
730 return PI.setAborted(UnsafeI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000731
Chandler Carruth97121172012-09-16 19:39:50 +0000732 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000733 }
734
735 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000736 void visitInstruction(Instruction &I) {
737 PI.setAborted(&I);
738 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000739};
740
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000741/// \brief Use adder for the alloca partitioning.
742///
Chandler Carruth93a21e72012-09-14 10:18:49 +0000743/// This class adds the uses of an alloca to all of the partitions which they
744/// use. For splittable partitions, this can end up doing essentially a linear
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000745/// walk of the partitions, but the number of steps remains bounded by the
746/// total result instruction size:
747/// - The number of partitions is a result of the number unsplittable
748/// instructions using the alloca.
749/// - The number of users of each partition is at worst the total number of
750/// splittable instructions using the alloca.
751/// Thus we will produce N * M instructions in the end, where N are the number
752/// of unsplittable uses and M are the number of splittable. This visitor does
753/// the exact same number of updates to the partitioning.
754///
755/// In the more common case, this visitor will leverage the fact that the
756/// partition space is pre-sorted, and do a logarithmic search for the
757/// partition needed, making the total visit a classical ((N + M) * log(N))
758/// complexity operation.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000759class AllocaPartitioning::UseBuilder : public PtrUseVisitor<UseBuilder> {
760 friend class PtrUseVisitor<UseBuilder>;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000761 friend class InstVisitor<UseBuilder>;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000762 typedef PtrUseVisitor<UseBuilder> Base;
763
764 const uint64_t AllocSize;
765 AllocaPartitioning &P;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000766
767 /// \brief Set to de-duplicate dead instructions found in the use walk.
768 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
769
770public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000771 UseBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000772 : PtrUseVisitor<UseBuilder>(TD),
773 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
774 P(P) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000775
776private:
777 void markAsDead(Instruction &I) {
778 if (VisitedDeadInsts.insert(&I))
779 P.DeadUsers.push_back(&I);
780 }
781
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000782 void insertUse(Instruction &User, const APInt &Offset, uint64_t Size) {
Chandler Carruth8b907e82012-09-25 10:03:40 +0000783 // If the use has a zero size or extends outside of the allocation, record
784 // it as a dead use for elimination later.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000785 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize))
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000786 return markAsDead(User);
787
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000788 uint64_t BeginOffset = Offset.getZExtValue();
789 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000790
791 // Clamp the end offset to the end of the allocation. Note that this is
792 // formulated to handle even the case where "BeginOffset + Size" overflows.
793 assert(AllocSize >= BeginOffset); // Established above.
794 if (Size > AllocSize - BeginOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000795 EndOffset = AllocSize;
796
797 // NB: This only works if we have zero overlapping partitions.
798 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
799 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
800 B = llvm::prior(B);
801 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
802 ++I) {
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000803 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
804 std::min(I->EndOffset, EndOffset), U);
805 P.use_push_back(I, NewPU);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000806 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000807 P.PHIOrSelectOpMap[U]
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000808 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
809 }
810 }
811
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000812 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset) {
813 uint64_t Size = DL.getTypeStoreSize(Ty);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000814
815 // If this memory access can be shown to *statically* extend outside the
816 // bounds of of the allocation, it's behavior is undefined, so simply
817 // ignore it. Note that this is more strict than the generic clamping
818 // behavior of insertUse.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000819 if (Offset.isNegative() || Size > AllocSize ||
820 Offset.ugt(AllocSize - Size))
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000821 return markAsDead(I);
822
Chandler Carruth97121172012-09-16 19:39:50 +0000823 insertUse(I, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000824 }
825
826 void visitBitCastInst(BitCastInst &BC) {
827 if (BC.use_empty())
828 return markAsDead(BC);
829
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000830 return Base::visitBitCastInst(BC);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000831 }
832
833 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
834 if (GEPI.use_empty())
835 return markAsDead(GEPI);
836
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000837 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000838 }
839
840 void visitLoadInst(LoadInst &LI) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000841 assert(IsOffsetKnown);
Chandler Carruth97121172012-09-16 19:39:50 +0000842 handleLoadOrStore(LI.getType(), LI, Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000843 }
844
845 void visitStoreInst(StoreInst &SI) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000846 assert(IsOffsetKnown);
Chandler Carruth97121172012-09-16 19:39:50 +0000847 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000848 }
849
850 void visitMemSetInst(MemSetInst &II) {
851 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000852 if ((Length && Length->getValue() == 0) ||
853 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
854 return markAsDead(II);
855
856 assert(IsOffsetKnown);
857 insertUse(II, Offset, Length ? Length->getLimitedValue()
858 : AllocSize - Offset.getLimitedValue());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000859 }
860
861 void visitMemTransferInst(MemTransferInst &II) {
862 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000863 if ((Length && Length->getValue() == 0) ||
864 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000865 return markAsDead(II);
866
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000867 assert(IsOffsetKnown);
868 uint64_t Size = Length ? Length->getLimitedValue()
869 : AllocSize - Offset.getLimitedValue();
870
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000871 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
872 if (!II.isVolatile() && Offsets.DestEnd && Offsets.SourceEnd &&
873 Offsets.DestBegin == Offsets.SourceBegin)
874 return markAsDead(II); // Skip identity transfers without side-effects.
875
Chandler Carruth97121172012-09-16 19:39:50 +0000876 insertUse(II, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000877 }
878
879 void visitIntrinsicInst(IntrinsicInst &II) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000880 assert(IsOffsetKnown);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000881 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
882 II.getIntrinsicID() == Intrinsic::lifetime_end);
883
884 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000885 insertUse(II, Offset, std::min(Length->getLimitedValue(),
886 AllocSize - Offset.getLimitedValue()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000887 }
888
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000889 void insertPHIOrSelect(Instruction &User, const APInt &Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000890 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
891
892 // For PHI and select operands outside the alloca, we can't nuke the entire
893 // phi or select -- the other side might still be relevant, so we special
894 // case them here and use a separate structure to track the operands
895 // themselves which should be replaced with undef.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000896 if ((Offset.isNegative() && Offset.uge(Size)) ||
897 (!Offset.isNegative() && Offset.uge(AllocSize))) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000898 P.DeadOperands.push_back(U);
899 return;
900 }
901
Chandler Carruth97121172012-09-16 19:39:50 +0000902 insertUse(User, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000903 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000904
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000905 void visitPHINode(PHINode &PN) {
906 if (PN.use_empty())
907 return markAsDead(PN);
908
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000909 assert(IsOffsetKnown);
Chandler Carruth97121172012-09-16 19:39:50 +0000910 insertPHIOrSelect(PN, Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000911 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000912
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000913 void visitSelectInst(SelectInst &SI) {
914 if (SI.use_empty())
915 return markAsDead(SI);
916
917 if (Value *Result = foldSelectInst(SI)) {
918 if (Result == *U)
919 // If the result of the constant fold will be the pointer, recurse
920 // through the select as if we had RAUW'ed it.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000921 enqueueUsers(SI);
Chandler Carruth225d4bd2012-09-21 23:36:40 +0000922 else
923 // Otherwise the operand to the select is dead, and we can replace it
924 // with undef.
925 P.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000926
927 return;
928 }
929
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000930 assert(IsOffsetKnown);
Chandler Carruth97121172012-09-16 19:39:50 +0000931 insertPHIOrSelect(SI, Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000932 }
933
934 /// \brief Unreachable, we've already visited the alloca once.
935 void visitInstruction(Instruction &I) {
936 llvm_unreachable("Unhandled instruction in use builder.");
937 }
938};
939
940void AllocaPartitioning::splitAndMergePartitions() {
941 size_t NumDeadPartitions = 0;
942
943 // Track the range of splittable partitions that we pass when accumulating
944 // overlapping unsplittable partitions.
945 uint64_t SplitEndOffset = 0ull;
946
947 Partition New(0ull, 0ull, false);
948
949 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
950 ++j;
951
952 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
953 assert(New.BeginOffset == New.EndOffset);
954 New = Partitions[i];
955 } else {
956 assert(New.IsSplittable);
957 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
958 }
959 assert(New.BeginOffset != New.EndOffset);
960
961 // Scan the overlapping partitions.
962 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
963 // If the new partition we are forming is splittable, stop at the first
964 // unsplittable partition.
965 if (New.IsSplittable && !Partitions[j].IsSplittable)
966 break;
967
968 // Grow the new partition to include any equally splittable range. 'j' is
969 // always equally splittable when New is splittable, but when New is not
970 // splittable, we may subsume some (or part of some) splitable partition
971 // without growing the new one.
972 if (New.IsSplittable == Partitions[j].IsSplittable) {
973 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
974 } else {
975 assert(!New.IsSplittable);
976 assert(Partitions[j].IsSplittable);
977 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
978 }
979
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000980 Partitions[j].kill();
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000981 ++NumDeadPartitions;
982 ++j;
983 }
984
985 // If the new partition is splittable, chop off the end as soon as the
986 // unsplittable subsequent partition starts and ensure we eventually cover
987 // the splittable area.
988 if (j != e && New.IsSplittable) {
989 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
990 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
991 }
992
993 // Add the new partition if it differs from the original one and is
994 // non-empty. We can end up with an empty partition here if it was
995 // splittable but there is an unsplittable one that starts at the same
996 // offset.
997 if (New != Partitions[i]) {
998 if (New.BeginOffset != New.EndOffset)
999 Partitions.push_back(New);
1000 // Mark the old one for removal.
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001001 Partitions[i].kill();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001002 ++NumDeadPartitions;
1003 }
1004
1005 New.BeginOffset = New.EndOffset;
1006 if (!New.IsSplittable) {
1007 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1008 if (j != e && !Partitions[j].IsSplittable)
1009 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1010 New.IsSplittable = true;
1011 // If there is a trailing splittable partition which won't be fused into
1012 // the next splittable partition go ahead and add it onto the partitions
1013 // list.
1014 if (New.BeginOffset < New.EndOffset &&
1015 (j == e || !Partitions[j].IsSplittable ||
1016 New.EndOffset < Partitions[j].BeginOffset)) {
1017 Partitions.push_back(New);
1018 New.BeginOffset = New.EndOffset = 0ull;
1019 }
1020 }
1021 }
1022
1023 // Re-sort the partitions now that they have been split and merged into
1024 // disjoint set of partitions. Also remove any of the dead partitions we've
1025 // replaced in the process.
1026 std::sort(Partitions.begin(), Partitions.end());
1027 if (NumDeadPartitions) {
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001028 assert(Partitions.back().isDead());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001029 assert((ptrdiff_t)NumDeadPartitions ==
1030 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1031 }
1032 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1033}
1034
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001035AllocaPartitioning::AllocaPartitioning(const DataLayout &TD, AllocaInst &AI)
Benjamin Kramer4622cd72012-09-14 13:08:09 +00001036 :
Chandler Carruthb7915f72012-11-20 10:23:07 +00001037#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Benjamin Kramer4622cd72012-09-14 13:08:09 +00001038 AI(AI),
1039#endif
1040 PointerEscapingInstr(0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001041 PartitionBuilder PB(TD, AI, *this);
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001042 PartitionBuilder::PtrInfo PtrI = PB.visitPtr(AI);
1043 if (PtrI.isEscaped() || PtrI.isAborted()) {
1044 // FIXME: We should sink the escape vs. abort info into the caller nicely,
1045 // possibly by just storing the PtrInfo in the AllocaPartitioning.
1046 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1047 : PtrI.getAbortingInst();
1048 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001049 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001050 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001051
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001052 // Sort the uses. This arranges for the offsets to be in ascending order,
1053 // and the sizes to be in descending order.
1054 std::sort(Partitions.begin(), Partitions.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001055
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001056 // Remove any partitions from the back which are marked as dead.
1057 while (!Partitions.empty() && Partitions.back().isDead())
1058 Partitions.pop_back();
1059
1060 if (Partitions.size() > 1) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001061 // Intersect splittability for all partitions with equal offsets and sizes.
1062 // Then remove all but the first so that we have a sequence of non-equal but
1063 // potentially overlapping partitions.
1064 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1065 I = J) {
1066 ++J;
1067 while (J != E && *I == *J) {
1068 I->IsSplittable &= J->IsSplittable;
1069 ++J;
1070 }
1071 }
1072 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1073 Partitions.end());
1074
1075 // Split splittable and merge unsplittable partitions into a disjoint set
1076 // of partitions over the used space of the allocation.
1077 splitAndMergePartitions();
1078 }
1079
1080 // Now build up the user lists for each of these disjoint partitions by
1081 // re-walking the recursive users of the alloca.
1082 Uses.resize(Partitions.size());
1083 UseBuilder UB(TD, AI, *this);
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001084 PtrI = UB.visitPtr(AI);
1085 assert(!PtrI.isEscaped() && "Previously analyzed pointer now escapes!");
1086 assert(!PtrI.isAborted() && "Early aborted the visit of the pointer.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001087}
1088
1089Type *AllocaPartitioning::getCommonType(iterator I) const {
1090 Type *Ty = 0;
1091 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
Chandler Carruth6c3890b2012-10-02 18:57:13 +00001092 if (!UI->U)
1093 continue; // Skip dead uses.
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00001094 if (isa<IntrinsicInst>(*UI->U->getUser()))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001095 continue;
1096 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
Chandler Carruthd356fd02012-09-18 17:49:37 +00001097 continue;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001098
1099 Type *UserTy = 0;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00001100 if (LoadInst *LI = dyn_cast<LoadInst>(UI->U->getUser())) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001101 UserTy = LI->getType();
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00001102 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI->U->getUser())) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001103 UserTy = SI->getValueOperand()->getType();
Chandler Carruth58d05562012-10-25 04:37:07 +00001104 } else {
1105 return 0; // Bail if we have weird uses.
1106 }
1107
1108 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
1109 // If the type is larger than the partition, skip it. We only encounter
1110 // this for split integer operations where we want to use the type of the
1111 // entity causing the split.
1112 if (ITy->getBitWidth() > (I->EndOffset - I->BeginOffset)*8)
1113 continue;
1114
1115 // If we have found an integer type use covering the alloca, use that
1116 // regardless of the other types, as integers are often used for a "bucket
1117 // of bits" type.
1118 return ITy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001119 }
1120
1121 if (Ty && Ty != UserTy)
1122 return 0;
1123
1124 Ty = UserTy;
1125 }
1126 return Ty;
1127}
1128
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001129#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1130
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001131void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1132 StringRef Indent) const {
1133 OS << Indent << "partition #" << (I - begin())
1134 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1135 << (I->IsSplittable ? " (splittable)" : "")
1136 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1137 << "\n";
1138}
1139
1140void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1141 StringRef Indent) const {
Jakub Staszak3c6583a2013-02-19 22:14:45 +00001142 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
Chandler Carruth6c3890b2012-10-02 18:57:13 +00001143 if (!UI->U)
1144 continue; // Skip dead uses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001145 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00001146 << "used by: " << *UI->U->getUser() << "\n";
1147 if (MemTransferInst *II = dyn_cast<MemTransferInst>(UI->U->getUser())) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001148 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1149 bool IsDest;
1150 if (!MTO.IsSplittable)
1151 IsDest = UI->BeginOffset == MTO.DestBegin;
1152 else
1153 IsDest = MTO.DestBegin != 0u;
1154 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1155 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1156 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1157 }
1158 }
1159}
1160
1161void AllocaPartitioning::print(raw_ostream &OS) const {
1162 if (PointerEscapingInstr) {
1163 OS << "No partitioning for alloca: " << AI << "\n"
1164 << " A pointer to this alloca escaped by:\n"
1165 << " " << *PointerEscapingInstr << "\n";
1166 return;
1167 }
1168
1169 OS << "Partitioning of alloca: " << AI << "\n";
1170 unsigned Num = 0;
1171 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1172 print(OS, I);
1173 printUsers(OS, I);
1174 }
1175}
1176
1177void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1178void AllocaPartitioning::dump() const { print(dbgs()); }
1179
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001180#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1181
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001182
1183namespace {
Chandler Carruth70b44c52012-09-15 11:43:14 +00001184/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1185///
1186/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1187/// the loads and stores of an alloca instruction, as well as updating its
1188/// debug information. This is used when a domtree is unavailable and thus
1189/// mem2reg in its full form can't be used to handle promotion of allocas to
1190/// scalar values.
1191class AllocaPromoter : public LoadAndStorePromoter {
1192 AllocaInst &AI;
1193 DIBuilder &DIB;
1194
1195 SmallVector<DbgDeclareInst *, 4> DDIs;
1196 SmallVector<DbgValueInst *, 4> DVIs;
1197
1198public:
1199 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1200 AllocaInst &AI, DIBuilder &DIB)
1201 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1202
1203 void run(const SmallVectorImpl<Instruction*> &Insts) {
1204 // Remember which alloca we're promoting (for isInstInList).
1205 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1206 for (Value::use_iterator UI = DebugNode->use_begin(),
1207 UE = DebugNode->use_end();
1208 UI != UE; ++UI)
1209 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1210 DDIs.push_back(DDI);
1211 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1212 DVIs.push_back(DVI);
1213 }
1214
1215 LoadAndStorePromoter::run(Insts);
1216 AI.eraseFromParent();
1217 while (!DDIs.empty())
1218 DDIs.pop_back_val()->eraseFromParent();
1219 while (!DVIs.empty())
1220 DVIs.pop_back_val()->eraseFromParent();
1221 }
1222
1223 virtual bool isInstInList(Instruction *I,
1224 const SmallVectorImpl<Instruction*> &Insts) const {
1225 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1226 return LI->getOperand(0) == &AI;
1227 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1228 }
1229
1230 virtual void updateDebugInfo(Instruction *Inst) const {
1231 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1232 E = DDIs.end(); I != E; ++I) {
1233 DbgDeclareInst *DDI = *I;
1234 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1235 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1236 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1237 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1238 }
1239 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1240 E = DVIs.end(); I != E; ++I) {
1241 DbgValueInst *DVI = *I;
Jakub Staszak3c6583a2013-02-19 22:14:45 +00001242 Value *Arg = 0;
Chandler Carruth70b44c52012-09-15 11:43:14 +00001243 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1244 // If an argument is zero extended then use argument directly. The ZExt
1245 // may be zapped by an optimization pass in future.
1246 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1247 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1248 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1249 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1250 if (!Arg)
1251 Arg = SI->getOperand(0);
1252 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1253 Arg = LI->getOperand(0);
1254 } else {
1255 continue;
1256 }
1257 Instruction *DbgVal =
1258 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1259 Inst);
1260 DbgVal->setDebugLoc(DVI->getDebugLoc());
1261 }
1262 }
1263};
1264} // end anon namespace
1265
1266
1267namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001268/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1269///
1270/// This pass takes allocations which can be completely analyzed (that is, they
1271/// don't escape) and tries to turn them into scalar SSA values. There are
1272/// a few steps to this process.
1273///
1274/// 1) It takes allocations of aggregates and analyzes the ways in which they
1275/// are used to try to split them into smaller allocations, ideally of
1276/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001277/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001278/// 2) It will transform accesses into forms which are suitable for SSA value
1279/// promotion. This can be replacing a memset with a scalar store of an
1280/// integer value, or it can involve speculating operations on a PHI or
1281/// select to be a PHI or select of the results.
1282/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1283/// onto insert and extract operations on a vector value, and convert them to
1284/// this form. By doing so, it will enable promotion of vector aggregates to
1285/// SSA vector values.
1286class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +00001287 const bool RequiresDomTree;
1288
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001289 LLVMContext *C;
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001290 const DataLayout *TD;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001291 DominatorTree *DT;
1292
1293 /// \brief Worklist of alloca instructions to simplify.
1294 ///
1295 /// Each alloca in the function is added to this. Each new alloca formed gets
1296 /// added to it as well to recursively simplify unless that alloca can be
1297 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1298 /// the one being actively rewritten, we add it back onto the list if not
1299 /// already present to ensure it is re-visited.
1300 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1301
1302 /// \brief A collection of instructions to delete.
1303 /// We try to batch deletions to simplify code and make things a bit more
1304 /// efficient.
Chandler Carruth18db7952012-11-20 01:12:50 +00001305 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001306
Chandler Carruthac8317f2012-10-04 12:33:50 +00001307 /// \brief Post-promotion worklist.
1308 ///
1309 /// Sometimes we discover an alloca which has a high probability of becoming
1310 /// viable for SROA after a round of promotion takes place. In those cases,
1311 /// the alloca is enqueued here for re-processing.
1312 ///
1313 /// Note that we have to be very careful to clear allocas out of this list in
1314 /// the event they are deleted.
1315 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
1316
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001317 /// \brief A collection of alloca instructions we can directly promote.
1318 std::vector<AllocaInst *> PromotableAllocas;
1319
1320public:
Chandler Carruth70b44c52012-09-15 11:43:14 +00001321 SROA(bool RequiresDomTree = true)
1322 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1323 C(0), TD(0), DT(0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001324 initializeSROAPass(*PassRegistry::getPassRegistry());
1325 }
1326 bool runOnFunction(Function &F);
1327 void getAnalysisUsage(AnalysisUsage &AU) const;
1328
1329 const char *getPassName() const { return "SROA"; }
1330 static char ID;
1331
1332private:
Chandler Carruth82a57542012-10-01 10:54:05 +00001333 friend class PHIOrSelectSpeculator;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001334 friend class AllocaPartitionRewriter;
1335 friend class AllocaPartitionVectorRewriter;
1336
1337 bool rewriteAllocaPartition(AllocaInst &AI,
1338 AllocaPartitioning &P,
1339 AllocaPartitioning::iterator PI);
1340 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1341 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth19450da2012-09-14 10:26:38 +00001342 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +00001343 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001344};
1345}
1346
1347char SROA::ID = 0;
1348
Chandler Carruth70b44c52012-09-15 11:43:14 +00001349FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1350 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001351}
1352
1353INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1354 false, false)
1355INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1356INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1357 false, false)
1358
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001359namespace {
1360/// \brief Visitor to speculate PHIs and Selects where possible.
1361class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
1362 // Befriend the base class so it can delegate to private visit methods.
1363 friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
1364
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001365 const DataLayout &TD;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001366 AllocaPartitioning &P;
1367 SROA &Pass;
1368
1369public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001370 PHIOrSelectSpeculator(const DataLayout &TD, AllocaPartitioning &P, SROA &Pass)
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001371 : TD(TD), P(P), Pass(Pass) {}
1372
1373 /// \brief Visit the users of an alloca partition and rewrite them.
1374 void visitUsers(AllocaPartitioning::const_iterator PI) {
1375 // Note that we need to use an index here as the underlying vector of uses
1376 // may be grown during speculation. However, we never need to re-visit the
1377 // new uses, and so we can use the initial size bound.
1378 for (unsigned Idx = 0, Size = P.use_size(PI); Idx != Size; ++Idx) {
1379 const AllocaPartitioning::PartitionUse &PU = P.getUse(PI, Idx);
1380 if (!PU.U)
1381 continue; // Skip dead use.
1382
1383 visit(cast<Instruction>(PU.U->getUser()));
1384 }
1385 }
1386
1387private:
1388 // By default, skip this instruction.
1389 void visitInstruction(Instruction &I) {}
1390
1391 /// PHI instructions that use an alloca and are subsequently loaded can be
1392 /// rewritten to load both input pointers in the pred blocks and then PHI the
1393 /// results, allowing the load of the alloca to be promoted.
1394 /// From this:
1395 /// %P2 = phi [i32* %Alloca, i32* %Other]
1396 /// %V = load i32* %P2
1397 /// to:
1398 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1399 /// ...
1400 /// %V2 = load i32* %Other
1401 /// ...
1402 /// %V = phi [i32 %V1, i32 %V2]
1403 ///
1404 /// We can do this to a select if its only uses are loads and if the operands
1405 /// to the select can be loaded unconditionally.
1406 ///
1407 /// FIXME: This should be hoisted into a generic utility, likely in
1408 /// Transforms/Util/Local.h
1409 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
1410 // For now, we can only do this promotion if the load is in the same block
1411 // as the PHI, and if there are no stores between the phi and load.
1412 // TODO: Allow recursive phi users.
1413 // TODO: Allow stores.
1414 BasicBlock *BB = PN.getParent();
1415 unsigned MaxAlign = 0;
1416 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
1417 UI != UE; ++UI) {
1418 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1419 if (LI == 0 || !LI->isSimple()) return false;
1420
1421 // For now we only allow loads in the same block as the PHI. This is
1422 // a common case that happens when instcombine merges two loads through
1423 // a PHI.
1424 if (LI->getParent() != BB) return false;
1425
1426 // Ensure that there are no instructions between the PHI and the load that
1427 // could store.
1428 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1429 if (BBI->mayWriteToMemory())
1430 return false;
1431
1432 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1433 Loads.push_back(LI);
1434 }
1435
1436 // We can only transform this if it is safe to push the loads into the
1437 // predecessor blocks. The only thing to watch out for is that we can't put
1438 // a possibly trapping load in the predecessor if it is a critical edge.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00001439 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001440 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1441 Value *InVal = PN.getIncomingValue(Idx);
1442
1443 // If the value is produced by the terminator of the predecessor (an
1444 // invoke) or it has side-effects, there is no valid place to put a load
1445 // in the predecessor.
1446 if (TI == InVal || TI->mayHaveSideEffects())
1447 return false;
1448
1449 // If the predecessor has a single successor, then the edge isn't
1450 // critical.
1451 if (TI->getNumSuccessors() == 1)
1452 continue;
1453
1454 // If this pointer is always safe to load, or if we can prove that there
1455 // is already a load in the block, then we can move the load to the pred
1456 // block.
1457 if (InVal->isDereferenceablePointer() ||
1458 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
1459 continue;
1460
1461 return false;
1462 }
1463
1464 return true;
1465 }
1466
1467 void visitPHINode(PHINode &PN) {
1468 DEBUG(dbgs() << " original: " << PN << "\n");
1469
1470 SmallVector<LoadInst *, 4> Loads;
1471 if (!isSafePHIToSpeculate(PN, Loads))
1472 return;
1473
1474 assert(!Loads.empty());
1475
1476 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1477 IRBuilder<> PHIBuilder(&PN);
1478 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1479 PN.getName() + ".sroa.speculated");
1480
1481 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001482 // matter which one we get and if any differ.
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001483 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
1484 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1485 unsigned Align = SomeLoad->getAlignment();
1486
1487 // Rewrite all loads of the PN to use the new PHI.
1488 do {
1489 LoadInst *LI = Loads.pop_back_val();
1490 LI->replaceAllUsesWith(NewPN);
Chandler Carruth18db7952012-11-20 01:12:50 +00001491 Pass.DeadInsts.insert(LI);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001492 } while (!Loads.empty());
1493
1494 // Inject loads into all of the pred blocks.
1495 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1496 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1497 TerminatorInst *TI = Pred->getTerminator();
1498 Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
1499 Value *InVal = PN.getIncomingValue(Idx);
1500 IRBuilder<> PredBuilder(TI);
1501
1502 LoadInst *Load
1503 = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
1504 Pred->getName()));
1505 ++NumLoadsSpeculated;
1506 Load->setAlignment(Align);
1507 if (TBAATag)
1508 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1509 NewPN->addIncoming(Load, Pred);
1510
1511 Instruction *Ptr = dyn_cast<Instruction>(InVal);
1512 if (!Ptr)
1513 // No uses to rewrite.
1514 continue;
1515
1516 // Try to lookup and rewrite any partition uses corresponding to this phi
1517 // input.
1518 AllocaPartitioning::iterator PI
1519 = P.findPartitionForPHIOrSelectOperand(InUse);
1520 if (PI == P.end())
1521 continue;
1522
1523 // Replace the Use in the PartitionUse for this operand with the Use
1524 // inside the load.
1525 AllocaPartitioning::use_iterator UI
1526 = P.findPartitionUseForPHIOrSelectOperand(InUse);
1527 assert(isa<PHINode>(*UI->U->getUser()));
1528 UI->U = &Load->getOperandUse(Load->getPointerOperandIndex());
1529 }
1530 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1531 }
1532
1533 /// Select instructions that use an alloca and are subsequently loaded can be
1534 /// rewritten to load both input pointers and then select between the result,
1535 /// allowing the load of the alloca to be promoted.
1536 /// From this:
1537 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1538 /// %V = load i32* %P2
1539 /// to:
1540 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1541 /// %V2 = load i32* %Other
1542 /// %V = select i1 %cond, i32 %V1, i32 %V2
1543 ///
1544 /// We can do this to a select if its only uses are loads and if the operand
1545 /// to the select can be loaded unconditionally.
1546 bool isSafeSelectToSpeculate(SelectInst &SI,
1547 SmallVectorImpl<LoadInst *> &Loads) {
1548 Value *TValue = SI.getTrueValue();
1549 Value *FValue = SI.getFalseValue();
1550 bool TDerefable = TValue->isDereferenceablePointer();
1551 bool FDerefable = FValue->isDereferenceablePointer();
1552
1553 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
1554 UI != UE; ++UI) {
1555 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1556 if (LI == 0 || !LI->isSimple()) return false;
1557
1558 // Both operands to the select need to be dereferencable, either
1559 // absolutely (e.g. allocas) or at this point because we can see other
1560 // accesses to it.
1561 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
1562 LI->getAlignment(), &TD))
1563 return false;
1564 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
1565 LI->getAlignment(), &TD))
1566 return false;
1567 Loads.push_back(LI);
1568 }
1569
1570 return true;
1571 }
1572
1573 void visitSelectInst(SelectInst &SI) {
1574 DEBUG(dbgs() << " original: " << SI << "\n");
1575 IRBuilder<> IRB(&SI);
1576
1577 // If the select isn't safe to speculate, just use simple logic to emit it.
1578 SmallVector<LoadInst *, 4> Loads;
1579 if (!isSafeSelectToSpeculate(SI, Loads))
1580 return;
1581
1582 Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) };
1583 AllocaPartitioning::iterator PIs[2];
1584 AllocaPartitioning::PartitionUse PUs[2];
1585 for (unsigned i = 0, e = 2; i != e; ++i) {
1586 PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]);
1587 if (PIs[i] != P.end()) {
1588 // If the pointer is within the partitioning, remove the select from
1589 // its uses. We'll add in the new loads below.
1590 AllocaPartitioning::use_iterator UI
1591 = P.findPartitionUseForPHIOrSelectOperand(Ops[i]);
1592 PUs[i] = *UI;
1593 // Clear out the use here so that the offsets into the use list remain
1594 // stable but this use is ignored when rewriting.
1595 UI->U = 0;
1596 }
1597 }
1598
1599 Value *TV = SI.getTrueValue();
1600 Value *FV = SI.getFalseValue();
1601 // Replace the loads of the select with a select of two loads.
1602 while (!Loads.empty()) {
1603 LoadInst *LI = Loads.pop_back_val();
1604
1605 IRB.SetInsertPoint(LI);
1606 LoadInst *TL =
1607 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1608 LoadInst *FL =
1609 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1610 NumLoadsSpeculated += 2;
1611
1612 // Transfer alignment and TBAA info if present.
1613 TL->setAlignment(LI->getAlignment());
1614 FL->setAlignment(LI->getAlignment());
1615 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1616 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1617 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1618 }
1619
1620 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1621 LI->getName() + ".sroa.speculated");
1622
1623 LoadInst *Loads[2] = { TL, FL };
1624 for (unsigned i = 0, e = 2; i != e; ++i) {
1625 if (PIs[i] != P.end()) {
1626 Use *LoadUse = &Loads[i]->getOperandUse(0);
1627 assert(PUs[i].U->get() == LoadUse->get());
1628 PUs[i].U = LoadUse;
1629 P.use_push_back(PIs[i], PUs[i]);
1630 }
1631 }
1632
1633 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1634 LI->replaceAllUsesWith(V);
Chandler Carruth18db7952012-11-20 01:12:50 +00001635 Pass.DeadInsts.insert(LI);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001636 }
1637 }
1638};
1639}
1640
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001641/// \brief Build a GEP out of a base pointer and indices.
1642///
1643/// This will return the BasePtr if that is valid, or build a new GEP
1644/// instruction using the IRBuilder if GEP-ing is needed.
1645static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1646 SmallVectorImpl<Value *> &Indices,
1647 const Twine &Prefix) {
1648 if (Indices.empty())
1649 return BasePtr;
1650
1651 // A single zero index is a no-op, so check for this and avoid building a GEP
1652 // in that case.
1653 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1654 return BasePtr;
1655
1656 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1657}
1658
1659/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1660/// TargetTy without changing the offset of the pointer.
1661///
1662/// This routine assumes we've already established a properly offset GEP with
1663/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1664/// zero-indices down through type layers until we find one the same as
1665/// TargetTy. If we can't find one with the same type, we at least try to use
1666/// one with the same size. If none of that works, we just produce the GEP as
1667/// indicated by Indices to have the correct offset.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001668static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001669 Value *BasePtr, Type *Ty, Type *TargetTy,
1670 SmallVectorImpl<Value *> &Indices,
1671 const Twine &Prefix) {
1672 if (Ty == TargetTy)
1673 return buildGEP(IRB, BasePtr, Indices, Prefix);
1674
1675 // See if we can descend into a struct and locate a field with the correct
1676 // type.
1677 unsigned NumLayers = 0;
1678 Type *ElementTy = Ty;
1679 do {
1680 if (ElementTy->isPointerTy())
1681 break;
1682 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1683 ElementTy = SeqTy->getElementType();
Chandler Carruth40617f52012-10-17 07:22:16 +00001684 // Note that we use the default address space as this index is over an
1685 // array or a vector, not a pointer.
1686 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(0), 0)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001687 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001688 if (STy->element_begin() == STy->element_end())
1689 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001690 ElementTy = *STy->element_begin();
1691 Indices.push_back(IRB.getInt32(0));
1692 } else {
1693 break;
1694 }
1695 ++NumLayers;
1696 } while (ElementTy != TargetTy);
1697 if (ElementTy != TargetTy)
1698 Indices.erase(Indices.end() - NumLayers, Indices.end());
1699
1700 return buildGEP(IRB, BasePtr, Indices, Prefix);
1701}
1702
1703/// \brief Recursively compute indices for a natural GEP.
1704///
1705/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1706/// element types adding appropriate indices for the GEP.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001707static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001708 Value *Ptr, Type *Ty, APInt &Offset,
1709 Type *TargetTy,
1710 SmallVectorImpl<Value *> &Indices,
1711 const Twine &Prefix) {
1712 if (Offset == 0)
1713 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1714
1715 // We can't recurse through pointer types.
1716 if (Ty->isPointerTy())
1717 return 0;
1718
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001719 // We try to analyze GEPs over vectors here, but note that these GEPs are
1720 // extremely poorly defined currently. The long-term goal is to remove GEPing
1721 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001722 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Nadav Rotema5024fc2012-12-18 05:23:31 +00001723 unsigned ElementSizeInBits = TD.getTypeSizeInBits(VecTy->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001724 if (ElementSizeInBits % 8)
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001725 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001726 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001727 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001728 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1729 return 0;
1730 Offset -= NumSkippedElements * ElementSize;
1731 Indices.push_back(IRB.getInt(NumSkippedElements));
1732 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1733 Offset, TargetTy, Indices, Prefix);
1734 }
1735
1736 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1737 Type *ElementTy = ArrTy->getElementType();
1738 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001739 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001740 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1741 return 0;
1742
1743 Offset -= NumSkippedElements * ElementSize;
1744 Indices.push_back(IRB.getInt(NumSkippedElements));
1745 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1746 Indices, Prefix);
1747 }
1748
1749 StructType *STy = dyn_cast<StructType>(Ty);
1750 if (!STy)
1751 return 0;
1752
1753 const StructLayout *SL = TD.getStructLayout(STy);
1754 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001755 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001756 return 0;
1757 unsigned Index = SL->getElementContainingOffset(StructOffset);
1758 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1759 Type *ElementTy = STy->getElementType(Index);
1760 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1761 return 0; // The offset points into alignment padding.
1762
1763 Indices.push_back(IRB.getInt32(Index));
1764 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1765 Indices, Prefix);
1766}
1767
1768/// \brief Get a natural GEP from a base pointer to a particular offset and
1769/// resulting in a particular type.
1770///
1771/// The goal is to produce a "natural" looking GEP that works with the existing
1772/// composite types to arrive at the appropriate offset and element type for
1773/// a pointer. TargetTy is the element type the returned GEP should point-to if
1774/// possible. We recurse by decreasing Offset, adding the appropriate index to
1775/// Indices, and setting Ty to the result subtype.
1776///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001777/// If no natural GEP can be constructed, this function returns null.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001778static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001779 Value *Ptr, APInt Offset, Type *TargetTy,
1780 SmallVectorImpl<Value *> &Indices,
1781 const Twine &Prefix) {
1782 PointerType *Ty = cast<PointerType>(Ptr->getType());
1783
1784 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1785 // an i8.
1786 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1787 return 0;
1788
1789 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001790 if (!ElementTy->isSized())
1791 return 0; // We can't GEP through an unsized element.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001792 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1793 if (ElementSize == 0)
1794 return 0; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001795 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001796
1797 Offset -= NumSkippedElements * ElementSize;
1798 Indices.push_back(IRB.getInt(NumSkippedElements));
1799 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1800 Indices, Prefix);
1801}
1802
1803/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1804/// resulting pointer has PointerTy.
1805///
1806/// This tries very hard to compute a "natural" GEP which arrives at the offset
1807/// and produces the pointer type desired. Where it cannot, it will try to use
1808/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1809/// fails, it will try to use an existing i8* and GEP to the byte offset and
1810/// bitcast to the type.
1811///
1812/// The strategy for finding the more natural GEPs is to peel off layers of the
1813/// pointer, walking back through bit casts and GEPs, searching for a base
1814/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001815/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001816/// a single GEP as possible, thus making each GEP more independent of the
1817/// surrounding code.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001818static Value *getAdjustedPtr(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001819 Value *Ptr, APInt Offset, Type *PointerTy,
1820 const Twine &Prefix) {
1821 // Even though we don't look through PHI nodes, we could be called on an
1822 // instruction in an unreachable block, which may be on a cycle.
1823 SmallPtrSet<Value *, 4> Visited;
1824 Visited.insert(Ptr);
1825 SmallVector<Value *, 4> Indices;
1826
1827 // We may end up computing an offset pointer that has the wrong type. If we
1828 // never are able to compute one directly that has the correct type, we'll
1829 // fall back to it, so keep it around here.
1830 Value *OffsetPtr = 0;
1831
1832 // Remember any i8 pointer we come across to re-use if we need to do a raw
1833 // byte offset.
1834 Value *Int8Ptr = 0;
1835 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1836
1837 Type *TargetTy = PointerTy->getPointerElementType();
1838
1839 do {
1840 // First fold any existing GEPs into the offset.
1841 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1842 APInt GEPOffset(Offset.getBitWidth(), 0);
Nuno Lopesb6ad9822012-12-30 16:25:48 +00001843 if (!GEP->accumulateConstantOffset(TD, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001844 break;
1845 Offset += GEPOffset;
1846 Ptr = GEP->getPointerOperand();
1847 if (!Visited.insert(Ptr))
1848 break;
1849 }
1850
1851 // See if we can perform a natural GEP here.
1852 Indices.clear();
1853 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1854 Indices, Prefix)) {
1855 if (P->getType() == PointerTy) {
1856 // Zap any offset pointer that we ended up computing in previous rounds.
1857 if (OffsetPtr && OffsetPtr->use_empty())
1858 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1859 I->eraseFromParent();
1860 return P;
1861 }
1862 if (!OffsetPtr) {
1863 OffsetPtr = P;
1864 }
1865 }
1866
1867 // Stash this pointer if we've found an i8*.
1868 if (Ptr->getType()->isIntegerTy(8)) {
1869 Int8Ptr = Ptr;
1870 Int8PtrOffset = Offset;
1871 }
1872
1873 // Peel off a layer of the pointer and update the offset appropriately.
1874 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1875 Ptr = cast<Operator>(Ptr)->getOperand(0);
1876 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1877 if (GA->mayBeOverridden())
1878 break;
1879 Ptr = GA->getAliasee();
1880 } else {
1881 break;
1882 }
1883 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1884 } while (Visited.insert(Ptr));
1885
1886 if (!OffsetPtr) {
1887 if (!Int8Ptr) {
1888 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1889 Prefix + ".raw_cast");
1890 Int8PtrOffset = Offset;
1891 }
1892
1893 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1894 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1895 Prefix + ".raw_idx");
1896 }
1897 Ptr = OffsetPtr;
1898
1899 // On the off chance we were targeting i8*, guard the bitcast here.
1900 if (Ptr->getType() != PointerTy)
1901 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
1902
1903 return Ptr;
1904}
1905
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001906/// \brief Test whether we can convert a value from the old to the new type.
1907///
1908/// This predicate should be used to guard calls to convertValue in order to
1909/// ensure that we only try to convert viable values. The strategy is that we
1910/// will peel off single element struct and array wrappings to get to an
1911/// underlying value, and convert that value.
1912static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1913 if (OldTy == NewTy)
1914 return true;
1915 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1916 return false;
1917 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1918 return false;
1919
1920 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1921 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1922 return true;
1923 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1924 return true;
1925 return false;
1926 }
1927
1928 return true;
1929}
1930
1931/// \brief Generic routine to convert an SSA value to a value of a different
1932/// type.
1933///
1934/// This will try various different casting techniques, such as bitcasts,
1935/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1936/// two types for viability with this routine.
1937static Value *convertValue(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
1938 Type *Ty) {
1939 assert(canConvertValue(DL, V->getType(), Ty) &&
1940 "Value not convertable to type");
1941 if (V->getType() == Ty)
1942 return V;
1943 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1944 return IRB.CreateIntToPtr(V, Ty);
1945 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1946 return IRB.CreatePtrToInt(V, Ty);
1947
1948 return IRB.CreateBitCast(V, Ty);
1949}
1950
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001951/// \brief Test whether the given alloca partition can be promoted to a vector.
1952///
1953/// This is a quick test to check whether we can rewrite a particular alloca
1954/// partition (and its newly formed alloca) into a vector alloca with only
1955/// whole-vector loads and stores such that it could be promoted to a vector
1956/// SSA value. We only can ensure this for a limited set of operations, and we
1957/// don't want to do the rewrites unless we are confident that the result will
1958/// be promotable, so we have an early test here.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001959static bool isVectorPromotionViable(const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001960 Type *AllocaTy,
1961 AllocaPartitioning &P,
1962 uint64_t PartitionBeginOffset,
1963 uint64_t PartitionEndOffset,
1964 AllocaPartitioning::const_use_iterator I,
1965 AllocaPartitioning::const_use_iterator E) {
1966 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1967 if (!Ty)
1968 return false;
1969
Nadav Rotema5024fc2012-12-18 05:23:31 +00001970 uint64_t ElementSize = TD.getTypeSizeInBits(Ty->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001971
1972 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1973 // that aren't byte sized.
1974 if (ElementSize % 8)
1975 return false;
Benjamin Kramerc003a452013-01-01 16:13:35 +00001976 assert((TD.getTypeSizeInBits(Ty) % 8) == 0 &&
1977 "vector size not a multiple of element size?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001978 ElementSize /= 8;
1979
1980 for (; I != E; ++I) {
Chandler Carruth6c3890b2012-10-02 18:57:13 +00001981 if (!I->U)
1982 continue; // Skip dead use.
1983
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001984 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
1985 uint64_t BeginIndex = BeginOffset / ElementSize;
1986 if (BeginIndex * ElementSize != BeginOffset ||
1987 BeginIndex >= Ty->getNumElements())
1988 return false;
1989 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
1990 uint64_t EndIndex = EndOffset / ElementSize;
1991 if (EndIndex * ElementSize != EndOffset ||
1992 EndIndex > Ty->getNumElements())
1993 return false;
1994
Chandler Carruth845b73c2012-11-21 08:16:30 +00001995 assert(EndIndex > BeginIndex && "Empty vector!");
1996 uint64_t NumElements = EndIndex - BeginIndex;
1997 Type *PartitionTy
1998 = (NumElements == 1) ? Ty->getElementType()
1999 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002000
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002001 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002002 if (MI->isVolatile())
2003 return false;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002004 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002005 const AllocaPartitioning::MemTransferOffsets &MTO
2006 = P.getMemTransferOffsets(*MTI);
2007 if (!MTO.IsSplittable)
2008 return false;
2009 }
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002010 } else if (I->U->get()->getType()->getPointerElementType()->isStructTy()) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002011 // Disable vector promotion when there are loads or stores of an FCA.
2012 return false;
Chandler Carruth18db7952012-11-20 01:12:50 +00002013 } else if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
2014 if (LI->isVolatile())
2015 return false;
Chandler Carruth845b73c2012-11-21 08:16:30 +00002016 if (!canConvertValue(TD, PartitionTy, LI->getType()))
2017 return false;
Chandler Carruth18db7952012-11-20 01:12:50 +00002018 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
2019 if (SI->isVolatile())
2020 return false;
Chandler Carruth845b73c2012-11-21 08:16:30 +00002021 if (!canConvertValue(TD, SI->getValueOperand()->getType(), PartitionTy))
2022 return false;
Chandler Carruth18db7952012-11-20 01:12:50 +00002023 } else {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002024 return false;
2025 }
2026 }
2027 return true;
2028}
2029
Chandler Carruth435c4e02012-10-15 08:40:30 +00002030/// \brief Test whether the given alloca partition's integer operations can be
2031/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002032///
Chandler Carruth435c4e02012-10-15 08:40:30 +00002033/// This is a quick test to check whether we can rewrite the integer loads and
2034/// stores to a particular alloca into wider loads and stores and be able to
2035/// promote the resulting alloca.
2036static bool isIntegerWideningViable(const DataLayout &TD,
2037 Type *AllocaTy,
2038 uint64_t AllocBeginOffset,
2039 AllocaPartitioning &P,
2040 AllocaPartitioning::const_use_iterator I,
2041 AllocaPartitioning::const_use_iterator E) {
2042 uint64_t SizeInBits = TD.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00002043 // Don't create integer types larger than the maximum bitwidth.
2044 if (SizeInBits > IntegerType::MAX_INT_BITS)
2045 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002046
2047 // Don't try to handle allocas with bit-padding.
2048 if (SizeInBits != TD.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002049 return false;
2050
Chandler Carruth58d05562012-10-25 04:37:07 +00002051 // We need to ensure that an integer type with the appropriate bitwidth can
2052 // be converted to the alloca type, whatever that is. We don't want to force
2053 // the alloca itself to have an integer type if there is a more suitable one.
2054 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2055 if (!canConvertValue(TD, AllocaTy, IntTy) ||
2056 !canConvertValue(TD, IntTy, AllocaTy))
2057 return false;
2058
Chandler Carruth435c4e02012-10-15 08:40:30 +00002059 uint64_t Size = TD.getTypeStoreSize(AllocaTy);
2060
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002061 // Check the uses to ensure the uses are (likely) promotable integer uses.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002062 // Also ensure that the alloca has a covering load or store. We don't want
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002063 // to widen the integer operations only to fail to promote due to some other
Chandler Carruth435c4e02012-10-15 08:40:30 +00002064 // unsplittable entry (which we may make splittable later).
Chandler Carruth92924fd2012-09-24 00:34:20 +00002065 bool WholeAllocaOp = false;
2066 for (; I != E; ++I) {
Chandler Carruth6c3890b2012-10-02 18:57:13 +00002067 if (!I->U)
2068 continue; // Skip dead use.
Chandler Carruth43c8b462012-10-04 10:39:28 +00002069
Chandler Carruth435c4e02012-10-15 08:40:30 +00002070 uint64_t RelBegin = I->BeginOffset - AllocBeginOffset;
2071 uint64_t RelEnd = I->EndOffset - AllocBeginOffset;
2072
Chandler Carruth43c8b462012-10-04 10:39:28 +00002073 // We can't reasonably handle cases where the load or store extends past
2074 // the end of the aloca's type and into its padding.
Chandler Carruth435c4e02012-10-15 08:40:30 +00002075 if (RelEnd > Size)
Chandler Carruth43c8b462012-10-04 10:39:28 +00002076 return false;
2077
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002078 if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
Chandler Carruth435c4e02012-10-15 08:40:30 +00002079 if (LI->isVolatile())
Chandler Carruth92924fd2012-09-24 00:34:20 +00002080 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002081 if (RelBegin == 0 && RelEnd == Size)
Chandler Carruth92924fd2012-09-24 00:34:20 +00002082 WholeAllocaOp = true;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002083 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruthe45f4652012-12-10 00:54:45 +00002084 if (ITy->getBitWidth() < TD.getTypeStoreSizeInBits(ITy))
Chandler Carruth435c4e02012-10-15 08:40:30 +00002085 return false;
2086 continue;
2087 }
2088 // Non-integer loads need to be convertible from the alloca type so that
2089 // they are promotable.
2090 if (RelBegin != 0 || RelEnd != Size ||
2091 !canConvertValue(TD, AllocaTy, LI->getType()))
2092 return false;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002093 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
Chandler Carruth435c4e02012-10-15 08:40:30 +00002094 Type *ValueTy = SI->getValueOperand()->getType();
2095 if (SI->isVolatile())
Chandler Carruth92924fd2012-09-24 00:34:20 +00002096 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002097 if (RelBegin == 0 && RelEnd == Size)
Chandler Carruth92924fd2012-09-24 00:34:20 +00002098 WholeAllocaOp = true;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002099 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruthe45f4652012-12-10 00:54:45 +00002100 if (ITy->getBitWidth() < TD.getTypeStoreSizeInBits(ITy))
Chandler Carruth435c4e02012-10-15 08:40:30 +00002101 return false;
2102 continue;
2103 }
2104 // Non-integer stores need to be convertible to the alloca type so that
2105 // they are promotable.
2106 if (RelBegin != 0 || RelEnd != Size ||
2107 !canConvertValue(TD, ValueTy, AllocaTy))
2108 return false;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002109 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
Chandler Carruthe3f41192012-12-17 18:48:07 +00002110 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002111 return false;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002112 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
Chandler Carruth92924fd2012-09-24 00:34:20 +00002113 const AllocaPartitioning::MemTransferOffsets &MTO
2114 = P.getMemTransferOffsets(*MTI);
2115 if (!MTO.IsSplittable)
2116 return false;
2117 }
Chandler Carruth435c4e02012-10-15 08:40:30 +00002118 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->U->getUser())) {
2119 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2120 II->getIntrinsicID() != Intrinsic::lifetime_end)
2121 return false;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002122 } else {
2123 return false;
2124 }
2125 }
2126 return WholeAllocaOp;
2127}
2128
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002129static Value *extractInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2130 IntegerType *Ty, uint64_t Offset,
2131 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002132 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002133 IntegerType *IntTy = cast<IntegerType>(V->getType());
2134 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2135 "Element extends past full value");
2136 uint64_t ShAmt = 8*Offset;
2137 if (DL.isBigEndian())
2138 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002139 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002140 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002141 DEBUG(dbgs() << " shifted: " << *V << "\n");
2142 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002143 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2144 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002145 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002146 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00002147 DEBUG(dbgs() << " trunced: " << *V << "\n");
2148 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002149 return V;
2150}
2151
2152static Value *insertInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *Old,
2153 Value *V, uint64_t Offset, const Twine &Name) {
2154 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2155 IntegerType *Ty = cast<IntegerType>(V->getType());
2156 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2157 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002158 DEBUG(dbgs() << " start: " << *V << "\n");
2159 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002160 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00002161 DEBUG(dbgs() << " extended: " << *V << "\n");
2162 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002163 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2164 "Element store outside of alloca store");
2165 uint64_t ShAmt = 8*Offset;
2166 if (DL.isBigEndian())
2167 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002168 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002169 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002170 DEBUG(dbgs() << " shifted: " << *V << "\n");
2171 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002172
2173 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2174 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2175 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00002176 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002177 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00002178 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002179 }
2180 return V;
2181}
2182
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002183static Value *extractVector(IRBuilder<> &IRB, Value *V,
2184 unsigned BeginIndex, unsigned EndIndex,
2185 const Twine &Name) {
2186 VectorType *VecTy = cast<VectorType>(V->getType());
2187 unsigned NumElements = EndIndex - BeginIndex;
2188 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2189
2190 if (NumElements == VecTy->getNumElements())
2191 return V;
2192
2193 if (NumElements == 1) {
2194 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2195 Name + ".extract");
2196 DEBUG(dbgs() << " extract: " << *V << "\n");
2197 return V;
2198 }
2199
2200 SmallVector<Constant*, 8> Mask;
2201 Mask.reserve(NumElements);
2202 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2203 Mask.push_back(IRB.getInt32(i));
2204 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2205 ConstantVector::get(Mask),
2206 Name + ".extract");
2207 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2208 return V;
2209}
2210
Chandler Carruthce4562b2012-12-17 13:41:21 +00002211static Value *insertVector(IRBuilder<> &IRB, Value *Old, Value *V,
2212 unsigned BeginIndex, const Twine &Name) {
2213 VectorType *VecTy = cast<VectorType>(Old->getType());
2214 assert(VecTy && "Can only insert a vector into a vector");
2215
2216 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2217 if (!Ty) {
2218 // Single element to insert.
2219 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2220 Name + ".insert");
2221 DEBUG(dbgs() << " insert: " << *V << "\n");
2222 return V;
2223 }
2224
2225 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2226 "Too many elements!");
2227 if (Ty->getNumElements() == VecTy->getNumElements()) {
2228 assert(V->getType() == VecTy && "Vector type mismatch");
2229 return V;
2230 }
2231 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2232
2233 // When inserting a smaller vector into the larger to store, we first
2234 // use a shuffle vector to widen it with undef elements, and then
2235 // a second shuffle vector to select between the loaded vector and the
2236 // incoming vector.
2237 SmallVector<Constant*, 8> Mask;
2238 Mask.reserve(VecTy->getNumElements());
2239 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2240 if (i >= BeginIndex && i < EndIndex)
2241 Mask.push_back(IRB.getInt32(i - BeginIndex));
2242 else
2243 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2244 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2245 ConstantVector::get(Mask),
2246 Name + ".expand");
2247 DEBUG(dbgs() << " shuffle1: " << *V << "\n");
2248
2249 Mask.clear();
2250 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2251 if (i >= BeginIndex && i < EndIndex)
2252 Mask.push_back(IRB.getInt32(i));
2253 else
2254 Mask.push_back(IRB.getInt32(i + VecTy->getNumElements()));
2255 V = IRB.CreateShuffleVector(V, Old, ConstantVector::get(Mask),
2256 Name + "insert");
2257 DEBUG(dbgs() << " shuffle2: " << *V << "\n");
2258 return V;
2259}
2260
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002261namespace {
2262/// \brief Visitor to rewrite instructions using a partition of an alloca to
2263/// use a new alloca.
2264///
2265/// Also implements the rewriting to vector-based accesses when the partition
2266/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2267/// lives here.
2268class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
2269 bool> {
2270 // Befriend the base class so it can delegate to private visit methods.
2271 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
2272
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002273 const DataLayout &TD;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002274 AllocaPartitioning &P;
2275 SROA &Pass;
2276 AllocaInst &OldAI, &NewAI;
2277 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002278 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002279
2280 // If we are rewriting an alloca partition which can be written as pure
2281 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002282 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002283 // - The new alloca is exactly the size of the vector type here.
2284 // - The accesses all either map to the entire vector or to a single
2285 // element.
2286 // - The set of accessing instructions is only one of those handled above
2287 // in isVectorPromotionViable. Generally these are the same access kinds
2288 // which are promotable via mem2reg.
2289 VectorType *VecTy;
2290 Type *ElementTy;
2291 uint64_t ElementSize;
2292
Chandler Carruth92924fd2012-09-24 00:34:20 +00002293 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth435c4e02012-10-15 08:40:30 +00002294 // alloca's integer operations should be widened to this integer type due to
2295 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruth92924fd2012-09-24 00:34:20 +00002296 // integer type will be stored here for easy access during rewriting.
Chandler Carruth435c4e02012-10-15 08:40:30 +00002297 IntegerType *IntTy;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002298
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002299 // The offset of the partition user currently being rewritten.
2300 uint64_t BeginOffset, EndOffset;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002301 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002302 Instruction *OldPtr;
2303
2304 // The name prefix to use when rewriting instructions for this alloca.
2305 std::string NamePrefix;
2306
2307public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002308 AllocaPartitionRewriter(const DataLayout &TD, AllocaPartitioning &P,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002309 AllocaPartitioning::iterator PI,
2310 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
2311 uint64_t NewBeginOffset, uint64_t NewEndOffset)
2312 : TD(TD), P(P), Pass(Pass),
2313 OldAI(OldAI), NewAI(NewAI),
2314 NewAllocaBeginOffset(NewBeginOffset),
2315 NewAllocaEndOffset(NewEndOffset),
Chandler Carruth891fec02012-10-13 02:41:05 +00002316 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruth435c4e02012-10-15 08:40:30 +00002317 VecTy(), ElementTy(), ElementSize(), IntTy(),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002318 BeginOffset(), EndOffset() {
2319 }
2320
2321 /// \brief Visit the users of the alloca partition and rewrite them.
2322 bool visitUsers(AllocaPartitioning::const_use_iterator I,
2323 AllocaPartitioning::const_use_iterator E) {
2324 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
2325 NewAllocaBeginOffset, NewAllocaEndOffset,
2326 I, E)) {
2327 ++NumVectorized;
2328 VecTy = cast<VectorType>(NewAI.getAllocatedType());
2329 ElementTy = VecTy->getElementType();
Nadav Rotema5024fc2012-12-18 05:23:31 +00002330 assert((TD.getTypeSizeInBits(VecTy->getScalarType()) % 8) == 0 &&
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002331 "Only multiple-of-8 sized vector elements are viable");
Nadav Rotema5024fc2012-12-18 05:23:31 +00002332 ElementSize = TD.getTypeSizeInBits(VecTy->getScalarType()) / 8;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002333 } else if (isIntegerWideningViable(TD, NewAI.getAllocatedType(),
2334 NewAllocaBeginOffset, P, I, E)) {
2335 IntTy = Type::getIntNTy(NewAI.getContext(),
2336 TD.getTypeSizeInBits(NewAI.getAllocatedType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002337 }
2338 bool CanSROA = true;
2339 for (; I != E; ++I) {
Chandler Carruth6c3890b2012-10-02 18:57:13 +00002340 if (!I->U)
2341 continue; // Skip dead uses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002342 BeginOffset = I->BeginOffset;
2343 EndOffset = I->EndOffset;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002344 OldUse = I->U;
2345 OldPtr = cast<Instruction>(I->U->get());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002346 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002347 CanSROA &= visit(cast<Instruction>(I->U->getUser()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002348 }
2349 if (VecTy) {
2350 assert(CanSROA);
2351 VecTy = 0;
2352 ElementTy = 0;
2353 ElementSize = 0;
2354 }
Chandler Carruth435c4e02012-10-15 08:40:30 +00002355 if (IntTy) {
2356 assert(CanSROA);
2357 IntTy = 0;
2358 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002359 return CanSROA;
2360 }
2361
2362private:
2363 // Every instruction which can end up as a user must have a rewrite rule.
2364 bool visitInstruction(Instruction &I) {
2365 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2366 llvm_unreachable("No rewrite rule for this instruction!");
2367 }
2368
2369 Twine getName(const Twine &Suffix) {
2370 return NamePrefix + Suffix;
2371 }
2372
2373 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
2374 assert(BeginOffset >= NewAllocaBeginOffset);
Chandler Carruth5da3f052012-11-01 09:14:31 +00002375 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002376 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
2377 }
2378
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002379 /// \brief Compute suitable alignment to access an offset into the new alloca.
2380 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002381 unsigned NewAIAlign = NewAI.getAlignment();
2382 if (!NewAIAlign)
2383 NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
2384 return MinAlign(NewAIAlign, Offset);
2385 }
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002386
2387 /// \brief Compute suitable alignment to access this partition of the new
2388 /// alloca.
2389 unsigned getPartitionAlign() {
2390 return getOffsetAlign(BeginOffset - NewAllocaBeginOffset);
Chandler Carruth176ca712012-10-01 12:16:54 +00002391 }
2392
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002393 /// \brief Compute suitable alignment to access a type at an offset of the
2394 /// new alloca.
2395 ///
2396 /// \returns zero if the type's ABI alignment is a suitable alignment,
2397 /// otherwise returns the maximal suitable alignment.
2398 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2399 unsigned Align = getOffsetAlign(Offset);
2400 return Align == TD.getABITypeAlignment(Ty) ? 0 : Align;
2401 }
2402
2403 /// \brief Compute suitable alignment to access a type at the beginning of
2404 /// this partition of the new alloca.
2405 ///
2406 /// See \c getOffsetTypeAlign for details; this routine delegates to it.
2407 unsigned getPartitionTypeAlign(Type *Ty) {
2408 return getOffsetTypeAlign(Ty, BeginOffset - NewAllocaBeginOffset);
Chandler Carruth176ca712012-10-01 12:16:54 +00002409 }
2410
Chandler Carruth845b73c2012-11-21 08:16:30 +00002411 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002412 assert(VecTy && "Can only call getIndex when rewriting a vector");
2413 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2414 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2415 uint32_t Index = RelOffset / ElementSize;
2416 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002417 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002418 }
2419
2420 void deleteIfTriviallyDead(Value *V) {
2421 Instruction *I = cast<Instruction>(V);
2422 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002423 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002424 }
2425
Chandler Carruth769445e2012-12-17 12:50:21 +00002426 Value *rewriteVectorizedLoadInst(IRBuilder<> &IRB) {
2427 unsigned BeginIndex = getIndex(BeginOffset);
2428 unsigned EndIndex = getIndex(EndOffset);
2429 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002430
2431 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2432 getName(".load"));
2433 return extractVector(IRB, V, BeginIndex, EndIndex, getName(".vec"));
Chandler Carruth769445e2012-12-17 12:50:21 +00002434 }
2435
Chandler Carruth18db7952012-11-20 01:12:50 +00002436 Value *rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002437 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002438 assert(!LI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002439 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2440 getName(".load"));
2441 V = convertValue(TD, IRB, V, IntTy);
2442 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2443 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth18db7952012-11-20 01:12:50 +00002444 if (Offset > 0 || EndOffset < NewAllocaEndOffset)
2445 V = extractInteger(TD, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2446 getName(".extract"));
2447 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002448 }
2449
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002450 bool visitLoadInst(LoadInst &LI) {
2451 DEBUG(dbgs() << " original: " << LI << "\n");
2452 Value *OldOp = LI.getOperand(0);
2453 assert(OldOp == OldPtr);
2454 IRBuilder<> IRB(&LI);
2455
Chandler Carruth58d05562012-10-25 04:37:07 +00002456 uint64_t Size = EndOffset - BeginOffset;
Chandler Carruth18db7952012-11-20 01:12:50 +00002457 bool IsSplitIntLoad = Size < TD.getTypeStoreSize(LI.getType());
Chandler Carruth3e994a22012-11-20 10:02:19 +00002458
2459 // If this memory access can be shown to *statically* extend outside the
2460 // bounds of the original allocation it's behavior is undefined. Rather
2461 // than trying to transform it, just replace it with undef.
2462 // FIXME: We should do something more clever for functions being
2463 // instrumented by asan.
2464 // FIXME: Eventually, once ASan and friends can flush out bugs here, this
2465 // should be transformed to a load of null making it unreachable.
2466 uint64_t OldAllocSize = TD.getTypeAllocSize(OldAI.getAllocatedType());
2467 if (TD.getTypeStoreSize(LI.getType()) > OldAllocSize) {
2468 LI.replaceAllUsesWith(UndefValue::get(LI.getType()));
2469 Pass.DeadInsts.insert(&LI);
2470 deleteIfTriviallyDead(OldOp);
2471 DEBUG(dbgs() << " to: undef!!\n");
2472 return true;
2473 }
2474
Chandler Carruth18db7952012-11-20 01:12:50 +00002475 Type *TargetTy = IsSplitIntLoad ? Type::getIntNTy(LI.getContext(), Size * 8)
2476 : LI.getType();
2477 bool IsPtrAdjusted = false;
2478 Value *V;
2479 if (VecTy) {
Chandler Carruth769445e2012-12-17 12:50:21 +00002480 V = rewriteVectorizedLoadInst(IRB);
Chandler Carruth18db7952012-11-20 01:12:50 +00002481 } else if (IntTy && LI.getType()->isIntegerTy()) {
2482 V = rewriteIntegerLoad(IRB, LI);
2483 } else if (BeginOffset == NewAllocaBeginOffset &&
2484 canConvertValue(TD, NewAllocaTy, LI.getType())) {
2485 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2486 LI.isVolatile(), getName(".load"));
2487 } else {
2488 Type *LTy = TargetTy->getPointerTo();
2489 V = IRB.CreateAlignedLoad(getAdjustedAllocaPtr(IRB, LTy),
2490 getPartitionTypeAlign(TargetTy),
2491 LI.isVolatile(), getName(".load"));
2492 IsPtrAdjusted = true;
2493 }
2494 V = convertValue(TD, IRB, V, TargetTy);
2495
2496 if (IsSplitIntLoad) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002497 assert(!LI.isVolatile());
2498 assert(LI.getType()->isIntegerTy() &&
2499 "Only integer type loads and stores are split");
2500 assert(LI.getType()->getIntegerBitWidth() ==
2501 TD.getTypeStoreSizeInBits(LI.getType()) &&
2502 "Non-byte-multiple bit width");
2503 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth1296b592012-10-30 20:52:40 +00002504 TD.getTypeAllocSizeInBits(OldAI.getAllocatedType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002505 "Only alloca-wide loads can be split and recomposed");
Chandler Carruth58d05562012-10-25 04:37:07 +00002506 // Move the insertion point just past the load so that we can refer to it.
2507 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002508 // Create a placeholder value with the same type as LI to use as the
2509 // basis for the new value. This allows us to replace the uses of LI with
2510 // the computed value, and then replace the placeholder with LI, leaving
2511 // LI only used for this computation.
2512 Value *Placeholder
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002513 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth58d05562012-10-25 04:37:07 +00002514 V = insertInteger(TD, IRB, Placeholder, V, BeginOffset,
2515 getName(".insert"));
2516 LI.replaceAllUsesWith(V);
2517 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002518 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002519 } else {
2520 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002521 }
2522
Chandler Carruth18db7952012-11-20 01:12:50 +00002523 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002524 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002525 DEBUG(dbgs() << " to: " << *V << "\n");
2526 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002527 }
2528
Chandler Carruth18db7952012-11-20 01:12:50 +00002529 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, Value *V,
2530 StoreInst &SI, Value *OldOp) {
Chandler Carruth845b73c2012-11-21 08:16:30 +00002531 unsigned BeginIndex = getIndex(BeginOffset);
2532 unsigned EndIndex = getIndex(EndOffset);
2533 assert(EndIndex > BeginIndex && "Empty vector!");
2534 unsigned NumElements = EndIndex - BeginIndex;
2535 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2536 Type *PartitionTy
2537 = (NumElements == 1) ? ElementTy
2538 : VectorType::get(ElementTy, NumElements);
2539 if (V->getType() != PartitionTy)
2540 V = convertValue(TD, IRB, V, PartitionTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002541
Chandler Carrutheae65a52012-12-17 04:07:35 +00002542 // Mix in the existing elements.
Chandler Carruthce4562b2012-12-17 13:41:21 +00002543 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2544 getName(".load"));
2545 V = insertVector(IRB, Old, V, BeginIndex, getName(".vec"));
Chandler Carrutheae65a52012-12-17 04:07:35 +00002546
Chandler Carruth871ba722012-09-26 10:27:46 +00002547 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002548 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002549
2550 (void)Store;
2551 DEBUG(dbgs() << " to: " << *Store << "\n");
2552 return true;
2553 }
2554
Chandler Carruth18db7952012-11-20 01:12:50 +00002555 bool rewriteIntegerStore(IRBuilder<> &IRB, Value *V, StoreInst &SI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002556 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002557 assert(!SI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002558 if (TD.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2559 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2560 getName(".oldload"));
2561 Old = convertValue(TD, IRB, Old, IntTy);
2562 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2563 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2564 V = insertInteger(TD, IRB, Old, SI.getValueOperand(), Offset,
2565 getName(".insert"));
2566 }
2567 V = convertValue(TD, IRB, V, NewAllocaTy);
2568 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002569 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002570 (void)Store;
2571 DEBUG(dbgs() << " to: " << *Store << "\n");
2572 return true;
2573 }
2574
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002575 bool visitStoreInst(StoreInst &SI) {
2576 DEBUG(dbgs() << " original: " << SI << "\n");
2577 Value *OldOp = SI.getOperand(1);
2578 assert(OldOp == OldPtr);
2579 IRBuilder<> IRB(&SI);
2580
Chandler Carruth18db7952012-11-20 01:12:50 +00002581 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002582
Chandler Carruthac8317f2012-10-04 12:33:50 +00002583 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2584 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002585 if (V->getType()->isPointerTy())
2586 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002587 Pass.PostPromotionWorklist.insert(AI);
2588
Chandler Carruth18db7952012-11-20 01:12:50 +00002589 uint64_t Size = EndOffset - BeginOffset;
2590 if (Size < TD.getTypeStoreSize(V->getType())) {
2591 assert(!SI.isVolatile());
2592 assert(V->getType()->isIntegerTy() &&
2593 "Only integer type loads and stores are split");
2594 assert(V->getType()->getIntegerBitWidth() ==
2595 TD.getTypeStoreSizeInBits(V->getType()) &&
2596 "Non-byte-multiple bit width");
2597 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth067edd32012-12-15 09:26:06 +00002598 TD.getTypeAllocSizeInBits(OldAI.getAllocatedType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002599 "Only alloca-wide stores can be split and recomposed");
2600 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
2601 V = extractInteger(TD, IRB, V, NarrowTy, BeginOffset,
2602 getName(".extract"));
Chandler Carruth891fec02012-10-13 02:41:05 +00002603 }
2604
Chandler Carruth18db7952012-11-20 01:12:50 +00002605 if (VecTy)
2606 return rewriteVectorizedStoreInst(IRB, V, SI, OldOp);
2607 if (IntTy && V->getType()->isIntegerTy())
2608 return rewriteIntegerStore(IRB, V, SI);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002609
Chandler Carruth18db7952012-11-20 01:12:50 +00002610 StoreInst *NewSI;
2611 if (BeginOffset == NewAllocaBeginOffset &&
2612 canConvertValue(TD, V->getType(), NewAllocaTy)) {
2613 V = convertValue(TD, IRB, V, NewAllocaTy);
2614 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2615 SI.isVolatile());
2616 } else {
2617 Value *NewPtr = getAdjustedAllocaPtr(IRB, V->getType()->getPointerTo());
2618 NewSI = IRB.CreateAlignedStore(V, NewPtr,
2619 getPartitionTypeAlign(V->getType()),
2620 SI.isVolatile());
2621 }
2622 (void)NewSI;
2623 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002624 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002625
2626 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2627 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002628 }
2629
Chandler Carruth514f34f2012-12-17 04:07:30 +00002630 /// \brief Compute an integer value from splatting an i8 across the given
2631 /// number of bytes.
2632 ///
2633 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2634 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002635 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002636 ///
2637 /// \param V The i8 value to splat.
2638 /// \param Size The number of bytes in the output (assuming i8 is one byte)
2639 Value *getIntegerSplat(IRBuilder<> &IRB, Value *V, unsigned Size) {
2640 assert(Size > 0 && "Expected a positive number of bytes.");
2641 IntegerType *VTy = cast<IntegerType>(V->getType());
2642 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2643 if (Size == 1)
2644 return V;
2645
2646 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2647 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, getName(".zext")),
2648 ConstantExpr::getUDiv(
2649 Constant::getAllOnesValue(SplatIntTy),
2650 ConstantExpr::getZExt(
2651 Constant::getAllOnesValue(V->getType()),
2652 SplatIntTy)),
2653 getName(".isplat"));
2654 return V;
2655 }
2656
Chandler Carruthccca5042012-12-17 04:07:37 +00002657 /// \brief Compute a vector splat for a given element value.
2658 Value *getVectorSplat(IRBuilder<> &IRB, Value *V, unsigned NumElements) {
Benjamin Kramer614b5e82013-01-01 19:55:16 +00002659 V = IRB.CreateVectorSplat(NumElements, V, NamePrefix);
Chandler Carruthccca5042012-12-17 04:07:37 +00002660 DEBUG(dbgs() << " splat: " << *V << "\n");
2661 return V;
2662 }
2663
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002664 bool visitMemSetInst(MemSetInst &II) {
2665 DEBUG(dbgs() << " original: " << II << "\n");
2666 IRBuilder<> IRB(&II);
2667 assert(II.getRawDest() == OldPtr);
2668
2669 // If the memset has a variable size, it cannot be split, just adjust the
2670 // pointer to the new alloca.
2671 if (!isa<Constant>(II.getLength())) {
2672 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002673 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002674 II.setAlignment(ConstantInt::get(CstTy, getPartitionAlign()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002675
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002676 deleteIfTriviallyDead(OldPtr);
2677 return false;
2678 }
2679
2680 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002681 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002682
2683 Type *AllocaTy = NewAI.getAllocatedType();
2684 Type *ScalarTy = AllocaTy->getScalarType();
2685
2686 // If this doesn't map cleanly onto the alloca type, and that type isn't
2687 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002688 if (!VecTy && !IntTy &&
2689 (BeginOffset != NewAllocaBeginOffset ||
2690 EndOffset != NewAllocaEndOffset ||
2691 !AllocaTy->isSingleValueType() ||
Chandler Carruthccca5042012-12-17 04:07:37 +00002692 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)) ||
2693 TD.getTypeSizeInBits(ScalarTy)%8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002694 Type *SizeTy = II.getLength()->getType();
2695 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002696 CallInst *New
2697 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2698 II.getRawDest()->getType()),
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002699 II.getValue(), Size, getPartitionAlign(),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002700 II.isVolatile());
2701 (void)New;
2702 DEBUG(dbgs() << " to: " << *New << "\n");
2703 return false;
2704 }
2705
2706 // If we can represent this as a simple value, we have to build the actual
2707 // value to store, which requires expanding the byte present in memset to
2708 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002709 // splatting the byte to a sufficiently wide integer, splatting it across
2710 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002711 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002712
Chandler Carruthccca5042012-12-17 04:07:37 +00002713 if (VecTy) {
2714 // If this is a memset of a vectorized alloca, insert it.
2715 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002716
Chandler Carruthccca5042012-12-17 04:07:37 +00002717 unsigned BeginIndex = getIndex(BeginOffset);
2718 unsigned EndIndex = getIndex(EndOffset);
2719 assert(EndIndex > BeginIndex && "Empty vector!");
2720 unsigned NumElements = EndIndex - BeginIndex;
2721 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2722
2723 Value *Splat = getIntegerSplat(IRB, II.getValue(),
2724 TD.getTypeSizeInBits(ElementTy)/8);
Chandler Carruthcacda252012-12-17 14:03:01 +00002725 Splat = convertValue(TD, IRB, Splat, ElementTy);
2726 if (NumElements > 1)
Chandler Carruthccca5042012-12-17 04:07:37 +00002727 Splat = getVectorSplat(IRB, Splat, NumElements);
2728
Chandler Carruthce4562b2012-12-17 13:41:21 +00002729 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2730 getName(".oldload"));
2731 V = insertVector(IRB, Old, Splat, BeginIndex, getName(".vec"));
Chandler Carruthccca5042012-12-17 04:07:37 +00002732 } else if (IntTy) {
2733 // If this is a memset on an alloca where we can widen stores, insert the
2734 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002735 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002736
Benjamin Kramerc003a452013-01-01 16:13:35 +00002737 uint64_t Size = EndOffset - BeginOffset;
Chandler Carruthccca5042012-12-17 04:07:37 +00002738 V = getIntegerSplat(IRB, II.getValue(), Size);
2739
2740 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2741 EndOffset != NewAllocaBeginOffset)) {
2742 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2743 getName(".oldload"));
2744 Old = convertValue(TD, IRB, Old, IntTy);
2745 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2746 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2747 V = insertInteger(TD, IRB, Old, V, Offset, getName(".insert"));
2748 } else {
2749 assert(V->getType() == IntTy &&
2750 "Wrong type for an alloca wide integer!");
2751 }
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002752 V = convertValue(TD, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002753 } else {
2754 // Established these invariants above.
2755 assert(BeginOffset == NewAllocaBeginOffset);
2756 assert(EndOffset == NewAllocaEndOffset);
2757
2758 V = getIntegerSplat(IRB, II.getValue(),
2759 TD.getTypeSizeInBits(ScalarTy)/8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002760 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2761 V = getVectorSplat(IRB, V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002762
2763 V = convertValue(TD, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002764 }
2765
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002766 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002767 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002768 (void)New;
2769 DEBUG(dbgs() << " to: " << *New << "\n");
2770 return !II.isVolatile();
2771 }
2772
2773 bool visitMemTransferInst(MemTransferInst &II) {
2774 // Rewriting of memory transfer instructions can be a bit tricky. We break
2775 // them into two categories: split intrinsics and unsplit intrinsics.
2776
2777 DEBUG(dbgs() << " original: " << II << "\n");
2778 IRBuilder<> IRB(&II);
2779
2780 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2781 bool IsDest = II.getRawDest() == OldPtr;
2782
2783 const AllocaPartitioning::MemTransferOffsets &MTO
2784 = P.getMemTransferOffsets(II);
2785
Chandler Carruth176ca712012-10-01 12:16:54 +00002786 // Compute the relative offset within the transfer.
Chandler Carruth5da3f052012-11-01 09:14:31 +00002787 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chandler Carruth176ca712012-10-01 12:16:54 +00002788 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2789 : MTO.SourceBegin));
2790
2791 unsigned Align = II.getAlignment();
2792 if (Align > 1)
2793 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002794 MinAlign(II.getAlignment(), getPartitionAlign()));
Chandler Carruth176ca712012-10-01 12:16:54 +00002795
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002796 // For unsplit intrinsics, we simply modify the source and destination
2797 // pointers in place. This isn't just an optimization, it is a matter of
2798 // correctness. With unsplit intrinsics we may be dealing with transfers
2799 // within a single alloca before SROA ran, or with transfers that have
2800 // a variable length. We may also be dealing with memmove instead of
2801 // memcpy, and so simply updating the pointers is the necessary for us to
2802 // update both source and dest of a single call.
2803 if (!MTO.IsSplittable) {
2804 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2805 if (IsDest)
2806 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2807 else
2808 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2809
Chandler Carruth208124f2012-09-26 10:59:22 +00002810 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth176ca712012-10-01 12:16:54 +00002811 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruth208124f2012-09-26 10:59:22 +00002812
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002813 DEBUG(dbgs() << " to: " << II << "\n");
2814 deleteIfTriviallyDead(OldOp);
2815 return false;
2816 }
2817 // For split transfer intrinsics we have an incredibly useful assurance:
2818 // the source and destination do not reside within the same alloca, and at
2819 // least one of them does not escape. This means that we can replace
2820 // memmove with memcpy, and we don't need to worry about all manner of
2821 // downsides to splitting and transforming the operations.
2822
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002823 // If this doesn't map cleanly onto the alloca type, and that type isn't
2824 // a single value type, just emit a memcpy.
2825 bool EmitMemCpy
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002826 = !VecTy && !IntTy && (BeginOffset != NewAllocaBeginOffset ||
2827 EndOffset != NewAllocaEndOffset ||
2828 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002829
2830 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2831 // size hasn't been shrunk based on analysis of the viable range, this is
2832 // a no-op.
2833 if (EmitMemCpy && &OldAI == &NewAI) {
2834 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2835 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2836 // Ensure the start lines up.
2837 assert(BeginOffset == OrigBegin);
Benjamin Kramer4622cd72012-09-14 13:08:09 +00002838 (void)OrigBegin;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002839
2840 // Rewrite the size as needed.
2841 if (EndOffset != OrigEnd)
2842 II.setLength(ConstantInt::get(II.getLength()->getType(),
2843 EndOffset - BeginOffset));
2844 return false;
2845 }
2846 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002847 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002848
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002849 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2850 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002851 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002852 if (AllocaInst *AI
2853 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002854 Pass.Worklist.insert(AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002855
2856 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002857 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2858 : II.getRawDest()->getType();
2859
2860 // Compute the other pointer, folding as much as possible to produce
2861 // a single, simple GEP in most cases.
2862 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2863 getName("." + OtherPtr->getName()));
2864
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002865 Value *OurPtr
2866 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2867 : II.getRawSource()->getType());
2868 Type *SizeTy = II.getLength()->getType();
2869 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2870
2871 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2872 IsDest ? OtherPtr : OurPtr,
Chandler Carruth871ba722012-09-26 10:27:46 +00002873 Size, Align, II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002874 (void)New;
2875 DEBUG(dbgs() << " to: " << *New << "\n");
2876 return false;
2877 }
2878
Chandler Carruth08e5f492012-10-03 08:26:28 +00002879 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2880 // is equivalent to 1, but that isn't true if we end up rewriting this as
2881 // a load or store.
2882 if (!Align)
2883 Align = 1;
2884
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002885 bool IsWholeAlloca = BeginOffset == NewAllocaBeginOffset &&
2886 EndOffset == NewAllocaEndOffset;
2887 uint64_t Size = EndOffset - BeginOffset;
2888 unsigned BeginIndex = VecTy ? getIndex(BeginOffset) : 0;
2889 unsigned EndIndex = VecTy ? getIndex(EndOffset) : 0;
2890 unsigned NumElements = EndIndex - BeginIndex;
2891 IntegerType *SubIntTy
2892 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2893
2894 Type *OtherPtrTy = NewAI.getType();
2895 if (VecTy && !IsWholeAlloca) {
2896 if (NumElements == 1)
2897 OtherPtrTy = VecTy->getElementType();
2898 else
2899 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2900
2901 OtherPtrTy = OtherPtrTy->getPointerTo();
2902 } else if (IntTy && !IsWholeAlloca) {
2903 OtherPtrTy = SubIntTy->getPointerTo();
2904 }
2905
2906 Value *SrcPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2907 getName("." + OtherPtr->getName()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002908 Value *DstPtr = &NewAI;
2909 if (!IsDest)
2910 std::swap(SrcPtr, DstPtr);
2911
2912 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002913 if (VecTy && !IsWholeAlloca && !IsDest) {
2914 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2915 getName(".load"));
2916 Src = extractVector(IRB, Src, BeginIndex, EndIndex, getName(".vec"));
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002917 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002918 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2919 getName(".load"));
2920 Src = convertValue(TD, IRB, Src, IntTy);
2921 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2922 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2923 Src = extractInteger(TD, IRB, Src, SubIntTy, Offset, getName(".extract"));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002924 } else {
Chandler Carruth871ba722012-09-26 10:27:46 +00002925 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2926 getName(".copyload"));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002927 }
2928
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002929 if (VecTy && !IsWholeAlloca && IsDest) {
2930 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2931 getName(".oldload"));
2932 Src = insertVector(IRB, Old, Src, BeginIndex, getName(".vec"));
2933 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002934 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2935 getName(".oldload"));
2936 Old = convertValue(TD, IRB, Old, IntTy);
2937 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2938 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2939 Src = insertInteger(TD, IRB, Old, Src, Offset, getName(".insert"));
2940 Src = convertValue(TD, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002941 }
2942
Chandler Carruth871ba722012-09-26 10:27:46 +00002943 StoreInst *Store = cast<StoreInst>(
2944 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2945 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002946 DEBUG(dbgs() << " to: " << *Store << "\n");
2947 return !II.isVolatile();
2948 }
2949
2950 bool visitIntrinsicInst(IntrinsicInst &II) {
2951 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2952 II.getIntrinsicID() == Intrinsic::lifetime_end);
2953 DEBUG(dbgs() << " original: " << II << "\n");
2954 IRBuilder<> IRB(&II);
2955 assert(II.getArgOperand(1) == OldPtr);
2956
2957 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002958 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002959
2960 ConstantInt *Size
2961 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2962 EndOffset - BeginOffset);
2963 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2964 Value *New;
2965 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2966 New = IRB.CreateLifetimeStart(Ptr, Size);
2967 else
2968 New = IRB.CreateLifetimeEnd(Ptr, Size);
2969
Edwin Vane82f80d42013-01-29 17:42:24 +00002970 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002971 DEBUG(dbgs() << " to: " << *New << "\n");
2972 return true;
2973 }
2974
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002975 bool visitPHINode(PHINode &PN) {
2976 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruth82a57542012-10-01 10:54:05 +00002977
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002978 // We would like to compute a new pointer in only one place, but have it be
2979 // as local as possible to the PHI. To do that, we re-use the location of
2980 // the old pointer, which necessarily must be in the right position to
2981 // dominate the PHI.
2982 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2983
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002984 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002985 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002986 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002987
Chandler Carruth82a57542012-10-01 10:54:05 +00002988 DEBUG(dbgs() << " to: " << PN << "\n");
2989 deleteIfTriviallyDead(OldPtr);
2990 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002991 }
2992
2993 bool visitSelectInst(SelectInst &SI) {
2994 DEBUG(dbgs() << " original: " << SI << "\n");
2995 IRBuilder<> IRB(&SI);
2996
2997 // Find the operand we need to rewrite here.
2998 bool IsTrueVal = SI.getTrueValue() == OldPtr;
2999 if (IsTrueVal)
3000 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
3001 else
3002 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
Chandler Carruth82a57542012-10-01 10:54:05 +00003003
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003004 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00003005 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
3006 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003007 deleteIfTriviallyDead(OldPtr);
Chandler Carruth82a57542012-10-01 10:54:05 +00003008 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003009 }
3010
3011};
3012}
3013
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003014namespace {
3015/// \brief Visitor to rewrite aggregate loads and stores as scalar.
3016///
3017/// This pass aggressively rewrites all aggregate loads and stores on
3018/// a particular pointer (or any pointer derived from it which we can identify)
3019/// with scalar loads and stores.
3020class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3021 // Befriend the base class so it can delegate to private visit methods.
3022 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3023
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003024 const DataLayout &TD;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003025
3026 /// Queue of pointer uses to analyze and potentially rewrite.
3027 SmallVector<Use *, 8> Queue;
3028
3029 /// Set to prevent us from cycling with phi nodes and loops.
3030 SmallPtrSet<User *, 8> Visited;
3031
3032 /// The current pointer use being rewritten. This is used to dig up the used
3033 /// value (as opposed to the user).
3034 Use *U;
3035
3036public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003037 AggLoadStoreRewriter(const DataLayout &TD) : TD(TD) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003038
3039 /// Rewrite loads and stores through a pointer and all pointers derived from
3040 /// it.
3041 bool rewrite(Instruction &I) {
3042 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3043 enqueueUsers(I);
3044 bool Changed = false;
3045 while (!Queue.empty()) {
3046 U = Queue.pop_back_val();
3047 Changed |= visit(cast<Instruction>(U->getUser()));
3048 }
3049 return Changed;
3050 }
3051
3052private:
3053 /// Enqueue all the users of the given instruction for further processing.
3054 /// This uses a set to de-duplicate users.
3055 void enqueueUsers(Instruction &I) {
3056 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3057 ++UI)
3058 if (Visited.insert(*UI))
3059 Queue.push_back(&UI.getUse());
3060 }
3061
3062 // Conservative default is to not rewrite anything.
3063 bool visitInstruction(Instruction &I) { return false; }
3064
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003065 /// \brief Generic recursive split emission class.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003066 template <typename Derived>
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003067 class OpSplitter {
3068 protected:
3069 /// The builder used to form new instructions.
3070 IRBuilder<> IRB;
3071 /// The indices which to be used with insert- or extractvalue to select the
3072 /// appropriate value within the aggregate.
3073 SmallVector<unsigned, 4> Indices;
3074 /// The indices to a GEP instruction which will move Ptr to the correct slot
3075 /// within the aggregate.
3076 SmallVector<Value *, 4> GEPIndices;
3077 /// The base pointer of the original op, used as a base for GEPing the
3078 /// split operations.
3079 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003080
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003081 /// Initialize the splitter with an insertion point, Ptr and start with a
3082 /// single zero GEP index.
3083 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003084 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003085
3086 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003087 /// \brief Generic recursive split emission routine.
3088 ///
3089 /// This method recursively splits an aggregate op (load or store) into
3090 /// scalar or vector ops. It splits recursively until it hits a single value
3091 /// and emits that single value operation via the template argument.
3092 ///
3093 /// The logic of this routine relies on GEPs and insertvalue and
3094 /// extractvalue all operating with the same fundamental index list, merely
3095 /// formatted differently (GEPs need actual values).
3096 ///
3097 /// \param Ty The type being split recursively into smaller ops.
3098 /// \param Agg The aggregate value being built up or stored, depending on
3099 /// whether this is splitting a load or a store respectively.
3100 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3101 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003102 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003103
3104 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3105 unsigned OldSize = Indices.size();
3106 (void)OldSize;
3107 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3108 ++Idx) {
3109 assert(Indices.size() == OldSize && "Did not return to the old size");
3110 Indices.push_back(Idx);
3111 GEPIndices.push_back(IRB.getInt32(Idx));
3112 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3113 GEPIndices.pop_back();
3114 Indices.pop_back();
3115 }
3116 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003117 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003118
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003119 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3120 unsigned OldSize = Indices.size();
3121 (void)OldSize;
3122 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3123 ++Idx) {
3124 assert(Indices.size() == OldSize && "Did not return to the old size");
3125 Indices.push_back(Idx);
3126 GEPIndices.push_back(IRB.getInt32(Idx));
3127 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3128 GEPIndices.pop_back();
3129 Indices.pop_back();
3130 }
3131 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003132 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003133
3134 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003135 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003136 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003137
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003138 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003139 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00003140 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003141
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003142 /// Emit a leaf load of a single value. This is called at the leaves of the
3143 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003144 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003145 assert(Ty->isSingleValueType());
3146 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00003147 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
3148 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003149 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3150 DEBUG(dbgs() << " to: " << *Load << "\n");
3151 }
3152 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003153
3154 bool visitLoadInst(LoadInst &LI) {
3155 assert(LI.getPointerOperand() == *U);
3156 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3157 return false;
3158
3159 // We have an aggregate being loaded, split it apart.
3160 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003161 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003162 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003163 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003164 LI.replaceAllUsesWith(V);
3165 LI.eraseFromParent();
3166 return true;
3167 }
3168
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003169 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003170 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00003171 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003172
3173 /// Emit a leaf store of a single value. This is called at the leaves of the
3174 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003175 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003176 assert(Ty->isSingleValueType());
3177 // Extract the single value and store it using the indices.
3178 Value *Store = IRB.CreateStore(
3179 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3180 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
3181 (void)Store;
3182 DEBUG(dbgs() << " to: " << *Store << "\n");
3183 }
3184 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003185
3186 bool visitStoreInst(StoreInst &SI) {
3187 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3188 return false;
3189 Value *V = SI.getValueOperand();
3190 if (V->getType()->isSingleValueType())
3191 return false;
3192
3193 // We have an aggregate being stored, split it apart.
3194 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003195 StoreOpSplitter Splitter(&SI, *U);
3196 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003197 SI.eraseFromParent();
3198 return true;
3199 }
3200
3201 bool visitBitCastInst(BitCastInst &BC) {
3202 enqueueUsers(BC);
3203 return false;
3204 }
3205
3206 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3207 enqueueUsers(GEPI);
3208 return false;
3209 }
3210
3211 bool visitPHINode(PHINode &PN) {
3212 enqueueUsers(PN);
3213 return false;
3214 }
3215
3216 bool visitSelectInst(SelectInst &SI) {
3217 enqueueUsers(SI);
3218 return false;
3219 }
3220};
3221}
3222
Chandler Carruthba931992012-10-13 10:49:33 +00003223/// \brief Strip aggregate type wrapping.
3224///
3225/// This removes no-op aggregate types wrapping an underlying type. It will
3226/// strip as many layers of types as it can without changing either the type
3227/// size or the allocated size.
3228static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3229 if (Ty->isSingleValueType())
3230 return Ty;
3231
3232 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3233 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3234
3235 Type *InnerTy;
3236 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3237 InnerTy = ArrTy->getElementType();
3238 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3239 const StructLayout *SL = DL.getStructLayout(STy);
3240 unsigned Index = SL->getElementContainingOffset(0);
3241 InnerTy = STy->getElementType(Index);
3242 } else {
3243 return Ty;
3244 }
3245
3246 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3247 TypeSize > DL.getTypeSizeInBits(InnerTy))
3248 return Ty;
3249
3250 return stripAggregateTypeWrapping(DL, InnerTy);
3251}
3252
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003253/// \brief Try to find a partition of the aggregate type passed in for a given
3254/// offset and size.
3255///
3256/// This recurses through the aggregate type and tries to compute a subtype
3257/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003258/// of an array, it will even compute a new array type for that sub-section,
3259/// and the same for structs.
3260///
3261/// Note that this routine is very strict and tries to find a partition of the
3262/// type which produces the *exact* right offset and size. It is not forgiving
3263/// when the size or offset cause either end of type-based partition to be off.
3264/// Also, this is a best-effort routine. It is reasonable to give up and not
3265/// return a type if necessary.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003266static Type *getTypePartition(const DataLayout &TD, Type *Ty,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003267 uint64_t Offset, uint64_t Size) {
3268 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
Chandler Carruthba931992012-10-13 10:49:33 +00003269 return stripAggregateTypeWrapping(TD, Ty);
Chandler Carruth58d05562012-10-25 04:37:07 +00003270 if (Offset > TD.getTypeAllocSize(Ty) ||
3271 (TD.getTypeAllocSize(Ty) - Offset) < Size)
3272 return 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003273
3274 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3275 // We can't partition pointers...
3276 if (SeqTy->isPointerTy())
3277 return 0;
3278
3279 Type *ElementTy = SeqTy->getElementType();
3280 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3281 uint64_t NumSkippedElements = Offset / ElementSize;
3282 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
3283 if (NumSkippedElements >= ArrTy->getNumElements())
3284 return 0;
3285 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
3286 if (NumSkippedElements >= VecTy->getNumElements())
3287 return 0;
3288 Offset -= NumSkippedElements * ElementSize;
3289
3290 // First check if we need to recurse.
3291 if (Offset > 0 || Size < ElementSize) {
3292 // Bail if the partition ends in a different array element.
3293 if ((Offset + Size) > ElementSize)
3294 return 0;
3295 // Recurse through the element type trying to peel off offset bytes.
3296 return getTypePartition(TD, ElementTy, Offset, Size);
3297 }
3298 assert(Offset == 0);
3299
3300 if (Size == ElementSize)
Chandler Carruthba931992012-10-13 10:49:33 +00003301 return stripAggregateTypeWrapping(TD, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003302 assert(Size > ElementSize);
3303 uint64_t NumElements = Size / ElementSize;
3304 if (NumElements * ElementSize != Size)
3305 return 0;
3306 return ArrayType::get(ElementTy, NumElements);
3307 }
3308
3309 StructType *STy = dyn_cast<StructType>(Ty);
3310 if (!STy)
3311 return 0;
3312
3313 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003314 if (Offset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003315 return 0;
3316 uint64_t EndOffset = Offset + Size;
3317 if (EndOffset > SL->getSizeInBytes())
3318 return 0;
3319
3320 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003321 Offset -= SL->getElementOffset(Index);
3322
3323 Type *ElementTy = STy->getElementType(Index);
3324 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3325 if (Offset >= ElementSize)
3326 return 0; // The offset points into alignment padding.
3327
3328 // See if any partition must be contained by the element.
3329 if (Offset > 0 || Size < ElementSize) {
3330 if ((Offset + Size) > ElementSize)
3331 return 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003332 return getTypePartition(TD, ElementTy, Offset, Size);
3333 }
3334 assert(Offset == 0);
3335
3336 if (Size == ElementSize)
Chandler Carruthba931992012-10-13 10:49:33 +00003337 return stripAggregateTypeWrapping(TD, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003338
3339 StructType::element_iterator EI = STy->element_begin() + Index,
3340 EE = STy->element_end();
3341 if (EndOffset < SL->getSizeInBytes()) {
3342 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3343 if (Index == EndIndex)
3344 return 0; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003345
3346 // Don't try to form "natural" types if the elements don't line up with the
3347 // expected size.
3348 // FIXME: We could potentially recurse down through the last element in the
3349 // sub-struct to find a natural end point.
3350 if (SL->getElementOffset(EndIndex) != EndOffset)
3351 return 0;
3352
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003353 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003354 EE = STy->element_begin() + EndIndex;
3355 }
3356
3357 // Try to build up a sub-structure.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003358 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003359 STy->isPacked());
3360 const StructLayout *SubSL = TD.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003361 if (Size != SubSL->getSizeInBytes())
3362 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003363
Chandler Carruth054a40a2012-09-14 11:08:31 +00003364 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003365}
3366
3367/// \brief Rewrite an alloca partition's users.
3368///
3369/// This routine drives both of the rewriting goals of the SROA pass. It tries
3370/// to rewrite uses of an alloca partition to be conducive for SSA value
3371/// promotion. If the partition needs a new, more refined alloca, this will
3372/// build that new alloca, preserving as much type information as possible, and
3373/// rewrite the uses of the old alloca to point at the new one and have the
3374/// appropriate new offsets. It also evaluates how successful the rewrite was
3375/// at enabling promotion and if it was successful queues the alloca to be
3376/// promoted.
3377bool SROA::rewriteAllocaPartition(AllocaInst &AI,
3378 AllocaPartitioning &P,
3379 AllocaPartitioning::iterator PI) {
3380 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
Chandler Carruth6c3890b2012-10-02 18:57:13 +00003381 bool IsLive = false;
3382 for (AllocaPartitioning::use_iterator UI = P.use_begin(PI),
3383 UE = P.use_end(PI);
3384 UI != UE && !IsLive; ++UI)
3385 if (UI->U)
3386 IsLive = true;
3387 if (!IsLive)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003388 return false; // No live uses left of this partition.
3389
Chandler Carruth82a57542012-10-01 10:54:05 +00003390 DEBUG(dbgs() << "Speculating PHIs and selects in partition "
3391 << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
3392
3393 PHIOrSelectSpeculator Speculator(*TD, P, *this);
3394 DEBUG(dbgs() << " speculating ");
3395 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carruth3903e052012-10-02 17:49:47 +00003396 Speculator.visitUsers(PI);
Chandler Carruth82a57542012-10-01 10:54:05 +00003397
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003398 // Try to compute a friendly type for this partition of the alloca. This
3399 // won't always succeed, in which case we fall back to a legal integer type
3400 // or an i8 array of an appropriate size.
3401 Type *AllocaTy = 0;
3402 if (Type *PartitionTy = P.getCommonType(PI))
3403 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
3404 AllocaTy = PartitionTy;
3405 if (!AllocaTy)
3406 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3407 PI->BeginOffset, AllocaSize))
3408 AllocaTy = PartitionTy;
3409 if ((!AllocaTy ||
3410 (AllocaTy->isArrayTy() &&
3411 AllocaTy->getArrayElementType()->isIntegerTy())) &&
3412 TD->isLegalInteger(AllocaSize * 8))
3413 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
3414 if (!AllocaTy)
3415 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
Chandler Carruthb0de6dd2012-09-14 10:26:34 +00003416 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003417
3418 // Check for the case where we're going to rewrite to a new alloca of the
3419 // exact same type as the original, and with the same access offsets. In that
3420 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003421 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003422 AllocaInst *NewAI;
3423 if (AllocaTy == AI.getAllocatedType()) {
3424 assert(PI->BeginOffset == 0 &&
3425 "Non-zero begin offset but same alloca type");
3426 assert(PI == P.begin() && "Begin offset is zero on later partition");
3427 NewAI = &AI;
3428 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003429 unsigned Alignment = AI.getAlignment();
3430 if (!Alignment) {
3431 // The minimum alignment which users can rely on when the explicit
3432 // alignment is omitted or zero is that required by the ABI for this
3433 // type.
3434 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3435 }
3436 Alignment = MinAlign(Alignment, PI->BeginOffset);
3437 // If we will get at least this much alignment from the type alone, leave
3438 // the alloca's alignment unconstrained.
3439 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3440 Alignment = 0;
3441 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003442 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3443 &AI);
3444 ++NumNewAllocas;
3445 }
3446
3447 DEBUG(dbgs() << "Rewriting alloca partition "
3448 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3449 << *NewAI << "\n");
3450
Chandler Carruthac8317f2012-10-04 12:33:50 +00003451 // Track the high watermark of the post-promotion worklist. We will reset it
3452 // to this point if the alloca is not in fact scheduled for promotion.
3453 unsigned PPWOldSize = PostPromotionWorklist.size();
3454
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003455 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3456 PI->BeginOffset, PI->EndOffset);
3457 DEBUG(dbgs() << " rewriting ");
3458 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carruthac8317f2012-10-04 12:33:50 +00003459 bool Promotable = Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI));
3460 if (Promotable) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003461 DEBUG(dbgs() << " and queuing for promotion\n");
3462 PromotableAllocas.push_back(NewAI);
3463 } else if (NewAI != &AI) {
3464 // If we can't promote the alloca, iterate on it to check for new
3465 // refinements exposed by splitting the current alloca. Don't iterate on an
3466 // alloca which didn't actually change and didn't get promoted.
3467 Worklist.insert(NewAI);
3468 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003469
3470 // Drop any post-promotion work items if promotion didn't happen.
3471 if (!Promotable)
3472 while (PostPromotionWorklist.size() > PPWOldSize)
3473 PostPromotionWorklist.pop_back();
3474
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003475 return true;
3476}
3477
3478/// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3479bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3480 bool Changed = false;
3481 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3482 ++PI)
3483 Changed |= rewriteAllocaPartition(AI, P, PI);
3484
3485 return Changed;
3486}
3487
3488/// \brief Analyze an alloca for SROA.
3489///
3490/// This analyzes the alloca to ensure we can reason about it, builds
3491/// a partitioning of the alloca, and then hands it off to be split and
3492/// rewritten as needed.
3493bool SROA::runOnAlloca(AllocaInst &AI) {
3494 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3495 ++NumAllocasAnalyzed;
3496
3497 // Special case dead allocas, as they're trivial.
3498 if (AI.use_empty()) {
3499 AI.eraseFromParent();
3500 return true;
3501 }
3502
3503 // Skip alloca forms that this analysis can't handle.
3504 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3505 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3506 return false;
3507
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003508 bool Changed = false;
3509
3510 // First, split any FCA loads and stores touching this alloca to promote
3511 // better splitting and promotion opportunities.
3512 AggLoadStoreRewriter AggRewriter(*TD);
3513 Changed |= AggRewriter.rewrite(AI);
3514
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003515 // Build the partition set using a recursive instruction-visiting builder.
3516 AllocaPartitioning P(*TD, AI);
3517 DEBUG(P.print(dbgs()));
3518 if (P.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003519 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003520
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003521 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003522 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3523 DE = P.dead_user_end();
3524 DI != DE; ++DI) {
3525 Changed = true;
3526 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
Chandler Carruth18db7952012-11-20 01:12:50 +00003527 DeadInsts.insert(*DI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003528 }
3529 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3530 DE = P.dead_op_end();
3531 DO != DE; ++DO) {
3532 Value *OldV = **DO;
3533 // Clobber the use with an undef value.
3534 **DO = UndefValue::get(OldV->getType());
3535 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3536 if (isInstructionTriviallyDead(OldI)) {
3537 Changed = true;
Chandler Carruth18db7952012-11-20 01:12:50 +00003538 DeadInsts.insert(OldI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003539 }
3540 }
3541
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003542 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3543 if (P.begin() == P.end())
3544 return Changed;
3545
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003546 return splitAlloca(AI, P) || Changed;
3547}
3548
Chandler Carruth19450da2012-09-14 10:26:38 +00003549/// \brief Delete the dead instructions accumulated in this run.
3550///
3551/// Recursively deletes the dead instructions we've accumulated. This is done
3552/// at the very end to maximize locality of the recursive delete and to
3553/// minimize the problems of invalidated instruction pointers as such pointers
3554/// are used heavily in the intermediate stages of the algorithm.
3555///
3556/// We also record the alloca instructions deleted here so that they aren't
3557/// subsequently handed to mem2reg to promote.
3558void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003559 while (!DeadInsts.empty()) {
3560 Instruction *I = DeadInsts.pop_back_val();
3561 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3562
Chandler Carruth58d05562012-10-25 04:37:07 +00003563 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3564
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003565 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3566 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3567 // Zero out the operand and see if it becomes trivially dead.
3568 *OI = 0;
3569 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003570 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003571 }
3572
3573 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3574 DeletedAllocas.insert(AI);
3575
3576 ++NumDeleted;
3577 I->eraseFromParent();
3578 }
3579}
3580
Chandler Carruth70b44c52012-09-15 11:43:14 +00003581/// \brief Promote the allocas, using the best available technique.
3582///
3583/// This attempts to promote whatever allocas have been identified as viable in
3584/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3585/// If there is a domtree available, we attempt to promote using the full power
3586/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3587/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003588/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003589bool SROA::promoteAllocas(Function &F) {
3590 if (PromotableAllocas.empty())
3591 return false;
3592
3593 NumPromoted += PromotableAllocas.size();
3594
3595 if (DT && !ForceSSAUpdater) {
3596 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3597 PromoteMemToReg(PromotableAllocas, *DT);
3598 PromotableAllocas.clear();
3599 return true;
3600 }
3601
3602 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3603 SSAUpdater SSA;
3604 DIBuilder DIB(*F.getParent());
3605 SmallVector<Instruction*, 64> Insts;
3606
3607 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3608 AllocaInst *AI = PromotableAllocas[Idx];
3609 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3610 UI != UE;) {
3611 Instruction *I = cast<Instruction>(*UI++);
3612 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3613 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3614 // leading to them) here. Eventually it should use them to optimize the
3615 // scalar values produced.
3616 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3617 assert(onlyUsedByLifetimeMarkers(I) &&
3618 "Found a bitcast used outside of a lifetime marker.");
3619 while (!I->use_empty())
3620 cast<Instruction>(*I->use_begin())->eraseFromParent();
3621 I->eraseFromParent();
3622 continue;
3623 }
3624 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3625 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3626 II->getIntrinsicID() == Intrinsic::lifetime_end);
3627 II->eraseFromParent();
3628 continue;
3629 }
3630
3631 Insts.push_back(I);
3632 }
3633 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3634 Insts.clear();
3635 }
3636
3637 PromotableAllocas.clear();
3638 return true;
3639}
3640
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003641namespace {
3642 /// \brief A predicate to test whether an alloca belongs to a set.
3643 class IsAllocaInSet {
3644 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3645 const SetType &Set;
3646
3647 public:
Chandler Carruth3f57b822012-10-03 00:03:00 +00003648 typedef AllocaInst *argument_type;
3649
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003650 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth3f57b822012-10-03 00:03:00 +00003651 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003652 };
3653}
3654
3655bool SROA::runOnFunction(Function &F) {
3656 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3657 C = &F.getContext();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003658 TD = getAnalysisIfAvailable<DataLayout>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003659 if (!TD) {
3660 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3661 return false;
3662 }
Chandler Carruth70b44c52012-09-15 11:43:14 +00003663 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003664
3665 BasicBlock &EntryBB = F.getEntryBlock();
3666 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3667 I != E; ++I)
3668 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3669 Worklist.insert(AI);
3670
3671 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003672 // A set of deleted alloca instruction pointers which should be removed from
3673 // the list of promotable allocas.
3674 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3675
Chandler Carruthac8317f2012-10-04 12:33:50 +00003676 do {
3677 while (!Worklist.empty()) {
3678 Changed |= runOnAlloca(*Worklist.pop_back_val());
3679 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003680
Chandler Carruthac8317f2012-10-04 12:33:50 +00003681 // Remove the deleted allocas from various lists so that we don't try to
3682 // continue processing them.
3683 if (!DeletedAllocas.empty()) {
3684 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3685 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3686 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3687 PromotableAllocas.end(),
3688 IsAllocaInSet(DeletedAllocas)),
3689 PromotableAllocas.end());
3690 DeletedAllocas.clear();
3691 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003692 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003693
Chandler Carruthac8317f2012-10-04 12:33:50 +00003694 Changed |= promoteAllocas(F);
3695
3696 Worklist = PostPromotionWorklist;
3697 PostPromotionWorklist.clear();
3698 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003699
3700 return Changed;
3701}
3702
3703void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003704 if (RequiresDomTree)
3705 AU.addRequired<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003706 AU.setPreservesCFG();
3707}