blob: b968cb8c892b05c94cb571db9c64eab1fe1afb71 [file] [log] [blame]
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This transformation implements the well known scalar replacement of
11/// aggregates transformation. It tries to identify promotable elements of an
12/// aggregate alloca, and promote them to registers. It will also try to
13/// convert uses of an element (or set of elements) of an alloca into a vector
14/// or bitfield-style integer scalar if appropriate.
15///
16/// It works to do this with minimal slicing of the alloca so that regions
17/// which are merely transferred in and out of external memory remain unchanged
18/// and are not decomposed to scalar code.
19///
20/// Because this also performs alloca promotion, it can be thought of as also
21/// serving the purpose of SSA formation. The algorithm iterates on the
22/// function until all opportunities for promotion have been realized.
23///
24//===----------------------------------------------------------------------===//
25
Chandler Carruth29a18a42015-09-12 09:09:14 +000026#include "llvm/Transforms/Scalar/SROA.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000027#include "llvm/ADT/APInt.h"
28#include "llvm/ADT/ArrayRef.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/PointerIntPair.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/ADT/STLExtras.h"
Davide Italiano81a26da2017-04-27 23:09:01 +000032#include "llvm/ADT/SetVector.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000033#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/Statistic.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000036#include "llvm/ADT/StringRef.h"
37#include "llvm/ADT/Twine.h"
38#include "llvm/ADT/iterator.h"
39#include "llvm/ADT/iterator_range.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000040#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +000041#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000042#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000043#include "llvm/Analysis/PtrUseVisitor.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000044#include "llvm/IR/BasicBlock.h"
45#include "llvm/IR/Constant.h"
46#include "llvm/IR/ConstantFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000048#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/DataLayout.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000050#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000052#include "llvm/IR/Dominators.h"
53#include "llvm/IR/Function.h"
54#include "llvm/IR/GetElementPtrTypeIterator.h"
55#include "llvm/IR/GlobalAlias.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/IRBuilder.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000057#include "llvm/IR/InstVisitor.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000058#include "llvm/IR/InstrTypes.h"
59#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000060#include "llvm/IR/Instructions.h"
61#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000062#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000063#include "llvm/IR/LLVMContext.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000064#include "llvm/IR/Metadata.h"
65#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000066#include "llvm/IR/Operator.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000067#include "llvm/IR/PassManager.h"
68#include "llvm/IR/Type.h"
69#include "llvm/IR/Use.h"
70#include "llvm/IR/User.h"
71#include "llvm/IR/Value.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000072#include "llvm/Pass.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000073#include "llvm/Support/Casting.h"
Chandler Carruth70b44c52012-09-15 11:43:14 +000074#include "llvm/Support/CommandLine.h"
Chandler Carruthf0546402013-07-18 07:15:00 +000075#include "llvm/Support/Compiler.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000076#include "llvm/Support/Debug.h"
77#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000078#include "llvm/Support/MathExtras.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000079#include "llvm/Support/raw_ostream.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +000080#include "llvm/Transforms/Scalar.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000081#include "llvm/Transforms/Utils/Local.h"
82#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000083#include <algorithm>
84#include <cassert>
85#include <chrono>
86#include <cstddef>
87#include <cstdint>
88#include <cstring>
89#include <iterator>
90#include <string>
91#include <tuple>
92#include <utility>
93#include <vector>
Chandler Carruth83cee772014-02-25 03:59:29 +000094
Hal Finkel29f51312016-03-28 11:13:03 +000095#ifndef NDEBUG
96// We only use this for a debug check.
Chandler Carruth83cee772014-02-25 03:59:29 +000097#include <random>
98#endif
99
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000100using namespace llvm;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000101using namespace llvm::sroa;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000102
Chandler Carruth964daaa2014-04-22 02:55:47 +0000103#define DEBUG_TYPE "sroa"
104
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000105STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000106STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +0000107STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
108STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
109STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000110STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
111STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000112STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000113STATISTIC(NumDeleted, "Number of instructions deleted");
114STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000115
Chandler Carruth83cee772014-02-25 03:59:29 +0000116/// Hidden option to enable randomly shuffling the slices to help uncover
117/// instability in their order.
118static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
119 cl::init(false), cl::Hidden);
120
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000121/// Hidden option to experiment with completely strict handling of inbounds
122/// GEPs.
Chandler Carruth113dc642014-12-20 02:39:18 +0000123static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
124 cl::Hidden);
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000125
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000126namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000127
Mehdi Amini1e9c9252016-03-11 17:15:34 +0000128/// \brief A custom IRBuilder inserter which prefixes all names, but only in
129/// Assert builds.
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000130class IRBuilderPrefixedInserter : public IRBuilderDefaultInserter {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000131 std::string Prefix;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000132
Zachary Turner41a9ee92017-10-11 23:54:34 +0000133 const Twine getNameWithPrefix(const Twine &Name) const {
134 return Name.isTriviallyEmpty() ? Name : Prefix + Name;
135 }
136
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000137public:
138 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
139
140protected:
141 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
142 BasicBlock::iterator InsertPt) const {
Zachary Turner41a9ee92017-10-11 23:54:34 +0000143 IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name), BB,
144 InsertPt);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000145 }
146};
147
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000148/// \brief Provide a type for IRBuilder that drops names in release builds.
149using IRBuilderTy = IRBuilder<ConstantFolder, IRBuilderPrefixedInserter>;
Chandler Carruthd177f862013-03-20 07:30:36 +0000150
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000151/// \brief A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000152///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000153/// This structure represents a slice of an alloca used by some instruction. It
154/// stores both the begin and end offsets of this use, a pointer to the use
155/// itself, and a flag indicating whether we can classify the use as splittable
156/// or not when forming partitions of the alloca.
157class Slice {
Chandler Carruthf74654d2013-03-18 08:36:46 +0000158 /// \brief The beginning offset of the range.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000159 uint64_t BeginOffset = 0;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000160
161 /// \brief The ending offset, not included in the range.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000162 uint64_t EndOffset = 0;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000163
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000164 /// \brief Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000165 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000166 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000167
168public:
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000169 Slice() = default;
170
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000171 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000172 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000173 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000174
175 uint64_t beginOffset() const { return BeginOffset; }
176 uint64_t endOffset() const { return EndOffset; }
177
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000178 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
179 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000180
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000181 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000182
Craig Topperf40110f2014-04-25 05:29:35 +0000183 bool isDead() const { return getUse() == nullptr; }
184 void kill() { UseAndIsSplittable.setPointer(nullptr); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000185
186 /// \brief Support for ordering ranges.
187 ///
188 /// This provides an ordering over ranges such that start offsets are
189 /// always increasing, and within equal start offsets, the end offsets are
190 /// decreasing. Thus the spanning range comes first in a cluster with the
191 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000192 bool operator<(const Slice &RHS) const {
Chandler Carruth113dc642014-12-20 02:39:18 +0000193 if (beginOffset() < RHS.beginOffset())
194 return true;
195 if (beginOffset() > RHS.beginOffset())
196 return false;
197 if (isSplittable() != RHS.isSplittable())
198 return !isSplittable();
199 if (endOffset() > RHS.endOffset())
200 return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000201 return false;
202 }
203
204 /// \brief Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000205 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000206 uint64_t RHSOffset) {
207 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000208 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000209 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000210 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000211 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000212 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000213
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000214 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000215 return isSplittable() == RHS.isSplittable() &&
216 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000217 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000218 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000219};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000220
Chandler Carruthf0546402013-07-18 07:15:00 +0000221} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000222
223namespace llvm {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000224
Chandler Carruthf0546402013-07-18 07:15:00 +0000225template <typename T> struct isPodLike;
Chandler Carruth113dc642014-12-20 02:39:18 +0000226template <> struct isPodLike<Slice> { static const bool value = true; };
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000227
228} // end namespace llvm
Chandler Carruthf74654d2013-03-18 08:36:46 +0000229
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000230/// \brief Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000231///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000232/// This class represents the slices of an alloca which are formed by its
233/// various uses. If a pointer escapes, we can't fully build a representation
234/// for the slices used and we reflect that in this structure. The uses are
235/// stored, sorted by increasing beginning offset and with unsplittable slices
236/// starting at a particular offset before splittable slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000237class llvm::sroa::AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000238public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000239 /// \brief Construct the slices of a particular alloca.
240 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000241
242 /// \brief Test whether a pointer to the allocation escapes our analysis.
243 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000244 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000245 /// ignored.
246 bool isEscaped() const { return PointerEscapingInstr; }
247
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000248 /// \brief Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000249 /// @{
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000250 using iterator = SmallVectorImpl<Slice>::iterator;
251 using range = iterator_range<iterator>;
252
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000253 iterator begin() { return Slices.begin(); }
254 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000255
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000256 using const_iterator = SmallVectorImpl<Slice>::const_iterator;
257 using const_range = iterator_range<const_iterator>;
258
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000259 const_iterator begin() const { return Slices.begin(); }
260 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000261 /// @}
262
Chandler Carruth0715cba2015-01-01 11:54:38 +0000263 /// \brief Erase a range of slices.
Chandler Carruth994cde82015-01-01 12:01:03 +0000264 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
Chandler Carruth0715cba2015-01-01 11:54:38 +0000265
266 /// \brief Insert new slices for this alloca.
267 ///
268 /// This moves the slices into the alloca's slices collection, and re-sorts
269 /// everything so that the usual ordering properties of the alloca's slices
270 /// hold.
271 void insert(ArrayRef<Slice> NewSlices) {
272 int OldSize = Slices.size();
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000273 Slices.append(NewSlices.begin(), NewSlices.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +0000274 auto SliceI = Slices.begin() + OldSize;
275 std::sort(SliceI, Slices.end());
276 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
277 }
278
Chandler Carruth29a18a42015-09-12 09:09:14 +0000279 // Forward declare the iterator and range accessor for walking the
280 // partitions.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000281 class partition_iterator;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000282 iterator_range<partition_iterator> partitions();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000283
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000284 /// \brief Access the dead users for this alloca.
285 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000286
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000287 /// \brief Access the dead operands referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000288 ///
289 /// These are operands which have cannot actually be used to refer to the
290 /// alloca as they are outside its range and the user doesn't correct for
291 /// that. These mostly consist of PHI node inputs and the like which we just
292 /// need to replace with undef.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000293 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000294
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000295#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000296 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000297 void printSlice(raw_ostream &OS, const_iterator I,
298 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000299 void printUse(raw_ostream &OS, const_iterator I,
300 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000301 void print(raw_ostream &OS) const;
Alp Tokerf929e092014-01-04 22:47:48 +0000302 void dump(const_iterator I) const;
303 void dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000304#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000305
306private:
307 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000308 class SliceBuilder;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000309
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000310 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000311
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000312#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000313 /// \brief Handle to alloca instruction to simplify method interfaces.
314 AllocaInst &AI;
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000315#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000316
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000317 /// \brief The instruction responsible for this alloca not having a known set
318 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000319 ///
320 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000321 /// store a pointer to that here and abort trying to form slices of the
322 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000323 Instruction *PointerEscapingInstr;
324
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000325 /// \brief The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000326 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000327 /// We store a vector of the slices formed by uses of the alloca here. This
328 /// vector is sorted by increasing begin offset, and then the unsplittable
329 /// slices before the splittable ones. See the Slice inner class for more
330 /// details.
331 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000332
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000333 /// \brief Instructions which will become dead if we rewrite the alloca.
334 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000335 /// Note that these are not separated by slice. This is because we expect an
336 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
337 /// all these instructions can simply be removed and replaced with undef as
338 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000339 SmallVector<Instruction *, 8> DeadUsers;
340
341 /// \brief Operands which will become dead if we rewrite the alloca.
342 ///
343 /// These are operands that in their particular use can be replaced with
344 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
345 /// to PHI nodes and the like. They aren't entirely dead (there might be
346 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
347 /// want to swap this particular input for undef to simplify the use lists of
348 /// the alloca.
349 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000350};
Chandler Carruth29a18a42015-09-12 09:09:14 +0000351
352/// \brief A partition of the slices.
353///
354/// An ephemeral representation for a range of slices which can be viewed as
355/// a partition of the alloca. This range represents a span of the alloca's
356/// memory which cannot be split, and provides access to all of the slices
357/// overlapping some part of the partition.
358///
359/// Objects of this type are produced by traversing the alloca's slices, but
360/// are only ephemeral and not persistent.
361class llvm::sroa::Partition {
362private:
363 friend class AllocaSlices;
364 friend class AllocaSlices::partition_iterator;
365
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000366 using iterator = AllocaSlices::iterator;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000367
368 /// \brief The beginning and ending offsets of the alloca for this
369 /// partition.
370 uint64_t BeginOffset, EndOffset;
371
Hiroshi Inoueac9cd302017-05-29 08:37:42 +0000372 /// \brief The start and end iterators of this partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000373 iterator SI, SJ;
374
375 /// \brief A collection of split slice tails overlapping the partition.
376 SmallVector<Slice *, 4> SplitTails;
377
378 /// \brief Raw constructor builds an empty partition starting and ending at
379 /// the given iterator.
380 Partition(iterator SI) : SI(SI), SJ(SI) {}
381
382public:
383 /// \brief The start offset of this partition.
384 ///
385 /// All of the contained slices start at or after this offset.
386 uint64_t beginOffset() const { return BeginOffset; }
387
388 /// \brief The end offset of this partition.
389 ///
390 /// All of the contained slices end at or before this offset.
391 uint64_t endOffset() const { return EndOffset; }
392
393 /// \brief The size of the partition.
394 ///
395 /// Note that this can never be zero.
396 uint64_t size() const {
397 assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
398 return EndOffset - BeginOffset;
399 }
400
401 /// \brief Test whether this partition contains no slices, and merely spans
402 /// a region occupied by split slices.
403 bool empty() const { return SI == SJ; }
404
405 /// \name Iterate slices that start within the partition.
406 /// These may be splittable or unsplittable. They have a begin offset >= the
407 /// partition begin offset.
408 /// @{
409 // FIXME: We should probably define a "concat_iterator" helper and use that
410 // to stitch together pointee_iterators over the split tails and the
411 // contiguous iterators of the partition. That would give a much nicer
412 // interface here. We could then additionally expose filtered iterators for
413 // split, unsplit, and unsplittable splices based on the usage patterns.
414 iterator begin() const { return SI; }
415 iterator end() const { return SJ; }
416 /// @}
417
418 /// \brief Get the sequence of split slice tails.
419 ///
420 /// These tails are of slices which start before this partition but are
421 /// split and overlap into the partition. We accumulate these while forming
422 /// partitions.
423 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
424};
425
426/// \brief An iterator over partitions of the alloca's slices.
427///
428/// This iterator implements the core algorithm for partitioning the alloca's
429/// slices. It is a forward iterator as we don't support backtracking for
430/// efficiency reasons, and re-use a single storage area to maintain the
431/// current set of split slices.
432///
433/// It is templated on the slice iterator type to use so that it can operate
434/// with either const or non-const slice iterators.
435class AllocaSlices::partition_iterator
436 : public iterator_facade_base<partition_iterator, std::forward_iterator_tag,
437 Partition> {
438 friend class AllocaSlices;
439
440 /// \brief Most of the state for walking the partitions is held in a class
441 /// with a nice interface for examining them.
442 Partition P;
443
444 /// \brief We need to keep the end of the slices to know when to stop.
445 AllocaSlices::iterator SE;
446
447 /// \brief We also need to keep track of the maximum split end offset seen.
448 /// FIXME: Do we really?
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000449 uint64_t MaxSplitSliceEndOffset = 0;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000450
451 /// \brief Sets the partition to be empty at given iterator, and sets the
452 /// end iterator.
453 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000454 : P(SI), SE(SE) {
Chandler Carruth29a18a42015-09-12 09:09:14 +0000455 // If not already at the end, advance our state to form the initial
456 // partition.
457 if (SI != SE)
458 advance();
459 }
460
461 /// \brief Advance the iterator to the next partition.
462 ///
463 /// Requires that the iterator not be at the end of the slices.
464 void advance() {
465 assert((P.SI != SE || !P.SplitTails.empty()) &&
466 "Cannot advance past the end of the slices!");
467
468 // Clear out any split uses which have ended.
469 if (!P.SplitTails.empty()) {
470 if (P.EndOffset >= MaxSplitSliceEndOffset) {
471 // If we've finished all splits, this is easy.
472 P.SplitTails.clear();
473 MaxSplitSliceEndOffset = 0;
474 } else {
475 // Remove the uses which have ended in the prior partition. This
476 // cannot change the max split slice end because we just checked that
477 // the prior partition ended prior to that max.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000478 P.SplitTails.erase(llvm::remove_if(P.SplitTails,
479 [&](Slice *S) {
480 return S->endOffset() <=
481 P.EndOffset;
482 }),
483 P.SplitTails.end());
484 assert(llvm::any_of(P.SplitTails,
485 [&](Slice *S) {
486 return S->endOffset() == MaxSplitSliceEndOffset;
487 }) &&
Chandler Carruth29a18a42015-09-12 09:09:14 +0000488 "Could not find the current max split slice offset!");
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000489 assert(llvm::all_of(P.SplitTails,
490 [&](Slice *S) {
491 return S->endOffset() <= MaxSplitSliceEndOffset;
492 }) &&
Chandler Carruth29a18a42015-09-12 09:09:14 +0000493 "Max split slice end offset is not actually the max!");
494 }
495 }
496
497 // If P.SI is already at the end, then we've cleared the split tail and
498 // now have an end iterator.
499 if (P.SI == SE) {
500 assert(P.SplitTails.empty() && "Failed to clear the split slices!");
501 return;
502 }
503
504 // If we had a non-empty partition previously, set up the state for
505 // subsequent partitions.
506 if (P.SI != P.SJ) {
507 // Accumulate all the splittable slices which started in the old
508 // partition into the split list.
509 for (Slice &S : P)
510 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
511 P.SplitTails.push_back(&S);
512 MaxSplitSliceEndOffset =
513 std::max(S.endOffset(), MaxSplitSliceEndOffset);
514 }
515
516 // Start from the end of the previous partition.
517 P.SI = P.SJ;
518
519 // If P.SI is now at the end, we at most have a tail of split slices.
520 if (P.SI == SE) {
521 P.BeginOffset = P.EndOffset;
522 P.EndOffset = MaxSplitSliceEndOffset;
523 return;
524 }
525
526 // If the we have split slices and the next slice is after a gap and is
527 // not splittable immediately form an empty partition for the split
528 // slices up until the next slice begins.
529 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
530 !P.SI->isSplittable()) {
531 P.BeginOffset = P.EndOffset;
532 P.EndOffset = P.SI->beginOffset();
533 return;
534 }
535 }
536
537 // OK, we need to consume new slices. Set the end offset based on the
538 // current slice, and step SJ past it. The beginning offset of the
539 // partition is the beginning offset of the next slice unless we have
540 // pre-existing split slices that are continuing, in which case we begin
541 // at the prior end offset.
542 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
543 P.EndOffset = P.SI->endOffset();
544 ++P.SJ;
545
546 // There are two strategies to form a partition based on whether the
547 // partition starts with an unsplittable slice or a splittable slice.
548 if (!P.SI->isSplittable()) {
549 // When we're forming an unsplittable region, it must always start at
550 // the first slice and will extend through its end.
551 assert(P.BeginOffset == P.SI->beginOffset());
552
553 // Form a partition including all of the overlapping slices with this
554 // unsplittable slice.
555 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
556 if (!P.SJ->isSplittable())
557 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
558 ++P.SJ;
559 }
560
561 // We have a partition across a set of overlapping unsplittable
562 // partitions.
563 return;
564 }
565
566 // If we're starting with a splittable slice, then we need to form
567 // a synthetic partition spanning it and any other overlapping splittable
568 // splices.
569 assert(P.SI->isSplittable() && "Forming a splittable partition!");
570
571 // Collect all of the overlapping splittable slices.
572 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
573 P.SJ->isSplittable()) {
574 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
575 ++P.SJ;
576 }
577
578 // Back upiP.EndOffset if we ended the span early when encountering an
579 // unsplittable slice. This synthesizes the early end offset of
580 // a partition spanning only splittable slices.
581 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
582 assert(!P.SJ->isSplittable());
583 P.EndOffset = P.SJ->beginOffset();
584 }
585 }
586
587public:
588 bool operator==(const partition_iterator &RHS) const {
589 assert(SE == RHS.SE &&
590 "End iterators don't match between compared partition iterators!");
591
592 // The observed positions of partitions is marked by the P.SI iterator and
593 // the emptiness of the split slices. The latter is only relevant when
594 // P.SI == SE, as the end iterator will additionally have an empty split
595 // slices list, but the prior may have the same P.SI and a tail of split
596 // slices.
597 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
598 assert(P.SJ == RHS.P.SJ &&
599 "Same set of slices formed two different sized partitions!");
600 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
601 "Same slice position with differently sized non-empty split "
602 "slice tails!");
603 return true;
604 }
605 return false;
606 }
607
608 partition_iterator &operator++() {
609 advance();
610 return *this;
611 }
612
613 Partition &operator*() { return P; }
614};
615
616/// \brief A forward range over the partitions of the alloca's slices.
617///
618/// This accesses an iterator range over the partitions of the alloca's
619/// slices. It computes these partitions on the fly based on the overlapping
620/// offsets of the slices and the ability to split them. It will visit "empty"
621/// partitions to cover regions of the alloca only accessed via split
622/// slices.
623iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() {
624 return make_range(partition_iterator(begin(), end()),
625 partition_iterator(end(), end()));
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000626}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000627
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000628static Value *foldSelectInst(SelectInst &SI) {
629 // If the condition being selected on is a constant or the same value is
630 // being selected between, fold the select. Yes this does (rarely) happen
631 // early on.
632 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
Chandler Carruth113dc642014-12-20 02:39:18 +0000633 return SI.getOperand(1 + CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000634 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000635 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000636
Craig Topperf40110f2014-04-25 05:29:35 +0000637 return nullptr;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000638}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000639
Jingyue Wuec33fa92014-08-22 22:45:57 +0000640/// \brief A helper that folds a PHI node or a select.
641static Value *foldPHINodeOrSelectInst(Instruction &I) {
642 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
643 // If PN merges together the same value, return that value.
644 return PN->hasConstantValue();
645 }
646 return foldSelectInst(cast<SelectInst>(I));
647}
648
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000649/// \brief Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000650///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000651/// This class builds a set of alloca slices by recursively visiting the uses
652/// of an alloca and making a slice for each load and store at each offset.
653class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
654 friend class PtrUseVisitor<SliceBuilder>;
655 friend class InstVisitor<SliceBuilder>;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000656
657 using Base = PtrUseVisitor<SliceBuilder>;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000658
659 const uint64_t AllocSize;
Chandler Carruth83934062014-10-16 21:11:55 +0000660 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000661
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000662 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000663 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
664
665 /// \brief Set to de-duplicate dead instructions found in the use walk.
666 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000667
668public:
Chandler Carruth83934062014-10-16 21:11:55 +0000669 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000670 : PtrUseVisitor<SliceBuilder>(DL),
Chandler Carruth83934062014-10-16 21:11:55 +0000671 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000672
673private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000674 void markAsDead(Instruction &I) {
David Blaikie70573dc2014-11-19 07:49:26 +0000675 if (VisitedDeadInsts.insert(&I).second)
Chandler Carruth83934062014-10-16 21:11:55 +0000676 AS.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000677 }
678
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000679 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000680 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000681 // Completely skip uses which have a zero size or start either before or
682 // past the end of the allocation.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000683 if (Size == 0 || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000684 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000685 << " which has zero size or starts outside of the "
686 << AllocSize << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000687 << " alloca: " << AS.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000688 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000689 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000690 }
691
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000692 uint64_t BeginOffset = Offset.getZExtValue();
693 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000694
695 // Clamp the end offset to the end of the allocation. Note that this is
696 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000697 // This may appear superficially to be something we could ignore entirely,
698 // but that is not so! There may be widened loads or PHI-node uses where
699 // some instructions are dead but not others. We can't completely ignore
700 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000701 assert(AllocSize >= BeginOffset); // Established above.
702 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000703 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
704 << " to remain within the " << AllocSize << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000705 << " alloca: " << AS.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000706 << " use: " << I << "\n");
707 EndOffset = AllocSize;
708 }
709
Chandler Carruth83934062014-10-16 21:11:55 +0000710 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000711 }
712
713 void visitBitCastInst(BitCastInst &BC) {
714 if (BC.use_empty())
715 return markAsDead(BC);
716
717 return Base::visitBitCastInst(BC);
718 }
719
720 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
721 if (GEPI.use_empty())
722 return markAsDead(GEPI);
723
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000724 if (SROAStrictInbounds && GEPI.isInBounds()) {
725 // FIXME: This is a manually un-factored variant of the basic code inside
726 // of GEPs with checking of the inbounds invariant specified in the
727 // langref in a very strict sense. If we ever want to enable
728 // SROAStrictInbounds, this code should be factored cleanly into
729 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
Hal Finkel5c83a092016-03-28 11:23:21 +0000730 // by writing out the code here where we have the underlying allocation
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000731 // size readily available.
732 APInt GEPOffset = Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000733 const DataLayout &DL = GEPI.getModule()->getDataLayout();
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000734 for (gep_type_iterator GTI = gep_type_begin(GEPI),
735 GTE = gep_type_end(GEPI);
736 GTI != GTE; ++GTI) {
737 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
738 if (!OpC)
739 break;
740
741 // Handle a struct index, which adds its field offset to the pointer.
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000742 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000743 unsigned ElementIdx = OpC->getZExtValue();
744 const StructLayout *SL = DL.getStructLayout(STy);
745 GEPOffset +=
746 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
747 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +0000748 // For array or vector indices, scale the index by the size of the
749 // type.
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000750 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
751 GEPOffset += Index * APInt(Offset.getBitWidth(),
752 DL.getTypeAllocSize(GTI.getIndexedType()));
753 }
754
755 // If this index has computed an intermediate pointer which is not
756 // inbounds, then the result of the GEP is a poison value and we can
757 // delete it and all uses.
758 if (GEPOffset.ugt(AllocSize))
759 return markAsDead(GEPI);
760 }
761 }
762
Chandler Carruthf0546402013-07-18 07:15:00 +0000763 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000764 }
765
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000766 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000767 uint64_t Size, bool IsVolatile) {
Chandler Carruth24ac8302015-01-02 03:55:54 +0000768 // We allow splitting of non-volatile loads and stores where the type is an
769 // integer type. These may be used to implement 'memcpy' or other "transfer
770 // of bits" patterns.
771 bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
Chandler Carruth58d05562012-10-25 04:37:07 +0000772
773 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000774 }
775
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000776 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000777 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
778 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000779
780 if (!IsOffsetKnown)
781 return PI.setAborted(&LI);
782
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000783 const DataLayout &DL = LI.getModule()->getDataLayout();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000784 uint64_t Size = DL.getTypeStoreSize(LI.getType());
785 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000786 }
787
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000788 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000789 Value *ValOp = SI.getValueOperand();
790 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000791 return PI.setEscapedAndAborted(&SI);
792 if (!IsOffsetKnown)
793 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000794
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000795 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000796 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
797
798 // If this memory access can be shown to *statically* extend outside the
799 // bounds of of the allocation, it's behavior is undefined, so simply
800 // ignore it. Note that this is more strict than the generic clamping
801 // behavior of insertUse. We also try to handle cases which might run the
802 // risk of overflow.
803 // FIXME: We should instead consider the pointer to have escaped if this
804 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000805 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000806 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
807 << " which extends past the end of the " << AllocSize
808 << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000809 << " alloca: " << AS.AI << "\n"
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000810 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000811 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000812 }
813
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000814 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
815 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000816 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000817 }
818
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000819 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000820 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000821 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000822 if ((Length && Length->getValue() == 0) ||
Chandler Carruth6aedc102014-02-26 03:14:14 +0000823 (IsOffsetKnown && Offset.uge(AllocSize)))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000824 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000825 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000826
827 if (!IsOffsetKnown)
828 return PI.setAborted(&II);
829
Chandler Carruth113dc642014-12-20 02:39:18 +0000830 insertUse(II, Offset, Length ? Length->getLimitedValue()
831 : AllocSize - Offset.getLimitedValue(),
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000832 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000833 }
834
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000835 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000836 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000837 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000838 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000839 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000840
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000841 // Because we can visit these intrinsics twice, also check to see if the
842 // first time marked this instruction as dead. If so, skip it.
843 if (VisitedDeadInsts.count(&II))
844 return;
845
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000846 if (!IsOffsetKnown)
847 return PI.setAborted(&II);
848
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000849 // This side of the transfer is completely out-of-bounds, and so we can
850 // nuke the entire transfer. However, we also need to nuke the other side
851 // if already added to our partitions.
852 // FIXME: Yet another place we really should bypass this when
853 // instrumenting for ASan.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000854 if (Offset.uge(AllocSize)) {
Chandler Carruth113dc642014-12-20 02:39:18 +0000855 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
856 MemTransferSliceMap.find(&II);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000857 if (MTPI != MemTransferSliceMap.end())
Chandler Carruth83934062014-10-16 21:11:55 +0000858 AS.Slices[MTPI->second].kill();
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000859 return markAsDead(II);
860 }
861
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000862 uint64_t RawOffset = Offset.getLimitedValue();
Chandler Carruth113dc642014-12-20 02:39:18 +0000863 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000864
Chandler Carruthf0546402013-07-18 07:15:00 +0000865 // Check for the special case where the same exact value is used for both
866 // source and dest.
867 if (*U == II.getRawDest() && *U == II.getRawSource()) {
868 // For non-volatile transfers this is a no-op.
869 if (!II.isVolatile())
870 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000871
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000872 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000873 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000874
Chandler Carruthf0546402013-07-18 07:15:00 +0000875 // If we have seen both source and destination for a mem transfer, then
876 // they both point to the same alloca.
877 bool Inserted;
878 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000879 std::tie(MTPI, Inserted) =
Chandler Carruth83934062014-10-16 21:11:55 +0000880 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000881 unsigned PrevIdx = MTPI->second;
882 if (!Inserted) {
Chandler Carruth83934062014-10-16 21:11:55 +0000883 Slice &PrevP = AS.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000884
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000885 // Check if the begin offsets match and this is a non-volatile transfer.
886 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000887 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
888 PrevP.kill();
889 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000890 }
891
892 // Otherwise we have an offset transfer within the same alloca. We can't
893 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000894 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000895 }
896
Chandler Carruthe3899f22013-07-15 17:36:21 +0000897 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000898 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000899
Chandler Carruthf0546402013-07-18 07:15:00 +0000900 // Check that we ended up with a valid index in the map.
Chandler Carruth83934062014-10-16 21:11:55 +0000901 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000902 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000903 }
904
905 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000906 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000907 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000908 void visitIntrinsicInst(IntrinsicInst &II) {
909 if (!IsOffsetKnown)
910 return PI.setAborted(&II);
911
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000912 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
913 II.getIntrinsicID() == Intrinsic::lifetime_end) {
914 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000915 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
916 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000917 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000918 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000919 }
920
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000921 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000922 }
923
924 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
925 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000926 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000927 // are considered unsplittable and the size is the maximum loaded or stored
928 // size.
929 SmallPtrSet<Instruction *, 4> Visited;
930 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
931 Visited.insert(Root);
932 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000933 const DataLayout &DL = Root->getModule()->getDataLayout();
Chandler Carruth8b907e82012-09-25 10:03:40 +0000934 // If there are no loads or stores, the access is dead. We mark that as
935 // a size zero access.
936 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000937 do {
938 Instruction *I, *UsedI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000939 std::tie(UsedI, I) = Uses.pop_back_val();
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000940
941 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000942 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000943 continue;
944 }
945 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
946 Value *Op = SI->getOperand(0);
947 if (Op == UsedI)
948 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000949 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000950 continue;
951 }
952
953 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
954 if (!GEP->hasAllZeroIndices())
955 return GEP;
956 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
957 !isa<SelectInst>(I)) {
958 return I;
959 }
960
Chandler Carruthcdf47882014-03-09 03:16:01 +0000961 for (User *U : I->users())
David Blaikie70573dc2014-11-19 07:49:26 +0000962 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000963 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000964 } while (!Uses.empty());
965
Craig Topperf40110f2014-04-25 05:29:35 +0000966 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000967 }
968
Jingyue Wuec33fa92014-08-22 22:45:57 +0000969 void visitPHINodeOrSelectInst(Instruction &I) {
970 assert(isa<PHINode>(I) || isa<SelectInst>(I));
971 if (I.use_empty())
972 return markAsDead(I);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000973
Jingyue Wuec33fa92014-08-22 22:45:57 +0000974 // TODO: We could use SimplifyInstruction here to fold PHINodes and
975 // SelectInsts. However, doing so requires to change the current
976 // dead-operand-tracking mechanism. For instance, suppose neither loading
977 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
978 // trap either. However, if we simply replace %U with undef using the
979 // current dead-operand-tracking mechanism, "load (select undef, undef,
980 // %other)" may trap because the select may return the first operand
981 // "undef".
982 if (Value *Result = foldPHINodeOrSelectInst(I)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000983 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000984 // If the result of the constant fold will be the pointer, recurse
Jingyue Wuec33fa92014-08-22 22:45:57 +0000985 // through the PHI/select as if we had RAUW'ed it.
986 enqueueUsers(I);
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000987 else
Jingyue Wuec33fa92014-08-22 22:45:57 +0000988 // Otherwise the operand to the PHI/select is dead, and we can replace
989 // it with undef.
Chandler Carruth83934062014-10-16 21:11:55 +0000990 AS.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000991
992 return;
993 }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000994
Chandler Carruthf0546402013-07-18 07:15:00 +0000995 if (!IsOffsetKnown)
Jingyue Wuec33fa92014-08-22 22:45:57 +0000996 return PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000997
Chandler Carruthf0546402013-07-18 07:15:00 +0000998 // See if we already have computed info on this node.
Jingyue Wuec33fa92014-08-22 22:45:57 +0000999 uint64_t &Size = PHIOrSelectSizes[&I];
1000 if (!Size) {
1001 // This is a new PHI/Select, check for an unsafe use of it.
1002 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
Chandler Carruthf0546402013-07-18 07:15:00 +00001003 return PI.setAborted(UnsafeI);
1004 }
1005
1006 // For PHI and select operands outside the alloca, we can't nuke the entire
1007 // phi or select -- the other side might still be relevant, so we special
1008 // case them here and use a separate structure to track the operands
1009 // themselves which should be replaced with undef.
1010 // FIXME: This should instead be escaped in the event we're instrumenting
1011 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +00001012 if (Offset.uge(AllocSize)) {
Chandler Carruth83934062014-10-16 21:11:55 +00001013 AS.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +00001014 return;
1015 }
1016
Jingyue Wuec33fa92014-08-22 22:45:57 +00001017 insertUse(I, Offset, Size);
1018 }
1019
Chandler Carruth113dc642014-12-20 02:39:18 +00001020 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
Jingyue Wuec33fa92014-08-22 22:45:57 +00001021
Chandler Carruth113dc642014-12-20 02:39:18 +00001022 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001023
Chandler Carruthf0546402013-07-18 07:15:00 +00001024 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth113dc642014-12-20 02:39:18 +00001025 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001026};
1027
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001028AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001029 :
1030#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1031 AI(AI),
1032#endif
Craig Topperf40110f2014-04-25 05:29:35 +00001033 PointerEscapingInstr(nullptr) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001034 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001035 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001036 if (PtrI.isEscaped() || PtrI.isAborted()) {
1037 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001038 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001039 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1040 : PtrI.getAbortingInst();
1041 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001042 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001043 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001044
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001045 Slices.erase(
1046 llvm::remove_if(Slices, [](const Slice &S) { return S.isDead(); }),
1047 Slices.end());
Benjamin Kramer08e50702013-07-20 08:38:34 +00001048
Hal Finkel29f51312016-03-28 11:13:03 +00001049#ifndef NDEBUG
Chandler Carruth83cee772014-02-25 03:59:29 +00001050 if (SROARandomShuffleSlices) {
Pavel Labathc207bec2016-11-09 12:07:12 +00001051 std::mt19937 MT(static_cast<unsigned>(
1052 std::chrono::system_clock::now().time_since_epoch().count()));
Chandler Carruth83cee772014-02-25 03:59:29 +00001053 std::shuffle(Slices.begin(), Slices.end(), MT);
1054 }
1055#endif
1056
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001057 // Sort the uses. This arranges for the offsets to be in ascending order,
1058 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001059 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001060}
1061
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001062#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1063
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001064void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1065 StringRef Indent) const {
1066 printSlice(OS, I, Indent);
Chandler Carruth0715cba2015-01-01 11:54:38 +00001067 OS << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001068 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001069}
1070
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001071void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1072 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001073 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001074 << " slice #" << (I - begin())
Chandler Carruth0715cba2015-01-01 11:54:38 +00001075 << (I->isSplittable() ? " (splittable)" : "");
Chandler Carruthf0546402013-07-18 07:15:00 +00001076}
1077
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001078void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1079 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001080 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001081}
1082
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001083void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001084 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001085 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001086 << " A pointer to this alloca escaped by:\n"
1087 << " " << *PointerEscapingInstr << "\n";
1088 return;
1089 }
1090
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001091 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001092 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001093 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001094}
1095
Alp Tokerf929e092014-01-04 22:47:48 +00001096LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1097 print(dbgs(), I);
1098}
1099LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001100
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001101#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1102
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001103/// Walk the range of a partitioning looking for a common type to cover this
1104/// sequence of slices.
1105static Type *findCommonType(AllocaSlices::const_iterator B,
1106 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001107 uint64_t EndOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001108 Type *Ty = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001109 bool TyIsCommon = true;
Craig Topperf40110f2014-04-25 05:29:35 +00001110 IntegerType *ITy = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001111
1112 // Note that we need to look at *every* alloca slice's Use to ensure we
1113 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001114 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001115 Use *U = I->getUse();
1116 if (isa<IntrinsicInst>(*U->getUser()))
1117 continue;
1118 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1119 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001120
Craig Topperf40110f2014-04-25 05:29:35 +00001121 Type *UserTy = nullptr;
Chandler Carrutha1262002013-11-19 09:03:18 +00001122 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001123 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001124 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001125 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001126 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001127
Chandler Carruth4de31542014-01-21 23:16:05 +00001128 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001129 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001130 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001131 // entity causing the split. Also skip if the type is not a byte width
1132 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001133 if (UserITy->getBitWidth() % 8 != 0 ||
1134 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001135 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001136
Chandler Carruth4de31542014-01-21 23:16:05 +00001137 // Track the largest bitwidth integer type used in this way in case there
1138 // is no common type.
1139 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1140 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001141 }
Duncan P. N. Exon Smith73686d32014-06-17 00:19:35 +00001142
1143 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1144 // depend on types skipped above.
1145 if (!UserTy || (Ty && Ty != UserTy))
1146 TyIsCommon = false; // Give up on anything but an iN type.
1147 else
1148 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001149 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001150
1151 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001152}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001153
Chandler Carruthf0546402013-07-18 07:15:00 +00001154/// PHI instructions that use an alloca and are subsequently loaded can be
1155/// rewritten to load both input pointers in the pred blocks and then PHI the
1156/// results, allowing the load of the alloca to be promoted.
1157/// From this:
1158/// %P2 = phi [i32* %Alloca, i32* %Other]
1159/// %V = load i32* %P2
1160/// to:
1161/// %V1 = load i32* %Alloca -> will be mem2reg'd
1162/// ...
1163/// %V2 = load i32* %Other
1164/// ...
1165/// %V = phi [i32 %V1, i32 %V2]
1166///
1167/// We can do this to a select if its only uses are loads and if the operands
1168/// to the select can be loaded unconditionally.
1169///
1170/// FIXME: This should be hoisted into a generic utility, likely in
1171/// Transforms/Util/Local.h
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001172static bool isSafePHIToSpeculate(PHINode &PN) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001173 // For now, we can only do this promotion if the load is in the same block
1174 // as the PHI, and if there are no stores between the phi and load.
1175 // TODO: Allow recursive phi users.
1176 // TODO: Allow stores.
1177 BasicBlock *BB = PN.getParent();
1178 unsigned MaxAlign = 0;
1179 bool HaveLoad = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001180 for (User *U : PN.users()) {
1181 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001182 if (!LI || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001183 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001184
Chandler Carruthf0546402013-07-18 07:15:00 +00001185 // For now we only allow loads in the same block as the PHI. This is
1186 // a common case that happens when instcombine merges two loads through
1187 // a PHI.
1188 if (LI->getParent() != BB)
1189 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001190
Chandler Carruthf0546402013-07-18 07:15:00 +00001191 // Ensure that there are no instructions between the PHI and the load that
1192 // could store.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001193 for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
Chandler Carruthf0546402013-07-18 07:15:00 +00001194 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001195 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001196
Chandler Carruthf0546402013-07-18 07:15:00 +00001197 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1198 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001199 }
1200
Chandler Carruthf0546402013-07-18 07:15:00 +00001201 if (!HaveLoad)
1202 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001203
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001204 const DataLayout &DL = PN.getModule()->getDataLayout();
1205
Chandler Carruthf0546402013-07-18 07:15:00 +00001206 // We can only transform this if it is safe to push the loads into the
1207 // predecessor blocks. The only thing to watch out for is that we can't put
1208 // a possibly trapping load in the predecessor if it is a critical edge.
1209 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1210 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1211 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001212
Chandler Carruthf0546402013-07-18 07:15:00 +00001213 // If the value is produced by the terminator of the predecessor (an
1214 // invoke) or it has side-effects, there is no valid place to put a load
1215 // in the predecessor.
1216 if (TI == InVal || TI->mayHaveSideEffects())
1217 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001218
Chandler Carruthf0546402013-07-18 07:15:00 +00001219 // If the predecessor has a single successor, then the edge isn't
1220 // critical.
1221 if (TI->getNumSuccessors() == 1)
1222 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001223
Chandler Carruthf0546402013-07-18 07:15:00 +00001224 // If this pointer is always safe to load, or if we can prove that there
1225 // is already a load in the block, then we can move the load to the pred
1226 // block.
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001227 if (isSafeToLoadUnconditionally(InVal, MaxAlign, DL, TI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001228 continue;
1229
1230 return false;
1231 }
1232
1233 return true;
1234}
1235
1236static void speculatePHINodeLoads(PHINode &PN) {
1237 DEBUG(dbgs() << " original: " << PN << "\n");
1238
1239 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1240 IRBuilderTy PHIBuilder(&PN);
1241 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1242 PN.getName() + ".sroa.speculated");
1243
Hal Finkelcc39b672014-07-24 12:16:19 +00001244 // Get the AA tags and alignment to use from one of the loads. It doesn't
Chandler Carruthf0546402013-07-18 07:15:00 +00001245 // matter which one we get and if any differ.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001246 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
Hal Finkelcc39b672014-07-24 12:16:19 +00001247
1248 AAMDNodes AATags;
1249 SomeLoad->getAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001250 unsigned Align = SomeLoad->getAlignment();
1251
1252 // Rewrite all loads of the PN to use the new PHI.
1253 while (!PN.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001254 LoadInst *LI = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001255 LI->replaceAllUsesWith(NewPN);
1256 LI->eraseFromParent();
1257 }
1258
1259 // Inject loads into all of the pred blocks.
1260 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1261 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1262 TerminatorInst *TI = Pred->getTerminator();
1263 Value *InVal = PN.getIncomingValue(Idx);
1264 IRBuilderTy PredBuilder(TI);
1265
1266 LoadInst *Load = PredBuilder.CreateLoad(
1267 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1268 ++NumLoadsSpeculated;
1269 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001270 if (AATags)
1271 Load->setAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001272 NewPN->addIncoming(Load, Pred);
1273 }
1274
1275 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1276 PN.eraseFromParent();
1277}
1278
1279/// Select instructions that use an alloca and are subsequently loaded can be
1280/// rewritten to load both input pointers and then select between the result,
1281/// allowing the load of the alloca to be promoted.
1282/// From this:
1283/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1284/// %V = load i32* %P2
1285/// to:
1286/// %V1 = load i32* %Alloca -> will be mem2reg'd
1287/// %V2 = load i32* %Other
1288/// %V = select i1 %cond, i32 %V1, i32 %V2
1289///
1290/// We can do this to a select if its only uses are loads and if the operand
1291/// to the select can be loaded unconditionally.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001292static bool isSafeSelectToSpeculate(SelectInst &SI) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001293 Value *TValue = SI.getTrueValue();
1294 Value *FValue = SI.getFalseValue();
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001295 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00001296
Chandler Carruthcdf47882014-03-09 03:16:01 +00001297 for (User *U : SI.users()) {
1298 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001299 if (!LI || !LI->isSimple())
Chandler Carruthf0546402013-07-18 07:15:00 +00001300 return false;
1301
Hiroshi Inoueb3008242017-06-24 15:43:33 +00001302 // Both operands to the select need to be dereferenceable, either
Chandler Carruthf0546402013-07-18 07:15:00 +00001303 // absolutely (e.g. allocas) or at this point because we can see other
1304 // accesses to it.
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001305 if (!isSafeToLoadUnconditionally(TValue, LI->getAlignment(), DL, LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001306 return false;
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001307 if (!isSafeToLoadUnconditionally(FValue, LI->getAlignment(), DL, LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001308 return false;
1309 }
1310
1311 return true;
1312}
1313
1314static void speculateSelectInstLoads(SelectInst &SI) {
1315 DEBUG(dbgs() << " original: " << SI << "\n");
1316
1317 IRBuilderTy IRB(&SI);
1318 Value *TV = SI.getTrueValue();
1319 Value *FV = SI.getFalseValue();
1320 // Replace the loads of the select with a select of two loads.
1321 while (!SI.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001322 LoadInst *LI = cast<LoadInst>(SI.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001323 assert(LI->isSimple() && "We only speculate simple loads");
1324
1325 IRB.SetInsertPoint(LI);
1326 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001327 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001328 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001329 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001330 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001331
Hal Finkelcc39b672014-07-24 12:16:19 +00001332 // Transfer alignment and AA info if present.
Chandler Carruthf0546402013-07-18 07:15:00 +00001333 TL->setAlignment(LI->getAlignment());
1334 FL->setAlignment(LI->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +00001335
1336 AAMDNodes Tags;
1337 LI->getAAMetadata(Tags);
1338 if (Tags) {
1339 TL->setAAMetadata(Tags);
1340 FL->setAAMetadata(Tags);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001341 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001342
1343 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1344 LI->getName() + ".sroa.speculated");
1345
1346 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1347 LI->replaceAllUsesWith(V);
1348 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001349 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001350 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001351}
1352
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001353/// \brief Build a GEP out of a base pointer and indices.
1354///
1355/// This will return the BasePtr if that is valid, or build a new GEP
1356/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001357static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001358 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001359 if (Indices.empty())
1360 return BasePtr;
1361
1362 // A single zero index is a no-op, so check for this and avoid building a GEP
1363 // in that case.
1364 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1365 return BasePtr;
1366
David Blaikieaa41cd52015-04-03 21:33:42 +00001367 return IRB.CreateInBoundsGEP(nullptr, BasePtr, Indices,
1368 NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001369}
1370
1371/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1372/// TargetTy without changing the offset of the pointer.
1373///
1374/// This routine assumes we've already established a properly offset GEP with
1375/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1376/// zero-indices down through type layers until we find one the same as
1377/// TargetTy. If we can't find one with the same type, we at least try to use
1378/// one with the same size. If none of that works, we just produce the GEP as
1379/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001380static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001381 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001382 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001383 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001384 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001385 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001386
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001387 // Pointer size to use for the indices.
1388 unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1389
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001390 // See if we can descend into a struct and locate a field with the correct
1391 // type.
1392 unsigned NumLayers = 0;
1393 Type *ElementTy = Ty;
1394 do {
1395 if (ElementTy->isPointerTy())
1396 break;
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001397
1398 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1399 ElementTy = ArrayTy->getElementType();
1400 Indices.push_back(IRB.getIntN(PtrSize, 0));
1401 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1402 ElementTy = VectorTy->getElementType();
1403 Indices.push_back(IRB.getInt32(0));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001404 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001405 if (STy->element_begin() == STy->element_end())
1406 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001407 ElementTy = *STy->element_begin();
1408 Indices.push_back(IRB.getInt32(0));
1409 } else {
1410 break;
1411 }
1412 ++NumLayers;
1413 } while (ElementTy != TargetTy);
1414 if (ElementTy != TargetTy)
1415 Indices.erase(Indices.end() - NumLayers, Indices.end());
1416
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001417 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001418}
1419
1420/// \brief Recursively compute indices for a natural GEP.
1421///
1422/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1423/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001424static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001425 Value *Ptr, Type *Ty, APInt &Offset,
1426 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001427 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001428 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001429 if (Offset == 0)
Chandler Carruth113dc642014-12-20 02:39:18 +00001430 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1431 NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001432
1433 // We can't recurse through pointer types.
1434 if (Ty->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001435 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001436
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001437 // We try to analyze GEPs over vectors here, but note that these GEPs are
1438 // extremely poorly defined currently. The long-term goal is to remove GEPing
1439 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001440 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001441 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Craig Topperf40110f2014-04-25 05:29:35 +00001442 if (ElementSizeInBits % 8 != 0) {
1443 // GEPs over non-multiple of 8 size vector elements are invalid.
1444 return nullptr;
1445 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001446 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001447 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001448 if (NumSkippedElements.ugt(VecTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001449 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001450 Offset -= NumSkippedElements * ElementSize;
1451 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001452 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001453 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001454 }
1455
1456 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1457 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001458 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001459 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001460 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001461 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001462
1463 Offset -= NumSkippedElements * ElementSize;
1464 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001465 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001466 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001467 }
1468
1469 StructType *STy = dyn_cast<StructType>(Ty);
1470 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00001471 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001472
Chandler Carruth90a735d2013-07-19 07:21:28 +00001473 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001474 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001475 if (StructOffset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00001476 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001477 unsigned Index = SL->getElementContainingOffset(StructOffset);
1478 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1479 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001480 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Craig Topperf40110f2014-04-25 05:29:35 +00001481 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001482
1483 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001484 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001485 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001486}
1487
1488/// \brief Get a natural GEP from a base pointer to a particular offset and
1489/// resulting in a particular type.
1490///
1491/// The goal is to produce a "natural" looking GEP that works with the existing
1492/// composite types to arrive at the appropriate offset and element type for
1493/// a pointer. TargetTy is the element type the returned GEP should point-to if
1494/// possible. We recurse by decreasing Offset, adding the appropriate index to
1495/// Indices, and setting Ty to the result subtype.
1496///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001497/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001498static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001499 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001500 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001501 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001502 PointerType *Ty = cast<PointerType>(Ptr->getType());
1503
1504 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1505 // an i8.
Chandler Carruth286d87e2014-02-26 08:25:02 +00001506 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +00001507 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001508
1509 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001510 if (!ElementTy->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +00001511 return nullptr; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001512 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001513 if (ElementSize == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001514 return nullptr; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001515 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001516
1517 Offset -= NumSkippedElements * ElementSize;
1518 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001519 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001520 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001521}
1522
1523/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1524/// resulting pointer has PointerTy.
1525///
1526/// This tries very hard to compute a "natural" GEP which arrives at the offset
1527/// and produces the pointer type desired. Where it cannot, it will try to use
1528/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1529/// fails, it will try to use an existing i8* and GEP to the byte offset and
1530/// bitcast to the type.
1531///
1532/// The strategy for finding the more natural GEPs is to peel off layers of the
1533/// pointer, walking back through bit casts and GEPs, searching for a base
1534/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001535/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001536/// a single GEP as possible, thus making each GEP more independent of the
1537/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001538static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001539 APInt Offset, Type *PointerTy, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001540 // Even though we don't look through PHI nodes, we could be called on an
1541 // instruction in an unreachable block, which may be on a cycle.
1542 SmallPtrSet<Value *, 4> Visited;
1543 Visited.insert(Ptr);
1544 SmallVector<Value *, 4> Indices;
1545
1546 // We may end up computing an offset pointer that has the wrong type. If we
1547 // never are able to compute one directly that has the correct type, we'll
Chandler Carruth5986b542015-01-02 02:47:38 +00001548 // fall back to it, so keep it and the base it was computed from around here.
Craig Topperf40110f2014-04-25 05:29:35 +00001549 Value *OffsetPtr = nullptr;
Chandler Carruth5986b542015-01-02 02:47:38 +00001550 Value *OffsetBasePtr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001551
1552 // Remember any i8 pointer we come across to re-use if we need to do a raw
1553 // byte offset.
Craig Topperf40110f2014-04-25 05:29:35 +00001554 Value *Int8Ptr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001555 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1556
1557 Type *TargetTy = PointerTy->getPointerElementType();
1558
1559 do {
1560 // First fold any existing GEPs into the offset.
1561 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1562 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001563 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001564 break;
1565 Offset += GEPOffset;
1566 Ptr = GEP->getPointerOperand();
David Blaikie70573dc2014-11-19 07:49:26 +00001567 if (!Visited.insert(Ptr).second)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001568 break;
1569 }
1570
1571 // See if we can perform a natural GEP here.
1572 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001573 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001574 Indices, NamePrefix)) {
Chandler Carruth5986b542015-01-02 02:47:38 +00001575 // If we have a new natural pointer at the offset, clear out any old
1576 // offset pointer we computed. Unless it is the base pointer or
1577 // a non-instruction, we built a GEP we don't need. Zap it.
1578 if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1579 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1580 assert(I->use_empty() && "Built a GEP with uses some how!");
1581 I->eraseFromParent();
1582 }
1583 OffsetPtr = P;
1584 OffsetBasePtr = Ptr;
1585 // If we also found a pointer of the right type, we're done.
1586 if (P->getType() == PointerTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001587 return P;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001588 }
1589
1590 // Stash this pointer if we've found an i8*.
1591 if (Ptr->getType()->isIntegerTy(8)) {
1592 Int8Ptr = Ptr;
1593 Int8PtrOffset = Offset;
1594 }
1595
1596 // Peel off a layer of the pointer and update the offset appropriately.
1597 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1598 Ptr = cast<Operator>(Ptr)->getOperand(0);
1599 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001600 if (GA->isInterposable())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001601 break;
1602 Ptr = GA->getAliasee();
1603 } else {
1604 break;
1605 }
1606 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +00001607 } while (Visited.insert(Ptr).second);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001608
1609 if (!OffsetPtr) {
1610 if (!Int8Ptr) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00001611 Int8Ptr = IRB.CreateBitCast(
1612 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1613 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001614 Int8PtrOffset = Offset;
1615 }
1616
Chandler Carruth113dc642014-12-20 02:39:18 +00001617 OffsetPtr = Int8PtrOffset == 0
1618 ? Int8Ptr
David Blaikieaa41cd52015-04-03 21:33:42 +00001619 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1620 IRB.getInt(Int8PtrOffset),
Chandler Carruth113dc642014-12-20 02:39:18 +00001621 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001622 }
1623 Ptr = OffsetPtr;
1624
1625 // On the off chance we were targeting i8*, guard the bitcast here.
1626 if (Ptr->getType() != PointerTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001627 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001628
1629 return Ptr;
1630}
1631
Chandler Carruth0715cba2015-01-01 11:54:38 +00001632/// \brief Compute the adjusted alignment for a load or store from an offset.
1633static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
1634 const DataLayout &DL) {
1635 unsigned Alignment;
1636 Type *Ty;
1637 if (auto *LI = dyn_cast<LoadInst>(I)) {
1638 Alignment = LI->getAlignment();
1639 Ty = LI->getType();
1640 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
1641 Alignment = SI->getAlignment();
1642 Ty = SI->getValueOperand()->getType();
1643 } else {
1644 llvm_unreachable("Only loads and stores are allowed!");
1645 }
1646
1647 if (!Alignment)
1648 Alignment = DL.getABITypeAlignment(Ty);
1649
1650 return MinAlign(Alignment, Offset);
1651}
1652
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001653/// \brief Test whether we can convert a value from the old to the new type.
1654///
1655/// This predicate should be used to guard calls to convertValue in order to
1656/// ensure that we only try to convert viable values. The strategy is that we
1657/// will peel off single element struct and array wrappings to get to an
1658/// underlying value, and convert that value.
1659static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1660 if (OldTy == NewTy)
1661 return true;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001662
1663 // For integer types, we can't handle any bit-width differences. This would
1664 // break both vector conversions with extension and introduce endianness
1665 // issues when in conjunction with loads and stores.
1666 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1667 assert(cast<IntegerType>(OldTy)->getBitWidth() !=
1668 cast<IntegerType>(NewTy)->getBitWidth() &&
1669 "We can't have the same bitwidth for different int types");
1670 return false;
1671 }
1672
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001673 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1674 return false;
1675 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1676 return false;
1677
Benjamin Kramer56262592013-09-22 11:24:58 +00001678 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001679 // of pointers and integers.
1680 OldTy = OldTy->getScalarType();
1681 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001682 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
Jack Liuf101c0f2016-05-03 19:30:48 +00001683 if (NewTy->isPointerTy() && OldTy->isPointerTy()) {
1684 return cast<PointerType>(NewTy)->getPointerAddressSpace() ==
1685 cast<PointerType>(OldTy)->getPointerAddressSpace();
1686 }
Sanjoy Dasb70ddd82017-06-17 20:28:13 +00001687
1688 // We can convert integers to integral pointers, but not to non-integral
1689 // pointers.
1690 if (OldTy->isIntegerTy())
1691 return !DL.isNonIntegralPointerType(NewTy);
1692
1693 // We can convert integral pointers to integers, but non-integral pointers
1694 // need to remain pointers.
1695 if (!DL.isNonIntegralPointerType(OldTy))
1696 return NewTy->isIntegerTy();
1697
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001698 return false;
1699 }
1700
1701 return true;
1702}
1703
1704/// \brief Generic routine to convert an SSA value to a value of a different
1705/// type.
1706///
1707/// This will try various different casting techniques, such as bitcasts,
1708/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1709/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001710static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001711 Type *NewTy) {
1712 Type *OldTy = V->getType();
1713 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1714
1715 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001716 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001717
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001718 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
1719 "Integer types must be the exact same to convert.");
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001720
Benjamin Kramer90901a32013-09-21 20:36:04 +00001721 // See if we need inttoptr for this type pair. A cast involving both scalars
1722 // and vectors requires and additional bitcast.
Craig Topper95d23472017-07-09 07:04:00 +00001723 if (OldTy->isIntOrIntVectorTy() && NewTy->isPtrOrPtrVectorTy()) {
Benjamin Kramer90901a32013-09-21 20:36:04 +00001724 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1725 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1726 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1727 NewTy);
1728
1729 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1730 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1731 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1732 NewTy);
1733
1734 return IRB.CreateIntToPtr(V, NewTy);
1735 }
1736
1737 // See if we need ptrtoint for this type pair. A cast involving both scalars
1738 // and vectors requires and additional bitcast.
Craig Topper95d23472017-07-09 07:04:00 +00001739 if (OldTy->isPtrOrPtrVectorTy() && NewTy->isIntOrIntVectorTy()) {
Benjamin Kramer90901a32013-09-21 20:36:04 +00001740 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1741 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1742 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1743 NewTy);
1744
1745 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1746 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1747 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1748 NewTy);
1749
1750 return IRB.CreatePtrToInt(V, NewTy);
1751 }
1752
1753 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001754}
1755
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001756/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001757///
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001758/// This function is called to test each entry in a partition which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001759/// for a single slice.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001760static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
1761 VectorType *Ty,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001762 uint64_t ElementSize,
1763 const DataLayout &DL) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001764 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001765 uint64_t BeginOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001766 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001767 uint64_t BeginIndex = BeginOffset / ElementSize;
1768 if (BeginIndex * ElementSize != BeginOffset ||
1769 BeginIndex >= Ty->getNumElements())
1770 return false;
1771 uint64_t EndOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001772 std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001773 uint64_t EndIndex = EndOffset / ElementSize;
1774 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1775 return false;
1776
1777 assert(EndIndex > BeginIndex && "Empty vector!");
1778 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruthc659df92014-10-16 20:24:07 +00001779 Type *SliceTy = (NumElements == 1)
1780 ? Ty->getElementType()
1781 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruthf0546402013-07-18 07:15:00 +00001782
1783 Type *SplitIntTy =
1784 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1785
Chandler Carruthc659df92014-10-16 20:24:07 +00001786 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001787
1788 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1789 if (MI->isVolatile())
1790 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001791 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001792 return false; // Skip any unsplittable intrinsics.
Owen Anderson6c19ab12014-08-07 21:07:35 +00001793 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1794 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1795 II->getIntrinsicID() != Intrinsic::lifetime_end)
1796 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001797 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1798 // Disable vector promotion when there are loads or stores of an FCA.
1799 return false;
1800 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1801 if (LI->isVolatile())
1802 return false;
1803 Type *LTy = LI->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001804 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001805 assert(LTy->isIntegerTy());
1806 LTy = SplitIntTy;
1807 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001808 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001809 return false;
1810 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1811 if (SI->isVolatile())
1812 return false;
1813 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001814 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001815 assert(STy->isIntegerTy());
1816 STy = SplitIntTy;
1817 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001818 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001819 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001820 } else {
1821 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001822 }
1823
1824 return true;
1825}
1826
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001827/// \brief Test whether the given alloca partitioning and range of slices can be
1828/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001829///
1830/// This is a quick test to check whether we can rewrite a particular alloca
1831/// partition (and its newly formed alloca) into a vector alloca with only
1832/// whole-vector loads and stores such that it could be promoted to a vector
1833/// SSA value. We only can ensure this for a limited set of operations, and we
1834/// don't want to do the rewrites unless we are confident that the result will
1835/// be promotable, so we have an early test here.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001836static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001837 // Collect the candidate types for vector-based promotion. Also track whether
1838 // we have different element types.
1839 SmallVector<VectorType *, 4> CandidateTys;
1840 Type *CommonEltTy = nullptr;
1841 bool HaveCommonEltTy = true;
1842 auto CheckCandidateType = [&](Type *Ty) {
1843 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1844 CandidateTys.push_back(VTy);
1845 if (!CommonEltTy)
1846 CommonEltTy = VTy->getElementType();
1847 else if (CommonEltTy != VTy->getElementType())
1848 HaveCommonEltTy = false;
1849 }
1850 };
Chandler Carruth2dc96822014-10-18 00:44:02 +00001851 // Consider any loads or stores that are the exact size of the slice.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001852 for (const Slice &S : P)
1853 if (S.beginOffset() == P.beginOffset() &&
1854 S.endOffset() == P.endOffset()) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001855 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1856 CheckCandidateType(LI->getType());
1857 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1858 CheckCandidateType(SI->getValueOperand()->getType());
1859 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001860
Chandler Carruth2dc96822014-10-18 00:44:02 +00001861 // If we didn't find a vector type, nothing to do here.
1862 if (CandidateTys.empty())
1863 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001864
Chandler Carruth2dc96822014-10-18 00:44:02 +00001865 // Remove non-integer vector types if we had multiple common element types.
1866 // FIXME: It'd be nice to replace them with integer vector types, but we can't
1867 // do that until all the backends are known to produce good code for all
1868 // integer vector types.
1869 if (!HaveCommonEltTy) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001870 CandidateTys.erase(
1871 llvm::remove_if(CandidateTys,
1872 [](VectorType *VTy) {
1873 return !VTy->getElementType()->isIntegerTy();
1874 }),
1875 CandidateTys.end());
Chandler Carruth2dc96822014-10-18 00:44:02 +00001876
1877 // If there were no integer vector types, give up.
1878 if (CandidateTys.empty())
1879 return nullptr;
1880
1881 // Rank the remaining candidate vector types. This is easy because we know
1882 // they're all integer vectors. We sort by ascending number of elements.
1883 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
David L. Jones41cecba2017-01-13 21:02:41 +00001884 (void)DL;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001885 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
1886 "Cannot have vector types of different sizes!");
1887 assert(RHSTy->getElementType()->isIntegerTy() &&
1888 "All non-integer types eliminated!");
1889 assert(LHSTy->getElementType()->isIntegerTy() &&
1890 "All non-integer types eliminated!");
1891 return RHSTy->getNumElements() < LHSTy->getNumElements();
1892 };
1893 std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
1894 CandidateTys.erase(
1895 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1896 CandidateTys.end());
1897 } else {
1898// The only way to have the same element type in every vector type is to
1899// have the same vector type. Check that and remove all but one.
1900#ifndef NDEBUG
1901 for (VectorType *VTy : CandidateTys) {
1902 assert(VTy->getElementType() == CommonEltTy &&
1903 "Unaccounted for element type!");
1904 assert(VTy == CandidateTys[0] &&
1905 "Different vector types with the same element type!");
1906 }
1907#endif
1908 CandidateTys.resize(1);
1909 }
1910
1911 // Try each vector type, and return the one which works.
1912 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1913 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
1914
1915 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1916 // that aren't byte sized.
1917 if (ElementSize % 8)
1918 return false;
1919 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
1920 "vector size not a multiple of element size?");
1921 ElementSize /= 8;
1922
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001923 for (const Slice &S : P)
1924 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001925 return false;
1926
Chandler Carruthffb7ce52014-12-24 01:48:09 +00001927 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001928 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001929 return false;
1930
1931 return true;
1932 };
1933 for (VectorType *VTy : CandidateTys)
1934 if (CheckVectorTypeForPromotion(VTy))
1935 return VTy;
1936
1937 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001938}
1939
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001940/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001941///
1942/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001943/// test below on a single slice of the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001944static bool isIntegerWideningViableForSlice(const Slice &S,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001945 uint64_t AllocBeginOffset,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001946 Type *AllocaTy,
1947 const DataLayout &DL,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001948 bool &WholeAllocaOp) {
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001949 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1950
Chandler Carruthc659df92014-10-16 20:24:07 +00001951 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1952 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001953
1954 // We can't reasonably handle cases where the load or store extends past
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001955 // the end of the alloca's type and into its padding.
Chandler Carruthf0546402013-07-18 07:15:00 +00001956 if (RelEnd > Size)
1957 return false;
1958
Chandler Carruthc659df92014-10-16 20:24:07 +00001959 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001960
1961 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1962 if (LI->isVolatile())
1963 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001964 // We can't handle loads that extend past the allocated memory.
1965 if (DL.getTypeStoreSize(LI->getType()) > Size)
1966 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001967 // Note that we don't count vector loads or stores as whole-alloca
1968 // operations which enable integer widening because we would prefer to use
1969 // vector widening instead.
1970 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00001971 WholeAllocaOp = true;
1972 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001973 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001974 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001975 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001976 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001977 // Non-integer loads need to be convertible from the alloca type so that
1978 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001979 return false;
1980 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001981 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1982 Type *ValueTy = SI->getValueOperand()->getType();
1983 if (SI->isVolatile())
1984 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001985 // We can't handle stores that extend past the allocated memory.
1986 if (DL.getTypeStoreSize(ValueTy) > Size)
1987 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001988 // Note that we don't count vector loads or stores as whole-alloca
1989 // operations which enable integer widening because we would prefer to use
1990 // vector widening instead.
1991 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00001992 WholeAllocaOp = true;
1993 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001994 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001995 return false;
1996 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001997 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001998 // Non-integer stores need to be convertible to the alloca type so that
1999 // they are promotable.
2000 return false;
2001 }
2002 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2003 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2004 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00002005 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00002006 return false; // Skip any unsplittable intrinsics.
2007 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2008 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2009 II->getIntrinsicID() != Intrinsic::lifetime_end)
2010 return false;
2011 } else {
2012 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002013 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002014
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002015 return true;
2016}
2017
Chandler Carruth435c4e02012-10-15 08:40:30 +00002018/// \brief Test whether the given alloca partition's integer operations can be
2019/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002020///
Chandler Carruth435c4e02012-10-15 08:40:30 +00002021/// This is a quick test to check whether we can rewrite the integer loads and
2022/// stores to a particular alloca into wider loads and stores and be able to
2023/// promote the resulting alloca.
Chandler Carruth29a18a42015-09-12 09:09:14 +00002024static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002025 const DataLayout &DL) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002026 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00002027 // Don't create integer types larger than the maximum bitwidth.
2028 if (SizeInBits > IntegerType::MAX_INT_BITS)
2029 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002030
2031 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002032 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002033 return false;
2034
Chandler Carruth58d05562012-10-25 04:37:07 +00002035 // We need to ensure that an integer type with the appropriate bitwidth can
2036 // be converted to the alloca type, whatever that is. We don't want to force
2037 // the alloca itself to have an integer type if there is a more suitable one.
2038 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002039 if (!canConvertValue(DL, AllocaTy, IntTy) ||
2040 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00002041 return false;
2042
Chandler Carruthf0546402013-07-18 07:15:00 +00002043 // While examining uses, we ensure that the alloca has a covering load or
2044 // store. We don't want to widen the integer operations only to fail to
2045 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00002046 // later). However, if there are only splittable uses, go ahead and assume
2047 // that we cover the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002048 // FIXME: We shouldn't consider split slices that happen to start in the
2049 // partition here...
Chandler Carruthc659df92014-10-16 20:24:07 +00002050 bool WholeAllocaOp =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002051 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00002052
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002053 for (const Slice &S : P)
2054 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2055 WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00002056 return false;
2057
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002058 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002059 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2060 WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002061 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002062
Chandler Carruth92924fd2012-09-24 00:34:20 +00002063 return WholeAllocaOp;
2064}
2065
Chandler Carruthd177f862013-03-20 07:30:36 +00002066static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002067 IntegerType *Ty, uint64_t Offset,
2068 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002069 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002070 IntegerType *IntTy = cast<IntegerType>(V->getType());
2071 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2072 "Element extends past full value");
Chandler Carruth113dc642014-12-20 02:39:18 +00002073 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002074 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002075 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002076 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002077 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002078 DEBUG(dbgs() << " shifted: " << *V << "\n");
2079 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002080 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2081 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002082 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002083 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00002084 DEBUG(dbgs() << " trunced: " << *V << "\n");
2085 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002086 return V;
2087}
2088
Chandler Carruthd177f862013-03-20 07:30:36 +00002089static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002090 Value *V, uint64_t Offset, const Twine &Name) {
2091 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2092 IntegerType *Ty = cast<IntegerType>(V->getType());
2093 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2094 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002095 DEBUG(dbgs() << " start: " << *V << "\n");
2096 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002097 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00002098 DEBUG(dbgs() << " extended: " << *V << "\n");
2099 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002100 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2101 "Element store outside of alloca store");
Chandler Carruth113dc642014-12-20 02:39:18 +00002102 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002103 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002104 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002105 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002106 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002107 DEBUG(dbgs() << " shifted: " << *V << "\n");
2108 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002109
2110 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2111 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2112 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00002113 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002114 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00002115 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002116 }
2117 return V;
2118}
2119
Chandler Carruth113dc642014-12-20 02:39:18 +00002120static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2121 unsigned EndIndex, const Twine &Name) {
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002122 VectorType *VecTy = cast<VectorType>(V->getType());
2123 unsigned NumElements = EndIndex - BeginIndex;
2124 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2125
2126 if (NumElements == VecTy->getNumElements())
2127 return V;
2128
2129 if (NumElements == 1) {
2130 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2131 Name + ".extract");
2132 DEBUG(dbgs() << " extract: " << *V << "\n");
2133 return V;
2134 }
2135
Chandler Carruth113dc642014-12-20 02:39:18 +00002136 SmallVector<Constant *, 8> Mask;
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002137 Mask.reserve(NumElements);
2138 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2139 Mask.push_back(IRB.getInt32(i));
2140 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002141 ConstantVector::get(Mask), Name + ".extract");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002142 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2143 return V;
2144}
2145
Chandler Carruthd177f862013-03-20 07:30:36 +00002146static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00002147 unsigned BeginIndex, const Twine &Name) {
2148 VectorType *VecTy = cast<VectorType>(Old->getType());
2149 assert(VecTy && "Can only insert a vector into a vector");
2150
2151 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2152 if (!Ty) {
2153 // Single element to insert.
2154 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2155 Name + ".insert");
Chandler Carruth113dc642014-12-20 02:39:18 +00002156 DEBUG(dbgs() << " insert: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002157 return V;
2158 }
2159
2160 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2161 "Too many elements!");
2162 if (Ty->getNumElements() == VecTy->getNumElements()) {
2163 assert(V->getType() == VecTy && "Vector type mismatch");
2164 return V;
2165 }
2166 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2167
2168 // When inserting a smaller vector into the larger to store, we first
2169 // use a shuffle vector to widen it with undef elements, and then
2170 // a second shuffle vector to select between the loaded vector and the
2171 // incoming vector.
Chandler Carruth113dc642014-12-20 02:39:18 +00002172 SmallVector<Constant *, 8> Mask;
Chandler Carruthce4562b2012-12-17 13:41:21 +00002173 Mask.reserve(VecTy->getNumElements());
2174 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2175 if (i >= BeginIndex && i < EndIndex)
2176 Mask.push_back(IRB.getInt32(i - BeginIndex));
2177 else
2178 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2179 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002180 ConstantVector::get(Mask), Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00002181 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002182
2183 Mask.clear();
2184 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00002185 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2186
2187 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2188
2189 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002190 return V;
2191}
2192
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002193/// \brief Visitor to rewrite instructions using p particular slice of an alloca
2194/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002195///
2196/// Also implements the rewriting to vector-based accesses when the partition
2197/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2198/// lives here.
Chandler Carruth29a18a42015-09-12 09:09:14 +00002199class llvm::sroa::AllocaSliceRewriter
2200 : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002201 // Befriend the base class so it can delegate to private visit methods.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002202 friend class InstVisitor<AllocaSliceRewriter, bool>;
2203
2204 using Base = InstVisitor<AllocaSliceRewriter, bool>;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002205
Chandler Carruth90a735d2013-07-19 07:21:28 +00002206 const DataLayout &DL;
Chandler Carruth83934062014-10-16 21:11:55 +00002207 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002208 SROA &Pass;
2209 AllocaInst &OldAI, &NewAI;
2210 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002211 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002212
Chandler Carruth2dc96822014-10-18 00:44:02 +00002213 // This is a convenience and flag variable that will be null unless the new
2214 // alloca's integer operations should be widened to this integer type due to
2215 // passing isIntegerWideningViable above. If it is non-null, the desired
2216 // integer type will be stored here for easy access during rewriting.
2217 IntegerType *IntTy;
2218
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002219 // If we are rewriting an alloca partition which can be written as pure
2220 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002221 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002222 // - The new alloca is exactly the size of the vector type here.
2223 // - The accesses all either map to the entire vector or to a single
2224 // element.
2225 // - The set of accessing instructions is only one of those handled above
2226 // in isVectorPromotionViable. Generally these are the same access kinds
2227 // which are promotable via mem2reg.
2228 VectorType *VecTy;
2229 Type *ElementTy;
2230 uint64_t ElementSize;
2231
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002232 // The original offset of the slice currently being rewritten relative to
2233 // the original alloca.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002234 uint64_t BeginOffset = 0;
2235 uint64_t EndOffset = 0;
2236
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002237 // The new offsets of the slice currently being rewritten relative to the
2238 // original alloca.
2239 uint64_t NewBeginOffset, NewEndOffset;
2240
2241 uint64_t SliceSize;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002242 bool IsSplittable = false;
2243 bool IsSplit = false;
2244 Use *OldUse = nullptr;
2245 Instruction *OldPtr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002246
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002247 // Track post-rewrite users which are PHI nodes and Selects.
Davide Italiano81a26da2017-04-27 23:09:01 +00002248 SmallSetVector<PHINode *, 8> &PHIUsers;
2249 SmallSetVector<SelectInst *, 8> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002250
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002251 // Utility IR builder, whose name prefix is setup for each visited use, and
2252 // the insertion point is set to point to the user.
2253 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002254
2255public:
Chandler Carruth83934062014-10-16 21:11:55 +00002256 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002257 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002258 uint64_t NewAllocaBeginOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00002259 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2260 VectorType *PromotableVecTy,
Davide Italiano81a26da2017-04-27 23:09:01 +00002261 SmallSetVector<PHINode *, 8> &PHIUsers,
2262 SmallSetVector<SelectInst *, 8> &SelectUsers)
Chandler Carruth83934062014-10-16 21:11:55 +00002263 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002264 NewAllocaBeginOffset(NewAllocaBeginOffset),
2265 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002266 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002267 IntTy(IsIntegerPromotable
2268 ? Type::getIntNTy(
2269 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002270 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Craig Topperf40110f2014-04-25 05:29:35 +00002271 : nullptr),
Chandler Carruth2dc96822014-10-18 00:44:02 +00002272 VecTy(PromotableVecTy),
2273 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2274 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002275 PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002276 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002277 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002278 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002279 "Only multiple-of-8 sized vector elements are viable");
2280 ++NumVectorized;
2281 }
Chandler Carruth2dc96822014-10-18 00:44:02 +00002282 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002283 }
2284
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002285 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002286 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002287 BeginOffset = I->beginOffset();
2288 EndOffset = I->endOffset();
2289 IsSplittable = I->isSplittable();
2290 IsSplit =
2291 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002292 DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2293 DEBUG(AS.printSlice(dbgs(), I, ""));
Chandler Carruth0715cba2015-01-01 11:54:38 +00002294 DEBUG(dbgs() << "\n");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002295
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002296 // Compute the intersecting offset range.
2297 assert(BeginOffset < NewAllocaEndOffset);
2298 assert(EndOffset > NewAllocaBeginOffset);
2299 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2300 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2301
2302 SliceSize = NewEndOffset - NewBeginOffset;
2303
Chandler Carruthf0546402013-07-18 07:15:00 +00002304 OldUse = I->getUse();
2305 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002306
Chandler Carruthf0546402013-07-18 07:15:00 +00002307 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2308 IRB.SetInsertPoint(OldUserI);
2309 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2310 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2311
2312 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2313 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002314 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002315 return CanSROA;
2316 }
2317
2318private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002319 // Make sure the other visit overloads are visible.
2320 using Base::visit;
2321
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002322 // Every instruction which can end up as a user must have a rewrite rule.
2323 bool visitInstruction(Instruction &I) {
2324 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2325 llvm_unreachable("No rewrite rule for this instruction!");
2326 }
2327
Chandler Carruth47954c82014-02-26 05:12:43 +00002328 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2329 // Note that the offset computation can use BeginOffset or NewBeginOffset
2330 // interchangeably for unsplit slices.
2331 assert(IsSplit || BeginOffset == NewBeginOffset);
2332 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2333
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002334#ifndef NDEBUG
2335 StringRef OldName = OldPtr->getName();
2336 // Skip through the last '.sroa.' component of the name.
2337 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2338 if (LastSROAPrefix != StringRef::npos) {
2339 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2340 // Look for an SROA slice index.
2341 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2342 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2343 // Strip the index and look for the offset.
2344 OldName = OldName.substr(IndexEnd + 1);
2345 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2346 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2347 // Strip the offset.
2348 OldName = OldName.substr(OffsetEnd + 1);
2349 }
2350 }
2351 // Strip any SROA suffixes as well.
2352 OldName = OldName.substr(0, OldName.find(".sroa_"));
2353#endif
Chandler Carruth47954c82014-02-26 05:12:43 +00002354
2355 return getAdjustedPtr(IRB, DL, &NewAI,
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002356 APInt(DL.getPointerTypeSizeInBits(PointerTy), Offset),
2357 PointerTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002358#ifndef NDEBUG
2359 Twine(OldName) + "."
2360#else
2361 Twine()
2362#endif
2363 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002364 }
2365
Chandler Carruth113dc642014-12-20 02:39:18 +00002366 /// \brief Compute suitable alignment to access this slice of the *new*
2367 /// alloca.
Chandler Carruth2659e502014-02-26 05:02:19 +00002368 ///
2369 /// You can optionally pass a type to this routine and if that type's ABI
2370 /// alignment is itself suitable, this will return zero.
Craig Topperf40110f2014-04-25 05:29:35 +00002371 unsigned getSliceAlign(Type *Ty = nullptr) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002372 unsigned NewAIAlign = NewAI.getAlignment();
2373 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002374 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth113dc642014-12-20 02:39:18 +00002375 unsigned Align =
2376 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
Chandler Carruth2659e502014-02-26 05:02:19 +00002377 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002378 }
2379
Chandler Carruth845b73c2012-11-21 08:16:30 +00002380 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002381 assert(VecTy && "Can only call getIndex when rewriting a vector");
2382 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2383 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2384 uint32_t Index = RelOffset / ElementSize;
2385 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002386 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002387 }
2388
2389 void deleteIfTriviallyDead(Value *V) {
2390 Instruction *I = cast<Instruction>(V);
2391 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002392 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002393 }
2394
Chandler Carruthea27cf02014-02-26 04:25:04 +00002395 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002396 unsigned BeginIndex = getIndex(NewBeginOffset);
2397 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002398 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002399
Chandler Carruth113dc642014-12-20 02:39:18 +00002400 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002401 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002402 }
2403
Chandler Carruthea27cf02014-02-26 04:25:04 +00002404 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002405 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002406 assert(!LI.isVolatile());
Chandler Carruth113dc642014-12-20 02:39:18 +00002407 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002408 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002409 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2410 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth4b682f62015-08-28 09:03:52 +00002411 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
2412 IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
2413 V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
2414 }
2415 // It is possible that the extracted type is not the load type. This
2416 // happens if there is a load past the end of the alloca, and as
2417 // a consequence the slice is narrower but still a candidate for integer
2418 // lowering. To handle this case, we just zero extend the extracted
2419 // integer.
2420 assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&
2421 "Can only handle an extract for an overly wide load");
2422 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
2423 V = IRB.CreateZExt(V, LI.getType());
Chandler Carruth18db7952012-11-20 01:12:50 +00002424 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002425 }
2426
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002427 bool visitLoadInst(LoadInst &LI) {
2428 DEBUG(dbgs() << " original: " << LI << "\n");
2429 Value *OldOp = LI.getOperand(0);
2430 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002431
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002432 unsigned AS = LI.getPointerAddressSpace();
2433
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002434 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002435 : LI.getType();
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002436 const bool IsLoadPastEnd = DL.getTypeStoreSize(TargetTy) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002437 bool IsPtrAdjusted = false;
2438 Value *V;
2439 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002440 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002441 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002442 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002443 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002444 NewEndOffset == NewAllocaEndOffset &&
2445 (canConvertValue(DL, NewAllocaTy, TargetTy) ||
2446 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
2447 TargetTy->isIntegerTy()))) {
David Majnemer62690b12015-07-14 06:19:58 +00002448 LoadInst *NewLI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2449 LI.isVolatile(), LI.getName());
2450 if (LI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002451 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
Luqman Aden3f807c92017-03-22 19:16:39 +00002452
Chandler Carruth3f81d802017-06-27 08:32:03 +00002453 // Any !nonnull metadata or !range metadata on the old load is also valid
2454 // on the new load. This is even true in some cases even when the loads
2455 // are different types, for example by mapping !nonnull metadata to
2456 // !range metadata by modeling the null pointer constant converted to the
2457 // integer type.
2458 // FIXME: Add support for range metadata here. Currently the utilities
2459 // for this don't propagate range metadata in trivial cases from one
2460 // integer load to another, don't handle non-addrspace-0 null pointers
2461 // correctly, and don't have any support for mapping ranges as the
2462 // integer type becomes winder or narrower.
2463 if (MDNode *N = LI.getMetadata(LLVMContext::MD_nonnull))
2464 copyNonnullMetadata(LI, N, *NewLI);
2465
Luqman Aden3f807c92017-03-22 19:16:39 +00002466 // Try to preserve nonnull metadata
David Majnemer62690b12015-07-14 06:19:58 +00002467 V = NewLI;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002468
2469 // If this is an integer load past the end of the slice (which means the
2470 // bytes outside the slice are undef or this load is dead) just forcibly
2471 // fix the integer size with correct handling of endianness.
2472 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2473 if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
2474 if (AITy->getBitWidth() < TITy->getBitWidth()) {
2475 V = IRB.CreateZExt(V, TITy, "load.ext");
2476 if (DL.isBigEndian())
2477 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2478 "endian_shift");
2479 }
Chandler Carruth18db7952012-11-20 01:12:50 +00002480 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002481 Type *LTy = TargetTy->getPointerTo(AS);
David Majnemer62690b12015-07-14 06:19:58 +00002482 LoadInst *NewLI = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2483 getSliceAlign(TargetTy),
2484 LI.isVolatile(), LI.getName());
2485 if (LI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002486 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
David Majnemer62690b12015-07-14 06:19:58 +00002487
2488 V = NewLI;
Chandler Carruth18db7952012-11-20 01:12:50 +00002489 IsPtrAdjusted = true;
2490 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002491 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002492
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002493 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002494 assert(!LI.isVolatile());
2495 assert(LI.getType()->isIntegerTy() &&
2496 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002497 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002498 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002499 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002500 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002501 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002502 // Move the insertion point just past the load so that we can refer to it.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002503 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002504 // Create a placeholder value with the same type as LI to use as the
2505 // basis for the new value. This allows us to replace the uses of LI with
2506 // the computed value, and then replace the placeholder with LI, leaving
2507 // LI only used for this computation.
Chandler Carruth113dc642014-12-20 02:39:18 +00002508 Value *Placeholder =
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002509 new LoadInst(UndefValue::get(LI.getType()->getPointerTo(AS)));
Chandler Carruth24ac8302015-01-02 03:55:54 +00002510 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2511 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002512 LI.replaceAllUsesWith(V);
2513 Placeholder->replaceAllUsesWith(&LI);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002514 Placeholder->deleteValue();
Chandler Carruth18db7952012-11-20 01:12:50 +00002515 } else {
2516 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002517 }
2518
Chandler Carruth18db7952012-11-20 01:12:50 +00002519 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002520 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002521 DEBUG(dbgs() << " to: " << *V << "\n");
2522 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002523 }
2524
Chandler Carruthea27cf02014-02-26 04:25:04 +00002525 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002526 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002527 unsigned BeginIndex = getIndex(NewBeginOffset);
2528 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002529 assert(EndIndex > BeginIndex && "Empty vector!");
2530 unsigned NumElements = EndIndex - BeginIndex;
2531 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth113dc642014-12-20 02:39:18 +00002532 Type *SliceTy = (NumElements == 1)
2533 ? ElementTy
2534 : VectorType::get(ElementTy, NumElements);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002535 if (V->getType() != SliceTy)
2536 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002537
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002538 // Mix in the existing elements.
Chandler Carruth113dc642014-12-20 02:39:18 +00002539 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002540 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2541 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002542 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002543 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002544
2545 (void)Store;
2546 DEBUG(dbgs() << " to: " << *Store << "\n");
2547 return true;
2548 }
2549
Chandler Carruthea27cf02014-02-26 04:25:04 +00002550 bool rewriteIntegerStore(Value *V, StoreInst &SI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002551 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002552 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002553 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002554 Value *Old =
2555 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002556 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002557 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2558 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth113dc642014-12-20 02:39:18 +00002559 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002560 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002561 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002562 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Dorit Nuzmand1247a62016-09-22 07:56:23 +00002563 Store->copyMetadata(SI, LLVMContext::MD_mem_parallel_loop_access);
Chandler Carruth18db7952012-11-20 01:12:50 +00002564 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002565 DEBUG(dbgs() << " to: " << *Store << "\n");
2566 return true;
2567 }
2568
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002569 bool visitStoreInst(StoreInst &SI) {
2570 DEBUG(dbgs() << " original: " << SI << "\n");
2571 Value *OldOp = SI.getOperand(1);
2572 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002573
Chandler Carruth18db7952012-11-20 01:12:50 +00002574 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002575
Chandler Carruthac8317f2012-10-04 12:33:50 +00002576 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2577 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002578 if (V->getType()->isPointerTy())
2579 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002580 Pass.PostPromotionWorklist.insert(AI);
2581
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002582 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002583 assert(!SI.isVolatile());
2584 assert(V->getType()->isIntegerTy() &&
2585 "Only integer type loads and stores are split");
2586 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002587 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002588 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002589 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth24ac8302015-01-02 03:55:54 +00002590 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2591 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002592 }
2593
Chandler Carruth18db7952012-11-20 01:12:50 +00002594 if (VecTy)
Chandler Carruthea27cf02014-02-26 04:25:04 +00002595 return rewriteVectorizedStoreInst(V, SI, OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002596 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthea27cf02014-02-26 04:25:04 +00002597 return rewriteIntegerStore(V, SI);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002598
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002599 const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002600 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002601 if (NewBeginOffset == NewAllocaBeginOffset &&
2602 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002603 (canConvertValue(DL, V->getType(), NewAllocaTy) ||
2604 (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
2605 V->getType()->isIntegerTy()))) {
2606 // If this is an integer store past the end of slice (and thus the bytes
2607 // past that point are irrelevant or this is unreachable), truncate the
2608 // value prior to storing.
2609 if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
2610 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2611 if (VITy->getBitWidth() > AITy->getBitWidth()) {
2612 if (DL.isBigEndian())
2613 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2614 "endian_shift");
2615 V = IRB.CreateTrunc(V, AITy, "load.trunc");
2616 }
2617
Chandler Carruth90a735d2013-07-19 07:21:28 +00002618 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002619 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2620 SI.isVolatile());
2621 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002622 unsigned AS = SI.getPointerAddressSpace();
2623 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS));
Chandler Carruth2659e502014-02-26 05:02:19 +00002624 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2625 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002626 }
Dorit Nuzmand1247a62016-09-22 07:56:23 +00002627 NewSI->copyMetadata(SI, LLVMContext::MD_mem_parallel_loop_access);
David Majnemer62690b12015-07-14 06:19:58 +00002628 if (SI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002629 NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
Chandler Carruth18db7952012-11-20 01:12:50 +00002630 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002631 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002632
2633 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2634 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002635 }
2636
Chandler Carruth514f34f2012-12-17 04:07:30 +00002637 /// \brief Compute an integer value from splatting an i8 across the given
2638 /// number of bytes.
2639 ///
2640 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2641 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002642 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002643 ///
2644 /// \param V The i8 value to splat.
2645 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002646 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002647 assert(Size > 0 && "Expected a positive number of bytes.");
2648 IntegerType *VTy = cast<IntegerType>(V->getType());
2649 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2650 if (Size == 1)
2651 return V;
2652
Chandler Carruth113dc642014-12-20 02:39:18 +00002653 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2654 V = IRB.CreateMul(
2655 IRB.CreateZExt(V, SplatIntTy, "zext"),
2656 ConstantExpr::getUDiv(
2657 Constant::getAllOnesValue(SplatIntTy),
2658 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2659 SplatIntTy)),
2660 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002661 return V;
2662 }
2663
Chandler Carruthccca5042012-12-17 04:07:37 +00002664 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002665 Value *getVectorSplat(Value *V, unsigned NumElements) {
2666 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002667 DEBUG(dbgs() << " splat: " << *V << "\n");
2668 return V;
2669 }
2670
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002671 bool visitMemSetInst(MemSetInst &II) {
2672 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002673 assert(II.getRawDest() == OldPtr);
2674
2675 // If the memset has a variable size, it cannot be split, just adjust the
2676 // pointer to the new alloca.
2677 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002678 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002679 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002680 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Pete Cooper67cf9a72015-11-19 05:56:52 +00002681 Type *CstTy = II.getAlignmentCst()->getType();
2682 II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002683
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002684 deleteIfTriviallyDead(OldPtr);
2685 return false;
2686 }
2687
2688 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002689 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002690
2691 Type *AllocaTy = NewAI.getAllocatedType();
2692 Type *ScalarTy = AllocaTy->getScalarType();
2693
2694 // If this doesn't map cleanly onto the alloca type, and that type isn't
2695 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002696 if (!VecTy && !IntTy &&
Chandler Carruth113dc642014-12-20 02:39:18 +00002697 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002698 SliceSize != DL.getTypeStoreSize(AllocaTy) ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002699 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002700 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
Chandler Carruth113dc642014-12-20 02:39:18 +00002701 DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002702 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002703 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2704 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002705 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2706 getSliceAlign(), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002707 (void)New;
2708 DEBUG(dbgs() << " to: " << *New << "\n");
2709 return false;
2710 }
2711
2712 // If we can represent this as a simple value, we have to build the actual
2713 // value to store, which requires expanding the byte present in memset to
2714 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002715 // splatting the byte to a sufficiently wide integer, splatting it across
2716 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002717 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002718
Chandler Carruthccca5042012-12-17 04:07:37 +00002719 if (VecTy) {
2720 // If this is a memset of a vectorized alloca, insert it.
2721 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002722
Chandler Carruthf0546402013-07-18 07:15:00 +00002723 unsigned BeginIndex = getIndex(NewBeginOffset);
2724 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002725 assert(EndIndex > BeginIndex && "Empty vector!");
2726 unsigned NumElements = EndIndex - BeginIndex;
2727 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2728
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002729 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002730 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2731 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002732 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002733 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002734
Chandler Carruth113dc642014-12-20 02:39:18 +00002735 Value *Old =
2736 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002737 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002738 } else if (IntTy) {
2739 // If this is a memset on an alloca where we can widen stores, insert the
2740 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002741 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002742
Chandler Carruthf0546402013-07-18 07:15:00 +00002743 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002744 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002745
2746 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2747 EndOffset != NewAllocaBeginOffset)) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002748 Value *Old =
2749 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002750 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002751 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002752 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002753 } else {
2754 assert(V->getType() == IntTy &&
2755 "Wrong type for an alloca wide integer!");
2756 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002757 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002758 } else {
2759 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002760 assert(NewBeginOffset == NewAllocaBeginOffset);
2761 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002762
Chandler Carruth90a735d2013-07-19 07:21:28 +00002763 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002764 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002765 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002766
Chandler Carruth90a735d2013-07-19 07:21:28 +00002767 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002768 }
2769
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002770 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002771 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002772 (void)New;
2773 DEBUG(dbgs() << " to: " << *New << "\n");
2774 return !II.isVolatile();
2775 }
2776
2777 bool visitMemTransferInst(MemTransferInst &II) {
2778 // Rewriting of memory transfer instructions can be a bit tricky. We break
2779 // them into two categories: split intrinsics and unsplit intrinsics.
2780
2781 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002782
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002783 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002784 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002785 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002786
Chandler Carruthaa72b932014-02-26 07:29:54 +00002787 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002788
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002789 // For unsplit intrinsics, we simply modify the source and destination
2790 // pointers in place. This isn't just an optimization, it is a matter of
2791 // correctness. With unsplit intrinsics we may be dealing with transfers
2792 // within a single alloca before SROA ran, or with transfers that have
2793 // a variable length. We may also be dealing with memmove instead of
2794 // memcpy, and so simply updating the pointers is the necessary for us to
2795 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002796 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002797 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Pete Cooper67cf9a72015-11-19 05:56:52 +00002798 if (IsDest)
Chandler Carruth8183a502014-02-25 11:08:02 +00002799 II.setDest(AdjustedPtr);
Pete Cooper67cf9a72015-11-19 05:56:52 +00002800 else
Chandler Carruth8183a502014-02-25 11:08:02 +00002801 II.setSource(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002802
Pete Cooper67cf9a72015-11-19 05:56:52 +00002803 if (II.getAlignment() > SliceAlign) {
2804 Type *CstTy = II.getAlignmentCst()->getType();
2805 II.setAlignment(
2806 ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
Chandler Carruth181ed052014-02-26 05:33:36 +00002807 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002808
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002809 DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002810 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002811 return false;
2812 }
2813 // For split transfer intrinsics we have an incredibly useful assurance:
2814 // the source and destination do not reside within the same alloca, and at
2815 // least one of them does not escape. This means that we can replace
2816 // memmove with memcpy, and we don't need to worry about all manner of
2817 // downsides to splitting and transforming the operations.
2818
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002819 // If this doesn't map cleanly onto the alloca type, and that type isn't
2820 // a single value type, just emit a memcpy.
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002821 bool EmitMemCpy =
2822 !VecTy && !IntTy &&
2823 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2824 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2825 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002826
2827 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2828 // size hasn't been shrunk based on analysis of the viable range, this is
2829 // a no-op.
2830 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002831 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002832 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002833
2834 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002835 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002836 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002837 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002838 return false;
2839 }
2840 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002841 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002842
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002843 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2844 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002845 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth113dc642014-12-20 02:39:18 +00002846 if (AllocaInst *AI =
2847 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002848 assert(AI != &OldAI && AI != &NewAI &&
2849 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002850 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002851 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002852
Chandler Carruth286d87e2014-02-26 08:25:02 +00002853 Type *OtherPtrTy = OtherPtr->getType();
2854 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2855
Chandler Carruth181ed052014-02-26 05:33:36 +00002856 // Compute the relative offset for the other pointer within the transfer.
Chandler Carruth286d87e2014-02-26 08:25:02 +00002857 unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
Chandler Carruth181ed052014-02-26 05:33:36 +00002858 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Pete Cooper67cf9a72015-11-19 05:56:52 +00002859 unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2860 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002861
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002862 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002863 // Compute the other pointer, folding as much as possible to produce
2864 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002865 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002866 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002867
Chandler Carruth47954c82014-02-26 05:12:43 +00002868 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002869 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002870 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002871
Pete Cooper67cf9a72015-11-19 05:56:52 +00002872 CallInst *New = IRB.CreateMemCpy(
2873 IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2874 MinAlign(SliceAlign, OtherAlign), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002875 (void)New;
2876 DEBUG(dbgs() << " to: " << *New << "\n");
2877 return false;
2878 }
2879
Chandler Carruthf0546402013-07-18 07:15:00 +00002880 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2881 NewEndOffset == NewAllocaEndOffset;
2882 uint64_t Size = NewEndOffset - NewBeginOffset;
2883 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2884 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002885 unsigned NumElements = EndIndex - BeginIndex;
Chandler Carruth113dc642014-12-20 02:39:18 +00002886 IntegerType *SubIntTy =
2887 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002888
Chandler Carruth286d87e2014-02-26 08:25:02 +00002889 // Reset the other pointer type to match the register type we're going to
2890 // use, but using the address space of the original other pointer.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002891 if (VecTy && !IsWholeAlloca) {
2892 if (NumElements == 1)
2893 OtherPtrTy = VecTy->getElementType();
2894 else
2895 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2896
Chandler Carruth286d87e2014-02-26 08:25:02 +00002897 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002898 } else if (IntTy && !IsWholeAlloca) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00002899 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2900 } else {
2901 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002902 }
2903
Chandler Carruth181ed052014-02-26 05:33:36 +00002904 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002905 OtherPtr->getName() + ".");
Pete Cooper67cf9a72015-11-19 05:56:52 +00002906 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002907 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00002908 unsigned DstAlign = SliceAlign;
2909 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002910 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002911 std::swap(SrcAlign, DstAlign);
2912 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002913
2914 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002915 if (VecTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002916 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002917 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002918 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002919 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002920 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002921 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002922 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002923 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +00002924 Src =
2925 IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002926 }
2927
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002928 if (VecTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002929 Value *Old =
2930 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002931 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002932 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002933 Value *Old =
2934 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002935 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002936 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002937 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2938 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002939 }
2940
Chandler Carruth871ba722012-09-26 10:27:46 +00002941 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00002942 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Chandler Carruth871ba722012-09-26 10:27:46 +00002943 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002944 DEBUG(dbgs() << " to: " << *Store << "\n");
2945 return !II.isVolatile();
2946 }
2947
2948 bool visitIntrinsicInst(IntrinsicInst &II) {
2949 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2950 II.getIntrinsicID() == Intrinsic::lifetime_end);
2951 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002952 assert(II.getArgOperand(1) == OldPtr);
2953
2954 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002955 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002956
Eli Friedman50967752016-11-28 21:50:34 +00002957 // Lifetime intrinsics are only promotable if they cover the whole alloca.
2958 // Therefore, we drop lifetime intrinsics which don't cover the whole
2959 // alloca.
2960 // (In theory, intrinsics which partially cover an alloca could be
2961 // promoted, but PromoteMemToReg doesn't handle that case.)
2962 // FIXME: Check whether the alloca is promotable before dropping the
2963 // lifetime intrinsics?
2964 if (NewBeginOffset != NewAllocaBeginOffset ||
2965 NewEndOffset != NewAllocaEndOffset)
2966 return true;
2967
Chandler Carruth113dc642014-12-20 02:39:18 +00002968 ConstantInt *Size =
2969 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002970 NewEndOffset - NewBeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002971 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002972 Value *New;
2973 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2974 New = IRB.CreateLifetimeStart(Ptr, Size);
2975 else
2976 New = IRB.CreateLifetimeEnd(Ptr, Size);
2977
Edwin Vane82f80d42013-01-29 17:42:24 +00002978 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002979 DEBUG(dbgs() << " to: " << *New << "\n");
Eli Friedman2a65dd12016-08-08 01:30:53 +00002980
Eli Friedman50967752016-11-28 21:50:34 +00002981 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002982 }
2983
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002984 bool visitPHINode(PHINode &PN) {
2985 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00002986 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2987 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002988
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002989 // We would like to compute a new pointer in only one place, but have it be
2990 // as local as possible to the PHI. To do that, we re-use the location of
2991 // the old pointer, which necessarily must be in the right position to
2992 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00002993 IRBuilderTy PtrBuilder(IRB);
David Majnemerd4cffcf2014-09-01 21:20:14 +00002994 if (isa<PHINode>(OldPtr))
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002995 PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
David Majnemerd4cffcf2014-09-01 21:20:14 +00002996 else
2997 PtrBuilder.SetInsertPoint(OldPtr);
Chandler Carruth51175532014-02-25 11:12:04 +00002998 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002999
Chandler Carruth47954c82014-02-26 05:12:43 +00003000 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00003001 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003002 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003003
Chandler Carruth82a57542012-10-01 10:54:05 +00003004 DEBUG(dbgs() << " to: " << PN << "\n");
3005 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003006
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003007 // PHIs can't be promoted on their own, but often can be speculated. We
3008 // check the speculation outside of the rewriter so that we see the
3009 // fully-rewritten alloca.
3010 PHIUsers.insert(&PN);
3011 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003012 }
3013
3014 bool visitSelectInst(SelectInst &SI) {
3015 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003016 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3017 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00003018 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
3019 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003020
Chandler Carruth47954c82014-02-26 05:12:43 +00003021 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003022 // Replace the operands which were using the old pointer.
3023 if (SI.getOperand(1) == OldPtr)
3024 SI.setOperand(1, NewPtr);
3025 if (SI.getOperand(2) == OldPtr)
3026 SI.setOperand(2, NewPtr);
3027
Chandler Carruth82a57542012-10-01 10:54:05 +00003028 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003029 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003030
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003031 // Selects can't be promoted on their own, but often can be speculated. We
3032 // check the speculation outside of the rewriter so that we see the
3033 // fully-rewritten alloca.
3034 SelectUsers.insert(&SI);
3035 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003036 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003037};
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003038
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003039namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003040
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003041/// \brief Visitor to rewrite aggregate loads and stores as scalar.
3042///
3043/// This pass aggressively rewrites all aggregate loads and stores on
3044/// a particular pointer (or any pointer derived from it which we can identify)
3045/// with scalar loads and stores.
3046class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3047 // Befriend the base class so it can delegate to private visit methods.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003048 friend class InstVisitor<AggLoadStoreRewriter, bool>;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003049
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003050 /// Queue of pointer uses to analyze and potentially rewrite.
3051 SmallVector<Use *, 8> Queue;
3052
3053 /// Set to prevent us from cycling with phi nodes and loops.
3054 SmallPtrSet<User *, 8> Visited;
3055
3056 /// The current pointer use being rewritten. This is used to dig up the used
3057 /// value (as opposed to the user).
3058 Use *U;
3059
3060public:
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003061 /// Rewrite loads and stores through a pointer and all pointers derived from
3062 /// it.
3063 bool rewrite(Instruction &I) {
3064 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3065 enqueueUsers(I);
3066 bool Changed = false;
3067 while (!Queue.empty()) {
3068 U = Queue.pop_back_val();
3069 Changed |= visit(cast<Instruction>(U->getUser()));
3070 }
3071 return Changed;
3072 }
3073
3074private:
3075 /// Enqueue all the users of the given instruction for further processing.
3076 /// This uses a set to de-duplicate users.
3077 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003078 for (Use &U : I.uses())
David Blaikie70573dc2014-11-19 07:49:26 +00003079 if (Visited.insert(U.getUser()).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003080 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003081 }
3082
3083 // Conservative default is to not rewrite anything.
3084 bool visitInstruction(Instruction &I) { return false; }
3085
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003086 /// \brief Generic recursive split emission class.
Chandler Carruth113dc642014-12-20 02:39:18 +00003087 template <typename Derived> class OpSplitter {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003088 protected:
3089 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00003090 IRBuilderTy IRB;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003091
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003092 /// The indices which to be used with insert- or extractvalue to select the
3093 /// appropriate value within the aggregate.
3094 SmallVector<unsigned, 4> Indices;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003095
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003096 /// The indices to a GEP instruction which will move Ptr to the correct slot
3097 /// within the aggregate.
3098 SmallVector<Value *, 4> GEPIndices;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003099
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003100 /// The base pointer of the original op, used as a base for GEPing the
3101 /// split operations.
3102 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003103
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003104 /// Initialize the splitter with an insertion point, Ptr and start with a
3105 /// single zero GEP index.
3106 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003107 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003108
3109 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003110 /// \brief Generic recursive split emission routine.
3111 ///
3112 /// This method recursively splits an aggregate op (load or store) into
3113 /// scalar or vector ops. It splits recursively until it hits a single value
3114 /// and emits that single value operation via the template argument.
3115 ///
3116 /// The logic of this routine relies on GEPs and insertvalue and
3117 /// extractvalue all operating with the same fundamental index list, merely
3118 /// formatted differently (GEPs need actual values).
3119 ///
3120 /// \param Ty The type being split recursively into smaller ops.
3121 /// \param Agg The aggregate value being built up or stored, depending on
3122 /// whether this is splitting a load or a store respectively.
3123 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3124 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003125 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003126
3127 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3128 unsigned OldSize = Indices.size();
3129 (void)OldSize;
3130 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3131 ++Idx) {
3132 assert(Indices.size() == OldSize && "Did not return to the old size");
3133 Indices.push_back(Idx);
3134 GEPIndices.push_back(IRB.getInt32(Idx));
3135 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3136 GEPIndices.pop_back();
3137 Indices.pop_back();
3138 }
3139 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003140 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003141
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003142 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3143 unsigned OldSize = Indices.size();
3144 (void)OldSize;
3145 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3146 ++Idx) {
3147 assert(Indices.size() == OldSize && "Did not return to the old size");
3148 Indices.push_back(Idx);
3149 GEPIndices.push_back(IRB.getInt32(Idx));
3150 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3151 GEPIndices.pop_back();
3152 Indices.pop_back();
3153 }
3154 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003155 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003156
3157 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003158 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003159 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003160
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003161 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003162 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003163 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003164
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003165 /// Emit a leaf load of a single value. This is called at the leaves of the
3166 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003167 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003168 assert(Ty->isSingleValueType());
3169 // Load the single value and insert it using the indices.
David Blaikieaa41cd52015-04-03 21:33:42 +00003170 Value *GEP =
3171 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
Jakub Staszak3c6583a2013-02-19 22:14:45 +00003172 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003173 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3174 DEBUG(dbgs() << " to: " << *Load << "\n");
3175 }
3176 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003177
3178 bool visitLoadInst(LoadInst &LI) {
3179 assert(LI.getPointerOperand() == *U);
3180 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3181 return false;
3182
3183 // We have an aggregate being loaded, split it apart.
3184 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003185 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003186 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003187 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003188 LI.replaceAllUsesWith(V);
3189 LI.eraseFromParent();
3190 return true;
3191 }
3192
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003193 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003194 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003195 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003196
3197 /// Emit a leaf store of a single value. This is called at the leaves of the
3198 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003199 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003200 assert(Ty->isSingleValueType());
3201 // Extract the single value and store it using the indices.
Patrik Hagglunda83706e2016-06-20 10:19:00 +00003202 //
3203 // The gep and extractvalue values are factored out of the CreateStore
3204 // call to make the output independent of the argument evaluation order.
Patrik Hagglund4e0bd842016-06-20 11:19:58 +00003205 Value *ExtractValue =
3206 IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
3207 Value *InBoundsGEP =
3208 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
Patrik Hagglunda83706e2016-06-20 10:19:00 +00003209 Value *Store = IRB.CreateStore(ExtractValue, InBoundsGEP);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003210 (void)Store;
3211 DEBUG(dbgs() << " to: " << *Store << "\n");
3212 }
3213 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003214
3215 bool visitStoreInst(StoreInst &SI) {
3216 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3217 return false;
3218 Value *V = SI.getValueOperand();
3219 if (V->getType()->isSingleValueType())
3220 return false;
3221
3222 // We have an aggregate being stored, split it apart.
3223 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003224 StoreOpSplitter Splitter(&SI, *U);
3225 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003226 SI.eraseFromParent();
3227 return true;
3228 }
3229
3230 bool visitBitCastInst(BitCastInst &BC) {
3231 enqueueUsers(BC);
3232 return false;
3233 }
3234
3235 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3236 enqueueUsers(GEPI);
3237 return false;
3238 }
3239
3240 bool visitPHINode(PHINode &PN) {
3241 enqueueUsers(PN);
3242 return false;
3243 }
3244
3245 bool visitSelectInst(SelectInst &SI) {
3246 enqueueUsers(SI);
3247 return false;
3248 }
3249};
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003250
3251} // end anonymous namespace
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003252
Chandler Carruthba931992012-10-13 10:49:33 +00003253/// \brief Strip aggregate type wrapping.
3254///
3255/// This removes no-op aggregate types wrapping an underlying type. It will
3256/// strip as many layers of types as it can without changing either the type
3257/// size or the allocated size.
3258static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3259 if (Ty->isSingleValueType())
3260 return Ty;
3261
3262 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3263 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3264
3265 Type *InnerTy;
3266 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3267 InnerTy = ArrTy->getElementType();
3268 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3269 const StructLayout *SL = DL.getStructLayout(STy);
3270 unsigned Index = SL->getElementContainingOffset(0);
3271 InnerTy = STy->getElementType(Index);
3272 } else {
3273 return Ty;
3274 }
3275
3276 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3277 TypeSize > DL.getTypeSizeInBits(InnerTy))
3278 return Ty;
3279
3280 return stripAggregateTypeWrapping(DL, InnerTy);
3281}
3282
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003283/// \brief Try to find a partition of the aggregate type passed in for a given
3284/// offset and size.
3285///
3286/// This recurses through the aggregate type and tries to compute a subtype
3287/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003288/// of an array, it will even compute a new array type for that sub-section,
3289/// and the same for structs.
3290///
3291/// Note that this routine is very strict and tries to find a partition of the
3292/// type which produces the *exact* right offset and size. It is not forgiving
3293/// when the size or offset cause either end of type-based partition to be off.
3294/// Also, this is a best-effort routine. It is reasonable to give up and not
3295/// return a type if necessary.
Chandler Carruth113dc642014-12-20 02:39:18 +00003296static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3297 uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003298 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3299 return stripAggregateTypeWrapping(DL, Ty);
3300 if (Offset > DL.getTypeAllocSize(Ty) ||
3301 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003302 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003303
3304 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003305 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003306 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003307 uint64_t NumSkippedElements = Offset / ElementSize;
Peter Collingbournebc070522016-12-02 03:20:58 +00003308 if (NumSkippedElements >= SeqTy->getNumElements())
3309 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003310 Offset -= NumSkippedElements * ElementSize;
3311
3312 // First check if we need to recurse.
3313 if (Offset > 0 || Size < ElementSize) {
3314 // Bail if the partition ends in a different array element.
3315 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003316 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003317 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003318 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003319 }
3320 assert(Offset == 0);
3321
3322 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003323 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003324 assert(Size > ElementSize);
3325 uint64_t NumElements = Size / ElementSize;
3326 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003327 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003328 return ArrayType::get(ElementTy, NumElements);
3329 }
3330
3331 StructType *STy = dyn_cast<StructType>(Ty);
3332 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003333 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003334
Chandler Carruth90a735d2013-07-19 07:21:28 +00003335 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003336 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003337 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003338 uint64_t EndOffset = Offset + Size;
3339 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003340 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003341
3342 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003343 Offset -= SL->getElementOffset(Index);
3344
3345 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003346 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003347 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003348 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003349
3350 // See if any partition must be contained by the element.
3351 if (Offset > 0 || Size < ElementSize) {
3352 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003353 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003354 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003355 }
3356 assert(Offset == 0);
3357
3358 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003359 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003360
3361 StructType::element_iterator EI = STy->element_begin() + Index,
3362 EE = STy->element_end();
3363 if (EndOffset < SL->getSizeInBytes()) {
3364 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3365 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003366 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003367
3368 // Don't try to form "natural" types if the elements don't line up with the
3369 // expected size.
3370 // FIXME: We could potentially recurse down through the last element in the
3371 // sub-struct to find a natural end point.
3372 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003373 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003374
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003375 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003376 EE = STy->element_begin() + EndIndex;
3377 }
3378
3379 // Try to build up a sub-structure.
Chandler Carruth113dc642014-12-20 02:39:18 +00003380 StructType *SubTy =
3381 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003382 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003383 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003384 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003385
Chandler Carruth054a40a2012-09-14 11:08:31 +00003386 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003387}
3388
Chandler Carruth0715cba2015-01-01 11:54:38 +00003389/// \brief Pre-split loads and stores to simplify rewriting.
3390///
3391/// We want to break up the splittable load+store pairs as much as
3392/// possible. This is important to do as a preprocessing step, as once we
3393/// start rewriting the accesses to partitions of the alloca we lose the
3394/// necessary information to correctly split apart paired loads and stores
3395/// which both point into this alloca. The case to consider is something like
3396/// the following:
3397///
3398/// %a = alloca [12 x i8]
3399/// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3400/// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3401/// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3402/// %iptr1 = bitcast i8* %gep1 to i64*
3403/// %iptr2 = bitcast i8* %gep2 to i64*
3404/// %fptr1 = bitcast i8* %gep1 to float*
3405/// %fptr2 = bitcast i8* %gep2 to float*
3406/// %fptr3 = bitcast i8* %gep3 to float*
3407/// store float 0.0, float* %fptr1
3408/// store float 1.0, float* %fptr2
3409/// %v = load i64* %iptr1
3410/// store i64 %v, i64* %iptr2
3411/// %f1 = load float* %fptr2
3412/// %f2 = load float* %fptr3
3413///
3414/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3415/// promote everything so we recover the 2 SSA values that should have been
3416/// there all along.
3417///
3418/// \returns true if any changes are made.
3419bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
3420 DEBUG(dbgs() << "Pre-splitting loads and stores\n");
3421
3422 // Track the loads and stores which are candidates for pre-splitting here, in
3423 // the order they first appear during the partition scan. These give stable
3424 // iteration order and a basis for tracking which loads and stores we
3425 // actually split.
3426 SmallVector<LoadInst *, 4> Loads;
3427 SmallVector<StoreInst *, 4> Stores;
3428
3429 // We need to accumulate the splits required of each load or store where we
3430 // can find them via a direct lookup. This is important to cross-check loads
3431 // and stores against each other. We also track the slice so that we can kill
3432 // all the slices that end up split.
3433 struct SplitOffsets {
3434 Slice *S;
3435 std::vector<uint64_t> Splits;
3436 };
3437 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3438
Chandler Carruth73b01642015-01-05 04:17:53 +00003439 // Track loads out of this alloca which cannot, for any reason, be pre-split.
3440 // This is important as we also cannot pre-split stores of those loads!
3441 // FIXME: This is all pretty gross. It means that we can be more aggressive
3442 // in pre-splitting when the load feeding the store happens to come from
3443 // a separate alloca. Put another way, the effectiveness of SROA would be
3444 // decreased by a frontend which just concatenated all of its local allocas
3445 // into one big flat alloca. But defeating such patterns is exactly the job
3446 // SROA is tasked with! Sadly, to not have this discrepancy we would have
3447 // change store pre-splitting to actually force pre-splitting of the load
3448 // that feeds it *and all stores*. That makes pre-splitting much harder, but
3449 // maybe it would make it more principled?
3450 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3451
Chandler Carruth0715cba2015-01-01 11:54:38 +00003452 DEBUG(dbgs() << " Searching for candidate loads and stores\n");
3453 for (auto &P : AS.partitions()) {
3454 for (Slice &S : P) {
Chandler Carruth73b01642015-01-05 04:17:53 +00003455 Instruction *I = cast<Instruction>(S.getUse()->getUser());
Chandler Carruth37f1f122016-03-10 15:31:17 +00003456 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
3457 // If this is a load we have to track that it can't participate in any
3458 // pre-splitting. If this is a store of a load we have to track that
3459 // that load also can't participate in any pre-splitting.
Chandler Carruth73b01642015-01-05 04:17:53 +00003460 if (auto *LI = dyn_cast<LoadInst>(I))
3461 UnsplittableLoads.insert(LI);
Chandler Carruth37f1f122016-03-10 15:31:17 +00003462 else if (auto *SI = dyn_cast<StoreInst>(I))
3463 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
3464 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003465 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003466 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003467 assert(P.endOffset() > S.beginOffset() &&
3468 "Empty or backwards partition!");
3469
3470 // Determine if this is a pre-splittable slice.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003471 if (auto *LI = dyn_cast<LoadInst>(I)) {
3472 assert(!LI->isVolatile() && "Cannot split volatile loads!");
3473
3474 // The load must be used exclusively to store into other pointers for
3475 // us to be able to arbitrarily pre-split it. The stores must also be
3476 // simple to avoid changing semantics.
3477 auto IsLoadSimplyStored = [](LoadInst *LI) {
3478 for (User *LU : LI->users()) {
3479 auto *SI = dyn_cast<StoreInst>(LU);
3480 if (!SI || !SI->isSimple())
3481 return false;
3482 }
3483 return true;
3484 };
Chandler Carruth73b01642015-01-05 04:17:53 +00003485 if (!IsLoadSimplyStored(LI)) {
3486 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003487 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003488 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003489
3490 Loads.push_back(LI);
Chandler Carruthd94a5962016-03-10 14:16:18 +00003491 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
3492 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3493 // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
Chandler Carruth994cde82015-01-01 12:01:03 +00003494 continue;
3495 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3496 if (!StoredLoad || !StoredLoad->isSimple())
3497 continue;
3498 assert(!SI->isVolatile() && "Cannot split volatile stores!");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003499
Chandler Carruth994cde82015-01-01 12:01:03 +00003500 Stores.push_back(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003501 } else {
3502 // Other uses cannot be pre-split.
3503 continue;
3504 }
3505
3506 // Record the initial split.
3507 DEBUG(dbgs() << " Candidate: " << *I << "\n");
3508 auto &Offsets = SplitOffsetsMap[I];
3509 assert(Offsets.Splits.empty() &&
3510 "Should not have splits the first time we see an instruction!");
3511 Offsets.S = &S;
Chandler Carruth24ac8302015-01-02 03:55:54 +00003512 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003513 }
3514
3515 // Now scan the already split slices, and add a split for any of them which
3516 // we're going to pre-split.
3517 for (Slice *S : P.splitSliceTails()) {
3518 auto SplitOffsetsMapI =
3519 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3520 if (SplitOffsetsMapI == SplitOffsetsMap.end())
3521 continue;
3522 auto &Offsets = SplitOffsetsMapI->second;
3523
3524 assert(Offsets.S == S && "Found a mismatched slice!");
3525 assert(!Offsets.Splits.empty() &&
3526 "Cannot have an empty set of splits on the second partition!");
Chandler Carruth24ac8302015-01-02 03:55:54 +00003527 assert(Offsets.Splits.back() ==
3528 P.beginOffset() - Offsets.S->beginOffset() &&
Chandler Carruth0715cba2015-01-01 11:54:38 +00003529 "Previous split does not end where this one begins!");
3530
3531 // Record each split. The last partition's end isn't needed as the size
3532 // of the slice dictates that.
3533 if (S->endOffset() > P.endOffset())
Chandler Carruth24ac8302015-01-02 03:55:54 +00003534 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003535 }
3536 }
3537
3538 // We may have split loads where some of their stores are split stores. For
3539 // such loads and stores, we can only pre-split them if their splits exactly
3540 // match relative to their starting offset. We have to verify this prior to
3541 // any rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003542 Stores.erase(
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003543 llvm::remove_if(Stores,
3544 [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
3545 // Lookup the load we are storing in our map of split
3546 // offsets.
3547 auto *LI = cast<LoadInst>(SI->getValueOperand());
3548 // If it was completely unsplittable, then we're done,
3549 // and this store can't be pre-split.
3550 if (UnsplittableLoads.count(LI))
3551 return true;
Chandler Carruth73b01642015-01-05 04:17:53 +00003552
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003553 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3554 if (LoadOffsetsI == SplitOffsetsMap.end())
3555 return false; // Unrelated loads are definitely safe.
3556 auto &LoadOffsets = LoadOffsetsI->second;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003557
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003558 // Now lookup the store's offsets.
3559 auto &StoreOffsets = SplitOffsetsMap[SI];
Chandler Carruth0715cba2015-01-01 11:54:38 +00003560
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003561 // If the relative offsets of each split in the load and
3562 // store match exactly, then we can split them and we
3563 // don't need to remove them here.
3564 if (LoadOffsets.Splits == StoreOffsets.Splits)
3565 return false;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003566
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003567 DEBUG(dbgs()
3568 << " Mismatched splits for load and store:\n"
3569 << " " << *LI << "\n"
3570 << " " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003571
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003572 // We've found a store and load that we need to split
3573 // with mismatched relative splits. Just give up on them
3574 // and remove both instructions from our list of
3575 // candidates.
3576 UnsplittableLoads.insert(LI);
3577 return true;
3578 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003579 Stores.end());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003580 // Now we have to go *back* through all the stores, because a later store may
Chandler Carruth73b01642015-01-05 04:17:53 +00003581 // have caused an earlier store's load to become unsplittable and if it is
3582 // unsplittable for the later store, then we can't rely on it being split in
3583 // the earlier store either.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003584 Stores.erase(llvm::remove_if(Stores,
3585 [&UnsplittableLoads](StoreInst *SI) {
3586 auto *LI =
3587 cast<LoadInst>(SI->getValueOperand());
3588 return UnsplittableLoads.count(LI);
3589 }),
Chandler Carruth73b01642015-01-05 04:17:53 +00003590 Stores.end());
3591 // Once we've established all the loads that can't be split for some reason,
3592 // filter any that made it into our list out.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003593 Loads.erase(llvm::remove_if(Loads,
3594 [&UnsplittableLoads](LoadInst *LI) {
3595 return UnsplittableLoads.count(LI);
3596 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003597 Loads.end());
3598
3599 // If no loads or stores are left, there is no pre-splitting to be done for
3600 // this alloca.
3601 if (Loads.empty() && Stores.empty())
3602 return false;
3603
3604 // From here on, we can't fail and will be building new accesses, so rig up
3605 // an IR builder.
3606 IRBuilderTy IRB(&AI);
3607
3608 // Collect the new slices which we will merge into the alloca slices.
3609 SmallVector<Slice, 4> NewSlices;
3610
3611 // Track any allocas we end up splitting loads and stores for so we iterate
3612 // on them.
3613 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3614
3615 // At this point, we have collected all of the loads and stores we can
3616 // pre-split, and the specific splits needed for them. We actually do the
3617 // splitting in a specific order in order to handle when one of the loads in
3618 // the value operand to one of the stores.
3619 //
3620 // First, we rewrite all of the split loads, and just accumulate each split
3621 // load in a parallel structure. We also build the slices for them and append
3622 // them to the alloca slices.
3623 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3624 std::vector<LoadInst *> SplitLoads;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003625 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003626 for (LoadInst *LI : Loads) {
3627 SplitLoads.clear();
3628
3629 IntegerType *Ty = cast<IntegerType>(LI->getType());
3630 uint64_t LoadSize = Ty->getBitWidth() / 8;
3631 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3632
3633 auto &Offsets = SplitOffsetsMap[LI];
3634 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3635 "Slice size should always match load size exactly!");
3636 uint64_t BaseOffset = Offsets.S->beginOffset();
3637 assert(BaseOffset + LoadSize > BaseOffset &&
3638 "Cannot represent alloca access size using 64-bit integers!");
3639
3640 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003641 IRB.SetInsertPoint(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003642
3643 DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
3644
3645 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3646 int Idx = 0, Size = Offsets.Splits.size();
3647 for (;;) {
3648 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
Yaxun Liu7c44f342017-06-27 18:26:06 +00003649 auto AS = LI->getPointerAddressSpace();
3650 auto *PartPtrTy = PartTy->getPointerTo(AS);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003651 LoadInst *PLoad = IRB.CreateAlignedLoad(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003652 getAdjustedPtr(IRB, DL, BasePtr,
Yaxun Liu7c44f342017-06-27 18:26:06 +00003653 APInt(DL.getPointerSizeInBits(AS), PartOffset),
Chandler Carruth994cde82015-01-01 12:01:03 +00003654 PartPtrTy, BasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003655 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003656 LI->getName());
Dorit Nuzmand1247a62016-09-22 07:56:23 +00003657 PLoad->copyMetadata(*LI, LLVMContext::MD_mem_parallel_loop_access);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003658
3659 // Append this load onto the list of split loads so we can find it later
3660 // to rewrite the stores.
3661 SplitLoads.push_back(PLoad);
3662
3663 // Now build a new slice for the alloca.
Chandler Carruth994cde82015-01-01 12:01:03 +00003664 NewSlices.push_back(
3665 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3666 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003667 /*IsSplittable*/ false));
Chandler Carruth6044c0b2015-01-01 12:56:47 +00003668 DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3669 << ", " << NewSlices.back().endOffset() << "): " << *PLoad
3670 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003671
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003672 // See if we've handled all the splits.
3673 if (Idx >= Size)
3674 break;
3675
Chandler Carruth0715cba2015-01-01 11:54:38 +00003676 // Setup the next partition.
3677 PartOffset = Offsets.Splits[Idx];
3678 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003679 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3680 }
3681
3682 // Now that we have the split loads, do the slow walk over all uses of the
3683 // load and rewrite them as split stores, or save the split loads to use
3684 // below if the store is going to be split there anyways.
3685 bool DeferredStores = false;
3686 for (User *LU : LI->users()) {
3687 StoreInst *SI = cast<StoreInst>(LU);
3688 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3689 DeferredStores = true;
3690 DEBUG(dbgs() << " Deferred splitting of store: " << *SI << "\n");
3691 continue;
3692 }
3693
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003694 Value *StoreBasePtr = SI->getPointerOperand();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003695 IRB.SetInsertPoint(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003696
3697 DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
3698
3699 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3700 LoadInst *PLoad = SplitLoads[Idx];
3701 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
Chandler Carruth994cde82015-01-01 12:01:03 +00003702 auto *PartPtrTy =
3703 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003704
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003705 auto AS = SI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003706 StoreInst *PStore = IRB.CreateAlignedStore(
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003707 PLoad,
3708 getAdjustedPtr(IRB, DL, StoreBasePtr,
3709 APInt(DL.getPointerSizeInBits(AS), PartOffset),
3710 PartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003711 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Dorit Nuzmand1247a62016-09-22 07:56:23 +00003712 PStore->copyMetadata(*LI, LLVMContext::MD_mem_parallel_loop_access);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003713 DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
3714 }
3715
3716 // We want to immediately iterate on any allocas impacted by splitting
3717 // this store, and we have to track any promotable alloca (indicated by
3718 // a direct store) as needing to be resplit because it is no longer
3719 // promotable.
3720 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3721 ResplitPromotableAllocas.insert(OtherAI);
3722 Worklist.insert(OtherAI);
3723 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3724 StoreBasePtr->stripInBoundsOffsets())) {
3725 Worklist.insert(OtherAI);
3726 }
3727
3728 // Mark the original store as dead.
3729 DeadInsts.insert(SI);
3730 }
3731
3732 // Save the split loads if there are deferred stores among the users.
3733 if (DeferredStores)
3734 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3735
3736 // Mark the original load as dead and kill the original slice.
3737 DeadInsts.insert(LI);
3738 Offsets.S->kill();
3739 }
3740
3741 // Second, we rewrite all of the split stores. At this point, we know that
3742 // all loads from this alloca have been split already. For stores of such
3743 // loads, we can simply look up the pre-existing split loads. For stores of
3744 // other loads, we split those loads first and then write split stores of
3745 // them.
3746 for (StoreInst *SI : Stores) {
3747 auto *LI = cast<LoadInst>(SI->getValueOperand());
3748 IntegerType *Ty = cast<IntegerType>(LI->getType());
3749 uint64_t StoreSize = Ty->getBitWidth() / 8;
3750 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3751
3752 auto &Offsets = SplitOffsetsMap[SI];
3753 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3754 "Slice size should always match load size exactly!");
3755 uint64_t BaseOffset = Offsets.S->beginOffset();
3756 assert(BaseOffset + StoreSize > BaseOffset &&
3757 "Cannot represent alloca access size using 64-bit integers!");
3758
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003759 Value *LoadBasePtr = LI->getPointerOperand();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003760 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3761
3762 DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
3763
3764 // Check whether we have an already split load.
3765 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3766 std::vector<LoadInst *> *SplitLoads = nullptr;
3767 if (SplitLoadsMapI != SplitLoadsMap.end()) {
3768 SplitLoads = &SplitLoadsMapI->second;
3769 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3770 "Too few split loads for the number of splits in the store!");
3771 } else {
3772 DEBUG(dbgs() << " of load: " << *LI << "\n");
3773 }
3774
Chandler Carruth0715cba2015-01-01 11:54:38 +00003775 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3776 int Idx = 0, Size = Offsets.Splits.size();
3777 for (;;) {
3778 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
Keno Fischer514a6a52017-06-02 19:04:17 +00003779 auto *LoadPartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3780 auto *StorePartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003781
3782 // Either lookup a split load or create one.
3783 LoadInst *PLoad;
3784 if (SplitLoads) {
3785 PLoad = (*SplitLoads)[Idx];
3786 } else {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003787 IRB.SetInsertPoint(LI);
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003788 auto AS = LI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003789 PLoad = IRB.CreateAlignedLoad(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003790 getAdjustedPtr(IRB, DL, LoadBasePtr,
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003791 APInt(DL.getPointerSizeInBits(AS), PartOffset),
Keno Fischer514a6a52017-06-02 19:04:17 +00003792 LoadPartPtrTy, LoadBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003793 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003794 LI->getName());
3795 }
3796
3797 // And store this partition.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003798 IRB.SetInsertPoint(SI);
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003799 auto AS = SI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003800 StoreInst *PStore = IRB.CreateAlignedStore(
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003801 PLoad,
3802 getAdjustedPtr(IRB, DL, StoreBasePtr,
3803 APInt(DL.getPointerSizeInBits(AS), PartOffset),
3804 StorePartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003805 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003806
3807 // Now build a new slice for the alloca.
3808 NewSlices.push_back(
3809 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3810 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003811 /*IsSplittable*/ false));
Chandler Carruth6044c0b2015-01-01 12:56:47 +00003812 DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3813 << ", " << NewSlices.back().endOffset() << "): " << *PStore
3814 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003815 if (!SplitLoads) {
3816 DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
3817 }
3818
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003819 // See if we've finished all the splits.
3820 if (Idx >= Size)
3821 break;
3822
Chandler Carruth0715cba2015-01-01 11:54:38 +00003823 // Setup the next partition.
3824 PartOffset = Offsets.Splits[Idx];
3825 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003826 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
3827 }
3828
3829 // We want to immediately iterate on any allocas impacted by splitting
3830 // this load, which is only relevant if it isn't a load of this alloca and
3831 // thus we didn't already split the loads above. We also have to keep track
3832 // of any promotable allocas we split loads on as they can no longer be
3833 // promoted.
3834 if (!SplitLoads) {
3835 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
3836 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3837 ResplitPromotableAllocas.insert(OtherAI);
3838 Worklist.insert(OtherAI);
3839 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3840 LoadBasePtr->stripInBoundsOffsets())) {
3841 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3842 Worklist.insert(OtherAI);
3843 }
3844 }
3845
3846 // Mark the original store as dead now that we've split it up and kill its
Chandler Carruth24ac8302015-01-02 03:55:54 +00003847 // slice. Note that we leave the original load in place unless this store
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003848 // was its only use. It may in turn be split up if it is an alloca load
Chandler Carruth24ac8302015-01-02 03:55:54 +00003849 // for some other alloca, but it may be a normal load. This may introduce
3850 // redundant loads, but where those can be merged the rest of the optimizer
3851 // should handle the merging, and this uncovers SSA splits which is more
3852 // important. In practice, the original loads will almost always be fully
3853 // split and removed eventually, and the splits will be merged by any
3854 // trivial CSE, including instcombine.
3855 if (LI->hasOneUse()) {
3856 assert(*LI->user_begin() == SI && "Single use isn't this store!");
3857 DeadInsts.insert(LI);
3858 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003859 DeadInsts.insert(SI);
3860 Offsets.S->kill();
3861 }
3862
Chandler Carruth24ac8302015-01-02 03:55:54 +00003863 // Remove the killed slices that have ben pre-split.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003864 AS.erase(llvm::remove_if(AS, [](const Slice &S) { return S.isDead(); }),
3865 AS.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003866
Chandler Carruth24ac8302015-01-02 03:55:54 +00003867 // Insert our new slices. This will sort and merge them into the sorted
3868 // sequence.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003869 AS.insert(NewSlices);
3870
3871 DEBUG(dbgs() << " Pre-split slices:\n");
3872#ifndef NDEBUG
3873 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
3874 DEBUG(AS.print(dbgs(), I, " "));
3875#endif
3876
3877 // Finally, don't try to promote any allocas that new require re-splitting.
3878 // They have already been added to the worklist above.
3879 PromotableAllocas.erase(
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003880 llvm::remove_if(
David Majnemerc7004902016-08-12 04:32:37 +00003881 PromotableAllocas,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003882 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
3883 PromotableAllocas.end());
3884
3885 return true;
3886}
3887
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003888/// \brief Rewrite an alloca partition's users.
3889///
3890/// This routine drives both of the rewriting goals of the SROA pass. It tries
3891/// to rewrite uses of an alloca partition to be conducive for SSA value
3892/// promotion. If the partition needs a new, more refined alloca, this will
3893/// build that new alloca, preserving as much type information as possible, and
3894/// rewrite the uses of the old alloca to point at the new one and have the
3895/// appropriate new offsets. It also evaluates how successful the rewrite was
3896/// at enabling promotion and if it was successful queues the alloca to be
3897/// promoted.
Adrian Prantl565cc182015-01-20 19:42:22 +00003898AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruth29a18a42015-09-12 09:09:14 +00003899 Partition &P) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003900 // Try to compute a friendly type for this partition of the alloca. This
3901 // won't always succeed, in which case we fall back to a legal integer type
3902 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00003903 Type *SliceTy = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003904 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003905 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003906 if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003907 SliceTy = CommonUseTy;
3908 if (!SliceTy)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003909 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003910 P.beginOffset(), P.size()))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003911 SliceTy = TypePartitionTy;
3912 if ((!SliceTy || (SliceTy->isArrayTy() &&
3913 SliceTy->getArrayElementType()->isIntegerTy())) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003914 DL.isLegalInteger(P.size() * 8))
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003915 SliceTy = Type::getIntNTy(*C, P.size() * 8);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003916 if (!SliceTy)
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003917 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003918 assert(DL.getTypeAllocSize(SliceTy) >= P.size());
Chandler Carruthf0546402013-07-18 07:15:00 +00003919
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003920 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00003921
Chandler Carruth2dc96822014-10-18 00:44:02 +00003922 VectorType *VecTy =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003923 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
Chandler Carruth2dc96822014-10-18 00:44:02 +00003924 if (VecTy)
3925 SliceTy = VecTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003926
3927 // Check for the case where we're going to rewrite to a new alloca of the
3928 // exact same type as the original, and with the same access offsets. In that
3929 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003930 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003931 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003932 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003933 assert(P.beginOffset() == 0 &&
3934 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003935 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003936 // FIXME: We should be able to bail at this point with "nothing changed".
3937 // FIXME: We might want to defer PHI speculation until after here.
Adrian Prantl565cc182015-01-20 19:42:22 +00003938 // FIXME: return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003939 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003940 unsigned Alignment = AI.getAlignment();
3941 if (!Alignment) {
3942 // The minimum alignment which users can rely on when the explicit
3943 // alignment is omitted or zero is that required by the ABI for this
3944 // type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003945 Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003946 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003947 Alignment = MinAlign(Alignment, P.beginOffset());
Chandler Carruth903790e2012-09-29 10:41:21 +00003948 // If we will get at least this much alignment from the type alone, leave
3949 // the alloca's alignment unconstrained.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003950 if (Alignment <= DL.getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003951 Alignment = 0;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003952 NewAI = new AllocaInst(
Matt Arsenault3c1fc762017-04-10 22:27:50 +00003953 SliceTy, AI.getType()->getAddressSpace(), nullptr, Alignment,
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003954 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003955 ++NumNewAllocas;
3956 }
3957
3958 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003959 << "[" << P.beginOffset() << "," << P.endOffset()
3960 << ") to: " << *NewAI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003961
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003962 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00003963 // promoted allocas. We will reset it to this point if the alloca is not in
3964 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003965 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00003966 unsigned NumUses = 0;
Davide Italiano81a26da2017-04-27 23:09:01 +00003967 SmallSetVector<PHINode *, 8> PHIUsers;
3968 SmallSetVector<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003969
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003970 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003971 P.endOffset(), IsIntegerPromotable, VecTy,
3972 PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00003973 bool Promotable = true;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00003974 for (Slice *S : P.splitSliceTails()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003975 Promotable &= Rewriter.visit(S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003976 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003977 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003978 for (Slice &S : P) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003979 Promotable &= Rewriter.visit(&S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003980 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003981 }
3982
Chandler Carruth6c321c12013-07-19 10:57:36 +00003983 NumAllocaPartitionUses += NumUses;
Craig Topper8a950272017-05-18 00:51:39 +00003984 MaxUsesPerAllocaPartition.updateMax(NumUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003985
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003986 // Now that we've processed all the slices in the new partition, check if any
3987 // PHIs or Selects would block promotion.
Davide Italiano81a26da2017-04-27 23:09:01 +00003988 for (PHINode *PHI : PHIUsers)
3989 if (!isSafePHIToSpeculate(*PHI)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003990 Promotable = false;
3991 PHIUsers.clear();
3992 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003993 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003994 }
Davide Italiano81a26da2017-04-27 23:09:01 +00003995
3996 for (SelectInst *Sel : SelectUsers)
3997 if (!isSafeSelectToSpeculate(*Sel)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003998 Promotable = false;
3999 PHIUsers.clear();
4000 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00004001 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004002 }
4003
4004 if (Promotable) {
4005 if (PHIUsers.empty() && SelectUsers.empty()) {
4006 // Promote the alloca.
4007 PromotableAllocas.push_back(NewAI);
4008 } else {
4009 // If we have either PHIs or Selects to speculate, add them to those
4010 // worklists and re-queue the new alloca so that we promote in on the
4011 // next iteration.
Chandler Carruth61747042014-10-16 21:05:14 +00004012 for (PHINode *PHIUser : PHIUsers)
4013 SpeculatablePHIs.insert(PHIUser);
4014 for (SelectInst *SelectUser : SelectUsers)
4015 SpeculatableSelects.insert(SelectUser);
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004016 Worklist.insert(NewAI);
4017 }
4018 } else {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004019 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00004020 while (PostPromotionWorklist.size() > PPWOldSize)
4021 PostPromotionWorklist.pop_back();
David Majnemer30ffc4c2016-04-26 01:05:00 +00004022
4023 // We couldn't promote and we didn't create a new partition, nothing
4024 // happened.
4025 if (NewAI == &AI)
4026 return nullptr;
4027
4028 // If we can't promote the alloca, iterate on it to check for new
4029 // refinements exposed by splitting the current alloca. Don't iterate on an
4030 // alloca which didn't actually change and didn't get promoted.
4031 Worklist.insert(NewAI);
Chandler Carruthf0546402013-07-18 07:15:00 +00004032 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00004033
Adrian Prantl565cc182015-01-20 19:42:22 +00004034 return NewAI;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004035}
4036
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004037/// \brief Walks the slices of an alloca and form partitions based on them,
4038/// rewriting each of their uses.
Chandler Carruth83934062014-10-16 21:11:55 +00004039bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
4040 if (AS.begin() == AS.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00004041 return false;
4042
Chandler Carruth6c321c12013-07-19 10:57:36 +00004043 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004044 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004045 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00004046
Chandler Carruth24ac8302015-01-02 03:55:54 +00004047 // First try to pre-split loads and stores.
Chandler Carruth0715cba2015-01-01 11:54:38 +00004048 Changed |= presplitLoadsAndStores(AI, AS);
4049
Chandler Carruth24ac8302015-01-02 03:55:54 +00004050 // Now that we have identified any pre-splitting opportunities, mark any
4051 // splittable (non-whole-alloca) loads and stores as unsplittable. If we fail
4052 // to split these during pre-splitting, we want to force them to be
4053 // rewritten into a partition.
4054 bool IsSorted = true;
4055 for (Slice &S : AS) {
4056 if (!S.isSplittable())
4057 continue;
4058 // FIXME: We currently leave whole-alloca splittable loads and stores. This
4059 // used to be the only splittable loads and stores and we need to be
4060 // confident that the above handling of splittable loads and stores is
4061 // completely sufficient before we forcibly disable the remaining handling.
4062 if (S.beginOffset() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004063 S.endOffset() >= DL.getTypeAllocSize(AI.getAllocatedType()))
Chandler Carruth24ac8302015-01-02 03:55:54 +00004064 continue;
4065 if (isa<LoadInst>(S.getUse()->getUser()) ||
4066 isa<StoreInst>(S.getUse()->getUser())) {
4067 S.makeUnsplittable();
4068 IsSorted = false;
4069 }
4070 }
4071 if (!IsSorted)
4072 std::sort(AS.begin(), AS.end());
4073
Adrian Prantl941fa752016-12-05 18:04:47 +00004074 /// Describes the allocas introduced by rewritePartition in order to migrate
4075 /// the debug info.
4076 struct Fragment {
Adrian Prantl565cc182015-01-20 19:42:22 +00004077 AllocaInst *Alloca;
4078 uint64_t Offset;
4079 uint64_t Size;
Adrian Prantl941fa752016-12-05 18:04:47 +00004080 Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
Adrian Prantl565cc182015-01-20 19:42:22 +00004081 : Alloca(AI), Offset(O), Size(S) {}
4082 };
Adrian Prantl941fa752016-12-05 18:04:47 +00004083 SmallVector<Fragment, 4> Fragments;
Adrian Prantl565cc182015-01-20 19:42:22 +00004084
Chandler Carruth0715cba2015-01-01 11:54:38 +00004085 // Rewrite each partition.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004086 for (auto &P : AS.partitions()) {
Adrian Prantl565cc182015-01-20 19:42:22 +00004087 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4088 Changed = true;
Adrian Prantl34e75902015-02-09 23:57:22 +00004089 if (NewAI != &AI) {
4090 uint64_t SizeOfByte = 8;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004091 uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
Adrian Prantl34e75902015-02-09 23:57:22 +00004092 // Don't include any padding.
4093 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
Adrian Prantl941fa752016-12-05 18:04:47 +00004094 Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
Adrian Prantl34e75902015-02-09 23:57:22 +00004095 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004096 }
Chandler Carruth6c321c12013-07-19 10:57:36 +00004097 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00004098 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004099
Chandler Carruth6c321c12013-07-19 10:57:36 +00004100 NumAllocaPartitions += NumPartitions;
Craig Topper8a950272017-05-18 00:51:39 +00004101 MaxPartitionsPerAlloca.updateMax(NumPartitions);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004102
Adrian Prantl565cc182015-01-20 19:42:22 +00004103 // Migrate debug information from the old alloca to the new alloca(s)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004104 // and the individual partitions.
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004105 TinyPtrVector<DbgInfoIntrinsic *> DbgDeclares = FindDbgAddrUses(&AI);
4106 if (!DbgDeclares.empty()) {
4107 auto *Var = DbgDeclares.front()->getVariable();
4108 auto *Expr = DbgDeclares.front()->getExpression();
Sanjay Patelaf674fb2015-12-14 17:24:23 +00004109 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
Keno Fischerd5354fd2016-01-14 20:06:34 +00004110 uint64_t AllocaSize = DL.getTypeSizeInBits(AI.getAllocatedType());
Adrian Prantl941fa752016-12-05 18:04:47 +00004111 for (auto Fragment : Fragments) {
4112 // Create a fragment expression describing the new partition or reuse AI's
Adrian Prantl565cc182015-01-20 19:42:22 +00004113 // expression if there is only one partition.
Adrian Prantl941fa752016-12-05 18:04:47 +00004114 auto *FragmentExpr = Expr;
4115 if (Fragment.Size < AllocaSize || Expr->isFragment()) {
Adrian Prantl152ac392015-02-01 00:58:04 +00004116 // If this alloca is already a scalar replacement of a larger aggregate,
Adrian Prantl941fa752016-12-05 18:04:47 +00004117 // Fragment.Offset describes the offset inside the scalar.
Adrian Prantl49797ca2016-12-22 05:27:12 +00004118 auto ExprFragment = Expr->getFragmentInfo();
4119 uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0;
Adrian Prantl941fa752016-12-05 18:04:47 +00004120 uint64_t Start = Offset + Fragment.Offset;
4121 uint64_t Size = Fragment.Size;
Adrian Prantl49797ca2016-12-22 05:27:12 +00004122 if (ExprFragment) {
Adrian Prantl941fa752016-12-05 18:04:47 +00004123 uint64_t AbsEnd =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00004124 ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
Adrian Prantl34e75902015-02-09 23:57:22 +00004125 if (Start >= AbsEnd)
4126 // No need to describe a SROAed padding.
4127 continue;
4128 Size = std::min(Size, AbsEnd - Start);
4129 }
Adrian Prantlb192b542017-08-30 20:04:17 +00004130 // The new, smaller fragment is stenciled out from the old fragment.
4131 if (auto OrigFragment = FragmentExpr->getFragmentInfo()) {
4132 assert(Start >= OrigFragment->OffsetInBits &&
4133 "new fragment is outside of original fragment");
4134 Start -= OrigFragment->OffsetInBits;
4135 }
4136 FragmentExpr =
4137 DIExpression::createFragmentExpression(Expr, Start, Size);
Adrian Prantl152ac392015-02-01 00:58:04 +00004138 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004139
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004140 // Remove any existing intrinsics describing the same alloca.
4141 for (DbgInfoIntrinsic *OldDII : FindDbgAddrUses(Fragment.Alloca))
4142 OldDII->eraseFromParent();
Adrian Prantl565cc182015-01-20 19:42:22 +00004143
Adrian Prantl941fa752016-12-05 18:04:47 +00004144 DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr,
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004145 DbgDeclares.front()->getDebugLoc(), &AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004146 }
4147 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004148 return Changed;
4149}
4150
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004151/// \brief Clobber a use with undef, deleting the used value if it becomes dead.
4152void SROA::clobberUse(Use &U) {
4153 Value *OldV = U;
4154 // Replace the use with an undef value.
4155 U = UndefValue::get(OldV->getType());
4156
4157 // Check for this making an instruction dead. We have to garbage collect
4158 // all the dead instructions to ensure the uses of any alloca end up being
4159 // minimal.
4160 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4161 if (isInstructionTriviallyDead(OldI)) {
4162 DeadInsts.insert(OldI);
4163 }
4164}
4165
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004166/// \brief Analyze an alloca for SROA.
4167///
4168/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004169/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004170/// rewritten as needed.
4171bool SROA::runOnAlloca(AllocaInst &AI) {
4172 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
4173 ++NumAllocasAnalyzed;
4174
4175 // Special case dead allocas, as they're trivial.
4176 if (AI.use_empty()) {
4177 AI.eraseFromParent();
4178 return true;
4179 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004180 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004181
4182 // Skip alloca forms that this analysis can't handle.
4183 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004184 DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004185 return false;
4186
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004187 bool Changed = false;
4188
4189 // First, split any FCA loads and stores touching this alloca to promote
4190 // better splitting and promotion opportunities.
Benjamin Kramer6db33382015-10-15 15:08:58 +00004191 AggLoadStoreRewriter AggRewriter;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004192 Changed |= AggRewriter.rewrite(AI);
4193
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004194 // Build the slices using a recursive instruction-visiting builder.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004195 AllocaSlices AS(DL, AI);
Chandler Carruth83934062014-10-16 21:11:55 +00004196 DEBUG(AS.print(dbgs()));
4197 if (AS.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004198 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004199
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004200 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth83934062014-10-16 21:11:55 +00004201 for (Instruction *DeadUser : AS.getDeadUsers()) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004202 // Free up everything used by this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004203 for (Use &DeadOp : DeadUser->operands())
Chandler Carruth1583e992014-03-03 10:42:58 +00004204 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004205
4206 // Now replace the uses of this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004207 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004208
4209 // And mark it for deletion.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004210 DeadInsts.insert(DeadUser);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004211 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004212 }
Chandler Carruth83934062014-10-16 21:11:55 +00004213 for (Use *DeadOp : AS.getDeadOperands()) {
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004214 clobberUse(*DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004215 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004216 }
4217
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004218 // No slices to split. Leave the dead alloca for a later pass to clean up.
Chandler Carruth83934062014-10-16 21:11:55 +00004219 if (AS.begin() == AS.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00004220 return Changed;
4221
Chandler Carruth83934062014-10-16 21:11:55 +00004222 Changed |= splitAlloca(AI, AS);
Chandler Carruthf0546402013-07-18 07:15:00 +00004223
4224 DEBUG(dbgs() << " Speculating PHIs\n");
4225 while (!SpeculatablePHIs.empty())
4226 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4227
4228 DEBUG(dbgs() << " Speculating Selects\n");
4229 while (!SpeculatableSelects.empty())
4230 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4231
4232 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004233}
4234
Chandler Carruth19450da2012-09-14 10:26:38 +00004235/// \brief Delete the dead instructions accumulated in this run.
4236///
4237/// Recursively deletes the dead instructions we've accumulated. This is done
4238/// at the very end to maximize locality of the recursive delete and to
4239/// minimize the problems of invalidated instruction pointers as such pointers
4240/// are used heavily in the intermediate stages of the algorithm.
4241///
4242/// We also record the alloca instructions deleted here so that they aren't
4243/// subsequently handed to mem2reg to promote.
Chandler Carruth113dc642014-12-20 02:39:18 +00004244void SROA::deleteDeadInstructions(
4245 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004246 while (!DeadInsts.empty()) {
4247 Instruction *I = DeadInsts.pop_back_val();
4248 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
4249
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004250 // If the instruction is an alloca, find the possible dbg.declare connected
4251 // to it, and remove it too. We must do this before calling RAUW or we will
4252 // not be able to find it.
4253 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4254 DeletedAllocas.insert(AI);
4255 for (DbgInfoIntrinsic *OldDII : FindDbgAddrUses(AI))
4256 OldDII->eraseFromParent();
4257 }
4258
Chandler Carruth58d05562012-10-25 04:37:07 +00004259 I->replaceAllUsesWith(UndefValue::get(I->getType()));
4260
Chandler Carruth1583e992014-03-03 10:42:58 +00004261 for (Use &Operand : I->operands())
4262 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004263 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00004264 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004265 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00004266 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004267 }
4268
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004269 ++NumDeleted;
4270 I->eraseFromParent();
4271 }
4272}
4273
Chandler Carruth70b44c52012-09-15 11:43:14 +00004274/// \brief Promote the allocas, using the best available technique.
4275///
4276/// This attempts to promote whatever allocas have been identified as viable in
4277/// the PromotableAllocas list. If that list is empty, there is nothing to do.
Chandler Carruth748d0952015-08-26 09:09:29 +00004278/// This function returns whether any promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004279bool SROA::promoteAllocas(Function &F) {
4280 if (PromotableAllocas.empty())
4281 return false;
4282
4283 NumPromoted += PromotableAllocas.size();
4284
Chandler Carruth748d0952015-08-26 09:09:29 +00004285 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Davide Italiano612d5a92017-04-09 20:47:14 +00004286 PromoteMemToReg(PromotableAllocas, *DT, AC);
Chandler Carruth70b44c52012-09-15 11:43:14 +00004287 PromotableAllocas.clear();
4288 return true;
4289}
4290
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004291PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT,
4292 AssumptionCache &RunAC) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004293 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
4294 C = &F.getContext();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004295 DT = &RunDT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004296 AC = &RunAC;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004297
4298 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00004299 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Adrian Prantl565cc182015-01-20 19:42:22 +00004300 I != E; ++I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004301 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4302 Worklist.insert(AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004303 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004304
4305 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00004306 // A set of deleted alloca instruction pointers which should be removed from
4307 // the list of promotable allocas.
4308 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4309
Chandler Carruthac8317f2012-10-04 12:33:50 +00004310 do {
4311 while (!Worklist.empty()) {
4312 Changed |= runOnAlloca(*Worklist.pop_back_val());
4313 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00004314
Chandler Carruthac8317f2012-10-04 12:33:50 +00004315 // Remove the deleted allocas from various lists so that we don't try to
4316 // continue processing them.
4317 if (!DeletedAllocas.empty()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00004318 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00004319 Worklist.remove_if(IsInSet);
4320 PostPromotionWorklist.remove_if(IsInSet);
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004321 PromotableAllocas.erase(llvm::remove_if(PromotableAllocas, IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00004322 PromotableAllocas.end());
4323 DeletedAllocas.clear();
4324 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004325 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004326
Chandler Carruthac8317f2012-10-04 12:33:50 +00004327 Changed |= promoteAllocas(F);
4328
4329 Worklist = PostPromotionWorklist;
4330 PostPromotionWorklist.clear();
4331 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004332
Davide Italiano16e96d42016-06-07 13:21:17 +00004333 if (!Changed)
4334 return PreservedAnalyses::all();
4335
Davide Italiano16e96d42016-06-07 13:21:17 +00004336 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00004337 PA.preserveSet<CFGAnalyses>();
Davide Italiano16e96d42016-06-07 13:21:17 +00004338 PA.preserve<GlobalsAA>();
4339 return PA;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004340}
4341
Sean Silva36e0d012016-08-09 00:28:15 +00004342PreservedAnalyses SROA::run(Function &F, FunctionAnalysisManager &AM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004343 return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F),
4344 AM.getResult<AssumptionAnalysis>(F));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004345}
Chandler Carruth29a18a42015-09-12 09:09:14 +00004346
4347/// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
4348///
4349/// This is in the llvm namespace purely to allow it to be a friend of the \c
4350/// SROA pass.
4351class llvm::sroa::SROALegacyPass : public FunctionPass {
4352 /// The SROA implementation.
4353 SROA Impl;
4354
4355public:
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004356 static char ID;
4357
Chandler Carruth29a18a42015-09-12 09:09:14 +00004358 SROALegacyPass() : FunctionPass(ID) {
4359 initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
4360 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004361
Chandler Carruth29a18a42015-09-12 09:09:14 +00004362 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00004363 if (skipFunction(F))
Chandler Carruth29a18a42015-09-12 09:09:14 +00004364 return false;
4365
4366 auto PA = Impl.runImpl(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004367 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4368 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
Chandler Carruth29a18a42015-09-12 09:09:14 +00004369 return !PA.areAllPreserved();
4370 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004371
Chandler Carruth29a18a42015-09-12 09:09:14 +00004372 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004373 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004374 AU.addRequired<DominatorTreeWrapperPass>();
4375 AU.addPreserved<GlobalsAAWrapperPass>();
4376 AU.setPreservesCFG();
4377 }
4378
Mehdi Amini117296c2016-10-01 02:56:57 +00004379 StringRef getPassName() const override { return "SROA"; }
Chandler Carruth29a18a42015-09-12 09:09:14 +00004380};
4381
4382char SROALegacyPass::ID = 0;
4383
4384FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); }
4385
4386INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
4387 "Scalar Replacement Of Aggregates", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004388INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth29a18a42015-09-12 09:09:14 +00004389INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4390INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
4391 false, false)