blob: c3f95ad01d6ef609df29f762b19ab30d84c7e0cf [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 {
Chandler Carruth77c12702012-10-01 01:49:22 +0000158 /// \brief The use in question. Provides access to both user and used value.
159 Use* U;
Chandler Carruth713aa942012-09-14 09:22:59 +0000160
Chandler Carruth77c12702012-10-01 01:49:22 +0000161 PartitionUse() : ByteRange(), U() {}
162 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset, Use *U)
163 : ByteRange(BeginOffset, EndOffset), U(U) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000164 };
165
166 /// \brief Construct a partitioning of a particular alloca.
167 ///
168 /// Construction does most of the work for partitioning the alloca. This
169 /// performs the necessary walks of users and builds a partitioning from it.
170 AllocaPartitioning(const TargetData &TD, AllocaInst &AI);
171
172 /// \brief Test whether a pointer to the allocation escapes our analysis.
173 ///
174 /// If this is true, the partitioning is never fully built and should be
175 /// ignored.
176 bool isEscaped() const { return PointerEscapingInstr; }
177
178 /// \brief Support for iterating over the partitions.
179 /// @{
180 typedef SmallVectorImpl<Partition>::iterator iterator;
181 iterator begin() { return Partitions.begin(); }
182 iterator end() { return Partitions.end(); }
183
184 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
185 const_iterator begin() const { return Partitions.begin(); }
186 const_iterator end() const { return Partitions.end(); }
187 /// @}
188
189 /// \brief Support for iterating over and manipulating a particular
190 /// partition's uses.
191 ///
192 /// The iteration support provided for uses is more limited, but also
193 /// includes some manipulation routines to support rewriting the uses of
194 /// partitions during SROA.
195 /// @{
196 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
197 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
198 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
199 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
200 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
Chandler Carruth77c12702012-10-01 01:49:22 +0000201 void use_push_back(unsigned Idx, const PartitionUse &PU) {
202 Uses[Idx].push_back(PU);
Chandler Carruth713aa942012-09-14 09:22:59 +0000203 }
Chandler Carruth77c12702012-10-01 01:49:22 +0000204 void use_push_back(const_iterator I, const PartitionUse &PU) {
205 Uses[I - begin()].push_back(PU);
Chandler Carruth713aa942012-09-14 09:22:59 +0000206 }
207 void use_erase(unsigned Idx, use_iterator UI) { Uses[Idx].erase(UI); }
208 void use_erase(const_iterator I, use_iterator UI) {
209 Uses[I - begin()].erase(UI);
210 }
211
212 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
213 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
214 const_use_iterator use_begin(const_iterator I) const {
215 return Uses[I - begin()].begin();
216 }
217 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
218 const_use_iterator use_end(const_iterator I) const {
219 return Uses[I - begin()].end();
220 }
221 /// @}
222
223 /// \brief Allow iterating the dead users for this alloca.
224 ///
225 /// These are instructions which will never actually use the alloca as they
226 /// are outside the allocated range. They are safe to replace with undef and
227 /// delete.
228 /// @{
229 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
230 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
231 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
232 /// @}
233
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000234 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth713aa942012-09-14 09:22:59 +0000235 ///
236 /// These are operands which have cannot actually be used to refer to the
237 /// alloca as they are outside its range and the user doesn't correct for
238 /// that. These mostly consist of PHI node inputs and the like which we just
239 /// need to replace with undef.
240 /// @{
241 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
242 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
243 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
244 /// @}
245
246 /// \brief MemTransferInst auxiliary data.
247 /// This struct provides some auxiliary data about memory transfer
248 /// intrinsics such as memcpy and memmove. These intrinsics can use two
249 /// different ranges within the same alloca, and provide other challenges to
250 /// correctly represent. We stash extra data to help us untangle this
251 /// after the partitioning is complete.
252 struct MemTransferOffsets {
253 uint64_t DestBegin, DestEnd;
254 uint64_t SourceBegin, SourceEnd;
255 bool IsSplittable;
256 };
257 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
258 return MemTransferInstData.lookup(&II);
259 }
260
261 /// \brief Map from a PHI or select operand back to a partition.
262 ///
263 /// When manipulating PHI nodes or selects, they can use more than one
264 /// partition of an alloca. We store a special mapping to allow finding the
265 /// partition referenced by each of these operands, if any.
Chandler Carruth77c12702012-10-01 01:49:22 +0000266 iterator findPartitionForPHIOrSelectOperand(Use *U) {
267 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
268 = PHIOrSelectOpMap.find(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000269 if (MapIt == PHIOrSelectOpMap.end())
270 return end();
271
272 return begin() + MapIt->second.first;
273 }
274
275 /// \brief Map from a PHI or select operand back to the specific use of
276 /// a partition.
277 ///
278 /// Similar to mapping these operands back to the partitions, this maps
279 /// directly to the use structure of that partition.
Chandler Carruth77c12702012-10-01 01:49:22 +0000280 use_iterator findPartitionUseForPHIOrSelectOperand(Use *U) {
281 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
282 = PHIOrSelectOpMap.find(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000283 assert(MapIt != PHIOrSelectOpMap.end());
284 return Uses[MapIt->second.first].begin() + MapIt->second.second;
285 }
286
287 /// \brief Compute a common type among the uses of a particular partition.
288 ///
289 /// This routines walks all of the uses of a particular partition and tries
290 /// to find a common type between them. Untyped operations such as memset and
291 /// memcpy are ignored.
292 Type *getCommonType(iterator I) const;
293
Chandler Carruthba13d2e2012-09-14 10:18:51 +0000294#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth713aa942012-09-14 09:22:59 +0000295 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
296 void printUsers(raw_ostream &OS, const_iterator I,
297 StringRef Indent = " ") const;
298 void print(raw_ostream &OS) const;
NAKAMURA Takumiad9f5b82012-09-14 10:06:10 +0000299 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
300 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
Chandler Carruthba13d2e2012-09-14 10:18:51 +0000301#endif
Chandler Carruth713aa942012-09-14 09:22:59 +0000302
303private:
304 template <typename DerivedT, typename RetT = void> class BuilderBase;
305 class PartitionBuilder;
306 friend class AllocaPartitioning::PartitionBuilder;
307 class UseBuilder;
308 friend class AllocaPartitioning::UseBuilder;
309
Benjamin Kramerd0807692012-09-14 13:08:09 +0000310#ifndef NDEBUG
Chandler Carruth713aa942012-09-14 09:22:59 +0000311 /// \brief Handle to alloca instruction to simplify method interfaces.
312 AllocaInst &AI;
Benjamin Kramerd0807692012-09-14 13:08:09 +0000313#endif
Chandler Carruth713aa942012-09-14 09:22:59 +0000314
315 /// \brief The instruction responsible for this alloca having no partitioning.
316 ///
317 /// When an instruction (potentially) escapes the pointer to the alloca, we
318 /// store a pointer to that here and abort trying to partition the alloca.
319 /// This will be null if the alloca is partitioned successfully.
320 Instruction *PointerEscapingInstr;
321
322 /// \brief The partitions of the alloca.
323 ///
324 /// We store a vector of the partitions over the alloca here. This vector is
325 /// sorted by increasing begin offset, and then by decreasing end offset. See
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000326 /// the Partition inner class for more details. Initially (during
327 /// construction) there are overlaps, but we form a disjoint sequence of
328 /// partitions while finishing construction and a fully constructed object is
329 /// expected to always have this as a disjoint space.
Chandler Carruth713aa942012-09-14 09:22:59 +0000330 SmallVector<Partition, 8> Partitions;
331
332 /// \brief The uses of the partitions.
333 ///
334 /// This is essentially a mapping from each partition to a list of uses of
335 /// that partition. The mapping is done with a Uses vector that has the exact
336 /// same number of entries as the partition vector. Each entry is itself
337 /// a vector of the uses.
338 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
339
340 /// \brief Instructions which will become dead if we rewrite the alloca.
341 ///
342 /// Note that these are not separated by partition. This is because we expect
343 /// a partitioned alloca to be completely rewritten or not rewritten at all.
344 /// If rewritten, all these instructions can simply be removed and replaced
345 /// with undef as they come from outside of the allocated space.
346 SmallVector<Instruction *, 8> DeadUsers;
347
348 /// \brief Operands which will become dead if we rewrite the alloca.
349 ///
350 /// These are operands that in their particular use can be replaced with
351 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
352 /// to PHI nodes and the like. They aren't entirely dead (there might be
353 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
354 /// want to swap this particular input for undef to simplify the use lists of
355 /// the alloca.
356 SmallVector<Use *, 8> DeadOperands;
357
358 /// \brief The underlying storage for auxiliary memcpy and memset info.
359 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
360
361 /// \brief A side datastructure used when building up the partitions and uses.
362 ///
363 /// This mapping is only really used during the initial building of the
364 /// partitioning so that we can retain information about PHI and select nodes
365 /// processed.
366 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
367
368 /// \brief Auxiliary information for particular PHI or select operands.
Chandler Carruth77c12702012-10-01 01:49:22 +0000369 SmallDenseMap<Use *, std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
Chandler Carruth713aa942012-09-14 09:22:59 +0000370
371 /// \brief A utility routine called from the constructor.
372 ///
373 /// This does what it says on the tin. It is the key of the alloca partition
374 /// splitting and merging. After it is called we have the desired disjoint
375 /// collection of partitions.
376 void splitAndMergePartitions();
377};
378}
379
380template <typename DerivedT, typename RetT>
381class AllocaPartitioning::BuilderBase
382 : public InstVisitor<DerivedT, RetT> {
383public:
384 BuilderBase(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
385 : TD(TD),
386 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
387 P(P) {
388 enqueueUsers(AI, 0);
389 }
390
391protected:
392 const TargetData &TD;
393 const uint64_t AllocSize;
394 AllocaPartitioning &P;
395
Chandler Carruth77c12702012-10-01 01:49:22 +0000396 SmallPtrSet<Use *, 8> VisitedUses;
397
Chandler Carruth713aa942012-09-14 09:22:59 +0000398 struct OffsetUse {
399 Use *U;
Chandler Carruth02e92a02012-09-23 11:43:14 +0000400 int64_t Offset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000401 };
402 SmallVector<OffsetUse, 8> Queue;
403
404 // The active offset and use while visiting.
405 Use *U;
Chandler Carruth02e92a02012-09-23 11:43:14 +0000406 int64_t Offset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000407
Chandler Carruth02e92a02012-09-23 11:43:14 +0000408 void enqueueUsers(Instruction &I, int64_t UserOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000409 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
410 UI != UE; ++UI) {
Chandler Carruth77c12702012-10-01 01:49:22 +0000411 if (VisitedUses.insert(&UI.getUse())) {
412 OffsetUse OU = { &UI.getUse(), UserOffset };
413 Queue.push_back(OU);
414 }
Chandler Carruth713aa942012-09-14 09:22:59 +0000415 }
416 }
417
Chandler Carruth02e92a02012-09-23 11:43:14 +0000418 bool computeConstantGEPOffset(GetElementPtrInst &GEPI, int64_t &GEPOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000419 GEPOffset = Offset;
420 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
421 GTI != GTE; ++GTI) {
422 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
423 if (!OpC)
424 return false;
425 if (OpC->isZero())
426 continue;
427
428 // Handle a struct index, which adds its field offset to the pointer.
429 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
430 unsigned ElementIdx = OpC->getZExtValue();
431 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth02e92a02012-09-23 11:43:14 +0000432 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
433 // Check that we can continue to model this GEP in a signed 64-bit offset.
434 if (ElementOffset > INT64_MAX ||
435 (GEPOffset >= 0 &&
436 ((uint64_t)GEPOffset + ElementOffset) > INT64_MAX)) {
437 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
438 << "what can be represented in an int64_t!\n"
439 << " alloca: " << P.AI << "\n");
440 return false;
441 }
442 if (GEPOffset < 0)
443 GEPOffset = ElementOffset + (uint64_t)-GEPOffset;
444 else
445 GEPOffset += ElementOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000446 continue;
447 }
448
Chandler Carruth02e92a02012-09-23 11:43:14 +0000449 APInt Index = OpC->getValue().sextOrTrunc(TD.getPointerSizeInBits());
450 Index *= APInt(Index.getBitWidth(),
451 TD.getTypeAllocSize(GTI.getIndexedType()));
452 Index += APInt(Index.getBitWidth(), (uint64_t)GEPOffset,
453 /*isSigned*/true);
454 // Check if the result can be stored in our int64_t offset.
455 if (!Index.isSignedIntN(sizeof(GEPOffset) * 8)) {
456 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
457 << "what can be represented in an int64_t!\n"
458 << " alloca: " << P.AI << "\n");
459 return false;
460 }
461
462 GEPOffset = Index.getSExtValue();
Chandler Carruth713aa942012-09-14 09:22:59 +0000463 }
464 return true;
465 }
466
467 Value *foldSelectInst(SelectInst &SI) {
468 // If the condition being selected on is a constant or the same value is
469 // being selected between, fold the select. Yes this does (rarely) happen
470 // early on.
471 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
472 return SI.getOperand(1+CI->isZero());
473 if (SI.getOperand(1) == SI.getOperand(2)) {
474 assert(*U == SI.getOperand(1));
475 return SI.getOperand(1);
476 }
477 return 0;
478 }
479};
480
481/// \brief Builder for the alloca partitioning.
482///
483/// This class builds an alloca partitioning by recursively visiting the uses
484/// of an alloca and splitting the partitions for each load and store at each
485/// offset.
486class AllocaPartitioning::PartitionBuilder
487 : public BuilderBase<PartitionBuilder, bool> {
488 friend class InstVisitor<PartitionBuilder, bool>;
489
490 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
491
492public:
493 PartitionBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000494 : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000495
496 /// \brief Run the builder over the allocation.
497 bool operator()() {
498 // Note that we have to re-evaluate size on each trip through the loop as
499 // the queue grows at the tail.
500 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
501 U = Queue[Idx].U;
502 Offset = Queue[Idx].Offset;
503 if (!visit(cast<Instruction>(U->getUser())))
504 return false;
505 }
506 return true;
507 }
508
509private:
510 bool markAsEscaping(Instruction &I) {
511 P.PointerEscapingInstr = &I;
512 return false;
513 }
514
Chandler Carruth02e92a02012-09-23 11:43:14 +0000515 void insertUse(Instruction &I, int64_t Offset, uint64_t Size,
Chandler Carruth63392ea2012-09-16 19:39:50 +0000516 bool IsSplittable = false) {
Chandler Carruthc3034632012-09-25 10:03:40 +0000517 // Completely skip uses which have a zero size or don't overlap the
518 // allocation.
519 if (Size == 0 ||
520 (Offset >= 0 && (uint64_t)Offset >= AllocSize) ||
Chandler Carruth02e92a02012-09-23 11:43:14 +0000521 (Offset < 0 && (uint64_t)-Offset >= Size)) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000522 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
523 << " which starts past the end of the " << AllocSize
524 << " byte alloca:\n"
525 << " alloca: " << P.AI << "\n"
526 << " use: " << I << "\n");
527 return;
528 }
529
Chandler Carruth02e92a02012-09-23 11:43:14 +0000530 // Clamp the start to the beginning of the allocation.
531 if (Offset < 0) {
532 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
533 << " to start at the beginning of the alloca:\n"
534 << " alloca: " << P.AI << "\n"
535 << " use: " << I << "\n");
536 Size -= (uint64_t)-Offset;
537 Offset = 0;
538 }
539
540 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
541
542 // Clamp the end offset to the end of the allocation. Note that this is
543 // formulated to handle even the case where "BeginOffset + Size" overflows.
544 assert(AllocSize >= BeginOffset); // Established above.
545 if (Size > AllocSize - BeginOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000546 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
547 << " to remain within the " << AllocSize << " byte alloca:\n"
548 << " alloca: " << P.AI << "\n"
549 << " use: " << I << "\n");
550 EndOffset = AllocSize;
551 }
552
553 // See if we can just add a user onto the last slot currently occupied.
554 if (!P.Partitions.empty() &&
555 P.Partitions.back().BeginOffset == BeginOffset &&
556 P.Partitions.back().EndOffset == EndOffset) {
557 P.Partitions.back().IsSplittable &= IsSplittable;
558 return;
559 }
560
561 Partition New(BeginOffset, EndOffset, IsSplittable);
562 P.Partitions.push_back(New);
563 }
564
Chandler Carruth02e92a02012-09-23 11:43:14 +0000565 bool handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000566 uint64_t Size = TD.getTypeStoreSize(Ty);
567
568 // If this memory access can be shown to *statically* extend outside the
569 // bounds of of the allocation, it's behavior is undefined, so simply
570 // ignore it. Note that this is more strict than the generic clamping
571 // behavior of insertUse. We also try to handle cases which might run the
572 // risk of overflow.
573 // FIXME: We should instead consider the pointer to have escaped if this
574 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000575 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
576 Size > (AllocSize - (uint64_t)Offset)) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000577 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
578 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
579 << " which extends past the end of the " << AllocSize
580 << " byte alloca:\n"
581 << " alloca: " << P.AI << "\n"
582 << " use: " << I << "\n");
583 return true;
584 }
585
Chandler Carruth63392ea2012-09-16 19:39:50 +0000586 insertUse(I, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000587 return true;
588 }
589
590 bool visitBitCastInst(BitCastInst &BC) {
591 enqueueUsers(BC, Offset);
592 return true;
593 }
594
595 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
Chandler Carruth02e92a02012-09-23 11:43:14 +0000596 int64_t GEPOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000597 if (!computeConstantGEPOffset(GEPI, GEPOffset))
598 return markAsEscaping(GEPI);
599
600 enqueueUsers(GEPI, GEPOffset);
601 return true;
602 }
603
604 bool visitLoadInst(LoadInst &LI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000605 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
606 "All simple FCA loads should have been pre-split");
Chandler Carruth63392ea2012-09-16 19:39:50 +0000607 return handleLoadOrStore(LI.getType(), LI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000608 }
609
610 bool visitStoreInst(StoreInst &SI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000611 Value *ValOp = SI.getValueOperand();
612 if (ValOp == *U)
Chandler Carruth713aa942012-09-14 09:22:59 +0000613 return markAsEscaping(SI);
614
Chandler Carruthc370acd2012-09-18 12:57:43 +0000615 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
616 "All simple FCA stores should have been pre-split");
617 return handleLoadOrStore(ValOp->getType(), SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000618 }
619
620
621 bool visitMemSetInst(MemSetInst &II) {
Chandler Carruthb3dd9a12012-09-14 10:26:34 +0000622 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth713aa942012-09-14 09:22:59 +0000623 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000624 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
625 insertUse(II, Offset, Size, Length);
Chandler Carruth713aa942012-09-14 09:22:59 +0000626 return true;
627 }
628
629 bool visitMemTransferInst(MemTransferInst &II) {
630 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
631 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
632 if (!Size)
633 // Zero-length mem transfer intrinsics can be ignored entirely.
634 return true;
635
636 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
637
638 // Only intrinsics with a constant length can be split.
639 Offsets.IsSplittable = Length;
640
641 if (*U != II.getRawDest()) {
642 assert(*U == II.getRawSource());
643 Offsets.SourceBegin = Offset;
644 Offsets.SourceEnd = Offset + Size;
645 } else {
646 Offsets.DestBegin = Offset;
647 Offsets.DestEnd = Offset + Size;
648 }
649
Chandler Carruth63392ea2012-09-16 19:39:50 +0000650 insertUse(II, Offset, Size, Offsets.IsSplittable);
Chandler Carruth713aa942012-09-14 09:22:59 +0000651 unsigned NewIdx = P.Partitions.size() - 1;
652
653 SmallDenseMap<Instruction *, unsigned>::const_iterator PMI;
654 bool Inserted = false;
655 llvm::tie(PMI, Inserted)
656 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx));
Chandler Carruthb3dca3f2012-09-26 07:41:40 +0000657 if (Offsets.IsSplittable &&
658 (!Inserted || II.getRawSource() == II.getRawDest())) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000659 // We've found a memory transfer intrinsic which refers to the alloca as
Chandler Carruthb3dca3f2012-09-26 07:41:40 +0000660 // both a source and dest. This is detected either by direct equality of
661 // the operand values, or when we visit the intrinsic twice due to two
662 // different chains of values leading to it. We refuse to split these to
663 // simplify splitting logic. If possible, SROA will still split them into
664 // separate allocas and then re-analyze.
Chandler Carruth713aa942012-09-14 09:22:59 +0000665 Offsets.IsSplittable = false;
666 P.Partitions[PMI->second].IsSplittable = false;
667 P.Partitions[NewIdx].IsSplittable = false;
668 }
669
670 return true;
671 }
672
673 // Disable SRoA for any intrinsics except for lifetime invariants.
Chandler Carruth50754f02012-09-14 10:26:36 +0000674 // FIXME: What about debug instrinsics? This matches old behavior, but
675 // doesn't make sense.
Chandler Carruth713aa942012-09-14 09:22:59 +0000676 bool visitIntrinsicInst(IntrinsicInst &II) {
677 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
678 II.getIntrinsicID() == Intrinsic::lifetime_end) {
679 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
680 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000681 insertUse(II, Offset, Size, true);
Chandler Carruth713aa942012-09-14 09:22:59 +0000682 return true;
683 }
684
685 return markAsEscaping(II);
686 }
687
688 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
689 // We consider any PHI or select that results in a direct load or store of
690 // the same offset to be a viable use for partitioning purposes. These uses
691 // are considered unsplittable and the size is the maximum loaded or stored
692 // size.
693 SmallPtrSet<Instruction *, 4> Visited;
694 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
695 Visited.insert(Root);
696 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruthc3034632012-09-25 10:03:40 +0000697 // If there are no loads or stores, the access is dead. We mark that as
698 // a size zero access.
699 Size = 0;
Chandler Carruth713aa942012-09-14 09:22:59 +0000700 do {
701 Instruction *I, *UsedI;
702 llvm::tie(UsedI, I) = Uses.pop_back_val();
703
704 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
705 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
706 continue;
707 }
708 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
709 Value *Op = SI->getOperand(0);
710 if (Op == UsedI)
711 return SI;
712 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
713 continue;
714 }
715
716 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
717 if (!GEP->hasAllZeroIndices())
718 return GEP;
719 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
720 !isa<SelectInst>(I)) {
721 return I;
722 }
723
724 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
725 ++UI)
726 if (Visited.insert(cast<Instruction>(*UI)))
727 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
728 } while (!Uses.empty());
729
730 return 0;
731 }
732
733 bool visitPHINode(PHINode &PN) {
734 // See if we already have computed info on this node.
735 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
736 if (PHIInfo.first) {
737 PHIInfo.second = true;
Chandler Carruth63392ea2012-09-16 19:39:50 +0000738 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000739 return true;
740 }
741
742 // Check for an unsafe use of the PHI node.
743 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
744 return markAsEscaping(*EscapingI);
745
Chandler Carruth63392ea2012-09-16 19:39:50 +0000746 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000747 return true;
748 }
749
750 bool visitSelectInst(SelectInst &SI) {
751 if (Value *Result = foldSelectInst(SI)) {
752 if (Result == *U)
753 // If the result of the constant fold will be the pointer, recurse
754 // through the select as if we had RAUW'ed it.
755 enqueueUsers(SI, Offset);
756
757 return true;
758 }
759
760 // See if we already have computed info on this node.
761 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
762 if (SelectInfo.first) {
763 SelectInfo.second = true;
Chandler Carruth63392ea2012-09-16 19:39:50 +0000764 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000765 return true;
766 }
767
768 // Check for an unsafe use of the PHI node.
769 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
770 return markAsEscaping(*EscapingI);
771
Chandler Carruth63392ea2012-09-16 19:39:50 +0000772 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000773 return true;
774 }
775
776 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
777 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
778};
779
780
781/// \brief Use adder for the alloca partitioning.
782///
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000783/// This class adds the uses of an alloca to all of the partitions which they
784/// use. For splittable partitions, this can end up doing essentially a linear
Chandler Carruth713aa942012-09-14 09:22:59 +0000785/// walk of the partitions, but the number of steps remains bounded by the
786/// total result instruction size:
787/// - The number of partitions is a result of the number unsplittable
788/// instructions using the alloca.
789/// - The number of users of each partition is at worst the total number of
790/// splittable instructions using the alloca.
791/// Thus we will produce N * M instructions in the end, where N are the number
792/// of unsplittable uses and M are the number of splittable. This visitor does
793/// the exact same number of updates to the partitioning.
794///
795/// In the more common case, this visitor will leverage the fact that the
796/// partition space is pre-sorted, and do a logarithmic search for the
797/// partition needed, making the total visit a classical ((N + M) * log(N))
798/// complexity operation.
799class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
800 friend class InstVisitor<UseBuilder>;
801
802 /// \brief Set to de-duplicate dead instructions found in the use walk.
803 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
804
805public:
806 UseBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000807 : BuilderBase<UseBuilder>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000808
809 /// \brief Run the builder over the allocation.
810 void operator()() {
811 // Note that we have to re-evaluate size on each trip through the loop as
812 // the queue grows at the tail.
813 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
814 U = Queue[Idx].U;
815 Offset = Queue[Idx].Offset;
816 this->visit(cast<Instruction>(U->getUser()));
817 }
818 }
819
820private:
821 void markAsDead(Instruction &I) {
822 if (VisitedDeadInsts.insert(&I))
823 P.DeadUsers.push_back(&I);
824 }
825
Chandler Carruth02e92a02012-09-23 11:43:14 +0000826 void insertUse(Instruction &User, int64_t Offset, uint64_t Size) {
Chandler Carruthc3034632012-09-25 10:03:40 +0000827 // If the use has a zero size or extends outside of the allocation, record
828 // it as a dead use for elimination later.
829 if (Size == 0 || (uint64_t)Offset >= AllocSize ||
Chandler Carruth02e92a02012-09-23 11:43:14 +0000830 (Offset < 0 && (uint64_t)-Offset >= Size))
Chandler Carruth713aa942012-09-14 09:22:59 +0000831 return markAsDead(User);
832
Chandler Carruth02e92a02012-09-23 11:43:14 +0000833 // Clamp the start to the beginning of the allocation.
834 if (Offset < 0) {
835 Size -= (uint64_t)-Offset;
836 Offset = 0;
837 }
838
839 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
840
841 // Clamp the end offset to the end of the allocation. Note that this is
842 // formulated to handle even the case where "BeginOffset + Size" overflows.
843 assert(AllocSize >= BeginOffset); // Established above.
844 if (Size > AllocSize - BeginOffset)
Chandler Carruth713aa942012-09-14 09:22:59 +0000845 EndOffset = AllocSize;
846
847 // NB: This only works if we have zero overlapping partitions.
848 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
849 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
850 B = llvm::prior(B);
851 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
852 ++I) {
Chandler Carruth77c12702012-10-01 01:49:22 +0000853 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
854 std::min(I->EndOffset, EndOffset), U);
855 P.use_push_back(I, NewPU);
Chandler Carruth713aa942012-09-14 09:22:59 +0000856 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
Chandler Carruth77c12702012-10-01 01:49:22 +0000857 P.PHIOrSelectOpMap[U]
Chandler Carruth713aa942012-09-14 09:22:59 +0000858 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
859 }
860 }
861
Chandler Carruth02e92a02012-09-23 11:43:14 +0000862 void handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000863 uint64_t Size = TD.getTypeStoreSize(Ty);
864
865 // If this memory access can be shown to *statically* extend outside the
866 // bounds of of the allocation, it's behavior is undefined, so simply
867 // ignore it. Note that this is more strict than the generic clamping
868 // behavior of insertUse.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000869 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
870 Size > (AllocSize - (uint64_t)Offset))
Chandler Carruth713aa942012-09-14 09:22:59 +0000871 return markAsDead(I);
872
Chandler Carruth63392ea2012-09-16 19:39:50 +0000873 insertUse(I, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000874 }
875
876 void visitBitCastInst(BitCastInst &BC) {
877 if (BC.use_empty())
878 return markAsDead(BC);
879
880 enqueueUsers(BC, Offset);
881 }
882
883 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
884 if (GEPI.use_empty())
885 return markAsDead(GEPI);
886
Chandler Carruth02e92a02012-09-23 11:43:14 +0000887 int64_t GEPOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000888 if (!computeConstantGEPOffset(GEPI, GEPOffset))
889 llvm_unreachable("Unable to compute constant offset for use");
890
891 enqueueUsers(GEPI, GEPOffset);
892 }
893
894 void visitLoadInst(LoadInst &LI) {
Chandler Carruth63392ea2012-09-16 19:39:50 +0000895 handleLoadOrStore(LI.getType(), LI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000896 }
897
898 void visitStoreInst(StoreInst &SI) {
Chandler Carruth63392ea2012-09-16 19:39:50 +0000899 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000900 }
901
902 void visitMemSetInst(MemSetInst &II) {
903 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000904 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
905 insertUse(II, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000906 }
907
908 void visitMemTransferInst(MemTransferInst &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 visitIntrinsicInst(IntrinsicInst &II) {
915 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
916 II.getIntrinsicID() == Intrinsic::lifetime_end);
917
918 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruth63392ea2012-09-16 19:39:50 +0000919 insertUse(II, Offset,
920 std::min(AllocSize - Offset, Length->getLimitedValue()));
Chandler Carruth713aa942012-09-14 09:22:59 +0000921 }
922
Chandler Carruth63392ea2012-09-16 19:39:50 +0000923 void insertPHIOrSelect(Instruction &User, uint64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000924 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
925
926 // For PHI and select operands outside the alloca, we can't nuke the entire
927 // phi or select -- the other side might still be relevant, so we special
928 // case them here and use a separate structure to track the operands
929 // themselves which should be replaced with undef.
930 if (Offset >= AllocSize) {
931 P.DeadOperands.push_back(U);
932 return;
933 }
934
Chandler Carruth63392ea2012-09-16 19:39:50 +0000935 insertUse(User, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000936 }
937 void visitPHINode(PHINode &PN) {
938 if (PN.use_empty())
939 return markAsDead(PN);
940
Chandler Carruth63392ea2012-09-16 19:39:50 +0000941 insertPHIOrSelect(PN, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000942 }
943 void visitSelectInst(SelectInst &SI) {
944 if (SI.use_empty())
945 return markAsDead(SI);
946
947 if (Value *Result = foldSelectInst(SI)) {
948 if (Result == *U)
949 // If the result of the constant fold will be the pointer, recurse
950 // through the select as if we had RAUW'ed it.
951 enqueueUsers(SI, Offset);
Chandler Carruthd54a6b52012-09-21 23:36:40 +0000952 else
953 // Otherwise the operand to the select is dead, and we can replace it
954 // with undef.
955 P.DeadOperands.push_back(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000956
957 return;
958 }
959
Chandler Carruth63392ea2012-09-16 19:39:50 +0000960 insertPHIOrSelect(SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000961 }
962
963 /// \brief Unreachable, we've already visited the alloca once.
964 void visitInstruction(Instruction &I) {
965 llvm_unreachable("Unhandled instruction in use builder.");
966 }
967};
968
969void AllocaPartitioning::splitAndMergePartitions() {
970 size_t NumDeadPartitions = 0;
971
972 // Track the range of splittable partitions that we pass when accumulating
973 // overlapping unsplittable partitions.
974 uint64_t SplitEndOffset = 0ull;
975
976 Partition New(0ull, 0ull, false);
977
978 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
979 ++j;
980
981 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
982 assert(New.BeginOffset == New.EndOffset);
983 New = Partitions[i];
984 } else {
985 assert(New.IsSplittable);
986 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
987 }
988 assert(New.BeginOffset != New.EndOffset);
989
990 // Scan the overlapping partitions.
991 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
992 // If the new partition we are forming is splittable, stop at the first
993 // unsplittable partition.
994 if (New.IsSplittable && !Partitions[j].IsSplittable)
995 break;
996
997 // Grow the new partition to include any equally splittable range. 'j' is
998 // always equally splittable when New is splittable, but when New is not
999 // splittable, we may subsume some (or part of some) splitable partition
1000 // without growing the new one.
1001 if (New.IsSplittable == Partitions[j].IsSplittable) {
1002 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
1003 } else {
1004 assert(!New.IsSplittable);
1005 assert(Partitions[j].IsSplittable);
1006 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
1007 }
1008
1009 Partitions[j].BeginOffset = Partitions[j].EndOffset = UINT64_MAX;
1010 ++NumDeadPartitions;
1011 ++j;
1012 }
1013
1014 // If the new partition is splittable, chop off the end as soon as the
1015 // unsplittable subsequent partition starts and ensure we eventually cover
1016 // the splittable area.
1017 if (j != e && New.IsSplittable) {
1018 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1019 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1020 }
1021
1022 // Add the new partition if it differs from the original one and is
1023 // non-empty. We can end up with an empty partition here if it was
1024 // splittable but there is an unsplittable one that starts at the same
1025 // offset.
1026 if (New != Partitions[i]) {
1027 if (New.BeginOffset != New.EndOffset)
1028 Partitions.push_back(New);
1029 // Mark the old one for removal.
1030 Partitions[i].BeginOffset = Partitions[i].EndOffset = UINT64_MAX;
1031 ++NumDeadPartitions;
1032 }
1033
1034 New.BeginOffset = New.EndOffset;
1035 if (!New.IsSplittable) {
1036 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1037 if (j != e && !Partitions[j].IsSplittable)
1038 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1039 New.IsSplittable = true;
1040 // If there is a trailing splittable partition which won't be fused into
1041 // the next splittable partition go ahead and add it onto the partitions
1042 // list.
1043 if (New.BeginOffset < New.EndOffset &&
1044 (j == e || !Partitions[j].IsSplittable ||
1045 New.EndOffset < Partitions[j].BeginOffset)) {
1046 Partitions.push_back(New);
1047 New.BeginOffset = New.EndOffset = 0ull;
1048 }
1049 }
1050 }
1051
1052 // Re-sort the partitions now that they have been split and merged into
1053 // disjoint set of partitions. Also remove any of the dead partitions we've
1054 // replaced in the process.
1055 std::sort(Partitions.begin(), Partitions.end());
1056 if (NumDeadPartitions) {
1057 assert(Partitions.back().BeginOffset == UINT64_MAX);
1058 assert(Partitions.back().EndOffset == UINT64_MAX);
1059 assert((ptrdiff_t)NumDeadPartitions ==
1060 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1061 }
1062 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1063}
1064
1065AllocaPartitioning::AllocaPartitioning(const TargetData &TD, AllocaInst &AI)
Benjamin Kramerd0807692012-09-14 13:08:09 +00001066 :
1067#ifndef NDEBUG
1068 AI(AI),
1069#endif
1070 PointerEscapingInstr(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001071 PartitionBuilder PB(TD, AI, *this);
1072 if (!PB())
1073 return;
1074
1075 if (Partitions.size() > 1) {
1076 // Sort the uses. This arranges for the offsets to be in ascending order,
1077 // and the sizes to be in descending order.
1078 std::sort(Partitions.begin(), Partitions.end());
1079
1080 // Intersect splittability for all partitions with equal offsets and sizes.
1081 // Then remove all but the first so that we have a sequence of non-equal but
1082 // potentially overlapping partitions.
1083 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1084 I = J) {
1085 ++J;
1086 while (J != E && *I == *J) {
1087 I->IsSplittable &= J->IsSplittable;
1088 ++J;
1089 }
1090 }
1091 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1092 Partitions.end());
1093
1094 // Split splittable and merge unsplittable partitions into a disjoint set
1095 // of partitions over the used space of the allocation.
1096 splitAndMergePartitions();
1097 }
1098
1099 // Now build up the user lists for each of these disjoint partitions by
1100 // re-walking the recursive users of the alloca.
1101 Uses.resize(Partitions.size());
1102 UseBuilder UB(TD, AI, *this);
1103 UB();
Chandler Carruth713aa942012-09-14 09:22:59 +00001104}
1105
1106Type *AllocaPartitioning::getCommonType(iterator I) const {
1107 Type *Ty = 0;
1108 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
Chandler Carruth77c12702012-10-01 01:49:22 +00001109 if (isa<IntrinsicInst>(*UI->U->getUser()))
Chandler Carruth713aa942012-09-14 09:22:59 +00001110 continue;
1111 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
Chandler Carruth7c8df7a2012-09-18 17:49:37 +00001112 continue;
Chandler Carruth713aa942012-09-14 09:22:59 +00001113
1114 Type *UserTy = 0;
Chandler Carruth77c12702012-10-01 01:49:22 +00001115 if (LoadInst *LI = dyn_cast<LoadInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001116 UserTy = LI->getType();
Chandler Carruth77c12702012-10-01 01:49:22 +00001117 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001118 UserTy = SI->getValueOperand()->getType();
Chandler Carruth713aa942012-09-14 09:22:59 +00001119 }
1120
1121 if (Ty && Ty != UserTy)
1122 return 0;
1123
1124 Ty = UserTy;
1125 }
1126 return Ty;
1127}
1128
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001129#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1130
Chandler Carruth713aa942012-09-14 09:22:59 +00001131void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1132 StringRef Indent) const {
1133 OS << Indent << "partition #" << (I - begin())
1134 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1135 << (I->IsSplittable ? " (splittable)" : "")
1136 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1137 << "\n";
1138}
1139
1140void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1141 StringRef Indent) const {
1142 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1143 UI != UE; ++UI) {
1144 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
Chandler Carruth77c12702012-10-01 01:49:22 +00001145 << "used by: " << *UI->U->getUser() << "\n";
1146 if (MemTransferInst *II = dyn_cast<MemTransferInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001147 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1148 bool IsDest;
1149 if (!MTO.IsSplittable)
1150 IsDest = UI->BeginOffset == MTO.DestBegin;
1151 else
1152 IsDest = MTO.DestBegin != 0u;
1153 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1154 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1155 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1156 }
1157 }
1158}
1159
1160void AllocaPartitioning::print(raw_ostream &OS) const {
1161 if (PointerEscapingInstr) {
1162 OS << "No partitioning for alloca: " << AI << "\n"
1163 << " A pointer to this alloca escaped by:\n"
1164 << " " << *PointerEscapingInstr << "\n";
1165 return;
1166 }
1167
1168 OS << "Partitioning of alloca: " << AI << "\n";
1169 unsigned Num = 0;
1170 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1171 print(OS, I);
1172 printUsers(OS, I);
1173 }
1174}
1175
1176void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1177void AllocaPartitioning::dump() const { print(dbgs()); }
1178
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001179#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1180
Chandler Carruth713aa942012-09-14 09:22:59 +00001181
1182namespace {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001183/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1184///
1185/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1186/// the loads and stores of an alloca instruction, as well as updating its
1187/// debug information. This is used when a domtree is unavailable and thus
1188/// mem2reg in its full form can't be used to handle promotion of allocas to
1189/// scalar values.
1190class AllocaPromoter : public LoadAndStorePromoter {
1191 AllocaInst &AI;
1192 DIBuilder &DIB;
1193
1194 SmallVector<DbgDeclareInst *, 4> DDIs;
1195 SmallVector<DbgValueInst *, 4> DVIs;
1196
1197public:
1198 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1199 AllocaInst &AI, DIBuilder &DIB)
1200 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1201
1202 void run(const SmallVectorImpl<Instruction*> &Insts) {
1203 // Remember which alloca we're promoting (for isInstInList).
1204 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1205 for (Value::use_iterator UI = DebugNode->use_begin(),
1206 UE = DebugNode->use_end();
1207 UI != UE; ++UI)
1208 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1209 DDIs.push_back(DDI);
1210 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1211 DVIs.push_back(DVI);
1212 }
1213
1214 LoadAndStorePromoter::run(Insts);
1215 AI.eraseFromParent();
1216 while (!DDIs.empty())
1217 DDIs.pop_back_val()->eraseFromParent();
1218 while (!DVIs.empty())
1219 DVIs.pop_back_val()->eraseFromParent();
1220 }
1221
1222 virtual bool isInstInList(Instruction *I,
1223 const SmallVectorImpl<Instruction*> &Insts) const {
1224 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1225 return LI->getOperand(0) == &AI;
1226 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1227 }
1228
1229 virtual void updateDebugInfo(Instruction *Inst) const {
1230 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1231 E = DDIs.end(); I != E; ++I) {
1232 DbgDeclareInst *DDI = *I;
1233 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1234 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1235 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1236 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1237 }
1238 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1239 E = DVIs.end(); I != E; ++I) {
1240 DbgValueInst *DVI = *I;
1241 Value *Arg = NULL;
1242 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1243 // If an argument is zero extended then use argument directly. The ZExt
1244 // may be zapped by an optimization pass in future.
1245 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1246 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1247 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1248 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1249 if (!Arg)
1250 Arg = SI->getOperand(0);
1251 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1252 Arg = LI->getOperand(0);
1253 } else {
1254 continue;
1255 }
1256 Instruction *DbgVal =
1257 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1258 Inst);
1259 DbgVal->setDebugLoc(DVI->getDebugLoc());
1260 }
1261 }
1262};
1263} // end anon namespace
1264
1265
1266namespace {
Chandler Carruth713aa942012-09-14 09:22:59 +00001267/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1268///
1269/// This pass takes allocations which can be completely analyzed (that is, they
1270/// don't escape) and tries to turn them into scalar SSA values. There are
1271/// a few steps to this process.
1272///
1273/// 1) It takes allocations of aggregates and analyzes the ways in which they
1274/// are used to try to split them into smaller allocations, ideally of
1275/// a single scalar data type. It will split up memcpy and memset accesses
1276/// as necessary and try to isolate invidual scalar accesses.
1277/// 2) It will transform accesses into forms which are suitable for SSA value
1278/// promotion. This can be replacing a memset with a scalar store of an
1279/// integer value, or it can involve speculating operations on a PHI or
1280/// select to be a PHI or select of the results.
1281/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1282/// onto insert and extract operations on a vector value, and convert them to
1283/// this form. By doing so, it will enable promotion of vector aggregates to
1284/// SSA vector values.
1285class SROA : public FunctionPass {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001286 const bool RequiresDomTree;
1287
Chandler Carruth713aa942012-09-14 09:22:59 +00001288 LLVMContext *C;
1289 const TargetData *TD;
1290 DominatorTree *DT;
1291
1292 /// \brief Worklist of alloca instructions to simplify.
1293 ///
1294 /// Each alloca in the function is added to this. Each new alloca formed gets
1295 /// added to it as well to recursively simplify unless that alloca can be
1296 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1297 /// the one being actively rewritten, we add it back onto the list if not
1298 /// already present to ensure it is re-visited.
1299 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1300
1301 /// \brief A collection of instructions to delete.
1302 /// We try to batch deletions to simplify code and make things a bit more
1303 /// efficient.
1304 SmallVector<Instruction *, 8> DeadInsts;
1305
1306 /// \brief A set to prevent repeatedly marking an instruction split into many
1307 /// uses as dead. Only used to guard insertion into DeadInsts.
1308 SmallPtrSet<Instruction *, 4> DeadSplitInsts;
1309
Chandler Carruth713aa942012-09-14 09:22:59 +00001310 /// \brief A collection of alloca instructions we can directly promote.
1311 std::vector<AllocaInst *> PromotableAllocas;
1312
1313public:
Chandler Carruth1c8db502012-09-15 11:43:14 +00001314 SROA(bool RequiresDomTree = true)
1315 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1316 C(0), TD(0), DT(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001317 initializeSROAPass(*PassRegistry::getPassRegistry());
1318 }
1319 bool runOnFunction(Function &F);
1320 void getAnalysisUsage(AnalysisUsage &AU) const;
1321
1322 const char *getPassName() const { return "SROA"; }
1323 static char ID;
1324
1325private:
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00001326 friend class PHIOrSelectSpeculator;
Chandler Carruth713aa942012-09-14 09:22:59 +00001327 friend class AllocaPartitionRewriter;
1328 friend class AllocaPartitionVectorRewriter;
1329
1330 bool rewriteAllocaPartition(AllocaInst &AI,
1331 AllocaPartitioning &P,
1332 AllocaPartitioning::iterator PI);
1333 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1334 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth8615cd22012-09-14 10:26:38 +00001335 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth1c8db502012-09-15 11:43:14 +00001336 bool promoteAllocas(Function &F);
Chandler Carruth713aa942012-09-14 09:22:59 +00001337};
1338}
1339
1340char SROA::ID = 0;
1341
Chandler Carruth1c8db502012-09-15 11:43:14 +00001342FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1343 return new SROA(RequiresDomTree);
Chandler Carruth713aa942012-09-14 09:22:59 +00001344}
1345
1346INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1347 false, false)
1348INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1349INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1350 false, false)
1351
1352/// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1353///
1354/// If the provided GEP is all-constant, the total byte offset formed by the
1355/// GEP is computed and Offset is set to it. If the GEP has any non-constant
1356/// operands, the function returns false and the value of Offset is unmodified.
1357static bool accumulateGEPOffsets(const TargetData &TD, GEPOperator &GEP,
1358 APInt &Offset) {
1359 APInt GEPOffset(Offset.getBitWidth(), 0);
1360 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1361 GTI != GTE; ++GTI) {
1362 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1363 if (!OpC)
1364 return false;
1365 if (OpC->isZero()) continue;
1366
1367 // Handle a struct index, which adds its field offset to the pointer.
1368 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1369 unsigned ElementIdx = OpC->getZExtValue();
1370 const StructLayout *SL = TD.getStructLayout(STy);
1371 GEPOffset += APInt(Offset.getBitWidth(),
1372 SL->getElementOffset(ElementIdx));
1373 continue;
1374 }
1375
1376 APInt TypeSize(Offset.getBitWidth(),
1377 TD.getTypeAllocSize(GTI.getIndexedType()));
1378 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1379 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1380 "vector element size is not a multiple of 8, cannot GEP over it");
1381 TypeSize = VTy->getScalarSizeInBits() / 8;
1382 }
1383
1384 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1385 }
1386 Offset = GEPOffset;
1387 return true;
1388}
1389
1390/// \brief Build a GEP out of a base pointer and indices.
1391///
1392/// This will return the BasePtr if that is valid, or build a new GEP
1393/// instruction using the IRBuilder if GEP-ing is needed.
1394static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1395 SmallVectorImpl<Value *> &Indices,
1396 const Twine &Prefix) {
1397 if (Indices.empty())
1398 return BasePtr;
1399
1400 // A single zero index is a no-op, so check for this and avoid building a GEP
1401 // in that case.
1402 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1403 return BasePtr;
1404
1405 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1406}
1407
1408/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1409/// TargetTy without changing the offset of the pointer.
1410///
1411/// This routine assumes we've already established a properly offset GEP with
1412/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1413/// zero-indices down through type layers until we find one the same as
1414/// TargetTy. If we can't find one with the same type, we at least try to use
1415/// one with the same size. If none of that works, we just produce the GEP as
1416/// indicated by Indices to have the correct offset.
1417static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const TargetData &TD,
1418 Value *BasePtr, Type *Ty, Type *TargetTy,
1419 SmallVectorImpl<Value *> &Indices,
1420 const Twine &Prefix) {
1421 if (Ty == TargetTy)
1422 return buildGEP(IRB, BasePtr, Indices, Prefix);
1423
1424 // See if we can descend into a struct and locate a field with the correct
1425 // type.
1426 unsigned NumLayers = 0;
1427 Type *ElementTy = Ty;
1428 do {
1429 if (ElementTy->isPointerTy())
1430 break;
1431 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1432 ElementTy = SeqTy->getElementType();
1433 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(), 0)));
1434 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1435 ElementTy = *STy->element_begin();
1436 Indices.push_back(IRB.getInt32(0));
1437 } else {
1438 break;
1439 }
1440 ++NumLayers;
1441 } while (ElementTy != TargetTy);
1442 if (ElementTy != TargetTy)
1443 Indices.erase(Indices.end() - NumLayers, Indices.end());
1444
1445 return buildGEP(IRB, BasePtr, Indices, Prefix);
1446}
1447
1448/// \brief Recursively compute indices for a natural GEP.
1449///
1450/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1451/// element types adding appropriate indices for the GEP.
1452static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const TargetData &TD,
1453 Value *Ptr, Type *Ty, APInt &Offset,
1454 Type *TargetTy,
1455 SmallVectorImpl<Value *> &Indices,
1456 const Twine &Prefix) {
1457 if (Offset == 0)
1458 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1459
1460 // We can't recurse through pointer types.
1461 if (Ty->isPointerTy())
1462 return 0;
1463
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001464 // We try to analyze GEPs over vectors here, but note that these GEPs are
1465 // extremely poorly defined currently. The long-term goal is to remove GEPing
1466 // over a vector from the IR completely.
Chandler Carruth713aa942012-09-14 09:22:59 +00001467 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1468 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1469 if (ElementSizeInBits % 8)
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001470 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth713aa942012-09-14 09:22:59 +00001471 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1472 APInt NumSkippedElements = Offset.udiv(ElementSize);
1473 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1474 return 0;
1475 Offset -= NumSkippedElements * ElementSize;
1476 Indices.push_back(IRB.getInt(NumSkippedElements));
1477 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1478 Offset, TargetTy, Indices, Prefix);
1479 }
1480
1481 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1482 Type *ElementTy = ArrTy->getElementType();
1483 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1484 APInt NumSkippedElements = Offset.udiv(ElementSize);
1485 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1486 return 0;
1487
1488 Offset -= NumSkippedElements * ElementSize;
1489 Indices.push_back(IRB.getInt(NumSkippedElements));
1490 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1491 Indices, Prefix);
1492 }
1493
1494 StructType *STy = dyn_cast<StructType>(Ty);
1495 if (!STy)
1496 return 0;
1497
1498 const StructLayout *SL = TD.getStructLayout(STy);
1499 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthad41dcf2012-09-14 10:30:42 +00001500 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00001501 return 0;
1502 unsigned Index = SL->getElementContainingOffset(StructOffset);
1503 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1504 Type *ElementTy = STy->getElementType(Index);
1505 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1506 return 0; // The offset points into alignment padding.
1507
1508 Indices.push_back(IRB.getInt32(Index));
1509 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1510 Indices, Prefix);
1511}
1512
1513/// \brief Get a natural GEP from a base pointer to a particular offset and
1514/// resulting in a particular type.
1515///
1516/// The goal is to produce a "natural" looking GEP that works with the existing
1517/// composite types to arrive at the appropriate offset and element type for
1518/// a pointer. TargetTy is the element type the returned GEP should point-to if
1519/// possible. We recurse by decreasing Offset, adding the appropriate index to
1520/// Indices, and setting Ty to the result subtype.
1521///
Chandler Carruth7f5bede2012-09-14 10:18:49 +00001522/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth713aa942012-09-14 09:22:59 +00001523static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const TargetData &TD,
1524 Value *Ptr, APInt Offset, Type *TargetTy,
1525 SmallVectorImpl<Value *> &Indices,
1526 const Twine &Prefix) {
1527 PointerType *Ty = cast<PointerType>(Ptr->getType());
1528
1529 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1530 // an i8.
1531 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1532 return 0;
1533
1534 Type *ElementTy = Ty->getElementType();
Chandler Carruth38f35fd2012-09-18 22:37:19 +00001535 if (!ElementTy->isSized())
1536 return 0; // We can't GEP through an unsized element.
Chandler Carruth713aa942012-09-14 09:22:59 +00001537 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1538 if (ElementSize == 0)
1539 return 0; // Zero-length arrays can't help us build a natural GEP.
1540 APInt NumSkippedElements = Offset.udiv(ElementSize);
1541
1542 Offset -= NumSkippedElements * ElementSize;
1543 Indices.push_back(IRB.getInt(NumSkippedElements));
1544 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1545 Indices, Prefix);
1546}
1547
1548/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1549/// resulting pointer has PointerTy.
1550///
1551/// This tries very hard to compute a "natural" GEP which arrives at the offset
1552/// and produces the pointer type desired. Where it cannot, it will try to use
1553/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1554/// fails, it will try to use an existing i8* and GEP to the byte offset and
1555/// bitcast to the type.
1556///
1557/// The strategy for finding the more natural GEPs is to peel off layers of the
1558/// pointer, walking back through bit casts and GEPs, searching for a base
1559/// pointer from which we can compute a natural GEP with the desired
1560/// properities. The algorithm tries to fold as many constant indices into
1561/// a single GEP as possible, thus making each GEP more independent of the
1562/// surrounding code.
1563static Value *getAdjustedPtr(IRBuilder<> &IRB, const TargetData &TD,
1564 Value *Ptr, APInt Offset, Type *PointerTy,
1565 const Twine &Prefix) {
1566 // Even though we don't look through PHI nodes, we could be called on an
1567 // instruction in an unreachable block, which may be on a cycle.
1568 SmallPtrSet<Value *, 4> Visited;
1569 Visited.insert(Ptr);
1570 SmallVector<Value *, 4> Indices;
1571
1572 // We may end up computing an offset pointer that has the wrong type. If we
1573 // never are able to compute one directly that has the correct type, we'll
1574 // fall back to it, so keep it around here.
1575 Value *OffsetPtr = 0;
1576
1577 // Remember any i8 pointer we come across to re-use if we need to do a raw
1578 // byte offset.
1579 Value *Int8Ptr = 0;
1580 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1581
1582 Type *TargetTy = PointerTy->getPointerElementType();
1583
1584 do {
1585 // First fold any existing GEPs into the offset.
1586 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1587 APInt GEPOffset(Offset.getBitWidth(), 0);
1588 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1589 break;
1590 Offset += GEPOffset;
1591 Ptr = GEP->getPointerOperand();
1592 if (!Visited.insert(Ptr))
1593 break;
1594 }
1595
1596 // See if we can perform a natural GEP here.
1597 Indices.clear();
1598 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1599 Indices, Prefix)) {
1600 if (P->getType() == PointerTy) {
1601 // Zap any offset pointer that we ended up computing in previous rounds.
1602 if (OffsetPtr && OffsetPtr->use_empty())
1603 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1604 I->eraseFromParent();
1605 return P;
1606 }
1607 if (!OffsetPtr) {
1608 OffsetPtr = P;
1609 }
1610 }
1611
1612 // Stash this pointer if we've found an i8*.
1613 if (Ptr->getType()->isIntegerTy(8)) {
1614 Int8Ptr = Ptr;
1615 Int8PtrOffset = Offset;
1616 }
1617
1618 // Peel off a layer of the pointer and update the offset appropriately.
1619 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1620 Ptr = cast<Operator>(Ptr)->getOperand(0);
1621 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1622 if (GA->mayBeOverridden())
1623 break;
1624 Ptr = GA->getAliasee();
1625 } else {
1626 break;
1627 }
1628 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1629 } while (Visited.insert(Ptr));
1630
1631 if (!OffsetPtr) {
1632 if (!Int8Ptr) {
1633 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1634 Prefix + ".raw_cast");
1635 Int8PtrOffset = Offset;
1636 }
1637
1638 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1639 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1640 Prefix + ".raw_idx");
1641 }
1642 Ptr = OffsetPtr;
1643
1644 // On the off chance we were targeting i8*, guard the bitcast here.
1645 if (Ptr->getType() != PointerTy)
1646 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
1647
1648 return Ptr;
1649}
1650
1651/// \brief Test whether the given alloca partition can be promoted to a vector.
1652///
1653/// This is a quick test to check whether we can rewrite a particular alloca
1654/// partition (and its newly formed alloca) into a vector alloca with only
1655/// whole-vector loads and stores such that it could be promoted to a vector
1656/// SSA value. We only can ensure this for a limited set of operations, and we
1657/// don't want to do the rewrites unless we are confident that the result will
1658/// be promotable, so we have an early test here.
1659static bool isVectorPromotionViable(const TargetData &TD,
1660 Type *AllocaTy,
1661 AllocaPartitioning &P,
1662 uint64_t PartitionBeginOffset,
1663 uint64_t PartitionEndOffset,
1664 AllocaPartitioning::const_use_iterator I,
1665 AllocaPartitioning::const_use_iterator E) {
1666 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1667 if (!Ty)
1668 return false;
1669
1670 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
1671 uint64_t ElementSize = Ty->getScalarSizeInBits();
1672
1673 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1674 // that aren't byte sized.
1675 if (ElementSize % 8)
1676 return false;
1677 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
1678 VecSize /= 8;
1679 ElementSize /= 8;
1680
1681 for (; I != E; ++I) {
1682 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
1683 uint64_t BeginIndex = BeginOffset / ElementSize;
1684 if (BeginIndex * ElementSize != BeginOffset ||
1685 BeginIndex >= Ty->getNumElements())
1686 return false;
1687 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
1688 uint64_t EndIndex = EndOffset / ElementSize;
1689 if (EndIndex * ElementSize != EndOffset ||
1690 EndIndex > Ty->getNumElements())
1691 return false;
1692
1693 // FIXME: We should build shuffle vector instructions to handle
1694 // non-element-sized accesses.
1695 if ((EndOffset - BeginOffset) != ElementSize &&
1696 (EndOffset - BeginOffset) != VecSize)
1697 return false;
1698
Chandler Carruth77c12702012-10-01 01:49:22 +00001699 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001700 if (MI->isVolatile())
1701 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00001702 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001703 const AllocaPartitioning::MemTransferOffsets &MTO
1704 = P.getMemTransferOffsets(*MTI);
1705 if (!MTO.IsSplittable)
1706 return false;
1707 }
Chandler Carruth77c12702012-10-01 01:49:22 +00001708 } else if (I->U->get()->getType()->getPointerElementType()->isStructTy()) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001709 // Disable vector promotion when there are loads or stores of an FCA.
1710 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00001711 } else if (!isa<LoadInst>(I->U->getUser()) &&
1712 !isa<StoreInst>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001713 return false;
1714 }
1715 }
1716 return true;
1717}
1718
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001719/// \brief Test whether the given alloca partition can be promoted to an int.
1720///
1721/// This is a quick test to check whether we can rewrite a particular alloca
1722/// partition (and its newly formed alloca) into an integer alloca suitable for
1723/// promotion to an SSA value. We only can ensure this for a limited set of
1724/// operations, and we don't want to do the rewrites unless we are confident
1725/// that the result will be promotable, so we have an early test here.
1726static bool isIntegerPromotionViable(const TargetData &TD,
1727 Type *AllocaTy,
1728 AllocaPartitioning &P,
1729 AllocaPartitioning::const_use_iterator I,
1730 AllocaPartitioning::const_use_iterator E) {
1731 IntegerType *Ty = dyn_cast<IntegerType>(AllocaTy);
1732 if (!Ty)
1733 return false;
1734
1735 // Check the uses to ensure the uses are (likely) promoteable integer uses.
1736 // Also ensure that the alloca has a covering load or store. We don't want
1737 // promote because of some other unsplittable entry (which we may make
1738 // splittable later) and lose the ability to promote each element access.
1739 bool WholeAllocaOp = false;
1740 for (; I != E; ++I) {
Chandler Carruth77c12702012-10-01 01:49:22 +00001741 if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001742 if (LI->isVolatile() || !LI->getType()->isIntegerTy())
1743 return false;
1744 if (LI->getType() == Ty)
1745 WholeAllocaOp = true;
Chandler Carruth77c12702012-10-01 01:49:22 +00001746 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001747 if (SI->isVolatile() || !SI->getValueOperand()->getType()->isIntegerTy())
1748 return false;
1749 if (SI->getValueOperand()->getType() == Ty)
1750 WholeAllocaOp = true;
Chandler Carruth77c12702012-10-01 01:49:22 +00001751 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001752 if (MI->isVolatile())
1753 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00001754 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001755 const AllocaPartitioning::MemTransferOffsets &MTO
1756 = P.getMemTransferOffsets(*MTI);
1757 if (!MTO.IsSplittable)
1758 return false;
1759 }
1760 } else {
1761 return false;
1762 }
1763 }
1764 return WholeAllocaOp;
1765}
1766
Chandler Carruth713aa942012-09-14 09:22:59 +00001767namespace {
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00001768/// \brief Visitor to speculate PHIs and Selects where possible.
1769class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
1770 // Befriend the base class so it can delegate to private visit methods.
1771 friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
1772
1773 const TargetData &TD;
1774 AllocaPartitioning &P;
1775 SROA &Pass;
1776
1777public:
1778 PHIOrSelectSpeculator(const TargetData &TD, AllocaPartitioning &P, SROA &Pass)
1779 : TD(TD), P(P), Pass(Pass) {}
1780
1781 /// \brief Visit the users of the alloca partition and rewrite them.
1782 void visitUsers(AllocaPartitioning::const_use_iterator I,
1783 AllocaPartitioning::const_use_iterator E) {
1784 for (; I != E; ++I)
1785 visit(cast<Instruction>(I->U->getUser()));
1786 }
1787
1788private:
1789 // By default, skip this instruction.
1790 void visitInstruction(Instruction &I) {}
1791
1792 /// PHI instructions that use an alloca and are subsequently loaded can be
1793 /// rewritten to load both input pointers in the pred blocks and then PHI the
1794 /// results, allowing the load of the alloca to be promoted.
1795 /// From this:
1796 /// %P2 = phi [i32* %Alloca, i32* %Other]
1797 /// %V = load i32* %P2
1798 /// to:
1799 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1800 /// ...
1801 /// %V2 = load i32* %Other
1802 /// ...
1803 /// %V = phi [i32 %V1, i32 %V2]
1804 ///
1805 /// We can do this to a select if its only uses are loads and if the operand
1806 /// to the select can be loaded unconditionally.
1807 ///
1808 /// FIXME: This should be hoisted into a generic utility, likely in
1809 /// Transforms/Util/Local.h
1810 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
1811 // For now, we can only do this promotion if the load is in the same block
1812 // as the PHI, and if there are no stores between the phi and load.
1813 // TODO: Allow recursive phi users.
1814 // TODO: Allow stores.
1815 BasicBlock *BB = PN.getParent();
1816 unsigned MaxAlign = 0;
1817 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
1818 UI != UE; ++UI) {
1819 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1820 if (LI == 0 || !LI->isSimple()) return false;
1821
1822 // For now we only allow loads in the same block as the PHI. This is
1823 // a common case that happens when instcombine merges two loads through
1824 // a PHI.
1825 if (LI->getParent() != BB) return false;
1826
1827 // Ensure that there are no instructions between the PHI and the load that
1828 // could store.
1829 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1830 if (BBI->mayWriteToMemory())
1831 return false;
1832
1833 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1834 Loads.push_back(LI);
1835 }
1836
1837 // We can only transform this if it is safe to push the loads into the
1838 // predecessor blocks. The only thing to watch out for is that we can't put
1839 // a possibly trapping load in the predecessor if it is a critical edge.
1840 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
1841 ++Idx) {
1842 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1843 Value *InVal = PN.getIncomingValue(Idx);
1844
1845 // If the value is produced by the terminator of the predecessor (an
1846 // invoke) or it has side-effects, there is no valid place to put a load
1847 // in the predecessor.
1848 if (TI == InVal || TI->mayHaveSideEffects())
1849 return false;
1850
1851 // If the predecessor has a single successor, then the edge isn't
1852 // critical.
1853 if (TI->getNumSuccessors() == 1)
1854 continue;
1855
1856 // If this pointer is always safe to load, or if we can prove that there
1857 // is already a load in the block, then we can move the load to the pred
1858 // block.
1859 if (InVal->isDereferenceablePointer() ||
1860 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
1861 continue;
1862
1863 return false;
1864 }
1865
1866 return true;
1867 }
1868
1869 void visitPHINode(PHINode &PN) {
1870 DEBUG(dbgs() << " original: " << PN << "\n");
1871
1872 SmallVector<LoadInst *, 4> Loads;
1873 if (!isSafePHIToSpeculate(PN, Loads))
1874 return;
1875
1876 assert(!Loads.empty());
1877
1878 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1879 IRBuilder<> PHIBuilder(&PN);
1880 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1881 PN.getName() + ".sroa.speculated");
1882
1883 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1884 // matter which one we get and if any differ, it doesn't matter.
1885 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
1886 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1887 unsigned Align = SomeLoad->getAlignment();
1888
1889 // Rewrite all loads of the PN to use the new PHI.
1890 do {
1891 LoadInst *LI = Loads.pop_back_val();
1892 LI->replaceAllUsesWith(NewPN);
1893 Pass.DeadInsts.push_back(LI);
1894 } while (!Loads.empty());
1895
1896 // Inject loads into all of the pred blocks.
1897 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1898 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1899 TerminatorInst *TI = Pred->getTerminator();
1900 Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
1901 Value *InVal = PN.getIncomingValue(Idx);
1902 IRBuilder<> PredBuilder(TI);
1903
1904 LoadInst *Load
1905 = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
1906 Pred->getName()));
1907 ++NumLoadsSpeculated;
1908 Load->setAlignment(Align);
1909 if (TBAATag)
1910 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1911 NewPN->addIncoming(Load, Pred);
1912
1913 Instruction *Ptr = dyn_cast<Instruction>(InVal);
1914 if (!Ptr)
1915 // No uses to rewrite.
1916 continue;
1917
1918 // Try to lookup and rewrite any partition uses corresponding to this phi
1919 // input.
1920 AllocaPartitioning::iterator PI
1921 = P.findPartitionForPHIOrSelectOperand(InUse);
1922 if (PI == P.end())
1923 continue;
1924
1925 // Replace the Use in the PartitionUse for this operand with the Use
1926 // inside the load.
1927 AllocaPartitioning::use_iterator UI
1928 = P.findPartitionUseForPHIOrSelectOperand(InUse);
1929 assert(isa<PHINode>(*UI->U->getUser()));
1930 UI->U = &Load->getOperandUse(Load->getPointerOperandIndex());
1931 }
1932 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1933 }
1934
1935 /// Select instructions that use an alloca and are subsequently loaded can be
1936 /// rewritten to load both input pointers and then select between the result,
1937 /// allowing the load of the alloca to be promoted.
1938 /// From this:
1939 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1940 /// %V = load i32* %P2
1941 /// to:
1942 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1943 /// %V2 = load i32* %Other
1944 /// %V = select i1 %cond, i32 %V1, i32 %V2
1945 ///
1946 /// We can do this to a select if its only uses are loads and if the operand
1947 /// to the select can be loaded unconditionally.
1948 bool isSafeSelectToSpeculate(SelectInst &SI,
1949 SmallVectorImpl<LoadInst *> &Loads) {
1950 Value *TValue = SI.getTrueValue();
1951 Value *FValue = SI.getFalseValue();
1952 bool TDerefable = TValue->isDereferenceablePointer();
1953 bool FDerefable = FValue->isDereferenceablePointer();
1954
1955 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
1956 UI != UE; ++UI) {
1957 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1958 if (LI == 0 || !LI->isSimple()) return false;
1959
1960 // Both operands to the select need to be dereferencable, either
1961 // absolutely (e.g. allocas) or at this point because we can see other
1962 // accesses to it.
1963 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
1964 LI->getAlignment(), &TD))
1965 return false;
1966 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
1967 LI->getAlignment(), &TD))
1968 return false;
1969 Loads.push_back(LI);
1970 }
1971
1972 return true;
1973 }
1974
1975 void visitSelectInst(SelectInst &SI) {
1976 DEBUG(dbgs() << " original: " << SI << "\n");
1977 IRBuilder<> IRB(&SI);
1978
1979 // If the select isn't safe to speculate, just use simple logic to emit it.
1980 SmallVector<LoadInst *, 4> Loads;
1981 if (!isSafeSelectToSpeculate(SI, Loads))
1982 return;
1983
1984 Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) };
1985 AllocaPartitioning::iterator PIs[2];
1986 AllocaPartitioning::PartitionUse PUs[2];
1987 for (unsigned i = 0, e = 2; i != e; ++i) {
1988 PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]);
1989 if (PIs[i] != P.end()) {
1990 // If the pointer is within the partitioning, remove the select from
1991 // its uses. We'll add in the new loads below.
1992 AllocaPartitioning::use_iterator UI
1993 = P.findPartitionUseForPHIOrSelectOperand(Ops[i]);
1994 PUs[i] = *UI;
1995 P.use_erase(PIs[i], UI);
1996 }
1997 }
1998
1999 Value *TV = SI.getTrueValue();
2000 Value *FV = SI.getFalseValue();
2001 // Replace the loads of the select with a select of two loads.
2002 while (!Loads.empty()) {
2003 LoadInst *LI = Loads.pop_back_val();
2004
2005 IRB.SetInsertPoint(LI);
2006 LoadInst *TL =
2007 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
2008 LoadInst *FL =
2009 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
2010 NumLoadsSpeculated += 2;
2011
2012 // Transfer alignment and TBAA info if present.
2013 TL->setAlignment(LI->getAlignment());
2014 FL->setAlignment(LI->getAlignment());
2015 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
2016 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
2017 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
2018 }
2019
2020 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
2021 LI->getName() + ".sroa.speculated");
2022
2023 LoadInst *Loads[2] = { TL, FL };
2024 for (unsigned i = 0, e = 2; i != e; ++i) {
2025 if (PIs[i] != P.end()) {
2026 Use *LoadUse = &Loads[i]->getOperandUse(0);
2027 assert(PUs[i].U->get() == LoadUse->get());
2028 PUs[i].U = LoadUse;
2029 P.use_push_back(PIs[i], PUs[i]);
2030 }
2031 }
2032
2033 DEBUG(dbgs() << " speculated to: " << *V << "\n");
2034 LI->replaceAllUsesWith(V);
2035 Pass.DeadInsts.push_back(LI);
2036 }
2037 }
2038};
2039
Chandler Carruth713aa942012-09-14 09:22:59 +00002040/// \brief Visitor to rewrite instructions using a partition of an alloca to
2041/// use a new alloca.
2042///
2043/// Also implements the rewriting to vector-based accesses when the partition
2044/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2045/// lives here.
2046class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
2047 bool> {
2048 // Befriend the base class so it can delegate to private visit methods.
2049 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
2050
2051 const TargetData &TD;
2052 AllocaPartitioning &P;
2053 SROA &Pass;
2054 AllocaInst &OldAI, &NewAI;
2055 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2056
2057 // If we are rewriting an alloca partition which can be written as pure
2058 // vector operations, we stash extra information here. When VecTy is
2059 // non-null, we have some strict guarantees about the rewriten alloca:
2060 // - The new alloca is exactly the size of the vector type here.
2061 // - The accesses all either map to the entire vector or to a single
2062 // element.
2063 // - The set of accessing instructions is only one of those handled above
2064 // in isVectorPromotionViable. Generally these are the same access kinds
2065 // which are promotable via mem2reg.
2066 VectorType *VecTy;
2067 Type *ElementTy;
2068 uint64_t ElementSize;
2069
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002070 // This is a convenience and flag variable that will be null unless the new
2071 // alloca has a promotion-targeted integer type due to passing
2072 // isIntegerPromotionViable above. If it is non-null does, the desired
2073 // integer type will be stored here for easy access during rewriting.
2074 IntegerType *IntPromotionTy;
2075
Chandler Carruth713aa942012-09-14 09:22:59 +00002076 // The offset of the partition user currently being rewritten.
2077 uint64_t BeginOffset, EndOffset;
Chandler Carruth77c12702012-10-01 01:49:22 +00002078 Use *OldUse;
Chandler Carruth713aa942012-09-14 09:22:59 +00002079 Instruction *OldPtr;
2080
2081 // The name prefix to use when rewriting instructions for this alloca.
2082 std::string NamePrefix;
2083
2084public:
2085 AllocaPartitionRewriter(const TargetData &TD, AllocaPartitioning &P,
2086 AllocaPartitioning::iterator PI,
2087 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
2088 uint64_t NewBeginOffset, uint64_t NewEndOffset)
2089 : TD(TD), P(P), Pass(Pass),
2090 OldAI(OldAI), NewAI(NewAI),
2091 NewAllocaBeginOffset(NewBeginOffset),
2092 NewAllocaEndOffset(NewEndOffset),
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002093 VecTy(), ElementTy(), ElementSize(), IntPromotionTy(),
Chandler Carruth713aa942012-09-14 09:22:59 +00002094 BeginOffset(), EndOffset() {
2095 }
2096
2097 /// \brief Visit the users of the alloca partition and rewrite them.
2098 bool visitUsers(AllocaPartitioning::const_use_iterator I,
2099 AllocaPartitioning::const_use_iterator E) {
2100 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
2101 NewAllocaBeginOffset, NewAllocaEndOffset,
2102 I, E)) {
2103 ++NumVectorized;
2104 VecTy = cast<VectorType>(NewAI.getAllocatedType());
2105 ElementTy = VecTy->getElementType();
2106 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
2107 "Only multiple-of-8 sized vector elements are viable");
2108 ElementSize = VecTy->getScalarSizeInBits() / 8;
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002109 } else if (isIntegerPromotionViable(TD, NewAI.getAllocatedType(),
2110 P, I, E)) {
2111 IntPromotionTy = cast<IntegerType>(NewAI.getAllocatedType());
Chandler Carruth713aa942012-09-14 09:22:59 +00002112 }
2113 bool CanSROA = true;
2114 for (; I != E; ++I) {
2115 BeginOffset = I->BeginOffset;
2116 EndOffset = I->EndOffset;
Chandler Carruth77c12702012-10-01 01:49:22 +00002117 OldUse = I->U;
2118 OldPtr = cast<Instruction>(I->U->get());
Chandler Carruth713aa942012-09-14 09:22:59 +00002119 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
Chandler Carruth77c12702012-10-01 01:49:22 +00002120 CanSROA &= visit(cast<Instruction>(I->U->getUser()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002121 }
2122 if (VecTy) {
2123 assert(CanSROA);
2124 VecTy = 0;
2125 ElementTy = 0;
2126 ElementSize = 0;
2127 }
2128 return CanSROA;
2129 }
2130
2131private:
2132 // Every instruction which can end up as a user must have a rewrite rule.
2133 bool visitInstruction(Instruction &I) {
2134 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2135 llvm_unreachable("No rewrite rule for this instruction!");
2136 }
2137
2138 Twine getName(const Twine &Suffix) {
2139 return NamePrefix + Suffix;
2140 }
2141
2142 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
2143 assert(BeginOffset >= NewAllocaBeginOffset);
2144 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
2145 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
2146 }
2147
2148 ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
2149 assert(VecTy && "Can only call getIndex when rewriting a vector");
2150 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2151 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2152 uint32_t Index = RelOffset / ElementSize;
2153 assert(Index * ElementSize == RelOffset);
2154 return IRB.getInt32(Index);
2155 }
2156
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002157 Value *extractInteger(IRBuilder<> &IRB, IntegerType *TargetTy,
2158 uint64_t Offset) {
2159 assert(IntPromotionTy && "Alloca is not an integer we can extract from");
Chandler Carruth81b001a2012-09-26 10:27:46 +00002160 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2161 getName(".load"));
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002162 assert(Offset >= NewAllocaBeginOffset && "Out of bounds offset");
2163 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2164 if (RelOffset)
2165 V = IRB.CreateLShr(V, RelOffset*8, getName(".shift"));
2166 if (TargetTy != IntPromotionTy) {
2167 assert(TargetTy->getBitWidth() < IntPromotionTy->getBitWidth() &&
2168 "Cannot extract to a larger integer!");
2169 V = IRB.CreateTrunc(V, TargetTy, getName(".trunc"));
2170 }
2171 return V;
2172 }
2173
2174 StoreInst *insertInteger(IRBuilder<> &IRB, Value *V, uint64_t Offset) {
2175 IntegerType *Ty = cast<IntegerType>(V->getType());
2176 if (Ty == IntPromotionTy)
Chandler Carruth81b001a2012-09-26 10:27:46 +00002177 return IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002178
2179 assert(Ty->getBitWidth() < IntPromotionTy->getBitWidth() &&
2180 "Cannot insert a larger integer!");
2181 V = IRB.CreateZExt(V, IntPromotionTy, getName(".ext"));
2182 assert(Offset >= NewAllocaBeginOffset && "Out of bounds offset");
2183 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2184 if (RelOffset)
2185 V = IRB.CreateShl(V, RelOffset*8, getName(".shift"));
2186
2187 APInt Mask = ~Ty->getMask().zext(IntPromotionTy->getBitWidth())
2188 .shl(RelOffset*8);
Chandler Carruth81b001a2012-09-26 10:27:46 +00002189 Value *Old = IRB.CreateAnd(IRB.CreateAlignedLoad(&NewAI,
2190 NewAI.getAlignment(),
2191 getName(".oldload")),
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002192 Mask, getName(".mask"));
Chandler Carruth81b001a2012-09-26 10:27:46 +00002193 return IRB.CreateAlignedStore(IRB.CreateOr(Old, V, getName(".insert")),
2194 &NewAI, NewAI.getAlignment());
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002195 }
2196
Chandler Carruth713aa942012-09-14 09:22:59 +00002197 void deleteIfTriviallyDead(Value *V) {
2198 Instruction *I = cast<Instruction>(V);
2199 if (isInstructionTriviallyDead(I))
2200 Pass.DeadInsts.push_back(I);
2201 }
2202
2203 Value *getValueCast(IRBuilder<> &IRB, Value *V, Type *Ty) {
2204 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
2205 return IRB.CreateIntToPtr(V, Ty);
2206 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
2207 return IRB.CreatePtrToInt(V, Ty);
2208
2209 return IRB.CreateBitCast(V, Ty);
2210 }
2211
2212 bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
2213 Value *Result;
2214 if (LI.getType() == VecTy->getElementType() ||
2215 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002216 Result = IRB.CreateExtractElement(
2217 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
2218 getIndex(IRB, BeginOffset), getName(".extract"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002219 } else {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002220 Result = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2221 getName(".load"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002222 }
2223 if (Result->getType() != LI.getType())
2224 Result = getValueCast(IRB, Result, LI.getType());
2225 LI.replaceAllUsesWith(Result);
2226 Pass.DeadInsts.push_back(&LI);
2227
2228 DEBUG(dbgs() << " to: " << *Result << "\n");
2229 return true;
2230 }
2231
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002232 bool rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
2233 assert(!LI.isVolatile());
2234 Value *Result = extractInteger(IRB, cast<IntegerType>(LI.getType()),
2235 BeginOffset);
2236 LI.replaceAllUsesWith(Result);
2237 Pass.DeadInsts.push_back(&LI);
2238 DEBUG(dbgs() << " to: " << *Result << "\n");
2239 return true;
2240 }
2241
Chandler Carruth713aa942012-09-14 09:22:59 +00002242 bool visitLoadInst(LoadInst &LI) {
2243 DEBUG(dbgs() << " original: " << LI << "\n");
2244 Value *OldOp = LI.getOperand(0);
2245 assert(OldOp == OldPtr);
2246 IRBuilder<> IRB(&LI);
2247
2248 if (VecTy)
2249 return rewriteVectorizedLoadInst(IRB, LI, OldOp);
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002250 if (IntPromotionTy)
2251 return rewriteIntegerLoad(IRB, LI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002252
2253 Value *NewPtr = getAdjustedAllocaPtr(IRB,
2254 LI.getPointerOperand()->getType());
2255 LI.setOperand(0, NewPtr);
Chandler Carruth238fd152012-09-26 10:45:28 +00002256 if (LI.getAlignment())
2257 LI.setAlignment(MinAlign(NewAI.getAlignment(),
2258 BeginOffset - NewAllocaBeginOffset));
Chandler Carruth713aa942012-09-14 09:22:59 +00002259 DEBUG(dbgs() << " to: " << LI << "\n");
2260
2261 deleteIfTriviallyDead(OldOp);
2262 return NewPtr == &NewAI && !LI.isVolatile();
2263 }
2264
2265 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI,
2266 Value *OldOp) {
2267 Value *V = SI.getValueOperand();
2268 if (V->getType() == ElementTy ||
2269 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
2270 if (V->getType() != ElementTy)
2271 V = getValueCast(IRB, V, ElementTy);
Chandler Carruth81b001a2012-09-26 10:27:46 +00002272 LoadInst *LI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2273 getName(".load"));
2274 V = IRB.CreateInsertElement(LI, V, getIndex(IRB, BeginOffset),
Chandler Carruth713aa942012-09-14 09:22:59 +00002275 getName(".insert"));
2276 } else if (V->getType() != VecTy) {
2277 V = getValueCast(IRB, V, VecTy);
2278 }
Chandler Carruth81b001a2012-09-26 10:27:46 +00002279 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth713aa942012-09-14 09:22:59 +00002280 Pass.DeadInsts.push_back(&SI);
2281
2282 (void)Store;
2283 DEBUG(dbgs() << " to: " << *Store << "\n");
2284 return true;
2285 }
2286
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002287 bool rewriteIntegerStore(IRBuilder<> &IRB, StoreInst &SI) {
2288 assert(!SI.isVolatile());
2289 StoreInst *Store = insertInteger(IRB, SI.getValueOperand(), BeginOffset);
2290 Pass.DeadInsts.push_back(&SI);
2291 (void)Store;
2292 DEBUG(dbgs() << " to: " << *Store << "\n");
2293 return true;
2294 }
2295
Chandler Carruth713aa942012-09-14 09:22:59 +00002296 bool visitStoreInst(StoreInst &SI) {
2297 DEBUG(dbgs() << " original: " << SI << "\n");
2298 Value *OldOp = SI.getOperand(1);
2299 assert(OldOp == OldPtr);
2300 IRBuilder<> IRB(&SI);
2301
2302 if (VecTy)
2303 return rewriteVectorizedStoreInst(IRB, SI, OldOp);
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002304 if (IntPromotionTy)
2305 return rewriteIntegerStore(IRB, SI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002306
2307 Value *NewPtr = getAdjustedAllocaPtr(IRB,
2308 SI.getPointerOperand()->getType());
2309 SI.setOperand(1, NewPtr);
Chandler Carruth238fd152012-09-26 10:45:28 +00002310 if (SI.getAlignment())
2311 SI.setAlignment(MinAlign(NewAI.getAlignment(),
2312 BeginOffset - NewAllocaBeginOffset));
Chandler Carruth713aa942012-09-14 09:22:59 +00002313 DEBUG(dbgs() << " to: " << SI << "\n");
2314
2315 deleteIfTriviallyDead(OldOp);
2316 return NewPtr == &NewAI && !SI.isVolatile();
2317 }
2318
2319 bool visitMemSetInst(MemSetInst &II) {
2320 DEBUG(dbgs() << " original: " << II << "\n");
2321 IRBuilder<> IRB(&II);
2322 assert(II.getRawDest() == OldPtr);
2323
2324 // If the memset has a variable size, it cannot be split, just adjust the
2325 // pointer to the new alloca.
2326 if (!isa<Constant>(II.getLength())) {
2327 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002328
2329 Type *CstTy = II.getAlignmentCst()->getType();
2330 if (!NewAI.getAlignment())
2331 II.setAlignment(ConstantInt::get(CstTy, 0));
2332 else
2333 II.setAlignment(
2334 ConstantInt::get(CstTy, MinAlign(NewAI.getAlignment(),
2335 BeginOffset - NewAllocaBeginOffset)));
2336
Chandler Carruth713aa942012-09-14 09:22:59 +00002337 deleteIfTriviallyDead(OldPtr);
2338 return false;
2339 }
2340
2341 // Record this instruction for deletion.
2342 if (Pass.DeadSplitInsts.insert(&II))
2343 Pass.DeadInsts.push_back(&II);
2344
2345 Type *AllocaTy = NewAI.getAllocatedType();
2346 Type *ScalarTy = AllocaTy->getScalarType();
2347
2348 // If this doesn't map cleanly onto the alloca type, and that type isn't
2349 // a single value type, just emit a memset.
2350 if (!VecTy && (BeginOffset != NewAllocaBeginOffset ||
2351 EndOffset != NewAllocaEndOffset ||
2352 !AllocaTy->isSingleValueType() ||
2353 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
2354 Type *SizeTy = II.getLength()->getType();
2355 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
Chandler Carruth81b001a2012-09-26 10:27:46 +00002356 unsigned Align = 1;
2357 if (NewAI.getAlignment())
2358 Align = MinAlign(NewAI.getAlignment(),
2359 BeginOffset - NewAllocaBeginOffset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002360
2361 CallInst *New
2362 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2363 II.getRawDest()->getType()),
Chandler Carruth81b001a2012-09-26 10:27:46 +00002364 II.getValue(), Size, Align,
Chandler Carruth713aa942012-09-14 09:22:59 +00002365 II.isVolatile());
2366 (void)New;
2367 DEBUG(dbgs() << " to: " << *New << "\n");
2368 return false;
2369 }
2370
2371 // If we can represent this as a simple value, we have to build the actual
2372 // value to store, which requires expanding the byte present in memset to
2373 // a sensible representation for the alloca type. This is essentially
2374 // splatting the byte to a sufficiently wide integer, bitcasting to the
2375 // desired scalar type, and splatting it across any desired vector type.
2376 Value *V = II.getValue();
2377 IntegerType *VTy = cast<IntegerType>(V->getType());
2378 Type *IntTy = Type::getIntNTy(VTy->getContext(),
2379 TD.getTypeSizeInBits(ScalarTy));
2380 if (TD.getTypeSizeInBits(ScalarTy) > VTy->getBitWidth())
2381 V = IRB.CreateMul(IRB.CreateZExt(V, IntTy, getName(".zext")),
2382 ConstantExpr::getUDiv(
2383 Constant::getAllOnesValue(IntTy),
2384 ConstantExpr::getZExt(
2385 Constant::getAllOnesValue(V->getType()),
2386 IntTy)),
2387 getName(".isplat"));
2388 if (V->getType() != ScalarTy) {
2389 if (ScalarTy->isPointerTy())
2390 V = IRB.CreateIntToPtr(V, ScalarTy);
2391 else if (ScalarTy->isPrimitiveType() || ScalarTy->isVectorTy())
2392 V = IRB.CreateBitCast(V, ScalarTy);
2393 else if (ScalarTy->isIntegerTy())
2394 llvm_unreachable("Computed different integer types with equal widths");
2395 else
2396 llvm_unreachable("Invalid scalar type");
2397 }
2398
2399 // If this is an element-wide memset of a vectorizable alloca, insert it.
2400 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
2401 EndOffset < NewAllocaEndOffset)) {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002402 StoreInst *Store = IRB.CreateAlignedStore(
2403 IRB.CreateInsertElement(IRB.CreateAlignedLoad(&NewAI,
2404 NewAI.getAlignment(),
2405 getName(".load")),
2406 V, getIndex(IRB, BeginOffset),
Chandler Carruth713aa942012-09-14 09:22:59 +00002407 getName(".insert")),
Chandler Carruth81b001a2012-09-26 10:27:46 +00002408 &NewAI, NewAI.getAlignment());
Chandler Carruth713aa942012-09-14 09:22:59 +00002409 (void)Store;
2410 DEBUG(dbgs() << " to: " << *Store << "\n");
2411 return true;
2412 }
2413
2414 // Splat to a vector if needed.
2415 if (VectorType *VecTy = dyn_cast<VectorType>(AllocaTy)) {
2416 VectorType *SplatSourceTy = VectorType::get(V->getType(), 1);
2417 V = IRB.CreateShuffleVector(
2418 IRB.CreateInsertElement(UndefValue::get(SplatSourceTy), V,
2419 IRB.getInt32(0), getName(".vsplat.insert")),
2420 UndefValue::get(SplatSourceTy),
2421 ConstantVector::getSplat(VecTy->getNumElements(), IRB.getInt32(0)),
2422 getName(".vsplat.shuffle"));
2423 assert(V->getType() == VecTy);
2424 }
2425
Chandler Carruth81b001a2012-09-26 10:27:46 +00002426 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2427 II.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +00002428 (void)New;
2429 DEBUG(dbgs() << " to: " << *New << "\n");
2430 return !II.isVolatile();
2431 }
2432
2433 bool visitMemTransferInst(MemTransferInst &II) {
2434 // Rewriting of memory transfer instructions can be a bit tricky. We break
2435 // them into two categories: split intrinsics and unsplit intrinsics.
2436
2437 DEBUG(dbgs() << " original: " << II << "\n");
2438 IRBuilder<> IRB(&II);
2439
2440 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2441 bool IsDest = II.getRawDest() == OldPtr;
2442
2443 const AllocaPartitioning::MemTransferOffsets &MTO
2444 = P.getMemTransferOffsets(II);
2445
2446 // For unsplit intrinsics, we simply modify the source and destination
2447 // pointers in place. This isn't just an optimization, it is a matter of
2448 // correctness. With unsplit intrinsics we may be dealing with transfers
2449 // within a single alloca before SROA ran, or with transfers that have
2450 // a variable length. We may also be dealing with memmove instead of
2451 // memcpy, and so simply updating the pointers is the necessary for us to
2452 // update both source and dest of a single call.
2453 if (!MTO.IsSplittable) {
2454 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2455 if (IsDest)
2456 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2457 else
2458 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2459
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002460 Type *CstTy = II.getAlignmentCst()->getType();
2461 if (II.getAlignment() > 1)
2462 II.setAlignment(ConstantInt::get(
2463 CstTy, MinAlign(II.getAlignment(),
2464 MinAlign(NewAI.getAlignment(),
2465 BeginOffset - NewAllocaBeginOffset))));
2466
Chandler Carruth713aa942012-09-14 09:22:59 +00002467 DEBUG(dbgs() << " to: " << II << "\n");
2468 deleteIfTriviallyDead(OldOp);
2469 return false;
2470 }
2471 // For split transfer intrinsics we have an incredibly useful assurance:
2472 // the source and destination do not reside within the same alloca, and at
2473 // least one of them does not escape. This means that we can replace
2474 // memmove with memcpy, and we don't need to worry about all manner of
2475 // downsides to splitting and transforming the operations.
2476
2477 // Compute the relative offset within the transfer.
2478 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2479 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2480 : MTO.SourceBegin));
2481
2482 // If this doesn't map cleanly onto the alloca type, and that type isn't
2483 // a single value type, just emit a memcpy.
2484 bool EmitMemCpy
2485 = !VecTy && (BeginOffset != NewAllocaBeginOffset ||
2486 EndOffset != NewAllocaEndOffset ||
2487 !NewAI.getAllocatedType()->isSingleValueType());
2488
2489 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2490 // size hasn't been shrunk based on analysis of the viable range, this is
2491 // a no-op.
2492 if (EmitMemCpy && &OldAI == &NewAI) {
2493 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2494 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2495 // Ensure the start lines up.
2496 assert(BeginOffset == OrigBegin);
Benjamin Kramerd0807692012-09-14 13:08:09 +00002497 (void)OrigBegin;
Chandler Carruth713aa942012-09-14 09:22:59 +00002498
2499 // Rewrite the size as needed.
2500 if (EndOffset != OrigEnd)
2501 II.setLength(ConstantInt::get(II.getLength()->getType(),
2502 EndOffset - BeginOffset));
2503 return false;
2504 }
2505 // Record this instruction for deletion.
2506 if (Pass.DeadSplitInsts.insert(&II))
2507 Pass.DeadInsts.push_back(&II);
2508
2509 bool IsVectorElement = VecTy && (BeginOffset > NewAllocaBeginOffset ||
2510 EndOffset < NewAllocaEndOffset);
2511
2512 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2513 : II.getRawDest()->getType();
2514 if (!EmitMemCpy)
2515 OtherPtrTy = IsVectorElement ? VecTy->getElementType()->getPointerTo()
2516 : NewAI.getType();
2517
2518 // Compute the other pointer, folding as much as possible to produce
2519 // a single, simple GEP in most cases.
2520 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2521 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2522 getName("." + OtherPtr->getName()));
2523
Chandler Carruth81b001a2012-09-26 10:27:46 +00002524 unsigned Align = II.getAlignment();
2525 if (Align > 1)
2526 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2527 MinAlign(II.getAlignment(), NewAI.getAlignment()));
2528
Chandler Carruth713aa942012-09-14 09:22:59 +00002529 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2530 // alloca that should be re-examined after rewriting this instruction.
2531 if (AllocaInst *AI
2532 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Chandler Carruthb3dca3f2012-09-26 07:41:40 +00002533 Pass.Worklist.insert(AI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002534
2535 if (EmitMemCpy) {
2536 Value *OurPtr
2537 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2538 : II.getRawSource()->getType());
2539 Type *SizeTy = II.getLength()->getType();
2540 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2541
2542 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2543 IsDest ? OtherPtr : OurPtr,
Chandler Carruth81b001a2012-09-26 10:27:46 +00002544 Size, Align, II.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +00002545 (void)New;
2546 DEBUG(dbgs() << " to: " << *New << "\n");
2547 return false;
2548 }
2549
2550 Value *SrcPtr = OtherPtr;
2551 Value *DstPtr = &NewAI;
2552 if (!IsDest)
2553 std::swap(SrcPtr, DstPtr);
2554
2555 Value *Src;
2556 if (IsVectorElement && !IsDest) {
2557 // We have to extract rather than load.
Chandler Carruth81b001a2012-09-26 10:27:46 +00002558 Src = IRB.CreateExtractElement(
2559 IRB.CreateAlignedLoad(SrcPtr, Align, getName(".copyload")),
2560 getIndex(IRB, BeginOffset),
2561 getName(".copyextract"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002562 } else {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002563 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2564 getName(".copyload"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002565 }
2566
2567 if (IsVectorElement && IsDest) {
2568 // We have to insert into a loaded copy before storing.
Chandler Carruth81b001a2012-09-26 10:27:46 +00002569 Src = IRB.CreateInsertElement(
2570 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
2571 Src, getIndex(IRB, BeginOffset),
2572 getName(".insert"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002573 }
2574
Chandler Carruth81b001a2012-09-26 10:27:46 +00002575 StoreInst *Store = cast<StoreInst>(
2576 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2577 (void)Store;
Chandler Carruth713aa942012-09-14 09:22:59 +00002578 DEBUG(dbgs() << " to: " << *Store << "\n");
2579 return !II.isVolatile();
2580 }
2581
2582 bool visitIntrinsicInst(IntrinsicInst &II) {
2583 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2584 II.getIntrinsicID() == Intrinsic::lifetime_end);
2585 DEBUG(dbgs() << " original: " << II << "\n");
2586 IRBuilder<> IRB(&II);
2587 assert(II.getArgOperand(1) == OldPtr);
2588
2589 // Record this instruction for deletion.
2590 if (Pass.DeadSplitInsts.insert(&II))
2591 Pass.DeadInsts.push_back(&II);
2592
2593 ConstantInt *Size
2594 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2595 EndOffset - BeginOffset);
2596 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2597 Value *New;
2598 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2599 New = IRB.CreateLifetimeStart(Ptr, Size);
2600 else
2601 New = IRB.CreateLifetimeEnd(Ptr, Size);
2602
2603 DEBUG(dbgs() << " to: " << *New << "\n");
2604 return true;
2605 }
2606
Chandler Carruth713aa942012-09-14 09:22:59 +00002607 bool visitPHINode(PHINode &PN) {
2608 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002609
Chandler Carruth713aa942012-09-14 09:22:59 +00002610 // We would like to compute a new pointer in only one place, but have it be
2611 // as local as possible to the PHI. To do that, we re-use the location of
2612 // the old pointer, which necessarily must be in the right position to
2613 // dominate the PHI.
2614 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2615
Chandler Carruth713aa942012-09-14 09:22:59 +00002616 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002617 // Replace the operands which were using the old pointer.
2618 User::op_iterator OI = PN.op_begin(), OE = PN.op_end();
2619 for (; OI != OE; ++OI)
2620 if (*OI == OldPtr)
2621 *OI = NewPtr;
Chandler Carruth713aa942012-09-14 09:22:59 +00002622
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002623 DEBUG(dbgs() << " to: " << PN << "\n");
2624 deleteIfTriviallyDead(OldPtr);
2625 return false;
Chandler Carruth713aa942012-09-14 09:22:59 +00002626 }
2627
2628 bool visitSelectInst(SelectInst &SI) {
2629 DEBUG(dbgs() << " original: " << SI << "\n");
2630 IRBuilder<> IRB(&SI);
2631
2632 // Find the operand we need to rewrite here.
2633 bool IsTrueVal = SI.getTrueValue() == OldPtr;
2634 if (IsTrueVal)
2635 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
2636 else
2637 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002638
Chandler Carruth713aa942012-09-14 09:22:59 +00002639 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002640 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
2641 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth713aa942012-09-14 09:22:59 +00002642 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002643 return false;
Chandler Carruth713aa942012-09-14 09:22:59 +00002644 }
2645
2646};
2647}
2648
Chandler Carruthc370acd2012-09-18 12:57:43 +00002649namespace {
2650/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2651///
2652/// This pass aggressively rewrites all aggregate loads and stores on
2653/// a particular pointer (or any pointer derived from it which we can identify)
2654/// with scalar loads and stores.
2655class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2656 // Befriend the base class so it can delegate to private visit methods.
2657 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2658
2659 const TargetData &TD;
2660
2661 /// Queue of pointer uses to analyze and potentially rewrite.
2662 SmallVector<Use *, 8> Queue;
2663
2664 /// Set to prevent us from cycling with phi nodes and loops.
2665 SmallPtrSet<User *, 8> Visited;
2666
2667 /// The current pointer use being rewritten. This is used to dig up the used
2668 /// value (as opposed to the user).
2669 Use *U;
2670
2671public:
2672 AggLoadStoreRewriter(const TargetData &TD) : TD(TD) {}
2673
2674 /// Rewrite loads and stores through a pointer and all pointers derived from
2675 /// it.
2676 bool rewrite(Instruction &I) {
2677 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2678 enqueueUsers(I);
2679 bool Changed = false;
2680 while (!Queue.empty()) {
2681 U = Queue.pop_back_val();
2682 Changed |= visit(cast<Instruction>(U->getUser()));
2683 }
2684 return Changed;
2685 }
2686
2687private:
2688 /// Enqueue all the users of the given instruction for further processing.
2689 /// This uses a set to de-duplicate users.
2690 void enqueueUsers(Instruction &I) {
2691 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2692 ++UI)
2693 if (Visited.insert(*UI))
2694 Queue.push_back(&UI.getUse());
2695 }
2696
2697 // Conservative default is to not rewrite anything.
2698 bool visitInstruction(Instruction &I) { return false; }
2699
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002700 /// \brief Generic recursive split emission class.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002701 template <typename Derived>
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002702 class OpSplitter {
2703 protected:
2704 /// The builder used to form new instructions.
2705 IRBuilder<> IRB;
2706 /// The indices which to be used with insert- or extractvalue to select the
2707 /// appropriate value within the aggregate.
2708 SmallVector<unsigned, 4> Indices;
2709 /// The indices to a GEP instruction which will move Ptr to the correct slot
2710 /// within the aggregate.
2711 SmallVector<Value *, 4> GEPIndices;
2712 /// The base pointer of the original op, used as a base for GEPing the
2713 /// split operations.
2714 Value *Ptr;
Chandler Carruthc370acd2012-09-18 12:57:43 +00002715
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002716 /// Initialize the splitter with an insertion point, Ptr and start with a
2717 /// single zero GEP index.
2718 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002719 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002720
2721 public:
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002722 /// \brief Generic recursive split emission routine.
2723 ///
2724 /// This method recursively splits an aggregate op (load or store) into
2725 /// scalar or vector ops. It splits recursively until it hits a single value
2726 /// and emits that single value operation via the template argument.
2727 ///
2728 /// The logic of this routine relies on GEPs and insertvalue and
2729 /// extractvalue all operating with the same fundamental index list, merely
2730 /// formatted differently (GEPs need actual values).
2731 ///
2732 /// \param Ty The type being split recursively into smaller ops.
2733 /// \param Agg The aggregate value being built up or stored, depending on
2734 /// whether this is splitting a load or a store respectively.
2735 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2736 if (Ty->isSingleValueType())
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002737 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002738
2739 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2740 unsigned OldSize = Indices.size();
2741 (void)OldSize;
2742 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2743 ++Idx) {
2744 assert(Indices.size() == OldSize && "Did not return to the old size");
2745 Indices.push_back(Idx);
2746 GEPIndices.push_back(IRB.getInt32(Idx));
2747 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2748 GEPIndices.pop_back();
2749 Indices.pop_back();
2750 }
2751 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00002752 }
Chandler Carruthc370acd2012-09-18 12:57:43 +00002753
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002754 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2755 unsigned OldSize = Indices.size();
2756 (void)OldSize;
2757 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2758 ++Idx) {
2759 assert(Indices.size() == OldSize && "Did not return to the old size");
2760 Indices.push_back(Idx);
2761 GEPIndices.push_back(IRB.getInt32(Idx));
2762 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2763 GEPIndices.pop_back();
2764 Indices.pop_back();
2765 }
2766 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00002767 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002768
2769 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruthc370acd2012-09-18 12:57:43 +00002770 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002771 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00002772
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002773 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002774 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00002775 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruthc370acd2012-09-18 12:57:43 +00002776
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002777 /// Emit a leaf load of a single value. This is called at the leaves of the
2778 /// recursive emission to actually load values.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002779 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002780 assert(Ty->isSingleValueType());
2781 // Load the single value and insert it using the indices.
2782 Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices,
2783 Name + ".gep"),
2784 Name + ".load");
2785 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2786 DEBUG(dbgs() << " to: " << *Load << "\n");
2787 }
2788 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00002789
2790 bool visitLoadInst(LoadInst &LI) {
2791 assert(LI.getPointerOperand() == *U);
2792 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2793 return false;
2794
2795 // We have an aggregate being loaded, split it apart.
2796 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002797 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruthc370acd2012-09-18 12:57:43 +00002798 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002799 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00002800 LI.replaceAllUsesWith(V);
2801 LI.eraseFromParent();
2802 return true;
2803 }
2804
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002805 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002806 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00002807 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002808
2809 /// Emit a leaf store of a single value. This is called at the leaves of the
2810 /// recursive emission to actually produce stores.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002811 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002812 assert(Ty->isSingleValueType());
2813 // Extract the single value and store it using the indices.
2814 Value *Store = IRB.CreateStore(
2815 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2816 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2817 (void)Store;
2818 DEBUG(dbgs() << " to: " << *Store << "\n");
2819 }
2820 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00002821
2822 bool visitStoreInst(StoreInst &SI) {
2823 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2824 return false;
2825 Value *V = SI.getValueOperand();
2826 if (V->getType()->isSingleValueType())
2827 return false;
2828
2829 // We have an aggregate being stored, split it apart.
2830 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002831 StoreOpSplitter Splitter(&SI, *U);
2832 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00002833 SI.eraseFromParent();
2834 return true;
2835 }
2836
2837 bool visitBitCastInst(BitCastInst &BC) {
2838 enqueueUsers(BC);
2839 return false;
2840 }
2841
2842 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2843 enqueueUsers(GEPI);
2844 return false;
2845 }
2846
2847 bool visitPHINode(PHINode &PN) {
2848 enqueueUsers(PN);
2849 return false;
2850 }
2851
2852 bool visitSelectInst(SelectInst &SI) {
2853 enqueueUsers(SI);
2854 return false;
2855 }
2856};
2857}
2858
Chandler Carruth713aa942012-09-14 09:22:59 +00002859/// \brief Try to find a partition of the aggregate type passed in for a given
2860/// offset and size.
2861///
2862/// This recurses through the aggregate type and tries to compute a subtype
2863/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth6b547a22012-09-14 11:08:31 +00002864/// of an array, it will even compute a new array type for that sub-section,
2865/// and the same for structs.
2866///
2867/// Note that this routine is very strict and tries to find a partition of the
2868/// type which produces the *exact* right offset and size. It is not forgiving
2869/// when the size or offset cause either end of type-based partition to be off.
2870/// Also, this is a best-effort routine. It is reasonable to give up and not
2871/// return a type if necessary.
Chandler Carruth713aa942012-09-14 09:22:59 +00002872static Type *getTypePartition(const TargetData &TD, Type *Ty,
2873 uint64_t Offset, uint64_t Size) {
2874 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
2875 return Ty;
2876
2877 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2878 // We can't partition pointers...
2879 if (SeqTy->isPointerTy())
2880 return 0;
2881
2882 Type *ElementTy = SeqTy->getElementType();
2883 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2884 uint64_t NumSkippedElements = Offset / ElementSize;
2885 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
2886 if (NumSkippedElements >= ArrTy->getNumElements())
2887 return 0;
2888 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
2889 if (NumSkippedElements >= VecTy->getNumElements())
2890 return 0;
2891 Offset -= NumSkippedElements * ElementSize;
2892
2893 // First check if we need to recurse.
2894 if (Offset > 0 || Size < ElementSize) {
2895 // Bail if the partition ends in a different array element.
2896 if ((Offset + Size) > ElementSize)
2897 return 0;
2898 // Recurse through the element type trying to peel off offset bytes.
2899 return getTypePartition(TD, ElementTy, Offset, Size);
2900 }
2901 assert(Offset == 0);
2902
2903 if (Size == ElementSize)
2904 return ElementTy;
2905 assert(Size > ElementSize);
2906 uint64_t NumElements = Size / ElementSize;
2907 if (NumElements * ElementSize != Size)
2908 return 0;
2909 return ArrayType::get(ElementTy, NumElements);
2910 }
2911
2912 StructType *STy = dyn_cast<StructType>(Ty);
2913 if (!STy)
2914 return 0;
2915
2916 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00002917 if (Offset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00002918 return 0;
2919 uint64_t EndOffset = Offset + Size;
2920 if (EndOffset > SL->getSizeInBytes())
2921 return 0;
2922
2923 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002924 Offset -= SL->getElementOffset(Index);
2925
2926 Type *ElementTy = STy->getElementType(Index);
2927 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2928 if (Offset >= ElementSize)
2929 return 0; // The offset points into alignment padding.
2930
2931 // See if any partition must be contained by the element.
2932 if (Offset > 0 || Size < ElementSize) {
2933 if ((Offset + Size) > ElementSize)
2934 return 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00002935 return getTypePartition(TD, ElementTy, Offset, Size);
2936 }
2937 assert(Offset == 0);
2938
2939 if (Size == ElementSize)
2940 return ElementTy;
2941
2942 StructType::element_iterator EI = STy->element_begin() + Index,
2943 EE = STy->element_end();
2944 if (EndOffset < SL->getSizeInBytes()) {
2945 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
2946 if (Index == EndIndex)
2947 return 0; // Within a single element and its padding.
Chandler Carruth6b547a22012-09-14 11:08:31 +00002948
2949 // Don't try to form "natural" types if the elements don't line up with the
2950 // expected size.
2951 // FIXME: We could potentially recurse down through the last element in the
2952 // sub-struct to find a natural end point.
2953 if (SL->getElementOffset(EndIndex) != EndOffset)
2954 return 0;
2955
Chandler Carruth713aa942012-09-14 09:22:59 +00002956 assert(Index < EndIndex);
Chandler Carruth713aa942012-09-14 09:22:59 +00002957 EE = STy->element_begin() + EndIndex;
2958 }
2959
2960 // Try to build up a sub-structure.
2961 SmallVector<Type *, 4> ElementTys;
2962 do {
2963 ElementTys.push_back(*EI++);
2964 } while (EI != EE);
2965 StructType *SubTy = StructType::get(STy->getContext(), ElementTys,
2966 STy->isPacked());
2967 const StructLayout *SubSL = TD.getStructLayout(SubTy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00002968 if (Size != SubSL->getSizeInBytes())
2969 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth713aa942012-09-14 09:22:59 +00002970
Chandler Carruth6b547a22012-09-14 11:08:31 +00002971 return SubTy;
Chandler Carruth713aa942012-09-14 09:22:59 +00002972}
2973
2974/// \brief Rewrite an alloca partition's users.
2975///
2976/// This routine drives both of the rewriting goals of the SROA pass. It tries
2977/// to rewrite uses of an alloca partition to be conducive for SSA value
2978/// promotion. If the partition needs a new, more refined alloca, this will
2979/// build that new alloca, preserving as much type information as possible, and
2980/// rewrite the uses of the old alloca to point at the new one and have the
2981/// appropriate new offsets. It also evaluates how successful the rewrite was
2982/// at enabling promotion and if it was successful queues the alloca to be
2983/// promoted.
2984bool SROA::rewriteAllocaPartition(AllocaInst &AI,
2985 AllocaPartitioning &P,
2986 AllocaPartitioning::iterator PI) {
2987 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
2988 if (P.use_begin(PI) == P.use_end(PI))
2989 return false; // No live uses left of this partition.
2990
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002991 DEBUG(dbgs() << "Speculating PHIs and selects in partition "
2992 << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
2993
2994 PHIOrSelectSpeculator Speculator(*TD, P, *this);
2995 DEBUG(dbgs() << " speculating ");
2996 DEBUG(P.print(dbgs(), PI, ""));
2997 Speculator.visitUsers(P.use_begin(PI), P.use_end(PI));
2998
Chandler Carruth713aa942012-09-14 09:22:59 +00002999 // Try to compute a friendly type for this partition of the alloca. This
3000 // won't always succeed, in which case we fall back to a legal integer type
3001 // or an i8 array of an appropriate size.
3002 Type *AllocaTy = 0;
3003 if (Type *PartitionTy = P.getCommonType(PI))
3004 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
3005 AllocaTy = PartitionTy;
3006 if (!AllocaTy)
3007 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3008 PI->BeginOffset, AllocaSize))
3009 AllocaTy = PartitionTy;
3010 if ((!AllocaTy ||
3011 (AllocaTy->isArrayTy() &&
3012 AllocaTy->getArrayElementType()->isIntegerTy())) &&
3013 TD->isLegalInteger(AllocaSize * 8))
3014 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
3015 if (!AllocaTy)
3016 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
Chandler Carruthb3dd9a12012-09-14 10:26:34 +00003017 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00003018
3019 // Check for the case where we're going to rewrite to a new alloca of the
3020 // exact same type as the original, and with the same access offsets. In that
3021 // case, re-use the existing alloca, but still run through the rewriter to
3022 // performe phi and select speculation.
3023 AllocaInst *NewAI;
3024 if (AllocaTy == AI.getAllocatedType()) {
3025 assert(PI->BeginOffset == 0 &&
3026 "Non-zero begin offset but same alloca type");
3027 assert(PI == P.begin() && "Begin offset is zero on later partition");
3028 NewAI = &AI;
3029 } else {
Chandler Carruthb67c9a52012-09-29 10:41:21 +00003030 unsigned Alignment = AI.getAlignment();
3031 if (!Alignment) {
3032 // The minimum alignment which users can rely on when the explicit
3033 // alignment is omitted or zero is that required by the ABI for this
3034 // type.
3035 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3036 }
3037 Alignment = MinAlign(Alignment, PI->BeginOffset);
3038 // If we will get at least this much alignment from the type alone, leave
3039 // the alloca's alignment unconstrained.
3040 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3041 Alignment = 0;
3042 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
Chandler Carruth713aa942012-09-14 09:22:59 +00003043 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3044 &AI);
3045 ++NumNewAllocas;
3046 }
3047
3048 DEBUG(dbgs() << "Rewriting alloca partition "
3049 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3050 << *NewAI << "\n");
3051
3052 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3053 PI->BeginOffset, PI->EndOffset);
3054 DEBUG(dbgs() << " rewriting ");
3055 DEBUG(P.print(dbgs(), PI, ""));
3056 if (Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI))) {
3057 DEBUG(dbgs() << " and queuing for promotion\n");
3058 PromotableAllocas.push_back(NewAI);
3059 } else if (NewAI != &AI) {
3060 // If we can't promote the alloca, iterate on it to check for new
3061 // refinements exposed by splitting the current alloca. Don't iterate on an
3062 // alloca which didn't actually change and didn't get promoted.
3063 Worklist.insert(NewAI);
3064 }
3065 return true;
3066}
3067
3068/// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3069bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3070 bool Changed = false;
3071 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3072 ++PI)
3073 Changed |= rewriteAllocaPartition(AI, P, PI);
3074
3075 return Changed;
3076}
3077
3078/// \brief Analyze an alloca for SROA.
3079///
3080/// This analyzes the alloca to ensure we can reason about it, builds
3081/// a partitioning of the alloca, and then hands it off to be split and
3082/// rewritten as needed.
3083bool SROA::runOnAlloca(AllocaInst &AI) {
3084 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3085 ++NumAllocasAnalyzed;
3086
3087 // Special case dead allocas, as they're trivial.
3088 if (AI.use_empty()) {
3089 AI.eraseFromParent();
3090 return true;
3091 }
3092
3093 // Skip alloca forms that this analysis can't handle.
3094 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3095 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3096 return false;
3097
3098 // First check if this is a non-aggregate type that we should simply promote.
3099 if (!AI.getAllocatedType()->isAggregateType() && isAllocaPromotable(&AI)) {
3100 DEBUG(dbgs() << " Trivially scalar type, queuing for promotion...\n");
3101 PromotableAllocas.push_back(&AI);
3102 return false;
3103 }
3104
Chandler Carruthc370acd2012-09-18 12:57:43 +00003105 bool Changed = false;
3106
3107 // First, split any FCA loads and stores touching this alloca to promote
3108 // better splitting and promotion opportunities.
3109 AggLoadStoreRewriter AggRewriter(*TD);
3110 Changed |= AggRewriter.rewrite(AI);
3111
Chandler Carruth713aa942012-09-14 09:22:59 +00003112 // Build the partition set using a recursive instruction-visiting builder.
3113 AllocaPartitioning P(*TD, AI);
3114 DEBUG(P.print(dbgs()));
3115 if (P.isEscaped())
Chandler Carruthc370acd2012-09-18 12:57:43 +00003116 return Changed;
Chandler Carruth713aa942012-09-14 09:22:59 +00003117
3118 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3119 if (P.begin() == P.end())
Chandler Carruthc370acd2012-09-18 12:57:43 +00003120 return Changed;
Chandler Carruth713aa942012-09-14 09:22:59 +00003121
3122 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth713aa942012-09-14 09:22:59 +00003123 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3124 DE = P.dead_user_end();
3125 DI != DE; ++DI) {
3126 Changed = true;
3127 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3128 DeadInsts.push_back(*DI);
3129 }
3130 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3131 DE = P.dead_op_end();
3132 DO != DE; ++DO) {
3133 Value *OldV = **DO;
3134 // Clobber the use with an undef value.
3135 **DO = UndefValue::get(OldV->getType());
3136 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3137 if (isInstructionTriviallyDead(OldI)) {
3138 Changed = true;
3139 DeadInsts.push_back(OldI);
3140 }
3141 }
3142
3143 return splitAlloca(AI, P) || Changed;
3144}
3145
Chandler Carruth8615cd22012-09-14 10:26:38 +00003146/// \brief Delete the dead instructions accumulated in this run.
3147///
3148/// Recursively deletes the dead instructions we've accumulated. This is done
3149/// at the very end to maximize locality of the recursive delete and to
3150/// minimize the problems of invalidated instruction pointers as such pointers
3151/// are used heavily in the intermediate stages of the algorithm.
3152///
3153/// We also record the alloca instructions deleted here so that they aren't
3154/// subsequently handed to mem2reg to promote.
3155void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth713aa942012-09-14 09:22:59 +00003156 DeadSplitInsts.clear();
3157 while (!DeadInsts.empty()) {
3158 Instruction *I = DeadInsts.pop_back_val();
3159 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3160
3161 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3162 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3163 // Zero out the operand and see if it becomes trivially dead.
3164 *OI = 0;
3165 if (isInstructionTriviallyDead(U))
3166 DeadInsts.push_back(U);
3167 }
3168
3169 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3170 DeletedAllocas.insert(AI);
3171
3172 ++NumDeleted;
3173 I->eraseFromParent();
3174 }
3175}
3176
Chandler Carruth1c8db502012-09-15 11:43:14 +00003177/// \brief Promote the allocas, using the best available technique.
3178///
3179/// This attempts to promote whatever allocas have been identified as viable in
3180/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3181/// If there is a domtree available, we attempt to promote using the full power
3182/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3183/// based on the SSAUpdater utilities. This function returns whether any
3184/// promotion occured.
3185bool SROA::promoteAllocas(Function &F) {
3186 if (PromotableAllocas.empty())
3187 return false;
3188
3189 NumPromoted += PromotableAllocas.size();
3190
3191 if (DT && !ForceSSAUpdater) {
3192 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3193 PromoteMemToReg(PromotableAllocas, *DT);
3194 PromotableAllocas.clear();
3195 return true;
3196 }
3197
3198 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3199 SSAUpdater SSA;
3200 DIBuilder DIB(*F.getParent());
3201 SmallVector<Instruction*, 64> Insts;
3202
3203 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3204 AllocaInst *AI = PromotableAllocas[Idx];
3205 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3206 UI != UE;) {
3207 Instruction *I = cast<Instruction>(*UI++);
3208 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3209 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3210 // leading to them) here. Eventually it should use them to optimize the
3211 // scalar values produced.
3212 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3213 assert(onlyUsedByLifetimeMarkers(I) &&
3214 "Found a bitcast used outside of a lifetime marker.");
3215 while (!I->use_empty())
3216 cast<Instruction>(*I->use_begin())->eraseFromParent();
3217 I->eraseFromParent();
3218 continue;
3219 }
3220 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3221 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3222 II->getIntrinsicID() == Intrinsic::lifetime_end);
3223 II->eraseFromParent();
3224 continue;
3225 }
3226
3227 Insts.push_back(I);
3228 }
3229 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3230 Insts.clear();
3231 }
3232
3233 PromotableAllocas.clear();
3234 return true;
3235}
3236
Chandler Carruth713aa942012-09-14 09:22:59 +00003237namespace {
3238 /// \brief A predicate to test whether an alloca belongs to a set.
3239 class IsAllocaInSet {
3240 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3241 const SetType &Set;
3242
3243 public:
3244 IsAllocaInSet(const SetType &Set) : Set(Set) {}
3245 bool operator()(AllocaInst *AI) { return Set.count(AI); }
3246 };
3247}
3248
3249bool SROA::runOnFunction(Function &F) {
3250 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3251 C = &F.getContext();
3252 TD = getAnalysisIfAvailable<TargetData>();
3253 if (!TD) {
3254 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3255 return false;
3256 }
Chandler Carruth1c8db502012-09-15 11:43:14 +00003257 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003258
3259 BasicBlock &EntryBB = F.getEntryBlock();
3260 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3261 I != E; ++I)
3262 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3263 Worklist.insert(AI);
3264
3265 bool Changed = false;
Chandler Carruth8615cd22012-09-14 10:26:38 +00003266 // A set of deleted alloca instruction pointers which should be removed from
3267 // the list of promotable allocas.
3268 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3269
Chandler Carruth713aa942012-09-14 09:22:59 +00003270 while (!Worklist.empty()) {
3271 Changed |= runOnAlloca(*Worklist.pop_back_val());
Chandler Carruth8615cd22012-09-14 10:26:38 +00003272 deleteDeadInstructions(DeletedAllocas);
Chandler Carruth713aa942012-09-14 09:22:59 +00003273 if (!DeletedAllocas.empty()) {
3274 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3275 PromotableAllocas.end(),
3276 IsAllocaInSet(DeletedAllocas)),
3277 PromotableAllocas.end());
3278 DeletedAllocas.clear();
3279 }
3280 }
3281
Chandler Carruth1c8db502012-09-15 11:43:14 +00003282 Changed |= promoteAllocas(F);
Chandler Carruth713aa942012-09-14 09:22:59 +00003283
3284 return Changed;
3285}
3286
3287void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth1c8db502012-09-15 11:43:14 +00003288 if (RequiresDomTree)
3289 AU.addRequired<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003290 AU.setPreservesCFG();
3291}