blob: 93321076a85d1894b5a27bef60233bf82914ae03 [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
Aaron Ballman615eb472017-10-15 14:32:27 +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
Aaron Ballman615eb472017-10-15 14:32:27 +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 :
Aaron Ballman615eb472017-10-15 14:32:27 +00001030#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001031 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
Aaron Ballman615eb472017-10-15 14:32:27 +00001062#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001063
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
Aaron Ballman615eb472017-10-15 14:32:27 +00001101#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001102
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.
Chandler Carruth3f81d802017-06-27 08:32:03 +00002458 if (MDNode *N = LI.getMetadata(LLVMContext::MD_nonnull))
2459 copyNonnullMetadata(LI, N, *NewLI);
Davide Italianob5d59e72017-11-27 21:25:13 +00002460 if (MDNode *N = LI.getMetadata(LLVMContext::MD_range))
2461 copyRangeMetadata(DL, LI, N, *NewLI);
David Majnemer62690b12015-07-14 06:19:58 +00002462 V = NewLI;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002463
2464 // If this is an integer load past the end of the slice (which means the
2465 // bytes outside the slice are undef or this load is dead) just forcibly
2466 // fix the integer size with correct handling of endianness.
2467 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2468 if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
2469 if (AITy->getBitWidth() < TITy->getBitWidth()) {
2470 V = IRB.CreateZExt(V, TITy, "load.ext");
2471 if (DL.isBigEndian())
2472 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2473 "endian_shift");
2474 }
Chandler Carruth18db7952012-11-20 01:12:50 +00002475 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002476 Type *LTy = TargetTy->getPointerTo(AS);
David Majnemer62690b12015-07-14 06:19:58 +00002477 LoadInst *NewLI = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2478 getSliceAlign(TargetTy),
2479 LI.isVolatile(), LI.getName());
2480 if (LI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002481 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
David Majnemer62690b12015-07-14 06:19:58 +00002482
2483 V = NewLI;
Chandler Carruth18db7952012-11-20 01:12:50 +00002484 IsPtrAdjusted = true;
2485 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002486 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002487
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002488 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002489 assert(!LI.isVolatile());
2490 assert(LI.getType()->isIntegerTy() &&
2491 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002492 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002493 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002494 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002495 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002496 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002497 // 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 +00002498 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002499 // Create a placeholder value with the same type as LI to use as the
2500 // basis for the new value. This allows us to replace the uses of LI with
2501 // the computed value, and then replace the placeholder with LI, leaving
2502 // LI only used for this computation.
Chandler Carruth113dc642014-12-20 02:39:18 +00002503 Value *Placeholder =
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002504 new LoadInst(UndefValue::get(LI.getType()->getPointerTo(AS)));
Chandler Carruth24ac8302015-01-02 03:55:54 +00002505 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2506 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002507 LI.replaceAllUsesWith(V);
2508 Placeholder->replaceAllUsesWith(&LI);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002509 Placeholder->deleteValue();
Chandler Carruth18db7952012-11-20 01:12:50 +00002510 } else {
2511 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002512 }
2513
Chandler Carruth18db7952012-11-20 01:12:50 +00002514 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002515 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002516 DEBUG(dbgs() << " to: " << *V << "\n");
2517 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002518 }
2519
Chandler Carruthea27cf02014-02-26 04:25:04 +00002520 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002521 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002522 unsigned BeginIndex = getIndex(NewBeginOffset);
2523 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002524 assert(EndIndex > BeginIndex && "Empty vector!");
2525 unsigned NumElements = EndIndex - BeginIndex;
2526 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth113dc642014-12-20 02:39:18 +00002527 Type *SliceTy = (NumElements == 1)
2528 ? ElementTy
2529 : VectorType::get(ElementTy, NumElements);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002530 if (V->getType() != SliceTy)
2531 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002532
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002533 // Mix in the existing elements.
Chandler Carruth113dc642014-12-20 02:39:18 +00002534 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002535 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2536 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002537 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002538 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002539
2540 (void)Store;
2541 DEBUG(dbgs() << " to: " << *Store << "\n");
2542 return true;
2543 }
2544
Chandler Carruthea27cf02014-02-26 04:25:04 +00002545 bool rewriteIntegerStore(Value *V, StoreInst &SI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002546 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002547 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002548 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002549 Value *Old =
2550 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002551 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002552 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2553 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth113dc642014-12-20 02:39:18 +00002554 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002555 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002556 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002557 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Dorit Nuzmand1247a62016-09-22 07:56:23 +00002558 Store->copyMetadata(SI, LLVMContext::MD_mem_parallel_loop_access);
Chandler Carruth18db7952012-11-20 01:12:50 +00002559 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002560 DEBUG(dbgs() << " to: " << *Store << "\n");
2561 return true;
2562 }
2563
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002564 bool visitStoreInst(StoreInst &SI) {
2565 DEBUG(dbgs() << " original: " << SI << "\n");
2566 Value *OldOp = SI.getOperand(1);
2567 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002568
Chandler Carruth18db7952012-11-20 01:12:50 +00002569 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002570
Chandler Carruthac8317f2012-10-04 12:33:50 +00002571 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2572 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002573 if (V->getType()->isPointerTy())
2574 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002575 Pass.PostPromotionWorklist.insert(AI);
2576
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002577 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002578 assert(!SI.isVolatile());
2579 assert(V->getType()->isIntegerTy() &&
2580 "Only integer type loads and stores are split");
2581 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002582 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002583 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002584 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth24ac8302015-01-02 03:55:54 +00002585 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2586 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002587 }
2588
Chandler Carruth18db7952012-11-20 01:12:50 +00002589 if (VecTy)
Chandler Carruthea27cf02014-02-26 04:25:04 +00002590 return rewriteVectorizedStoreInst(V, SI, OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002591 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthea27cf02014-02-26 04:25:04 +00002592 return rewriteIntegerStore(V, SI);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002593
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002594 const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002595 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002596 if (NewBeginOffset == NewAllocaBeginOffset &&
2597 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002598 (canConvertValue(DL, V->getType(), NewAllocaTy) ||
2599 (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
2600 V->getType()->isIntegerTy()))) {
2601 // If this is an integer store past the end of slice (and thus the bytes
2602 // past that point are irrelevant or this is unreachable), truncate the
2603 // value prior to storing.
2604 if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
2605 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2606 if (VITy->getBitWidth() > AITy->getBitWidth()) {
2607 if (DL.isBigEndian())
2608 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2609 "endian_shift");
2610 V = IRB.CreateTrunc(V, AITy, "load.trunc");
2611 }
2612
Chandler Carruth90a735d2013-07-19 07:21:28 +00002613 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002614 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2615 SI.isVolatile());
2616 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002617 unsigned AS = SI.getPointerAddressSpace();
2618 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS));
Chandler Carruth2659e502014-02-26 05:02:19 +00002619 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2620 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002621 }
Dorit Nuzmand1247a62016-09-22 07:56:23 +00002622 NewSI->copyMetadata(SI, LLVMContext::MD_mem_parallel_loop_access);
David Majnemer62690b12015-07-14 06:19:58 +00002623 if (SI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002624 NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
Chandler Carruth18db7952012-11-20 01:12:50 +00002625 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002626 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002627
2628 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2629 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002630 }
2631
Chandler Carruth514f34f2012-12-17 04:07:30 +00002632 /// \brief Compute an integer value from splatting an i8 across the given
2633 /// number of bytes.
2634 ///
2635 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2636 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002637 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002638 ///
2639 /// \param V The i8 value to splat.
2640 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002641 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002642 assert(Size > 0 && "Expected a positive number of bytes.");
2643 IntegerType *VTy = cast<IntegerType>(V->getType());
2644 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2645 if (Size == 1)
2646 return V;
2647
Chandler Carruth113dc642014-12-20 02:39:18 +00002648 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2649 V = IRB.CreateMul(
2650 IRB.CreateZExt(V, SplatIntTy, "zext"),
2651 ConstantExpr::getUDiv(
2652 Constant::getAllOnesValue(SplatIntTy),
2653 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2654 SplatIntTy)),
2655 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002656 return V;
2657 }
2658
Chandler Carruthccca5042012-12-17 04:07:37 +00002659 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002660 Value *getVectorSplat(Value *V, unsigned NumElements) {
2661 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002662 DEBUG(dbgs() << " splat: " << *V << "\n");
2663 return V;
2664 }
2665
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002666 bool visitMemSetInst(MemSetInst &II) {
2667 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002668 assert(II.getRawDest() == OldPtr);
2669
2670 // If the memset has a variable size, it cannot be split, just adjust the
2671 // pointer to the new alloca.
2672 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002673 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002674 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002675 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Pete Cooper67cf9a72015-11-19 05:56:52 +00002676 Type *CstTy = II.getAlignmentCst()->getType();
2677 II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002678
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002679 deleteIfTriviallyDead(OldPtr);
2680 return false;
2681 }
2682
2683 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002684 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002685
2686 Type *AllocaTy = NewAI.getAllocatedType();
2687 Type *ScalarTy = AllocaTy->getScalarType();
2688
2689 // If this doesn't map cleanly onto the alloca type, and that type isn't
2690 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002691 if (!VecTy && !IntTy &&
Chandler Carruth113dc642014-12-20 02:39:18 +00002692 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002693 SliceSize != DL.getTypeStoreSize(AllocaTy) ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002694 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002695 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
Chandler Carruth113dc642014-12-20 02:39:18 +00002696 DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002697 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002698 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2699 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002700 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2701 getSliceAlign(), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002702 (void)New;
2703 DEBUG(dbgs() << " to: " << *New << "\n");
2704 return false;
2705 }
2706
2707 // If we can represent this as a simple value, we have to build the actual
2708 // value to store, which requires expanding the byte present in memset to
2709 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002710 // splatting the byte to a sufficiently wide integer, splatting it across
2711 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002712 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002713
Chandler Carruthccca5042012-12-17 04:07:37 +00002714 if (VecTy) {
2715 // If this is a memset of a vectorized alloca, insert it.
2716 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002717
Chandler Carruthf0546402013-07-18 07:15:00 +00002718 unsigned BeginIndex = getIndex(NewBeginOffset);
2719 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002720 assert(EndIndex > BeginIndex && "Empty vector!");
2721 unsigned NumElements = EndIndex - BeginIndex;
2722 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2723
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002724 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002725 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2726 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002727 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002728 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002729
Chandler Carruth113dc642014-12-20 02:39:18 +00002730 Value *Old =
2731 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002732 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002733 } else if (IntTy) {
2734 // If this is a memset on an alloca where we can widen stores, insert the
2735 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002736 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002737
Chandler Carruthf0546402013-07-18 07:15:00 +00002738 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002739 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002740
2741 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2742 EndOffset != NewAllocaBeginOffset)) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002743 Value *Old =
2744 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002745 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002746 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002747 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002748 } else {
2749 assert(V->getType() == IntTy &&
2750 "Wrong type for an alloca wide integer!");
2751 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002752 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002753 } else {
2754 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002755 assert(NewBeginOffset == NewAllocaBeginOffset);
2756 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002757
Chandler Carruth90a735d2013-07-19 07:21:28 +00002758 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002759 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002760 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002761
Chandler Carruth90a735d2013-07-19 07:21:28 +00002762 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002763 }
2764
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002765 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002766 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002767 (void)New;
2768 DEBUG(dbgs() << " to: " << *New << "\n");
2769 return !II.isVolatile();
2770 }
2771
2772 bool visitMemTransferInst(MemTransferInst &II) {
2773 // Rewriting of memory transfer instructions can be a bit tricky. We break
2774 // them into two categories: split intrinsics and unsplit intrinsics.
2775
2776 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002777
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002778 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002779 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002780 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002781
Chandler Carruthaa72b932014-02-26 07:29:54 +00002782 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002783
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002784 // For unsplit intrinsics, we simply modify the source and destination
2785 // pointers in place. This isn't just an optimization, it is a matter of
2786 // correctness. With unsplit intrinsics we may be dealing with transfers
2787 // within a single alloca before SROA ran, or with transfers that have
2788 // a variable length. We may also be dealing with memmove instead of
2789 // memcpy, and so simply updating the pointers is the necessary for us to
2790 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002791 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002792 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Pete Cooper67cf9a72015-11-19 05:56:52 +00002793 if (IsDest)
Chandler Carruth8183a502014-02-25 11:08:02 +00002794 II.setDest(AdjustedPtr);
Pete Cooper67cf9a72015-11-19 05:56:52 +00002795 else
Chandler Carruth8183a502014-02-25 11:08:02 +00002796 II.setSource(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002797
Pete Cooper67cf9a72015-11-19 05:56:52 +00002798 if (II.getAlignment() > SliceAlign) {
2799 Type *CstTy = II.getAlignmentCst()->getType();
2800 II.setAlignment(
2801 ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
Chandler Carruth181ed052014-02-26 05:33:36 +00002802 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002803
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002804 DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002805 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002806 return false;
2807 }
2808 // For split transfer intrinsics we have an incredibly useful assurance:
2809 // the source and destination do not reside within the same alloca, and at
2810 // least one of them does not escape. This means that we can replace
2811 // memmove with memcpy, and we don't need to worry about all manner of
2812 // downsides to splitting and transforming the operations.
2813
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002814 // If this doesn't map cleanly onto the alloca type, and that type isn't
2815 // a single value type, just emit a memcpy.
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002816 bool EmitMemCpy =
2817 !VecTy && !IntTy &&
2818 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2819 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2820 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002821
2822 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2823 // size hasn't been shrunk based on analysis of the viable range, this is
2824 // a no-op.
2825 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002826 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002827 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002828
2829 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002830 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002831 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002832 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002833 return false;
2834 }
2835 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002836 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002837
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002838 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2839 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002840 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth113dc642014-12-20 02:39:18 +00002841 if (AllocaInst *AI =
2842 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002843 assert(AI != &OldAI && AI != &NewAI &&
2844 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002845 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002846 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002847
Chandler Carruth286d87e2014-02-26 08:25:02 +00002848 Type *OtherPtrTy = OtherPtr->getType();
2849 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2850
Chandler Carruth181ed052014-02-26 05:33:36 +00002851 // Compute the relative offset for the other pointer within the transfer.
Chandler Carruth286d87e2014-02-26 08:25:02 +00002852 unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
Chandler Carruth181ed052014-02-26 05:33:36 +00002853 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Pete Cooper67cf9a72015-11-19 05:56:52 +00002854 unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2855 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002856
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002857 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002858 // Compute the other pointer, folding as much as possible to produce
2859 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002860 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002861 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002862
Chandler Carruth47954c82014-02-26 05:12:43 +00002863 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002864 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002865 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002866
Pete Cooper67cf9a72015-11-19 05:56:52 +00002867 CallInst *New = IRB.CreateMemCpy(
2868 IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2869 MinAlign(SliceAlign, OtherAlign), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002870 (void)New;
2871 DEBUG(dbgs() << " to: " << *New << "\n");
2872 return false;
2873 }
2874
Chandler Carruthf0546402013-07-18 07:15:00 +00002875 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2876 NewEndOffset == NewAllocaEndOffset;
2877 uint64_t Size = NewEndOffset - NewBeginOffset;
2878 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2879 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002880 unsigned NumElements = EndIndex - BeginIndex;
Chandler Carruth113dc642014-12-20 02:39:18 +00002881 IntegerType *SubIntTy =
2882 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002883
Chandler Carruth286d87e2014-02-26 08:25:02 +00002884 // Reset the other pointer type to match the register type we're going to
2885 // use, but using the address space of the original other pointer.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002886 if (VecTy && !IsWholeAlloca) {
2887 if (NumElements == 1)
2888 OtherPtrTy = VecTy->getElementType();
2889 else
2890 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2891
Chandler Carruth286d87e2014-02-26 08:25:02 +00002892 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002893 } else if (IntTy && !IsWholeAlloca) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00002894 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2895 } else {
2896 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002897 }
2898
Chandler Carruth181ed052014-02-26 05:33:36 +00002899 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002900 OtherPtr->getName() + ".");
Pete Cooper67cf9a72015-11-19 05:56:52 +00002901 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002902 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00002903 unsigned DstAlign = SliceAlign;
2904 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002905 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002906 std::swap(SrcAlign, DstAlign);
2907 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002908
2909 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002910 if (VecTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002911 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002912 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002913 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002914 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002915 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002916 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002917 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002918 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +00002919 Src =
2920 IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002921 }
2922
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002923 if (VecTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002924 Value *Old =
2925 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002926 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002927 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002928 Value *Old =
2929 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002930 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002931 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002932 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2933 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002934 }
2935
Chandler Carruth871ba722012-09-26 10:27:46 +00002936 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00002937 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Chandler Carruth871ba722012-09-26 10:27:46 +00002938 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002939 DEBUG(dbgs() << " to: " << *Store << "\n");
2940 return !II.isVolatile();
2941 }
2942
2943 bool visitIntrinsicInst(IntrinsicInst &II) {
2944 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2945 II.getIntrinsicID() == Intrinsic::lifetime_end);
2946 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002947 assert(II.getArgOperand(1) == OldPtr);
2948
2949 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002950 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002951
Eli Friedman50967752016-11-28 21:50:34 +00002952 // Lifetime intrinsics are only promotable if they cover the whole alloca.
2953 // Therefore, we drop lifetime intrinsics which don't cover the whole
2954 // alloca.
2955 // (In theory, intrinsics which partially cover an alloca could be
2956 // promoted, but PromoteMemToReg doesn't handle that case.)
2957 // FIXME: Check whether the alloca is promotable before dropping the
2958 // lifetime intrinsics?
2959 if (NewBeginOffset != NewAllocaBeginOffset ||
2960 NewEndOffset != NewAllocaEndOffset)
2961 return true;
2962
Chandler Carruth113dc642014-12-20 02:39:18 +00002963 ConstantInt *Size =
2964 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002965 NewEndOffset - NewBeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002966 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002967 Value *New;
2968 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2969 New = IRB.CreateLifetimeStart(Ptr, Size);
2970 else
2971 New = IRB.CreateLifetimeEnd(Ptr, Size);
2972
Edwin Vane82f80d42013-01-29 17:42:24 +00002973 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002974 DEBUG(dbgs() << " to: " << *New << "\n");
Eli Friedman2a65dd12016-08-08 01:30:53 +00002975
Eli Friedman50967752016-11-28 21:50:34 +00002976 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002977 }
2978
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002979 bool visitPHINode(PHINode &PN) {
2980 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00002981 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2982 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002983
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002984 // We would like to compute a new pointer in only one place, but have it be
2985 // as local as possible to the PHI. To do that, we re-use the location of
2986 // the old pointer, which necessarily must be in the right position to
2987 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00002988 IRBuilderTy PtrBuilder(IRB);
David Majnemerd4cffcf2014-09-01 21:20:14 +00002989 if (isa<PHINode>(OldPtr))
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002990 PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
David Majnemerd4cffcf2014-09-01 21:20:14 +00002991 else
2992 PtrBuilder.SetInsertPoint(OldPtr);
Chandler Carruth51175532014-02-25 11:12:04 +00002993 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002994
Chandler Carruth47954c82014-02-26 05:12:43 +00002995 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002996 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002997 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002998
Chandler Carruth82a57542012-10-01 10:54:05 +00002999 DEBUG(dbgs() << " to: " << PN << "\n");
3000 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003001
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003002 // PHIs can't be promoted on their own, but often can be speculated. We
3003 // check the speculation outside of the rewriter so that we see the
3004 // fully-rewritten alloca.
3005 PHIUsers.insert(&PN);
3006 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003007 }
3008
3009 bool visitSelectInst(SelectInst &SI) {
3010 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003011 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3012 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00003013 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
3014 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003015
Chandler Carruth47954c82014-02-26 05:12:43 +00003016 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003017 // Replace the operands which were using the old pointer.
3018 if (SI.getOperand(1) == OldPtr)
3019 SI.setOperand(1, NewPtr);
3020 if (SI.getOperand(2) == OldPtr)
3021 SI.setOperand(2, NewPtr);
3022
Chandler Carruth82a57542012-10-01 10:54:05 +00003023 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003024 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003025
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003026 // Selects can't be promoted on their own, but often can be speculated. We
3027 // check the speculation outside of the rewriter so that we see the
3028 // fully-rewritten alloca.
3029 SelectUsers.insert(&SI);
3030 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003031 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003032};
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003033
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003034namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003035
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003036/// \brief Visitor to rewrite aggregate loads and stores as scalar.
3037///
3038/// This pass aggressively rewrites all aggregate loads and stores on
3039/// a particular pointer (or any pointer derived from it which we can identify)
3040/// with scalar loads and stores.
3041class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3042 // Befriend the base class so it can delegate to private visit methods.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003043 friend class InstVisitor<AggLoadStoreRewriter, bool>;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003044
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003045 /// Queue of pointer uses to analyze and potentially rewrite.
3046 SmallVector<Use *, 8> Queue;
3047
3048 /// Set to prevent us from cycling with phi nodes and loops.
3049 SmallPtrSet<User *, 8> Visited;
3050
3051 /// The current pointer use being rewritten. This is used to dig up the used
3052 /// value (as opposed to the user).
3053 Use *U;
3054
3055public:
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003056 /// Rewrite loads and stores through a pointer and all pointers derived from
3057 /// it.
3058 bool rewrite(Instruction &I) {
3059 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3060 enqueueUsers(I);
3061 bool Changed = false;
3062 while (!Queue.empty()) {
3063 U = Queue.pop_back_val();
3064 Changed |= visit(cast<Instruction>(U->getUser()));
3065 }
3066 return Changed;
3067 }
3068
3069private:
3070 /// Enqueue all the users of the given instruction for further processing.
3071 /// This uses a set to de-duplicate users.
3072 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003073 for (Use &U : I.uses())
David Blaikie70573dc2014-11-19 07:49:26 +00003074 if (Visited.insert(U.getUser()).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003075 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003076 }
3077
3078 // Conservative default is to not rewrite anything.
3079 bool visitInstruction(Instruction &I) { return false; }
3080
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003081 /// \brief Generic recursive split emission class.
Chandler Carruth113dc642014-12-20 02:39:18 +00003082 template <typename Derived> class OpSplitter {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003083 protected:
3084 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00003085 IRBuilderTy IRB;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003086
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003087 /// The indices which to be used with insert- or extractvalue to select the
3088 /// appropriate value within the aggregate.
3089 SmallVector<unsigned, 4> Indices;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003090
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003091 /// The indices to a GEP instruction which will move Ptr to the correct slot
3092 /// within the aggregate.
3093 SmallVector<Value *, 4> GEPIndices;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003094
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003095 /// The base pointer of the original op, used as a base for GEPing the
3096 /// split operations.
3097 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003098
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003099 /// Initialize the splitter with an insertion point, Ptr and start with a
3100 /// single zero GEP index.
3101 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003102 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003103
3104 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003105 /// \brief Generic recursive split emission routine.
3106 ///
3107 /// This method recursively splits an aggregate op (load or store) into
3108 /// scalar or vector ops. It splits recursively until it hits a single value
3109 /// and emits that single value operation via the template argument.
3110 ///
3111 /// The logic of this routine relies on GEPs and insertvalue and
3112 /// extractvalue all operating with the same fundamental index list, merely
3113 /// formatted differently (GEPs need actual values).
3114 ///
3115 /// \param Ty The type being split recursively into smaller ops.
3116 /// \param Agg The aggregate value being built up or stored, depending on
3117 /// whether this is splitting a load or a store respectively.
3118 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3119 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003120 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003121
3122 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3123 unsigned OldSize = Indices.size();
3124 (void)OldSize;
3125 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3126 ++Idx) {
3127 assert(Indices.size() == OldSize && "Did not return to the old size");
3128 Indices.push_back(Idx);
3129 GEPIndices.push_back(IRB.getInt32(Idx));
3130 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3131 GEPIndices.pop_back();
3132 Indices.pop_back();
3133 }
3134 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003135 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003136
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003137 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3138 unsigned OldSize = Indices.size();
3139 (void)OldSize;
3140 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3141 ++Idx) {
3142 assert(Indices.size() == OldSize && "Did not return to the old size");
3143 Indices.push_back(Idx);
3144 GEPIndices.push_back(IRB.getInt32(Idx));
3145 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3146 GEPIndices.pop_back();
3147 Indices.pop_back();
3148 }
3149 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003150 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003151
3152 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003153 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003154 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003155
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003156 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003157 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003158 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003159
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003160 /// Emit a leaf load of a single value. This is called at the leaves of the
3161 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003162 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003163 assert(Ty->isSingleValueType());
3164 // Load the single value and insert it using the indices.
David Blaikieaa41cd52015-04-03 21:33:42 +00003165 Value *GEP =
3166 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
Jakub Staszak3c6583a2013-02-19 22:14:45 +00003167 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003168 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3169 DEBUG(dbgs() << " to: " << *Load << "\n");
3170 }
3171 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003172
3173 bool visitLoadInst(LoadInst &LI) {
3174 assert(LI.getPointerOperand() == *U);
3175 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3176 return false;
3177
3178 // We have an aggregate being loaded, split it apart.
3179 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003180 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003181 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003182 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003183 LI.replaceAllUsesWith(V);
3184 LI.eraseFromParent();
3185 return true;
3186 }
3187
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003188 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003189 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003190 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003191
3192 /// Emit a leaf store of a single value. This is called at the leaves of the
3193 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003194 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003195 assert(Ty->isSingleValueType());
3196 // Extract the single value and store it using the indices.
Patrik Hagglunda83706e2016-06-20 10:19:00 +00003197 //
3198 // The gep and extractvalue values are factored out of the CreateStore
3199 // call to make the output independent of the argument evaluation order.
Patrik Hagglund4e0bd842016-06-20 11:19:58 +00003200 Value *ExtractValue =
3201 IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
3202 Value *InBoundsGEP =
3203 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
Patrik Hagglunda83706e2016-06-20 10:19:00 +00003204 Value *Store = IRB.CreateStore(ExtractValue, InBoundsGEP);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003205 (void)Store;
3206 DEBUG(dbgs() << " to: " << *Store << "\n");
3207 }
3208 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003209
3210 bool visitStoreInst(StoreInst &SI) {
3211 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3212 return false;
3213 Value *V = SI.getValueOperand();
3214 if (V->getType()->isSingleValueType())
3215 return false;
3216
3217 // We have an aggregate being stored, split it apart.
3218 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003219 StoreOpSplitter Splitter(&SI, *U);
3220 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003221 SI.eraseFromParent();
3222 return true;
3223 }
3224
3225 bool visitBitCastInst(BitCastInst &BC) {
3226 enqueueUsers(BC);
3227 return false;
3228 }
3229
3230 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3231 enqueueUsers(GEPI);
3232 return false;
3233 }
3234
3235 bool visitPHINode(PHINode &PN) {
3236 enqueueUsers(PN);
3237 return false;
3238 }
3239
3240 bool visitSelectInst(SelectInst &SI) {
3241 enqueueUsers(SI);
3242 return false;
3243 }
3244};
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003245
3246} // end anonymous namespace
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003247
Chandler Carruthba931992012-10-13 10:49:33 +00003248/// \brief Strip aggregate type wrapping.
3249///
3250/// This removes no-op aggregate types wrapping an underlying type. It will
3251/// strip as many layers of types as it can without changing either the type
3252/// size or the allocated size.
3253static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3254 if (Ty->isSingleValueType())
3255 return Ty;
3256
3257 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3258 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3259
3260 Type *InnerTy;
3261 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3262 InnerTy = ArrTy->getElementType();
3263 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3264 const StructLayout *SL = DL.getStructLayout(STy);
3265 unsigned Index = SL->getElementContainingOffset(0);
3266 InnerTy = STy->getElementType(Index);
3267 } else {
3268 return Ty;
3269 }
3270
3271 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3272 TypeSize > DL.getTypeSizeInBits(InnerTy))
3273 return Ty;
3274
3275 return stripAggregateTypeWrapping(DL, InnerTy);
3276}
3277
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003278/// \brief Try to find a partition of the aggregate type passed in for a given
3279/// offset and size.
3280///
3281/// This recurses through the aggregate type and tries to compute a subtype
3282/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003283/// of an array, it will even compute a new array type for that sub-section,
3284/// and the same for structs.
3285///
3286/// Note that this routine is very strict and tries to find a partition of the
3287/// type which produces the *exact* right offset and size. It is not forgiving
3288/// when the size or offset cause either end of type-based partition to be off.
3289/// Also, this is a best-effort routine. It is reasonable to give up and not
3290/// return a type if necessary.
Chandler Carruth113dc642014-12-20 02:39:18 +00003291static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3292 uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003293 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3294 return stripAggregateTypeWrapping(DL, Ty);
3295 if (Offset > DL.getTypeAllocSize(Ty) ||
3296 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003297 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003298
3299 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003300 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003301 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003302 uint64_t NumSkippedElements = Offset / ElementSize;
Peter Collingbournebc070522016-12-02 03:20:58 +00003303 if (NumSkippedElements >= SeqTy->getNumElements())
3304 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003305 Offset -= NumSkippedElements * ElementSize;
3306
3307 // First check if we need to recurse.
3308 if (Offset > 0 || Size < ElementSize) {
3309 // Bail if the partition ends in a different array element.
3310 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003311 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003312 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003313 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003314 }
3315 assert(Offset == 0);
3316
3317 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003318 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003319 assert(Size > ElementSize);
3320 uint64_t NumElements = Size / ElementSize;
3321 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003322 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003323 return ArrayType::get(ElementTy, NumElements);
3324 }
3325
3326 StructType *STy = dyn_cast<StructType>(Ty);
3327 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003328 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003329
Chandler Carruth90a735d2013-07-19 07:21:28 +00003330 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003331 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003332 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003333 uint64_t EndOffset = Offset + Size;
3334 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003335 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003336
3337 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003338 Offset -= SL->getElementOffset(Index);
3339
3340 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003341 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003342 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003343 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003344
3345 // See if any partition must be contained by the element.
3346 if (Offset > 0 || Size < ElementSize) {
3347 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003348 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003349 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003350 }
3351 assert(Offset == 0);
3352
3353 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003354 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003355
3356 StructType::element_iterator EI = STy->element_begin() + Index,
3357 EE = STy->element_end();
3358 if (EndOffset < SL->getSizeInBytes()) {
3359 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3360 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003361 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003362
3363 // Don't try to form "natural" types if the elements don't line up with the
3364 // expected size.
3365 // FIXME: We could potentially recurse down through the last element in the
3366 // sub-struct to find a natural end point.
3367 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003368 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003369
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003370 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003371 EE = STy->element_begin() + EndIndex;
3372 }
3373
3374 // Try to build up a sub-structure.
Chandler Carruth113dc642014-12-20 02:39:18 +00003375 StructType *SubTy =
3376 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003377 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003378 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003379 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003380
Chandler Carruth054a40a2012-09-14 11:08:31 +00003381 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003382}
3383
Chandler Carruth0715cba2015-01-01 11:54:38 +00003384/// \brief Pre-split loads and stores to simplify rewriting.
3385///
3386/// We want to break up the splittable load+store pairs as much as
3387/// possible. This is important to do as a preprocessing step, as once we
3388/// start rewriting the accesses to partitions of the alloca we lose the
3389/// necessary information to correctly split apart paired loads and stores
3390/// which both point into this alloca. The case to consider is something like
3391/// the following:
3392///
3393/// %a = alloca [12 x i8]
3394/// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3395/// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3396/// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3397/// %iptr1 = bitcast i8* %gep1 to i64*
3398/// %iptr2 = bitcast i8* %gep2 to i64*
3399/// %fptr1 = bitcast i8* %gep1 to float*
3400/// %fptr2 = bitcast i8* %gep2 to float*
3401/// %fptr3 = bitcast i8* %gep3 to float*
3402/// store float 0.0, float* %fptr1
3403/// store float 1.0, float* %fptr2
3404/// %v = load i64* %iptr1
3405/// store i64 %v, i64* %iptr2
3406/// %f1 = load float* %fptr2
3407/// %f2 = load float* %fptr3
3408///
3409/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3410/// promote everything so we recover the 2 SSA values that should have been
3411/// there all along.
3412///
3413/// \returns true if any changes are made.
3414bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
3415 DEBUG(dbgs() << "Pre-splitting loads and stores\n");
3416
3417 // Track the loads and stores which are candidates for pre-splitting here, in
3418 // the order they first appear during the partition scan. These give stable
3419 // iteration order and a basis for tracking which loads and stores we
3420 // actually split.
3421 SmallVector<LoadInst *, 4> Loads;
3422 SmallVector<StoreInst *, 4> Stores;
3423
3424 // We need to accumulate the splits required of each load or store where we
3425 // can find them via a direct lookup. This is important to cross-check loads
3426 // and stores against each other. We also track the slice so that we can kill
3427 // all the slices that end up split.
3428 struct SplitOffsets {
3429 Slice *S;
3430 std::vector<uint64_t> Splits;
3431 };
3432 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3433
Chandler Carruth73b01642015-01-05 04:17:53 +00003434 // Track loads out of this alloca which cannot, for any reason, be pre-split.
3435 // This is important as we also cannot pre-split stores of those loads!
3436 // FIXME: This is all pretty gross. It means that we can be more aggressive
3437 // in pre-splitting when the load feeding the store happens to come from
3438 // a separate alloca. Put another way, the effectiveness of SROA would be
3439 // decreased by a frontend which just concatenated all of its local allocas
3440 // into one big flat alloca. But defeating such patterns is exactly the job
3441 // SROA is tasked with! Sadly, to not have this discrepancy we would have
3442 // change store pre-splitting to actually force pre-splitting of the load
3443 // that feeds it *and all stores*. That makes pre-splitting much harder, but
3444 // maybe it would make it more principled?
3445 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3446
Chandler Carruth0715cba2015-01-01 11:54:38 +00003447 DEBUG(dbgs() << " Searching for candidate loads and stores\n");
3448 for (auto &P : AS.partitions()) {
3449 for (Slice &S : P) {
Chandler Carruth73b01642015-01-05 04:17:53 +00003450 Instruction *I = cast<Instruction>(S.getUse()->getUser());
Chandler Carruth37f1f122016-03-10 15:31:17 +00003451 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
3452 // If this is a load we have to track that it can't participate in any
3453 // pre-splitting. If this is a store of a load we have to track that
3454 // that load also can't participate in any pre-splitting.
Chandler Carruth73b01642015-01-05 04:17:53 +00003455 if (auto *LI = dyn_cast<LoadInst>(I))
3456 UnsplittableLoads.insert(LI);
Chandler Carruth37f1f122016-03-10 15:31:17 +00003457 else if (auto *SI = dyn_cast<StoreInst>(I))
3458 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
3459 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003460 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003461 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003462 assert(P.endOffset() > S.beginOffset() &&
3463 "Empty or backwards partition!");
3464
3465 // Determine if this is a pre-splittable slice.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003466 if (auto *LI = dyn_cast<LoadInst>(I)) {
3467 assert(!LI->isVolatile() && "Cannot split volatile loads!");
3468
3469 // The load must be used exclusively to store into other pointers for
3470 // us to be able to arbitrarily pre-split it. The stores must also be
3471 // simple to avoid changing semantics.
3472 auto IsLoadSimplyStored = [](LoadInst *LI) {
3473 for (User *LU : LI->users()) {
3474 auto *SI = dyn_cast<StoreInst>(LU);
3475 if (!SI || !SI->isSimple())
3476 return false;
3477 }
3478 return true;
3479 };
Chandler Carruth73b01642015-01-05 04:17:53 +00003480 if (!IsLoadSimplyStored(LI)) {
3481 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003482 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003483 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003484
3485 Loads.push_back(LI);
Chandler Carruthd94a5962016-03-10 14:16:18 +00003486 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
3487 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3488 // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
Chandler Carruth994cde82015-01-01 12:01:03 +00003489 continue;
3490 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3491 if (!StoredLoad || !StoredLoad->isSimple())
3492 continue;
3493 assert(!SI->isVolatile() && "Cannot split volatile stores!");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003494
Chandler Carruth994cde82015-01-01 12:01:03 +00003495 Stores.push_back(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003496 } else {
3497 // Other uses cannot be pre-split.
3498 continue;
3499 }
3500
3501 // Record the initial split.
3502 DEBUG(dbgs() << " Candidate: " << *I << "\n");
3503 auto &Offsets = SplitOffsetsMap[I];
3504 assert(Offsets.Splits.empty() &&
3505 "Should not have splits the first time we see an instruction!");
3506 Offsets.S = &S;
Chandler Carruth24ac8302015-01-02 03:55:54 +00003507 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003508 }
3509
3510 // Now scan the already split slices, and add a split for any of them which
3511 // we're going to pre-split.
3512 for (Slice *S : P.splitSliceTails()) {
3513 auto SplitOffsetsMapI =
3514 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3515 if (SplitOffsetsMapI == SplitOffsetsMap.end())
3516 continue;
3517 auto &Offsets = SplitOffsetsMapI->second;
3518
3519 assert(Offsets.S == S && "Found a mismatched slice!");
3520 assert(!Offsets.Splits.empty() &&
3521 "Cannot have an empty set of splits on the second partition!");
Chandler Carruth24ac8302015-01-02 03:55:54 +00003522 assert(Offsets.Splits.back() ==
3523 P.beginOffset() - Offsets.S->beginOffset() &&
Chandler Carruth0715cba2015-01-01 11:54:38 +00003524 "Previous split does not end where this one begins!");
3525
3526 // Record each split. The last partition's end isn't needed as the size
3527 // of the slice dictates that.
3528 if (S->endOffset() > P.endOffset())
Chandler Carruth24ac8302015-01-02 03:55:54 +00003529 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003530 }
3531 }
3532
3533 // We may have split loads where some of their stores are split stores. For
3534 // such loads and stores, we can only pre-split them if their splits exactly
3535 // match relative to their starting offset. We have to verify this prior to
3536 // any rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003537 Stores.erase(
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003538 llvm::remove_if(Stores,
3539 [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
3540 // Lookup the load we are storing in our map of split
3541 // offsets.
3542 auto *LI = cast<LoadInst>(SI->getValueOperand());
3543 // If it was completely unsplittable, then we're done,
3544 // and this store can't be pre-split.
3545 if (UnsplittableLoads.count(LI))
3546 return true;
Chandler Carruth73b01642015-01-05 04:17:53 +00003547
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003548 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3549 if (LoadOffsetsI == SplitOffsetsMap.end())
3550 return false; // Unrelated loads are definitely safe.
3551 auto &LoadOffsets = LoadOffsetsI->second;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003552
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003553 // Now lookup the store's offsets.
3554 auto &StoreOffsets = SplitOffsetsMap[SI];
Chandler Carruth0715cba2015-01-01 11:54:38 +00003555
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003556 // If the relative offsets of each split in the load and
3557 // store match exactly, then we can split them and we
3558 // don't need to remove them here.
3559 if (LoadOffsets.Splits == StoreOffsets.Splits)
3560 return false;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003561
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003562 DEBUG(dbgs()
3563 << " Mismatched splits for load and store:\n"
3564 << " " << *LI << "\n"
3565 << " " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003566
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003567 // We've found a store and load that we need to split
3568 // with mismatched relative splits. Just give up on them
3569 // and remove both instructions from our list of
3570 // candidates.
3571 UnsplittableLoads.insert(LI);
3572 return true;
3573 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003574 Stores.end());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003575 // Now we have to go *back* through all the stores, because a later store may
Chandler Carruth73b01642015-01-05 04:17:53 +00003576 // have caused an earlier store's load to become unsplittable and if it is
3577 // unsplittable for the later store, then we can't rely on it being split in
3578 // the earlier store either.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003579 Stores.erase(llvm::remove_if(Stores,
3580 [&UnsplittableLoads](StoreInst *SI) {
3581 auto *LI =
3582 cast<LoadInst>(SI->getValueOperand());
3583 return UnsplittableLoads.count(LI);
3584 }),
Chandler Carruth73b01642015-01-05 04:17:53 +00003585 Stores.end());
3586 // Once we've established all the loads that can't be split for some reason,
3587 // filter any that made it into our list out.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003588 Loads.erase(llvm::remove_if(Loads,
3589 [&UnsplittableLoads](LoadInst *LI) {
3590 return UnsplittableLoads.count(LI);
3591 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003592 Loads.end());
3593
3594 // If no loads or stores are left, there is no pre-splitting to be done for
3595 // this alloca.
3596 if (Loads.empty() && Stores.empty())
3597 return false;
3598
3599 // From here on, we can't fail and will be building new accesses, so rig up
3600 // an IR builder.
3601 IRBuilderTy IRB(&AI);
3602
3603 // Collect the new slices which we will merge into the alloca slices.
3604 SmallVector<Slice, 4> NewSlices;
3605
3606 // Track any allocas we end up splitting loads and stores for so we iterate
3607 // on them.
3608 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3609
3610 // At this point, we have collected all of the loads and stores we can
3611 // pre-split, and the specific splits needed for them. We actually do the
3612 // splitting in a specific order in order to handle when one of the loads in
3613 // the value operand to one of the stores.
3614 //
3615 // First, we rewrite all of the split loads, and just accumulate each split
3616 // load in a parallel structure. We also build the slices for them and append
3617 // them to the alloca slices.
3618 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3619 std::vector<LoadInst *> SplitLoads;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003620 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003621 for (LoadInst *LI : Loads) {
3622 SplitLoads.clear();
3623
3624 IntegerType *Ty = cast<IntegerType>(LI->getType());
3625 uint64_t LoadSize = Ty->getBitWidth() / 8;
3626 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3627
3628 auto &Offsets = SplitOffsetsMap[LI];
3629 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3630 "Slice size should always match load size exactly!");
3631 uint64_t BaseOffset = Offsets.S->beginOffset();
3632 assert(BaseOffset + LoadSize > BaseOffset &&
3633 "Cannot represent alloca access size using 64-bit integers!");
3634
3635 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003636 IRB.SetInsertPoint(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003637
3638 DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
3639
3640 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3641 int Idx = 0, Size = Offsets.Splits.size();
3642 for (;;) {
3643 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
Yaxun Liu7c44f342017-06-27 18:26:06 +00003644 auto AS = LI->getPointerAddressSpace();
3645 auto *PartPtrTy = PartTy->getPointerTo(AS);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003646 LoadInst *PLoad = IRB.CreateAlignedLoad(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003647 getAdjustedPtr(IRB, DL, BasePtr,
Yaxun Liu7c44f342017-06-27 18:26:06 +00003648 APInt(DL.getPointerSizeInBits(AS), PartOffset),
Chandler Carruth994cde82015-01-01 12:01:03 +00003649 PartPtrTy, BasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003650 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003651 LI->getName());
Davide Italianob5d59e72017-11-27 21:25:13 +00003652 PLoad->copyMetadata(*LI, LLVMContext::MD_mem_parallel_loop_access);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003653
3654 // Append this load onto the list of split loads so we can find it later
3655 // to rewrite the stores.
3656 SplitLoads.push_back(PLoad);
3657
3658 // Now build a new slice for the alloca.
Chandler Carruth994cde82015-01-01 12:01:03 +00003659 NewSlices.push_back(
3660 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3661 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003662 /*IsSplittable*/ false));
Chandler Carruth6044c0b2015-01-01 12:56:47 +00003663 DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3664 << ", " << NewSlices.back().endOffset() << "): " << *PLoad
3665 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003666
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003667 // See if we've handled all the splits.
3668 if (Idx >= Size)
3669 break;
3670
Chandler Carruth0715cba2015-01-01 11:54:38 +00003671 // Setup the next partition.
3672 PartOffset = Offsets.Splits[Idx];
3673 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003674 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3675 }
3676
3677 // Now that we have the split loads, do the slow walk over all uses of the
3678 // load and rewrite them as split stores, or save the split loads to use
3679 // below if the store is going to be split there anyways.
3680 bool DeferredStores = false;
3681 for (User *LU : LI->users()) {
3682 StoreInst *SI = cast<StoreInst>(LU);
3683 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3684 DeferredStores = true;
3685 DEBUG(dbgs() << " Deferred splitting of store: " << *SI << "\n");
3686 continue;
3687 }
3688
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003689 Value *StoreBasePtr = SI->getPointerOperand();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003690 IRB.SetInsertPoint(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003691
3692 DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
3693
3694 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3695 LoadInst *PLoad = SplitLoads[Idx];
3696 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
Chandler Carruth994cde82015-01-01 12:01:03 +00003697 auto *PartPtrTy =
3698 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003699
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003700 auto AS = SI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003701 StoreInst *PStore = IRB.CreateAlignedStore(
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003702 PLoad,
3703 getAdjustedPtr(IRB, DL, StoreBasePtr,
3704 APInt(DL.getPointerSizeInBits(AS), PartOffset),
3705 PartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003706 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Dorit Nuzmand1247a62016-09-22 07:56:23 +00003707 PStore->copyMetadata(*LI, LLVMContext::MD_mem_parallel_loop_access);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003708 DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
3709 }
3710
3711 // We want to immediately iterate on any allocas impacted by splitting
3712 // this store, and we have to track any promotable alloca (indicated by
3713 // a direct store) as needing to be resplit because it is no longer
3714 // promotable.
3715 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3716 ResplitPromotableAllocas.insert(OtherAI);
3717 Worklist.insert(OtherAI);
3718 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3719 StoreBasePtr->stripInBoundsOffsets())) {
3720 Worklist.insert(OtherAI);
3721 }
3722
3723 // Mark the original store as dead.
3724 DeadInsts.insert(SI);
3725 }
3726
3727 // Save the split loads if there are deferred stores among the users.
3728 if (DeferredStores)
3729 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3730
3731 // Mark the original load as dead and kill the original slice.
3732 DeadInsts.insert(LI);
3733 Offsets.S->kill();
3734 }
3735
3736 // Second, we rewrite all of the split stores. At this point, we know that
3737 // all loads from this alloca have been split already. For stores of such
3738 // loads, we can simply look up the pre-existing split loads. For stores of
3739 // other loads, we split those loads first and then write split stores of
3740 // them.
3741 for (StoreInst *SI : Stores) {
3742 auto *LI = cast<LoadInst>(SI->getValueOperand());
3743 IntegerType *Ty = cast<IntegerType>(LI->getType());
3744 uint64_t StoreSize = Ty->getBitWidth() / 8;
3745 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3746
3747 auto &Offsets = SplitOffsetsMap[SI];
3748 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3749 "Slice size should always match load size exactly!");
3750 uint64_t BaseOffset = Offsets.S->beginOffset();
3751 assert(BaseOffset + StoreSize > BaseOffset &&
3752 "Cannot represent alloca access size using 64-bit integers!");
3753
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003754 Value *LoadBasePtr = LI->getPointerOperand();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003755 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3756
3757 DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
3758
3759 // Check whether we have an already split load.
3760 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3761 std::vector<LoadInst *> *SplitLoads = nullptr;
3762 if (SplitLoadsMapI != SplitLoadsMap.end()) {
3763 SplitLoads = &SplitLoadsMapI->second;
3764 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3765 "Too few split loads for the number of splits in the store!");
3766 } else {
3767 DEBUG(dbgs() << " of load: " << *LI << "\n");
3768 }
3769
Chandler Carruth0715cba2015-01-01 11:54:38 +00003770 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3771 int Idx = 0, Size = Offsets.Splits.size();
3772 for (;;) {
3773 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
Keno Fischer514a6a52017-06-02 19:04:17 +00003774 auto *LoadPartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3775 auto *StorePartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003776
3777 // Either lookup a split load or create one.
3778 LoadInst *PLoad;
3779 if (SplitLoads) {
3780 PLoad = (*SplitLoads)[Idx];
3781 } else {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003782 IRB.SetInsertPoint(LI);
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003783 auto AS = LI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003784 PLoad = IRB.CreateAlignedLoad(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003785 getAdjustedPtr(IRB, DL, LoadBasePtr,
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003786 APInt(DL.getPointerSizeInBits(AS), PartOffset),
Keno Fischer514a6a52017-06-02 19:04:17 +00003787 LoadPartPtrTy, LoadBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003788 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003789 LI->getName());
3790 }
3791
3792 // And store this partition.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003793 IRB.SetInsertPoint(SI);
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003794 auto AS = SI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003795 StoreInst *PStore = IRB.CreateAlignedStore(
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003796 PLoad,
3797 getAdjustedPtr(IRB, DL, StoreBasePtr,
3798 APInt(DL.getPointerSizeInBits(AS), PartOffset),
3799 StorePartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003800 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003801
3802 // Now build a new slice for the alloca.
3803 NewSlices.push_back(
3804 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3805 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003806 /*IsSplittable*/ false));
Chandler Carruth6044c0b2015-01-01 12:56:47 +00003807 DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3808 << ", " << NewSlices.back().endOffset() << "): " << *PStore
3809 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003810 if (!SplitLoads) {
3811 DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
3812 }
3813
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003814 // See if we've finished all the splits.
3815 if (Idx >= Size)
3816 break;
3817
Chandler Carruth0715cba2015-01-01 11:54:38 +00003818 // Setup the next partition.
3819 PartOffset = Offsets.Splits[Idx];
3820 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003821 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
3822 }
3823
3824 // We want to immediately iterate on any allocas impacted by splitting
3825 // this load, which is only relevant if it isn't a load of this alloca and
3826 // thus we didn't already split the loads above. We also have to keep track
3827 // of any promotable allocas we split loads on as they can no longer be
3828 // promoted.
3829 if (!SplitLoads) {
3830 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
3831 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3832 ResplitPromotableAllocas.insert(OtherAI);
3833 Worklist.insert(OtherAI);
3834 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3835 LoadBasePtr->stripInBoundsOffsets())) {
3836 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3837 Worklist.insert(OtherAI);
3838 }
3839 }
3840
3841 // Mark the original store as dead now that we've split it up and kill its
Chandler Carruth24ac8302015-01-02 03:55:54 +00003842 // slice. Note that we leave the original load in place unless this store
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003843 // was its only use. It may in turn be split up if it is an alloca load
Chandler Carruth24ac8302015-01-02 03:55:54 +00003844 // for some other alloca, but it may be a normal load. This may introduce
3845 // redundant loads, but where those can be merged the rest of the optimizer
3846 // should handle the merging, and this uncovers SSA splits which is more
3847 // important. In practice, the original loads will almost always be fully
3848 // split and removed eventually, and the splits will be merged by any
3849 // trivial CSE, including instcombine.
3850 if (LI->hasOneUse()) {
3851 assert(*LI->user_begin() == SI && "Single use isn't this store!");
3852 DeadInsts.insert(LI);
3853 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003854 DeadInsts.insert(SI);
3855 Offsets.S->kill();
3856 }
3857
Chandler Carruth24ac8302015-01-02 03:55:54 +00003858 // Remove the killed slices that have ben pre-split.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003859 AS.erase(llvm::remove_if(AS, [](const Slice &S) { return S.isDead(); }),
3860 AS.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003861
Chandler Carruth24ac8302015-01-02 03:55:54 +00003862 // Insert our new slices. This will sort and merge them into the sorted
3863 // sequence.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003864 AS.insert(NewSlices);
3865
3866 DEBUG(dbgs() << " Pre-split slices:\n");
3867#ifndef NDEBUG
3868 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
3869 DEBUG(AS.print(dbgs(), I, " "));
3870#endif
3871
3872 // Finally, don't try to promote any allocas that new require re-splitting.
3873 // They have already been added to the worklist above.
3874 PromotableAllocas.erase(
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003875 llvm::remove_if(
David Majnemerc7004902016-08-12 04:32:37 +00003876 PromotableAllocas,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003877 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
3878 PromotableAllocas.end());
3879
3880 return true;
3881}
3882
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003883/// \brief Rewrite an alloca partition's users.
3884///
3885/// This routine drives both of the rewriting goals of the SROA pass. It tries
3886/// to rewrite uses of an alloca partition to be conducive for SSA value
3887/// promotion. If the partition needs a new, more refined alloca, this will
3888/// build that new alloca, preserving as much type information as possible, and
3889/// rewrite the uses of the old alloca to point at the new one and have the
3890/// appropriate new offsets. It also evaluates how successful the rewrite was
3891/// at enabling promotion and if it was successful queues the alloca to be
3892/// promoted.
Adrian Prantl565cc182015-01-20 19:42:22 +00003893AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruth29a18a42015-09-12 09:09:14 +00003894 Partition &P) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003895 // Try to compute a friendly type for this partition of the alloca. This
3896 // won't always succeed, in which case we fall back to a legal integer type
3897 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00003898 Type *SliceTy = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003899 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003900 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003901 if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003902 SliceTy = CommonUseTy;
3903 if (!SliceTy)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003904 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003905 P.beginOffset(), P.size()))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003906 SliceTy = TypePartitionTy;
3907 if ((!SliceTy || (SliceTy->isArrayTy() &&
3908 SliceTy->getArrayElementType()->isIntegerTy())) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003909 DL.isLegalInteger(P.size() * 8))
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003910 SliceTy = Type::getIntNTy(*C, P.size() * 8);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003911 if (!SliceTy)
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003912 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003913 assert(DL.getTypeAllocSize(SliceTy) >= P.size());
Chandler Carruthf0546402013-07-18 07:15:00 +00003914
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003915 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00003916
Chandler Carruth2dc96822014-10-18 00:44:02 +00003917 VectorType *VecTy =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003918 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
Chandler Carruth2dc96822014-10-18 00:44:02 +00003919 if (VecTy)
3920 SliceTy = VecTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003921
3922 // Check for the case where we're going to rewrite to a new alloca of the
3923 // exact same type as the original, and with the same access offsets. In that
3924 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003925 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003926 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003927 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003928 assert(P.beginOffset() == 0 &&
3929 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003930 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003931 // FIXME: We should be able to bail at this point with "nothing changed".
3932 // FIXME: We might want to defer PHI speculation until after here.
Adrian Prantl565cc182015-01-20 19:42:22 +00003933 // FIXME: return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003934 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003935 unsigned Alignment = AI.getAlignment();
3936 if (!Alignment) {
3937 // The minimum alignment which users can rely on when the explicit
3938 // alignment is omitted or zero is that required by the ABI for this
3939 // type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003940 Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003941 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003942 Alignment = MinAlign(Alignment, P.beginOffset());
Chandler Carruth903790e2012-09-29 10:41:21 +00003943 // If we will get at least this much alignment from the type alone, leave
3944 // the alloca's alignment unconstrained.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003945 if (Alignment <= DL.getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003946 Alignment = 0;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003947 NewAI = new AllocaInst(
Matt Arsenault3c1fc762017-04-10 22:27:50 +00003948 SliceTy, AI.getType()->getAddressSpace(), nullptr, Alignment,
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003949 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003950 ++NumNewAllocas;
3951 }
3952
3953 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003954 << "[" << P.beginOffset() << "," << P.endOffset()
3955 << ") to: " << *NewAI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003956
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003957 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00003958 // promoted allocas. We will reset it to this point if the alloca is not in
3959 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003960 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00003961 unsigned NumUses = 0;
Davide Italiano81a26da2017-04-27 23:09:01 +00003962 SmallSetVector<PHINode *, 8> PHIUsers;
3963 SmallSetVector<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003964
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003965 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003966 P.endOffset(), IsIntegerPromotable, VecTy,
3967 PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00003968 bool Promotable = true;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00003969 for (Slice *S : P.splitSliceTails()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003970 Promotable &= Rewriter.visit(S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003971 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003972 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003973 for (Slice &S : P) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003974 Promotable &= Rewriter.visit(&S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003975 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003976 }
3977
Chandler Carruth6c321c12013-07-19 10:57:36 +00003978 NumAllocaPartitionUses += NumUses;
Craig Topper8a950272017-05-18 00:51:39 +00003979 MaxUsesPerAllocaPartition.updateMax(NumUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003980
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003981 // Now that we've processed all the slices in the new partition, check if any
3982 // PHIs or Selects would block promotion.
Davide Italiano81a26da2017-04-27 23:09:01 +00003983 for (PHINode *PHI : PHIUsers)
3984 if (!isSafePHIToSpeculate(*PHI)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003985 Promotable = false;
3986 PHIUsers.clear();
3987 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003988 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003989 }
Davide Italiano81a26da2017-04-27 23:09:01 +00003990
3991 for (SelectInst *Sel : SelectUsers)
3992 if (!isSafeSelectToSpeculate(*Sel)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003993 Promotable = false;
3994 PHIUsers.clear();
3995 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003996 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003997 }
3998
3999 if (Promotable) {
4000 if (PHIUsers.empty() && SelectUsers.empty()) {
4001 // Promote the alloca.
4002 PromotableAllocas.push_back(NewAI);
4003 } else {
4004 // If we have either PHIs or Selects to speculate, add them to those
4005 // worklists and re-queue the new alloca so that we promote in on the
4006 // next iteration.
Chandler Carruth61747042014-10-16 21:05:14 +00004007 for (PHINode *PHIUser : PHIUsers)
4008 SpeculatablePHIs.insert(PHIUser);
4009 for (SelectInst *SelectUser : SelectUsers)
4010 SpeculatableSelects.insert(SelectUser);
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004011 Worklist.insert(NewAI);
4012 }
4013 } else {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004014 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00004015 while (PostPromotionWorklist.size() > PPWOldSize)
4016 PostPromotionWorklist.pop_back();
David Majnemer30ffc4c2016-04-26 01:05:00 +00004017
4018 // We couldn't promote and we didn't create a new partition, nothing
4019 // happened.
4020 if (NewAI == &AI)
4021 return nullptr;
4022
4023 // If we can't promote the alloca, iterate on it to check for new
4024 // refinements exposed by splitting the current alloca. Don't iterate on an
4025 // alloca which didn't actually change and didn't get promoted.
4026 Worklist.insert(NewAI);
Chandler Carruthf0546402013-07-18 07:15:00 +00004027 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00004028
Adrian Prantl565cc182015-01-20 19:42:22 +00004029 return NewAI;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004030}
4031
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004032/// \brief Walks the slices of an alloca and form partitions based on them,
4033/// rewriting each of their uses.
Chandler Carruth83934062014-10-16 21:11:55 +00004034bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
4035 if (AS.begin() == AS.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00004036 return false;
4037
Chandler Carruth6c321c12013-07-19 10:57:36 +00004038 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004039 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004040 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00004041
Chandler Carruth24ac8302015-01-02 03:55:54 +00004042 // First try to pre-split loads and stores.
Chandler Carruth0715cba2015-01-01 11:54:38 +00004043 Changed |= presplitLoadsAndStores(AI, AS);
4044
Chandler Carruth24ac8302015-01-02 03:55:54 +00004045 // Now that we have identified any pre-splitting opportunities, mark any
4046 // splittable (non-whole-alloca) loads and stores as unsplittable. If we fail
4047 // to split these during pre-splitting, we want to force them to be
4048 // rewritten into a partition.
4049 bool IsSorted = true;
4050 for (Slice &S : AS) {
4051 if (!S.isSplittable())
4052 continue;
4053 // FIXME: We currently leave whole-alloca splittable loads and stores. This
4054 // used to be the only splittable loads and stores and we need to be
4055 // confident that the above handling of splittable loads and stores is
4056 // completely sufficient before we forcibly disable the remaining handling.
4057 if (S.beginOffset() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004058 S.endOffset() >= DL.getTypeAllocSize(AI.getAllocatedType()))
Chandler Carruth24ac8302015-01-02 03:55:54 +00004059 continue;
4060 if (isa<LoadInst>(S.getUse()->getUser()) ||
4061 isa<StoreInst>(S.getUse()->getUser())) {
4062 S.makeUnsplittable();
4063 IsSorted = false;
4064 }
4065 }
4066 if (!IsSorted)
4067 std::sort(AS.begin(), AS.end());
4068
Adrian Prantl941fa752016-12-05 18:04:47 +00004069 /// Describes the allocas introduced by rewritePartition in order to migrate
4070 /// the debug info.
4071 struct Fragment {
Adrian Prantl565cc182015-01-20 19:42:22 +00004072 AllocaInst *Alloca;
4073 uint64_t Offset;
4074 uint64_t Size;
Adrian Prantl941fa752016-12-05 18:04:47 +00004075 Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
Adrian Prantl565cc182015-01-20 19:42:22 +00004076 : Alloca(AI), Offset(O), Size(S) {}
4077 };
Adrian Prantl941fa752016-12-05 18:04:47 +00004078 SmallVector<Fragment, 4> Fragments;
Adrian Prantl565cc182015-01-20 19:42:22 +00004079
Chandler Carruth0715cba2015-01-01 11:54:38 +00004080 // Rewrite each partition.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004081 for (auto &P : AS.partitions()) {
Adrian Prantl565cc182015-01-20 19:42:22 +00004082 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4083 Changed = true;
Adrian Prantl34e75902015-02-09 23:57:22 +00004084 if (NewAI != &AI) {
4085 uint64_t SizeOfByte = 8;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004086 uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
Adrian Prantl34e75902015-02-09 23:57:22 +00004087 // Don't include any padding.
4088 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
Adrian Prantl941fa752016-12-05 18:04:47 +00004089 Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
Adrian Prantl34e75902015-02-09 23:57:22 +00004090 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004091 }
Chandler Carruth6c321c12013-07-19 10:57:36 +00004092 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00004093 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004094
Chandler Carruth6c321c12013-07-19 10:57:36 +00004095 NumAllocaPartitions += NumPartitions;
Craig Topper8a950272017-05-18 00:51:39 +00004096 MaxPartitionsPerAlloca.updateMax(NumPartitions);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004097
Adrian Prantl565cc182015-01-20 19:42:22 +00004098 // Migrate debug information from the old alloca to the new alloca(s)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004099 // and the individual partitions.
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004100 TinyPtrVector<DbgInfoIntrinsic *> DbgDeclares = FindDbgAddrUses(&AI);
4101 if (!DbgDeclares.empty()) {
4102 auto *Var = DbgDeclares.front()->getVariable();
4103 auto *Expr = DbgDeclares.front()->getExpression();
Adrian Prantld7f6f162017-11-28 00:57:53 +00004104 auto VarSize = Var->getSizeInBits();
Sanjay Patelaf674fb2015-12-14 17:24:23 +00004105 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
Keno Fischerd5354fd2016-01-14 20:06:34 +00004106 uint64_t AllocaSize = DL.getTypeSizeInBits(AI.getAllocatedType());
Adrian Prantl941fa752016-12-05 18:04:47 +00004107 for (auto Fragment : Fragments) {
4108 // Create a fragment expression describing the new partition or reuse AI's
Adrian Prantl565cc182015-01-20 19:42:22 +00004109 // expression if there is only one partition.
Adrian Prantl941fa752016-12-05 18:04:47 +00004110 auto *FragmentExpr = Expr;
4111 if (Fragment.Size < AllocaSize || Expr->isFragment()) {
Adrian Prantl152ac392015-02-01 00:58:04 +00004112 // If this alloca is already a scalar replacement of a larger aggregate,
Adrian Prantl941fa752016-12-05 18:04:47 +00004113 // Fragment.Offset describes the offset inside the scalar.
Adrian Prantl49797ca2016-12-22 05:27:12 +00004114 auto ExprFragment = Expr->getFragmentInfo();
4115 uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0;
Adrian Prantl941fa752016-12-05 18:04:47 +00004116 uint64_t Start = Offset + Fragment.Offset;
4117 uint64_t Size = Fragment.Size;
Adrian Prantl49797ca2016-12-22 05:27:12 +00004118 if (ExprFragment) {
Adrian Prantl941fa752016-12-05 18:04:47 +00004119 uint64_t AbsEnd =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00004120 ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
Adrian Prantl34e75902015-02-09 23:57:22 +00004121 if (Start >= AbsEnd)
4122 // No need to describe a SROAed padding.
4123 continue;
4124 Size = std::min(Size, AbsEnd - Start);
4125 }
Adrian Prantlb192b542017-08-30 20:04:17 +00004126 // The new, smaller fragment is stenciled out from the old fragment.
4127 if (auto OrigFragment = FragmentExpr->getFragmentInfo()) {
4128 assert(Start >= OrigFragment->OffsetInBits &&
4129 "new fragment is outside of original fragment");
4130 Start -= OrigFragment->OffsetInBits;
4131 }
Adrian Prantld7f6f162017-11-28 00:57:53 +00004132 // Avoid creating a fragment expression that covers the entire variable.
4133 if (!VarSize || *VarSize != Size) {
4134 if (auto E =
4135 DIExpression::createFragmentExpression(Expr, Start, Size))
4136 FragmentExpr = *E;
4137 else
4138 continue;
4139 }
Adrian Prantl152ac392015-02-01 00:58:04 +00004140 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004141
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004142 // Remove any existing intrinsics describing the same alloca.
4143 for (DbgInfoIntrinsic *OldDII : FindDbgAddrUses(Fragment.Alloca))
4144 OldDII->eraseFromParent();
Adrian Prantl565cc182015-01-20 19:42:22 +00004145
Adrian Prantl941fa752016-12-05 18:04:47 +00004146 DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr,
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004147 DbgDeclares.front()->getDebugLoc(), &AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004148 }
4149 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004150 return Changed;
4151}
4152
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004153/// \brief Clobber a use with undef, deleting the used value if it becomes dead.
4154void SROA::clobberUse(Use &U) {
4155 Value *OldV = U;
4156 // Replace the use with an undef value.
4157 U = UndefValue::get(OldV->getType());
4158
4159 // Check for this making an instruction dead. We have to garbage collect
4160 // all the dead instructions to ensure the uses of any alloca end up being
4161 // minimal.
4162 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4163 if (isInstructionTriviallyDead(OldI)) {
4164 DeadInsts.insert(OldI);
4165 }
4166}
4167
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004168/// \brief Analyze an alloca for SROA.
4169///
4170/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004171/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004172/// rewritten as needed.
4173bool SROA::runOnAlloca(AllocaInst &AI) {
4174 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
4175 ++NumAllocasAnalyzed;
4176
4177 // Special case dead allocas, as they're trivial.
4178 if (AI.use_empty()) {
4179 AI.eraseFromParent();
4180 return true;
4181 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004182 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004183
4184 // Skip alloca forms that this analysis can't handle.
4185 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004186 DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004187 return false;
4188
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004189 bool Changed = false;
4190
4191 // First, split any FCA loads and stores touching this alloca to promote
4192 // better splitting and promotion opportunities.
Benjamin Kramer6db33382015-10-15 15:08:58 +00004193 AggLoadStoreRewriter AggRewriter;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004194 Changed |= AggRewriter.rewrite(AI);
4195
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004196 // Build the slices using a recursive instruction-visiting builder.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004197 AllocaSlices AS(DL, AI);
Chandler Carruth83934062014-10-16 21:11:55 +00004198 DEBUG(AS.print(dbgs()));
4199 if (AS.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004200 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004201
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004202 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth83934062014-10-16 21:11:55 +00004203 for (Instruction *DeadUser : AS.getDeadUsers()) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004204 // Free up everything used by this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004205 for (Use &DeadOp : DeadUser->operands())
Chandler Carruth1583e992014-03-03 10:42:58 +00004206 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004207
4208 // Now replace the uses of this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004209 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004210
4211 // And mark it for deletion.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004212 DeadInsts.insert(DeadUser);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004213 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004214 }
Chandler Carruth83934062014-10-16 21:11:55 +00004215 for (Use *DeadOp : AS.getDeadOperands()) {
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004216 clobberUse(*DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004217 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004218 }
4219
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004220 // No slices to split. Leave the dead alloca for a later pass to clean up.
Chandler Carruth83934062014-10-16 21:11:55 +00004221 if (AS.begin() == AS.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00004222 return Changed;
4223
Chandler Carruth83934062014-10-16 21:11:55 +00004224 Changed |= splitAlloca(AI, AS);
Chandler Carruthf0546402013-07-18 07:15:00 +00004225
4226 DEBUG(dbgs() << " Speculating PHIs\n");
4227 while (!SpeculatablePHIs.empty())
4228 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4229
4230 DEBUG(dbgs() << " Speculating Selects\n");
4231 while (!SpeculatableSelects.empty())
4232 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4233
4234 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004235}
4236
Chandler Carruth19450da2012-09-14 10:26:38 +00004237/// \brief Delete the dead instructions accumulated in this run.
4238///
4239/// Recursively deletes the dead instructions we've accumulated. This is done
4240/// at the very end to maximize locality of the recursive delete and to
4241/// minimize the problems of invalidated instruction pointers as such pointers
4242/// are used heavily in the intermediate stages of the algorithm.
4243///
4244/// We also record the alloca instructions deleted here so that they aren't
4245/// subsequently handed to mem2reg to promote.
Teresa Johnson33090022017-11-20 18:33:38 +00004246bool SROA::deleteDeadInstructions(
Chandler Carruth113dc642014-12-20 02:39:18 +00004247 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
Teresa Johnson33090022017-11-20 18:33:38 +00004248 bool Changed = false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004249 while (!DeadInsts.empty()) {
4250 Instruction *I = DeadInsts.pop_back_val();
4251 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
4252
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004253 // If the instruction is an alloca, find the possible dbg.declare connected
4254 // to it, and remove it too. We must do this before calling RAUW or we will
4255 // not be able to find it.
4256 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4257 DeletedAllocas.insert(AI);
4258 for (DbgInfoIntrinsic *OldDII : FindDbgAddrUses(AI))
4259 OldDII->eraseFromParent();
4260 }
4261
Chandler Carruth58d05562012-10-25 04:37:07 +00004262 I->replaceAllUsesWith(UndefValue::get(I->getType()));
4263
Chandler Carruth1583e992014-03-03 10:42:58 +00004264 for (Use &Operand : I->operands())
4265 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004266 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00004267 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004268 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00004269 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004270 }
4271
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004272 ++NumDeleted;
4273 I->eraseFromParent();
Teresa Johnson33090022017-11-20 18:33:38 +00004274 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004275 }
Teresa Johnson33090022017-11-20 18:33:38 +00004276 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004277}
4278
Chandler Carruth70b44c52012-09-15 11:43:14 +00004279/// \brief Promote the allocas, using the best available technique.
4280///
4281/// This attempts to promote whatever allocas have been identified as viable in
4282/// the PromotableAllocas list. If that list is empty, there is nothing to do.
Chandler Carruth748d0952015-08-26 09:09:29 +00004283/// This function returns whether any promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004284bool SROA::promoteAllocas(Function &F) {
4285 if (PromotableAllocas.empty())
4286 return false;
4287
4288 NumPromoted += PromotableAllocas.size();
4289
Chandler Carruth748d0952015-08-26 09:09:29 +00004290 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Davide Italiano612d5a92017-04-09 20:47:14 +00004291 PromoteMemToReg(PromotableAllocas, *DT, AC);
Chandler Carruth70b44c52012-09-15 11:43:14 +00004292 PromotableAllocas.clear();
4293 return true;
4294}
4295
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004296PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT,
4297 AssumptionCache &RunAC) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004298 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
4299 C = &F.getContext();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004300 DT = &RunDT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004301 AC = &RunAC;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004302
4303 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00004304 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Adrian Prantl565cc182015-01-20 19:42:22 +00004305 I != E; ++I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004306 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4307 Worklist.insert(AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004308 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004309
4310 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00004311 // A set of deleted alloca instruction pointers which should be removed from
4312 // the list of promotable allocas.
4313 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4314
Chandler Carruthac8317f2012-10-04 12:33:50 +00004315 do {
4316 while (!Worklist.empty()) {
4317 Changed |= runOnAlloca(*Worklist.pop_back_val());
Teresa Johnson33090022017-11-20 18:33:38 +00004318 Changed |= deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00004319
Chandler Carruthac8317f2012-10-04 12:33:50 +00004320 // Remove the deleted allocas from various lists so that we don't try to
4321 // continue processing them.
4322 if (!DeletedAllocas.empty()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00004323 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00004324 Worklist.remove_if(IsInSet);
4325 PostPromotionWorklist.remove_if(IsInSet);
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004326 PromotableAllocas.erase(llvm::remove_if(PromotableAllocas, IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00004327 PromotableAllocas.end());
4328 DeletedAllocas.clear();
4329 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004330 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004331
Chandler Carruthac8317f2012-10-04 12:33:50 +00004332 Changed |= promoteAllocas(F);
4333
4334 Worklist = PostPromotionWorklist;
4335 PostPromotionWorklist.clear();
4336 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004337
Davide Italiano16e96d42016-06-07 13:21:17 +00004338 if (!Changed)
4339 return PreservedAnalyses::all();
4340
Davide Italiano16e96d42016-06-07 13:21:17 +00004341 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00004342 PA.preserveSet<CFGAnalyses>();
Davide Italiano16e96d42016-06-07 13:21:17 +00004343 PA.preserve<GlobalsAA>();
4344 return PA;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004345}
4346
Sean Silva36e0d012016-08-09 00:28:15 +00004347PreservedAnalyses SROA::run(Function &F, FunctionAnalysisManager &AM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004348 return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F),
4349 AM.getResult<AssumptionAnalysis>(F));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004350}
Chandler Carruth29a18a42015-09-12 09:09:14 +00004351
4352/// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
4353///
4354/// This is in the llvm namespace purely to allow it to be a friend of the \c
4355/// SROA pass.
4356class llvm::sroa::SROALegacyPass : public FunctionPass {
4357 /// The SROA implementation.
4358 SROA Impl;
4359
4360public:
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004361 static char ID;
4362
Chandler Carruth29a18a42015-09-12 09:09:14 +00004363 SROALegacyPass() : FunctionPass(ID) {
4364 initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
4365 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004366
Chandler Carruth29a18a42015-09-12 09:09:14 +00004367 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00004368 if (skipFunction(F))
Chandler Carruth29a18a42015-09-12 09:09:14 +00004369 return false;
4370
4371 auto PA = Impl.runImpl(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004372 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4373 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
Chandler Carruth29a18a42015-09-12 09:09:14 +00004374 return !PA.areAllPreserved();
4375 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004376
Chandler Carruth29a18a42015-09-12 09:09:14 +00004377 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004378 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004379 AU.addRequired<DominatorTreeWrapperPass>();
4380 AU.addPreserved<GlobalsAAWrapperPass>();
4381 AU.setPreservesCFG();
4382 }
4383
Mehdi Amini117296c2016-10-01 02:56:57 +00004384 StringRef getPassName() const override { return "SROA"; }
Chandler Carruth29a18a42015-09-12 09:09:14 +00004385};
4386
4387char SROALegacyPass::ID = 0;
4388
4389FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); }
4390
4391INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
4392 "Scalar Replacement Of Aggregates", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004393INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth29a18a42015-09-12 09:09:14 +00004394INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4395INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
4396 false, false)