blob: 04e350c25fcb3f255936859538e9702911e65ae7 [file] [log] [blame]
Chandler Carruth713aa942012-09-14 09:22:59 +00001//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This transformation implements the well known scalar replacement of
11/// aggregates transformation. It tries to identify promotable elements of an
12/// aggregate alloca, and promote them to registers. It will also try to
13/// convert uses of an element (or set of elements) of an alloca into a vector
14/// or bitfield-style integer scalar if appropriate.
15///
16/// It works to do this with minimal slicing of the alloca so that regions
17/// which are merely transferred in and out of external memory remain unchanged
18/// and are not decomposed to scalar code.
19///
20/// Because this also performs alloca promotion, it can be thought of as also
21/// serving the purpose of SSA formation. The algorithm iterates on the
22/// function until all opportunities for promotion have been realized.
23///
24//===----------------------------------------------------------------------===//
25
26#define DEBUG_TYPE "sroa"
27#include "llvm/Transforms/Scalar.h"
28#include "llvm/Constants.h"
29#include "llvm/DIBuilder.h"
30#include "llvm/DebugInfo.h"
31#include "llvm/DerivedTypes.h"
32#include "llvm/Function.h"
33#include "llvm/GlobalVariable.h"
34#include "llvm/IRBuilder.h"
35#include "llvm/Instructions.h"
36#include "llvm/IntrinsicInst.h"
37#include "llvm/LLVMContext.h"
38#include "llvm/Module.h"
39#include "llvm/Operator.h"
40#include "llvm/Pass.h"
41#include "llvm/ADT/SetVector.h"
42#include "llvm/ADT/SmallVector.h"
43#include "llvm/ADT/Statistic.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/TinyPtrVector.h"
46#include "llvm/Analysis/Dominators.h"
47#include "llvm/Analysis/Loads.h"
48#include "llvm/Analysis/ValueTracking.h"
49#include "llvm/Support/CallSite.h"
Chandler Carruth1c8db502012-09-15 11:43:14 +000050#include "llvm/Support/CommandLine.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000051#include "llvm/Support/Debug.h"
52#include "llvm/Support/ErrorHandling.h"
53#include "llvm/Support/GetElementPtrTypeIterator.h"
54#include "llvm/Support/InstVisitor.h"
55#include "llvm/Support/MathExtras.h"
56#include "llvm/Support/ValueHandle.h"
57#include "llvm/Support/raw_ostream.h"
58#include "llvm/Target/TargetData.h"
59#include "llvm/Transforms/Utils/Local.h"
60#include "llvm/Transforms/Utils/PromoteMemToReg.h"
61#include "llvm/Transforms/Utils/SSAUpdater.h"
62using namespace llvm;
63
64STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
65STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
66STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
67STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
68STATISTIC(NumDeleted, "Number of instructions deleted");
69STATISTIC(NumVectorized, "Number of vectorized aggregates");
70
Chandler Carruth1c8db502012-09-15 11:43:14 +000071/// Hidden option to force the pass to not use DomTree and mem2reg, instead
72/// forming SSA values through the SSAUpdater infrastructure.
73static cl::opt<bool>
74ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
75
Chandler Carruth713aa942012-09-14 09:22:59 +000076namespace {
77/// \brief Alloca partitioning representation.
78///
79/// This class represents a partitioning of an alloca into slices, and
80/// information about the nature of uses of each slice of the alloca. The goal
81/// is that this information is sufficient to decide if and how to split the
82/// alloca apart and replace slices with scalars. It is also intended that this
Chandler Carruth7f5bede2012-09-14 10:18:49 +000083/// structure can capture the relevant information needed both to decide about
Chandler Carruth713aa942012-09-14 09:22:59 +000084/// and to enact these transformations.
85class AllocaPartitioning {
86public:
87 /// \brief A common base class for representing a half-open byte range.
88 struct ByteRange {
89 /// \brief The beginning offset of the range.
90 uint64_t BeginOffset;
91
92 /// \brief The ending offset, not included in the range.
93 uint64_t EndOffset;
94
95 ByteRange() : BeginOffset(), EndOffset() {}
96 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
97 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
98
99 /// \brief Support for ordering ranges.
100 ///
101 /// This provides an ordering over ranges such that start offsets are
102 /// always increasing, and within equal start offsets, the end offsets are
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000103 /// decreasing. Thus the spanning range comes first in a cluster with the
Chandler Carruth713aa942012-09-14 09:22:59 +0000104 /// same start position.
105 bool operator<(const ByteRange &RHS) const {
106 if (BeginOffset < RHS.BeginOffset) return true;
107 if (BeginOffset > RHS.BeginOffset) return false;
108 if (EndOffset > RHS.EndOffset) return true;
109 return false;
110 }
111
112 /// \brief Support comparison with a single offset to allow binary searches.
Benjamin Kramer2d1c2a22012-09-17 16:42:36 +0000113 friend bool operator<(const ByteRange &LHS, uint64_t RHSOffset) {
114 return LHS.BeginOffset < RHSOffset;
115 }
116
117 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
118 const ByteRange &RHS) {
119 return LHSOffset < RHS.BeginOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000120 }
121
122 bool operator==(const ByteRange &RHS) const {
123 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
124 }
125 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
126 };
127
128 /// \brief A partition of an alloca.
129 ///
130 /// This structure represents a contiguous partition of the alloca. These are
131 /// formed by examining the uses of the alloca. During formation, they may
132 /// overlap but once an AllocaPartitioning is built, the Partitions within it
133 /// are all disjoint.
134 struct Partition : public ByteRange {
135 /// \brief Whether this partition is splittable into smaller partitions.
136 ///
137 /// We flag partitions as splittable when they are formed entirely due to
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000138 /// accesses by trivially splittable operations such as memset and memcpy.
Chandler Carruth713aa942012-09-14 09:22:59 +0000139 ///
140 /// FIXME: At some point we should consider loads and stores of FCAs to be
141 /// splittable and eagerly split them into scalar values.
142 bool IsSplittable;
143
144 Partition() : ByteRange(), IsSplittable() {}
145 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
146 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
147 };
148
149 /// \brief A particular use of a partition of the alloca.
150 ///
151 /// This structure is used to associate uses of a partition with it. They
152 /// mark the range of bytes which are referenced by a particular instruction,
153 /// and includes a handle to the user itself and the pointer value in use.
154 /// The bounds of these uses are determined by intersecting the bounds of the
155 /// memory use itself with a particular partition. As a consequence there is
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000156 /// intentionally overlap between various uses of the same partition.
Chandler Carruth713aa942012-09-14 09:22:59 +0000157 struct PartitionUse : public ByteRange {
158 /// \brief The user of this range of the alloca.
159 AssertingVH<Instruction> User;
160
161 /// \brief The particular pointer value derived from this alloca in use.
162 AssertingVH<Instruction> Ptr;
163
164 PartitionUse() : ByteRange(), User(), Ptr() {}
165 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset,
166 Instruction *User, Instruction *Ptr)
167 : ByteRange(BeginOffset, EndOffset), User(User), Ptr(Ptr) {}
168 };
169
170 /// \brief Construct a partitioning of a particular alloca.
171 ///
172 /// Construction does most of the work for partitioning the alloca. This
173 /// performs the necessary walks of users and builds a partitioning from it.
174 AllocaPartitioning(const TargetData &TD, AllocaInst &AI);
175
176 /// \brief Test whether a pointer to the allocation escapes our analysis.
177 ///
178 /// If this is true, the partitioning is never fully built and should be
179 /// ignored.
180 bool isEscaped() const { return PointerEscapingInstr; }
181
182 /// \brief Support for iterating over the partitions.
183 /// @{
184 typedef SmallVectorImpl<Partition>::iterator iterator;
185 iterator begin() { return Partitions.begin(); }
186 iterator end() { return Partitions.end(); }
187
188 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
189 const_iterator begin() const { return Partitions.begin(); }
190 const_iterator end() const { return Partitions.end(); }
191 /// @}
192
193 /// \brief Support for iterating over and manipulating a particular
194 /// partition's uses.
195 ///
196 /// The iteration support provided for uses is more limited, but also
197 /// includes some manipulation routines to support rewriting the uses of
198 /// partitions during SROA.
199 /// @{
200 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
201 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
202 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
203 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
204 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
Chandler Carruth72bf29f2012-09-25 02:42:03 +0000205 void use_push_back(unsigned Idx, const PartitionUse &U) {
206 Uses[Idx].push_back(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000207 }
Chandler Carruth72bf29f2012-09-25 02:42:03 +0000208 void use_push_back(const_iterator I, const PartitionUse &U) {
209 Uses[I - begin()].push_back(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000210 }
211 void use_erase(unsigned Idx, use_iterator UI) { Uses[Idx].erase(UI); }
212 void use_erase(const_iterator I, use_iterator UI) {
213 Uses[I - begin()].erase(UI);
214 }
215
216 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
217 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
218 const_use_iterator use_begin(const_iterator I) const {
219 return Uses[I - begin()].begin();
220 }
221 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
222 const_use_iterator use_end(const_iterator I) const {
223 return Uses[I - begin()].end();
224 }
225 /// @}
226
227 /// \brief Allow iterating the dead users for this alloca.
228 ///
229 /// These are instructions which will never actually use the alloca as they
230 /// are outside the allocated range. They are safe to replace with undef and
231 /// delete.
232 /// @{
233 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
234 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
235 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
236 /// @}
237
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000238 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth713aa942012-09-14 09:22:59 +0000239 ///
240 /// These are operands which have cannot actually be used to refer to the
241 /// alloca as they are outside its range and the user doesn't correct for
242 /// that. These mostly consist of PHI node inputs and the like which we just
243 /// need to replace with undef.
244 /// @{
245 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
246 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
247 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
248 /// @}
249
250 /// \brief MemTransferInst auxiliary data.
251 /// This struct provides some auxiliary data about memory transfer
252 /// intrinsics such as memcpy and memmove. These intrinsics can use two
253 /// different ranges within the same alloca, and provide other challenges to
254 /// correctly represent. We stash extra data to help us untangle this
255 /// after the partitioning is complete.
256 struct MemTransferOffsets {
257 uint64_t DestBegin, DestEnd;
258 uint64_t SourceBegin, SourceEnd;
259 bool IsSplittable;
260 };
261 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
262 return MemTransferInstData.lookup(&II);
263 }
264
265 /// \brief Map from a PHI or select operand back to a partition.
266 ///
267 /// When manipulating PHI nodes or selects, they can use more than one
268 /// partition of an alloca. We store a special mapping to allow finding the
269 /// partition referenced by each of these operands, if any.
270 iterator findPartitionForPHIOrSelectOperand(Instruction &I, Value *Op) {
271 SmallDenseMap<std::pair<Instruction *, Value *>,
272 std::pair<unsigned, unsigned> >::const_iterator MapIt
273 = PHIOrSelectOpMap.find(std::make_pair(&I, Op));
274 if (MapIt == PHIOrSelectOpMap.end())
275 return end();
276
277 return begin() + MapIt->second.first;
278 }
279
280 /// \brief Map from a PHI or select operand back to the specific use of
281 /// a partition.
282 ///
283 /// Similar to mapping these operands back to the partitions, this maps
284 /// directly to the use structure of that partition.
285 use_iterator findPartitionUseForPHIOrSelectOperand(Instruction &I,
286 Value *Op) {
287 SmallDenseMap<std::pair<Instruction *, Value *>,
288 std::pair<unsigned, unsigned> >::const_iterator MapIt
289 = PHIOrSelectOpMap.find(std::make_pair(&I, Op));
290 assert(MapIt != PHIOrSelectOpMap.end());
291 return Uses[MapIt->second.first].begin() + MapIt->second.second;
292 }
293
294 /// \brief Compute a common type among the uses of a particular partition.
295 ///
296 /// This routines walks all of the uses of a particular partition and tries
297 /// to find a common type between them. Untyped operations such as memset and
298 /// memcpy are ignored.
299 Type *getCommonType(iterator I) const;
300
Chandler Carruthba13d2e2012-09-14 10:18:51 +0000301#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth713aa942012-09-14 09:22:59 +0000302 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
303 void printUsers(raw_ostream &OS, const_iterator I,
304 StringRef Indent = " ") const;
305 void print(raw_ostream &OS) const;
NAKAMURA Takumiad9f5b82012-09-14 10:06:10 +0000306 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
307 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
Chandler Carruthba13d2e2012-09-14 10:18:51 +0000308#endif
Chandler Carruth713aa942012-09-14 09:22:59 +0000309
310private:
311 template <typename DerivedT, typename RetT = void> class BuilderBase;
312 class PartitionBuilder;
313 friend class AllocaPartitioning::PartitionBuilder;
314 class UseBuilder;
315 friend class AllocaPartitioning::UseBuilder;
316
Benjamin Kramerd0807692012-09-14 13:08:09 +0000317#ifndef NDEBUG
Chandler Carruth713aa942012-09-14 09:22:59 +0000318 /// \brief Handle to alloca instruction to simplify method interfaces.
319 AllocaInst &AI;
Benjamin Kramerd0807692012-09-14 13:08:09 +0000320#endif
Chandler Carruth713aa942012-09-14 09:22:59 +0000321
322 /// \brief The instruction responsible for this alloca having no partitioning.
323 ///
324 /// When an instruction (potentially) escapes the pointer to the alloca, we
325 /// store a pointer to that here and abort trying to partition the alloca.
326 /// This will be null if the alloca is partitioned successfully.
327 Instruction *PointerEscapingInstr;
328
329 /// \brief The partitions of the alloca.
330 ///
331 /// We store a vector of the partitions over the alloca here. This vector is
332 /// sorted by increasing begin offset, and then by decreasing end offset. See
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000333 /// the Partition inner class for more details. Initially (during
334 /// construction) there are overlaps, but we form a disjoint sequence of
335 /// partitions while finishing construction and a fully constructed object is
336 /// expected to always have this as a disjoint space.
Chandler Carruth713aa942012-09-14 09:22:59 +0000337 SmallVector<Partition, 8> Partitions;
338
339 /// \brief The uses of the partitions.
340 ///
341 /// This is essentially a mapping from each partition to a list of uses of
342 /// that partition. The mapping is done with a Uses vector that has the exact
343 /// same number of entries as the partition vector. Each entry is itself
344 /// a vector of the uses.
345 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
346
347 /// \brief Instructions which will become dead if we rewrite the alloca.
348 ///
349 /// Note that these are not separated by partition. This is because we expect
350 /// a partitioned alloca to be completely rewritten or not rewritten at all.
351 /// If rewritten, all these instructions can simply be removed and replaced
352 /// with undef as they come from outside of the allocated space.
353 SmallVector<Instruction *, 8> DeadUsers;
354
355 /// \brief Operands which will become dead if we rewrite the alloca.
356 ///
357 /// These are operands that in their particular use can be replaced with
358 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
359 /// to PHI nodes and the like. They aren't entirely dead (there might be
360 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
361 /// want to swap this particular input for undef to simplify the use lists of
362 /// the alloca.
363 SmallVector<Use *, 8> DeadOperands;
364
365 /// \brief The underlying storage for auxiliary memcpy and memset info.
366 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
367
368 /// \brief A side datastructure used when building up the partitions and uses.
369 ///
370 /// This mapping is only really used during the initial building of the
371 /// partitioning so that we can retain information about PHI and select nodes
372 /// processed.
373 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
374
375 /// \brief Auxiliary information for particular PHI or select operands.
376 SmallDenseMap<std::pair<Instruction *, Value *>,
377 std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
378
379 /// \brief A utility routine called from the constructor.
380 ///
381 /// This does what it says on the tin. It is the key of the alloca partition
382 /// splitting and merging. After it is called we have the desired disjoint
383 /// collection of partitions.
384 void splitAndMergePartitions();
385};
386}
387
388template <typename DerivedT, typename RetT>
389class AllocaPartitioning::BuilderBase
390 : public InstVisitor<DerivedT, RetT> {
391public:
392 BuilderBase(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
393 : TD(TD),
394 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
395 P(P) {
396 enqueueUsers(AI, 0);
397 }
398
399protected:
400 const TargetData &TD;
401 const uint64_t AllocSize;
402 AllocaPartitioning &P;
403
404 struct OffsetUse {
405 Use *U;
Chandler Carruth02e92a02012-09-23 11:43:14 +0000406 int64_t Offset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000407 };
408 SmallVector<OffsetUse, 8> Queue;
409
410 // The active offset and use while visiting.
411 Use *U;
Chandler Carruth02e92a02012-09-23 11:43:14 +0000412 int64_t Offset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000413
Chandler Carruth02e92a02012-09-23 11:43:14 +0000414 void enqueueUsers(Instruction &I, int64_t UserOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000415 SmallPtrSet<User *, 8> UserSet;
416 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
417 UI != UE; ++UI) {
418 if (!UserSet.insert(*UI))
419 continue;
420
421 OffsetUse OU = { &UI.getUse(), UserOffset };
422 Queue.push_back(OU);
423 }
424 }
425
Chandler Carruth02e92a02012-09-23 11:43:14 +0000426 bool computeConstantGEPOffset(GetElementPtrInst &GEPI, int64_t &GEPOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000427 GEPOffset = Offset;
428 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
429 GTI != GTE; ++GTI) {
430 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
431 if (!OpC)
432 return false;
433 if (OpC->isZero())
434 continue;
435
436 // Handle a struct index, which adds its field offset to the pointer.
437 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
438 unsigned ElementIdx = OpC->getZExtValue();
439 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth02e92a02012-09-23 11:43:14 +0000440 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
441 // Check that we can continue to model this GEP in a signed 64-bit offset.
442 if (ElementOffset > INT64_MAX ||
443 (GEPOffset >= 0 &&
444 ((uint64_t)GEPOffset + ElementOffset) > INT64_MAX)) {
445 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
446 << "what can be represented in an int64_t!\n"
447 << " alloca: " << P.AI << "\n");
448 return false;
449 }
450 if (GEPOffset < 0)
451 GEPOffset = ElementOffset + (uint64_t)-GEPOffset;
452 else
453 GEPOffset += ElementOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000454 continue;
455 }
456
Chandler Carruth02e92a02012-09-23 11:43:14 +0000457 APInt Index = OpC->getValue().sextOrTrunc(TD.getPointerSizeInBits());
458 Index *= APInt(Index.getBitWidth(),
459 TD.getTypeAllocSize(GTI.getIndexedType()));
460 Index += APInt(Index.getBitWidth(), (uint64_t)GEPOffset,
461 /*isSigned*/true);
462 // Check if the result can be stored in our int64_t offset.
463 if (!Index.isSignedIntN(sizeof(GEPOffset) * 8)) {
464 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
465 << "what can be represented in an int64_t!\n"
466 << " alloca: " << P.AI << "\n");
467 return false;
468 }
469
470 GEPOffset = Index.getSExtValue();
Chandler Carruth713aa942012-09-14 09:22:59 +0000471 }
472 return true;
473 }
474
475 Value *foldSelectInst(SelectInst &SI) {
476 // If the condition being selected on is a constant or the same value is
477 // being selected between, fold the select. Yes this does (rarely) happen
478 // early on.
479 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
480 return SI.getOperand(1+CI->isZero());
481 if (SI.getOperand(1) == SI.getOperand(2)) {
482 assert(*U == SI.getOperand(1));
483 return SI.getOperand(1);
484 }
485 return 0;
486 }
487};
488
489/// \brief Builder for the alloca partitioning.
490///
491/// This class builds an alloca partitioning by recursively visiting the uses
492/// of an alloca and splitting the partitions for each load and store at each
493/// offset.
494class AllocaPartitioning::PartitionBuilder
495 : public BuilderBase<PartitionBuilder, bool> {
496 friend class InstVisitor<PartitionBuilder, bool>;
497
498 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
499
500public:
501 PartitionBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000502 : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000503
504 /// \brief Run the builder over the allocation.
505 bool operator()() {
506 // Note that we have to re-evaluate size on each trip through the loop as
507 // the queue grows at the tail.
508 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
509 U = Queue[Idx].U;
510 Offset = Queue[Idx].Offset;
511 if (!visit(cast<Instruction>(U->getUser())))
512 return false;
513 }
514 return true;
515 }
516
517private:
518 bool markAsEscaping(Instruction &I) {
519 P.PointerEscapingInstr = &I;
520 return false;
521 }
522
Chandler Carruth02e92a02012-09-23 11:43:14 +0000523 void insertUse(Instruction &I, int64_t Offset, uint64_t Size,
Chandler Carruth63392ea2012-09-16 19:39:50 +0000524 bool IsSplittable = false) {
Chandler Carruthc3034632012-09-25 10:03:40 +0000525 // Completely skip uses which have a zero size or don't overlap the
526 // allocation.
527 if (Size == 0 ||
528 (Offset >= 0 && (uint64_t)Offset >= AllocSize) ||
Chandler Carruth02e92a02012-09-23 11:43:14 +0000529 (Offset < 0 && (uint64_t)-Offset >= Size)) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000530 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
531 << " which starts past the end of the " << AllocSize
532 << " byte alloca:\n"
533 << " alloca: " << P.AI << "\n"
534 << " use: " << I << "\n");
535 return;
536 }
537
Chandler Carruth02e92a02012-09-23 11:43:14 +0000538 // Clamp the start to the beginning of the allocation.
539 if (Offset < 0) {
540 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
541 << " to start at the beginning of the alloca:\n"
542 << " alloca: " << P.AI << "\n"
543 << " use: " << I << "\n");
544 Size -= (uint64_t)-Offset;
545 Offset = 0;
546 }
547
548 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
549
550 // Clamp the end offset to the end of the allocation. Note that this is
551 // formulated to handle even the case where "BeginOffset + Size" overflows.
552 assert(AllocSize >= BeginOffset); // Established above.
553 if (Size > AllocSize - BeginOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000554 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
555 << " to remain within the " << AllocSize << " byte alloca:\n"
556 << " alloca: " << P.AI << "\n"
557 << " use: " << I << "\n");
558 EndOffset = AllocSize;
559 }
560
561 // See if we can just add a user onto the last slot currently occupied.
562 if (!P.Partitions.empty() &&
563 P.Partitions.back().BeginOffset == BeginOffset &&
564 P.Partitions.back().EndOffset == EndOffset) {
565 P.Partitions.back().IsSplittable &= IsSplittable;
566 return;
567 }
568
569 Partition New(BeginOffset, EndOffset, IsSplittable);
570 P.Partitions.push_back(New);
571 }
572
Chandler Carruth02e92a02012-09-23 11:43:14 +0000573 bool handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000574 uint64_t Size = TD.getTypeStoreSize(Ty);
575
576 // If this memory access can be shown to *statically* extend outside the
577 // bounds of of the allocation, it's behavior is undefined, so simply
578 // ignore it. Note that this is more strict than the generic clamping
579 // behavior of insertUse. We also try to handle cases which might run the
580 // risk of overflow.
581 // FIXME: We should instead consider the pointer to have escaped if this
582 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000583 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
584 Size > (AllocSize - (uint64_t)Offset)) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000585 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
586 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
587 << " which extends past the end of the " << AllocSize
588 << " byte alloca:\n"
589 << " alloca: " << P.AI << "\n"
590 << " use: " << I << "\n");
591 return true;
592 }
593
Chandler Carruth63392ea2012-09-16 19:39:50 +0000594 insertUse(I, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000595 return true;
596 }
597
598 bool visitBitCastInst(BitCastInst &BC) {
599 enqueueUsers(BC, Offset);
600 return true;
601 }
602
603 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
Chandler Carruth02e92a02012-09-23 11:43:14 +0000604 int64_t GEPOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000605 if (!computeConstantGEPOffset(GEPI, GEPOffset))
606 return markAsEscaping(GEPI);
607
608 enqueueUsers(GEPI, GEPOffset);
609 return true;
610 }
611
612 bool visitLoadInst(LoadInst &LI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000613 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
614 "All simple FCA loads should have been pre-split");
Chandler Carruth63392ea2012-09-16 19:39:50 +0000615 return handleLoadOrStore(LI.getType(), LI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000616 }
617
618 bool visitStoreInst(StoreInst &SI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000619 Value *ValOp = SI.getValueOperand();
620 if (ValOp == *U)
Chandler Carruth713aa942012-09-14 09:22:59 +0000621 return markAsEscaping(SI);
622
Chandler Carruthc370acd2012-09-18 12:57:43 +0000623 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
624 "All simple FCA stores should have been pre-split");
625 return handleLoadOrStore(ValOp->getType(), SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000626 }
627
628
629 bool visitMemSetInst(MemSetInst &II) {
Chandler Carruthb3dd9a12012-09-14 10:26:34 +0000630 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth713aa942012-09-14 09:22:59 +0000631 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000632 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
633 insertUse(II, Offset, Size, Length);
Chandler Carruth713aa942012-09-14 09:22:59 +0000634 return true;
635 }
636
637 bool visitMemTransferInst(MemTransferInst &II) {
638 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
639 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
640 if (!Size)
641 // Zero-length mem transfer intrinsics can be ignored entirely.
642 return true;
643
644 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
645
646 // Only intrinsics with a constant length can be split.
647 Offsets.IsSplittable = Length;
648
649 if (*U != II.getRawDest()) {
650 assert(*U == II.getRawSource());
651 Offsets.SourceBegin = Offset;
652 Offsets.SourceEnd = Offset + Size;
653 } else {
654 Offsets.DestBegin = Offset;
655 Offsets.DestEnd = Offset + Size;
656 }
657
Chandler Carruth63392ea2012-09-16 19:39:50 +0000658 insertUse(II, Offset, Size, Offsets.IsSplittable);
Chandler Carruth713aa942012-09-14 09:22:59 +0000659 unsigned NewIdx = P.Partitions.size() - 1;
660
661 SmallDenseMap<Instruction *, unsigned>::const_iterator PMI;
662 bool Inserted = false;
663 llvm::tie(PMI, Inserted)
664 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx));
665 if (!Inserted && Offsets.IsSplittable) {
666 // We've found a memory transfer intrinsic which refers to the alloca as
667 // both a source and dest. We refuse to split these to simplify splitting
668 // logic. If possible, SROA will still split them into separate allocas
669 // and then re-analyze.
670 Offsets.IsSplittable = false;
671 P.Partitions[PMI->second].IsSplittable = false;
672 P.Partitions[NewIdx].IsSplittable = false;
673 }
674
675 return true;
676 }
677
678 // Disable SRoA for any intrinsics except for lifetime invariants.
Chandler Carruth50754f02012-09-14 10:26:36 +0000679 // FIXME: What about debug instrinsics? This matches old behavior, but
680 // doesn't make sense.
Chandler Carruth713aa942012-09-14 09:22:59 +0000681 bool visitIntrinsicInst(IntrinsicInst &II) {
682 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
683 II.getIntrinsicID() == Intrinsic::lifetime_end) {
684 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
685 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000686 insertUse(II, Offset, Size, true);
Chandler Carruth713aa942012-09-14 09:22:59 +0000687 return true;
688 }
689
690 return markAsEscaping(II);
691 }
692
693 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
694 // We consider any PHI or select that results in a direct load or store of
695 // the same offset to be a viable use for partitioning purposes. These uses
696 // are considered unsplittable and the size is the maximum loaded or stored
697 // size.
698 SmallPtrSet<Instruction *, 4> Visited;
699 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
700 Visited.insert(Root);
701 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruthc3034632012-09-25 10:03:40 +0000702 // If there are no loads or stores, the access is dead. We mark that as
703 // a size zero access.
704 Size = 0;
Chandler Carruth713aa942012-09-14 09:22:59 +0000705 do {
706 Instruction *I, *UsedI;
707 llvm::tie(UsedI, I) = Uses.pop_back_val();
708
709 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
710 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
711 continue;
712 }
713 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
714 Value *Op = SI->getOperand(0);
715 if (Op == UsedI)
716 return SI;
717 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
718 continue;
719 }
720
721 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
722 if (!GEP->hasAllZeroIndices())
723 return GEP;
724 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
725 !isa<SelectInst>(I)) {
726 return I;
727 }
728
729 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
730 ++UI)
731 if (Visited.insert(cast<Instruction>(*UI)))
732 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
733 } while (!Uses.empty());
734
735 return 0;
736 }
737
738 bool visitPHINode(PHINode &PN) {
739 // See if we already have computed info on this node.
740 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
741 if (PHIInfo.first) {
742 PHIInfo.second = true;
Chandler Carruth63392ea2012-09-16 19:39:50 +0000743 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000744 return true;
745 }
746
747 // Check for an unsafe use of the PHI node.
748 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
749 return markAsEscaping(*EscapingI);
750
Chandler Carruth63392ea2012-09-16 19:39:50 +0000751 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000752 return true;
753 }
754
755 bool visitSelectInst(SelectInst &SI) {
756 if (Value *Result = foldSelectInst(SI)) {
757 if (Result == *U)
758 // If the result of the constant fold will be the pointer, recurse
759 // through the select as if we had RAUW'ed it.
760 enqueueUsers(SI, Offset);
761
762 return true;
763 }
764
765 // See if we already have computed info on this node.
766 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
767 if (SelectInfo.first) {
768 SelectInfo.second = true;
Chandler Carruth63392ea2012-09-16 19:39:50 +0000769 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000770 return true;
771 }
772
773 // Check for an unsafe use of the PHI node.
774 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
775 return markAsEscaping(*EscapingI);
776
Chandler Carruth63392ea2012-09-16 19:39:50 +0000777 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000778 return true;
779 }
780
781 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
782 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
783};
784
785
786/// \brief Use adder for the alloca partitioning.
787///
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000788/// This class adds the uses of an alloca to all of the partitions which they
789/// use. For splittable partitions, this can end up doing essentially a linear
Chandler Carruth713aa942012-09-14 09:22:59 +0000790/// walk of the partitions, but the number of steps remains bounded by the
791/// total result instruction size:
792/// - The number of partitions is a result of the number unsplittable
793/// instructions using the alloca.
794/// - The number of users of each partition is at worst the total number of
795/// splittable instructions using the alloca.
796/// Thus we will produce N * M instructions in the end, where N are the number
797/// of unsplittable uses and M are the number of splittable. This visitor does
798/// the exact same number of updates to the partitioning.
799///
800/// In the more common case, this visitor will leverage the fact that the
801/// partition space is pre-sorted, and do a logarithmic search for the
802/// partition needed, making the total visit a classical ((N + M) * log(N))
803/// complexity operation.
804class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
805 friend class InstVisitor<UseBuilder>;
806
807 /// \brief Set to de-duplicate dead instructions found in the use walk.
808 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
809
810public:
811 UseBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000812 : BuilderBase<UseBuilder>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000813
814 /// \brief Run the builder over the allocation.
815 void operator()() {
816 // Note that we have to re-evaluate size on each trip through the loop as
817 // the queue grows at the tail.
818 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
819 U = Queue[Idx].U;
820 Offset = Queue[Idx].Offset;
821 this->visit(cast<Instruction>(U->getUser()));
822 }
823 }
824
825private:
826 void markAsDead(Instruction &I) {
827 if (VisitedDeadInsts.insert(&I))
828 P.DeadUsers.push_back(&I);
829 }
830
Chandler Carruth02e92a02012-09-23 11:43:14 +0000831 void insertUse(Instruction &User, int64_t Offset, uint64_t Size) {
Chandler Carruthc3034632012-09-25 10:03:40 +0000832 // If the use has a zero size or extends outside of the allocation, record
833 // it as a dead use for elimination later.
834 if (Size == 0 || (uint64_t)Offset >= AllocSize ||
Chandler Carruth02e92a02012-09-23 11:43:14 +0000835 (Offset < 0 && (uint64_t)-Offset >= Size))
Chandler Carruth713aa942012-09-14 09:22:59 +0000836 return markAsDead(User);
837
Chandler Carruth02e92a02012-09-23 11:43:14 +0000838 // Clamp the start to the beginning of the allocation.
839 if (Offset < 0) {
840 Size -= (uint64_t)-Offset;
841 Offset = 0;
842 }
843
844 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
845
846 // Clamp the end offset to the end of the allocation. Note that this is
847 // formulated to handle even the case where "BeginOffset + Size" overflows.
848 assert(AllocSize >= BeginOffset); // Established above.
849 if (Size > AllocSize - BeginOffset)
Chandler Carruth713aa942012-09-14 09:22:59 +0000850 EndOffset = AllocSize;
851
852 // NB: This only works if we have zero overlapping partitions.
853 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
854 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
855 B = llvm::prior(B);
856 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
857 ++I) {
858 PartitionUse NewUse(std::max(I->BeginOffset, BeginOffset),
859 std::min(I->EndOffset, EndOffset),
860 &User, cast<Instruction>(*U));
Chandler Carruth72bf29f2012-09-25 02:42:03 +0000861 P.use_push_back(I, NewUse);
Chandler Carruth713aa942012-09-14 09:22:59 +0000862 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
863 P.PHIOrSelectOpMap[std::make_pair(&User, U->get())]
864 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
865 }
866 }
867
Chandler Carruth02e92a02012-09-23 11:43:14 +0000868 void handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000869 uint64_t Size = TD.getTypeStoreSize(Ty);
870
871 // If this memory access can be shown to *statically* extend outside the
872 // bounds of of the allocation, it's behavior is undefined, so simply
873 // ignore it. Note that this is more strict than the generic clamping
874 // behavior of insertUse.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000875 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
876 Size > (AllocSize - (uint64_t)Offset))
Chandler Carruth713aa942012-09-14 09:22:59 +0000877 return markAsDead(I);
878
Chandler Carruth63392ea2012-09-16 19:39:50 +0000879 insertUse(I, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000880 }
881
882 void visitBitCastInst(BitCastInst &BC) {
883 if (BC.use_empty())
884 return markAsDead(BC);
885
886 enqueueUsers(BC, Offset);
887 }
888
889 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
890 if (GEPI.use_empty())
891 return markAsDead(GEPI);
892
Chandler Carruth02e92a02012-09-23 11:43:14 +0000893 int64_t GEPOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000894 if (!computeConstantGEPOffset(GEPI, GEPOffset))
895 llvm_unreachable("Unable to compute constant offset for use");
896
897 enqueueUsers(GEPI, GEPOffset);
898 }
899
900 void visitLoadInst(LoadInst &LI) {
Chandler Carruth63392ea2012-09-16 19:39:50 +0000901 handleLoadOrStore(LI.getType(), LI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000902 }
903
904 void visitStoreInst(StoreInst &SI) {
Chandler Carruth63392ea2012-09-16 19:39:50 +0000905 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000906 }
907
908 void visitMemSetInst(MemSetInst &II) {
909 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000910 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
911 insertUse(II, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000912 }
913
914 void visitMemTransferInst(MemTransferInst &II) {
915 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000916 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
917 insertUse(II, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000918 }
919
920 void visitIntrinsicInst(IntrinsicInst &II) {
921 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
922 II.getIntrinsicID() == Intrinsic::lifetime_end);
923
924 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruth63392ea2012-09-16 19:39:50 +0000925 insertUse(II, Offset,
926 std::min(AllocSize - Offset, Length->getLimitedValue()));
Chandler Carruth713aa942012-09-14 09:22:59 +0000927 }
928
Chandler Carruth63392ea2012-09-16 19:39:50 +0000929 void insertPHIOrSelect(Instruction &User, uint64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000930 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
931
932 // For PHI and select operands outside the alloca, we can't nuke the entire
933 // phi or select -- the other side might still be relevant, so we special
934 // case them here and use a separate structure to track the operands
935 // themselves which should be replaced with undef.
936 if (Offset >= AllocSize) {
937 P.DeadOperands.push_back(U);
938 return;
939 }
940
Chandler Carruth63392ea2012-09-16 19:39:50 +0000941 insertUse(User, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000942 }
943 void visitPHINode(PHINode &PN) {
944 if (PN.use_empty())
945 return markAsDead(PN);
946
Chandler Carruth63392ea2012-09-16 19:39:50 +0000947 insertPHIOrSelect(PN, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000948 }
949 void visitSelectInst(SelectInst &SI) {
950 if (SI.use_empty())
951 return markAsDead(SI);
952
953 if (Value *Result = foldSelectInst(SI)) {
954 if (Result == *U)
955 // If the result of the constant fold will be the pointer, recurse
956 // through the select as if we had RAUW'ed it.
957 enqueueUsers(SI, Offset);
Chandler Carruthd54a6b52012-09-21 23:36:40 +0000958 else
959 // Otherwise the operand to the select is dead, and we can replace it
960 // with undef.
961 P.DeadOperands.push_back(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000962
963 return;
964 }
965
Chandler Carruth63392ea2012-09-16 19:39:50 +0000966 insertPHIOrSelect(SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000967 }
968
969 /// \brief Unreachable, we've already visited the alloca once.
970 void visitInstruction(Instruction &I) {
971 llvm_unreachable("Unhandled instruction in use builder.");
972 }
973};
974
975void AllocaPartitioning::splitAndMergePartitions() {
976 size_t NumDeadPartitions = 0;
977
978 // Track the range of splittable partitions that we pass when accumulating
979 // overlapping unsplittable partitions.
980 uint64_t SplitEndOffset = 0ull;
981
982 Partition New(0ull, 0ull, false);
983
984 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
985 ++j;
986
987 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
988 assert(New.BeginOffset == New.EndOffset);
989 New = Partitions[i];
990 } else {
991 assert(New.IsSplittable);
992 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
993 }
994 assert(New.BeginOffset != New.EndOffset);
995
996 // Scan the overlapping partitions.
997 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
998 // If the new partition we are forming is splittable, stop at the first
999 // unsplittable partition.
1000 if (New.IsSplittable && !Partitions[j].IsSplittable)
1001 break;
1002
1003 // Grow the new partition to include any equally splittable range. 'j' is
1004 // always equally splittable when New is splittable, but when New is not
1005 // splittable, we may subsume some (or part of some) splitable partition
1006 // without growing the new one.
1007 if (New.IsSplittable == Partitions[j].IsSplittable) {
1008 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
1009 } else {
1010 assert(!New.IsSplittable);
1011 assert(Partitions[j].IsSplittable);
1012 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
1013 }
1014
1015 Partitions[j].BeginOffset = Partitions[j].EndOffset = UINT64_MAX;
1016 ++NumDeadPartitions;
1017 ++j;
1018 }
1019
1020 // If the new partition is splittable, chop off the end as soon as the
1021 // unsplittable subsequent partition starts and ensure we eventually cover
1022 // the splittable area.
1023 if (j != e && New.IsSplittable) {
1024 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1025 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1026 }
1027
1028 // Add the new partition if it differs from the original one and is
1029 // non-empty. We can end up with an empty partition here if it was
1030 // splittable but there is an unsplittable one that starts at the same
1031 // offset.
1032 if (New != Partitions[i]) {
1033 if (New.BeginOffset != New.EndOffset)
1034 Partitions.push_back(New);
1035 // Mark the old one for removal.
1036 Partitions[i].BeginOffset = Partitions[i].EndOffset = UINT64_MAX;
1037 ++NumDeadPartitions;
1038 }
1039
1040 New.BeginOffset = New.EndOffset;
1041 if (!New.IsSplittable) {
1042 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1043 if (j != e && !Partitions[j].IsSplittable)
1044 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1045 New.IsSplittable = true;
1046 // If there is a trailing splittable partition which won't be fused into
1047 // the next splittable partition go ahead and add it onto the partitions
1048 // list.
1049 if (New.BeginOffset < New.EndOffset &&
1050 (j == e || !Partitions[j].IsSplittable ||
1051 New.EndOffset < Partitions[j].BeginOffset)) {
1052 Partitions.push_back(New);
1053 New.BeginOffset = New.EndOffset = 0ull;
1054 }
1055 }
1056 }
1057
1058 // Re-sort the partitions now that they have been split and merged into
1059 // disjoint set of partitions. Also remove any of the dead partitions we've
1060 // replaced in the process.
1061 std::sort(Partitions.begin(), Partitions.end());
1062 if (NumDeadPartitions) {
1063 assert(Partitions.back().BeginOffset == UINT64_MAX);
1064 assert(Partitions.back().EndOffset == UINT64_MAX);
1065 assert((ptrdiff_t)NumDeadPartitions ==
1066 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1067 }
1068 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1069}
1070
1071AllocaPartitioning::AllocaPartitioning(const TargetData &TD, AllocaInst &AI)
Benjamin Kramerd0807692012-09-14 13:08:09 +00001072 :
1073#ifndef NDEBUG
1074 AI(AI),
1075#endif
1076 PointerEscapingInstr(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001077 PartitionBuilder PB(TD, AI, *this);
1078 if (!PB())
1079 return;
1080
1081 if (Partitions.size() > 1) {
1082 // Sort the uses. This arranges for the offsets to be in ascending order,
1083 // and the sizes to be in descending order.
1084 std::sort(Partitions.begin(), Partitions.end());
1085
1086 // Intersect splittability for all partitions with equal offsets and sizes.
1087 // Then remove all but the first so that we have a sequence of non-equal but
1088 // potentially overlapping partitions.
1089 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1090 I = J) {
1091 ++J;
1092 while (J != E && *I == *J) {
1093 I->IsSplittable &= J->IsSplittable;
1094 ++J;
1095 }
1096 }
1097 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1098 Partitions.end());
1099
1100 // Split splittable and merge unsplittable partitions into a disjoint set
1101 // of partitions over the used space of the allocation.
1102 splitAndMergePartitions();
1103 }
1104
1105 // Now build up the user lists for each of these disjoint partitions by
1106 // re-walking the recursive users of the alloca.
1107 Uses.resize(Partitions.size());
1108 UseBuilder UB(TD, AI, *this);
1109 UB();
Chandler Carruth713aa942012-09-14 09:22:59 +00001110}
1111
1112Type *AllocaPartitioning::getCommonType(iterator I) const {
1113 Type *Ty = 0;
1114 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +00001115 if (isa<IntrinsicInst>(*UI->User))
Chandler Carruth713aa942012-09-14 09:22:59 +00001116 continue;
1117 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
Chandler Carruth7c8df7a2012-09-18 17:49:37 +00001118 continue;
Chandler Carruth713aa942012-09-14 09:22:59 +00001119
1120 Type *UserTy = 0;
1121 if (LoadInst *LI = dyn_cast<LoadInst>(&*UI->User)) {
1122 UserTy = LI->getType();
1123 } else if (StoreInst *SI = dyn_cast<StoreInst>(&*UI->User)) {
1124 UserTy = SI->getValueOperand()->getType();
1125 } else if (SelectInst *SI = dyn_cast<SelectInst>(&*UI->User)) {
1126 if (PointerType *PtrTy = dyn_cast<PointerType>(SI->getType()))
1127 UserTy = PtrTy->getElementType();
1128 } else if (PHINode *PN = dyn_cast<PHINode>(&*UI->User)) {
1129 if (PointerType *PtrTy = dyn_cast<PointerType>(PN->getType()))
1130 UserTy = PtrTy->getElementType();
1131 }
1132
1133 if (Ty && Ty != UserTy)
1134 return 0;
1135
1136 Ty = UserTy;
1137 }
1138 return Ty;
1139}
1140
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001141#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1142
Chandler Carruth713aa942012-09-14 09:22:59 +00001143void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1144 StringRef Indent) const {
1145 OS << Indent << "partition #" << (I - begin())
1146 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1147 << (I->IsSplittable ? " (splittable)" : "")
1148 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1149 << "\n";
1150}
1151
1152void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1153 StringRef Indent) const {
1154 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1155 UI != UE; ++UI) {
1156 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
1157 << "used by: " << *UI->User << "\n";
1158 if (MemTransferInst *II = dyn_cast<MemTransferInst>(&*UI->User)) {
1159 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1160 bool IsDest;
1161 if (!MTO.IsSplittable)
1162 IsDest = UI->BeginOffset == MTO.DestBegin;
1163 else
1164 IsDest = MTO.DestBegin != 0u;
1165 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1166 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1167 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1168 }
1169 }
1170}
1171
1172void AllocaPartitioning::print(raw_ostream &OS) const {
1173 if (PointerEscapingInstr) {
1174 OS << "No partitioning for alloca: " << AI << "\n"
1175 << " A pointer to this alloca escaped by:\n"
1176 << " " << *PointerEscapingInstr << "\n";
1177 return;
1178 }
1179
1180 OS << "Partitioning of alloca: " << AI << "\n";
1181 unsigned Num = 0;
1182 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1183 print(OS, I);
1184 printUsers(OS, I);
1185 }
1186}
1187
1188void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1189void AllocaPartitioning::dump() const { print(dbgs()); }
1190
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001191#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1192
Chandler Carruth713aa942012-09-14 09:22:59 +00001193
1194namespace {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001195/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1196///
1197/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1198/// the loads and stores of an alloca instruction, as well as updating its
1199/// debug information. This is used when a domtree is unavailable and thus
1200/// mem2reg in its full form can't be used to handle promotion of allocas to
1201/// scalar values.
1202class AllocaPromoter : public LoadAndStorePromoter {
1203 AllocaInst &AI;
1204 DIBuilder &DIB;
1205
1206 SmallVector<DbgDeclareInst *, 4> DDIs;
1207 SmallVector<DbgValueInst *, 4> DVIs;
1208
1209public:
1210 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1211 AllocaInst &AI, DIBuilder &DIB)
1212 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1213
1214 void run(const SmallVectorImpl<Instruction*> &Insts) {
1215 // Remember which alloca we're promoting (for isInstInList).
1216 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1217 for (Value::use_iterator UI = DebugNode->use_begin(),
1218 UE = DebugNode->use_end();
1219 UI != UE; ++UI)
1220 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1221 DDIs.push_back(DDI);
1222 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1223 DVIs.push_back(DVI);
1224 }
1225
1226 LoadAndStorePromoter::run(Insts);
1227 AI.eraseFromParent();
1228 while (!DDIs.empty())
1229 DDIs.pop_back_val()->eraseFromParent();
1230 while (!DVIs.empty())
1231 DVIs.pop_back_val()->eraseFromParent();
1232 }
1233
1234 virtual bool isInstInList(Instruction *I,
1235 const SmallVectorImpl<Instruction*> &Insts) const {
1236 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1237 return LI->getOperand(0) == &AI;
1238 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1239 }
1240
1241 virtual void updateDebugInfo(Instruction *Inst) const {
1242 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1243 E = DDIs.end(); I != E; ++I) {
1244 DbgDeclareInst *DDI = *I;
1245 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1246 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1247 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1248 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1249 }
1250 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1251 E = DVIs.end(); I != E; ++I) {
1252 DbgValueInst *DVI = *I;
1253 Value *Arg = NULL;
1254 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1255 // If an argument is zero extended then use argument directly. The ZExt
1256 // may be zapped by an optimization pass in future.
1257 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1258 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1259 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1260 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1261 if (!Arg)
1262 Arg = SI->getOperand(0);
1263 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1264 Arg = LI->getOperand(0);
1265 } else {
1266 continue;
1267 }
1268 Instruction *DbgVal =
1269 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1270 Inst);
1271 DbgVal->setDebugLoc(DVI->getDebugLoc());
1272 }
1273 }
1274};
1275} // end anon namespace
1276
1277
1278namespace {
Chandler Carruth713aa942012-09-14 09:22:59 +00001279/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1280///
1281/// This pass takes allocations which can be completely analyzed (that is, they
1282/// don't escape) and tries to turn them into scalar SSA values. There are
1283/// a few steps to this process.
1284///
1285/// 1) It takes allocations of aggregates and analyzes the ways in which they
1286/// are used to try to split them into smaller allocations, ideally of
1287/// a single scalar data type. It will split up memcpy and memset accesses
1288/// as necessary and try to isolate invidual scalar accesses.
1289/// 2) It will transform accesses into forms which are suitable for SSA value
1290/// promotion. This can be replacing a memset with a scalar store of an
1291/// integer value, or it can involve speculating operations on a PHI or
1292/// select to be a PHI or select of the results.
1293/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1294/// onto insert and extract operations on a vector value, and convert them to
1295/// this form. By doing so, it will enable promotion of vector aggregates to
1296/// SSA vector values.
1297class SROA : public FunctionPass {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001298 const bool RequiresDomTree;
1299
Chandler Carruth713aa942012-09-14 09:22:59 +00001300 LLVMContext *C;
1301 const TargetData *TD;
1302 DominatorTree *DT;
1303
1304 /// \brief Worklist of alloca instructions to simplify.
1305 ///
1306 /// Each alloca in the function is added to this. Each new alloca formed gets
1307 /// added to it as well to recursively simplify unless that alloca can be
1308 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1309 /// the one being actively rewritten, we add it back onto the list if not
1310 /// already present to ensure it is re-visited.
1311 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1312
1313 /// \brief A collection of instructions to delete.
1314 /// We try to batch deletions to simplify code and make things a bit more
1315 /// efficient.
1316 SmallVector<Instruction *, 8> DeadInsts;
1317
1318 /// \brief A set to prevent repeatedly marking an instruction split into many
1319 /// uses as dead. Only used to guard insertion into DeadInsts.
1320 SmallPtrSet<Instruction *, 4> DeadSplitInsts;
1321
Chandler Carruth713aa942012-09-14 09:22:59 +00001322 /// \brief A collection of alloca instructions we can directly promote.
1323 std::vector<AllocaInst *> PromotableAllocas;
1324
1325public:
Chandler Carruth1c8db502012-09-15 11:43:14 +00001326 SROA(bool RequiresDomTree = true)
1327 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1328 C(0), TD(0), DT(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001329 initializeSROAPass(*PassRegistry::getPassRegistry());
1330 }
1331 bool runOnFunction(Function &F);
1332 void getAnalysisUsage(AnalysisUsage &AU) const;
1333
1334 const char *getPassName() const { return "SROA"; }
1335 static char ID;
1336
1337private:
1338 friend class AllocaPartitionRewriter;
1339 friend class AllocaPartitionVectorRewriter;
1340
1341 bool rewriteAllocaPartition(AllocaInst &AI,
1342 AllocaPartitioning &P,
1343 AllocaPartitioning::iterator PI);
1344 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1345 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth8615cd22012-09-14 10:26:38 +00001346 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth1c8db502012-09-15 11:43:14 +00001347 bool promoteAllocas(Function &F);
Chandler Carruth713aa942012-09-14 09:22:59 +00001348};
1349}
1350
1351char SROA::ID = 0;
1352
Chandler Carruth1c8db502012-09-15 11:43:14 +00001353FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1354 return new SROA(RequiresDomTree);
Chandler Carruth713aa942012-09-14 09:22:59 +00001355}
1356
1357INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1358 false, false)
1359INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1360INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1361 false, false)
1362
1363/// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1364///
1365/// If the provided GEP is all-constant, the total byte offset formed by the
1366/// GEP is computed and Offset is set to it. If the GEP has any non-constant
1367/// operands, the function returns false and the value of Offset is unmodified.
1368static bool accumulateGEPOffsets(const TargetData &TD, GEPOperator &GEP,
1369 APInt &Offset) {
1370 APInt GEPOffset(Offset.getBitWidth(), 0);
1371 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1372 GTI != GTE; ++GTI) {
1373 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1374 if (!OpC)
1375 return false;
1376 if (OpC->isZero()) continue;
1377
1378 // Handle a struct index, which adds its field offset to the pointer.
1379 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1380 unsigned ElementIdx = OpC->getZExtValue();
1381 const StructLayout *SL = TD.getStructLayout(STy);
1382 GEPOffset += APInt(Offset.getBitWidth(),
1383 SL->getElementOffset(ElementIdx));
1384 continue;
1385 }
1386
1387 APInt TypeSize(Offset.getBitWidth(),
1388 TD.getTypeAllocSize(GTI.getIndexedType()));
1389 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1390 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1391 "vector element size is not a multiple of 8, cannot GEP over it");
1392 TypeSize = VTy->getScalarSizeInBits() / 8;
1393 }
1394
1395 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1396 }
1397 Offset = GEPOffset;
1398 return true;
1399}
1400
1401/// \brief Build a GEP out of a base pointer and indices.
1402///
1403/// This will return the BasePtr if that is valid, or build a new GEP
1404/// instruction using the IRBuilder if GEP-ing is needed.
1405static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1406 SmallVectorImpl<Value *> &Indices,
1407 const Twine &Prefix) {
1408 if (Indices.empty())
1409 return BasePtr;
1410
1411 // A single zero index is a no-op, so check for this and avoid building a GEP
1412 // in that case.
1413 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1414 return BasePtr;
1415
1416 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1417}
1418
1419/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1420/// TargetTy without changing the offset of the pointer.
1421///
1422/// This routine assumes we've already established a properly offset GEP with
1423/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1424/// zero-indices down through type layers until we find one the same as
1425/// TargetTy. If we can't find one with the same type, we at least try to use
1426/// one with the same size. If none of that works, we just produce the GEP as
1427/// indicated by Indices to have the correct offset.
1428static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const TargetData &TD,
1429 Value *BasePtr, Type *Ty, Type *TargetTy,
1430 SmallVectorImpl<Value *> &Indices,
1431 const Twine &Prefix) {
1432 if (Ty == TargetTy)
1433 return buildGEP(IRB, BasePtr, Indices, Prefix);
1434
1435 // See if we can descend into a struct and locate a field with the correct
1436 // type.
1437 unsigned NumLayers = 0;
1438 Type *ElementTy = Ty;
1439 do {
1440 if (ElementTy->isPointerTy())
1441 break;
1442 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1443 ElementTy = SeqTy->getElementType();
1444 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(), 0)));
1445 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1446 ElementTy = *STy->element_begin();
1447 Indices.push_back(IRB.getInt32(0));
1448 } else {
1449 break;
1450 }
1451 ++NumLayers;
1452 } while (ElementTy != TargetTy);
1453 if (ElementTy != TargetTy)
1454 Indices.erase(Indices.end() - NumLayers, Indices.end());
1455
1456 return buildGEP(IRB, BasePtr, Indices, Prefix);
1457}
1458
1459/// \brief Recursively compute indices for a natural GEP.
1460///
1461/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1462/// element types adding appropriate indices for the GEP.
1463static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const TargetData &TD,
1464 Value *Ptr, Type *Ty, APInt &Offset,
1465 Type *TargetTy,
1466 SmallVectorImpl<Value *> &Indices,
1467 const Twine &Prefix) {
1468 if (Offset == 0)
1469 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1470
1471 // We can't recurse through pointer types.
1472 if (Ty->isPointerTy())
1473 return 0;
1474
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001475 // We try to analyze GEPs over vectors here, but note that these GEPs are
1476 // extremely poorly defined currently. The long-term goal is to remove GEPing
1477 // over a vector from the IR completely.
Chandler Carruth713aa942012-09-14 09:22:59 +00001478 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1479 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1480 if (ElementSizeInBits % 8)
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001481 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth713aa942012-09-14 09:22:59 +00001482 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1483 APInt NumSkippedElements = Offset.udiv(ElementSize);
1484 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1485 return 0;
1486 Offset -= NumSkippedElements * ElementSize;
1487 Indices.push_back(IRB.getInt(NumSkippedElements));
1488 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1489 Offset, TargetTy, Indices, Prefix);
1490 }
1491
1492 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1493 Type *ElementTy = ArrTy->getElementType();
1494 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1495 APInt NumSkippedElements = Offset.udiv(ElementSize);
1496 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1497 return 0;
1498
1499 Offset -= NumSkippedElements * ElementSize;
1500 Indices.push_back(IRB.getInt(NumSkippedElements));
1501 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1502 Indices, Prefix);
1503 }
1504
1505 StructType *STy = dyn_cast<StructType>(Ty);
1506 if (!STy)
1507 return 0;
1508
1509 const StructLayout *SL = TD.getStructLayout(STy);
1510 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthad41dcf2012-09-14 10:30:42 +00001511 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00001512 return 0;
1513 unsigned Index = SL->getElementContainingOffset(StructOffset);
1514 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1515 Type *ElementTy = STy->getElementType(Index);
1516 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1517 return 0; // The offset points into alignment padding.
1518
1519 Indices.push_back(IRB.getInt32(Index));
1520 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1521 Indices, Prefix);
1522}
1523
1524/// \brief Get a natural GEP from a base pointer to a particular offset and
1525/// resulting in a particular type.
1526///
1527/// The goal is to produce a "natural" looking GEP that works with the existing
1528/// composite types to arrive at the appropriate offset and element type for
1529/// a pointer. TargetTy is the element type the returned GEP should point-to if
1530/// possible. We recurse by decreasing Offset, adding the appropriate index to
1531/// Indices, and setting Ty to the result subtype.
1532///
Chandler Carruth7f5bede2012-09-14 10:18:49 +00001533/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth713aa942012-09-14 09:22:59 +00001534static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const TargetData &TD,
1535 Value *Ptr, APInt Offset, Type *TargetTy,
1536 SmallVectorImpl<Value *> &Indices,
1537 const Twine &Prefix) {
1538 PointerType *Ty = cast<PointerType>(Ptr->getType());
1539
1540 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1541 // an i8.
1542 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1543 return 0;
1544
1545 Type *ElementTy = Ty->getElementType();
Chandler Carruth38f35fd2012-09-18 22:37:19 +00001546 if (!ElementTy->isSized())
1547 return 0; // We can't GEP through an unsized element.
Chandler Carruth713aa942012-09-14 09:22:59 +00001548 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1549 if (ElementSize == 0)
1550 return 0; // Zero-length arrays can't help us build a natural GEP.
1551 APInt NumSkippedElements = Offset.udiv(ElementSize);
1552
1553 Offset -= NumSkippedElements * ElementSize;
1554 Indices.push_back(IRB.getInt(NumSkippedElements));
1555 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1556 Indices, Prefix);
1557}
1558
1559/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1560/// resulting pointer has PointerTy.
1561///
1562/// This tries very hard to compute a "natural" GEP which arrives at the offset
1563/// and produces the pointer type desired. Where it cannot, it will try to use
1564/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1565/// fails, it will try to use an existing i8* and GEP to the byte offset and
1566/// bitcast to the type.
1567///
1568/// The strategy for finding the more natural GEPs is to peel off layers of the
1569/// pointer, walking back through bit casts and GEPs, searching for a base
1570/// pointer from which we can compute a natural GEP with the desired
1571/// properities. The algorithm tries to fold as many constant indices into
1572/// a single GEP as possible, thus making each GEP more independent of the
1573/// surrounding code.
1574static Value *getAdjustedPtr(IRBuilder<> &IRB, const TargetData &TD,
1575 Value *Ptr, APInt Offset, Type *PointerTy,
1576 const Twine &Prefix) {
1577 // Even though we don't look through PHI nodes, we could be called on an
1578 // instruction in an unreachable block, which may be on a cycle.
1579 SmallPtrSet<Value *, 4> Visited;
1580 Visited.insert(Ptr);
1581 SmallVector<Value *, 4> Indices;
1582
1583 // We may end up computing an offset pointer that has the wrong type. If we
1584 // never are able to compute one directly that has the correct type, we'll
1585 // fall back to it, so keep it around here.
1586 Value *OffsetPtr = 0;
1587
1588 // Remember any i8 pointer we come across to re-use if we need to do a raw
1589 // byte offset.
1590 Value *Int8Ptr = 0;
1591 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1592
1593 Type *TargetTy = PointerTy->getPointerElementType();
1594
1595 do {
1596 // First fold any existing GEPs into the offset.
1597 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1598 APInt GEPOffset(Offset.getBitWidth(), 0);
1599 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1600 break;
1601 Offset += GEPOffset;
1602 Ptr = GEP->getPointerOperand();
1603 if (!Visited.insert(Ptr))
1604 break;
1605 }
1606
1607 // See if we can perform a natural GEP here.
1608 Indices.clear();
1609 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1610 Indices, Prefix)) {
1611 if (P->getType() == PointerTy) {
1612 // Zap any offset pointer that we ended up computing in previous rounds.
1613 if (OffsetPtr && OffsetPtr->use_empty())
1614 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1615 I->eraseFromParent();
1616 return P;
1617 }
1618 if (!OffsetPtr) {
1619 OffsetPtr = P;
1620 }
1621 }
1622
1623 // Stash this pointer if we've found an i8*.
1624 if (Ptr->getType()->isIntegerTy(8)) {
1625 Int8Ptr = Ptr;
1626 Int8PtrOffset = Offset;
1627 }
1628
1629 // Peel off a layer of the pointer and update the offset appropriately.
1630 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1631 Ptr = cast<Operator>(Ptr)->getOperand(0);
1632 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1633 if (GA->mayBeOverridden())
1634 break;
1635 Ptr = GA->getAliasee();
1636 } else {
1637 break;
1638 }
1639 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1640 } while (Visited.insert(Ptr));
1641
1642 if (!OffsetPtr) {
1643 if (!Int8Ptr) {
1644 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1645 Prefix + ".raw_cast");
1646 Int8PtrOffset = Offset;
1647 }
1648
1649 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1650 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1651 Prefix + ".raw_idx");
1652 }
1653 Ptr = OffsetPtr;
1654
1655 // On the off chance we were targeting i8*, guard the bitcast here.
1656 if (Ptr->getType() != PointerTy)
1657 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
1658
1659 return Ptr;
1660}
1661
1662/// \brief Test whether the given alloca partition can be promoted to a vector.
1663///
1664/// This is a quick test to check whether we can rewrite a particular alloca
1665/// partition (and its newly formed alloca) into a vector alloca with only
1666/// whole-vector loads and stores such that it could be promoted to a vector
1667/// SSA value. We only can ensure this for a limited set of operations, and we
1668/// don't want to do the rewrites unless we are confident that the result will
1669/// be promotable, so we have an early test here.
1670static bool isVectorPromotionViable(const TargetData &TD,
1671 Type *AllocaTy,
1672 AllocaPartitioning &P,
1673 uint64_t PartitionBeginOffset,
1674 uint64_t PartitionEndOffset,
1675 AllocaPartitioning::const_use_iterator I,
1676 AllocaPartitioning::const_use_iterator E) {
1677 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1678 if (!Ty)
1679 return false;
1680
1681 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
1682 uint64_t ElementSize = Ty->getScalarSizeInBits();
1683
1684 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1685 // that aren't byte sized.
1686 if (ElementSize % 8)
1687 return false;
1688 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
1689 VecSize /= 8;
1690 ElementSize /= 8;
1691
1692 for (; I != E; ++I) {
1693 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
1694 uint64_t BeginIndex = BeginOffset / ElementSize;
1695 if (BeginIndex * ElementSize != BeginOffset ||
1696 BeginIndex >= Ty->getNumElements())
1697 return false;
1698 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
1699 uint64_t EndIndex = EndOffset / ElementSize;
1700 if (EndIndex * ElementSize != EndOffset ||
1701 EndIndex > Ty->getNumElements())
1702 return false;
1703
1704 // FIXME: We should build shuffle vector instructions to handle
1705 // non-element-sized accesses.
1706 if ((EndOffset - BeginOffset) != ElementSize &&
1707 (EndOffset - BeginOffset) != VecSize)
1708 return false;
1709
1710 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&*I->User)) {
1711 if (MI->isVolatile())
1712 return false;
1713 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(&*I->User)) {
1714 const AllocaPartitioning::MemTransferOffsets &MTO
1715 = P.getMemTransferOffsets(*MTI);
1716 if (!MTO.IsSplittable)
1717 return false;
1718 }
1719 } else if (I->Ptr->getType()->getPointerElementType()->isStructTy()) {
1720 // Disable vector promotion when there are loads or stores of an FCA.
1721 return false;
1722 } else if (!isa<LoadInst>(*I->User) && !isa<StoreInst>(*I->User)) {
1723 return false;
1724 }
1725 }
1726 return true;
1727}
1728
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001729/// \brief Test whether the given alloca partition can be promoted to an int.
1730///
1731/// This is a quick test to check whether we can rewrite a particular alloca
1732/// partition (and its newly formed alloca) into an integer alloca suitable for
1733/// promotion to an SSA value. We only can ensure this for a limited set of
1734/// operations, and we don't want to do the rewrites unless we are confident
1735/// that the result will be promotable, so we have an early test here.
1736static bool isIntegerPromotionViable(const TargetData &TD,
1737 Type *AllocaTy,
1738 AllocaPartitioning &P,
1739 AllocaPartitioning::const_use_iterator I,
1740 AllocaPartitioning::const_use_iterator E) {
1741 IntegerType *Ty = dyn_cast<IntegerType>(AllocaTy);
1742 if (!Ty)
1743 return false;
1744
1745 // Check the uses to ensure the uses are (likely) promoteable integer uses.
1746 // Also ensure that the alloca has a covering load or store. We don't want
1747 // promote because of some other unsplittable entry (which we may make
1748 // splittable later) and lose the ability to promote each element access.
1749 bool WholeAllocaOp = false;
1750 for (; I != E; ++I) {
1751 if (LoadInst *LI = dyn_cast<LoadInst>(&*I->User)) {
1752 if (LI->isVolatile() || !LI->getType()->isIntegerTy())
1753 return false;
1754 if (LI->getType() == Ty)
1755 WholeAllocaOp = true;
1756 } else if (StoreInst *SI = dyn_cast<StoreInst>(&*I->User)) {
1757 if (SI->isVolatile() || !SI->getValueOperand()->getType()->isIntegerTy())
1758 return false;
1759 if (SI->getValueOperand()->getType() == Ty)
1760 WholeAllocaOp = true;
1761 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&*I->User)) {
1762 if (MI->isVolatile())
1763 return false;
1764 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(&*I->User)) {
1765 const AllocaPartitioning::MemTransferOffsets &MTO
1766 = P.getMemTransferOffsets(*MTI);
1767 if (!MTO.IsSplittable)
1768 return false;
1769 }
1770 } else {
1771 return false;
1772 }
1773 }
1774 return WholeAllocaOp;
1775}
1776
Chandler Carruth713aa942012-09-14 09:22:59 +00001777namespace {
1778/// \brief Visitor to rewrite instructions using a partition of an alloca to
1779/// use a new alloca.
1780///
1781/// Also implements the rewriting to vector-based accesses when the partition
1782/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1783/// lives here.
1784class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
1785 bool> {
1786 // Befriend the base class so it can delegate to private visit methods.
1787 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
1788
1789 const TargetData &TD;
1790 AllocaPartitioning &P;
1791 SROA &Pass;
1792 AllocaInst &OldAI, &NewAI;
1793 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
1794
1795 // If we are rewriting an alloca partition which can be written as pure
1796 // vector operations, we stash extra information here. When VecTy is
1797 // non-null, we have some strict guarantees about the rewriten alloca:
1798 // - The new alloca is exactly the size of the vector type here.
1799 // - The accesses all either map to the entire vector or to a single
1800 // element.
1801 // - The set of accessing instructions is only one of those handled above
1802 // in isVectorPromotionViable. Generally these are the same access kinds
1803 // which are promotable via mem2reg.
1804 VectorType *VecTy;
1805 Type *ElementTy;
1806 uint64_t ElementSize;
1807
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001808 // This is a convenience and flag variable that will be null unless the new
1809 // alloca has a promotion-targeted integer type due to passing
1810 // isIntegerPromotionViable above. If it is non-null does, the desired
1811 // integer type will be stored here for easy access during rewriting.
1812 IntegerType *IntPromotionTy;
1813
Chandler Carruth713aa942012-09-14 09:22:59 +00001814 // The offset of the partition user currently being rewritten.
1815 uint64_t BeginOffset, EndOffset;
1816 Instruction *OldPtr;
1817
1818 // The name prefix to use when rewriting instructions for this alloca.
1819 std::string NamePrefix;
1820
1821public:
1822 AllocaPartitionRewriter(const TargetData &TD, AllocaPartitioning &P,
1823 AllocaPartitioning::iterator PI,
1824 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
1825 uint64_t NewBeginOffset, uint64_t NewEndOffset)
1826 : TD(TD), P(P), Pass(Pass),
1827 OldAI(OldAI), NewAI(NewAI),
1828 NewAllocaBeginOffset(NewBeginOffset),
1829 NewAllocaEndOffset(NewEndOffset),
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001830 VecTy(), ElementTy(), ElementSize(), IntPromotionTy(),
Chandler Carruth713aa942012-09-14 09:22:59 +00001831 BeginOffset(), EndOffset() {
1832 }
1833
1834 /// \brief Visit the users of the alloca partition and rewrite them.
1835 bool visitUsers(AllocaPartitioning::const_use_iterator I,
1836 AllocaPartitioning::const_use_iterator E) {
1837 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
1838 NewAllocaBeginOffset, NewAllocaEndOffset,
1839 I, E)) {
1840 ++NumVectorized;
1841 VecTy = cast<VectorType>(NewAI.getAllocatedType());
1842 ElementTy = VecTy->getElementType();
1843 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
1844 "Only multiple-of-8 sized vector elements are viable");
1845 ElementSize = VecTy->getScalarSizeInBits() / 8;
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001846 } else if (isIntegerPromotionViable(TD, NewAI.getAllocatedType(),
1847 P, I, E)) {
1848 IntPromotionTy = cast<IntegerType>(NewAI.getAllocatedType());
Chandler Carruth713aa942012-09-14 09:22:59 +00001849 }
1850 bool CanSROA = true;
1851 for (; I != E; ++I) {
1852 BeginOffset = I->BeginOffset;
1853 EndOffset = I->EndOffset;
1854 OldPtr = I->Ptr;
1855 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
1856 CanSROA &= visit(I->User);
1857 }
1858 if (VecTy) {
1859 assert(CanSROA);
1860 VecTy = 0;
1861 ElementTy = 0;
1862 ElementSize = 0;
1863 }
1864 return CanSROA;
1865 }
1866
1867private:
1868 // Every instruction which can end up as a user must have a rewrite rule.
1869 bool visitInstruction(Instruction &I) {
1870 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
1871 llvm_unreachable("No rewrite rule for this instruction!");
1872 }
1873
1874 Twine getName(const Twine &Suffix) {
1875 return NamePrefix + Suffix;
1876 }
1877
1878 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
1879 assert(BeginOffset >= NewAllocaBeginOffset);
1880 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
1881 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
1882 }
1883
1884 ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
1885 assert(VecTy && "Can only call getIndex when rewriting a vector");
1886 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1887 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
1888 uint32_t Index = RelOffset / ElementSize;
1889 assert(Index * ElementSize == RelOffset);
1890 return IRB.getInt32(Index);
1891 }
1892
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001893 Value *extractInteger(IRBuilder<> &IRB, IntegerType *TargetTy,
1894 uint64_t Offset) {
1895 assert(IntPromotionTy && "Alloca is not an integer we can extract from");
1896 Value *V = IRB.CreateLoad(&NewAI, getName(".load"));
1897 assert(Offset >= NewAllocaBeginOffset && "Out of bounds offset");
1898 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1899 if (RelOffset)
1900 V = IRB.CreateLShr(V, RelOffset*8, getName(".shift"));
1901 if (TargetTy != IntPromotionTy) {
1902 assert(TargetTy->getBitWidth() < IntPromotionTy->getBitWidth() &&
1903 "Cannot extract to a larger integer!");
1904 V = IRB.CreateTrunc(V, TargetTy, getName(".trunc"));
1905 }
1906 return V;
1907 }
1908
1909 StoreInst *insertInteger(IRBuilder<> &IRB, Value *V, uint64_t Offset) {
1910 IntegerType *Ty = cast<IntegerType>(V->getType());
1911 if (Ty == IntPromotionTy)
1912 return IRB.CreateStore(V, &NewAI);
1913
1914 assert(Ty->getBitWidth() < IntPromotionTy->getBitWidth() &&
1915 "Cannot insert a larger integer!");
1916 V = IRB.CreateZExt(V, IntPromotionTy, getName(".ext"));
1917 assert(Offset >= NewAllocaBeginOffset && "Out of bounds offset");
1918 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1919 if (RelOffset)
1920 V = IRB.CreateShl(V, RelOffset*8, getName(".shift"));
1921
1922 APInt Mask = ~Ty->getMask().zext(IntPromotionTy->getBitWidth())
1923 .shl(RelOffset*8);
1924 Value *Old = IRB.CreateAnd(IRB.CreateLoad(&NewAI, getName(".oldload")),
1925 Mask, getName(".mask"));
1926 return IRB.CreateStore(IRB.CreateOr(Old, V, getName(".insert")),
1927 &NewAI);
1928 }
1929
Chandler Carruth713aa942012-09-14 09:22:59 +00001930 void deleteIfTriviallyDead(Value *V) {
1931 Instruction *I = cast<Instruction>(V);
1932 if (isInstructionTriviallyDead(I))
1933 Pass.DeadInsts.push_back(I);
1934 }
1935
1936 Value *getValueCast(IRBuilder<> &IRB, Value *V, Type *Ty) {
1937 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1938 return IRB.CreateIntToPtr(V, Ty);
1939 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1940 return IRB.CreatePtrToInt(V, Ty);
1941
1942 return IRB.CreateBitCast(V, Ty);
1943 }
1944
1945 bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
1946 Value *Result;
1947 if (LI.getType() == VecTy->getElementType() ||
1948 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
1949 Result
1950 = IRB.CreateExtractElement(IRB.CreateLoad(&NewAI, getName(".load")),
1951 getIndex(IRB, BeginOffset),
1952 getName(".extract"));
1953 } else {
1954 Result = IRB.CreateLoad(&NewAI, getName(".load"));
1955 }
1956 if (Result->getType() != LI.getType())
1957 Result = getValueCast(IRB, Result, LI.getType());
1958 LI.replaceAllUsesWith(Result);
1959 Pass.DeadInsts.push_back(&LI);
1960
1961 DEBUG(dbgs() << " to: " << *Result << "\n");
1962 return true;
1963 }
1964
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001965 bool rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
1966 assert(!LI.isVolatile());
1967 Value *Result = extractInteger(IRB, cast<IntegerType>(LI.getType()),
1968 BeginOffset);
1969 LI.replaceAllUsesWith(Result);
1970 Pass.DeadInsts.push_back(&LI);
1971 DEBUG(dbgs() << " to: " << *Result << "\n");
1972 return true;
1973 }
1974
Chandler Carruth713aa942012-09-14 09:22:59 +00001975 bool visitLoadInst(LoadInst &LI) {
1976 DEBUG(dbgs() << " original: " << LI << "\n");
1977 Value *OldOp = LI.getOperand(0);
1978 assert(OldOp == OldPtr);
1979 IRBuilder<> IRB(&LI);
1980
1981 if (VecTy)
1982 return rewriteVectorizedLoadInst(IRB, LI, OldOp);
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001983 if (IntPromotionTy)
1984 return rewriteIntegerLoad(IRB, LI);
Chandler Carruth713aa942012-09-14 09:22:59 +00001985
1986 Value *NewPtr = getAdjustedAllocaPtr(IRB,
1987 LI.getPointerOperand()->getType());
1988 LI.setOperand(0, NewPtr);
1989 DEBUG(dbgs() << " to: " << LI << "\n");
1990
1991 deleteIfTriviallyDead(OldOp);
1992 return NewPtr == &NewAI && !LI.isVolatile();
1993 }
1994
1995 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI,
1996 Value *OldOp) {
1997 Value *V = SI.getValueOperand();
1998 if (V->getType() == ElementTy ||
1999 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
2000 if (V->getType() != ElementTy)
2001 V = getValueCast(IRB, V, ElementTy);
2002 V = IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")), V,
2003 getIndex(IRB, BeginOffset),
2004 getName(".insert"));
2005 } else if (V->getType() != VecTy) {
2006 V = getValueCast(IRB, V, VecTy);
2007 }
2008 StoreInst *Store = IRB.CreateStore(V, &NewAI);
2009 Pass.DeadInsts.push_back(&SI);
2010
2011 (void)Store;
2012 DEBUG(dbgs() << " to: " << *Store << "\n");
2013 return true;
2014 }
2015
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002016 bool rewriteIntegerStore(IRBuilder<> &IRB, StoreInst &SI) {
2017 assert(!SI.isVolatile());
2018 StoreInst *Store = insertInteger(IRB, SI.getValueOperand(), BeginOffset);
2019 Pass.DeadInsts.push_back(&SI);
2020 (void)Store;
2021 DEBUG(dbgs() << " to: " << *Store << "\n");
2022 return true;
2023 }
2024
Chandler Carruth713aa942012-09-14 09:22:59 +00002025 bool visitStoreInst(StoreInst &SI) {
2026 DEBUG(dbgs() << " original: " << SI << "\n");
2027 Value *OldOp = SI.getOperand(1);
2028 assert(OldOp == OldPtr);
2029 IRBuilder<> IRB(&SI);
2030
2031 if (VecTy)
2032 return rewriteVectorizedStoreInst(IRB, SI, OldOp);
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002033 if (IntPromotionTy)
2034 return rewriteIntegerStore(IRB, SI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002035
2036 Value *NewPtr = getAdjustedAllocaPtr(IRB,
2037 SI.getPointerOperand()->getType());
2038 SI.setOperand(1, NewPtr);
2039 DEBUG(dbgs() << " to: " << SI << "\n");
2040
2041 deleteIfTriviallyDead(OldOp);
2042 return NewPtr == &NewAI && !SI.isVolatile();
2043 }
2044
2045 bool visitMemSetInst(MemSetInst &II) {
2046 DEBUG(dbgs() << " original: " << II << "\n");
2047 IRBuilder<> IRB(&II);
2048 assert(II.getRawDest() == OldPtr);
2049
2050 // If the memset has a variable size, it cannot be split, just adjust the
2051 // pointer to the new alloca.
2052 if (!isa<Constant>(II.getLength())) {
2053 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2054 deleteIfTriviallyDead(OldPtr);
2055 return false;
2056 }
2057
2058 // Record this instruction for deletion.
2059 if (Pass.DeadSplitInsts.insert(&II))
2060 Pass.DeadInsts.push_back(&II);
2061
2062 Type *AllocaTy = NewAI.getAllocatedType();
2063 Type *ScalarTy = AllocaTy->getScalarType();
2064
2065 // If this doesn't map cleanly onto the alloca type, and that type isn't
2066 // a single value type, just emit a memset.
2067 if (!VecTy && (BeginOffset != NewAllocaBeginOffset ||
2068 EndOffset != NewAllocaEndOffset ||
2069 !AllocaTy->isSingleValueType() ||
2070 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
2071 Type *SizeTy = II.getLength()->getType();
2072 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2073
2074 CallInst *New
2075 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2076 II.getRawDest()->getType()),
2077 II.getValue(), Size, II.getAlignment(),
2078 II.isVolatile());
2079 (void)New;
2080 DEBUG(dbgs() << " to: " << *New << "\n");
2081 return false;
2082 }
2083
2084 // If we can represent this as a simple value, we have to build the actual
2085 // value to store, which requires expanding the byte present in memset to
2086 // a sensible representation for the alloca type. This is essentially
2087 // splatting the byte to a sufficiently wide integer, bitcasting to the
2088 // desired scalar type, and splatting it across any desired vector type.
2089 Value *V = II.getValue();
2090 IntegerType *VTy = cast<IntegerType>(V->getType());
2091 Type *IntTy = Type::getIntNTy(VTy->getContext(),
2092 TD.getTypeSizeInBits(ScalarTy));
2093 if (TD.getTypeSizeInBits(ScalarTy) > VTy->getBitWidth())
2094 V = IRB.CreateMul(IRB.CreateZExt(V, IntTy, getName(".zext")),
2095 ConstantExpr::getUDiv(
2096 Constant::getAllOnesValue(IntTy),
2097 ConstantExpr::getZExt(
2098 Constant::getAllOnesValue(V->getType()),
2099 IntTy)),
2100 getName(".isplat"));
2101 if (V->getType() != ScalarTy) {
2102 if (ScalarTy->isPointerTy())
2103 V = IRB.CreateIntToPtr(V, ScalarTy);
2104 else if (ScalarTy->isPrimitiveType() || ScalarTy->isVectorTy())
2105 V = IRB.CreateBitCast(V, ScalarTy);
2106 else if (ScalarTy->isIntegerTy())
2107 llvm_unreachable("Computed different integer types with equal widths");
2108 else
2109 llvm_unreachable("Invalid scalar type");
2110 }
2111
2112 // If this is an element-wide memset of a vectorizable alloca, insert it.
2113 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
2114 EndOffset < NewAllocaEndOffset)) {
2115 StoreInst *Store = IRB.CreateStore(
2116 IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")), V,
2117 getIndex(IRB, BeginOffset),
2118 getName(".insert")),
2119 &NewAI);
2120 (void)Store;
2121 DEBUG(dbgs() << " to: " << *Store << "\n");
2122 return true;
2123 }
2124
2125 // Splat to a vector if needed.
2126 if (VectorType *VecTy = dyn_cast<VectorType>(AllocaTy)) {
2127 VectorType *SplatSourceTy = VectorType::get(V->getType(), 1);
2128 V = IRB.CreateShuffleVector(
2129 IRB.CreateInsertElement(UndefValue::get(SplatSourceTy), V,
2130 IRB.getInt32(0), getName(".vsplat.insert")),
2131 UndefValue::get(SplatSourceTy),
2132 ConstantVector::getSplat(VecTy->getNumElements(), IRB.getInt32(0)),
2133 getName(".vsplat.shuffle"));
2134 assert(V->getType() == VecTy);
2135 }
2136
2137 Value *New = IRB.CreateStore(V, &NewAI, II.isVolatile());
2138 (void)New;
2139 DEBUG(dbgs() << " to: " << *New << "\n");
2140 return !II.isVolatile();
2141 }
2142
2143 bool visitMemTransferInst(MemTransferInst &II) {
2144 // Rewriting of memory transfer instructions can be a bit tricky. We break
2145 // them into two categories: split intrinsics and unsplit intrinsics.
2146
2147 DEBUG(dbgs() << " original: " << II << "\n");
2148 IRBuilder<> IRB(&II);
2149
2150 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2151 bool IsDest = II.getRawDest() == OldPtr;
2152
2153 const AllocaPartitioning::MemTransferOffsets &MTO
2154 = P.getMemTransferOffsets(II);
2155
2156 // For unsplit intrinsics, we simply modify the source and destination
2157 // pointers in place. This isn't just an optimization, it is a matter of
2158 // correctness. With unsplit intrinsics we may be dealing with transfers
2159 // within a single alloca before SROA ran, or with transfers that have
2160 // a variable length. We may also be dealing with memmove instead of
2161 // memcpy, and so simply updating the pointers is the necessary for us to
2162 // update both source and dest of a single call.
2163 if (!MTO.IsSplittable) {
2164 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2165 if (IsDest)
2166 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2167 else
2168 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2169
2170 DEBUG(dbgs() << " to: " << II << "\n");
2171 deleteIfTriviallyDead(OldOp);
2172 return false;
2173 }
2174 // For split transfer intrinsics we have an incredibly useful assurance:
2175 // the source and destination do not reside within the same alloca, and at
2176 // least one of them does not escape. This means that we can replace
2177 // memmove with memcpy, and we don't need to worry about all manner of
2178 // downsides to splitting and transforming the operations.
2179
2180 // Compute the relative offset within the transfer.
2181 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2182 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2183 : MTO.SourceBegin));
2184
2185 // If this doesn't map cleanly onto the alloca type, and that type isn't
2186 // a single value type, just emit a memcpy.
2187 bool EmitMemCpy
2188 = !VecTy && (BeginOffset != NewAllocaBeginOffset ||
2189 EndOffset != NewAllocaEndOffset ||
2190 !NewAI.getAllocatedType()->isSingleValueType());
2191
2192 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2193 // size hasn't been shrunk based on analysis of the viable range, this is
2194 // a no-op.
2195 if (EmitMemCpy && &OldAI == &NewAI) {
2196 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2197 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2198 // Ensure the start lines up.
2199 assert(BeginOffset == OrigBegin);
Benjamin Kramerd0807692012-09-14 13:08:09 +00002200 (void)OrigBegin;
Chandler Carruth713aa942012-09-14 09:22:59 +00002201
2202 // Rewrite the size as needed.
2203 if (EndOffset != OrigEnd)
2204 II.setLength(ConstantInt::get(II.getLength()->getType(),
2205 EndOffset - BeginOffset));
2206 return false;
2207 }
2208 // Record this instruction for deletion.
2209 if (Pass.DeadSplitInsts.insert(&II))
2210 Pass.DeadInsts.push_back(&II);
2211
2212 bool IsVectorElement = VecTy && (BeginOffset > NewAllocaBeginOffset ||
2213 EndOffset < NewAllocaEndOffset);
2214
2215 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2216 : II.getRawDest()->getType();
2217 if (!EmitMemCpy)
2218 OtherPtrTy = IsVectorElement ? VecTy->getElementType()->getPointerTo()
2219 : NewAI.getType();
2220
2221 // Compute the other pointer, folding as much as possible to produce
2222 // a single, simple GEP in most cases.
2223 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2224 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2225 getName("." + OtherPtr->getName()));
2226
2227 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2228 // alloca that should be re-examined after rewriting this instruction.
2229 if (AllocaInst *AI
2230 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Nick Lewycky48c0f652012-09-25 21:50:37 +00002231 // Don't revisit the alloca if both sides of the memory transfer are
2232 // referring to the same alloca.
2233 if (AI != &NewAI)
2234 Pass.Worklist.insert(AI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002235
2236 if (EmitMemCpy) {
2237 Value *OurPtr
2238 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2239 : II.getRawSource()->getType());
2240 Type *SizeTy = II.getLength()->getType();
2241 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2242
2243 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2244 IsDest ? OtherPtr : OurPtr,
2245 Size, II.getAlignment(),
2246 II.isVolatile());
2247 (void)New;
2248 DEBUG(dbgs() << " to: " << *New << "\n");
2249 return false;
2250 }
2251
2252 Value *SrcPtr = OtherPtr;
2253 Value *DstPtr = &NewAI;
2254 if (!IsDest)
2255 std::swap(SrcPtr, DstPtr);
2256
2257 Value *Src;
2258 if (IsVectorElement && !IsDest) {
2259 // We have to extract rather than load.
2260 Src = IRB.CreateExtractElement(IRB.CreateLoad(SrcPtr,
2261 getName(".copyload")),
2262 getIndex(IRB, BeginOffset),
2263 getName(".copyextract"));
2264 } else {
2265 Src = IRB.CreateLoad(SrcPtr, II.isVolatile(), getName(".copyload"));
2266 }
2267
2268 if (IsVectorElement && IsDest) {
2269 // We have to insert into a loaded copy before storing.
2270 Src = IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")),
2271 Src, getIndex(IRB, BeginOffset),
2272 getName(".insert"));
2273 }
2274
Nick Lewycky051a3182012-09-25 22:46:21 +00002275 StoreInst *Store = cast<StoreInst>(IRB.CreateStore(Src, DstPtr,
2276 II.isVolatile()));
2277 Store->setAlignment(II.getAlignment());
Chandler Carruth713aa942012-09-14 09:22:59 +00002278 DEBUG(dbgs() << " to: " << *Store << "\n");
2279 return !II.isVolatile();
2280 }
2281
2282 bool visitIntrinsicInst(IntrinsicInst &II) {
2283 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2284 II.getIntrinsicID() == Intrinsic::lifetime_end);
2285 DEBUG(dbgs() << " original: " << II << "\n");
2286 IRBuilder<> IRB(&II);
2287 assert(II.getArgOperand(1) == OldPtr);
2288
2289 // Record this instruction for deletion.
2290 if (Pass.DeadSplitInsts.insert(&II))
2291 Pass.DeadInsts.push_back(&II);
2292
2293 ConstantInt *Size
2294 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2295 EndOffset - BeginOffset);
2296 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2297 Value *New;
2298 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2299 New = IRB.CreateLifetimeStart(Ptr, Size);
2300 else
2301 New = IRB.CreateLifetimeEnd(Ptr, Size);
2302
2303 DEBUG(dbgs() << " to: " << *New << "\n");
2304 return true;
2305 }
2306
2307 /// PHI instructions that use an alloca and are subsequently loaded can be
2308 /// rewritten to load both input pointers in the pred blocks and then PHI the
2309 /// results, allowing the load of the alloca to be promoted.
2310 /// From this:
2311 /// %P2 = phi [i32* %Alloca, i32* %Other]
2312 /// %V = load i32* %P2
2313 /// to:
2314 /// %V1 = load i32* %Alloca -> will be mem2reg'd
2315 /// ...
2316 /// %V2 = load i32* %Other
2317 /// ...
2318 /// %V = phi [i32 %V1, i32 %V2]
2319 ///
2320 /// We can do this to a select if its only uses are loads and if the operand
2321 /// to the select can be loaded unconditionally.
2322 ///
2323 /// FIXME: This should be hoisted into a generic utility, likely in
2324 /// Transforms/Util/Local.h
2325 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
2326 // For now, we can only do this promotion if the load is in the same block
2327 // as the PHI, and if there are no stores between the phi and load.
2328 // TODO: Allow recursive phi users.
2329 // TODO: Allow stores.
2330 BasicBlock *BB = PN.getParent();
2331 unsigned MaxAlign = 0;
2332 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
2333 UI != UE; ++UI) {
2334 LoadInst *LI = dyn_cast<LoadInst>(*UI);
2335 if (LI == 0 || !LI->isSimple()) return false;
2336
2337 // For now we only allow loads in the same block as the PHI. This is
2338 // a common case that happens when instcombine merges two loads through
2339 // a PHI.
2340 if (LI->getParent() != BB) return false;
2341
2342 // Ensure that there are no instructions between the PHI and the load that
2343 // could store.
2344 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
2345 if (BBI->mayWriteToMemory())
2346 return false;
2347
2348 MaxAlign = std::max(MaxAlign, LI->getAlignment());
2349 Loads.push_back(LI);
2350 }
2351
2352 // We can only transform this if it is safe to push the loads into the
2353 // predecessor blocks. The only thing to watch out for is that we can't put
2354 // a possibly trapping load in the predecessor if it is a critical edge.
2355 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
2356 ++Idx) {
2357 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
2358 Value *InVal = PN.getIncomingValue(Idx);
2359
2360 // If the value is produced by the terminator of the predecessor (an
2361 // invoke) or it has side-effects, there is no valid place to put a load
2362 // in the predecessor.
2363 if (TI == InVal || TI->mayHaveSideEffects())
2364 return false;
2365
2366 // If the predecessor has a single successor, then the edge isn't
2367 // critical.
2368 if (TI->getNumSuccessors() == 1)
2369 continue;
2370
2371 // If this pointer is always safe to load, or if we can prove that there
2372 // is already a load in the block, then we can move the load to the pred
2373 // block.
2374 if (InVal->isDereferenceablePointer() ||
2375 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
2376 continue;
2377
2378 return false;
2379 }
2380
2381 return true;
2382 }
2383
2384 bool visitPHINode(PHINode &PN) {
2385 DEBUG(dbgs() << " original: " << PN << "\n");
2386 // We would like to compute a new pointer in only one place, but have it be
2387 // as local as possible to the PHI. To do that, we re-use the location of
2388 // the old pointer, which necessarily must be in the right position to
2389 // dominate the PHI.
2390 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2391
2392 SmallVector<LoadInst *, 4> Loads;
2393 if (!isSafePHIToSpeculate(PN, Loads)) {
2394 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2395 // Replace the operands which were using the old pointer.
2396 User::op_iterator OI = PN.op_begin(), OE = PN.op_end();
2397 for (; OI != OE; ++OI)
2398 if (*OI == OldPtr)
2399 *OI = NewPtr;
2400
2401 DEBUG(dbgs() << " to: " << PN << "\n");
2402 deleteIfTriviallyDead(OldPtr);
2403 return false;
2404 }
2405 assert(!Loads.empty());
2406
2407 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
2408 IRBuilder<> PHIBuilder(&PN);
2409 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues());
2410 NewPN->takeName(&PN);
2411
2412 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
2413 // matter which one we get and if any differ, it doesn't matter.
2414 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
2415 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
2416 unsigned Align = SomeLoad->getAlignment();
2417 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2418
2419 // Rewrite all loads of the PN to use the new PHI.
2420 do {
2421 LoadInst *LI = Loads.pop_back_val();
2422 LI->replaceAllUsesWith(NewPN);
2423 Pass.DeadInsts.push_back(LI);
2424 } while (!Loads.empty());
2425
2426 // Inject loads into all of the pred blocks.
2427 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
2428 BasicBlock *Pred = PN.getIncomingBlock(Idx);
2429 TerminatorInst *TI = Pred->getTerminator();
2430 Value *InVal = PN.getIncomingValue(Idx);
2431 IRBuilder<> PredBuilder(TI);
2432
2433 // Map the value to the new alloca pointer if this was the old alloca
2434 // pointer.
2435 bool ThisOperand = InVal == OldPtr;
2436 if (ThisOperand)
2437 InVal = NewPtr;
2438
2439 LoadInst *Load
2440 = PredBuilder.CreateLoad(InVal, getName(".sroa.speculate." +
2441 Pred->getName()));
2442 ++NumLoadsSpeculated;
2443 Load->setAlignment(Align);
2444 if (TBAATag)
2445 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
2446 NewPN->addIncoming(Load, Pred);
2447
2448 if (ThisOperand)
2449 continue;
2450 Instruction *OtherPtr = dyn_cast<Instruction>(InVal);
2451 if (!OtherPtr)
2452 // No uses to rewrite.
2453 continue;
2454
2455 // Try to lookup and rewrite any partition uses corresponding to this phi
2456 // input.
2457 AllocaPartitioning::iterator PI
2458 = P.findPartitionForPHIOrSelectOperand(PN, OtherPtr);
2459 if (PI != P.end()) {
2460 // If the other pointer is within the partitioning, replace the PHI in
2461 // its uses with the load we just speculated, or add another load for
2462 // it to rewrite if we've already replaced the PHI.
2463 AllocaPartitioning::use_iterator UI
2464 = P.findPartitionUseForPHIOrSelectOperand(PN, OtherPtr);
2465 if (isa<PHINode>(*UI->User))
2466 UI->User = Load;
2467 else {
2468 AllocaPartitioning::PartitionUse OtherUse = *UI;
2469 OtherUse.User = Load;
Chandler Carruth72bf29f2012-09-25 02:42:03 +00002470 P.use_push_back(PI, OtherUse);
Chandler Carruth713aa942012-09-14 09:22:59 +00002471 }
2472 }
2473 }
2474 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
2475 return NewPtr == &NewAI;
2476 }
2477
2478 /// Select instructions that use an alloca and are subsequently loaded can be
2479 /// rewritten to load both input pointers and then select between the result,
2480 /// allowing the load of the alloca to be promoted.
2481 /// From this:
2482 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
2483 /// %V = load i32* %P2
2484 /// to:
2485 /// %V1 = load i32* %Alloca -> will be mem2reg'd
2486 /// %V2 = load i32* %Other
2487 /// %V = select i1 %cond, i32 %V1, i32 %V2
2488 ///
2489 /// We can do this to a select if its only uses are loads and if the operand
2490 /// to the select can be loaded unconditionally.
2491 bool isSafeSelectToSpeculate(SelectInst &SI,
2492 SmallVectorImpl<LoadInst *> &Loads) {
2493 Value *TValue = SI.getTrueValue();
2494 Value *FValue = SI.getFalseValue();
2495 bool TDerefable = TValue->isDereferenceablePointer();
2496 bool FDerefable = FValue->isDereferenceablePointer();
2497
2498 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
2499 UI != UE; ++UI) {
2500 LoadInst *LI = dyn_cast<LoadInst>(*UI);
2501 if (LI == 0 || !LI->isSimple()) return false;
2502
2503 // Both operands to the select need to be dereferencable, either
2504 // absolutely (e.g. allocas) or at this point because we can see other
2505 // accesses to it.
2506 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
2507 LI->getAlignment(), &TD))
2508 return false;
2509 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
2510 LI->getAlignment(), &TD))
2511 return false;
2512 Loads.push_back(LI);
2513 }
2514
2515 return true;
2516 }
2517
2518 bool visitSelectInst(SelectInst &SI) {
2519 DEBUG(dbgs() << " original: " << SI << "\n");
2520 IRBuilder<> IRB(&SI);
2521
2522 // Find the operand we need to rewrite here.
2523 bool IsTrueVal = SI.getTrueValue() == OldPtr;
2524 if (IsTrueVal)
2525 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
2526 else
2527 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
2528 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
2529
2530 // If the select isn't safe to speculate, just use simple logic to emit it.
2531 SmallVector<LoadInst *, 4> Loads;
2532 if (!isSafeSelectToSpeculate(SI, Loads)) {
2533 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
2534 DEBUG(dbgs() << " to: " << SI << "\n");
2535 deleteIfTriviallyDead(OldPtr);
2536 return false;
2537 }
2538
2539 Value *OtherPtr = IsTrueVal ? SI.getFalseValue() : SI.getTrueValue();
2540 AllocaPartitioning::iterator PI
2541 = P.findPartitionForPHIOrSelectOperand(SI, OtherPtr);
2542 AllocaPartitioning::PartitionUse OtherUse;
2543 if (PI != P.end()) {
2544 // If the other pointer is within the partitioning, remove the select
2545 // from its uses. We'll add in the new loads below.
2546 AllocaPartitioning::use_iterator UI
2547 = P.findPartitionUseForPHIOrSelectOperand(SI, OtherPtr);
2548 OtherUse = *UI;
2549 P.use_erase(PI, UI);
2550 }
2551
2552 Value *TV = IsTrueVal ? NewPtr : SI.getTrueValue();
2553 Value *FV = IsTrueVal ? SI.getFalseValue() : NewPtr;
2554 // Replace the loads of the select with a select of two loads.
2555 while (!Loads.empty()) {
2556 LoadInst *LI = Loads.pop_back_val();
2557
2558 IRB.SetInsertPoint(LI);
2559 LoadInst *TL =
2560 IRB.CreateLoad(TV, getName("." + LI->getName() + ".true"));
2561 LoadInst *FL =
2562 IRB.CreateLoad(FV, getName("." + LI->getName() + ".false"));
2563 NumLoadsSpeculated += 2;
2564 if (PI != P.end()) {
2565 LoadInst *OtherLoad = IsTrueVal ? FL : TL;
2566 assert(OtherUse.Ptr == OtherLoad->getOperand(0));
2567 OtherUse.User = OtherLoad;
Chandler Carruth72bf29f2012-09-25 02:42:03 +00002568 P.use_push_back(PI, OtherUse);
Chandler Carruth713aa942012-09-14 09:22:59 +00002569 }
2570
2571 // Transfer alignment and TBAA info if present.
2572 TL->setAlignment(LI->getAlignment());
2573 FL->setAlignment(LI->getAlignment());
2574 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
2575 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
2576 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
2577 }
2578
2579 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL);
2580 V->takeName(LI);
2581 DEBUG(dbgs() << " speculated to: " << *V << "\n");
2582 LI->replaceAllUsesWith(V);
2583 Pass.DeadInsts.push_back(LI);
2584 }
Chandler Carruth713aa942012-09-14 09:22:59 +00002585
2586 deleteIfTriviallyDead(OldPtr);
2587 return NewPtr == &NewAI;
2588 }
2589
2590};
2591}
2592
Chandler Carruthc370acd2012-09-18 12:57:43 +00002593namespace {
2594/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2595///
2596/// This pass aggressively rewrites all aggregate loads and stores on
2597/// a particular pointer (or any pointer derived from it which we can identify)
2598/// with scalar loads and stores.
2599class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2600 // Befriend the base class so it can delegate to private visit methods.
2601 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2602
2603 const TargetData &TD;
2604
2605 /// Queue of pointer uses to analyze and potentially rewrite.
2606 SmallVector<Use *, 8> Queue;
2607
2608 /// Set to prevent us from cycling with phi nodes and loops.
2609 SmallPtrSet<User *, 8> Visited;
2610
2611 /// The current pointer use being rewritten. This is used to dig up the used
2612 /// value (as opposed to the user).
2613 Use *U;
2614
2615public:
2616 AggLoadStoreRewriter(const TargetData &TD) : TD(TD) {}
2617
2618 /// Rewrite loads and stores through a pointer and all pointers derived from
2619 /// it.
2620 bool rewrite(Instruction &I) {
2621 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2622 enqueueUsers(I);
2623 bool Changed = false;
2624 while (!Queue.empty()) {
2625 U = Queue.pop_back_val();
2626 Changed |= visit(cast<Instruction>(U->getUser()));
2627 }
2628 return Changed;
2629 }
2630
2631private:
2632 /// Enqueue all the users of the given instruction for further processing.
2633 /// This uses a set to de-duplicate users.
2634 void enqueueUsers(Instruction &I) {
2635 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2636 ++UI)
2637 if (Visited.insert(*UI))
2638 Queue.push_back(&UI.getUse());
2639 }
2640
2641 // Conservative default is to not rewrite anything.
2642 bool visitInstruction(Instruction &I) { return false; }
2643
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002644 /// \brief Generic recursive split emission class.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002645 template <typename Derived>
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002646 class OpSplitter {
2647 protected:
2648 /// The builder used to form new instructions.
2649 IRBuilder<> IRB;
2650 /// The indices which to be used with insert- or extractvalue to select the
2651 /// appropriate value within the aggregate.
2652 SmallVector<unsigned, 4> Indices;
2653 /// The indices to a GEP instruction which will move Ptr to the correct slot
2654 /// within the aggregate.
2655 SmallVector<Value *, 4> GEPIndices;
2656 /// The base pointer of the original op, used as a base for GEPing the
2657 /// split operations.
2658 Value *Ptr;
Chandler Carruthc370acd2012-09-18 12:57:43 +00002659
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002660 /// Initialize the splitter with an insertion point, Ptr and start with a
2661 /// single zero GEP index.
2662 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002663 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002664
2665 public:
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002666 /// \brief Generic recursive split emission routine.
2667 ///
2668 /// This method recursively splits an aggregate op (load or store) into
2669 /// scalar or vector ops. It splits recursively until it hits a single value
2670 /// and emits that single value operation via the template argument.
2671 ///
2672 /// The logic of this routine relies on GEPs and insertvalue and
2673 /// extractvalue all operating with the same fundamental index list, merely
2674 /// formatted differently (GEPs need actual values).
2675 ///
2676 /// \param Ty The type being split recursively into smaller ops.
2677 /// \param Agg The aggregate value being built up or stored, depending on
2678 /// whether this is splitting a load or a store respectively.
2679 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2680 if (Ty->isSingleValueType())
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002681 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002682
2683 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2684 unsigned OldSize = Indices.size();
2685 (void)OldSize;
2686 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2687 ++Idx) {
2688 assert(Indices.size() == OldSize && "Did not return to the old size");
2689 Indices.push_back(Idx);
2690 GEPIndices.push_back(IRB.getInt32(Idx));
2691 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2692 GEPIndices.pop_back();
2693 Indices.pop_back();
2694 }
2695 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00002696 }
Chandler Carruthc370acd2012-09-18 12:57:43 +00002697
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002698 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2699 unsigned OldSize = Indices.size();
2700 (void)OldSize;
2701 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2702 ++Idx) {
2703 assert(Indices.size() == OldSize && "Did not return to the old size");
2704 Indices.push_back(Idx);
2705 GEPIndices.push_back(IRB.getInt32(Idx));
2706 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2707 GEPIndices.pop_back();
2708 Indices.pop_back();
2709 }
2710 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00002711 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002712
2713 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruthc370acd2012-09-18 12:57:43 +00002714 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002715 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00002716
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002717 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002718 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00002719 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruthc370acd2012-09-18 12:57:43 +00002720
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002721 /// Emit a leaf load of a single value. This is called at the leaves of the
2722 /// recursive emission to actually load values.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002723 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002724 assert(Ty->isSingleValueType());
2725 // Load the single value and insert it using the indices.
2726 Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices,
2727 Name + ".gep"),
2728 Name + ".load");
2729 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2730 DEBUG(dbgs() << " to: " << *Load << "\n");
2731 }
2732 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00002733
2734 bool visitLoadInst(LoadInst &LI) {
2735 assert(LI.getPointerOperand() == *U);
2736 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2737 return false;
2738
2739 // We have an aggregate being loaded, split it apart.
2740 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002741 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruthc370acd2012-09-18 12:57:43 +00002742 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002743 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00002744 LI.replaceAllUsesWith(V);
2745 LI.eraseFromParent();
2746 return true;
2747 }
2748
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002749 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002750 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00002751 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002752
2753 /// Emit a leaf store of a single value. This is called at the leaves of the
2754 /// recursive emission to actually produce stores.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002755 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002756 assert(Ty->isSingleValueType());
2757 // Extract the single value and store it using the indices.
2758 Value *Store = IRB.CreateStore(
2759 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2760 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2761 (void)Store;
2762 DEBUG(dbgs() << " to: " << *Store << "\n");
2763 }
2764 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00002765
2766 bool visitStoreInst(StoreInst &SI) {
2767 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2768 return false;
2769 Value *V = SI.getValueOperand();
2770 if (V->getType()->isSingleValueType())
2771 return false;
2772
2773 // We have an aggregate being stored, split it apart.
2774 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002775 StoreOpSplitter Splitter(&SI, *U);
2776 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00002777 SI.eraseFromParent();
2778 return true;
2779 }
2780
2781 bool visitBitCastInst(BitCastInst &BC) {
2782 enqueueUsers(BC);
2783 return false;
2784 }
2785
2786 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2787 enqueueUsers(GEPI);
2788 return false;
2789 }
2790
2791 bool visitPHINode(PHINode &PN) {
2792 enqueueUsers(PN);
2793 return false;
2794 }
2795
2796 bool visitSelectInst(SelectInst &SI) {
2797 enqueueUsers(SI);
2798 return false;
2799 }
2800};
2801}
2802
Chandler Carruth713aa942012-09-14 09:22:59 +00002803/// \brief Try to find a partition of the aggregate type passed in for a given
2804/// offset and size.
2805///
2806/// This recurses through the aggregate type and tries to compute a subtype
2807/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth6b547a22012-09-14 11:08:31 +00002808/// of an array, it will even compute a new array type for that sub-section,
2809/// and the same for structs.
2810///
2811/// Note that this routine is very strict and tries to find a partition of the
2812/// type which produces the *exact* right offset and size. It is not forgiving
2813/// when the size or offset cause either end of type-based partition to be off.
2814/// Also, this is a best-effort routine. It is reasonable to give up and not
2815/// return a type if necessary.
Chandler Carruth713aa942012-09-14 09:22:59 +00002816static Type *getTypePartition(const TargetData &TD, Type *Ty,
2817 uint64_t Offset, uint64_t Size) {
2818 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
2819 return Ty;
2820
2821 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2822 // We can't partition pointers...
2823 if (SeqTy->isPointerTy())
2824 return 0;
2825
2826 Type *ElementTy = SeqTy->getElementType();
2827 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2828 uint64_t NumSkippedElements = Offset / ElementSize;
2829 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
2830 if (NumSkippedElements >= ArrTy->getNumElements())
2831 return 0;
2832 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
2833 if (NumSkippedElements >= VecTy->getNumElements())
2834 return 0;
2835 Offset -= NumSkippedElements * ElementSize;
2836
2837 // First check if we need to recurse.
2838 if (Offset > 0 || Size < ElementSize) {
2839 // Bail if the partition ends in a different array element.
2840 if ((Offset + Size) > ElementSize)
2841 return 0;
2842 // Recurse through the element type trying to peel off offset bytes.
2843 return getTypePartition(TD, ElementTy, Offset, Size);
2844 }
2845 assert(Offset == 0);
2846
2847 if (Size == ElementSize)
2848 return ElementTy;
2849 assert(Size > ElementSize);
2850 uint64_t NumElements = Size / ElementSize;
2851 if (NumElements * ElementSize != Size)
2852 return 0;
2853 return ArrayType::get(ElementTy, NumElements);
2854 }
2855
2856 StructType *STy = dyn_cast<StructType>(Ty);
2857 if (!STy)
2858 return 0;
2859
2860 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00002861 if (Offset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00002862 return 0;
2863 uint64_t EndOffset = Offset + Size;
2864 if (EndOffset > SL->getSizeInBytes())
2865 return 0;
2866
2867 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002868 Offset -= SL->getElementOffset(Index);
2869
2870 Type *ElementTy = STy->getElementType(Index);
2871 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2872 if (Offset >= ElementSize)
2873 return 0; // The offset points into alignment padding.
2874
2875 // See if any partition must be contained by the element.
2876 if (Offset > 0 || Size < ElementSize) {
2877 if ((Offset + Size) > ElementSize)
2878 return 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00002879 return getTypePartition(TD, ElementTy, Offset, Size);
2880 }
2881 assert(Offset == 0);
2882
2883 if (Size == ElementSize)
2884 return ElementTy;
2885
2886 StructType::element_iterator EI = STy->element_begin() + Index,
2887 EE = STy->element_end();
2888 if (EndOffset < SL->getSizeInBytes()) {
2889 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
2890 if (Index == EndIndex)
2891 return 0; // Within a single element and its padding.
Chandler Carruth6b547a22012-09-14 11:08:31 +00002892
2893 // Don't try to form "natural" types if the elements don't line up with the
2894 // expected size.
2895 // FIXME: We could potentially recurse down through the last element in the
2896 // sub-struct to find a natural end point.
2897 if (SL->getElementOffset(EndIndex) != EndOffset)
2898 return 0;
2899
Chandler Carruth713aa942012-09-14 09:22:59 +00002900 assert(Index < EndIndex);
Chandler Carruth713aa942012-09-14 09:22:59 +00002901 EE = STy->element_begin() + EndIndex;
2902 }
2903
2904 // Try to build up a sub-structure.
2905 SmallVector<Type *, 4> ElementTys;
2906 do {
2907 ElementTys.push_back(*EI++);
2908 } while (EI != EE);
2909 StructType *SubTy = StructType::get(STy->getContext(), ElementTys,
2910 STy->isPacked());
2911 const StructLayout *SubSL = TD.getStructLayout(SubTy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00002912 if (Size != SubSL->getSizeInBytes())
2913 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth713aa942012-09-14 09:22:59 +00002914
Chandler Carruth6b547a22012-09-14 11:08:31 +00002915 return SubTy;
Chandler Carruth713aa942012-09-14 09:22:59 +00002916}
2917
2918/// \brief Rewrite an alloca partition's users.
2919///
2920/// This routine drives both of the rewriting goals of the SROA pass. It tries
2921/// to rewrite uses of an alloca partition to be conducive for SSA value
2922/// promotion. If the partition needs a new, more refined alloca, this will
2923/// build that new alloca, preserving as much type information as possible, and
2924/// rewrite the uses of the old alloca to point at the new one and have the
2925/// appropriate new offsets. It also evaluates how successful the rewrite was
2926/// at enabling promotion and if it was successful queues the alloca to be
2927/// promoted.
2928bool SROA::rewriteAllocaPartition(AllocaInst &AI,
2929 AllocaPartitioning &P,
2930 AllocaPartitioning::iterator PI) {
2931 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
2932 if (P.use_begin(PI) == P.use_end(PI))
2933 return false; // No live uses left of this partition.
2934
2935 // Try to compute a friendly type for this partition of the alloca. This
2936 // won't always succeed, in which case we fall back to a legal integer type
2937 // or an i8 array of an appropriate size.
2938 Type *AllocaTy = 0;
2939 if (Type *PartitionTy = P.getCommonType(PI))
2940 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
2941 AllocaTy = PartitionTy;
2942 if (!AllocaTy)
2943 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
2944 PI->BeginOffset, AllocaSize))
2945 AllocaTy = PartitionTy;
2946 if ((!AllocaTy ||
2947 (AllocaTy->isArrayTy() &&
2948 AllocaTy->getArrayElementType()->isIntegerTy())) &&
2949 TD->isLegalInteger(AllocaSize * 8))
2950 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
2951 if (!AllocaTy)
2952 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
Chandler Carruthb3dd9a12012-09-14 10:26:34 +00002953 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00002954
2955 // Check for the case where we're going to rewrite to a new alloca of the
2956 // exact same type as the original, and with the same access offsets. In that
2957 // case, re-use the existing alloca, but still run through the rewriter to
2958 // performe phi and select speculation.
2959 AllocaInst *NewAI;
2960 if (AllocaTy == AI.getAllocatedType()) {
2961 assert(PI->BeginOffset == 0 &&
2962 "Non-zero begin offset but same alloca type");
2963 assert(PI == P.begin() && "Begin offset is zero on later partition");
2964 NewAI = &AI;
2965 } else {
2966 // FIXME: The alignment here is overly conservative -- we could in many
2967 // cases get away with much weaker alignment constraints.
2968 NewAI = new AllocaInst(AllocaTy, 0, AI.getAlignment(),
2969 AI.getName() + ".sroa." + Twine(PI - P.begin()),
2970 &AI);
2971 ++NumNewAllocas;
2972 }
2973
2974 DEBUG(dbgs() << "Rewriting alloca partition "
2975 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
2976 << *NewAI << "\n");
2977
2978 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
2979 PI->BeginOffset, PI->EndOffset);
2980 DEBUG(dbgs() << " rewriting ");
2981 DEBUG(P.print(dbgs(), PI, ""));
2982 if (Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI))) {
2983 DEBUG(dbgs() << " and queuing for promotion\n");
2984 PromotableAllocas.push_back(NewAI);
2985 } else if (NewAI != &AI) {
2986 // If we can't promote the alloca, iterate on it to check for new
2987 // refinements exposed by splitting the current alloca. Don't iterate on an
2988 // alloca which didn't actually change and didn't get promoted.
2989 Worklist.insert(NewAI);
2990 }
2991 return true;
2992}
2993
2994/// \brief Walks the partitioning of an alloca rewriting uses of each partition.
2995bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
2996 bool Changed = false;
2997 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
2998 ++PI)
2999 Changed |= rewriteAllocaPartition(AI, P, PI);
3000
3001 return Changed;
3002}
3003
3004/// \brief Analyze an alloca for SROA.
3005///
3006/// This analyzes the alloca to ensure we can reason about it, builds
3007/// a partitioning of the alloca, and then hands it off to be split and
3008/// rewritten as needed.
3009bool SROA::runOnAlloca(AllocaInst &AI) {
3010 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3011 ++NumAllocasAnalyzed;
3012
3013 // Special case dead allocas, as they're trivial.
3014 if (AI.use_empty()) {
3015 AI.eraseFromParent();
3016 return true;
3017 }
3018
3019 // Skip alloca forms that this analysis can't handle.
3020 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3021 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3022 return false;
3023
3024 // First check if this is a non-aggregate type that we should simply promote.
3025 if (!AI.getAllocatedType()->isAggregateType() && isAllocaPromotable(&AI)) {
3026 DEBUG(dbgs() << " Trivially scalar type, queuing for promotion...\n");
3027 PromotableAllocas.push_back(&AI);
3028 return false;
3029 }
3030
Chandler Carruthc370acd2012-09-18 12:57:43 +00003031 bool Changed = false;
3032
3033 // First, split any FCA loads and stores touching this alloca to promote
3034 // better splitting and promotion opportunities.
3035 AggLoadStoreRewriter AggRewriter(*TD);
3036 Changed |= AggRewriter.rewrite(AI);
3037
Chandler Carruth713aa942012-09-14 09:22:59 +00003038 // Build the partition set using a recursive instruction-visiting builder.
3039 AllocaPartitioning P(*TD, AI);
3040 DEBUG(P.print(dbgs()));
3041 if (P.isEscaped())
Chandler Carruthc370acd2012-09-18 12:57:43 +00003042 return Changed;
Chandler Carruth713aa942012-09-14 09:22:59 +00003043
3044 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3045 if (P.begin() == P.end())
Chandler Carruthc370acd2012-09-18 12:57:43 +00003046 return Changed;
Chandler Carruth713aa942012-09-14 09:22:59 +00003047
3048 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth713aa942012-09-14 09:22:59 +00003049 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3050 DE = P.dead_user_end();
3051 DI != DE; ++DI) {
3052 Changed = true;
3053 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3054 DeadInsts.push_back(*DI);
3055 }
3056 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3057 DE = P.dead_op_end();
3058 DO != DE; ++DO) {
3059 Value *OldV = **DO;
3060 // Clobber the use with an undef value.
3061 **DO = UndefValue::get(OldV->getType());
3062 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3063 if (isInstructionTriviallyDead(OldI)) {
3064 Changed = true;
3065 DeadInsts.push_back(OldI);
3066 }
3067 }
3068
3069 return splitAlloca(AI, P) || Changed;
3070}
3071
Chandler Carruth8615cd22012-09-14 10:26:38 +00003072/// \brief Delete the dead instructions accumulated in this run.
3073///
3074/// Recursively deletes the dead instructions we've accumulated. This is done
3075/// at the very end to maximize locality of the recursive delete and to
3076/// minimize the problems of invalidated instruction pointers as such pointers
3077/// are used heavily in the intermediate stages of the algorithm.
3078///
3079/// We also record the alloca instructions deleted here so that they aren't
3080/// subsequently handed to mem2reg to promote.
3081void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth713aa942012-09-14 09:22:59 +00003082 DeadSplitInsts.clear();
3083 while (!DeadInsts.empty()) {
3084 Instruction *I = DeadInsts.pop_back_val();
3085 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3086
3087 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3088 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3089 // Zero out the operand and see if it becomes trivially dead.
3090 *OI = 0;
3091 if (isInstructionTriviallyDead(U))
3092 DeadInsts.push_back(U);
3093 }
3094
3095 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3096 DeletedAllocas.insert(AI);
3097
3098 ++NumDeleted;
3099 I->eraseFromParent();
3100 }
3101}
3102
Chandler Carruth1c8db502012-09-15 11:43:14 +00003103/// \brief Promote the allocas, using the best available technique.
3104///
3105/// This attempts to promote whatever allocas have been identified as viable in
3106/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3107/// If there is a domtree available, we attempt to promote using the full power
3108/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3109/// based on the SSAUpdater utilities. This function returns whether any
3110/// promotion occured.
3111bool SROA::promoteAllocas(Function &F) {
3112 if (PromotableAllocas.empty())
3113 return false;
3114
3115 NumPromoted += PromotableAllocas.size();
3116
3117 if (DT && !ForceSSAUpdater) {
3118 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3119 PromoteMemToReg(PromotableAllocas, *DT);
3120 PromotableAllocas.clear();
3121 return true;
3122 }
3123
3124 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3125 SSAUpdater SSA;
3126 DIBuilder DIB(*F.getParent());
3127 SmallVector<Instruction*, 64> Insts;
3128
3129 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3130 AllocaInst *AI = PromotableAllocas[Idx];
3131 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3132 UI != UE;) {
3133 Instruction *I = cast<Instruction>(*UI++);
3134 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3135 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3136 // leading to them) here. Eventually it should use them to optimize the
3137 // scalar values produced.
3138 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3139 assert(onlyUsedByLifetimeMarkers(I) &&
3140 "Found a bitcast used outside of a lifetime marker.");
3141 while (!I->use_empty())
3142 cast<Instruction>(*I->use_begin())->eraseFromParent();
3143 I->eraseFromParent();
3144 continue;
3145 }
3146 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3147 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3148 II->getIntrinsicID() == Intrinsic::lifetime_end);
3149 II->eraseFromParent();
3150 continue;
3151 }
3152
3153 Insts.push_back(I);
3154 }
3155 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3156 Insts.clear();
3157 }
3158
3159 PromotableAllocas.clear();
3160 return true;
3161}
3162
Chandler Carruth713aa942012-09-14 09:22:59 +00003163namespace {
3164 /// \brief A predicate to test whether an alloca belongs to a set.
3165 class IsAllocaInSet {
3166 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3167 const SetType &Set;
3168
3169 public:
3170 IsAllocaInSet(const SetType &Set) : Set(Set) {}
3171 bool operator()(AllocaInst *AI) { return Set.count(AI); }
3172 };
3173}
3174
3175bool SROA::runOnFunction(Function &F) {
3176 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3177 C = &F.getContext();
3178 TD = getAnalysisIfAvailable<TargetData>();
3179 if (!TD) {
3180 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3181 return false;
3182 }
Chandler Carruth1c8db502012-09-15 11:43:14 +00003183 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003184
3185 BasicBlock &EntryBB = F.getEntryBlock();
3186 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3187 I != E; ++I)
3188 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3189 Worklist.insert(AI);
3190
3191 bool Changed = false;
Chandler Carruth8615cd22012-09-14 10:26:38 +00003192 // A set of deleted alloca instruction pointers which should be removed from
3193 // the list of promotable allocas.
3194 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3195
Chandler Carruth713aa942012-09-14 09:22:59 +00003196 while (!Worklist.empty()) {
3197 Changed |= runOnAlloca(*Worklist.pop_back_val());
Chandler Carruth8615cd22012-09-14 10:26:38 +00003198 deleteDeadInstructions(DeletedAllocas);
Chandler Carruth713aa942012-09-14 09:22:59 +00003199 if (!DeletedAllocas.empty()) {
3200 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3201 PromotableAllocas.end(),
3202 IsAllocaInSet(DeletedAllocas)),
3203 PromotableAllocas.end());
3204 DeletedAllocas.clear();
3205 }
3206 }
3207
Chandler Carruth1c8db502012-09-15 11:43:14 +00003208 Changed |= promoteAllocas(F);
Chandler Carruth713aa942012-09-14 09:22:59 +00003209
3210 return Changed;
3211}
3212
3213void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth1c8db502012-09-15 11:43:14 +00003214 if (RequiresDomTree)
3215 AU.addRequired<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003216 AU.setPreservesCFG();
3217}