blob: cc79afdb05a52e7d99eb4aa550b3ea4c12c3688f [file] [log] [blame]
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chandler Carruth1b398ae2012-09-14 09:22:59 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This transformation implements the well known scalar replacement of
10/// aggregates transformation. It tries to identify promotable elements of an
11/// aggregate alloca, and promote them to registers. It will also try to
12/// convert uses of an element (or set of elements) of an alloca into a vector
13/// or bitfield-style integer scalar if appropriate.
14///
15/// It works to do this with minimal slicing of the alloca so that regions
16/// which are merely transferred in and out of external memory remain unchanged
17/// and are not decomposed to scalar code.
18///
19/// Because this also performs alloca promotion, it can be thought of as also
20/// serving the purpose of SSA formation. The algorithm iterates on the
21/// function until all opportunities for promotion have been realized.
22///
23//===----------------------------------------------------------------------===//
24
Chandler Carruth29a18a42015-09-12 09:09:14 +000025#include "llvm/Transforms/Scalar/SROA.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000026#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/PointerIntPair.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/ADT/STLExtras.h"
Davide Italiano81a26da2017-04-27 23:09:01 +000031#include "llvm/ADT/SetVector.h"
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +000032#include "llvm/ADT/SmallBitVector.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"
David Blaikie31b98d22018-06-04 21:23:21 +000044#include "llvm/Transforms/Utils/Local.h"
Nico Weber432a3882018-04-30 14:59:11 +000045#include "llvm/Config/llvm-config.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000046#include "llvm/IR/BasicBlock.h"
47#include "llvm/IR/Constant.h"
48#include "llvm/IR/ConstantFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000050#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/DataLayout.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000052#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000054#include "llvm/IR/Dominators.h"
55#include "llvm/IR/Function.h"
56#include "llvm/IR/GetElementPtrTypeIterator.h"
57#include "llvm/IR/GlobalAlias.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/IRBuilder.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000059#include "llvm/IR/InstVisitor.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000060#include "llvm/IR/InstrTypes.h"
61#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000062#include "llvm/IR/Instructions.h"
63#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000064#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000065#include "llvm/IR/LLVMContext.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000066#include "llvm/IR/Metadata.h"
67#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000068#include "llvm/IR/Operator.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000069#include "llvm/IR/PassManager.h"
70#include "llvm/IR/Type.h"
71#include "llvm/IR/Use.h"
72#include "llvm/IR/User.h"
73#include "llvm/IR/Value.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000074#include "llvm/Pass.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000075#include "llvm/Support/Casting.h"
Chandler Carruth70b44c52012-09-15 11:43:14 +000076#include "llvm/Support/CommandLine.h"
Chandler Carruthf0546402013-07-18 07:15:00 +000077#include "llvm/Support/Compiler.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000078#include "llvm/Support/Debug.h"
79#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000080#include "llvm/Support/MathExtras.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000081#include "llvm/Support/raw_ostream.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +000082#include "llvm/Transforms/Scalar.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000083#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000084#include <algorithm>
85#include <cassert>
86#include <chrono>
87#include <cstddef>
88#include <cstdint>
89#include <cstring>
90#include <iterator>
91#include <string>
92#include <tuple>
93#include <utility>
94#include <vector>
Chandler Carruth83cee772014-02-25 03:59:29 +000095
Hal Finkel29f51312016-03-28 11:13:03 +000096#ifndef NDEBUG
97// We only use this for a debug check.
Chandler Carruth83cee772014-02-25 03:59:29 +000098#include <random>
99#endif
100
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000101using namespace llvm;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000102using namespace llvm::sroa;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000103
Chandler Carruth964daaa2014-04-22 02:55:47 +0000104#define DEBUG_TYPE "sroa"
105
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000106STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000107STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +0000108STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
109STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
110STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000111STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
112STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000113STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000114STATISTIC(NumDeleted, "Number of instructions deleted");
115STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000116
Chandler Carruth83cee772014-02-25 03:59:29 +0000117/// Hidden option to enable randomly shuffling the slices to help uncover
118/// instability in their order.
119static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
120 cl::init(false), cl::Hidden);
121
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000122/// Hidden option to experiment with completely strict handling of inbounds
123/// GEPs.
Chandler Carruth113dc642014-12-20 02:39:18 +0000124static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
125 cl::Hidden);
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000126
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000127namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000128
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000129/// A custom IRBuilder inserter which prefixes all names, but only in
Mehdi Amini1e9c9252016-03-11 17:15:34 +0000130/// Assert builds.
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000131class IRBuilderPrefixedInserter : public IRBuilderDefaultInserter {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000132 std::string Prefix;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000133
Zachary Turner41a9ee92017-10-11 23:54:34 +0000134 const Twine getNameWithPrefix(const Twine &Name) const {
135 return Name.isTriviallyEmpty() ? Name : Prefix + Name;
136 }
137
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000138public:
139 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
140
141protected:
142 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
143 BasicBlock::iterator InsertPt) const {
Zachary Turner41a9ee92017-10-11 23:54:34 +0000144 IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name), BB,
145 InsertPt);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000146 }
147};
148
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000149/// Provide a type for IRBuilder that drops names in release builds.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000150using IRBuilderTy = IRBuilder<ConstantFolder, IRBuilderPrefixedInserter>;
Chandler Carruthd177f862013-03-20 07:30:36 +0000151
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000152/// A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000153///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000154/// This structure represents a slice of an alloca used by some instruction. It
155/// stores both the begin and end offsets of this use, a pointer to the use
156/// itself, and a flag indicating whether we can classify the use as splittable
157/// or not when forming partitions of the alloca.
158class Slice {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000159 /// The beginning offset of the range.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000160 uint64_t BeginOffset = 0;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000161
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000162 /// The ending offset, not included in the range.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000163 uint64_t EndOffset = 0;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000164
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000165 /// Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000166 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000167 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000168
169public:
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000170 Slice() = default;
171
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000172 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000173 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000174 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000175
176 uint64_t beginOffset() const { return BeginOffset; }
177 uint64_t endOffset() const { return EndOffset; }
178
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000179 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
180 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000181
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000182 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000183
Craig Topperf40110f2014-04-25 05:29:35 +0000184 bool isDead() const { return getUse() == nullptr; }
185 void kill() { UseAndIsSplittable.setPointer(nullptr); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000186
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000187 /// Support for ordering ranges.
Chandler Carruthf74654d2013-03-18 08:36:46 +0000188 ///
189 /// This provides an ordering over ranges such that start offsets are
190 /// always increasing, and within equal start offsets, the end offsets are
191 /// decreasing. Thus the spanning range comes first in a cluster with the
192 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000193 bool operator<(const Slice &RHS) const {
Chandler Carruth113dc642014-12-20 02:39:18 +0000194 if (beginOffset() < RHS.beginOffset())
195 return true;
196 if (beginOffset() > RHS.beginOffset())
197 return false;
198 if (isSplittable() != RHS.isSplittable())
199 return !isSplittable();
200 if (endOffset() > RHS.endOffset())
201 return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000202 return false;
203 }
204
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000205 /// Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000206 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000207 uint64_t RHSOffset) {
208 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000209 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000210 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000211 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000212 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000213 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000214
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000215 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000216 return isSplittable() == RHS.isSplittable() &&
217 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000218 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000219 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000220};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000221
Chandler Carruthf0546402013-07-18 07:15:00 +0000222} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000223
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000224/// Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000225///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000226/// This class represents the slices of an alloca which are formed by its
227/// various uses. If a pointer escapes, we can't fully build a representation
228/// for the slices used and we reflect that in this structure. The uses are
229/// stored, sorted by increasing beginning offset and with unsplittable slices
230/// starting at a particular offset before splittable slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000231class llvm::sroa::AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000232public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000233 /// Construct the slices of a particular alloca.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000234 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000235
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000236 /// Test whether a pointer to the allocation escapes our analysis.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000237 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000238 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000239 /// ignored.
240 bool isEscaped() const { return PointerEscapingInstr; }
241
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000242 /// Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000243 /// @{
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000244 using iterator = SmallVectorImpl<Slice>::iterator;
245 using range = iterator_range<iterator>;
246
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000247 iterator begin() { return Slices.begin(); }
248 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000249
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000250 using const_iterator = SmallVectorImpl<Slice>::const_iterator;
251 using const_range = iterator_range<const_iterator>;
252
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000253 const_iterator begin() const { return Slices.begin(); }
254 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000255 /// @}
256
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000257 /// Erase a range of slices.
Chandler Carruth994cde82015-01-01 12:01:03 +0000258 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
Chandler Carruth0715cba2015-01-01 11:54:38 +0000259
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000260 /// Insert new slices for this alloca.
Chandler Carruth0715cba2015-01-01 11:54:38 +0000261 ///
262 /// This moves the slices into the alloca's slices collection, and re-sorts
263 /// everything so that the usual ordering properties of the alloca's slices
264 /// hold.
265 void insert(ArrayRef<Slice> NewSlices) {
266 int OldSize = Slices.size();
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000267 Slices.append(NewSlices.begin(), NewSlices.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +0000268 auto SliceI = Slices.begin() + OldSize;
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000269 llvm::sort(SliceI, Slices.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +0000270 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
271 }
272
Chandler Carruth29a18a42015-09-12 09:09:14 +0000273 // Forward declare the iterator and range accessor for walking the
274 // partitions.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000275 class partition_iterator;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000276 iterator_range<partition_iterator> partitions();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000277
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000278 /// Access the dead users for this alloca.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000279 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000280
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000281 /// Access the dead operands referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000282 ///
283 /// These are operands which have cannot actually be used to refer to the
284 /// alloca as they are outside its range and the user doesn't correct for
285 /// that. These mostly consist of PHI node inputs and the like which we just
286 /// need to replace with undef.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000287 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000288
Aaron Ballman615eb472017-10-15 14:32:27 +0000289#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000290 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000291 void printSlice(raw_ostream &OS, const_iterator I,
292 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000293 void printUse(raw_ostream &OS, const_iterator I,
294 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000295 void print(raw_ostream &OS) const;
Alp Tokerf929e092014-01-04 22:47:48 +0000296 void dump(const_iterator I) const;
297 void dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000298#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000299
300private:
301 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000302 class SliceBuilder;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000303
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000304 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000305
Aaron Ballman615eb472017-10-15 14:32:27 +0000306#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000307 /// Handle to alloca instruction to simplify method interfaces.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000308 AllocaInst &AI;
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000309#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000310
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000311 /// The instruction responsible for this alloca not having a known set
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000312 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000313 ///
314 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000315 /// store a pointer to that here and abort trying to form slices of the
316 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000317 Instruction *PointerEscapingInstr;
318
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000319 /// The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000320 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000321 /// We store a vector of the slices formed by uses of the alloca here. This
322 /// vector is sorted by increasing begin offset, and then the unsplittable
323 /// slices before the splittable ones. See the Slice inner class for more
324 /// details.
325 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000326
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000327 /// Instructions which will become dead if we rewrite the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000328 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000329 /// Note that these are not separated by slice. This is because we expect an
330 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
331 /// all these instructions can simply be removed and replaced with undef as
332 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000333 SmallVector<Instruction *, 8> DeadUsers;
334
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000335 /// Operands which will become dead if we rewrite the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000336 ///
337 /// These are operands that in their particular use can be replaced with
338 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
339 /// to PHI nodes and the like. They aren't entirely dead (there might be
340 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
341 /// want to swap this particular input for undef to simplify the use lists of
342 /// the alloca.
343 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000344};
Chandler Carruth29a18a42015-09-12 09:09:14 +0000345
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000346/// A partition of the slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000347///
348/// An ephemeral representation for a range of slices which can be viewed as
349/// a partition of the alloca. This range represents a span of the alloca's
350/// memory which cannot be split, and provides access to all of the slices
351/// overlapping some part of the partition.
352///
353/// Objects of this type are produced by traversing the alloca's slices, but
354/// are only ephemeral and not persistent.
355class llvm::sroa::Partition {
356private:
357 friend class AllocaSlices;
358 friend class AllocaSlices::partition_iterator;
359
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000360 using iterator = AllocaSlices::iterator;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000361
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000362 /// The beginning and ending offsets of the alloca for this
Chandler Carruth29a18a42015-09-12 09:09:14 +0000363 /// partition.
364 uint64_t BeginOffset, EndOffset;
365
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000366 /// The start and end iterators of this partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000367 iterator SI, SJ;
368
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000369 /// A collection of split slice tails overlapping the partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000370 SmallVector<Slice *, 4> SplitTails;
371
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000372 /// Raw constructor builds an empty partition starting and ending at
Chandler Carruth29a18a42015-09-12 09:09:14 +0000373 /// the given iterator.
374 Partition(iterator SI) : SI(SI), SJ(SI) {}
375
376public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000377 /// The start offset of this partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000378 ///
379 /// All of the contained slices start at or after this offset.
380 uint64_t beginOffset() const { return BeginOffset; }
381
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000382 /// The end offset of this partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000383 ///
384 /// All of the contained slices end at or before this offset.
385 uint64_t endOffset() const { return EndOffset; }
386
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000387 /// The size of the partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000388 ///
389 /// Note that this can never be zero.
390 uint64_t size() const {
391 assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
392 return EndOffset - BeginOffset;
393 }
394
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000395 /// Test whether this partition contains no slices, and merely spans
Chandler Carruth29a18a42015-09-12 09:09:14 +0000396 /// a region occupied by split slices.
397 bool empty() const { return SI == SJ; }
398
399 /// \name Iterate slices that start within the partition.
400 /// These may be splittable or unsplittable. They have a begin offset >= the
401 /// partition begin offset.
402 /// @{
403 // FIXME: We should probably define a "concat_iterator" helper and use that
404 // to stitch together pointee_iterators over the split tails and the
405 // contiguous iterators of the partition. That would give a much nicer
406 // interface here. We could then additionally expose filtered iterators for
407 // split, unsplit, and unsplittable splices based on the usage patterns.
408 iterator begin() const { return SI; }
409 iterator end() const { return SJ; }
410 /// @}
411
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000412 /// Get the sequence of split slice tails.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000413 ///
414 /// These tails are of slices which start before this partition but are
415 /// split and overlap into the partition. We accumulate these while forming
416 /// partitions.
417 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
418};
419
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000420/// An iterator over partitions of the alloca's slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000421///
422/// This iterator implements the core algorithm for partitioning the alloca's
423/// slices. It is a forward iterator as we don't support backtracking for
424/// efficiency reasons, and re-use a single storage area to maintain the
425/// current set of split slices.
426///
427/// It is templated on the slice iterator type to use so that it can operate
428/// with either const or non-const slice iterators.
429class AllocaSlices::partition_iterator
430 : public iterator_facade_base<partition_iterator, std::forward_iterator_tag,
431 Partition> {
432 friend class AllocaSlices;
433
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000434 /// Most of the state for walking the partitions is held in a class
Chandler Carruth29a18a42015-09-12 09:09:14 +0000435 /// with a nice interface for examining them.
436 Partition P;
437
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000438 /// We need to keep the end of the slices to know when to stop.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000439 AllocaSlices::iterator SE;
440
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000441 /// We also need to keep track of the maximum split end offset seen.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000442 /// FIXME: Do we really?
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000443 uint64_t MaxSplitSliceEndOffset = 0;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000444
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000445 /// Sets the partition to be empty at given iterator, and sets the
Chandler Carruth29a18a42015-09-12 09:09:14 +0000446 /// end iterator.
447 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000448 : P(SI), SE(SE) {
Chandler Carruth29a18a42015-09-12 09:09:14 +0000449 // If not already at the end, advance our state to form the initial
450 // partition.
451 if (SI != SE)
452 advance();
453 }
454
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000455 /// Advance the iterator to the next partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000456 ///
457 /// Requires that the iterator not be at the end of the slices.
458 void advance() {
459 assert((P.SI != SE || !P.SplitTails.empty()) &&
460 "Cannot advance past the end of the slices!");
461
462 // Clear out any split uses which have ended.
463 if (!P.SplitTails.empty()) {
464 if (P.EndOffset >= MaxSplitSliceEndOffset) {
465 // If we've finished all splits, this is easy.
466 P.SplitTails.clear();
467 MaxSplitSliceEndOffset = 0;
468 } else {
469 // Remove the uses which have ended in the prior partition. This
470 // cannot change the max split slice end because we just checked that
471 // the prior partition ended prior to that max.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000472 P.SplitTails.erase(llvm::remove_if(P.SplitTails,
473 [&](Slice *S) {
474 return S->endOffset() <=
475 P.EndOffset;
476 }),
477 P.SplitTails.end());
478 assert(llvm::any_of(P.SplitTails,
479 [&](Slice *S) {
480 return S->endOffset() == MaxSplitSliceEndOffset;
481 }) &&
Chandler Carruth29a18a42015-09-12 09:09:14 +0000482 "Could not find the current max split slice offset!");
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000483 assert(llvm::all_of(P.SplitTails,
484 [&](Slice *S) {
485 return S->endOffset() <= MaxSplitSliceEndOffset;
486 }) &&
Chandler Carruth29a18a42015-09-12 09:09:14 +0000487 "Max split slice end offset is not actually the max!");
488 }
489 }
490
491 // If P.SI is already at the end, then we've cleared the split tail and
492 // now have an end iterator.
493 if (P.SI == SE) {
494 assert(P.SplitTails.empty() && "Failed to clear the split slices!");
495 return;
496 }
497
498 // If we had a non-empty partition previously, set up the state for
499 // subsequent partitions.
500 if (P.SI != P.SJ) {
501 // Accumulate all the splittable slices which started in the old
502 // partition into the split list.
503 for (Slice &S : P)
504 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
505 P.SplitTails.push_back(&S);
506 MaxSplitSliceEndOffset =
507 std::max(S.endOffset(), MaxSplitSliceEndOffset);
508 }
509
510 // Start from the end of the previous partition.
511 P.SI = P.SJ;
512
513 // If P.SI is now at the end, we at most have a tail of split slices.
514 if (P.SI == SE) {
515 P.BeginOffset = P.EndOffset;
516 P.EndOffset = MaxSplitSliceEndOffset;
517 return;
518 }
519
520 // If the we have split slices and the next slice is after a gap and is
521 // not splittable immediately form an empty partition for the split
522 // slices up until the next slice begins.
523 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
524 !P.SI->isSplittable()) {
525 P.BeginOffset = P.EndOffset;
526 P.EndOffset = P.SI->beginOffset();
527 return;
528 }
529 }
530
531 // OK, we need to consume new slices. Set the end offset based on the
532 // current slice, and step SJ past it. The beginning offset of the
533 // partition is the beginning offset of the next slice unless we have
534 // pre-existing split slices that are continuing, in which case we begin
535 // at the prior end offset.
536 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
537 P.EndOffset = P.SI->endOffset();
538 ++P.SJ;
539
540 // There are two strategies to form a partition based on whether the
541 // partition starts with an unsplittable slice or a splittable slice.
542 if (!P.SI->isSplittable()) {
543 // When we're forming an unsplittable region, it must always start at
544 // the first slice and will extend through its end.
545 assert(P.BeginOffset == P.SI->beginOffset());
546
547 // Form a partition including all of the overlapping slices with this
548 // unsplittable slice.
549 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
550 if (!P.SJ->isSplittable())
551 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
552 ++P.SJ;
553 }
554
555 // We have a partition across a set of overlapping unsplittable
556 // partitions.
557 return;
558 }
559
560 // If we're starting with a splittable slice, then we need to form
561 // a synthetic partition spanning it and any other overlapping splittable
562 // splices.
563 assert(P.SI->isSplittable() && "Forming a splittable partition!");
564
565 // Collect all of the overlapping splittable slices.
566 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
567 P.SJ->isSplittable()) {
568 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
569 ++P.SJ;
570 }
571
572 // Back upiP.EndOffset if we ended the span early when encountering an
573 // unsplittable slice. This synthesizes the early end offset of
574 // a partition spanning only splittable slices.
575 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
576 assert(!P.SJ->isSplittable());
577 P.EndOffset = P.SJ->beginOffset();
578 }
579 }
580
581public:
582 bool operator==(const partition_iterator &RHS) const {
583 assert(SE == RHS.SE &&
584 "End iterators don't match between compared partition iterators!");
585
586 // The observed positions of partitions is marked by the P.SI iterator and
587 // the emptiness of the split slices. The latter is only relevant when
588 // P.SI == SE, as the end iterator will additionally have an empty split
589 // slices list, but the prior may have the same P.SI and a tail of split
590 // slices.
591 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
592 assert(P.SJ == RHS.P.SJ &&
593 "Same set of slices formed two different sized partitions!");
594 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
595 "Same slice position with differently sized non-empty split "
596 "slice tails!");
597 return true;
598 }
599 return false;
600 }
601
602 partition_iterator &operator++() {
603 advance();
604 return *this;
605 }
606
607 Partition &operator*() { return P; }
608};
609
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000610/// A forward range over the partitions of the alloca's slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000611///
612/// This accesses an iterator range over the partitions of the alloca's
613/// slices. It computes these partitions on the fly based on the overlapping
614/// offsets of the slices and the ability to split them. It will visit "empty"
615/// partitions to cover regions of the alloca only accessed via split
616/// slices.
617iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() {
618 return make_range(partition_iterator(begin(), end()),
619 partition_iterator(end(), end()));
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000620}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000621
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000622static Value *foldSelectInst(SelectInst &SI) {
623 // If the condition being selected on is a constant or the same value is
624 // being selected between, fold the select. Yes this does (rarely) happen
625 // early on.
626 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
Chandler Carruth113dc642014-12-20 02:39:18 +0000627 return SI.getOperand(1 + CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000628 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000629 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000630
Craig Topperf40110f2014-04-25 05:29:35 +0000631 return nullptr;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000632}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000633
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000634/// A helper that folds a PHI node or a select.
Jingyue Wuec33fa92014-08-22 22:45:57 +0000635static Value *foldPHINodeOrSelectInst(Instruction &I) {
636 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
637 // If PN merges together the same value, return that value.
638 return PN->hasConstantValue();
639 }
640 return foldSelectInst(cast<SelectInst>(I));
641}
642
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000643/// Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000644///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000645/// This class builds a set of alloca slices by recursively visiting the uses
646/// of an alloca and making a slice for each load and store at each offset.
647class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
648 friend class PtrUseVisitor<SliceBuilder>;
649 friend class InstVisitor<SliceBuilder>;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000650
651 using Base = PtrUseVisitor<SliceBuilder>;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000652
653 const uint64_t AllocSize;
Chandler Carruth83934062014-10-16 21:11:55 +0000654 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000655
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000656 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000657 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
658
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000659 /// Set to de-duplicate dead instructions found in the use walk.
Chandler Carruthf0546402013-07-18 07:15:00 +0000660 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000661
662public:
Chandler Carruth83934062014-10-16 21:11:55 +0000663 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000664 : PtrUseVisitor<SliceBuilder>(DL),
Chandler Carruth83934062014-10-16 21:11:55 +0000665 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000666
667private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000668 void markAsDead(Instruction &I) {
David Blaikie70573dc2014-11-19 07:49:26 +0000669 if (VisitedDeadInsts.insert(&I).second)
Chandler Carruth83934062014-10-16 21:11:55 +0000670 AS.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000671 }
672
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000673 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000674 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000675 // Completely skip uses which have a zero size or start either before or
676 // past the end of the allocation.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000677 if (Size == 0 || Offset.uge(AllocSize)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000678 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @"
679 << Offset
680 << " which has zero size or starts outside of the "
681 << AllocSize << " byte alloca:\n"
682 << " alloca: " << AS.AI << "\n"
683 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000684 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000685 }
686
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000687 uint64_t BeginOffset = Offset.getZExtValue();
688 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000689
690 // Clamp the end offset to the end of the allocation. Note that this is
691 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000692 // This may appear superficially to be something we could ignore entirely,
693 // but that is not so! There may be widened loads or PHI-node uses where
694 // some instructions are dead but not others. We can't completely ignore
695 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000696 assert(AllocSize >= BeginOffset); // Established above.
697 if (Size > AllocSize - BeginOffset) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000698 LLVM_DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @"
699 << Offset << " to remain within the " << AllocSize
700 << " byte alloca:\n"
701 << " alloca: " << AS.AI << "\n"
702 << " use: " << I << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000703 EndOffset = AllocSize;
704 }
705
Chandler Carruth83934062014-10-16 21:11:55 +0000706 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000707 }
708
709 void visitBitCastInst(BitCastInst &BC) {
710 if (BC.use_empty())
711 return markAsDead(BC);
712
713 return Base::visitBitCastInst(BC);
714 }
715
Matt Arsenault282dac72019-06-14 21:38:31 +0000716 void visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
717 if (ASC.use_empty())
718 return markAsDead(ASC);
719
720 return Base::visitAddrSpaceCastInst(ASC);
721 }
722
Chandler Carruthf0546402013-07-18 07:15:00 +0000723 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
724 if (GEPI.use_empty())
725 return markAsDead(GEPI);
726
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000727 if (SROAStrictInbounds && GEPI.isInBounds()) {
728 // FIXME: This is a manually un-factored variant of the basic code inside
729 // of GEPs with checking of the inbounds invariant specified in the
730 // langref in a very strict sense. If we ever want to enable
731 // SROAStrictInbounds, this code should be factored cleanly into
732 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
Hal Finkel5c83a092016-03-28 11:23:21 +0000733 // by writing out the code here where we have the underlying allocation
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000734 // size readily available.
735 APInt GEPOffset = Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000736 const DataLayout &DL = GEPI.getModule()->getDataLayout();
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000737 for (gep_type_iterator GTI = gep_type_begin(GEPI),
738 GTE = gep_type_end(GEPI);
739 GTI != GTE; ++GTI) {
740 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
741 if (!OpC)
742 break;
743
744 // Handle a struct index, which adds its field offset to the pointer.
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000745 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000746 unsigned ElementIdx = OpC->getZExtValue();
747 const StructLayout *SL = DL.getStructLayout(STy);
748 GEPOffset +=
749 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
750 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +0000751 // For array or vector indices, scale the index by the size of the
752 // type.
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000753 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
754 GEPOffset += Index * APInt(Offset.getBitWidth(),
755 DL.getTypeAllocSize(GTI.getIndexedType()));
756 }
757
758 // If this index has computed an intermediate pointer which is not
759 // inbounds, then the result of the GEP is a poison value and we can
760 // delete it and all uses.
761 if (GEPOffset.ugt(AllocSize))
762 return markAsDead(GEPI);
763 }
764 }
765
Chandler Carruthf0546402013-07-18 07:15:00 +0000766 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000767 }
768
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000769 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000770 uint64_t Size, bool IsVolatile) {
Chandler Carruth24ac8302015-01-02 03:55:54 +0000771 // We allow splitting of non-volatile loads and stores where the type is an
772 // integer type. These may be used to implement 'memcpy' or other "transfer
773 // of bits" patterns.
774 bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
Chandler Carruth58d05562012-10-25 04:37:07 +0000775
776 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000777 }
778
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000779 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000780 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
781 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000782
783 if (!IsOffsetKnown)
784 return PI.setAborted(&LI);
785
Matt Arsenault282dac72019-06-14 21:38:31 +0000786 if (LI.isVolatile() &&
787 LI.getPointerAddressSpace() != DL.getAllocaAddrSpace())
788 return PI.setAborted(&LI);
789
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000790 uint64_t Size = DL.getTypeStoreSize(LI.getType());
791 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000792 }
793
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000794 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000795 Value *ValOp = SI.getValueOperand();
796 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000797 return PI.setEscapedAndAborted(&SI);
798 if (!IsOffsetKnown)
799 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000800
Matt Arsenault282dac72019-06-14 21:38:31 +0000801 if (SI.isVolatile() &&
802 SI.getPointerAddressSpace() != DL.getAllocaAddrSpace())
803 return PI.setAborted(&SI);
804
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000805 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
806
807 // If this memory access can be shown to *statically* extend outside the
Hiroshi Inoue0909ca12018-01-26 08:15:29 +0000808 // bounds of the allocation, it's behavior is undefined, so simply
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000809 // ignore it. Note that this is more strict than the generic clamping
810 // behavior of insertUse. We also try to handle cases which might run the
811 // risk of overflow.
812 // FIXME: We should instead consider the pointer to have escaped if this
813 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000814 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000815 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @"
816 << Offset << " which extends past the end of the "
817 << AllocSize << " byte alloca:\n"
818 << " alloca: " << AS.AI << "\n"
819 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000820 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000821 }
822
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000823 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
824 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000825 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000826 }
827
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000828 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000829 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000830 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000831 if ((Length && Length->getValue() == 0) ||
Chandler Carruth6aedc102014-02-26 03:14:14 +0000832 (IsOffsetKnown && Offset.uge(AllocSize)))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000833 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000834 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000835
836 if (!IsOffsetKnown)
837 return PI.setAborted(&II);
838
Matt Arsenault282dac72019-06-14 21:38:31 +0000839 // Don't replace this with a store with a different address space. TODO:
840 // Use a store with the casted new alloca?
841 if (II.isVolatile() && II.getDestAddressSpace() != DL.getAllocaAddrSpace())
842 return PI.setAborted(&II);
843
Chandler Carruth113dc642014-12-20 02:39:18 +0000844 insertUse(II, Offset, Length ? Length->getLimitedValue()
845 : AllocSize - Offset.getLimitedValue(),
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000846 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000847 }
848
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000849 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000850 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000851 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000852 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000853 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000854
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000855 // Because we can visit these intrinsics twice, also check to see if the
856 // first time marked this instruction as dead. If so, skip it.
857 if (VisitedDeadInsts.count(&II))
858 return;
859
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000860 if (!IsOffsetKnown)
861 return PI.setAborted(&II);
862
Matt Arsenault282dac72019-06-14 21:38:31 +0000863 // Don't replace this with a load/store with a different address space.
864 // TODO: Use a store with the casted new alloca?
865 if (II.isVolatile() &&
866 (II.getDestAddressSpace() != DL.getAllocaAddrSpace() ||
867 II.getSourceAddressSpace() != DL.getAllocaAddrSpace()))
868 return PI.setAborted(&II);
869
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000870 // This side of the transfer is completely out-of-bounds, and so we can
871 // nuke the entire transfer. However, we also need to nuke the other side
872 // if already added to our partitions.
873 // FIXME: Yet another place we really should bypass this when
874 // instrumenting for ASan.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000875 if (Offset.uge(AllocSize)) {
Chandler Carruth113dc642014-12-20 02:39:18 +0000876 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
877 MemTransferSliceMap.find(&II);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000878 if (MTPI != MemTransferSliceMap.end())
Chandler Carruth83934062014-10-16 21:11:55 +0000879 AS.Slices[MTPI->second].kill();
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000880 return markAsDead(II);
881 }
882
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000883 uint64_t RawOffset = Offset.getLimitedValue();
Chandler Carruth113dc642014-12-20 02:39:18 +0000884 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000885
Chandler Carruthf0546402013-07-18 07:15:00 +0000886 // Check for the special case where the same exact value is used for both
887 // source and dest.
888 if (*U == II.getRawDest() && *U == II.getRawSource()) {
889 // For non-volatile transfers this is a no-op.
890 if (!II.isVolatile())
891 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000892
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000893 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000894 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000895
Chandler Carruthf0546402013-07-18 07:15:00 +0000896 // If we have seen both source and destination for a mem transfer, then
897 // they both point to the same alloca.
898 bool Inserted;
899 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000900 std::tie(MTPI, Inserted) =
Chandler Carruth83934062014-10-16 21:11:55 +0000901 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000902 unsigned PrevIdx = MTPI->second;
903 if (!Inserted) {
Chandler Carruth83934062014-10-16 21:11:55 +0000904 Slice &PrevP = AS.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000905
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000906 // Check if the begin offsets match and this is a non-volatile transfer.
907 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000908 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
909 PrevP.kill();
910 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000911 }
912
913 // Otherwise we have an offset transfer within the same alloca. We can't
914 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000915 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000916 }
917
Chandler Carruthe3899f22013-07-15 17:36:21 +0000918 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000919 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000920
Chandler Carruthf0546402013-07-18 07:15:00 +0000921 // Check that we ended up with a valid index in the map.
Chandler Carruth83934062014-10-16 21:11:55 +0000922 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000923 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000924 }
925
926 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000927 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000928 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000929 void visitIntrinsicInst(IntrinsicInst &II) {
930 if (!IsOffsetKnown)
931 return PI.setAborted(&II);
932
Vedant Kumarb264d692018-12-21 21:49:40 +0000933 if (II.isLifetimeStartOrEnd()) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000934 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000935 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
936 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000937 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000938 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000939 }
940
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000941 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000942 }
943
944 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
945 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000946 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000947 // are considered unsplittable and the size is the maximum loaded or stored
948 // size.
949 SmallPtrSet<Instruction *, 4> Visited;
950 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
951 Visited.insert(Root);
952 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000953 const DataLayout &DL = Root->getModule()->getDataLayout();
Chandler Carruth8b907e82012-09-25 10:03:40 +0000954 // If there are no loads or stores, the access is dead. We mark that as
955 // a size zero access.
956 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000957 do {
958 Instruction *I, *UsedI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000959 std::tie(UsedI, I) = Uses.pop_back_val();
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000960
961 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000962 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000963 continue;
964 }
965 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
966 Value *Op = SI->getOperand(0);
967 if (Op == UsedI)
968 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000969 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000970 continue;
971 }
972
973 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
974 if (!GEP->hasAllZeroIndices())
975 return GEP;
976 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
Matt Arsenault282dac72019-06-14 21:38:31 +0000977 !isa<SelectInst>(I) && !isa<AddrSpaceCastInst>(I)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000978 return I;
979 }
980
Chandler Carruthcdf47882014-03-09 03:16:01 +0000981 for (User *U : I->users())
David Blaikie70573dc2014-11-19 07:49:26 +0000982 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000983 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000984 } while (!Uses.empty());
985
Craig Topperf40110f2014-04-25 05:29:35 +0000986 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000987 }
988
Jingyue Wuec33fa92014-08-22 22:45:57 +0000989 void visitPHINodeOrSelectInst(Instruction &I) {
990 assert(isa<PHINode>(I) || isa<SelectInst>(I));
991 if (I.use_empty())
992 return markAsDead(I);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000993
Jingyue Wuec33fa92014-08-22 22:45:57 +0000994 // TODO: We could use SimplifyInstruction here to fold PHINodes and
995 // SelectInsts. However, doing so requires to change the current
996 // dead-operand-tracking mechanism. For instance, suppose neither loading
997 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
998 // trap either. However, if we simply replace %U with undef using the
999 // current dead-operand-tracking mechanism, "load (select undef, undef,
1000 // %other)" may trap because the select may return the first operand
1001 // "undef".
1002 if (Value *Result = foldPHINodeOrSelectInst(I)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001003 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001004 // If the result of the constant fold will be the pointer, recurse
Jingyue Wuec33fa92014-08-22 22:45:57 +00001005 // through the PHI/select as if we had RAUW'ed it.
1006 enqueueUsers(I);
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001007 else
Jingyue Wuec33fa92014-08-22 22:45:57 +00001008 // Otherwise the operand to the PHI/select is dead, and we can replace
1009 // it with undef.
Chandler Carruth83934062014-10-16 21:11:55 +00001010 AS.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001011
1012 return;
1013 }
Jingyue Wuec33fa92014-08-22 22:45:57 +00001014
Chandler Carruthf0546402013-07-18 07:15:00 +00001015 if (!IsOffsetKnown)
Jingyue Wuec33fa92014-08-22 22:45:57 +00001016 return PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001017
Chandler Carruthf0546402013-07-18 07:15:00 +00001018 // See if we already have computed info on this node.
Jingyue Wuec33fa92014-08-22 22:45:57 +00001019 uint64_t &Size = PHIOrSelectSizes[&I];
1020 if (!Size) {
1021 // This is a new PHI/Select, check for an unsafe use of it.
1022 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
Chandler Carruthf0546402013-07-18 07:15:00 +00001023 return PI.setAborted(UnsafeI);
1024 }
1025
1026 // For PHI and select operands outside the alloca, we can't nuke the entire
1027 // phi or select -- the other side might still be relevant, so we special
1028 // case them here and use a separate structure to track the operands
1029 // themselves which should be replaced with undef.
1030 // FIXME: This should instead be escaped in the event we're instrumenting
1031 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +00001032 if (Offset.uge(AllocSize)) {
Chandler Carruth83934062014-10-16 21:11:55 +00001033 AS.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +00001034 return;
1035 }
1036
Jingyue Wuec33fa92014-08-22 22:45:57 +00001037 insertUse(I, Offset, Size);
1038 }
1039
Chandler Carruth113dc642014-12-20 02:39:18 +00001040 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
Jingyue Wuec33fa92014-08-22 22:45:57 +00001041
Chandler Carruth113dc642014-12-20 02:39:18 +00001042 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001043
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001044 /// Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth113dc642014-12-20 02:39:18 +00001045 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001046};
1047
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001048AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001049 :
Aaron Ballman615eb472017-10-15 14:32:27 +00001050#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001051 AI(AI),
1052#endif
Craig Topperf40110f2014-04-25 05:29:35 +00001053 PointerEscapingInstr(nullptr) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001054 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001055 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001056 if (PtrI.isEscaped() || PtrI.isAborted()) {
1057 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001058 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001059 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1060 : PtrI.getAbortingInst();
1061 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001062 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001063 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001064
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001065 Slices.erase(
1066 llvm::remove_if(Slices, [](const Slice &S) { return S.isDead(); }),
1067 Slices.end());
Benjamin Kramer08e50702013-07-20 08:38:34 +00001068
Hal Finkel29f51312016-03-28 11:13:03 +00001069#ifndef NDEBUG
Chandler Carruth83cee772014-02-25 03:59:29 +00001070 if (SROARandomShuffleSlices) {
Pavel Labathc207bec2016-11-09 12:07:12 +00001071 std::mt19937 MT(static_cast<unsigned>(
1072 std::chrono::system_clock::now().time_since_epoch().count()));
Chandler Carruth83cee772014-02-25 03:59:29 +00001073 std::shuffle(Slices.begin(), Slices.end(), MT);
1074 }
1075#endif
1076
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001077 // Sort the uses. This arranges for the offsets to be in ascending order,
1078 // and the sizes to be in descending order.
Fangrui Song0cac7262018-09-27 02:13:45 +00001079 llvm::sort(Slices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001080}
1081
Aaron Ballman615eb472017-10-15 14:32:27 +00001082#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001083
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001084void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1085 StringRef Indent) const {
1086 printSlice(OS, I, Indent);
Chandler Carruth0715cba2015-01-01 11:54:38 +00001087 OS << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001088 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001089}
1090
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001091void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1092 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001093 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001094 << " slice #" << (I - begin())
Chandler Carruth0715cba2015-01-01 11:54:38 +00001095 << (I->isSplittable() ? " (splittable)" : "");
Chandler Carruthf0546402013-07-18 07:15:00 +00001096}
1097
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001098void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1099 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001100 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001101}
1102
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001103void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001104 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001105 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001106 << " A pointer to this alloca escaped by:\n"
1107 << " " << *PointerEscapingInstr << "\n";
1108 return;
1109 }
1110
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001111 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001112 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001113 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001114}
1115
Alp Tokerf929e092014-01-04 22:47:48 +00001116LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1117 print(dbgs(), I);
1118}
1119LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001120
Aaron Ballman615eb472017-10-15 14:32:27 +00001121#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001122
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001123/// Walk the range of a partitioning looking for a common type to cover this
1124/// sequence of slices.
1125static Type *findCommonType(AllocaSlices::const_iterator B,
1126 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001127 uint64_t EndOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001128 Type *Ty = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001129 bool TyIsCommon = true;
Craig Topperf40110f2014-04-25 05:29:35 +00001130 IntegerType *ITy = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001131
1132 // Note that we need to look at *every* alloca slice's Use to ensure we
1133 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001134 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001135 Use *U = I->getUse();
1136 if (isa<IntrinsicInst>(*U->getUser()))
1137 continue;
1138 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1139 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001140
Craig Topperf40110f2014-04-25 05:29:35 +00001141 Type *UserTy = nullptr;
Chandler Carrutha1262002013-11-19 09:03:18 +00001142 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001143 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001144 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001145 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001146 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001147
Chandler Carruth4de31542014-01-21 23:16:05 +00001148 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001149 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001150 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001151 // entity causing the split. Also skip if the type is not a byte width
1152 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001153 if (UserITy->getBitWidth() % 8 != 0 ||
1154 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001155 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001156
Chandler Carruth4de31542014-01-21 23:16:05 +00001157 // Track the largest bitwidth integer type used in this way in case there
1158 // is no common type.
1159 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1160 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001161 }
Duncan P. N. Exon Smith73686d32014-06-17 00:19:35 +00001162
1163 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1164 // depend on types skipped above.
1165 if (!UserTy || (Ty && Ty != UserTy))
1166 TyIsCommon = false; // Give up on anything but an iN type.
1167 else
1168 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001169 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001170
1171 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001172}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001173
Chandler Carruthf0546402013-07-18 07:15:00 +00001174/// PHI instructions that use an alloca and are subsequently loaded can be
1175/// rewritten to load both input pointers in the pred blocks and then PHI the
1176/// results, allowing the load of the alloca to be promoted.
1177/// From this:
1178/// %P2 = phi [i32* %Alloca, i32* %Other]
1179/// %V = load i32* %P2
1180/// to:
1181/// %V1 = load i32* %Alloca -> will be mem2reg'd
1182/// ...
1183/// %V2 = load i32* %Other
1184/// ...
1185/// %V = phi [i32 %V1, i32 %V2]
1186///
1187/// We can do this to a select if its only uses are loads and if the operands
1188/// to the select can be loaded unconditionally.
1189///
1190/// FIXME: This should be hoisted into a generic utility, likely in
1191/// Transforms/Util/Local.h
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001192static bool isSafePHIToSpeculate(PHINode &PN) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001193 // For now, we can only do this promotion if the load is in the same block
1194 // as the PHI, and if there are no stores between the phi and load.
1195 // TODO: Allow recursive phi users.
1196 // TODO: Allow stores.
1197 BasicBlock *BB = PN.getParent();
1198 unsigned MaxAlign = 0;
1199 bool HaveLoad = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001200 for (User *U : PN.users()) {
1201 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001202 if (!LI || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001203 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001204
Chandler Carruthf0546402013-07-18 07:15:00 +00001205 // For now we only allow loads in the same block as the PHI. This is
1206 // a common case that happens when instcombine merges two loads through
1207 // a PHI.
1208 if (LI->getParent() != BB)
1209 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001210
Chandler Carruthf0546402013-07-18 07:15:00 +00001211 // Ensure that there are no instructions between the PHI and the load that
1212 // could store.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001213 for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
Chandler Carruthf0546402013-07-18 07:15:00 +00001214 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001215 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001216
Chandler Carruthf0546402013-07-18 07:15:00 +00001217 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1218 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001219 }
1220
Chandler Carruthf0546402013-07-18 07:15:00 +00001221 if (!HaveLoad)
1222 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001223
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001224 const DataLayout &DL = PN.getModule()->getDataLayout();
1225
Chandler Carruthf0546402013-07-18 07:15:00 +00001226 // We can only transform this if it is safe to push the loads into the
1227 // predecessor blocks. The only thing to watch out for is that we can't put
1228 // a possibly trapping load in the predecessor if it is a critical edge.
1229 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001230 Instruction *TI = PN.getIncomingBlock(Idx)->getTerminator();
Chandler Carruthf0546402013-07-18 07:15:00 +00001231 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001232
Chandler Carruthf0546402013-07-18 07:15:00 +00001233 // If the value is produced by the terminator of the predecessor (an
1234 // invoke) or it has side-effects, there is no valid place to put a load
1235 // in the predecessor.
1236 if (TI == InVal || TI->mayHaveSideEffects())
1237 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001238
Chandler Carruthf0546402013-07-18 07:15:00 +00001239 // If the predecessor has a single successor, then the edge isn't
1240 // critical.
1241 if (TI->getNumSuccessors() == 1)
1242 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001243
Chandler Carruthf0546402013-07-18 07:15:00 +00001244 // If this pointer is always safe to load, or if we can prove that there
1245 // is already a load in the block, then we can move the load to the pred
1246 // block.
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001247 if (isSafeToLoadUnconditionally(InVal, MaxAlign, DL, TI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001248 continue;
1249
1250 return false;
1251 }
1252
1253 return true;
1254}
1255
1256static void speculatePHINodeLoads(PHINode &PN) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001257 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001258
James Y Knight14359ef2019-02-01 20:44:24 +00001259 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
1260 Type *LoadTy = SomeLoad->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00001261 IRBuilderTy PHIBuilder(&PN);
1262 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1263 PN.getName() + ".sroa.speculated");
1264
Hal Finkelcc39b672014-07-24 12:16:19 +00001265 // Get the AA tags and alignment to use from one of the loads. It doesn't
Chandler Carruthf0546402013-07-18 07:15:00 +00001266 // matter which one we get and if any differ.
Hal Finkelcc39b672014-07-24 12:16:19 +00001267 AAMDNodes AATags;
1268 SomeLoad->getAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001269 unsigned Align = SomeLoad->getAlignment();
1270
1271 // Rewrite all loads of the PN to use the new PHI.
1272 while (!PN.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001273 LoadInst *LI = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001274 LI->replaceAllUsesWith(NewPN);
1275 LI->eraseFromParent();
1276 }
1277
1278 // Inject loads into all of the pred blocks.
Bjorn Pettersson81a76a32018-05-17 07:21:41 +00001279 DenseMap<BasicBlock*, Value*> InjectedLoads;
Chandler Carruthf0546402013-07-18 07:15:00 +00001280 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1281 BasicBlock *Pred = PN.getIncomingBlock(Idx);
Chandler Carruthf0546402013-07-18 07:15:00 +00001282 Value *InVal = PN.getIncomingValue(Idx);
Bjorn Pettersson81a76a32018-05-17 07:21:41 +00001283
1284 // A PHI node is allowed to have multiple (duplicated) entries for the same
1285 // basic block, as long as the value is the same. So if we already injected
1286 // a load in the predecessor, then we should reuse the same load for all
1287 // duplicated entries.
1288 if (Value* V = InjectedLoads.lookup(Pred)) {
1289 NewPN->addIncoming(V, Pred);
1290 continue;
1291 }
1292
Chandler Carruthedb12a82018-10-15 10:04:59 +00001293 Instruction *TI = Pred->getTerminator();
Chandler Carruthf0546402013-07-18 07:15:00 +00001294 IRBuilderTy PredBuilder(TI);
1295
1296 LoadInst *Load = PredBuilder.CreateLoad(
James Y Knight14359ef2019-02-01 20:44:24 +00001297 LoadTy, InVal,
1298 (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
Chandler Carruthf0546402013-07-18 07:15:00 +00001299 ++NumLoadsSpeculated;
1300 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001301 if (AATags)
1302 Load->setAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001303 NewPN->addIncoming(Load, Pred);
Bjorn Pettersson81a76a32018-05-17 07:21:41 +00001304 InjectedLoads[Pred] = Load;
Chandler Carruthf0546402013-07-18 07:15:00 +00001305 }
1306
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001307 LLVM_DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001308 PN.eraseFromParent();
1309}
1310
1311/// Select instructions that use an alloca and are subsequently loaded can be
1312/// rewritten to load both input pointers and then select between the result,
1313/// allowing the load of the alloca to be promoted.
1314/// From this:
1315/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1316/// %V = load i32* %P2
1317/// to:
1318/// %V1 = load i32* %Alloca -> will be mem2reg'd
1319/// %V2 = load i32* %Other
1320/// %V = select i1 %cond, i32 %V1, i32 %V2
1321///
1322/// We can do this to a select if its only uses are loads and if the operand
1323/// to the select can be loaded unconditionally.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001324static bool isSafeSelectToSpeculate(SelectInst &SI) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001325 Value *TValue = SI.getTrueValue();
1326 Value *FValue = SI.getFalseValue();
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001327 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00001328
Chandler Carruthcdf47882014-03-09 03:16:01 +00001329 for (User *U : SI.users()) {
1330 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001331 if (!LI || !LI->isSimple())
Chandler Carruthf0546402013-07-18 07:15:00 +00001332 return false;
1333
Hiroshi Inoueb3008242017-06-24 15:43:33 +00001334 // Both operands to the select need to be dereferenceable, either
Chandler Carruthf0546402013-07-18 07:15:00 +00001335 // absolutely (e.g. allocas) or at this point because we can see other
1336 // accesses to it.
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001337 if (!isSafeToLoadUnconditionally(TValue, LI->getAlignment(), DL, LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001338 return false;
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001339 if (!isSafeToLoadUnconditionally(FValue, LI->getAlignment(), DL, LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001340 return false;
1341 }
1342
1343 return true;
1344}
1345
1346static void speculateSelectInstLoads(SelectInst &SI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001347 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001348
1349 IRBuilderTy IRB(&SI);
1350 Value *TV = SI.getTrueValue();
1351 Value *FV = SI.getFalseValue();
1352 // Replace the loads of the select with a select of two loads.
1353 while (!SI.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001354 LoadInst *LI = cast<LoadInst>(SI.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001355 assert(LI->isSimple() && "We only speculate simple loads");
1356
1357 IRB.SetInsertPoint(LI);
James Y Knight14359ef2019-02-01 20:44:24 +00001358 LoadInst *TL = IRB.CreateLoad(LI->getType(), TV,
1359 LI->getName() + ".sroa.speculate.load.true");
1360 LoadInst *FL = IRB.CreateLoad(LI->getType(), FV,
1361 LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001362 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001363
Hal Finkelcc39b672014-07-24 12:16:19 +00001364 // Transfer alignment and AA info if present.
Chandler Carruthf0546402013-07-18 07:15:00 +00001365 TL->setAlignment(LI->getAlignment());
1366 FL->setAlignment(LI->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +00001367
1368 AAMDNodes Tags;
1369 LI->getAAMetadata(Tags);
1370 if (Tags) {
1371 TL->setAAMetadata(Tags);
1372 FL->setAAMetadata(Tags);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001373 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001374
1375 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1376 LI->getName() + ".sroa.speculated");
1377
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001378 LLVM_DEBUG(dbgs() << " speculated to: " << *V << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001379 LI->replaceAllUsesWith(V);
1380 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001381 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001382 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001383}
1384
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001385/// Build a GEP out of a base pointer and indices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001386///
1387/// This will return the BasePtr if that is valid, or build a new GEP
1388/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001389static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001390 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001391 if (Indices.empty())
1392 return BasePtr;
1393
1394 // A single zero index is a no-op, so check for this and avoid building a GEP
1395 // in that case.
1396 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1397 return BasePtr;
1398
James Y Knight77160752019-02-01 20:44:47 +00001399 return IRB.CreateInBoundsGEP(BasePtr->getType()->getPointerElementType(),
1400 BasePtr, Indices, NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001401}
1402
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001403/// Get a natural GEP off of the BasePtr walking through Ty toward
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001404/// TargetTy without changing the offset of the pointer.
1405///
1406/// This routine assumes we've already established a properly offset GEP with
1407/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1408/// zero-indices down through type layers until we find one the same as
1409/// TargetTy. If we can't find one with the same type, we at least try to use
1410/// one with the same size. If none of that works, we just produce the GEP as
1411/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001412static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001413 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001414 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001415 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001416 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001417 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001418
Nicola Zaghenf96383c2018-10-30 11:15:04 +00001419 // Offset size to use for the indices.
1420 unsigned OffsetSize = DL.getIndexTypeSizeInBits(BasePtr->getType());
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001421
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001422 // See if we can descend into a struct and locate a field with the correct
1423 // type.
1424 unsigned NumLayers = 0;
1425 Type *ElementTy = Ty;
1426 do {
1427 if (ElementTy->isPointerTy())
1428 break;
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001429
1430 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1431 ElementTy = ArrayTy->getElementType();
Nicola Zaghenf96383c2018-10-30 11:15:04 +00001432 Indices.push_back(IRB.getIntN(OffsetSize, 0));
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001433 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1434 ElementTy = VectorTy->getElementType();
1435 Indices.push_back(IRB.getInt32(0));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001436 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001437 if (STy->element_begin() == STy->element_end())
1438 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001439 ElementTy = *STy->element_begin();
1440 Indices.push_back(IRB.getInt32(0));
1441 } else {
1442 break;
1443 }
1444 ++NumLayers;
1445 } while (ElementTy != TargetTy);
1446 if (ElementTy != TargetTy)
1447 Indices.erase(Indices.end() - NumLayers, Indices.end());
1448
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001449 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001450}
1451
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001452/// Recursively compute indices for a natural GEP.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001453///
1454/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1455/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001456static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001457 Value *Ptr, Type *Ty, APInt &Offset,
1458 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001459 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001460 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001461 if (Offset == 0)
Chandler Carruth113dc642014-12-20 02:39:18 +00001462 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1463 NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001464
1465 // We can't recurse through pointer types.
1466 if (Ty->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001467 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001468
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001469 // We try to analyze GEPs over vectors here, but note that these GEPs are
1470 // extremely poorly defined currently. The long-term goal is to remove GEPing
1471 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001472 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001473 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Craig Topperf40110f2014-04-25 05:29:35 +00001474 if (ElementSizeInBits % 8 != 0) {
1475 // GEPs over non-multiple of 8 size vector elements are invalid.
1476 return nullptr;
1477 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001478 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001479 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001480 if (NumSkippedElements.ugt(VecTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001481 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001482 Offset -= NumSkippedElements * ElementSize;
1483 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001484 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001485 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001486 }
1487
1488 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1489 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001490 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001491 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001492 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001493 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001494
1495 Offset -= NumSkippedElements * ElementSize;
1496 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001497 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001498 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001499 }
1500
1501 StructType *STy = dyn_cast<StructType>(Ty);
1502 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00001503 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001504
Chandler Carruth90a735d2013-07-19 07:21:28 +00001505 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001506 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001507 if (StructOffset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00001508 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001509 unsigned Index = SL->getElementContainingOffset(StructOffset);
1510 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1511 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001512 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Craig Topperf40110f2014-04-25 05:29:35 +00001513 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001514
1515 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001516 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001517 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001518}
1519
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001520/// Get a natural GEP from a base pointer to a particular offset and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001521/// resulting in a particular type.
1522///
1523/// The goal is to produce a "natural" looking GEP that works with the existing
1524/// composite types to arrive at the appropriate offset and element type for
1525/// a pointer. TargetTy is the element type the returned GEP should point-to if
1526/// possible. We recurse by decreasing Offset, adding the appropriate index to
1527/// Indices, and setting Ty to the result subtype.
1528///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001529/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001530static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001531 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001532 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001533 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001534 PointerType *Ty = cast<PointerType>(Ptr->getType());
1535
1536 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1537 // an i8.
Chandler Carruth286d87e2014-02-26 08:25:02 +00001538 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +00001539 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001540
1541 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001542 if (!ElementTy->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +00001543 return nullptr; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001544 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001545 if (ElementSize == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001546 return nullptr; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001547 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001548
1549 Offset -= NumSkippedElements * ElementSize;
1550 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001551 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001552 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001553}
1554
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001555/// Compute an adjusted pointer from Ptr by Offset bytes where the
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001556/// resulting pointer has PointerTy.
1557///
1558/// This tries very hard to compute a "natural" GEP which arrives at the offset
1559/// and produces the pointer type desired. Where it cannot, it will try to use
1560/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1561/// fails, it will try to use an existing i8* and GEP to the byte offset and
1562/// bitcast to the type.
1563///
1564/// The strategy for finding the more natural GEPs is to peel off layers of the
1565/// pointer, walking back through bit casts and GEPs, searching for a base
1566/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001567/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001568/// a single GEP as possible, thus making each GEP more independent of the
1569/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001570static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001571 APInt Offset, Type *PointerTy, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001572 // Even though we don't look through PHI nodes, we could be called on an
1573 // instruction in an unreachable block, which may be on a cycle.
1574 SmallPtrSet<Value *, 4> Visited;
1575 Visited.insert(Ptr);
1576 SmallVector<Value *, 4> Indices;
1577
1578 // We may end up computing an offset pointer that has the wrong type. If we
1579 // never are able to compute one directly that has the correct type, we'll
Chandler Carruth5986b542015-01-02 02:47:38 +00001580 // fall back to it, so keep it and the base it was computed from around here.
Craig Topperf40110f2014-04-25 05:29:35 +00001581 Value *OffsetPtr = nullptr;
Chandler Carruth5986b542015-01-02 02:47:38 +00001582 Value *OffsetBasePtr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001583
1584 // Remember any i8 pointer we come across to re-use if we need to do a raw
1585 // byte offset.
Craig Topperf40110f2014-04-25 05:29:35 +00001586 Value *Int8Ptr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001587 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1588
Matt Arsenault282dac72019-06-14 21:38:31 +00001589 PointerType *TargetPtrTy = cast<PointerType>(PointerTy);
1590 Type *TargetTy = TargetPtrTy->getElementType();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001591
Michael Liao4f7f70e2019-06-18 21:41:13 +00001592 // As `addrspacecast` is , `Ptr` (the storage pointer) may have different
1593 // address space from the expected `PointerTy` (the pointer to be used).
1594 // Adjust the pointer type based the original storage pointer.
1595 auto AS = cast<PointerType>(Ptr->getType())->getAddressSpace();
1596 PointerTy = TargetTy->getPointerTo(AS);
1597
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001598 do {
1599 // First fold any existing GEPs into the offset.
1600 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1601 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001602 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001603 break;
1604 Offset += GEPOffset;
1605 Ptr = GEP->getPointerOperand();
David Blaikie70573dc2014-11-19 07:49:26 +00001606 if (!Visited.insert(Ptr).second)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001607 break;
1608 }
1609
1610 // See if we can perform a natural GEP here.
1611 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001612 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001613 Indices, NamePrefix)) {
Chandler Carruth5986b542015-01-02 02:47:38 +00001614 // If we have a new natural pointer at the offset, clear out any old
1615 // offset pointer we computed. Unless it is the base pointer or
1616 // a non-instruction, we built a GEP we don't need. Zap it.
1617 if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1618 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1619 assert(I->use_empty() && "Built a GEP with uses some how!");
1620 I->eraseFromParent();
1621 }
1622 OffsetPtr = P;
1623 OffsetBasePtr = Ptr;
1624 // If we also found a pointer of the right type, we're done.
1625 if (P->getType() == PointerTy)
Michael Liao4f7f70e2019-06-18 21:41:13 +00001626 break;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001627 }
1628
1629 // Stash this pointer if we've found an i8*.
1630 if (Ptr->getType()->isIntegerTy(8)) {
1631 Int8Ptr = Ptr;
1632 Int8PtrOffset = Offset;
1633 }
1634
1635 // Peel off a layer of the pointer and update the offset appropriately.
1636 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1637 Ptr = cast<Operator>(Ptr)->getOperand(0);
1638 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001639 if (GA->isInterposable())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001640 break;
1641 Ptr = GA->getAliasee();
1642 } else {
1643 break;
1644 }
1645 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +00001646 } while (Visited.insert(Ptr).second);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001647
1648 if (!OffsetPtr) {
1649 if (!Int8Ptr) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00001650 Int8Ptr = IRB.CreateBitCast(
1651 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1652 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001653 Int8PtrOffset = Offset;
1654 }
1655
Chandler Carruth113dc642014-12-20 02:39:18 +00001656 OffsetPtr = Int8PtrOffset == 0
1657 ? Int8Ptr
David Blaikieaa41cd52015-04-03 21:33:42 +00001658 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1659 IRB.getInt(Int8PtrOffset),
Chandler Carruth113dc642014-12-20 02:39:18 +00001660 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001661 }
1662 Ptr = OffsetPtr;
1663
1664 // On the off chance we were targeting i8*, guard the bitcast here.
Matt Arsenault282dac72019-06-14 21:38:31 +00001665 if (cast<PointerType>(Ptr->getType()) != TargetPtrTy) {
1666 Ptr = IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr,
1667 TargetPtrTy,
1668 NamePrefix + "sroa_cast");
1669 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001670
1671 return Ptr;
1672}
1673
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001674/// Compute the adjusted alignment for a load or store from an offset.
Chandler Carruth0715cba2015-01-01 11:54:38 +00001675static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
1676 const DataLayout &DL) {
1677 unsigned Alignment;
1678 Type *Ty;
1679 if (auto *LI = dyn_cast<LoadInst>(I)) {
1680 Alignment = LI->getAlignment();
1681 Ty = LI->getType();
1682 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
1683 Alignment = SI->getAlignment();
1684 Ty = SI->getValueOperand()->getType();
1685 } else {
1686 llvm_unreachable("Only loads and stores are allowed!");
1687 }
1688
1689 if (!Alignment)
1690 Alignment = DL.getABITypeAlignment(Ty);
1691
1692 return MinAlign(Alignment, Offset);
1693}
1694
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001695/// Test whether we can convert a value from the old to the new type.
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001696///
1697/// This predicate should be used to guard calls to convertValue in order to
1698/// ensure that we only try to convert viable values. The strategy is that we
1699/// will peel off single element struct and array wrappings to get to an
1700/// underlying value, and convert that value.
1701static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1702 if (OldTy == NewTy)
1703 return true;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001704
1705 // For integer types, we can't handle any bit-width differences. This would
1706 // break both vector conversions with extension and introduce endianness
1707 // issues when in conjunction with loads and stores.
1708 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1709 assert(cast<IntegerType>(OldTy)->getBitWidth() !=
1710 cast<IntegerType>(NewTy)->getBitWidth() &&
1711 "We can't have the same bitwidth for different int types");
1712 return false;
1713 }
1714
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001715 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1716 return false;
1717 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1718 return false;
1719
Benjamin Kramer56262592013-09-22 11:24:58 +00001720 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001721 // of pointers and integers.
1722 OldTy = OldTy->getScalarType();
1723 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001724 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
Jack Liuf101c0f2016-05-03 19:30:48 +00001725 if (NewTy->isPointerTy() && OldTy->isPointerTy()) {
1726 return cast<PointerType>(NewTy)->getPointerAddressSpace() ==
1727 cast<PointerType>(OldTy)->getPointerAddressSpace();
1728 }
Sanjoy Dasb70ddd82017-06-17 20:28:13 +00001729
1730 // We can convert integers to integral pointers, but not to non-integral
1731 // pointers.
1732 if (OldTy->isIntegerTy())
1733 return !DL.isNonIntegralPointerType(NewTy);
1734
1735 // We can convert integral pointers to integers, but non-integral pointers
1736 // need to remain pointers.
1737 if (!DL.isNonIntegralPointerType(OldTy))
1738 return NewTy->isIntegerTy();
1739
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001740 return false;
1741 }
1742
1743 return true;
1744}
1745
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001746/// Generic routine to convert an SSA value to a value of a different
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001747/// type.
1748///
1749/// This will try various different casting techniques, such as bitcasts,
1750/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1751/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001752static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001753 Type *NewTy) {
1754 Type *OldTy = V->getType();
1755 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1756
1757 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001758 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001759
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001760 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
1761 "Integer types must be the exact same to convert.");
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001762
Benjamin Kramer90901a32013-09-21 20:36:04 +00001763 // See if we need inttoptr for this type pair. A cast involving both scalars
1764 // and vectors requires and additional bitcast.
Craig Topper95d23472017-07-09 07:04:00 +00001765 if (OldTy->isIntOrIntVectorTy() && NewTy->isPtrOrPtrVectorTy()) {
Benjamin Kramer90901a32013-09-21 20:36:04 +00001766 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1767 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1768 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1769 NewTy);
1770
1771 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1772 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1773 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1774 NewTy);
1775
1776 return IRB.CreateIntToPtr(V, NewTy);
1777 }
1778
1779 // See if we need ptrtoint for this type pair. A cast involving both scalars
1780 // and vectors requires and additional bitcast.
Craig Topper95d23472017-07-09 07:04:00 +00001781 if (OldTy->isPtrOrPtrVectorTy() && NewTy->isIntOrIntVectorTy()) {
Benjamin Kramer90901a32013-09-21 20:36:04 +00001782 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1783 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1784 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1785 NewTy);
1786
1787 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1788 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1789 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1790 NewTy);
1791
1792 return IRB.CreatePtrToInt(V, NewTy);
1793 }
1794
1795 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001796}
1797
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001798/// Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001799///
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001800/// This function is called to test each entry in a partition which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001801/// for a single slice.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001802static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
1803 VectorType *Ty,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001804 uint64_t ElementSize,
1805 const DataLayout &DL) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001806 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001807 uint64_t BeginOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001808 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001809 uint64_t BeginIndex = BeginOffset / ElementSize;
1810 if (BeginIndex * ElementSize != BeginOffset ||
1811 BeginIndex >= Ty->getNumElements())
1812 return false;
1813 uint64_t EndOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001814 std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001815 uint64_t EndIndex = EndOffset / ElementSize;
1816 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1817 return false;
1818
1819 assert(EndIndex > BeginIndex && "Empty vector!");
1820 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruthc659df92014-10-16 20:24:07 +00001821 Type *SliceTy = (NumElements == 1)
1822 ? Ty->getElementType()
1823 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruthf0546402013-07-18 07:15:00 +00001824
1825 Type *SplitIntTy =
1826 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1827
Chandler Carruthc659df92014-10-16 20:24:07 +00001828 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001829
1830 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1831 if (MI->isVolatile())
1832 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001833 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001834 return false; // Skip any unsplittable intrinsics.
Owen Anderson6c19ab12014-08-07 21:07:35 +00001835 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
Vedant Kumarb264d692018-12-21 21:49:40 +00001836 if (!II->isLifetimeStartOrEnd())
Owen Anderson6c19ab12014-08-07 21:07:35 +00001837 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001838 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1839 // Disable vector promotion when there are loads or stores of an FCA.
1840 return false;
1841 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1842 if (LI->isVolatile())
1843 return false;
1844 Type *LTy = LI->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001845 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001846 assert(LTy->isIntegerTy());
1847 LTy = SplitIntTy;
1848 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001849 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001850 return false;
1851 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1852 if (SI->isVolatile())
1853 return false;
1854 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001855 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001856 assert(STy->isIntegerTy());
1857 STy = SplitIntTy;
1858 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001859 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001860 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001861 } else {
1862 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001863 }
1864
1865 return true;
1866}
1867
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001868/// Test whether the given alloca partitioning and range of slices can be
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001869/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001870///
1871/// This is a quick test to check whether we can rewrite a particular alloca
1872/// partition (and its newly formed alloca) into a vector alloca with only
1873/// whole-vector loads and stores such that it could be promoted to a vector
1874/// SSA value. We only can ensure this for a limited set of operations, and we
1875/// don't want to do the rewrites unless we are confident that the result will
1876/// be promotable, so we have an early test here.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001877static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001878 // Collect the candidate types for vector-based promotion. Also track whether
1879 // we have different element types.
1880 SmallVector<VectorType *, 4> CandidateTys;
1881 Type *CommonEltTy = nullptr;
1882 bool HaveCommonEltTy = true;
1883 auto CheckCandidateType = [&](Type *Ty) {
1884 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1885 CandidateTys.push_back(VTy);
1886 if (!CommonEltTy)
1887 CommonEltTy = VTy->getElementType();
1888 else if (CommonEltTy != VTy->getElementType())
1889 HaveCommonEltTy = false;
1890 }
1891 };
Chandler Carruth2dc96822014-10-18 00:44:02 +00001892 // Consider any loads or stores that are the exact size of the slice.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001893 for (const Slice &S : P)
1894 if (S.beginOffset() == P.beginOffset() &&
1895 S.endOffset() == P.endOffset()) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001896 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1897 CheckCandidateType(LI->getType());
1898 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1899 CheckCandidateType(SI->getValueOperand()->getType());
1900 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001901
Chandler Carruth2dc96822014-10-18 00:44:02 +00001902 // If we didn't find a vector type, nothing to do here.
1903 if (CandidateTys.empty())
1904 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001905
Chandler Carruth2dc96822014-10-18 00:44:02 +00001906 // Remove non-integer vector types if we had multiple common element types.
1907 // FIXME: It'd be nice to replace them with integer vector types, but we can't
1908 // do that until all the backends are known to produce good code for all
1909 // integer vector types.
1910 if (!HaveCommonEltTy) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001911 CandidateTys.erase(
1912 llvm::remove_if(CandidateTys,
1913 [](VectorType *VTy) {
1914 return !VTy->getElementType()->isIntegerTy();
1915 }),
1916 CandidateTys.end());
Chandler Carruth2dc96822014-10-18 00:44:02 +00001917
1918 // If there were no integer vector types, give up.
1919 if (CandidateTys.empty())
1920 return nullptr;
1921
1922 // Rank the remaining candidate vector types. This is easy because we know
1923 // they're all integer vectors. We sort by ascending number of elements.
1924 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
David L. Jones41cecba2017-01-13 21:02:41 +00001925 (void)DL;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001926 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
1927 "Cannot have vector types of different sizes!");
1928 assert(RHSTy->getElementType()->isIntegerTy() &&
1929 "All non-integer types eliminated!");
1930 assert(LHSTy->getElementType()->isIntegerTy() &&
1931 "All non-integer types eliminated!");
1932 return RHSTy->getNumElements() < LHSTy->getNumElements();
1933 };
Fangrui Song0cac7262018-09-27 02:13:45 +00001934 llvm::sort(CandidateTys, RankVectorTypes);
Chandler Carruth2dc96822014-10-18 00:44:02 +00001935 CandidateTys.erase(
1936 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1937 CandidateTys.end());
1938 } else {
1939// The only way to have the same element type in every vector type is to
1940// have the same vector type. Check that and remove all but one.
1941#ifndef NDEBUG
1942 for (VectorType *VTy : CandidateTys) {
1943 assert(VTy->getElementType() == CommonEltTy &&
1944 "Unaccounted for element type!");
1945 assert(VTy == CandidateTys[0] &&
1946 "Different vector types with the same element type!");
1947 }
1948#endif
1949 CandidateTys.resize(1);
1950 }
1951
1952 // Try each vector type, and return the one which works.
1953 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1954 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
1955
1956 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1957 // that aren't byte sized.
1958 if (ElementSize % 8)
1959 return false;
1960 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
1961 "vector size not a multiple of element size?");
1962 ElementSize /= 8;
1963
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001964 for (const Slice &S : P)
1965 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001966 return false;
1967
Chandler Carruthffb7ce52014-12-24 01:48:09 +00001968 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001969 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001970 return false;
1971
1972 return true;
1973 };
1974 for (VectorType *VTy : CandidateTys)
1975 if (CheckVectorTypeForPromotion(VTy))
1976 return VTy;
1977
1978 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001979}
1980
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001981/// Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001982///
1983/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001984/// test below on a single slice of the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001985static bool isIntegerWideningViableForSlice(const Slice &S,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001986 uint64_t AllocBeginOffset,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001987 Type *AllocaTy,
1988 const DataLayout &DL,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001989 bool &WholeAllocaOp) {
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001990 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1991
Chandler Carruthc659df92014-10-16 20:24:07 +00001992 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1993 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001994
1995 // We can't reasonably handle cases where the load or store extends past
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001996 // the end of the alloca's type and into its padding.
Chandler Carruthf0546402013-07-18 07:15:00 +00001997 if (RelEnd > Size)
1998 return false;
1999
Chandler Carruthc659df92014-10-16 20:24:07 +00002000 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00002001
2002 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2003 if (LI->isVolatile())
2004 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002005 // We can't handle loads that extend past the allocated memory.
2006 if (DL.getTypeStoreSize(LI->getType()) > Size)
2007 return false;
Hiroshi Inouef5c0e6c2018-05-17 06:32:17 +00002008 // So far, AllocaSliceRewriter does not support widening split slice tails
2009 // in rewriteIntegerLoad.
2010 if (S.beginOffset() < AllocBeginOffset)
2011 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00002012 // Note that we don't count vector loads or stores as whole-alloca
2013 // operations which enable integer widening because we would prefer to use
2014 // vector widening instead.
2015 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00002016 WholeAllocaOp = true;
2017 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002018 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00002019 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002020 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002021 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002022 // Non-integer loads need to be convertible from the alloca type so that
2023 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002024 return false;
2025 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002026 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2027 Type *ValueTy = SI->getValueOperand()->getType();
2028 if (SI->isVolatile())
2029 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002030 // We can't handle stores that extend past the allocated memory.
2031 if (DL.getTypeStoreSize(ValueTy) > Size)
2032 return false;
Hiroshi Inouef5c0e6c2018-05-17 06:32:17 +00002033 // So far, AllocaSliceRewriter does not support widening split slice tails
2034 // in rewriteIntegerStore.
2035 if (S.beginOffset() < AllocBeginOffset)
2036 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00002037 // Note that we don't count vector loads or stores as whole-alloca
2038 // operations which enable integer widening because we would prefer to use
2039 // vector widening instead.
2040 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00002041 WholeAllocaOp = true;
2042 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002043 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00002044 return false;
2045 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002046 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002047 // Non-integer stores need to be convertible to the alloca type so that
2048 // they are promotable.
2049 return false;
2050 }
2051 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2052 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2053 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00002054 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00002055 return false; // Skip any unsplittable intrinsics.
2056 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
Vedant Kumarb264d692018-12-21 21:49:40 +00002057 if (!II->isLifetimeStartOrEnd())
Chandler Carruthf0546402013-07-18 07:15:00 +00002058 return false;
2059 } else {
2060 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002061 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002062
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002063 return true;
2064}
2065
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002066/// Test whether the given alloca partition's integer operations can be
Chandler Carruth435c4e02012-10-15 08:40:30 +00002067/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002068///
Chandler Carruth435c4e02012-10-15 08:40:30 +00002069/// This is a quick test to check whether we can rewrite the integer loads and
2070/// stores to a particular alloca into wider loads and stores and be able to
2071/// promote the resulting alloca.
Chandler Carruth29a18a42015-09-12 09:09:14 +00002072static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002073 const DataLayout &DL) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002074 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00002075 // Don't create integer types larger than the maximum bitwidth.
2076 if (SizeInBits > IntegerType::MAX_INT_BITS)
2077 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002078
2079 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002080 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002081 return false;
2082
Chandler Carruth58d05562012-10-25 04:37:07 +00002083 // We need to ensure that an integer type with the appropriate bitwidth can
2084 // be converted to the alloca type, whatever that is. We don't want to force
2085 // the alloca itself to have an integer type if there is a more suitable one.
2086 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002087 if (!canConvertValue(DL, AllocaTy, IntTy) ||
2088 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00002089 return false;
2090
Chandler Carruthf0546402013-07-18 07:15:00 +00002091 // While examining uses, we ensure that the alloca has a covering load or
2092 // store. We don't want to widen the integer operations only to fail to
2093 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00002094 // later). However, if there are only splittable uses, go ahead and assume
2095 // that we cover the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002096 // FIXME: We shouldn't consider split slices that happen to start in the
2097 // partition here...
Chandler Carruthc659df92014-10-16 20:24:07 +00002098 bool WholeAllocaOp =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002099 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00002100
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002101 for (const Slice &S : P)
2102 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2103 WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00002104 return false;
2105
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002106 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002107 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2108 WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002109 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002110
Chandler Carruth92924fd2012-09-24 00:34:20 +00002111 return WholeAllocaOp;
2112}
2113
Chandler Carruthd177f862013-03-20 07:30:36 +00002114static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002115 IntegerType *Ty, uint64_t Offset,
2116 const Twine &Name) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002117 LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002118 IntegerType *IntTy = cast<IntegerType>(V->getType());
2119 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2120 "Element extends past full value");
Chandler Carruth113dc642014-12-20 02:39:18 +00002121 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002122 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002123 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002124 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002125 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002126 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002127 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002128 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2129 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002130 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002131 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002132 LLVM_DEBUG(dbgs() << " trunced: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002133 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002134 return V;
2135}
2136
Chandler Carruthd177f862013-03-20 07:30:36 +00002137static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002138 Value *V, uint64_t Offset, const Twine &Name) {
2139 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2140 IntegerType *Ty = cast<IntegerType>(V->getType());
2141 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2142 "Cannot insert a larger integer!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002143 LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002144 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002145 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002146 LLVM_DEBUG(dbgs() << " extended: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002147 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002148 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2149 "Element store outside of alloca store");
Chandler Carruth113dc642014-12-20 02:39:18 +00002150 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002151 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002152 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002153 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002154 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002155 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002156 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002157
2158 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2159 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2160 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002161 LLVM_DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002162 V = IRB.CreateOr(Old, V, Name + ".insert");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002163 LLVM_DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002164 }
2165 return V;
2166}
2167
Chandler Carruth113dc642014-12-20 02:39:18 +00002168static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2169 unsigned EndIndex, const Twine &Name) {
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002170 VectorType *VecTy = cast<VectorType>(V->getType());
2171 unsigned NumElements = EndIndex - BeginIndex;
2172 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2173
2174 if (NumElements == VecTy->getNumElements())
2175 return V;
2176
2177 if (NumElements == 1) {
2178 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2179 Name + ".extract");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002180 LLVM_DEBUG(dbgs() << " extract: " << *V << "\n");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002181 return V;
2182 }
2183
Chandler Carruth113dc642014-12-20 02:39:18 +00002184 SmallVector<Constant *, 8> Mask;
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002185 Mask.reserve(NumElements);
2186 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2187 Mask.push_back(IRB.getInt32(i));
2188 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002189 ConstantVector::get(Mask), Name + ".extract");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002190 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002191 return V;
2192}
2193
Chandler Carruthd177f862013-03-20 07:30:36 +00002194static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00002195 unsigned BeginIndex, const Twine &Name) {
2196 VectorType *VecTy = cast<VectorType>(Old->getType());
2197 assert(VecTy && "Can only insert a vector into a vector");
2198
2199 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2200 if (!Ty) {
2201 // Single element to insert.
2202 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2203 Name + ".insert");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002204 LLVM_DEBUG(dbgs() << " insert: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002205 return V;
2206 }
2207
2208 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2209 "Too many elements!");
2210 if (Ty->getNumElements() == VecTy->getNumElements()) {
2211 assert(V->getType() == VecTy && "Vector type mismatch");
2212 return V;
2213 }
2214 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2215
2216 // When inserting a smaller vector into the larger to store, we first
2217 // use a shuffle vector to widen it with undef elements, and then
2218 // a second shuffle vector to select between the loaded vector and the
2219 // incoming vector.
Chandler Carruth113dc642014-12-20 02:39:18 +00002220 SmallVector<Constant *, 8> Mask;
Chandler Carruthce4562b2012-12-17 13:41:21 +00002221 Mask.reserve(VecTy->getNumElements());
2222 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2223 if (i >= BeginIndex && i < EndIndex)
2224 Mask.push_back(IRB.getInt32(i - BeginIndex));
2225 else
2226 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2227 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002228 ConstantVector::get(Mask), Name + ".expand");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002229 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002230
2231 Mask.clear();
2232 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00002233 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2234
2235 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2236
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002237 LLVM_DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002238 return V;
2239}
2240
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002241/// Visitor to rewrite instructions using p particular slice of an alloca
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002242/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002243///
2244/// Also implements the rewriting to vector-based accesses when the partition
2245/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2246/// lives here.
Chandler Carruth29a18a42015-09-12 09:09:14 +00002247class llvm::sroa::AllocaSliceRewriter
2248 : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002249 // Befriend the base class so it can delegate to private visit methods.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002250 friend class InstVisitor<AllocaSliceRewriter, bool>;
2251
2252 using Base = InstVisitor<AllocaSliceRewriter, bool>;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002253
Chandler Carruth90a735d2013-07-19 07:21:28 +00002254 const DataLayout &DL;
Chandler Carruth83934062014-10-16 21:11:55 +00002255 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002256 SROA &Pass;
2257 AllocaInst &OldAI, &NewAI;
2258 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002259 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002260
Chandler Carruth2dc96822014-10-18 00:44:02 +00002261 // This is a convenience and flag variable that will be null unless the new
2262 // alloca's integer operations should be widened to this integer type due to
2263 // passing isIntegerWideningViable above. If it is non-null, the desired
2264 // integer type will be stored here for easy access during rewriting.
2265 IntegerType *IntTy;
2266
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002267 // If we are rewriting an alloca partition which can be written as pure
2268 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002269 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002270 // - The new alloca is exactly the size of the vector type here.
2271 // - The accesses all either map to the entire vector or to a single
2272 // element.
2273 // - The set of accessing instructions is only one of those handled above
2274 // in isVectorPromotionViable. Generally these are the same access kinds
2275 // which are promotable via mem2reg.
2276 VectorType *VecTy;
2277 Type *ElementTy;
2278 uint64_t ElementSize;
2279
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002280 // The original offset of the slice currently being rewritten relative to
2281 // the original alloca.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002282 uint64_t BeginOffset = 0;
2283 uint64_t EndOffset = 0;
2284
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002285 // The new offsets of the slice currently being rewritten relative to the
2286 // original alloca.
2287 uint64_t NewBeginOffset, NewEndOffset;
2288
2289 uint64_t SliceSize;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002290 bool IsSplittable = false;
2291 bool IsSplit = false;
2292 Use *OldUse = nullptr;
2293 Instruction *OldPtr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002294
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002295 // Track post-rewrite users which are PHI nodes and Selects.
Davide Italiano81a26da2017-04-27 23:09:01 +00002296 SmallSetVector<PHINode *, 8> &PHIUsers;
2297 SmallSetVector<SelectInst *, 8> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002298
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002299 // Utility IR builder, whose name prefix is setup for each visited use, and
2300 // the insertion point is set to point to the user.
2301 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002302
2303public:
Chandler Carruth83934062014-10-16 21:11:55 +00002304 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002305 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002306 uint64_t NewAllocaBeginOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00002307 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2308 VectorType *PromotableVecTy,
Davide Italiano81a26da2017-04-27 23:09:01 +00002309 SmallSetVector<PHINode *, 8> &PHIUsers,
2310 SmallSetVector<SelectInst *, 8> &SelectUsers)
Chandler Carruth83934062014-10-16 21:11:55 +00002311 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002312 NewAllocaBeginOffset(NewAllocaBeginOffset),
2313 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002314 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002315 IntTy(IsIntegerPromotable
2316 ? Type::getIntNTy(
2317 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002318 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Craig Topperf40110f2014-04-25 05:29:35 +00002319 : nullptr),
Chandler Carruth2dc96822014-10-18 00:44:02 +00002320 VecTy(PromotableVecTy),
2321 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2322 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002323 PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002324 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002325 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002326 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002327 "Only multiple-of-8 sized vector elements are viable");
2328 ++NumVectorized;
2329 }
Chandler Carruth2dc96822014-10-18 00:44:02 +00002330 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002331 }
2332
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002333 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002334 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002335 BeginOffset = I->beginOffset();
2336 EndOffset = I->endOffset();
2337 IsSplittable = I->isSplittable();
2338 IsSplit =
2339 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002340 LLVM_DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2341 LLVM_DEBUG(AS.printSlice(dbgs(), I, ""));
2342 LLVM_DEBUG(dbgs() << "\n");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002343
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002344 // Compute the intersecting offset range.
2345 assert(BeginOffset < NewAllocaEndOffset);
2346 assert(EndOffset > NewAllocaBeginOffset);
2347 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2348 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2349
2350 SliceSize = NewEndOffset - NewBeginOffset;
2351
Chandler Carruthf0546402013-07-18 07:15:00 +00002352 OldUse = I->getUse();
2353 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002354
Chandler Carruthf0546402013-07-18 07:15:00 +00002355 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2356 IRB.SetInsertPoint(OldUserI);
2357 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2358 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2359
2360 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2361 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002362 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002363 return CanSROA;
2364 }
2365
2366private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002367 // Make sure the other visit overloads are visible.
2368 using Base::visit;
2369
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002370 // Every instruction which can end up as a user must have a rewrite rule.
2371 bool visitInstruction(Instruction &I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002372 LLVM_DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002373 llvm_unreachable("No rewrite rule for this instruction!");
2374 }
2375
Chandler Carruth47954c82014-02-26 05:12:43 +00002376 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2377 // Note that the offset computation can use BeginOffset or NewBeginOffset
2378 // interchangeably for unsplit slices.
2379 assert(IsSplit || BeginOffset == NewBeginOffset);
2380 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2381
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002382#ifndef NDEBUG
2383 StringRef OldName = OldPtr->getName();
2384 // Skip through the last '.sroa.' component of the name.
2385 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2386 if (LastSROAPrefix != StringRef::npos) {
2387 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2388 // Look for an SROA slice index.
2389 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2390 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2391 // Strip the index and look for the offset.
2392 OldName = OldName.substr(IndexEnd + 1);
2393 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2394 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2395 // Strip the offset.
2396 OldName = OldName.substr(OffsetEnd + 1);
2397 }
2398 }
2399 // Strip any SROA suffixes as well.
2400 OldName = OldName.substr(0, OldName.find(".sroa_"));
2401#endif
Chandler Carruth47954c82014-02-26 05:12:43 +00002402
2403 return getAdjustedPtr(IRB, DL, &NewAI,
Nicola Zaghenf96383c2018-10-30 11:15:04 +00002404 APInt(DL.getIndexTypeSizeInBits(PointerTy), Offset),
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002405 PointerTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002406#ifndef NDEBUG
2407 Twine(OldName) + "."
2408#else
2409 Twine()
2410#endif
2411 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002412 }
2413
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002414 /// Compute suitable alignment to access this slice of the *new*
Chandler Carruth113dc642014-12-20 02:39:18 +00002415 /// alloca.
Chandler Carruth2659e502014-02-26 05:02:19 +00002416 ///
2417 /// You can optionally pass a type to this routine and if that type's ABI
2418 /// alignment is itself suitable, this will return zero.
Craig Topperf40110f2014-04-25 05:29:35 +00002419 unsigned getSliceAlign(Type *Ty = nullptr) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002420 unsigned NewAIAlign = NewAI.getAlignment();
2421 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002422 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth113dc642014-12-20 02:39:18 +00002423 unsigned Align =
2424 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
Chandler Carruth2659e502014-02-26 05:02:19 +00002425 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002426 }
2427
Chandler Carruth845b73c2012-11-21 08:16:30 +00002428 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002429 assert(VecTy && "Can only call getIndex when rewriting a vector");
2430 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2431 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2432 uint32_t Index = RelOffset / ElementSize;
2433 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002434 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002435 }
2436
2437 void deleteIfTriviallyDead(Value *V) {
2438 Instruction *I = cast<Instruction>(V);
2439 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002440 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002441 }
2442
Chandler Carruthea27cf02014-02-26 04:25:04 +00002443 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002444 unsigned BeginIndex = getIndex(NewBeginOffset);
2445 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002446 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002447
James Y Knight14359ef2019-02-01 20:44:24 +00002448 Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2449 NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002450 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002451 }
2452
Chandler Carruthea27cf02014-02-26 04:25:04 +00002453 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002454 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002455 assert(!LI.isVolatile());
James Y Knight14359ef2019-02-01 20:44:24 +00002456 Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2457 NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002458 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002459 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2460 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth4b682f62015-08-28 09:03:52 +00002461 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
2462 IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
2463 V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
2464 }
2465 // It is possible that the extracted type is not the load type. This
2466 // happens if there is a load past the end of the alloca, and as
2467 // a consequence the slice is narrower but still a candidate for integer
2468 // lowering. To handle this case, we just zero extend the extracted
2469 // integer.
2470 assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&
2471 "Can only handle an extract for an overly wide load");
2472 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
2473 V = IRB.CreateZExt(V, LI.getType());
Chandler Carruth18db7952012-11-20 01:12:50 +00002474 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002475 }
2476
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002477 bool visitLoadInst(LoadInst &LI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002478 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002479 Value *OldOp = LI.getOperand(0);
2480 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002481
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002482 AAMDNodes AATags;
2483 LI.getAAMetadata(AATags);
2484
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002485 unsigned AS = LI.getPointerAddressSpace();
2486
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002487 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002488 : LI.getType();
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002489 const bool IsLoadPastEnd = DL.getTypeStoreSize(TargetTy) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002490 bool IsPtrAdjusted = false;
2491 Value *V;
2492 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002493 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002494 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002495 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002496 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002497 NewEndOffset == NewAllocaEndOffset &&
2498 (canConvertValue(DL, NewAllocaTy, TargetTy) ||
2499 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
2500 TargetTy->isIntegerTy()))) {
James Y Knight14359ef2019-02-01 20:44:24 +00002501 LoadInst *NewLI = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2502 NewAI.getAlignment(),
David Majnemer62690b12015-07-14 06:19:58 +00002503 LI.isVolatile(), LI.getName());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002504 if (AATags)
2505 NewLI->setAAMetadata(AATags);
David Majnemer62690b12015-07-14 06:19:58 +00002506 if (LI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002507 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
Luqman Aden3f807c92017-03-22 19:16:39 +00002508
Chandler Carruth3f81d802017-06-27 08:32:03 +00002509 // Any !nonnull metadata or !range metadata on the old load is also valid
2510 // on the new load. This is even true in some cases even when the loads
2511 // are different types, for example by mapping !nonnull metadata to
2512 // !range metadata by modeling the null pointer constant converted to the
2513 // integer type.
Rafael Espindolac06f55e2017-11-28 01:25:38 +00002514 // FIXME: Add support for range metadata here. Currently the utilities
2515 // for this don't propagate range metadata in trivial cases from one
2516 // integer load to another, don't handle non-addrspace-0 null pointers
2517 // correctly, and don't have any support for mapping ranges as the
2518 // integer type becomes winder or narrower.
Chandler Carruth3f81d802017-06-27 08:32:03 +00002519 if (MDNode *N = LI.getMetadata(LLVMContext::MD_nonnull))
2520 copyNonnullMetadata(LI, N, *NewLI);
Rafael Espindolac06f55e2017-11-28 01:25:38 +00002521
2522 // Try to preserve nonnull metadata
David Majnemer62690b12015-07-14 06:19:58 +00002523 V = NewLI;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002524
2525 // If this is an integer load past the end of the slice (which means the
2526 // bytes outside the slice are undef or this load is dead) just forcibly
2527 // fix the integer size with correct handling of endianness.
2528 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2529 if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
2530 if (AITy->getBitWidth() < TITy->getBitWidth()) {
2531 V = IRB.CreateZExt(V, TITy, "load.ext");
2532 if (DL.isBigEndian())
2533 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2534 "endian_shift");
2535 }
Chandler Carruth18db7952012-11-20 01:12:50 +00002536 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002537 Type *LTy = TargetTy->getPointerTo(AS);
James Y Knight14359ef2019-02-01 20:44:24 +00002538 LoadInst *NewLI = IRB.CreateAlignedLoad(
2539 TargetTy, getNewAllocaSlicePtr(IRB, LTy), getSliceAlign(TargetTy),
2540 LI.isVolatile(), LI.getName());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002541 if (AATags)
2542 NewLI->setAAMetadata(AATags);
David Majnemer62690b12015-07-14 06:19:58 +00002543 if (LI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002544 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
David Majnemer62690b12015-07-14 06:19:58 +00002545
2546 V = NewLI;
Chandler Carruth18db7952012-11-20 01:12:50 +00002547 IsPtrAdjusted = true;
2548 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002549 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002550
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002551 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002552 assert(!LI.isVolatile());
2553 assert(LI.getType()->isIntegerTy() &&
2554 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002555 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002556 "Split load isn't smaller than original load");
Bjorn Petterssonb4771422019-05-24 09:20:20 +00002557 assert(DL.typeSizeEqualsStoreSize(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002558 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002559 // 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 +00002560 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002561 // Create a placeholder value with the same type as LI to use as the
2562 // basis for the new value. This allows us to replace the uses of LI with
2563 // the computed value, and then replace the placeholder with LI, leaving
2564 // LI only used for this computation.
James Y Knight14359ef2019-02-01 20:44:24 +00002565 Value *Placeholder = new LoadInst(
2566 LI.getType(), UndefValue::get(LI.getType()->getPointerTo(AS)));
Chandler Carruth24ac8302015-01-02 03:55:54 +00002567 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2568 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002569 LI.replaceAllUsesWith(V);
2570 Placeholder->replaceAllUsesWith(&LI);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002571 Placeholder->deleteValue();
Chandler Carruth18db7952012-11-20 01:12:50 +00002572 } else {
2573 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002574 }
2575
Chandler Carruth18db7952012-11-20 01:12:50 +00002576 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002577 deleteIfTriviallyDead(OldOp);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002578 LLVM_DEBUG(dbgs() << " to: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002579 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002580 }
2581
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002582 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2583 AAMDNodes AATags) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002584 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002585 unsigned BeginIndex = getIndex(NewBeginOffset);
2586 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002587 assert(EndIndex > BeginIndex && "Empty vector!");
2588 unsigned NumElements = EndIndex - BeginIndex;
2589 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth113dc642014-12-20 02:39:18 +00002590 Type *SliceTy = (NumElements == 1)
2591 ? ElementTy
2592 : VectorType::get(ElementTy, NumElements);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002593 if (V->getType() != SliceTy)
2594 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002595
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002596 // Mix in the existing elements.
James Y Knight14359ef2019-02-01 20:44:24 +00002597 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2598 NewAI.getAlignment(), "load");
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002599 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2600 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002601 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002602 if (AATags)
2603 Store->setAAMetadata(AATags);
Chandler Carruth18db7952012-11-20 01:12:50 +00002604 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002605
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002606 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002607 return true;
2608 }
2609
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002610 bool rewriteIntegerStore(Value *V, StoreInst &SI, AAMDNodes AATags) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002611 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002612 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002613 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
James Y Knight14359ef2019-02-01 20:44:24 +00002614 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2615 NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002616 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002617 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2618 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth113dc642014-12-20 02:39:18 +00002619 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002620 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002621 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002622 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Michael Kruse978ba612018-12-20 04:58:07 +00002623 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2624 LLVMContext::MD_access_group});
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002625 if (AATags)
2626 Store->setAAMetadata(AATags);
Chandler Carruth18db7952012-11-20 01:12:50 +00002627 Pass.DeadInsts.insert(&SI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002628 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002629 return true;
2630 }
2631
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002632 bool visitStoreInst(StoreInst &SI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002633 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002634 Value *OldOp = SI.getOperand(1);
2635 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002636
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002637 AAMDNodes AATags;
2638 SI.getAAMetadata(AATags);
2639
Chandler Carruth18db7952012-11-20 01:12:50 +00002640 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002641
Chandler Carruthac8317f2012-10-04 12:33:50 +00002642 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2643 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002644 if (V->getType()->isPointerTy())
2645 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002646 Pass.PostPromotionWorklist.insert(AI);
2647
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002648 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002649 assert(!SI.isVolatile());
2650 assert(V->getType()->isIntegerTy() &&
2651 "Only integer type loads and stores are split");
Bjorn Petterssonb4771422019-05-24 09:20:20 +00002652 assert(DL.typeSizeEqualsStoreSize(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002653 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002654 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth24ac8302015-01-02 03:55:54 +00002655 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2656 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002657 }
2658
Chandler Carruth18db7952012-11-20 01:12:50 +00002659 if (VecTy)
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002660 return rewriteVectorizedStoreInst(V, SI, OldOp, AATags);
Chandler Carruth18db7952012-11-20 01:12:50 +00002661 if (IntTy && V->getType()->isIntegerTy())
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002662 return rewriteIntegerStore(V, SI, AATags);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002663
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002664 const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002665 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002666 if (NewBeginOffset == NewAllocaBeginOffset &&
2667 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002668 (canConvertValue(DL, V->getType(), NewAllocaTy) ||
2669 (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
2670 V->getType()->isIntegerTy()))) {
2671 // If this is an integer store past the end of slice (and thus the bytes
2672 // past that point are irrelevant or this is unreachable), truncate the
2673 // value prior to storing.
2674 if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
2675 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2676 if (VITy->getBitWidth() > AITy->getBitWidth()) {
2677 if (DL.isBigEndian())
2678 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2679 "endian_shift");
2680 V = IRB.CreateTrunc(V, AITy, "load.trunc");
2681 }
2682
Chandler Carruth90a735d2013-07-19 07:21:28 +00002683 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002684 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2685 SI.isVolatile());
2686 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002687 unsigned AS = SI.getPointerAddressSpace();
2688 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS));
Chandler Carruth2659e502014-02-26 05:02:19 +00002689 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2690 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002691 }
Michael Kruse978ba612018-12-20 04:58:07 +00002692 NewSI->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2693 LLVMContext::MD_access_group});
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002694 if (AATags)
2695 NewSI->setAAMetadata(AATags);
David Majnemer62690b12015-07-14 06:19:58 +00002696 if (SI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002697 NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
Chandler Carruth18db7952012-11-20 01:12:50 +00002698 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002699 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002700
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002701 LLVM_DEBUG(dbgs() << " to: " << *NewSI << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002702 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002703 }
2704
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002705 /// Compute an integer value from splatting an i8 across the given
Chandler Carruth514f34f2012-12-17 04:07:30 +00002706 /// number of bytes.
2707 ///
2708 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2709 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002710 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002711 ///
2712 /// \param V The i8 value to splat.
2713 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002714 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002715 assert(Size > 0 && "Expected a positive number of bytes.");
2716 IntegerType *VTy = cast<IntegerType>(V->getType());
2717 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2718 if (Size == 1)
2719 return V;
2720
Chandler Carruth113dc642014-12-20 02:39:18 +00002721 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2722 V = IRB.CreateMul(
2723 IRB.CreateZExt(V, SplatIntTy, "zext"),
2724 ConstantExpr::getUDiv(
2725 Constant::getAllOnesValue(SplatIntTy),
2726 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2727 SplatIntTy)),
2728 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002729 return V;
2730 }
2731
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002732 /// Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002733 Value *getVectorSplat(Value *V, unsigned NumElements) {
2734 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002735 LLVM_DEBUG(dbgs() << " splat: " << *V << "\n");
Chandler Carruthccca5042012-12-17 04:07:37 +00002736 return V;
2737 }
2738
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002739 bool visitMemSetInst(MemSetInst &II) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002740 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002741 assert(II.getRawDest() == OldPtr);
2742
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002743 AAMDNodes AATags;
2744 II.getAAMetadata(AATags);
2745
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002746 // If the memset has a variable size, it cannot be split, just adjust the
2747 // pointer to the new alloca.
2748 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002749 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002750 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002751 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Daniel Neilson41e781d2018-03-13 14:25:33 +00002752 II.setDestAlignment(getSliceAlign());
Chandler Carruth208124f2012-09-26 10:59:22 +00002753
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002754 deleteIfTriviallyDead(OldPtr);
2755 return false;
2756 }
2757
2758 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002759 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002760
2761 Type *AllocaTy = NewAI.getAllocatedType();
2762 Type *ScalarTy = AllocaTy->getScalarType();
Philip Reames9b6b4fa2019-03-12 20:15:05 +00002763
2764 const bool CanContinue = [&]() {
2765 if (VecTy || IntTy)
2766 return true;
2767 if (BeginOffset > NewAllocaBeginOffset ||
2768 EndOffset < NewAllocaEndOffset)
2769 return false;
2770 auto *C = cast<ConstantInt>(II.getLength());
2771 if (C->getBitWidth() > 64)
2772 return false;
2773 const auto Len = C->getZExtValue();
2774 auto *Int8Ty = IntegerType::getInt8Ty(NewAI.getContext());
2775 auto *SrcTy = VectorType::get(Int8Ty, Len);
2776 return canConvertValue(DL, SrcTy, AllocaTy) &&
2777 DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy));
2778 }();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002779
2780 // If this doesn't map cleanly onto the alloca type, and that type isn't
2781 // a single value type, just emit a memset.
Philip Reames9b6b4fa2019-03-12 20:15:05 +00002782 if (!CanContinue) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002783 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002784 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2785 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002786 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2787 getSliceAlign(), II.isVolatile());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002788 if (AATags)
2789 New->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002790 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002791 return false;
2792 }
2793
2794 // If we can represent this as a simple value, we have to build the actual
2795 // value to store, which requires expanding the byte present in memset to
2796 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002797 // splatting the byte to a sufficiently wide integer, splatting it across
2798 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002799 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002800
Chandler Carruthccca5042012-12-17 04:07:37 +00002801 if (VecTy) {
2802 // If this is a memset of a vectorized alloca, insert it.
2803 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002804
Chandler Carruthf0546402013-07-18 07:15:00 +00002805 unsigned BeginIndex = getIndex(NewBeginOffset);
2806 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002807 assert(EndIndex > BeginIndex && "Empty vector!");
2808 unsigned NumElements = EndIndex - BeginIndex;
2809 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2810
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002811 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002812 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2813 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002814 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002815 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002816
James Y Knight14359ef2019-02-01 20:44:24 +00002817 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2818 NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002819 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002820 } else if (IntTy) {
2821 // If this is a memset on an alloca where we can widen stores, insert the
2822 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002823 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002824
Chandler Carruthf0546402013-07-18 07:15:00 +00002825 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002826 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002827
2828 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2829 EndOffset != NewAllocaBeginOffset)) {
James Y Knight14359ef2019-02-01 20:44:24 +00002830 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2831 NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002832 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002833 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002834 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002835 } else {
2836 assert(V->getType() == IntTy &&
2837 "Wrong type for an alloca wide integer!");
2838 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002839 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002840 } else {
2841 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002842 assert(NewBeginOffset == NewAllocaBeginOffset);
2843 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002844
Chandler Carruth90a735d2013-07-19 07:21:28 +00002845 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002846 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002847 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002848
Chandler Carruth90a735d2013-07-19 07:21:28 +00002849 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002850 }
2851
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002852 StoreInst *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2853 II.isVolatile());
2854 if (AATags)
2855 New->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002856 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002857 return !II.isVolatile();
2858 }
2859
2860 bool visitMemTransferInst(MemTransferInst &II) {
2861 // Rewriting of memory transfer instructions can be a bit tricky. We break
2862 // them into two categories: split intrinsics and unsplit intrinsics.
2863
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002864 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002865
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002866 AAMDNodes AATags;
2867 II.getAAMetadata(AATags);
2868
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002869 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002870 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002871 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002872
Chandler Carruthaa72b932014-02-26 07:29:54 +00002873 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002874
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002875 // For unsplit intrinsics, we simply modify the source and destination
2876 // pointers in place. This isn't just an optimization, it is a matter of
2877 // correctness. With unsplit intrinsics we may be dealing with transfers
2878 // within a single alloca before SROA ran, or with transfers that have
2879 // a variable length. We may also be dealing with memmove instead of
2880 // memcpy, and so simply updating the pointers is the necessary for us to
2881 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002882 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002883 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Daniel Neilson41e781d2018-03-13 14:25:33 +00002884 if (IsDest) {
Chandler Carruth8183a502014-02-25 11:08:02 +00002885 II.setDest(AdjustedPtr);
Daniel Neilson41e781d2018-03-13 14:25:33 +00002886 II.setDestAlignment(SliceAlign);
2887 }
2888 else {
Chandler Carruth8183a502014-02-25 11:08:02 +00002889 II.setSource(AdjustedPtr);
Daniel Neilson41e781d2018-03-13 14:25:33 +00002890 II.setSourceAlignment(SliceAlign);
Chandler Carruth181ed052014-02-26 05:33:36 +00002891 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002892
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002893 LLVM_DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002894 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002895 return false;
2896 }
2897 // For split transfer intrinsics we have an incredibly useful assurance:
2898 // the source and destination do not reside within the same alloca, and at
2899 // least one of them does not escape. This means that we can replace
2900 // memmove with memcpy, and we don't need to worry about all manner of
2901 // downsides to splitting and transforming the operations.
2902
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002903 // If this doesn't map cleanly onto the alloca type, and that type isn't
2904 // a single value type, just emit a memcpy.
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002905 bool EmitMemCpy =
2906 !VecTy && !IntTy &&
2907 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2908 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2909 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002910
2911 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2912 // size hasn't been shrunk based on analysis of the viable range, this is
2913 // a no-op.
2914 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002915 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002916 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002917
2918 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002919 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002920 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002921 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002922 return false;
2923 }
2924 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002925 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002926
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002927 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2928 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002929 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth113dc642014-12-20 02:39:18 +00002930 if (AllocaInst *AI =
2931 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002932 assert(AI != &OldAI && AI != &NewAI &&
2933 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002934 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002935 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002936
Chandler Carruth286d87e2014-02-26 08:25:02 +00002937 Type *OtherPtrTy = OtherPtr->getType();
2938 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2939
Chandler Carruth181ed052014-02-26 05:33:36 +00002940 // Compute the relative offset for the other pointer within the transfer.
Nicola Zaghenf96383c2018-10-30 11:15:04 +00002941 unsigned OffsetWidth = DL.getIndexSizeInBits(OtherAS);
2942 APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset);
Daniel Neilson41e781d2018-03-13 14:25:33 +00002943 unsigned OtherAlign =
2944 IsDest ? II.getSourceAlignment() : II.getDestAlignment();
2945 OtherAlign = MinAlign(OtherAlign ? OtherAlign : 1,
2946 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002947
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002948 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002949 // Compute the other pointer, folding as much as possible to produce
2950 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002951 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002952 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002953
Chandler Carruth47954c82014-02-26 05:12:43 +00002954 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002955 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002956 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002957
Daniel Neilson41e781d2018-03-13 14:25:33 +00002958 Value *DestPtr, *SrcPtr;
2959 unsigned DestAlign, SrcAlign;
2960 // Note: IsDest is true iff we're copying into the new alloca slice
2961 if (IsDest) {
2962 DestPtr = OurPtr;
2963 DestAlign = SliceAlign;
2964 SrcPtr = OtherPtr;
2965 SrcAlign = OtherAlign;
2966 } else {
2967 DestPtr = OtherPtr;
2968 DestAlign = OtherAlign;
2969 SrcPtr = OurPtr;
2970 SrcAlign = SliceAlign;
2971 }
2972 CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign,
2973 Size, II.isVolatile());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002974 if (AATags)
2975 New->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002976 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002977 return false;
2978 }
2979
Chandler Carruthf0546402013-07-18 07:15:00 +00002980 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2981 NewEndOffset == NewAllocaEndOffset;
2982 uint64_t Size = NewEndOffset - NewBeginOffset;
2983 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2984 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002985 unsigned NumElements = EndIndex - BeginIndex;
Chandler Carruth113dc642014-12-20 02:39:18 +00002986 IntegerType *SubIntTy =
2987 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002988
Chandler Carruth286d87e2014-02-26 08:25:02 +00002989 // Reset the other pointer type to match the register type we're going to
2990 // use, but using the address space of the original other pointer.
James Y Knight14359ef2019-02-01 20:44:24 +00002991 Type *OtherTy;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002992 if (VecTy && !IsWholeAlloca) {
2993 if (NumElements == 1)
James Y Knight14359ef2019-02-01 20:44:24 +00002994 OtherTy = VecTy->getElementType();
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002995 else
James Y Knight14359ef2019-02-01 20:44:24 +00002996 OtherTy = VectorType::get(VecTy->getElementType(), NumElements);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002997 } else if (IntTy && !IsWholeAlloca) {
James Y Knight14359ef2019-02-01 20:44:24 +00002998 OtherTy = SubIntTy;
Chandler Carruth286d87e2014-02-26 08:25:02 +00002999 } else {
James Y Knight14359ef2019-02-01 20:44:24 +00003000 OtherTy = NewAllocaTy;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003001 }
James Y Knight14359ef2019-02-01 20:44:24 +00003002 OtherPtrTy = OtherTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003003
Chandler Carruth181ed052014-02-26 05:33:36 +00003004 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00003005 OtherPtr->getName() + ".");
Pete Cooper67cf9a72015-11-19 05:56:52 +00003006 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003007 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00003008 unsigned DstAlign = SliceAlign;
3009 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003010 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00003011 std::swap(SrcAlign, DstAlign);
3012 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003013
3014 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003015 if (VecTy && !IsWholeAlloca && !IsDest) {
James Y Knight14359ef2019-02-01 20:44:24 +00003016 Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3017 NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00003018 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00003019 } else if (IntTy && !IsWholeAlloca && !IsDest) {
James Y Knight14359ef2019-02-01 20:44:24 +00003020 Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3021 NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00003022 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00003023 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003024 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003025 } else {
James Y Knight14359ef2019-02-01 20:44:24 +00003026 LoadInst *Load = IRB.CreateAlignedLoad(OtherTy, SrcPtr, SrcAlign,
3027 II.isVolatile(), "copyload");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003028 if (AATags)
3029 Load->setAAMetadata(AATags);
3030 Src = Load;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003031 }
3032
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003033 if (VecTy && !IsWholeAlloca && IsDest) {
James Y Knight14359ef2019-02-01 20:44:24 +00003034 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3035 NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00003036 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003037 } else if (IntTy && !IsWholeAlloca && IsDest) {
James Y Knight14359ef2019-02-01 20:44:24 +00003038 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3039 NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00003040 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00003041 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003042 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
3043 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00003044 }
3045
Chandler Carruth871ba722012-09-26 10:27:46 +00003046 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00003047 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003048 if (AATags)
3049 Store->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003050 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003051 return !II.isVolatile();
3052 }
3053
3054 bool visitIntrinsicInst(IntrinsicInst &II) {
Vedant Kumarb264d692018-12-21 21:49:40 +00003055 assert(II.isLifetimeStartOrEnd());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003056 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003057 assert(II.getArgOperand(1) == OldPtr);
3058
3059 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00003060 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003061
Eli Friedman50967752016-11-28 21:50:34 +00003062 // Lifetime intrinsics are only promotable if they cover the whole alloca.
3063 // Therefore, we drop lifetime intrinsics which don't cover the whole
3064 // alloca.
3065 // (In theory, intrinsics which partially cover an alloca could be
3066 // promoted, but PromoteMemToReg doesn't handle that case.)
3067 // FIXME: Check whether the alloca is promotable before dropping the
3068 // lifetime intrinsics?
3069 if (NewBeginOffset != NewAllocaBeginOffset ||
3070 NewEndOffset != NewAllocaEndOffset)
3071 return true;
3072
Chandler Carruth113dc642014-12-20 02:39:18 +00003073 ConstantInt *Size =
3074 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00003075 NewEndOffset - NewBeginOffset);
Gabor Buella3ec170c2019-01-16 12:06:17 +00003076 // Lifetime intrinsics always expect an i8* so directly get such a pointer
3077 // for the new alloca slice.
3078 Type *PointerTy = IRB.getInt8PtrTy(OldPtr->getType()->getPointerAddressSpace());
3079 Value *Ptr = getNewAllocaSlicePtr(IRB, PointerTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003080 Value *New;
3081 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3082 New = IRB.CreateLifetimeStart(Ptr, Size);
3083 else
3084 New = IRB.CreateLifetimeEnd(Ptr, Size);
3085
Edwin Vane82f80d42013-01-29 17:42:24 +00003086 (void)New;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003087 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Eli Friedman2a65dd12016-08-08 01:30:53 +00003088
Eli Friedman50967752016-11-28 21:50:34 +00003089 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003090 }
3091
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003092 void fixLoadStoreAlign(Instruction &Root) {
3093 // This algorithm implements the same visitor loop as
3094 // hasUnsafePHIOrSelectUse, and fixes the alignment of each load
3095 // or store found.
3096 SmallPtrSet<Instruction *, 4> Visited;
3097 SmallVector<Instruction *, 4> Uses;
3098 Visited.insert(&Root);
3099 Uses.push_back(&Root);
3100 do {
3101 Instruction *I = Uses.pop_back_val();
3102
3103 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3104 unsigned LoadAlign = LI->getAlignment();
3105 if (!LoadAlign)
3106 LoadAlign = DL.getABITypeAlignment(LI->getType());
3107 LI->setAlignment(std::min(LoadAlign, getSliceAlign()));
3108 continue;
3109 }
3110 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3111 unsigned StoreAlign = SI->getAlignment();
3112 if (!StoreAlign) {
3113 Value *Op = SI->getOperand(0);
3114 StoreAlign = DL.getABITypeAlignment(Op->getType());
3115 }
3116 SI->setAlignment(std::min(StoreAlign, getSliceAlign()));
3117 continue;
3118 }
3119
Matt Arsenault282dac72019-06-14 21:38:31 +00003120 assert(isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I) ||
3121 isa<PHINode>(I) || isa<SelectInst>(I) ||
3122 isa<GetElementPtrInst>(I));
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003123 for (User *U : I->users())
3124 if (Visited.insert(cast<Instruction>(U)).second)
3125 Uses.push_back(cast<Instruction>(U));
3126 } while (!Uses.empty());
3127 }
3128
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003129 bool visitPHINode(PHINode &PN) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003130 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00003131 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
3132 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003133
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003134 // We would like to compute a new pointer in only one place, but have it be
3135 // as local as possible to the PHI. To do that, we re-use the location of
3136 // the old pointer, which necessarily must be in the right position to
3137 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00003138 IRBuilderTy PtrBuilder(IRB);
David Majnemerd4cffcf2014-09-01 21:20:14 +00003139 if (isa<PHINode>(OldPtr))
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003140 PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
David Majnemerd4cffcf2014-09-01 21:20:14 +00003141 else
3142 PtrBuilder.SetInsertPoint(OldPtr);
Chandler Carruth51175532014-02-25 11:12:04 +00003143 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003144
Chandler Carruth47954c82014-02-26 05:12:43 +00003145 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00003146 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003147 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003148
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003149 LLVM_DEBUG(dbgs() << " to: " << PN << "\n");
Chandler Carruth82a57542012-10-01 10:54:05 +00003150 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003151
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003152 // Fix the alignment of any loads or stores using this PHI node.
3153 fixLoadStoreAlign(PN);
3154
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003155 // PHIs can't be promoted on their own, but often can be speculated. We
3156 // check the speculation outside of the rewriter so that we see the
3157 // fully-rewritten alloca.
3158 PHIUsers.insert(&PN);
3159 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003160 }
3161
3162 bool visitSelectInst(SelectInst &SI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003163 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003164 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3165 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00003166 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
3167 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003168
Chandler Carruth47954c82014-02-26 05:12:43 +00003169 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003170 // Replace the operands which were using the old pointer.
3171 if (SI.getOperand(1) == OldPtr)
3172 SI.setOperand(1, NewPtr);
3173 if (SI.getOperand(2) == OldPtr)
3174 SI.setOperand(2, NewPtr);
3175
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003176 LLVM_DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003177 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003178
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003179 // Fix the alignment of any loads or stores using this select.
3180 fixLoadStoreAlign(SI);
3181
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003182 // Selects can't be promoted on their own, but often can be speculated. We
3183 // check the speculation outside of the rewriter so that we see the
3184 // fully-rewritten alloca.
3185 SelectUsers.insert(&SI);
3186 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003187 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003188};
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003189
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003190namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003191
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003192/// Visitor to rewrite aggregate loads and stores as scalar.
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003193///
3194/// This pass aggressively rewrites all aggregate loads and stores on
3195/// a particular pointer (or any pointer derived from it which we can identify)
3196/// with scalar loads and stores.
3197class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3198 // Befriend the base class so it can delegate to private visit methods.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003199 friend class InstVisitor<AggLoadStoreRewriter, bool>;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003200
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003201 /// Queue of pointer uses to analyze and potentially rewrite.
3202 SmallVector<Use *, 8> Queue;
3203
3204 /// Set to prevent us from cycling with phi nodes and loops.
3205 SmallPtrSet<User *, 8> Visited;
3206
3207 /// The current pointer use being rewritten. This is used to dig up the used
3208 /// value (as opposed to the user).
3209 Use *U;
3210
Tim Northover856628f2018-12-18 09:29:39 +00003211 /// Used to calculate offsets, and hence alignment, of subobjects.
3212 const DataLayout &DL;
3213
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003214public:
Tim Northover856628f2018-12-18 09:29:39 +00003215 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
3216
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003217 /// Rewrite loads and stores through a pointer and all pointers derived from
3218 /// it.
3219 bool rewrite(Instruction &I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003220 LLVM_DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003221 enqueueUsers(I);
3222 bool Changed = false;
3223 while (!Queue.empty()) {
3224 U = Queue.pop_back_val();
3225 Changed |= visit(cast<Instruction>(U->getUser()));
3226 }
3227 return Changed;
3228 }
3229
3230private:
3231 /// Enqueue all the users of the given instruction for further processing.
3232 /// This uses a set to de-duplicate users.
3233 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003234 for (Use &U : I.uses())
David Blaikie70573dc2014-11-19 07:49:26 +00003235 if (Visited.insert(U.getUser()).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003236 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003237 }
3238
3239 // Conservative default is to not rewrite anything.
3240 bool visitInstruction(Instruction &I) { return false; }
3241
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003242 /// Generic recursive split emission class.
Chandler Carruth113dc642014-12-20 02:39:18 +00003243 template <typename Derived> class OpSplitter {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003244 protected:
3245 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00003246 IRBuilderTy IRB;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003247
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003248 /// The indices which to be used with insert- or extractvalue to select the
3249 /// appropriate value within the aggregate.
3250 SmallVector<unsigned, 4> Indices;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003251
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003252 /// The indices to a GEP instruction which will move Ptr to the correct slot
3253 /// within the aggregate.
3254 SmallVector<Value *, 4> GEPIndices;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003255
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003256 /// The base pointer of the original op, used as a base for GEPing the
3257 /// split operations.
3258 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003259
Tim Northover856628f2018-12-18 09:29:39 +00003260 /// The base pointee type being GEPed into.
3261 Type *BaseTy;
3262
3263 /// Known alignment of the base pointer.
3264 unsigned BaseAlign;
3265
3266 /// To calculate offset of each component so we can correctly deduce
3267 /// alignments.
3268 const DataLayout &DL;
3269
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003270 /// Initialize the splitter with an insertion point, Ptr and start with a
3271 /// single zero GEP index.
Tim Northover856628f2018-12-18 09:29:39 +00003272 OpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3273 unsigned BaseAlign, const DataLayout &DL)
3274 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr),
3275 BaseTy(BaseTy), BaseAlign(BaseAlign), DL(DL) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003276
3277 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003278 /// Generic recursive split emission routine.
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003279 ///
3280 /// This method recursively splits an aggregate op (load or store) into
3281 /// scalar or vector ops. It splits recursively until it hits a single value
3282 /// and emits that single value operation via the template argument.
3283 ///
3284 /// The logic of this routine relies on GEPs and insertvalue and
3285 /// extractvalue all operating with the same fundamental index list, merely
3286 /// formatted differently (GEPs need actual values).
3287 ///
3288 /// \param Ty The type being split recursively into smaller ops.
3289 /// \param Agg The aggregate value being built up or stored, depending on
3290 /// whether this is splitting a load or a store respectively.
3291 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
Tim Northover856628f2018-12-18 09:29:39 +00003292 if (Ty->isSingleValueType()) {
3293 unsigned Offset = DL.getIndexedOffsetInType(BaseTy, GEPIndices);
3294 return static_cast<Derived *>(this)->emitFunc(
3295 Ty, Agg, MinAlign(BaseAlign, Offset), Name);
3296 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003297
3298 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3299 unsigned OldSize = Indices.size();
3300 (void)OldSize;
3301 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3302 ++Idx) {
3303 assert(Indices.size() == OldSize && "Did not return to the old size");
3304 Indices.push_back(Idx);
3305 GEPIndices.push_back(IRB.getInt32(Idx));
3306 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3307 GEPIndices.pop_back();
3308 Indices.pop_back();
3309 }
3310 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003311 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003312
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003313 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3314 unsigned OldSize = Indices.size();
3315 (void)OldSize;
3316 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3317 ++Idx) {
3318 assert(Indices.size() == OldSize && "Did not return to the old size");
3319 Indices.push_back(Idx);
3320 GEPIndices.push_back(IRB.getInt32(Idx));
3321 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3322 GEPIndices.pop_back();
3323 Indices.pop_back();
3324 }
3325 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003326 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003327
3328 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003329 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003330 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003331
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003332 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003333 AAMDNodes AATags;
3334
Tim Northover856628f2018-12-18 09:29:39 +00003335 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3336 AAMDNodes AATags, unsigned BaseAlign, const DataLayout &DL)
3337 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
3338 DL), AATags(AATags) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003339
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003340 /// Emit a leaf load of a single value. This is called at the leaves of the
3341 /// recursive emission to actually load values.
Tim Northover856628f2018-12-18 09:29:39 +00003342 void emitFunc(Type *Ty, Value *&Agg, unsigned Align, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003343 assert(Ty->isSingleValueType());
3344 // Load the single value and insert it using the indices.
David Blaikieaa41cd52015-04-03 21:33:42 +00003345 Value *GEP =
James Y Knight77160752019-02-01 20:44:47 +00003346 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
James Y Knight14359ef2019-02-01 20:44:24 +00003347 LoadInst *Load = IRB.CreateAlignedLoad(Ty, GEP, Align, Name + ".load");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003348 if (AATags)
3349 Load->setAAMetadata(AATags);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003350 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003351 LLVM_DEBUG(dbgs() << " to: " << *Load << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003352 }
3353 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003354
3355 bool visitLoadInst(LoadInst &LI) {
3356 assert(LI.getPointerOperand() == *U);
3357 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3358 return false;
3359
3360 // We have an aggregate being loaded, split it apart.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003361 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003362 AAMDNodes AATags;
3363 LI.getAAMetadata(AATags);
Tim Northover856628f2018-12-18 09:29:39 +00003364 LoadOpSplitter Splitter(&LI, *U, LI.getType(), AATags,
3365 getAdjustedAlignment(&LI, 0, DL), DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003366 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003367 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003368 LI.replaceAllUsesWith(V);
3369 LI.eraseFromParent();
3370 return true;
3371 }
3372
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003373 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Tim Northover856628f2018-12-18 09:29:39 +00003374 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3375 AAMDNodes AATags, unsigned BaseAlign, const DataLayout &DL)
3376 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
3377 DL),
3378 AATags(AATags) {}
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003379 AAMDNodes AATags;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003380 /// Emit a leaf store of a single value. This is called at the leaves of the
3381 /// recursive emission to actually produce stores.
Tim Northover856628f2018-12-18 09:29:39 +00003382 void emitFunc(Type *Ty, Value *&Agg, unsigned Align, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003383 assert(Ty->isSingleValueType());
3384 // Extract the single value and store it using the indices.
Patrik Hagglunda83706e2016-06-20 10:19:00 +00003385 //
3386 // The gep and extractvalue values are factored out of the CreateStore
3387 // call to make the output independent of the argument evaluation order.
Patrik Hagglund4e0bd842016-06-20 11:19:58 +00003388 Value *ExtractValue =
3389 IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
3390 Value *InBoundsGEP =
James Y Knight77160752019-02-01 20:44:47 +00003391 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
Tim Northover856628f2018-12-18 09:29:39 +00003392 StoreInst *Store =
3393 IRB.CreateAlignedStore(ExtractValue, InBoundsGEP, Align);
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003394 if (AATags)
3395 Store->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003396 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003397 }
3398 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003399
3400 bool visitStoreInst(StoreInst &SI) {
3401 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3402 return false;
3403 Value *V = SI.getValueOperand();
3404 if (V->getType()->isSingleValueType())
3405 return false;
3406
3407 // We have an aggregate being stored, split it apart.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003408 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003409 AAMDNodes AATags;
3410 SI.getAAMetadata(AATags);
Tim Northover856628f2018-12-18 09:29:39 +00003411 StoreOpSplitter Splitter(&SI, *U, V->getType(), AATags,
3412 getAdjustedAlignment(&SI, 0, DL), DL);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003413 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003414 SI.eraseFromParent();
3415 return true;
3416 }
3417
3418 bool visitBitCastInst(BitCastInst &BC) {
3419 enqueueUsers(BC);
3420 return false;
3421 }
3422
Matt Arsenault282dac72019-06-14 21:38:31 +00003423 bool visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
3424 enqueueUsers(ASC);
3425 return false;
3426 }
3427
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003428 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3429 enqueueUsers(GEPI);
3430 return false;
3431 }
3432
3433 bool visitPHINode(PHINode &PN) {
3434 enqueueUsers(PN);
3435 return false;
3436 }
3437
3438 bool visitSelectInst(SelectInst &SI) {
3439 enqueueUsers(SI);
3440 return false;
3441 }
3442};
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003443
3444} // end anonymous namespace
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003445
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003446/// Strip aggregate type wrapping.
Chandler Carruthba931992012-10-13 10:49:33 +00003447///
3448/// This removes no-op aggregate types wrapping an underlying type. It will
3449/// strip as many layers of types as it can without changing either the type
3450/// size or the allocated size.
3451static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3452 if (Ty->isSingleValueType())
3453 return Ty;
3454
3455 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3456 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3457
3458 Type *InnerTy;
3459 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3460 InnerTy = ArrTy->getElementType();
3461 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3462 const StructLayout *SL = DL.getStructLayout(STy);
3463 unsigned Index = SL->getElementContainingOffset(0);
3464 InnerTy = STy->getElementType(Index);
3465 } else {
3466 return Ty;
3467 }
3468
3469 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3470 TypeSize > DL.getTypeSizeInBits(InnerTy))
3471 return Ty;
3472
3473 return stripAggregateTypeWrapping(DL, InnerTy);
3474}
3475
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003476/// Try to find a partition of the aggregate type passed in for a given
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003477/// offset and size.
3478///
3479/// This recurses through the aggregate type and tries to compute a subtype
3480/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003481/// of an array, it will even compute a new array type for that sub-section,
3482/// and the same for structs.
3483///
3484/// Note that this routine is very strict and tries to find a partition of the
3485/// type which produces the *exact* right offset and size. It is not forgiving
3486/// when the size or offset cause either end of type-based partition to be off.
3487/// Also, this is a best-effort routine. It is reasonable to give up and not
3488/// return a type if necessary.
Chandler Carruth113dc642014-12-20 02:39:18 +00003489static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3490 uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003491 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3492 return stripAggregateTypeWrapping(DL, Ty);
3493 if (Offset > DL.getTypeAllocSize(Ty) ||
3494 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003495 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003496
3497 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003498 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003499 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003500 uint64_t NumSkippedElements = Offset / ElementSize;
Peter Collingbournebc070522016-12-02 03:20:58 +00003501 if (NumSkippedElements >= SeqTy->getNumElements())
3502 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003503 Offset -= NumSkippedElements * ElementSize;
3504
3505 // First check if we need to recurse.
3506 if (Offset > 0 || Size < ElementSize) {
3507 // Bail if the partition ends in a different array element.
3508 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003509 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003510 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003511 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003512 }
3513 assert(Offset == 0);
3514
3515 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003516 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003517 assert(Size > ElementSize);
3518 uint64_t NumElements = Size / ElementSize;
3519 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003520 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003521 return ArrayType::get(ElementTy, NumElements);
3522 }
3523
3524 StructType *STy = dyn_cast<StructType>(Ty);
3525 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003526 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003527
Chandler Carruth90a735d2013-07-19 07:21:28 +00003528 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003529 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003530 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003531 uint64_t EndOffset = Offset + Size;
3532 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003533 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003534
3535 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003536 Offset -= SL->getElementOffset(Index);
3537
3538 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003539 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003540 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003541 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003542
3543 // See if any partition must be contained by the element.
3544 if (Offset > 0 || Size < ElementSize) {
3545 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003546 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003547 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003548 }
3549 assert(Offset == 0);
3550
3551 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003552 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003553
3554 StructType::element_iterator EI = STy->element_begin() + Index,
3555 EE = STy->element_end();
3556 if (EndOffset < SL->getSizeInBytes()) {
3557 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3558 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003559 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003560
3561 // Don't try to form "natural" types if the elements don't line up with the
3562 // expected size.
3563 // FIXME: We could potentially recurse down through the last element in the
3564 // sub-struct to find a natural end point.
3565 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003566 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003567
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003568 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003569 EE = STy->element_begin() + EndIndex;
3570 }
3571
3572 // Try to build up a sub-structure.
Chandler Carruth113dc642014-12-20 02:39:18 +00003573 StructType *SubTy =
3574 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003575 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003576 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003577 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003578
Chandler Carruth054a40a2012-09-14 11:08:31 +00003579 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003580}
3581
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003582/// Pre-split loads and stores to simplify rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003583///
3584/// We want to break up the splittable load+store pairs as much as
3585/// possible. This is important to do as a preprocessing step, as once we
3586/// start rewriting the accesses to partitions of the alloca we lose the
3587/// necessary information to correctly split apart paired loads and stores
3588/// which both point into this alloca. The case to consider is something like
3589/// the following:
3590///
3591/// %a = alloca [12 x i8]
3592/// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3593/// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3594/// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3595/// %iptr1 = bitcast i8* %gep1 to i64*
3596/// %iptr2 = bitcast i8* %gep2 to i64*
3597/// %fptr1 = bitcast i8* %gep1 to float*
3598/// %fptr2 = bitcast i8* %gep2 to float*
3599/// %fptr3 = bitcast i8* %gep3 to float*
3600/// store float 0.0, float* %fptr1
3601/// store float 1.0, float* %fptr2
3602/// %v = load i64* %iptr1
3603/// store i64 %v, i64* %iptr2
3604/// %f1 = load float* %fptr2
3605/// %f2 = load float* %fptr3
3606///
3607/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3608/// promote everything so we recover the 2 SSA values that should have been
3609/// there all along.
3610///
3611/// \returns true if any changes are made.
3612bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003613 LLVM_DEBUG(dbgs() << "Pre-splitting loads and stores\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003614
3615 // Track the loads and stores which are candidates for pre-splitting here, in
3616 // the order they first appear during the partition scan. These give stable
3617 // iteration order and a basis for tracking which loads and stores we
3618 // actually split.
3619 SmallVector<LoadInst *, 4> Loads;
3620 SmallVector<StoreInst *, 4> Stores;
3621
3622 // We need to accumulate the splits required of each load or store where we
3623 // can find them via a direct lookup. This is important to cross-check loads
3624 // and stores against each other. We also track the slice so that we can kill
3625 // all the slices that end up split.
3626 struct SplitOffsets {
3627 Slice *S;
3628 std::vector<uint64_t> Splits;
3629 };
3630 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3631
Chandler Carruth73b01642015-01-05 04:17:53 +00003632 // Track loads out of this alloca which cannot, for any reason, be pre-split.
3633 // This is important as we also cannot pre-split stores of those loads!
3634 // FIXME: This is all pretty gross. It means that we can be more aggressive
3635 // in pre-splitting when the load feeding the store happens to come from
3636 // a separate alloca. Put another way, the effectiveness of SROA would be
3637 // decreased by a frontend which just concatenated all of its local allocas
3638 // into one big flat alloca. But defeating such patterns is exactly the job
3639 // SROA is tasked with! Sadly, to not have this discrepancy we would have
3640 // change store pre-splitting to actually force pre-splitting of the load
3641 // that feeds it *and all stores*. That makes pre-splitting much harder, but
3642 // maybe it would make it more principled?
3643 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3644
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003645 LLVM_DEBUG(dbgs() << " Searching for candidate loads and stores\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003646 for (auto &P : AS.partitions()) {
3647 for (Slice &S : P) {
Chandler Carruth73b01642015-01-05 04:17:53 +00003648 Instruction *I = cast<Instruction>(S.getUse()->getUser());
Chandler Carruth37f1f122016-03-10 15:31:17 +00003649 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
3650 // If this is a load we have to track that it can't participate in any
3651 // pre-splitting. If this is a store of a load we have to track that
3652 // that load also can't participate in any pre-splitting.
Chandler Carruth73b01642015-01-05 04:17:53 +00003653 if (auto *LI = dyn_cast<LoadInst>(I))
3654 UnsplittableLoads.insert(LI);
Chandler Carruth37f1f122016-03-10 15:31:17 +00003655 else if (auto *SI = dyn_cast<StoreInst>(I))
3656 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
3657 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003658 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003659 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003660 assert(P.endOffset() > S.beginOffset() &&
3661 "Empty or backwards partition!");
3662
3663 // Determine if this is a pre-splittable slice.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003664 if (auto *LI = dyn_cast<LoadInst>(I)) {
3665 assert(!LI->isVolatile() && "Cannot split volatile loads!");
3666
3667 // The load must be used exclusively to store into other pointers for
3668 // us to be able to arbitrarily pre-split it. The stores must also be
3669 // simple to avoid changing semantics.
3670 auto IsLoadSimplyStored = [](LoadInst *LI) {
3671 for (User *LU : LI->users()) {
3672 auto *SI = dyn_cast<StoreInst>(LU);
3673 if (!SI || !SI->isSimple())
3674 return false;
3675 }
3676 return true;
3677 };
Chandler Carruth73b01642015-01-05 04:17:53 +00003678 if (!IsLoadSimplyStored(LI)) {
3679 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003680 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003681 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003682
3683 Loads.push_back(LI);
Chandler Carruthd94a5962016-03-10 14:16:18 +00003684 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
3685 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3686 // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
Chandler Carruth994cde82015-01-01 12:01:03 +00003687 continue;
3688 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3689 if (!StoredLoad || !StoredLoad->isSimple())
3690 continue;
3691 assert(!SI->isVolatile() && "Cannot split volatile stores!");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003692
Chandler Carruth994cde82015-01-01 12:01:03 +00003693 Stores.push_back(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003694 } else {
3695 // Other uses cannot be pre-split.
3696 continue;
3697 }
3698
3699 // Record the initial split.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003700 LLVM_DEBUG(dbgs() << " Candidate: " << *I << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003701 auto &Offsets = SplitOffsetsMap[I];
3702 assert(Offsets.Splits.empty() &&
3703 "Should not have splits the first time we see an instruction!");
3704 Offsets.S = &S;
Chandler Carruth24ac8302015-01-02 03:55:54 +00003705 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003706 }
3707
3708 // Now scan the already split slices, and add a split for any of them which
3709 // we're going to pre-split.
3710 for (Slice *S : P.splitSliceTails()) {
3711 auto SplitOffsetsMapI =
3712 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3713 if (SplitOffsetsMapI == SplitOffsetsMap.end())
3714 continue;
3715 auto &Offsets = SplitOffsetsMapI->second;
3716
3717 assert(Offsets.S == S && "Found a mismatched slice!");
3718 assert(!Offsets.Splits.empty() &&
3719 "Cannot have an empty set of splits on the second partition!");
Chandler Carruth24ac8302015-01-02 03:55:54 +00003720 assert(Offsets.Splits.back() ==
3721 P.beginOffset() - Offsets.S->beginOffset() &&
Chandler Carruth0715cba2015-01-01 11:54:38 +00003722 "Previous split does not end where this one begins!");
3723
3724 // Record each split. The last partition's end isn't needed as the size
3725 // of the slice dictates that.
3726 if (S->endOffset() > P.endOffset())
Chandler Carruth24ac8302015-01-02 03:55:54 +00003727 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003728 }
3729 }
3730
3731 // We may have split loads where some of their stores are split stores. For
3732 // such loads and stores, we can only pre-split them if their splits exactly
3733 // match relative to their starting offset. We have to verify this prior to
3734 // any rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003735 Stores.erase(
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003736 llvm::remove_if(Stores,
3737 [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
3738 // Lookup the load we are storing in our map of split
3739 // offsets.
3740 auto *LI = cast<LoadInst>(SI->getValueOperand());
3741 // If it was completely unsplittable, then we're done,
3742 // and this store can't be pre-split.
3743 if (UnsplittableLoads.count(LI))
3744 return true;
Chandler Carruth73b01642015-01-05 04:17:53 +00003745
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003746 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3747 if (LoadOffsetsI == SplitOffsetsMap.end())
3748 return false; // Unrelated loads are definitely safe.
3749 auto &LoadOffsets = LoadOffsetsI->second;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003750
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003751 // Now lookup the store's offsets.
3752 auto &StoreOffsets = SplitOffsetsMap[SI];
Chandler Carruth0715cba2015-01-01 11:54:38 +00003753
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003754 // If the relative offsets of each split in the load and
3755 // store match exactly, then we can split them and we
3756 // don't need to remove them here.
3757 if (LoadOffsets.Splits == StoreOffsets.Splits)
3758 return false;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003759
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003760 LLVM_DEBUG(
3761 dbgs()
3762 << " Mismatched splits for load and store:\n"
3763 << " " << *LI << "\n"
3764 << " " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003765
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003766 // We've found a store and load that we need to split
3767 // with mismatched relative splits. Just give up on them
3768 // and remove both instructions from our list of
3769 // candidates.
3770 UnsplittableLoads.insert(LI);
3771 return true;
3772 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003773 Stores.end());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003774 // Now we have to go *back* through all the stores, because a later store may
Chandler Carruth73b01642015-01-05 04:17:53 +00003775 // have caused an earlier store's load to become unsplittable and if it is
3776 // unsplittable for the later store, then we can't rely on it being split in
3777 // the earlier store either.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003778 Stores.erase(llvm::remove_if(Stores,
3779 [&UnsplittableLoads](StoreInst *SI) {
3780 auto *LI =
3781 cast<LoadInst>(SI->getValueOperand());
3782 return UnsplittableLoads.count(LI);
3783 }),
Chandler Carruth73b01642015-01-05 04:17:53 +00003784 Stores.end());
3785 // Once we've established all the loads that can't be split for some reason,
3786 // filter any that made it into our list out.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003787 Loads.erase(llvm::remove_if(Loads,
3788 [&UnsplittableLoads](LoadInst *LI) {
3789 return UnsplittableLoads.count(LI);
3790 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003791 Loads.end());
3792
3793 // If no loads or stores are left, there is no pre-splitting to be done for
3794 // this alloca.
3795 if (Loads.empty() && Stores.empty())
3796 return false;
3797
3798 // From here on, we can't fail and will be building new accesses, so rig up
3799 // an IR builder.
3800 IRBuilderTy IRB(&AI);
3801
3802 // Collect the new slices which we will merge into the alloca slices.
3803 SmallVector<Slice, 4> NewSlices;
3804
3805 // Track any allocas we end up splitting loads and stores for so we iterate
3806 // on them.
3807 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3808
3809 // At this point, we have collected all of the loads and stores we can
3810 // pre-split, and the specific splits needed for them. We actually do the
3811 // splitting in a specific order in order to handle when one of the loads in
3812 // the value operand to one of the stores.
3813 //
3814 // First, we rewrite all of the split loads, and just accumulate each split
3815 // load in a parallel structure. We also build the slices for them and append
3816 // them to the alloca slices.
3817 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3818 std::vector<LoadInst *> SplitLoads;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003819 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003820 for (LoadInst *LI : Loads) {
3821 SplitLoads.clear();
3822
3823 IntegerType *Ty = cast<IntegerType>(LI->getType());
3824 uint64_t LoadSize = Ty->getBitWidth() / 8;
3825 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3826
3827 auto &Offsets = SplitOffsetsMap[LI];
3828 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3829 "Slice size should always match load size exactly!");
3830 uint64_t BaseOffset = Offsets.S->beginOffset();
3831 assert(BaseOffset + LoadSize > BaseOffset &&
3832 "Cannot represent alloca access size using 64-bit integers!");
3833
3834 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003835 IRB.SetInsertPoint(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003836
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003837 LLVM_DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003838
3839 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3840 int Idx = 0, Size = Offsets.Splits.size();
3841 for (;;) {
3842 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
Yaxun Liu7c44f342017-06-27 18:26:06 +00003843 auto AS = LI->getPointerAddressSpace();
3844 auto *PartPtrTy = PartTy->getPointerTo(AS);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003845 LoadInst *PLoad = IRB.CreateAlignedLoad(
James Y Knight14359ef2019-02-01 20:44:24 +00003846 PartTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003847 getAdjustedPtr(IRB, DL, BasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003848 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Chandler Carruth994cde82015-01-01 12:01:03 +00003849 PartPtrTy, BasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003850 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003851 LI->getName());
Michael Kruse978ba612018-12-20 04:58:07 +00003852 PLoad->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
3853 LLVMContext::MD_access_group});
Chandler Carruth0715cba2015-01-01 11:54:38 +00003854
3855 // Append this load onto the list of split loads so we can find it later
3856 // to rewrite the stores.
3857 SplitLoads.push_back(PLoad);
3858
3859 // Now build a new slice for the alloca.
Chandler Carruth994cde82015-01-01 12:01:03 +00003860 NewSlices.push_back(
3861 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3862 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003863 /*IsSplittable*/ false));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003864 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3865 << ", " << NewSlices.back().endOffset()
3866 << "): " << *PLoad << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003867
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003868 // See if we've handled all the splits.
3869 if (Idx >= Size)
3870 break;
3871
Chandler Carruth0715cba2015-01-01 11:54:38 +00003872 // Setup the next partition.
3873 PartOffset = Offsets.Splits[Idx];
3874 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003875 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3876 }
3877
3878 // Now that we have the split loads, do the slow walk over all uses of the
3879 // load and rewrite them as split stores, or save the split loads to use
3880 // below if the store is going to be split there anyways.
3881 bool DeferredStores = false;
3882 for (User *LU : LI->users()) {
3883 StoreInst *SI = cast<StoreInst>(LU);
3884 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3885 DeferredStores = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003886 LLVM_DEBUG(dbgs() << " Deferred splitting of store: " << *SI
3887 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003888 continue;
3889 }
3890
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003891 Value *StoreBasePtr = SI->getPointerOperand();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003892 IRB.SetInsertPoint(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003893
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003894 LLVM_DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003895
3896 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3897 LoadInst *PLoad = SplitLoads[Idx];
3898 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
Chandler Carruth994cde82015-01-01 12:01:03 +00003899 auto *PartPtrTy =
3900 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003901
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003902 auto AS = SI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003903 StoreInst *PStore = IRB.CreateAlignedStore(
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003904 PLoad,
3905 getAdjustedPtr(IRB, DL, StoreBasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003906 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003907 PartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003908 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Michael Kruse978ba612018-12-20 04:58:07 +00003909 PStore->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
3910 LLVMContext::MD_access_group});
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003911 LLVM_DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003912 }
3913
3914 // We want to immediately iterate on any allocas impacted by splitting
3915 // this store, and we have to track any promotable alloca (indicated by
3916 // a direct store) as needing to be resplit because it is no longer
3917 // promotable.
3918 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3919 ResplitPromotableAllocas.insert(OtherAI);
3920 Worklist.insert(OtherAI);
3921 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3922 StoreBasePtr->stripInBoundsOffsets())) {
3923 Worklist.insert(OtherAI);
3924 }
3925
3926 // Mark the original store as dead.
3927 DeadInsts.insert(SI);
3928 }
3929
3930 // Save the split loads if there are deferred stores among the users.
3931 if (DeferredStores)
3932 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3933
3934 // Mark the original load as dead and kill the original slice.
3935 DeadInsts.insert(LI);
3936 Offsets.S->kill();
3937 }
3938
3939 // Second, we rewrite all of the split stores. At this point, we know that
3940 // all loads from this alloca have been split already. For stores of such
3941 // loads, we can simply look up the pre-existing split loads. For stores of
3942 // other loads, we split those loads first and then write split stores of
3943 // them.
3944 for (StoreInst *SI : Stores) {
3945 auto *LI = cast<LoadInst>(SI->getValueOperand());
3946 IntegerType *Ty = cast<IntegerType>(LI->getType());
3947 uint64_t StoreSize = Ty->getBitWidth() / 8;
3948 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3949
3950 auto &Offsets = SplitOffsetsMap[SI];
3951 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3952 "Slice size should always match load size exactly!");
3953 uint64_t BaseOffset = Offsets.S->beginOffset();
3954 assert(BaseOffset + StoreSize > BaseOffset &&
3955 "Cannot represent alloca access size using 64-bit integers!");
3956
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003957 Value *LoadBasePtr = LI->getPointerOperand();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003958 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3959
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003960 LLVM_DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003961
3962 // Check whether we have an already split load.
3963 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3964 std::vector<LoadInst *> *SplitLoads = nullptr;
3965 if (SplitLoadsMapI != SplitLoadsMap.end()) {
3966 SplitLoads = &SplitLoadsMapI->second;
3967 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3968 "Too few split loads for the number of splits in the store!");
3969 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003970 LLVM_DEBUG(dbgs() << " of load: " << *LI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003971 }
3972
Chandler Carruth0715cba2015-01-01 11:54:38 +00003973 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3974 int Idx = 0, Size = Offsets.Splits.size();
3975 for (;;) {
3976 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
Keno Fischer514a6a52017-06-02 19:04:17 +00003977 auto *LoadPartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3978 auto *StorePartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003979
3980 // Either lookup a split load or create one.
3981 LoadInst *PLoad;
3982 if (SplitLoads) {
3983 PLoad = (*SplitLoads)[Idx];
3984 } else {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003985 IRB.SetInsertPoint(LI);
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003986 auto AS = LI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003987 PLoad = IRB.CreateAlignedLoad(
James Y Knight14359ef2019-02-01 20:44:24 +00003988 PartTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003989 getAdjustedPtr(IRB, DL, LoadBasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003990 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Keno Fischer514a6a52017-06-02 19:04:17 +00003991 LoadPartPtrTy, LoadBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003992 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003993 LI->getName());
3994 }
3995
3996 // And store this partition.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003997 IRB.SetInsertPoint(SI);
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003998 auto AS = SI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003999 StoreInst *PStore = IRB.CreateAlignedStore(
Yaxun Liu6455b0d2017-06-09 20:46:29 +00004000 PLoad,
4001 getAdjustedPtr(IRB, DL, StoreBasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00004002 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Yaxun Liu6455b0d2017-06-09 20:46:29 +00004003 StorePartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004004 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Chandler Carruth0715cba2015-01-01 11:54:38 +00004005
4006 // Now build a new slice for the alloca.
4007 NewSlices.push_back(
4008 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
4009 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00004010 /*IsSplittable*/ false));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004011 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
4012 << ", " << NewSlices.back().endOffset()
4013 << "): " << *PStore << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00004014 if (!SplitLoads) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004015 LLVM_DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00004016 }
4017
Chandler Carruth29c22fa2015-01-02 00:10:22 +00004018 // See if we've finished all the splits.
4019 if (Idx >= Size)
4020 break;
4021
Chandler Carruth0715cba2015-01-01 11:54:38 +00004022 // Setup the next partition.
4023 PartOffset = Offsets.Splits[Idx];
4024 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00004025 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
4026 }
4027
4028 // We want to immediately iterate on any allocas impacted by splitting
4029 // this load, which is only relevant if it isn't a load of this alloca and
4030 // thus we didn't already split the loads above. We also have to keep track
4031 // of any promotable allocas we split loads on as they can no longer be
4032 // promoted.
4033 if (!SplitLoads) {
4034 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
4035 assert(OtherAI != &AI && "We can't re-split our own alloca!");
4036 ResplitPromotableAllocas.insert(OtherAI);
4037 Worklist.insert(OtherAI);
4038 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
4039 LoadBasePtr->stripInBoundsOffsets())) {
4040 assert(OtherAI != &AI && "We can't re-split our own alloca!");
4041 Worklist.insert(OtherAI);
4042 }
4043 }
4044
4045 // Mark the original store as dead now that we've split it up and kill its
Chandler Carruth24ac8302015-01-02 03:55:54 +00004046 // slice. Note that we leave the original load in place unless this store
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004047 // was its only use. It may in turn be split up if it is an alloca load
Chandler Carruth24ac8302015-01-02 03:55:54 +00004048 // for some other alloca, but it may be a normal load. This may introduce
4049 // redundant loads, but where those can be merged the rest of the optimizer
4050 // should handle the merging, and this uncovers SSA splits which is more
4051 // important. In practice, the original loads will almost always be fully
4052 // split and removed eventually, and the splits will be merged by any
4053 // trivial CSE, including instcombine.
4054 if (LI->hasOneUse()) {
4055 assert(*LI->user_begin() == SI && "Single use isn't this store!");
4056 DeadInsts.insert(LI);
4057 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00004058 DeadInsts.insert(SI);
4059 Offsets.S->kill();
4060 }
4061
Chandler Carruth24ac8302015-01-02 03:55:54 +00004062 // Remove the killed slices that have ben pre-split.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004063 AS.erase(llvm::remove_if(AS, [](const Slice &S) { return S.isDead(); }),
4064 AS.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +00004065
Chandler Carruth24ac8302015-01-02 03:55:54 +00004066 // Insert our new slices. This will sort and merge them into the sorted
4067 // sequence.
Chandler Carruth0715cba2015-01-01 11:54:38 +00004068 AS.insert(NewSlices);
4069
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004070 LLVM_DEBUG(dbgs() << " Pre-split slices:\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00004071#ifndef NDEBUG
4072 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004073 LLVM_DEBUG(AS.print(dbgs(), I, " "));
Chandler Carruth0715cba2015-01-01 11:54:38 +00004074#endif
4075
4076 // Finally, don't try to promote any allocas that new require re-splitting.
4077 // They have already been added to the worklist above.
4078 PromotableAllocas.erase(
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004079 llvm::remove_if(
David Majnemerc7004902016-08-12 04:32:37 +00004080 PromotableAllocas,
Chandler Carruth0715cba2015-01-01 11:54:38 +00004081 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
4082 PromotableAllocas.end());
4083
4084 return true;
4085}
4086
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004087/// Rewrite an alloca partition's users.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004088///
4089/// This routine drives both of the rewriting goals of the SROA pass. It tries
4090/// to rewrite uses of an alloca partition to be conducive for SSA value
4091/// promotion. If the partition needs a new, more refined alloca, this will
4092/// build that new alloca, preserving as much type information as possible, and
4093/// rewrite the uses of the old alloca to point at the new one and have the
4094/// appropriate new offsets. It also evaluates how successful the rewrite was
4095/// at enabling promotion and if it was successful queues the alloca to be
4096/// promoted.
Adrian Prantl565cc182015-01-20 19:42:22 +00004097AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruth29a18a42015-09-12 09:09:14 +00004098 Partition &P) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004099 // Try to compute a friendly type for this partition of the alloca. This
4100 // won't always succeed, in which case we fall back to a legal integer type
4101 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00004102 Type *SliceTy = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004103 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004104 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004105 if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004106 SliceTy = CommonUseTy;
4107 if (!SliceTy)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004108 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004109 P.beginOffset(), P.size()))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004110 SliceTy = TypePartitionTy;
4111 if ((!SliceTy || (SliceTy->isArrayTy() &&
4112 SliceTy->getArrayElementType()->isIntegerTy())) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004113 DL.isLegalInteger(P.size() * 8))
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004114 SliceTy = Type::getIntNTy(*C, P.size() * 8);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004115 if (!SliceTy)
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004116 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004117 assert(DL.getTypeAllocSize(SliceTy) >= P.size());
Chandler Carruthf0546402013-07-18 07:15:00 +00004118
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004119 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00004120
Chandler Carruth2dc96822014-10-18 00:44:02 +00004121 VectorType *VecTy =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004122 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
Chandler Carruth2dc96822014-10-18 00:44:02 +00004123 if (VecTy)
4124 SliceTy = VecTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004125
4126 // Check for the case where we're going to rewrite to a new alloca of the
4127 // exact same type as the original, and with the same access offsets. In that
4128 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00004129 // perform phi and select speculation.
Hiroshi Inoue99a8faa2018-01-16 06:23:05 +00004130 // P.beginOffset() can be non-zero even with the same type in a case with
4131 // out-of-bounds access (e.g. @PR35657 function in SROA/basictest.ll).
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004132 AllocaInst *NewAI;
Hiroshi Inoue99a8faa2018-01-16 06:23:05 +00004133 if (SliceTy == AI.getAllocatedType() && P.beginOffset() == 0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004134 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00004135 // FIXME: We should be able to bail at this point with "nothing changed".
4136 // FIXME: We might want to defer PHI speculation until after here.
Adrian Prantl565cc182015-01-20 19:42:22 +00004137 // FIXME: return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004138 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00004139 unsigned Alignment = AI.getAlignment();
4140 if (!Alignment) {
4141 // The minimum alignment which users can rely on when the explicit
4142 // alignment is omitted or zero is that required by the ABI for this
4143 // type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004144 Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00004145 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004146 Alignment = MinAlign(Alignment, P.beginOffset());
Chandler Carruth903790e2012-09-29 10:41:21 +00004147 // If we will get at least this much alignment from the type alone, leave
4148 // the alloca's alignment unconstrained.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004149 if (Alignment <= DL.getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00004150 Alignment = 0;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004151 NewAI = new AllocaInst(
Matt Arsenault3c1fc762017-04-10 22:27:50 +00004152 SliceTy, AI.getType()->getAddressSpace(), nullptr, Alignment,
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004153 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
Anastasis Grammenos425df222018-06-28 18:58:30 +00004154 // Copy the old AI debug location over to the new one.
4155 NewAI->setDebugLoc(AI.getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004156 ++NumNewAllocas;
4157 }
4158
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004159 LLVM_DEBUG(dbgs() << "Rewriting alloca partition "
4160 << "[" << P.beginOffset() << "," << P.endOffset()
4161 << ") to: " << *NewAI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004162
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004163 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00004164 // promoted allocas. We will reset it to this point if the alloca is not in
4165 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00004166 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00004167 unsigned NumUses = 0;
Davide Italiano81a26da2017-04-27 23:09:01 +00004168 SmallSetVector<PHINode *, 8> PHIUsers;
4169 SmallSetVector<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00004170
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004171 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004172 P.endOffset(), IsIntegerPromotable, VecTy,
4173 PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00004174 bool Promotable = true;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00004175 for (Slice *S : P.splitSliceTails()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004176 Promotable &= Rewriter.visit(S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004177 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00004178 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004179 for (Slice &S : P) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004180 Promotable &= Rewriter.visit(&S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004181 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00004182 }
4183
Chandler Carruth6c321c12013-07-19 10:57:36 +00004184 NumAllocaPartitionUses += NumUses;
Craig Topper8a950272017-05-18 00:51:39 +00004185 MaxUsesPerAllocaPartition.updateMax(NumUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004186
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004187 // Now that we've processed all the slices in the new partition, check if any
4188 // PHIs or Selects would block promotion.
Davide Italiano81a26da2017-04-27 23:09:01 +00004189 for (PHINode *PHI : PHIUsers)
4190 if (!isSafePHIToSpeculate(*PHI)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004191 Promotable = false;
4192 PHIUsers.clear();
4193 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00004194 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004195 }
Davide Italiano81a26da2017-04-27 23:09:01 +00004196
4197 for (SelectInst *Sel : SelectUsers)
4198 if (!isSafeSelectToSpeculate(*Sel)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004199 Promotable = false;
4200 PHIUsers.clear();
4201 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00004202 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004203 }
4204
4205 if (Promotable) {
4206 if (PHIUsers.empty() && SelectUsers.empty()) {
4207 // Promote the alloca.
4208 PromotableAllocas.push_back(NewAI);
4209 } else {
4210 // If we have either PHIs or Selects to speculate, add them to those
4211 // worklists and re-queue the new alloca so that we promote in on the
4212 // next iteration.
Chandler Carruth61747042014-10-16 21:05:14 +00004213 for (PHINode *PHIUser : PHIUsers)
4214 SpeculatablePHIs.insert(PHIUser);
4215 for (SelectInst *SelectUser : SelectUsers)
4216 SpeculatableSelects.insert(SelectUser);
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004217 Worklist.insert(NewAI);
4218 }
4219 } else {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004220 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00004221 while (PostPromotionWorklist.size() > PPWOldSize)
4222 PostPromotionWorklist.pop_back();
David Majnemer30ffc4c2016-04-26 01:05:00 +00004223
4224 // We couldn't promote and we didn't create a new partition, nothing
4225 // happened.
4226 if (NewAI == &AI)
4227 return nullptr;
4228
4229 // If we can't promote the alloca, iterate on it to check for new
4230 // refinements exposed by splitting the current alloca. Don't iterate on an
4231 // alloca which didn't actually change and didn't get promoted.
4232 Worklist.insert(NewAI);
Chandler Carruthf0546402013-07-18 07:15:00 +00004233 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00004234
Adrian Prantl565cc182015-01-20 19:42:22 +00004235 return NewAI;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004236}
4237
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004238/// Walks the slices of an alloca and form partitions based on them,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004239/// rewriting each of their uses.
Chandler Carruth83934062014-10-16 21:11:55 +00004240bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
4241 if (AS.begin() == AS.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00004242 return false;
4243
Chandler Carruth6c321c12013-07-19 10:57:36 +00004244 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004245 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004246 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00004247
Chandler Carruth24ac8302015-01-02 03:55:54 +00004248 // First try to pre-split loads and stores.
Chandler Carruth0715cba2015-01-01 11:54:38 +00004249 Changed |= presplitLoadsAndStores(AI, AS);
4250
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004251 // Now that we have identified any pre-splitting opportunities,
4252 // mark loads and stores unsplittable except for the following case.
4253 // We leave a slice splittable if all other slices are disjoint or fully
4254 // included in the slice, such as whole-alloca loads and stores.
4255 // If we fail to split these during pre-splitting, we want to force them
4256 // to be rewritten into a partition.
Chandler Carruth24ac8302015-01-02 03:55:54 +00004257 bool IsSorted = true;
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004258
4259 uint64_t AllocaSize = DL.getTypeAllocSize(AI.getAllocatedType());
4260 const uint64_t MaxBitVectorSize = 1024;
Hiroshi Inoue99a8faa2018-01-16 06:23:05 +00004261 if (AllocaSize <= MaxBitVectorSize) {
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004262 // If a byte boundary is included in any load or store, a slice starting or
4263 // ending at the boundary is not splittable.
4264 SmallBitVector SplittableOffset(AllocaSize + 1, true);
4265 for (Slice &S : AS)
4266 for (unsigned O = S.beginOffset() + 1;
4267 O < S.endOffset() && O < AllocaSize; O++)
4268 SplittableOffset.reset(O);
4269
4270 for (Slice &S : AS) {
4271 if (!S.isSplittable())
4272 continue;
4273
4274 if ((S.beginOffset() > AllocaSize || SplittableOffset[S.beginOffset()]) &&
4275 (S.endOffset() > AllocaSize || SplittableOffset[S.endOffset()]))
4276 continue;
4277
4278 if (isa<LoadInst>(S.getUse()->getUser()) ||
4279 isa<StoreInst>(S.getUse()->getUser())) {
4280 S.makeUnsplittable();
4281 IsSorted = false;
4282 }
Chandler Carruth24ac8302015-01-02 03:55:54 +00004283 }
4284 }
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004285 else {
4286 // We only allow whole-alloca splittable loads and stores
4287 // for a large alloca to avoid creating too large BitVector.
4288 for (Slice &S : AS) {
4289 if (!S.isSplittable())
4290 continue;
4291
4292 if (S.beginOffset() == 0 && S.endOffset() >= AllocaSize)
4293 continue;
4294
4295 if (isa<LoadInst>(S.getUse()->getUser()) ||
4296 isa<StoreInst>(S.getUse()->getUser())) {
4297 S.makeUnsplittable();
4298 IsSorted = false;
4299 }
4300 }
4301 }
4302
Chandler Carruth24ac8302015-01-02 03:55:54 +00004303 if (!IsSorted)
Fangrui Song0cac7262018-09-27 02:13:45 +00004304 llvm::sort(AS);
Chandler Carruth24ac8302015-01-02 03:55:54 +00004305
Adrian Prantl941fa752016-12-05 18:04:47 +00004306 /// Describes the allocas introduced by rewritePartition in order to migrate
4307 /// the debug info.
4308 struct Fragment {
Adrian Prantl565cc182015-01-20 19:42:22 +00004309 AllocaInst *Alloca;
4310 uint64_t Offset;
4311 uint64_t Size;
Adrian Prantl941fa752016-12-05 18:04:47 +00004312 Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
Adrian Prantl565cc182015-01-20 19:42:22 +00004313 : Alloca(AI), Offset(O), Size(S) {}
4314 };
Adrian Prantl941fa752016-12-05 18:04:47 +00004315 SmallVector<Fragment, 4> Fragments;
Adrian Prantl565cc182015-01-20 19:42:22 +00004316
Chandler Carruth0715cba2015-01-01 11:54:38 +00004317 // Rewrite each partition.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004318 for (auto &P : AS.partitions()) {
Adrian Prantl565cc182015-01-20 19:42:22 +00004319 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4320 Changed = true;
Adrian Prantl34e75902015-02-09 23:57:22 +00004321 if (NewAI != &AI) {
4322 uint64_t SizeOfByte = 8;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004323 uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
Adrian Prantl34e75902015-02-09 23:57:22 +00004324 // Don't include any padding.
4325 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
Adrian Prantl941fa752016-12-05 18:04:47 +00004326 Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
Adrian Prantl34e75902015-02-09 23:57:22 +00004327 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004328 }
Chandler Carruth6c321c12013-07-19 10:57:36 +00004329 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00004330 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004331
Chandler Carruth6c321c12013-07-19 10:57:36 +00004332 NumAllocaPartitions += NumPartitions;
Craig Topper8a950272017-05-18 00:51:39 +00004333 MaxPartitionsPerAlloca.updateMax(NumPartitions);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004334
Adrian Prantl565cc182015-01-20 19:42:22 +00004335 // Migrate debug information from the old alloca to the new alloca(s)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004336 // and the individual partitions.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00004337 TinyPtrVector<DbgVariableIntrinsic *> DbgDeclares = FindDbgAddrUses(&AI);
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004338 if (!DbgDeclares.empty()) {
4339 auto *Var = DbgDeclares.front()->getVariable();
4340 auto *Expr = DbgDeclares.front()->getExpression();
Adrian Prantld7f6f162017-11-28 00:57:53 +00004341 auto VarSize = Var->getSizeInBits();
Sanjay Patelaf674fb2015-12-14 17:24:23 +00004342 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
Keno Fischerd5354fd2016-01-14 20:06:34 +00004343 uint64_t AllocaSize = DL.getTypeSizeInBits(AI.getAllocatedType());
Adrian Prantl941fa752016-12-05 18:04:47 +00004344 for (auto Fragment : Fragments) {
4345 // Create a fragment expression describing the new partition or reuse AI's
Adrian Prantl565cc182015-01-20 19:42:22 +00004346 // expression if there is only one partition.
Adrian Prantl941fa752016-12-05 18:04:47 +00004347 auto *FragmentExpr = Expr;
4348 if (Fragment.Size < AllocaSize || Expr->isFragment()) {
Adrian Prantl152ac392015-02-01 00:58:04 +00004349 // If this alloca is already a scalar replacement of a larger aggregate,
Adrian Prantl941fa752016-12-05 18:04:47 +00004350 // Fragment.Offset describes the offset inside the scalar.
Adrian Prantl49797ca2016-12-22 05:27:12 +00004351 auto ExprFragment = Expr->getFragmentInfo();
4352 uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0;
Adrian Prantl941fa752016-12-05 18:04:47 +00004353 uint64_t Start = Offset + Fragment.Offset;
4354 uint64_t Size = Fragment.Size;
Adrian Prantl49797ca2016-12-22 05:27:12 +00004355 if (ExprFragment) {
Adrian Prantl941fa752016-12-05 18:04:47 +00004356 uint64_t AbsEnd =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00004357 ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
Adrian Prantl34e75902015-02-09 23:57:22 +00004358 if (Start >= AbsEnd)
4359 // No need to describe a SROAed padding.
4360 continue;
4361 Size = std::min(Size, AbsEnd - Start);
4362 }
Adrian Prantlb192b542017-08-30 20:04:17 +00004363 // The new, smaller fragment is stenciled out from the old fragment.
4364 if (auto OrigFragment = FragmentExpr->getFragmentInfo()) {
4365 assert(Start >= OrigFragment->OffsetInBits &&
4366 "new fragment is outside of original fragment");
4367 Start -= OrigFragment->OffsetInBits;
4368 }
Adrian Prantl77d90b02017-11-28 21:30:38 +00004369
4370 // The alloca may be larger than the variable.
4371 if (VarSize) {
4372 if (Size > *VarSize)
4373 Size = *VarSize;
4374 if (Size == 0 || Start + Size > *VarSize)
4375 continue;
4376 }
4377
Adrian Prantld7f6f162017-11-28 00:57:53 +00004378 // Avoid creating a fragment expression that covers the entire variable.
4379 if (!VarSize || *VarSize != Size) {
4380 if (auto E =
4381 DIExpression::createFragmentExpression(Expr, Start, Size))
4382 FragmentExpr = *E;
4383 else
4384 continue;
4385 }
Adrian Prantl152ac392015-02-01 00:58:04 +00004386 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004387
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004388 // Remove any existing intrinsics describing the same alloca.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00004389 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(Fragment.Alloca))
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004390 OldDII->eraseFromParent();
Adrian Prantl565cc182015-01-20 19:42:22 +00004391
Adrian Prantl941fa752016-12-05 18:04:47 +00004392 DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr,
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004393 DbgDeclares.front()->getDebugLoc(), &AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004394 }
4395 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004396 return Changed;
4397}
4398
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004399/// Clobber a use with undef, deleting the used value if it becomes dead.
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004400void SROA::clobberUse(Use &U) {
4401 Value *OldV = U;
4402 // Replace the use with an undef value.
4403 U = UndefValue::get(OldV->getType());
4404
4405 // Check for this making an instruction dead. We have to garbage collect
4406 // all the dead instructions to ensure the uses of any alloca end up being
4407 // minimal.
4408 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4409 if (isInstructionTriviallyDead(OldI)) {
4410 DeadInsts.insert(OldI);
4411 }
4412}
4413
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004414/// Analyze an alloca for SROA.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004415///
4416/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004417/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004418/// rewritten as needed.
4419bool SROA::runOnAlloca(AllocaInst &AI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004420 LLVM_DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004421 ++NumAllocasAnalyzed;
4422
4423 // Special case dead allocas, as they're trivial.
4424 if (AI.use_empty()) {
4425 AI.eraseFromParent();
4426 return true;
4427 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004428 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004429
4430 // Skip alloca forms that this analysis can't handle.
4431 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004432 DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004433 return false;
4434
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004435 bool Changed = false;
4436
4437 // First, split any FCA loads and stores touching this alloca to promote
4438 // better splitting and promotion opportunities.
Tim Northover856628f2018-12-18 09:29:39 +00004439 AggLoadStoreRewriter AggRewriter(DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004440 Changed |= AggRewriter.rewrite(AI);
4441
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004442 // Build the slices using a recursive instruction-visiting builder.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004443 AllocaSlices AS(DL, AI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004444 LLVM_DEBUG(AS.print(dbgs()));
Chandler Carruth83934062014-10-16 21:11:55 +00004445 if (AS.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004446 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004447
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004448 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth83934062014-10-16 21:11:55 +00004449 for (Instruction *DeadUser : AS.getDeadUsers()) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004450 // Free up everything used by this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004451 for (Use &DeadOp : DeadUser->operands())
Chandler Carruth1583e992014-03-03 10:42:58 +00004452 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004453
4454 // Now replace the uses of this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004455 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004456
4457 // And mark it for deletion.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004458 DeadInsts.insert(DeadUser);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004459 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004460 }
Chandler Carruth83934062014-10-16 21:11:55 +00004461 for (Use *DeadOp : AS.getDeadOperands()) {
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004462 clobberUse(*DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004463 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004464 }
4465
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004466 // No slices to split. Leave the dead alloca for a later pass to clean up.
Chandler Carruth83934062014-10-16 21:11:55 +00004467 if (AS.begin() == AS.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00004468 return Changed;
4469
Chandler Carruth83934062014-10-16 21:11:55 +00004470 Changed |= splitAlloca(AI, AS);
Chandler Carruthf0546402013-07-18 07:15:00 +00004471
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004472 LLVM_DEBUG(dbgs() << " Speculating PHIs\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00004473 while (!SpeculatablePHIs.empty())
4474 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4475
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004476 LLVM_DEBUG(dbgs() << " Speculating Selects\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00004477 while (!SpeculatableSelects.empty())
4478 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4479
4480 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004481}
4482
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004483/// Delete the dead instructions accumulated in this run.
Chandler Carruth19450da2012-09-14 10:26:38 +00004484///
4485/// Recursively deletes the dead instructions we've accumulated. This is done
4486/// at the very end to maximize locality of the recursive delete and to
4487/// minimize the problems of invalidated instruction pointers as such pointers
4488/// are used heavily in the intermediate stages of the algorithm.
4489///
4490/// We also record the alloca instructions deleted here so that they aren't
4491/// subsequently handed to mem2reg to promote.
Teresa Johnson33090022017-11-20 18:33:38 +00004492bool SROA::deleteDeadInstructions(
Chandler Carruth113dc642014-12-20 02:39:18 +00004493 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
Teresa Johnson33090022017-11-20 18:33:38 +00004494 bool Changed = false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004495 while (!DeadInsts.empty()) {
4496 Instruction *I = DeadInsts.pop_back_val();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004497 LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004498
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004499 // If the instruction is an alloca, find the possible dbg.declare connected
4500 // to it, and remove it too. We must do this before calling RAUW or we will
4501 // not be able to find it.
4502 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4503 DeletedAllocas.insert(AI);
Hsiangkai Wangef72e482018-08-06 03:59:47 +00004504 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(AI))
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004505 OldDII->eraseFromParent();
4506 }
4507
Chandler Carruth58d05562012-10-25 04:37:07 +00004508 I->replaceAllUsesWith(UndefValue::get(I->getType()));
4509
Chandler Carruth1583e992014-03-03 10:42:58 +00004510 for (Use &Operand : I->operands())
4511 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004512 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00004513 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004514 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00004515 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004516 }
4517
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004518 ++NumDeleted;
4519 I->eraseFromParent();
Teresa Johnson33090022017-11-20 18:33:38 +00004520 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004521 }
Teresa Johnson33090022017-11-20 18:33:38 +00004522 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004523}
4524
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004525/// Promote the allocas, using the best available technique.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004526///
4527/// This attempts to promote whatever allocas have been identified as viable in
4528/// the PromotableAllocas list. If that list is empty, there is nothing to do.
Chandler Carruth748d0952015-08-26 09:09:29 +00004529/// This function returns whether any promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004530bool SROA::promoteAllocas(Function &F) {
4531 if (PromotableAllocas.empty())
4532 return false;
4533
4534 NumPromoted += PromotableAllocas.size();
4535
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004536 LLVM_DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Davide Italiano612d5a92017-04-09 20:47:14 +00004537 PromoteMemToReg(PromotableAllocas, *DT, AC);
Chandler Carruth70b44c52012-09-15 11:43:14 +00004538 PromotableAllocas.clear();
4539 return true;
4540}
4541
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004542PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT,
4543 AssumptionCache &RunAC) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004544 LLVM_DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004545 C = &F.getContext();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004546 DT = &RunDT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004547 AC = &RunAC;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004548
4549 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00004550 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Adrian Prantl565cc182015-01-20 19:42:22 +00004551 I != E; ++I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004552 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4553 Worklist.insert(AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004554 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004555
4556 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00004557 // A set of deleted alloca instruction pointers which should be removed from
4558 // the list of promotable allocas.
4559 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4560
Chandler Carruthac8317f2012-10-04 12:33:50 +00004561 do {
4562 while (!Worklist.empty()) {
4563 Changed |= runOnAlloca(*Worklist.pop_back_val());
Teresa Johnson33090022017-11-20 18:33:38 +00004564 Changed |= deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00004565
Chandler Carruthac8317f2012-10-04 12:33:50 +00004566 // Remove the deleted allocas from various lists so that we don't try to
4567 // continue processing them.
4568 if (!DeletedAllocas.empty()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00004569 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00004570 Worklist.remove_if(IsInSet);
4571 PostPromotionWorklist.remove_if(IsInSet);
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004572 PromotableAllocas.erase(llvm::remove_if(PromotableAllocas, IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00004573 PromotableAllocas.end());
4574 DeletedAllocas.clear();
4575 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004576 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004577
Chandler Carruthac8317f2012-10-04 12:33:50 +00004578 Changed |= promoteAllocas(F);
4579
4580 Worklist = PostPromotionWorklist;
4581 PostPromotionWorklist.clear();
4582 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004583
Davide Italiano16e96d42016-06-07 13:21:17 +00004584 if (!Changed)
4585 return PreservedAnalyses::all();
4586
Davide Italiano16e96d42016-06-07 13:21:17 +00004587 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00004588 PA.preserveSet<CFGAnalyses>();
Davide Italiano16e96d42016-06-07 13:21:17 +00004589 PA.preserve<GlobalsAA>();
4590 return PA;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004591}
4592
Sean Silva36e0d012016-08-09 00:28:15 +00004593PreservedAnalyses SROA::run(Function &F, FunctionAnalysisManager &AM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004594 return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F),
4595 AM.getResult<AssumptionAnalysis>(F));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004596}
Chandler Carruth29a18a42015-09-12 09:09:14 +00004597
4598/// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
4599///
4600/// This is in the llvm namespace purely to allow it to be a friend of the \c
4601/// SROA pass.
4602class llvm::sroa::SROALegacyPass : public FunctionPass {
4603 /// The SROA implementation.
4604 SROA Impl;
4605
4606public:
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004607 static char ID;
4608
Chandler Carruth29a18a42015-09-12 09:09:14 +00004609 SROALegacyPass() : FunctionPass(ID) {
4610 initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
4611 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004612
Chandler Carruth29a18a42015-09-12 09:09:14 +00004613 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00004614 if (skipFunction(F))
Chandler Carruth29a18a42015-09-12 09:09:14 +00004615 return false;
4616
4617 auto PA = Impl.runImpl(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004618 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4619 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
Chandler Carruth29a18a42015-09-12 09:09:14 +00004620 return !PA.areAllPreserved();
4621 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004622
Chandler Carruth29a18a42015-09-12 09:09:14 +00004623 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004624 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004625 AU.addRequired<DominatorTreeWrapperPass>();
4626 AU.addPreserved<GlobalsAAWrapperPass>();
4627 AU.setPreservesCFG();
4628 }
4629
Mehdi Amini117296c2016-10-01 02:56:57 +00004630 StringRef getPassName() const override { return "SROA"; }
Chandler Carruth29a18a42015-09-12 09:09:14 +00004631};
4632
4633char SROALegacyPass::ID = 0;
4634
4635FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); }
4636
4637INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
4638 "Scalar Replacement Of Aggregates", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004639INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth29a18a42015-09-12 09:09:14 +00004640INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4641INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
4642 false, false)