Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/lib/Transforms/Scalar/SROA.cpp
Warning:line 2903, column 54
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SROA.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/lib/Transforms/Scalar -I include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-10-03-140002-15933-1 -x c++ /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/lib/Transforms/Scalar/SROA.cpp
1//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2//
3// 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
6//
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
25#include "llvm/Transforms/Scalar/SROA.h"
26#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/PointerIntPair.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/SetVector.h"
32#include "llvm/ADT/SmallBitVector.h"
33#include "llvm/ADT/SmallPtrSet.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/ADT/StringRef.h"
37#include "llvm/ADT/Twine.h"
38#include "llvm/ADT/iterator.h"
39#include "llvm/ADT/iterator_range.h"
40#include "llvm/Analysis/AssumptionCache.h"
41#include "llvm/Analysis/GlobalsModRef.h"
42#include "llvm/Analysis/Loads.h"
43#include "llvm/Analysis/PtrUseVisitor.h"
44#include "llvm/Config/llvm-config.h"
45#include "llvm/IR/BasicBlock.h"
46#include "llvm/IR/Constant.h"
47#include "llvm/IR/ConstantFolder.h"
48#include "llvm/IR/Constants.h"
49#include "llvm/IR/DIBuilder.h"
50#include "llvm/IR/DataLayout.h"
51#include "llvm/IR/DebugInfo.h"
52#include "llvm/IR/DebugInfoMetadata.h"
53#include "llvm/IR/DerivedTypes.h"
54#include "llvm/IR/Dominators.h"
55#include "llvm/IR/Function.h"
56#include "llvm/IR/GetElementPtrTypeIterator.h"
57#include "llvm/IR/GlobalAlias.h"
58#include "llvm/IR/IRBuilder.h"
59#include "llvm/IR/InstVisitor.h"
60#include "llvm/IR/Instruction.h"
61#include "llvm/IR/Instructions.h"
62#include "llvm/IR/IntrinsicInst.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/Metadata.h"
65#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
67#include "llvm/IR/PassManager.h"
68#include "llvm/IR/Type.h"
69#include "llvm/IR/Use.h"
70#include "llvm/IR/User.h"
71#include "llvm/IR/Value.h"
72#include "llvm/InitializePasses.h"
73#include "llvm/Pass.h"
74#include "llvm/Support/Casting.h"
75#include "llvm/Support/CommandLine.h"
76#include "llvm/Support/Compiler.h"
77#include "llvm/Support/Debug.h"
78#include "llvm/Support/ErrorHandling.h"
79#include "llvm/Support/raw_ostream.h"
80#include "llvm/Transforms/Scalar.h"
81#include "llvm/Transforms/Utils/Local.h"
82#include "llvm/Transforms/Utils/PromoteMemToReg.h"
83#include <algorithm>
84#include <cassert>
85#include <cstddef>
86#include <cstdint>
87#include <cstring>
88#include <iterator>
89#include <string>
90#include <tuple>
91#include <utility>
92#include <vector>
93
94using namespace llvm;
95using namespace llvm::sroa;
96
97#define DEBUG_TYPE"sroa" "sroa"
98
99STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement")static llvm::Statistic NumAllocasAnalyzed = {"sroa", "NumAllocasAnalyzed"
, "Number of allocas analyzed for replacement"}
;
100STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed")static llvm::Statistic NumAllocaPartitions = {"sroa", "NumAllocaPartitions"
, "Number of alloca partitions formed"}
;
101STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca")static llvm::Statistic MaxPartitionsPerAlloca = {"sroa", "MaxPartitionsPerAlloca"
, "Maximum number of partitions per alloca"}
;
102STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten")static llvm::Statistic NumAllocaPartitionUses = {"sroa", "NumAllocaPartitionUses"
, "Number of alloca partition uses rewritten"}
;
103STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition")static llvm::Statistic MaxUsesPerAllocaPartition = {"sroa", "MaxUsesPerAllocaPartition"
, "Maximum number of uses of a partition"}
;
104STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced")static llvm::Statistic NumNewAllocas = {"sroa", "NumNewAllocas"
, "Number of new, smaller allocas introduced"}
;
105STATISTIC(NumPromoted, "Number of allocas promoted to SSA values")static llvm::Statistic NumPromoted = {"sroa", "NumPromoted", "Number of allocas promoted to SSA values"
}
;
106STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion")static llvm::Statistic NumLoadsSpeculated = {"sroa", "NumLoadsSpeculated"
, "Number of loads speculated to allow promotion"}
;
107STATISTIC(NumDeleted, "Number of instructions deleted")static llvm::Statistic NumDeleted = {"sroa", "NumDeleted", "Number of instructions deleted"
}
;
108STATISTIC(NumVectorized, "Number of vectorized aggregates")static llvm::Statistic NumVectorized = {"sroa", "NumVectorized"
, "Number of vectorized aggregates"}
;
109
110/// Hidden option to experiment with completely strict handling of inbounds
111/// GEPs.
112static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
113 cl::Hidden);
114
115namespace {
116
117/// A custom IRBuilder inserter which prefixes all names, but only in
118/// Assert builds.
119class IRBuilderPrefixedInserter final : public IRBuilderDefaultInserter {
120 std::string Prefix;
121
122 Twine getNameWithPrefix(const Twine &Name) const {
123 return Name.isTriviallyEmpty() ? Name : Prefix + Name;
124 }
125
126public:
127 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
128
129 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
130 BasicBlock::iterator InsertPt) const override {
131 IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name), BB,
132 InsertPt);
133 }
134};
135
136/// Provide a type for IRBuilder that drops names in release builds.
137using IRBuilderTy = IRBuilder<ConstantFolder, IRBuilderPrefixedInserter>;
138
139/// A used slice of an alloca.
140///
141/// This structure represents a slice of an alloca used by some instruction. It
142/// stores both the begin and end offsets of this use, a pointer to the use
143/// itself, and a flag indicating whether we can classify the use as splittable
144/// or not when forming partitions of the alloca.
145class Slice {
146 /// The beginning offset of the range.
147 uint64_t BeginOffset = 0;
148
149 /// The ending offset, not included in the range.
150 uint64_t EndOffset = 0;
151
152 /// Storage for both the use of this slice and whether it can be
153 /// split.
154 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
155
156public:
157 Slice() = default;
158
159 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
160 : BeginOffset(BeginOffset), EndOffset(EndOffset),
161 UseAndIsSplittable(U, IsSplittable) {}
162
163 uint64_t beginOffset() const { return BeginOffset; }
164 uint64_t endOffset() const { return EndOffset; }
165
166 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
167 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
168
169 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
170
171 bool isDead() const { return getUse() == nullptr; }
172 void kill() { UseAndIsSplittable.setPointer(nullptr); }
173
174 /// Support for ordering ranges.
175 ///
176 /// This provides an ordering over ranges such that start offsets are
177 /// always increasing, and within equal start offsets, the end offsets are
178 /// decreasing. Thus the spanning range comes first in a cluster with the
179 /// same start position.
180 bool operator<(const Slice &RHS) const {
181 if (beginOffset() < RHS.beginOffset())
182 return true;
183 if (beginOffset() > RHS.beginOffset())
184 return false;
185 if (isSplittable() != RHS.isSplittable())
186 return !isSplittable();
187 if (endOffset() > RHS.endOffset())
188 return true;
189 return false;
190 }
191
192 /// Support comparison with a single offset to allow binary searches.
193 friend LLVM_ATTRIBUTE_UNUSED__attribute__((__unused__)) bool operator<(const Slice &LHS,
194 uint64_t RHSOffset) {
195 return LHS.beginOffset() < RHSOffset;
196 }
197 friend LLVM_ATTRIBUTE_UNUSED__attribute__((__unused__)) bool operator<(uint64_t LHSOffset,
198 const Slice &RHS) {
199 return LHSOffset < RHS.beginOffset();
200 }
201
202 bool operator==(const Slice &RHS) const {
203 return isSplittable() == RHS.isSplittable() &&
204 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
205 }
206 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
207};
208
209} // end anonymous namespace
210
211/// Representation of the alloca slices.
212///
213/// This class represents the slices of an alloca which are formed by its
214/// various uses. If a pointer escapes, we can't fully build a representation
215/// for the slices used and we reflect that in this structure. The uses are
216/// stored, sorted by increasing beginning offset and with unsplittable slices
217/// starting at a particular offset before splittable slices.
218class llvm::sroa::AllocaSlices {
219public:
220 /// Construct the slices of a particular alloca.
221 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
222
223 /// Test whether a pointer to the allocation escapes our analysis.
224 ///
225 /// If this is true, the slices are never fully built and should be
226 /// ignored.
227 bool isEscaped() const { return PointerEscapingInstr; }
228
229 /// Support for iterating over the slices.
230 /// @{
231 using iterator = SmallVectorImpl<Slice>::iterator;
232 using range = iterator_range<iterator>;
233
234 iterator begin() { return Slices.begin(); }
235 iterator end() { return Slices.end(); }
236
237 using const_iterator = SmallVectorImpl<Slice>::const_iterator;
238 using const_range = iterator_range<const_iterator>;
239
240 const_iterator begin() const { return Slices.begin(); }
241 const_iterator end() const { return Slices.end(); }
242 /// @}
243
244 /// Erase a range of slices.
245 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
246
247 /// Insert new slices for this alloca.
248 ///
249 /// This moves the slices into the alloca's slices collection, and re-sorts
250 /// everything so that the usual ordering properties of the alloca's slices
251 /// hold.
252 void insert(ArrayRef<Slice> NewSlices) {
253 int OldSize = Slices.size();
254 Slices.append(NewSlices.begin(), NewSlices.end());
255 auto SliceI = Slices.begin() + OldSize;
256 llvm::sort(SliceI, Slices.end());
257 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
258 }
259
260 // Forward declare the iterator and range accessor for walking the
261 // partitions.
262 class partition_iterator;
263 iterator_range<partition_iterator> partitions();
264
265 /// Access the dead users for this alloca.
266 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
267
268 /// Access Uses that should be dropped if the alloca is promotable.
269 ArrayRef<Use *> getDeadUsesIfPromotable() const {
270 return DeadUseIfPromotable;
271 }
272
273 /// Access the dead operands referring to this alloca.
274 ///
275 /// These are operands which have cannot actually be used to refer to the
276 /// alloca as they are outside its range and the user doesn't correct for
277 /// that. These mostly consist of PHI node inputs and the like which we just
278 /// need to replace with undef.
279 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
280
281#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
282 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
283 void printSlice(raw_ostream &OS, const_iterator I,
284 StringRef Indent = " ") const;
285 void printUse(raw_ostream &OS, const_iterator I,
286 StringRef Indent = " ") const;
287 void print(raw_ostream &OS) const;
288 void dump(const_iterator I) const;
289 void dump() const;
290#endif
291
292private:
293 template <typename DerivedT, typename RetT = void> class BuilderBase;
294 class SliceBuilder;
295
296 friend class AllocaSlices::SliceBuilder;
297
298#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
299 /// Handle to alloca instruction to simplify method interfaces.
300 AllocaInst &AI;
301#endif
302
303 /// The instruction responsible for this alloca not having a known set
304 /// of slices.
305 ///
306 /// When an instruction (potentially) escapes the pointer to the alloca, we
307 /// store a pointer to that here and abort trying to form slices of the
308 /// alloca. This will be null if the alloca slices are analyzed successfully.
309 Instruction *PointerEscapingInstr;
310
311 /// The slices of the alloca.
312 ///
313 /// We store a vector of the slices formed by uses of the alloca here. This
314 /// vector is sorted by increasing begin offset, and then the unsplittable
315 /// slices before the splittable ones. See the Slice inner class for more
316 /// details.
317 SmallVector<Slice, 8> Slices;
318
319 /// Instructions which will become dead if we rewrite the alloca.
320 ///
321 /// Note that these are not separated by slice. This is because we expect an
322 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
323 /// all these instructions can simply be removed and replaced with poison as
324 /// they come from outside of the allocated space.
325 SmallVector<Instruction *, 8> DeadUsers;
326
327 /// Uses which will become dead if can promote the alloca.
328 SmallVector<Use *, 8> DeadUseIfPromotable;
329
330 /// Operands which will become dead if we rewrite the alloca.
331 ///
332 /// These are operands that in their particular use can be replaced with
333 /// poison when we rewrite the alloca. These show up in out-of-bounds inputs
334 /// to PHI nodes and the like. They aren't entirely dead (there might be
335 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
336 /// want to swap this particular input for poison to simplify the use lists of
337 /// the alloca.
338 SmallVector<Use *, 8> DeadOperands;
339};
340
341/// A partition of the slices.
342///
343/// An ephemeral representation for a range of slices which can be viewed as
344/// a partition of the alloca. This range represents a span of the alloca's
345/// memory which cannot be split, and provides access to all of the slices
346/// overlapping some part of the partition.
347///
348/// Objects of this type are produced by traversing the alloca's slices, but
349/// are only ephemeral and not persistent.
350class llvm::sroa::Partition {
351private:
352 friend class AllocaSlices;
353 friend class AllocaSlices::partition_iterator;
354
355 using iterator = AllocaSlices::iterator;
356
357 /// The beginning and ending offsets of the alloca for this
358 /// partition.
359 uint64_t BeginOffset = 0, EndOffset = 0;
360
361 /// The start and end iterators of this partition.
362 iterator SI, SJ;
363
364 /// A collection of split slice tails overlapping the partition.
365 SmallVector<Slice *, 4> SplitTails;
366
367 /// Raw constructor builds an empty partition starting and ending at
368 /// the given iterator.
369 Partition(iterator SI) : SI(SI), SJ(SI) {}
370
371public:
372 /// The start offset of this partition.
373 ///
374 /// All of the contained slices start at or after this offset.
375 uint64_t beginOffset() const { return BeginOffset; }
376
377 /// The end offset of this partition.
378 ///
379 /// All of the contained slices end at or before this offset.
380 uint64_t endOffset() const { return EndOffset; }
381
382 /// The size of the partition.
383 ///
384 /// Note that this can never be zero.
385 uint64_t size() const {
386 assert(BeginOffset < EndOffset && "Partitions must span some bytes!")(static_cast <bool> (BeginOffset < EndOffset &&
"Partitions must span some bytes!") ? void (0) : __assert_fail
("BeginOffset < EndOffset && \"Partitions must span some bytes!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 386, __extension__ __PRETTY_FUNCTION__
))
;
387 return EndOffset - BeginOffset;
388 }
389
390 /// Test whether this partition contains no slices, and merely spans
391 /// a region occupied by split slices.
392 bool empty() const { return SI == SJ; }
393
394 /// \name Iterate slices that start within the partition.
395 /// These may be splittable or unsplittable. They have a begin offset >= the
396 /// partition begin offset.
397 /// @{
398 // FIXME: We should probably define a "concat_iterator" helper and use that
399 // to stitch together pointee_iterators over the split tails and the
400 // contiguous iterators of the partition. That would give a much nicer
401 // interface here. We could then additionally expose filtered iterators for
402 // split, unsplit, and unsplittable splices based on the usage patterns.
403 iterator begin() const { return SI; }
404 iterator end() const { return SJ; }
405 /// @}
406
407 /// Get the sequence of split slice tails.
408 ///
409 /// These tails are of slices which start before this partition but are
410 /// split and overlap into the partition. We accumulate these while forming
411 /// partitions.
412 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
413};
414
415/// An iterator over partitions of the alloca's slices.
416///
417/// This iterator implements the core algorithm for partitioning the alloca's
418/// slices. It is a forward iterator as we don't support backtracking for
419/// efficiency reasons, and re-use a single storage area to maintain the
420/// current set of split slices.
421///
422/// It is templated on the slice iterator type to use so that it can operate
423/// with either const or non-const slice iterators.
424class AllocaSlices::partition_iterator
425 : public iterator_facade_base<partition_iterator, std::forward_iterator_tag,
426 Partition> {
427 friend class AllocaSlices;
428
429 /// Most of the state for walking the partitions is held in a class
430 /// with a nice interface for examining them.
431 Partition P;
432
433 /// We need to keep the end of the slices to know when to stop.
434 AllocaSlices::iterator SE;
435
436 /// We also need to keep track of the maximum split end offset seen.
437 /// FIXME: Do we really?
438 uint64_t MaxSplitSliceEndOffset = 0;
439
440 /// Sets the partition to be empty at given iterator, and sets the
441 /// end iterator.
442 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
443 : P(SI), SE(SE) {
444 // If not already at the end, advance our state to form the initial
445 // partition.
446 if (SI != SE)
447 advance();
448 }
449
450 /// Advance the iterator to the next partition.
451 ///
452 /// Requires that the iterator not be at the end of the slices.
453 void advance() {
454 assert((P.SI != SE || !P.SplitTails.empty()) &&(static_cast <bool> ((P.SI != SE || !P.SplitTails.empty
()) && "Cannot advance past the end of the slices!") ?
void (0) : __assert_fail ("(P.SI != SE || !P.SplitTails.empty()) && \"Cannot advance past the end of the slices!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 455, __extension__ __PRETTY_FUNCTION__
))
455 "Cannot advance past the end of the slices!")(static_cast <bool> ((P.SI != SE || !P.SplitTails.empty
()) && "Cannot advance past the end of the slices!") ?
void (0) : __assert_fail ("(P.SI != SE || !P.SplitTails.empty()) && \"Cannot advance past the end of the slices!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 455, __extension__ __PRETTY_FUNCTION__
))
;
456
457 // Clear out any split uses which have ended.
458 if (!P.SplitTails.empty()) {
459 if (P.EndOffset >= MaxSplitSliceEndOffset) {
460 // If we've finished all splits, this is easy.
461 P.SplitTails.clear();
462 MaxSplitSliceEndOffset = 0;
463 } else {
464 // Remove the uses which have ended in the prior partition. This
465 // cannot change the max split slice end because we just checked that
466 // the prior partition ended prior to that max.
467 llvm::erase_if(P.SplitTails,
468 [&](Slice *S) { return S->endOffset() <= P.EndOffset; });
469 assert(llvm::any_of(P.SplitTails,(static_cast <bool> (llvm::any_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset
; }) && "Could not find the current max split slice offset!"
) ? void (0) : __assert_fail ("llvm::any_of(P.SplitTails, [&](Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset; }) && \"Could not find the current max split slice offset!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 473, __extension__ __PRETTY_FUNCTION__
))
470 [&](Slice *S) {(static_cast <bool> (llvm::any_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset
; }) && "Could not find the current max split slice offset!"
) ? void (0) : __assert_fail ("llvm::any_of(P.SplitTails, [&](Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset; }) && \"Could not find the current max split slice offset!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 473, __extension__ __PRETTY_FUNCTION__
))
471 return S->endOffset() == MaxSplitSliceEndOffset;(static_cast <bool> (llvm::any_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset
; }) && "Could not find the current max split slice offset!"
) ? void (0) : __assert_fail ("llvm::any_of(P.SplitTails, [&](Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset; }) && \"Could not find the current max split slice offset!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 473, __extension__ __PRETTY_FUNCTION__
))
472 }) &&(static_cast <bool> (llvm::any_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset
; }) && "Could not find the current max split slice offset!"
) ? void (0) : __assert_fail ("llvm::any_of(P.SplitTails, [&](Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset; }) && \"Could not find the current max split slice offset!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 473, __extension__ __PRETTY_FUNCTION__
))
473 "Could not find the current max split slice offset!")(static_cast <bool> (llvm::any_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset
; }) && "Could not find the current max split slice offset!"
) ? void (0) : __assert_fail ("llvm::any_of(P.SplitTails, [&](Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset; }) && \"Could not find the current max split slice offset!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 473, __extension__ __PRETTY_FUNCTION__
))
;
474 assert(llvm::all_of(P.SplitTails,(static_cast <bool> (llvm::all_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset
; }) && "Max split slice end offset is not actually the max!"
) ? void (0) : __assert_fail ("llvm::all_of(P.SplitTails, [&](Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset; }) && \"Max split slice end offset is not actually the max!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 478, __extension__ __PRETTY_FUNCTION__
))
475 [&](Slice *S) {(static_cast <bool> (llvm::all_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset
; }) && "Max split slice end offset is not actually the max!"
) ? void (0) : __assert_fail ("llvm::all_of(P.SplitTails, [&](Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset; }) && \"Max split slice end offset is not actually the max!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 478, __extension__ __PRETTY_FUNCTION__
))
476 return S->endOffset() <= MaxSplitSliceEndOffset;(static_cast <bool> (llvm::all_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset
; }) && "Max split slice end offset is not actually the max!"
) ? void (0) : __assert_fail ("llvm::all_of(P.SplitTails, [&](Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset; }) && \"Max split slice end offset is not actually the max!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 478, __extension__ __PRETTY_FUNCTION__
))
477 }) &&(static_cast <bool> (llvm::all_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset
; }) && "Max split slice end offset is not actually the max!"
) ? void (0) : __assert_fail ("llvm::all_of(P.SplitTails, [&](Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset; }) && \"Max split slice end offset is not actually the max!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 478, __extension__ __PRETTY_FUNCTION__
))
478 "Max split slice end offset is not actually the max!")(static_cast <bool> (llvm::all_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset
; }) && "Max split slice end offset is not actually the max!"
) ? void (0) : __assert_fail ("llvm::all_of(P.SplitTails, [&](Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset; }) && \"Max split slice end offset is not actually the max!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 478, __extension__ __PRETTY_FUNCTION__
))
;
479 }
480 }
481
482 // If P.SI is already at the end, then we've cleared the split tail and
483 // now have an end iterator.
484 if (P.SI == SE) {
485 assert(P.SplitTails.empty() && "Failed to clear the split slices!")(static_cast <bool> (P.SplitTails.empty() && "Failed to clear the split slices!"
) ? void (0) : __assert_fail ("P.SplitTails.empty() && \"Failed to clear the split slices!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 485, __extension__ __PRETTY_FUNCTION__
))
;
486 return;
487 }
488
489 // If we had a non-empty partition previously, set up the state for
490 // subsequent partitions.
491 if (P.SI != P.SJ) {
492 // Accumulate all the splittable slices which started in the old
493 // partition into the split list.
494 for (Slice &S : P)
495 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
496 P.SplitTails.push_back(&S);
497 MaxSplitSliceEndOffset =
498 std::max(S.endOffset(), MaxSplitSliceEndOffset);
499 }
500
501 // Start from the end of the previous partition.
502 P.SI = P.SJ;
503
504 // If P.SI is now at the end, we at most have a tail of split slices.
505 if (P.SI == SE) {
506 P.BeginOffset = P.EndOffset;
507 P.EndOffset = MaxSplitSliceEndOffset;
508 return;
509 }
510
511 // If the we have split slices and the next slice is after a gap and is
512 // not splittable immediately form an empty partition for the split
513 // slices up until the next slice begins.
514 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
515 !P.SI->isSplittable()) {
516 P.BeginOffset = P.EndOffset;
517 P.EndOffset = P.SI->beginOffset();
518 return;
519 }
520 }
521
522 // OK, we need to consume new slices. Set the end offset based on the
523 // current slice, and step SJ past it. The beginning offset of the
524 // partition is the beginning offset of the next slice unless we have
525 // pre-existing split slices that are continuing, in which case we begin
526 // at the prior end offset.
527 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
528 P.EndOffset = P.SI->endOffset();
529 ++P.SJ;
530
531 // There are two strategies to form a partition based on whether the
532 // partition starts with an unsplittable slice or a splittable slice.
533 if (!P.SI->isSplittable()) {
534 // When we're forming an unsplittable region, it must always start at
535 // the first slice and will extend through its end.
536 assert(P.BeginOffset == P.SI->beginOffset())(static_cast <bool> (P.BeginOffset == P.SI->beginOffset
()) ? void (0) : __assert_fail ("P.BeginOffset == P.SI->beginOffset()"
, "llvm/lib/Transforms/Scalar/SROA.cpp", 536, __extension__ __PRETTY_FUNCTION__
))
;
537
538 // Form a partition including all of the overlapping slices with this
539 // unsplittable slice.
540 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
541 if (!P.SJ->isSplittable())
542 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
543 ++P.SJ;
544 }
545
546 // We have a partition across a set of overlapping unsplittable
547 // partitions.
548 return;
549 }
550
551 // If we're starting with a splittable slice, then we need to form
552 // a synthetic partition spanning it and any other overlapping splittable
553 // splices.
554 assert(P.SI->isSplittable() && "Forming a splittable partition!")(static_cast <bool> (P.SI->isSplittable() &&
"Forming a splittable partition!") ? void (0) : __assert_fail
("P.SI->isSplittable() && \"Forming a splittable partition!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 554, __extension__ __PRETTY_FUNCTION__
))
;
555
556 // Collect all of the overlapping splittable slices.
557 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
558 P.SJ->isSplittable()) {
559 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
560 ++P.SJ;
561 }
562
563 // Back upiP.EndOffset if we ended the span early when encountering an
564 // unsplittable slice. This synthesizes the early end offset of
565 // a partition spanning only splittable slices.
566 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
567 assert(!P.SJ->isSplittable())(static_cast <bool> (!P.SJ->isSplittable()) ? void (
0) : __assert_fail ("!P.SJ->isSplittable()", "llvm/lib/Transforms/Scalar/SROA.cpp"
, 567, __extension__ __PRETTY_FUNCTION__))
;
568 P.EndOffset = P.SJ->beginOffset();
569 }
570 }
571
572public:
573 bool operator==(const partition_iterator &RHS) const {
574 assert(SE == RHS.SE &&(static_cast <bool> (SE == RHS.SE && "End iterators don't match between compared partition iterators!"
) ? void (0) : __assert_fail ("SE == RHS.SE && \"End iterators don't match between compared partition iterators!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 575, __extension__ __PRETTY_FUNCTION__
))
575 "End iterators don't match between compared partition iterators!")(static_cast <bool> (SE == RHS.SE && "End iterators don't match between compared partition iterators!"
) ? void (0) : __assert_fail ("SE == RHS.SE && \"End iterators don't match between compared partition iterators!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 575, __extension__ __PRETTY_FUNCTION__
))
;
576
577 // The observed positions of partitions is marked by the P.SI iterator and
578 // the emptiness of the split slices. The latter is only relevant when
579 // P.SI == SE, as the end iterator will additionally have an empty split
580 // slices list, but the prior may have the same P.SI and a tail of split
581 // slices.
582 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
583 assert(P.SJ == RHS.P.SJ &&(static_cast <bool> (P.SJ == RHS.P.SJ && "Same set of slices formed two different sized partitions!"
) ? void (0) : __assert_fail ("P.SJ == RHS.P.SJ && \"Same set of slices formed two different sized partitions!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 584, __extension__ __PRETTY_FUNCTION__
))
584 "Same set of slices formed two different sized partitions!")(static_cast <bool> (P.SJ == RHS.P.SJ && "Same set of slices formed two different sized partitions!"
) ? void (0) : __assert_fail ("P.SJ == RHS.P.SJ && \"Same set of slices formed two different sized partitions!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 584, __extension__ __PRETTY_FUNCTION__
))
;
585 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&(static_cast <bool> (P.SplitTails.size() == RHS.P.SplitTails
.size() && "Same slice position with differently sized non-empty split "
"slice tails!") ? void (0) : __assert_fail ("P.SplitTails.size() == RHS.P.SplitTails.size() && \"Same slice position with differently sized non-empty split \" \"slice tails!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 587, __extension__ __PRETTY_FUNCTION__
))
586 "Same slice position with differently sized non-empty split "(static_cast <bool> (P.SplitTails.size() == RHS.P.SplitTails
.size() && "Same slice position with differently sized non-empty split "
"slice tails!") ? void (0) : __assert_fail ("P.SplitTails.size() == RHS.P.SplitTails.size() && \"Same slice position with differently sized non-empty split \" \"slice tails!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 587, __extension__ __PRETTY_FUNCTION__
))
587 "slice tails!")(static_cast <bool> (P.SplitTails.size() == RHS.P.SplitTails
.size() && "Same slice position with differently sized non-empty split "
"slice tails!") ? void (0) : __assert_fail ("P.SplitTails.size() == RHS.P.SplitTails.size() && \"Same slice position with differently sized non-empty split \" \"slice tails!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 587, __extension__ __PRETTY_FUNCTION__
))
;
588 return true;
589 }
590 return false;
591 }
592
593 partition_iterator &operator++() {
594 advance();
595 return *this;
596 }
597
598 Partition &operator*() { return P; }
599};
600
601/// A forward range over the partitions of the alloca's slices.
602///
603/// This accesses an iterator range over the partitions of the alloca's
604/// slices. It computes these partitions on the fly based on the overlapping
605/// offsets of the slices and the ability to split them. It will visit "empty"
606/// partitions to cover regions of the alloca only accessed via split
607/// slices.
608iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() {
609 return make_range(partition_iterator(begin(), end()),
610 partition_iterator(end(), end()));
611}
612
613static Value *foldSelectInst(SelectInst &SI) {
614 // If the condition being selected on is a constant or the same value is
615 // being selected between, fold the select. Yes this does (rarely) happen
616 // early on.
617 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
618 return SI.getOperand(1 + CI->isZero());
619 if (SI.getOperand(1) == SI.getOperand(2))
620 return SI.getOperand(1);
621
622 return nullptr;
623}
624
625/// A helper that folds a PHI node or a select.
626static Value *foldPHINodeOrSelectInst(Instruction &I) {
627 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
628 // If PN merges together the same value, return that value.
629 return PN->hasConstantValue();
630 }
631 return foldSelectInst(cast<SelectInst>(I));
632}
633
634/// Builder for the alloca slices.
635///
636/// This class builds a set of alloca slices by recursively visiting the uses
637/// of an alloca and making a slice for each load and store at each offset.
638class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
639 friend class PtrUseVisitor<SliceBuilder>;
640 friend class InstVisitor<SliceBuilder>;
641
642 using Base = PtrUseVisitor<SliceBuilder>;
643
644 const uint64_t AllocSize;
645 AllocaSlices &AS;
646
647 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
648 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
649
650 /// Set to de-duplicate dead instructions found in the use walk.
651 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
652
653public:
654 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
655 : PtrUseVisitor<SliceBuilder>(DL),
656 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType()).getFixedSize()),
657 AS(AS) {}
658
659private:
660 void markAsDead(Instruction &I) {
661 if (VisitedDeadInsts.insert(&I).second)
662 AS.DeadUsers.push_back(&I);
663 }
664
665 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
666 bool IsSplittable = false) {
667 // Completely skip uses which have a zero size or start either before or
668 // past the end of the allocation.
669 if (Size == 0 || Offset.uge(AllocSize)) {
670 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte use @" << Offset << " which has zero size or starts outside of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
671 << Offsetdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte use @" << Offset << " which has zero size or starts outside of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
672 << " which has zero size or starts outside of the "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte use @" << Offset << " which has zero size or starts outside of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
673 << AllocSize << " byte alloca:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte use @" << Offset << " which has zero size or starts outside of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
674 << " alloca: " << AS.AI << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte use @" << Offset << " which has zero size or starts outside of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
675 << " use: " << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte use @" << Offset << " which has zero size or starts outside of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
;
676 return markAsDead(I);
677 }
678
679 uint64_t BeginOffset = Offset.getZExtValue();
680 uint64_t EndOffset = BeginOffset + Size;
681
682 // Clamp the end offset to the end of the allocation. Note that this is
683 // formulated to handle even the case where "BeginOffset + Size" overflows.
684 // This may appear superficially to be something we could ignore entirely,
685 // but that is not so! There may be widened loads or PHI-node uses where
686 // some instructions are dead but not others. We can't completely ignore
687 // them, and so have to record at least the information here.
688 assert(AllocSize >= BeginOffset)(static_cast <bool> (AllocSize >= BeginOffset) ? void
(0) : __assert_fail ("AllocSize >= BeginOffset", "llvm/lib/Transforms/Scalar/SROA.cpp"
, 688, __extension__ __PRETTY_FUNCTION__))
; // Established above.
689 if (Size > AllocSize - BeginOffset) {
690 LLVM_DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Clamping a " << Size
<< " byte use @" << Offset << " to remain within the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
691 << Offset << " to remain within the " << AllocSizedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Clamping a " << Size
<< " byte use @" << Offset << " to remain within the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
692 << " byte alloca:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Clamping a " << Size
<< " byte use @" << Offset << " to remain within the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
693 << " alloca: " << AS.AI << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Clamping a " << Size
<< " byte use @" << Offset << " to remain within the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
694 << " use: " << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Clamping a " << Size
<< " byte use @" << Offset << " to remain within the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
;
695 EndOffset = AllocSize;
696 }
697
698 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
699 }
700
701 void visitBitCastInst(BitCastInst &BC) {
702 if (BC.use_empty())
703 return markAsDead(BC);
704
705 return Base::visitBitCastInst(BC);
706 }
707
708 void visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
709 if (ASC.use_empty())
710 return markAsDead(ASC);
711
712 return Base::visitAddrSpaceCastInst(ASC);
713 }
714
715 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
716 if (GEPI.use_empty())
717 return markAsDead(GEPI);
718
719 if (SROAStrictInbounds && GEPI.isInBounds()) {
720 // FIXME: This is a manually un-factored variant of the basic code inside
721 // of GEPs with checking of the inbounds invariant specified in the
722 // langref in a very strict sense. If we ever want to enable
723 // SROAStrictInbounds, this code should be factored cleanly into
724 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
725 // by writing out the code here where we have the underlying allocation
726 // size readily available.
727 APInt GEPOffset = Offset;
728 const DataLayout &DL = GEPI.getModule()->getDataLayout();
729 for (gep_type_iterator GTI = gep_type_begin(GEPI),
730 GTE = gep_type_end(GEPI);
731 GTI != GTE; ++GTI) {
732 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
733 if (!OpC)
734 break;
735
736 // Handle a struct index, which adds its field offset to the pointer.
737 if (StructType *STy = GTI.getStructTypeOrNull()) {
738 unsigned ElementIdx = OpC->getZExtValue();
739 const StructLayout *SL = DL.getStructLayout(STy);
740 GEPOffset +=
741 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
742 } else {
743 // For array or vector indices, scale the index by the size of the
744 // type.
745 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
746 GEPOffset +=
747 Index *
748 APInt(Offset.getBitWidth(),
749 DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize());
750 }
751
752 // If this index has computed an intermediate pointer which is not
753 // inbounds, then the result of the GEP is a poison value and we can
754 // delete it and all uses.
755 if (GEPOffset.ugt(AllocSize))
756 return markAsDead(GEPI);
757 }
758 }
759
760 return Base::visitGetElementPtrInst(GEPI);
761 }
762
763 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
764 uint64_t Size, bool IsVolatile) {
765 // We allow splitting of non-volatile loads and stores where the type is an
766 // integer type. These may be used to implement 'memcpy' or other "transfer
767 // of bits" patterns.
768 bool IsSplittable =
769 Ty->isIntegerTy() && !IsVolatile && DL.typeSizeEqualsStoreSize(Ty);
770
771 insertUse(I, Offset, Size, IsSplittable);
772 }
773
774 void visitLoadInst(LoadInst &LI) {
775 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&(static_cast <bool> ((!LI.isSimple() || LI.getType()->
isSingleValueType()) && "All simple FCA loads should have been pre-split"
) ? void (0) : __assert_fail ("(!LI.isSimple() || LI.getType()->isSingleValueType()) && \"All simple FCA loads should have been pre-split\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 776, __extension__ __PRETTY_FUNCTION__
))
776 "All simple FCA loads should have been pre-split")(static_cast <bool> ((!LI.isSimple() || LI.getType()->
isSingleValueType()) && "All simple FCA loads should have been pre-split"
) ? void (0) : __assert_fail ("(!LI.isSimple() || LI.getType()->isSingleValueType()) && \"All simple FCA loads should have been pre-split\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 776, __extension__ __PRETTY_FUNCTION__
))
;
777
778 if (!IsOffsetKnown)
779 return PI.setAborted(&LI);
780
781 if (LI.isVolatile() &&
782 LI.getPointerAddressSpace() != DL.getAllocaAddrSpace())
783 return PI.setAborted(&LI);
784
785 if (isa<ScalableVectorType>(LI.getType()))
786 return PI.setAborted(&LI);
787
788 uint64_t Size = DL.getTypeStoreSize(LI.getType()).getFixedSize();
789 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
790 }
791
792 void visitStoreInst(StoreInst &SI) {
793 Value *ValOp = SI.getValueOperand();
794 if (ValOp == *U)
795 return PI.setEscapedAndAborted(&SI);
796 if (!IsOffsetKnown)
797 return PI.setAborted(&SI);
798
799 if (SI.isVolatile() &&
800 SI.getPointerAddressSpace() != DL.getAllocaAddrSpace())
801 return PI.setAborted(&SI);
802
803 if (isa<ScalableVectorType>(ValOp->getType()))
804 return PI.setAborted(&SI);
805
806 uint64_t Size = DL.getTypeStoreSize(ValOp->getType()).getFixedSize();
807
808 // If this memory access can be shown to *statically* extend outside the
809 // bounds of the allocation, it's behavior is undefined, so simply
810 // ignore it. Note that this is more strict than the generic clamping
811 // behavior of insertUse. We also try to handle cases which might run the
812 // risk of overflow.
813 // FIXME: We should instead consider the pointer to have escaped if this
814 // function is being instrumented for addressing bugs or race conditions.
815 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
816 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte store @" << Offset << " which extends past the end of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
SI << "\n"; } } while (false)
817 << Offset << " which extends past the end of the "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte store @" << Offset << " which extends past the end of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
SI << "\n"; } } while (false)
818 << AllocSize << " byte alloca:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte store @" << Offset << " which extends past the end of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
SI << "\n"; } } while (false)
819 << " alloca: " << AS.AI << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte store @" << Offset << " which extends past the end of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
SI << "\n"; } } while (false)
820 << " use: " << SI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte store @" << Offset << " which extends past the end of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
SI << "\n"; } } while (false)
;
821 return markAsDead(SI);
822 }
823
824 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&(static_cast <bool> ((!SI.isSimple() || ValOp->getType
()->isSingleValueType()) && "All simple FCA stores should have been pre-split"
) ? void (0) : __assert_fail ("(!SI.isSimple() || ValOp->getType()->isSingleValueType()) && \"All simple FCA stores should have been pre-split\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 825, __extension__ __PRETTY_FUNCTION__
))
825 "All simple FCA stores should have been pre-split")(static_cast <bool> ((!SI.isSimple() || ValOp->getType
()->isSingleValueType()) && "All simple FCA stores should have been pre-split"
) ? void (0) : __assert_fail ("(!SI.isSimple() || ValOp->getType()->isSingleValueType()) && \"All simple FCA stores should have been pre-split\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 825, __extension__ __PRETTY_FUNCTION__
))
;
826 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
827 }
828
829 void visitMemSetInst(MemSetInst &II) {
830 assert(II.getRawDest() == *U && "Pointer use is not the destination?")(static_cast <bool> (II.getRawDest() == *U && "Pointer use is not the destination?"
) ? void (0) : __assert_fail ("II.getRawDest() == *U && \"Pointer use is not the destination?\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 830, __extension__ __PRETTY_FUNCTION__
))
;
831 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
832 if ((Length && Length->getValue() == 0) ||
833 (IsOffsetKnown && Offset.uge(AllocSize)))
834 // Zero-length mem transfer intrinsics can be ignored entirely.
835 return markAsDead(II);
836
837 if (!IsOffsetKnown)
838 return PI.setAborted(&II);
839
840 // Don't replace this with a store with a different address space. TODO:
841 // Use a store with the casted new alloca?
842 if (II.isVolatile() && II.getDestAddressSpace() != DL.getAllocaAddrSpace())
843 return PI.setAborted(&II);
844
845 insertUse(II, Offset, Length ? Length->getLimitedValue()
846 : AllocSize - Offset.getLimitedValue(),
847 (bool)Length);
848 }
849
850 void visitMemTransferInst(MemTransferInst &II) {
851 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
852 if (Length && Length->getValue() == 0)
853 // Zero-length mem transfer intrinsics can be ignored entirely.
854 return markAsDead(II);
855
856 // Because we can visit these intrinsics twice, also check to see if the
857 // first time marked this instruction as dead. If so, skip it.
858 if (VisitedDeadInsts.count(&II))
859 return;
860
861 if (!IsOffsetKnown)
862 return PI.setAborted(&II);
863
864 // Don't replace this with a load/store with a different address space.
865 // TODO: Use a store with the casted new alloca?
866 if (II.isVolatile() &&
867 (II.getDestAddressSpace() != DL.getAllocaAddrSpace() ||
868 II.getSourceAddressSpace() != DL.getAllocaAddrSpace()))
869 return PI.setAborted(&II);
870
871 // This side of the transfer is completely out-of-bounds, and so we can
872 // nuke the entire transfer. However, we also need to nuke the other side
873 // if already added to our partitions.
874 // FIXME: Yet another place we really should bypass this when
875 // instrumenting for ASan.
876 if (Offset.uge(AllocSize)) {
877 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
878 MemTransferSliceMap.find(&II);
879 if (MTPI != MemTransferSliceMap.end())
880 AS.Slices[MTPI->second].kill();
881 return markAsDead(II);
882 }
883
884 uint64_t RawOffset = Offset.getLimitedValue();
885 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
886
887 // Check for the special case where the same exact value is used for both
888 // source and dest.
889 if (*U == II.getRawDest() && *U == II.getRawSource()) {
890 // For non-volatile transfers this is a no-op.
891 if (!II.isVolatile())
892 return markAsDead(II);
893
894 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
895 }
896
897 // If we have seen both source and destination for a mem transfer, then
898 // they both point to the same alloca.
899 bool Inserted;
900 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
901 std::tie(MTPI, Inserted) =
902 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
903 unsigned PrevIdx = MTPI->second;
904 if (!Inserted) {
905 Slice &PrevP = AS.Slices[PrevIdx];
906
907 // Check if the begin offsets match and this is a non-volatile transfer.
908 // In that case, we can completely elide the transfer.
909 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
910 PrevP.kill();
911 return markAsDead(II);
912 }
913
914 // Otherwise we have an offset transfer within the same alloca. We can't
915 // split those.
916 PrevP.makeUnsplittable();
917 }
918
919 // Insert the use now that we've fixed up the splittable nature.
920 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
921
922 // Check that we ended up with a valid index in the map.
923 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&(static_cast <bool> (AS.Slices[PrevIdx].getUse()->getUser
() == &II && "Map index doesn't point back to a slice with this user."
) ? void (0) : __assert_fail ("AS.Slices[PrevIdx].getUse()->getUser() == &II && \"Map index doesn't point back to a slice with this user.\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 924, __extension__ __PRETTY_FUNCTION__
))
924 "Map index doesn't point back to a slice with this user.")(static_cast <bool> (AS.Slices[PrevIdx].getUse()->getUser
() == &II && "Map index doesn't point back to a slice with this user."
) ? void (0) : __assert_fail ("AS.Slices[PrevIdx].getUse()->getUser() == &II && \"Map index doesn't point back to a slice with this user.\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 924, __extension__ __PRETTY_FUNCTION__
))
;
925 }
926
927 // Disable SRoA for any intrinsics except for lifetime invariants and
928 // invariant group.
929 // FIXME: What about debug intrinsics? This matches old behavior, but
930 // doesn't make sense.
931 void visitIntrinsicInst(IntrinsicInst &II) {
932 if (II.isDroppable()) {
933 AS.DeadUseIfPromotable.push_back(U);
934 return;
935 }
936
937 if (!IsOffsetKnown)
938 return PI.setAborted(&II);
939
940 if (II.isLifetimeStartOrEnd()) {
941 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
942 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
943 Length->getLimitedValue());
944 insertUse(II, Offset, Size, true);
945 return;
946 }
947
948 if (II.isLaunderOrStripInvariantGroup()) {
949 enqueueUsers(II);
950 return;
951 }
952
953 Base::visitIntrinsicInst(II);
954 }
955
956 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
957 // We consider any PHI or select that results in a direct load or store of
958 // the same offset to be a viable use for slicing purposes. These uses
959 // are considered unsplittable and the size is the maximum loaded or stored
960 // size.
961 SmallPtrSet<Instruction *, 4> Visited;
962 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
963 Visited.insert(Root);
964 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
965 const DataLayout &DL = Root->getModule()->getDataLayout();
966 // If there are no loads or stores, the access is dead. We mark that as
967 // a size zero access.
968 Size = 0;
969 do {
970 Instruction *I, *UsedI;
971 std::tie(UsedI, I) = Uses.pop_back_val();
972
973 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
974 Size = std::max(Size,
975 DL.getTypeStoreSize(LI->getType()).getFixedSize());
976 continue;
977 }
978 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
979 Value *Op = SI->getOperand(0);
980 if (Op == UsedI)
981 return SI;
982 Size = std::max(Size,
983 DL.getTypeStoreSize(Op->getType()).getFixedSize());
984 continue;
985 }
986
987 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
988 if (!GEP->hasAllZeroIndices())
989 return GEP;
990 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
991 !isa<SelectInst>(I) && !isa<AddrSpaceCastInst>(I)) {
992 return I;
993 }
994
995 for (User *U : I->users())
996 if (Visited.insert(cast<Instruction>(U)).second)
997 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
998 } while (!Uses.empty());
999
1000 return nullptr;
1001 }
1002
1003 void visitPHINodeOrSelectInst(Instruction &I) {
1004 assert(isa<PHINode>(I) || isa<SelectInst>(I))(static_cast <bool> (isa<PHINode>(I) || isa<SelectInst
>(I)) ? void (0) : __assert_fail ("isa<PHINode>(I) || isa<SelectInst>(I)"
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1004, __extension__ __PRETTY_FUNCTION__
))
;
1005 if (I.use_empty())
1006 return markAsDead(I);
1007
1008 // If this is a PHI node before a catchswitch, we cannot insert any non-PHI
1009 // instructions in this BB, which may be required during rewriting. Bail out
1010 // on these cases.
1011 if (isa<PHINode>(I) &&
1012 I.getParent()->getFirstInsertionPt() == I.getParent()->end())
1013 return PI.setAborted(&I);
1014
1015 // TODO: We could use simplifyInstruction here to fold PHINodes and
1016 // SelectInsts. However, doing so requires to change the current
1017 // dead-operand-tracking mechanism. For instance, suppose neither loading
1018 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
1019 // trap either. However, if we simply replace %U with undef using the
1020 // current dead-operand-tracking mechanism, "load (select undef, undef,
1021 // %other)" may trap because the select may return the first operand
1022 // "undef".
1023 if (Value *Result = foldPHINodeOrSelectInst(I)) {
1024 if (Result == *U)
1025 // If the result of the constant fold will be the pointer, recurse
1026 // through the PHI/select as if we had RAUW'ed it.
1027 enqueueUsers(I);
1028 else
1029 // Otherwise the operand to the PHI/select is dead, and we can replace
1030 // it with poison.
1031 AS.DeadOperands.push_back(U);
1032
1033 return;
1034 }
1035
1036 if (!IsOffsetKnown)
1037 return PI.setAborted(&I);
1038
1039 // See if we already have computed info on this node.
1040 uint64_t &Size = PHIOrSelectSizes[&I];
1041 if (!Size) {
1042 // This is a new PHI/Select, check for an unsafe use of it.
1043 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
1044 return PI.setAborted(UnsafeI);
1045 }
1046
1047 // For PHI and select operands outside the alloca, we can't nuke the entire
1048 // phi or select -- the other side might still be relevant, so we special
1049 // case them here and use a separate structure to track the operands
1050 // themselves which should be replaced with poison.
1051 // FIXME: This should instead be escaped in the event we're instrumenting
1052 // for address sanitization.
1053 if (Offset.uge(AllocSize)) {
1054 AS.DeadOperands.push_back(U);
1055 return;
1056 }
1057
1058 insertUse(I, Offset, Size);
1059 }
1060
1061 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
1062
1063 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
1064
1065 /// Disable SROA entirely if there are unhandled users of the alloca.
1066 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
1067};
1068
1069AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
1070 :
1071#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1072 AI(AI),
1073#endif
1074 PointerEscapingInstr(nullptr) {
1075 SliceBuilder PB(DL, AI, *this);
1076 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
1077 if (PtrI.isEscaped() || PtrI.isAborted()) {
1078 // FIXME: We should sink the escape vs. abort info into the caller nicely,
1079 // possibly by just storing the PtrInfo in the AllocaSlices.
1080 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1081 : PtrI.getAbortingInst();
1082 assert(PointerEscapingInstr && "Did not track a bad instruction")(static_cast <bool> (PointerEscapingInstr && "Did not track a bad instruction"
) ? void (0) : __assert_fail ("PointerEscapingInstr && \"Did not track a bad instruction\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1082, __extension__ __PRETTY_FUNCTION__
))
;
1083 return;
1084 }
1085
1086 llvm::erase_if(Slices, [](const Slice &S) { return S.isDead(); });
1087
1088 // Sort the uses. This arranges for the offsets to be in ascending order,
1089 // and the sizes to be in descending order.
1090 llvm::stable_sort(Slices);
1091}
1092
1093#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1094
1095void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1096 StringRef Indent) const {
1097 printSlice(OS, I, Indent);
1098 OS << "\n";
1099 printUse(OS, I, Indent);
1100}
1101
1102void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1103 StringRef Indent) const {
1104 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
1105 << " slice #" << (I - begin())
1106 << (I->isSplittable() ? " (splittable)" : "");
1107}
1108
1109void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1110 StringRef Indent) const {
1111 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
1112}
1113
1114void AllocaSlices::print(raw_ostream &OS) const {
1115 if (PointerEscapingInstr) {
1116 OS << "Can't analyze slices for alloca: " << AI << "\n"
1117 << " A pointer to this alloca escaped by:\n"
1118 << " " << *PointerEscapingInstr << "\n";
1119 return;
1120 }
1121
1122 OS << "Slices of alloca: " << AI << "\n";
1123 for (const_iterator I = begin(), E = end(); I != E; ++I)
1124 print(OS, I);
1125}
1126
1127LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void AllocaSlices::dump(const_iterator I) const {
1128 print(dbgs(), I);
1129}
1130LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void AllocaSlices::dump() const { print(dbgs()); }
1131
1132#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1133
1134/// Walk the range of a partitioning looking for a common type to cover this
1135/// sequence of slices.
1136static std::pair<Type *, IntegerType *>
1137findCommonType(AllocaSlices::const_iterator B, AllocaSlices::const_iterator E,
1138 uint64_t EndOffset) {
1139 Type *Ty = nullptr;
1140 bool TyIsCommon = true;
1141 IntegerType *ITy = nullptr;
1142
1143 // Note that we need to look at *every* alloca slice's Use to ensure we
1144 // always get consistent results regardless of the order of slices.
1145 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
1146 Use *U = I->getUse();
1147 if (isa<IntrinsicInst>(*U->getUser()))
1148 continue;
1149 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1150 continue;
1151
1152 Type *UserTy = nullptr;
1153 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1154 UserTy = LI->getType();
1155 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1156 UserTy = SI->getValueOperand()->getType();
1157 }
1158
1159 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
1160 // If the type is larger than the partition, skip it. We only encounter
1161 // this for split integer operations where we want to use the type of the
1162 // entity causing the split. Also skip if the type is not a byte width
1163 // multiple.
1164 if (UserITy->getBitWidth() % 8 != 0 ||
1165 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
1166 continue;
1167
1168 // Track the largest bitwidth integer type used in this way in case there
1169 // is no common type.
1170 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1171 ITy = UserITy;
1172 }
1173
1174 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1175 // depend on types skipped above.
1176 if (!UserTy || (Ty && Ty != UserTy))
1177 TyIsCommon = false; // Give up on anything but an iN type.
1178 else
1179 Ty = UserTy;
1180 }
1181
1182 return {TyIsCommon ? Ty : nullptr, ITy};
1183}
1184
1185/// PHI instructions that use an alloca and are subsequently loaded can be
1186/// rewritten to load both input pointers in the pred blocks and then PHI the
1187/// results, allowing the load of the alloca to be promoted.
1188/// From this:
1189/// %P2 = phi [i32* %Alloca, i32* %Other]
1190/// %V = load i32* %P2
1191/// to:
1192/// %V1 = load i32* %Alloca -> will be mem2reg'd
1193/// ...
1194/// %V2 = load i32* %Other
1195/// ...
1196/// %V = phi [i32 %V1, i32 %V2]
1197///
1198/// We can do this to a select if its only uses are loads and if the operands
1199/// to the select can be loaded unconditionally.
1200///
1201/// FIXME: This should be hoisted into a generic utility, likely in
1202/// Transforms/Util/Local.h
1203static bool isSafePHIToSpeculate(PHINode &PN) {
1204 const DataLayout &DL = PN.getModule()->getDataLayout();
1205
1206 // For now, we can only do this promotion if the load is in the same block
1207 // as the PHI, and if there are no stores between the phi and load.
1208 // TODO: Allow recursive phi users.
1209 // TODO: Allow stores.
1210 BasicBlock *BB = PN.getParent();
1211 Align MaxAlign;
1212 uint64_t APWidth = DL.getIndexTypeSizeInBits(PN.getType());
1213 APInt MaxSize(APWidth, 0);
1214 bool HaveLoad = false;
1215 for (User *U : PN.users()) {
1216 LoadInst *LI = dyn_cast<LoadInst>(U);
1217 if (!LI || !LI->isSimple())
1218 return false;
1219
1220 // For now we only allow loads in the same block as the PHI. This is
1221 // a common case that happens when instcombine merges two loads through
1222 // a PHI.
1223 if (LI->getParent() != BB)
1224 return false;
1225
1226 // Ensure that there are no instructions between the PHI and the load that
1227 // could store.
1228 for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
1229 if (BBI->mayWriteToMemory())
1230 return false;
1231
1232 uint64_t Size = DL.getTypeStoreSize(LI->getType()).getFixedSize();
1233 MaxAlign = std::max(MaxAlign, LI->getAlign());
1234 MaxSize = MaxSize.ult(Size) ? APInt(APWidth, Size) : MaxSize;
1235 HaveLoad = true;
1236 }
1237
1238 if (!HaveLoad)
1239 return false;
1240
1241 // We can only transform this if it is safe to push the loads into the
1242 // predecessor blocks. The only thing to watch out for is that we can't put
1243 // a possibly trapping load in the predecessor if it is a critical edge.
1244 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1245 Instruction *TI = PN.getIncomingBlock(Idx)->getTerminator();
1246 Value *InVal = PN.getIncomingValue(Idx);
1247
1248 // If the value is produced by the terminator of the predecessor (an
1249 // invoke) or it has side-effects, there is no valid place to put a load
1250 // in the predecessor.
1251 if (TI == InVal || TI->mayHaveSideEffects())
1252 return false;
1253
1254 // If the predecessor has a single successor, then the edge isn't
1255 // critical.
1256 if (TI->getNumSuccessors() == 1)
1257 continue;
1258
1259 // If this pointer is always safe to load, or if we can prove that there
1260 // is already a load in the block, then we can move the load to the pred
1261 // block.
1262 if (isSafeToLoadUnconditionally(InVal, MaxAlign, MaxSize, DL, TI))
1263 continue;
1264
1265 return false;
1266 }
1267
1268 return true;
1269}
1270
1271static void speculatePHINodeLoads(IRBuilderTy &IRB, PHINode &PN) {
1272 LLVM_DEBUG(dbgs() << " original: " << PN << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << PN <<
"\n"; } } while (false)
;
1273
1274 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
1275 Type *LoadTy = SomeLoad->getType();
1276 IRB.SetInsertPoint(&PN);
1277 PHINode *NewPN = IRB.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1278 PN.getName() + ".sroa.speculated");
1279
1280 // Get the AA tags and alignment to use from one of the loads. It does not
1281 // matter which one we get and if any differ.
1282 AAMDNodes AATags = SomeLoad->getAAMetadata();
1283 Align Alignment = SomeLoad->getAlign();
1284
1285 // Rewrite all loads of the PN to use the new PHI.
1286 while (!PN.use_empty()) {
1287 LoadInst *LI = cast<LoadInst>(PN.user_back());
1288 LI->replaceAllUsesWith(NewPN);
1289 LI->eraseFromParent();
1290 }
1291
1292 // Inject loads into all of the pred blocks.
1293 DenseMap<BasicBlock*, Value*> InjectedLoads;
1294 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1295 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1296 Value *InVal = PN.getIncomingValue(Idx);
1297
1298 // A PHI node is allowed to have multiple (duplicated) entries for the same
1299 // basic block, as long as the value is the same. So if we already injected
1300 // a load in the predecessor, then we should reuse the same load for all
1301 // duplicated entries.
1302 if (Value* V = InjectedLoads.lookup(Pred)) {
1303 NewPN->addIncoming(V, Pred);
1304 continue;
1305 }
1306
1307 Instruction *TI = Pred->getTerminator();
1308 IRB.SetInsertPoint(TI);
1309
1310 LoadInst *Load = IRB.CreateAlignedLoad(
1311 LoadTy, InVal, Alignment,
1312 (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1313 ++NumLoadsSpeculated;
1314 if (AATags)
1315 Load->setAAMetadata(AATags);
1316 NewPN->addIncoming(Load, Pred);
1317 InjectedLoads[Pred] = Load;
1318 }
1319
1320 LLVM_DEBUG(dbgs() << " speculated to: " << *NewPN << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " speculated to: " <<
*NewPN << "\n"; } } while (false)
;
1321 PN.eraseFromParent();
1322}
1323
1324/// Select instructions that use an alloca and are subsequently loaded can be
1325/// rewritten to load both input pointers and then select between the result,
1326/// allowing the load of the alloca to be promoted.
1327/// From this:
1328/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1329/// %V = load i32* %P2
1330/// to:
1331/// %V1 = load i32* %Alloca -> will be mem2reg'd
1332/// %V2 = load i32* %Other
1333/// %V = select i1 %cond, i32 %V1, i32 %V2
1334///
1335/// We can do this to a select if its only uses are loads and if the operand
1336/// to the select can be loaded unconditionally. If found an intervening bitcast
1337/// with a single use of the load, allow the promotion.
1338static bool isSafeSelectToSpeculate(SelectInst &SI) {
1339 Value *TValue = SI.getTrueValue();
1340 Value *FValue = SI.getFalseValue();
1341 const DataLayout &DL = SI.getModule()->getDataLayout();
1342
1343 for (User *U : SI.users()) {
1344 LoadInst *LI;
1345 BitCastInst *BC = dyn_cast<BitCastInst>(U);
1346 if (BC && BC->hasOneUse())
1347 LI = dyn_cast<LoadInst>(*BC->user_begin());
1348 else
1349 LI = dyn_cast<LoadInst>(U);
1350
1351 if (!LI || !LI->isSimple())
1352 return false;
1353
1354 // Both operands to the select need to be dereferenceable, either
1355 // absolutely (e.g. allocas) or at this point because we can see other
1356 // accesses to it.
1357 if (!isSafeToLoadUnconditionally(TValue, LI->getType(),
1358 LI->getAlign(), DL, LI))
1359 return false;
1360 if (!isSafeToLoadUnconditionally(FValue, LI->getType(),
1361 LI->getAlign(), DL, LI))
1362 return false;
1363 }
1364
1365 return true;
1366}
1367
1368static void speculateSelectInstLoads(IRBuilderTy &IRB, SelectInst &SI) {
1369 LLVM_DEBUG(dbgs() << " original: " << SI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << SI <<
"\n"; } } while (false)
;
1370
1371 IRB.SetInsertPoint(&SI);
1372 Value *TV = SI.getTrueValue();
1373 Value *FV = SI.getFalseValue();
1374 // Replace the loads of the select with a select of two loads.
1375 while (!SI.use_empty()) {
1376 LoadInst *LI;
1377 BitCastInst *BC = dyn_cast<BitCastInst>(SI.user_back());
1378 if (BC) {
1379 assert(BC->hasOneUse() && "Bitcast should have a single use.")(static_cast <bool> (BC->hasOneUse() && "Bitcast should have a single use."
) ? void (0) : __assert_fail ("BC->hasOneUse() && \"Bitcast should have a single use.\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1379, __extension__ __PRETTY_FUNCTION__
))
;
1380 LI = cast<LoadInst>(BC->user_back());
1381 } else {
1382 LI = cast<LoadInst>(SI.user_back());
1383 }
1384
1385 assert(LI->isSimple() && "We only speculate simple loads")(static_cast <bool> (LI->isSimple() && "We only speculate simple loads"
) ? void (0) : __assert_fail ("LI->isSimple() && \"We only speculate simple loads\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1385, __extension__ __PRETTY_FUNCTION__
))
;
1386
1387 IRB.SetInsertPoint(LI);
1388 Value *NewTV =
1389 BC ? IRB.CreateBitCast(TV, BC->getType(), TV->getName() + ".sroa.cast")
1390 : TV;
1391 Value *NewFV =
1392 BC ? IRB.CreateBitCast(FV, BC->getType(), FV->getName() + ".sroa.cast")
1393 : FV;
1394 LoadInst *TL = IRB.CreateLoad(LI->getType(), NewTV,
1395 LI->getName() + ".sroa.speculate.load.true");
1396 LoadInst *FL = IRB.CreateLoad(LI->getType(), NewFV,
1397 LI->getName() + ".sroa.speculate.load.false");
1398 NumLoadsSpeculated += 2;
1399
1400 // Transfer alignment and AA info if present.
1401 TL->setAlignment(LI->getAlign());
1402 FL->setAlignment(LI->getAlign());
1403
1404 AAMDNodes Tags = LI->getAAMetadata();
1405 if (Tags) {
1406 TL->setAAMetadata(Tags);
1407 FL->setAAMetadata(Tags);
1408 }
1409
1410 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1411 LI->getName() + ".sroa.speculated");
1412
1413 LLVM_DEBUG(dbgs() << " speculated to: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " speculated to: " <<
*V << "\n"; } } while (false)
;
1414 LI->replaceAllUsesWith(V);
1415 LI->eraseFromParent();
1416 if (BC)
1417 BC->eraseFromParent();
1418 }
1419 SI.eraseFromParent();
1420}
1421
1422/// Build a GEP out of a base pointer and indices.
1423///
1424/// This will return the BasePtr if that is valid, or build a new GEP
1425/// instruction using the IRBuilder if GEP-ing is needed.
1426static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
1427 SmallVectorImpl<Value *> &Indices,
1428 const Twine &NamePrefix) {
1429 if (Indices.empty())
1430 return BasePtr;
1431
1432 // A single zero index is a no-op, so check for this and avoid building a GEP
1433 // in that case.
1434 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1435 return BasePtr;
1436
1437 // buildGEP() is only called for non-opaque pointers.
1438 return IRB.CreateInBoundsGEP(
1439 BasePtr->getType()->getNonOpaquePointerElementType(), BasePtr, Indices,
1440 NamePrefix + "sroa_idx");
1441}
1442
1443/// Get a natural GEP off of the BasePtr walking through Ty toward
1444/// TargetTy without changing the offset of the pointer.
1445///
1446/// This routine assumes we've already established a properly offset GEP with
1447/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1448/// zero-indices down through type layers until we find one the same as
1449/// TargetTy. If we can't find one with the same type, we at least try to use
1450/// one with the same size. If none of that works, we just produce the GEP as
1451/// indicated by Indices to have the correct offset.
1452static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
1453 Value *BasePtr, Type *Ty, Type *TargetTy,
1454 SmallVectorImpl<Value *> &Indices,
1455 const Twine &NamePrefix) {
1456 if (Ty == TargetTy)
1457 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1458
1459 // Offset size to use for the indices.
1460 unsigned OffsetSize = DL.getIndexTypeSizeInBits(BasePtr->getType());
1461
1462 // See if we can descend into a struct and locate a field with the correct
1463 // type.
1464 unsigned NumLayers = 0;
1465 Type *ElementTy = Ty;
1466 do {
1467 if (ElementTy->isPointerTy())
1468 break;
1469
1470 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1471 ElementTy = ArrayTy->getElementType();
1472 Indices.push_back(IRB.getIntN(OffsetSize, 0));
1473 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1474 ElementTy = VectorTy->getElementType();
1475 Indices.push_back(IRB.getInt32(0));
1476 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1477 if (STy->element_begin() == STy->element_end())
1478 break; // Nothing left to descend into.
1479 ElementTy = *STy->element_begin();
1480 Indices.push_back(IRB.getInt32(0));
1481 } else {
1482 break;
1483 }
1484 ++NumLayers;
1485 } while (ElementTy != TargetTy);
1486 if (ElementTy != TargetTy)
1487 Indices.erase(Indices.end() - NumLayers, Indices.end());
1488
1489 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1490}
1491
1492/// Get a natural GEP from a base pointer to a particular offset and
1493/// resulting in a particular type.
1494///
1495/// The goal is to produce a "natural" looking GEP that works with the existing
1496/// composite types to arrive at the appropriate offset and element type for
1497/// a pointer. TargetTy is the element type the returned GEP should point-to if
1498/// possible. We recurse by decreasing Offset, adding the appropriate index to
1499/// Indices, and setting Ty to the result subtype.
1500///
1501/// If no natural GEP can be constructed, this function returns null.
1502static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
1503 Value *Ptr, APInt Offset, Type *TargetTy,
1504 SmallVectorImpl<Value *> &Indices,
1505 const Twine &NamePrefix) {
1506 PointerType *Ty = cast<PointerType>(Ptr->getType());
1507
1508 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1509 // an i8.
1510 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
1511 return nullptr;
1512
1513 Type *ElementTy = Ty->getNonOpaquePointerElementType();
1514 if (!ElementTy->isSized())
1515 return nullptr; // We can't GEP through an unsized element.
1516
1517 SmallVector<APInt> IntIndices = DL.getGEPIndicesForOffset(ElementTy, Offset);
1518 if (Offset != 0)
1519 return nullptr;
1520
1521 for (const APInt &Index : IntIndices)
1522 Indices.push_back(IRB.getInt(Index));
1523 return getNaturalGEPWithType(IRB, DL, Ptr, ElementTy, TargetTy, Indices,
1524 NamePrefix);
1525}
1526
1527/// Compute an adjusted pointer from Ptr by Offset bytes where the
1528/// resulting pointer has PointerTy.
1529///
1530/// This tries very hard to compute a "natural" GEP which arrives at the offset
1531/// and produces the pointer type desired. Where it cannot, it will try to use
1532/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1533/// fails, it will try to use an existing i8* and GEP to the byte offset and
1534/// bitcast to the type.
1535///
1536/// The strategy for finding the more natural GEPs is to peel off layers of the
1537/// pointer, walking back through bit casts and GEPs, searching for a base
1538/// pointer from which we can compute a natural GEP with the desired
1539/// properties. The algorithm tries to fold as many constant indices into
1540/// a single GEP as possible, thus making each GEP more independent of the
1541/// surrounding code.
1542static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1543 APInt Offset, Type *PointerTy,
1544 const Twine &NamePrefix) {
1545 // Create i8 GEP for opaque pointers.
1546 if (Ptr->getType()->isOpaquePointerTy()) {
1547 if (Offset != 0)
1548 Ptr = IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Ptr, IRB.getInt(Offset),
1549 NamePrefix + "sroa_idx");
1550 return IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr, PointerTy,
1551 NamePrefix + "sroa_cast");
1552 }
1553
1554 // Even though we don't look through PHI nodes, we could be called on an
1555 // instruction in an unreachable block, which may be on a cycle.
1556 SmallPtrSet<Value *, 4> Visited;
1557 Visited.insert(Ptr);
1558 SmallVector<Value *, 4> Indices;
1559
1560 // We may end up computing an offset pointer that has the wrong type. If we
1561 // never are able to compute one directly that has the correct type, we'll
1562 // fall back to it, so keep it and the base it was computed from around here.
1563 Value *OffsetPtr = nullptr;
1564 Value *OffsetBasePtr;
1565
1566 // Remember any i8 pointer we come across to re-use if we need to do a raw
1567 // byte offset.
1568 Value *Int8Ptr = nullptr;
1569 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1570
1571 PointerType *TargetPtrTy = cast<PointerType>(PointerTy);
1572 Type *TargetTy = TargetPtrTy->getNonOpaquePointerElementType();
1573
1574 // As `addrspacecast` is , `Ptr` (the storage pointer) may have different
1575 // address space from the expected `PointerTy` (the pointer to be used).
1576 // Adjust the pointer type based the original storage pointer.
1577 auto AS = cast<PointerType>(Ptr->getType())->getAddressSpace();
1578 PointerTy = TargetTy->getPointerTo(AS);
1579
1580 do {
1581 // First fold any existing GEPs into the offset.
1582 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1583 APInt GEPOffset(Offset.getBitWidth(), 0);
1584 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
1585 break;
1586 Offset += GEPOffset;
1587 Ptr = GEP->getPointerOperand();
1588 if (!Visited.insert(Ptr).second)
1589 break;
1590 }
1591
1592 // See if we can perform a natural GEP here.
1593 Indices.clear();
1594 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
1595 Indices, NamePrefix)) {
1596 // If we have a new natural pointer at the offset, clear out any old
1597 // offset pointer we computed. Unless it is the base pointer or
1598 // a non-instruction, we built a GEP we don't need. Zap it.
1599 if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1600 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1601 assert(I->use_empty() && "Built a GEP with uses some how!")(static_cast <bool> (I->use_empty() && "Built a GEP with uses some how!"
) ? void (0) : __assert_fail ("I->use_empty() && \"Built a GEP with uses some how!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1601, __extension__ __PRETTY_FUNCTION__
))
;
1602 I->eraseFromParent();
1603 }
1604 OffsetPtr = P;
1605 OffsetBasePtr = Ptr;
1606 // If we also found a pointer of the right type, we're done.
1607 if (P->getType() == PointerTy)
1608 break;
1609 }
1610
1611 // Stash this pointer if we've found an i8*.
1612 if (Ptr->getType()->isIntegerTy(8)) {
1613 Int8Ptr = Ptr;
1614 Int8PtrOffset = Offset;
1615 }
1616
1617 // Peel off a layer of the pointer and update the offset appropriately.
1618 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1619 Ptr = cast<Operator>(Ptr)->getOperand(0);
1620 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1621 if (GA->isInterposable())
1622 break;
1623 Ptr = GA->getAliasee();
1624 } else {
1625 break;
1626 }
1627 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!")(static_cast <bool> (Ptr->getType()->isPointerTy(
) && "Unexpected operand type!") ? void (0) : __assert_fail
("Ptr->getType()->isPointerTy() && \"Unexpected operand type!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1627, __extension__ __PRETTY_FUNCTION__
))
;
1628 } while (Visited.insert(Ptr).second);
1629
1630 if (!OffsetPtr) {
1631 if (!Int8Ptr) {
1632 Int8Ptr = IRB.CreateBitCast(
1633 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1634 NamePrefix + "sroa_raw_cast");
1635 Int8PtrOffset = Offset;
1636 }
1637
1638 OffsetPtr = Int8PtrOffset == 0
1639 ? Int8Ptr
1640 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1641 IRB.getInt(Int8PtrOffset),
1642 NamePrefix + "sroa_raw_idx");
1643 }
1644 Ptr = OffsetPtr;
1645
1646 // On the off chance we were targeting i8*, guard the bitcast here.
1647 if (cast<PointerType>(Ptr->getType()) != TargetPtrTy) {
1648 Ptr = IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr,
1649 TargetPtrTy,
1650 NamePrefix + "sroa_cast");
1651 }
1652
1653 return Ptr;
1654}
1655
1656/// Compute the adjusted alignment for a load or store from an offset.
1657static Align getAdjustedAlignment(Instruction *I, uint64_t Offset) {
1658 return commonAlignment(getLoadStoreAlignment(I), Offset);
1659}
1660
1661/// Test whether we can convert a value from the old to the new type.
1662///
1663/// This predicate should be used to guard calls to convertValue in order to
1664/// ensure that we only try to convert viable values. The strategy is that we
1665/// will peel off single element struct and array wrappings to get to an
1666/// underlying value, and convert that value.
1667static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1668 if (OldTy == NewTy)
1669 return true;
1670
1671 // For integer types, we can't handle any bit-width differences. This would
1672 // break both vector conversions with extension and introduce endianness
1673 // issues when in conjunction with loads and stores.
1674 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1675 assert(cast<IntegerType>(OldTy)->getBitWidth() !=(static_cast <bool> (cast<IntegerType>(OldTy)->
getBitWidth() != cast<IntegerType>(NewTy)->getBitWidth
() && "We can't have the same bitwidth for different int types"
) ? void (0) : __assert_fail ("cast<IntegerType>(OldTy)->getBitWidth() != cast<IntegerType>(NewTy)->getBitWidth() && \"We can't have the same bitwidth for different int types\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1677, __extension__ __PRETTY_FUNCTION__
))
1676 cast<IntegerType>(NewTy)->getBitWidth() &&(static_cast <bool> (cast<IntegerType>(OldTy)->
getBitWidth() != cast<IntegerType>(NewTy)->getBitWidth
() && "We can't have the same bitwidth for different int types"
) ? void (0) : __assert_fail ("cast<IntegerType>(OldTy)->getBitWidth() != cast<IntegerType>(NewTy)->getBitWidth() && \"We can't have the same bitwidth for different int types\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1677, __extension__ __PRETTY_FUNCTION__
))
1677 "We can't have the same bitwidth for different int types")(static_cast <bool> (cast<IntegerType>(OldTy)->
getBitWidth() != cast<IntegerType>(NewTy)->getBitWidth
() && "We can't have the same bitwidth for different int types"
) ? void (0) : __assert_fail ("cast<IntegerType>(OldTy)->getBitWidth() != cast<IntegerType>(NewTy)->getBitWidth() && \"We can't have the same bitwidth for different int types\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1677, __extension__ __PRETTY_FUNCTION__
))
;
1678 return false;
1679 }
1680
1681 if (DL.getTypeSizeInBits(NewTy).getFixedSize() !=
1682 DL.getTypeSizeInBits(OldTy).getFixedSize())
1683 return false;
1684 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1685 return false;
1686
1687 // We can convert pointers to integers and vice-versa. Same for vectors
1688 // of pointers and integers.
1689 OldTy = OldTy->getScalarType();
1690 NewTy = NewTy->getScalarType();
1691 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1692 if (NewTy->isPointerTy() && OldTy->isPointerTy()) {
1693 unsigned OldAS = OldTy->getPointerAddressSpace();
1694 unsigned NewAS = NewTy->getPointerAddressSpace();
1695 // Convert pointers if they are pointers from the same address space or
1696 // different integral (not non-integral) address spaces with the same
1697 // pointer size.
1698 return OldAS == NewAS ||
1699 (!DL.isNonIntegralAddressSpace(OldAS) &&
1700 !DL.isNonIntegralAddressSpace(NewAS) &&
1701 DL.getPointerSize(OldAS) == DL.getPointerSize(NewAS));
1702 }
1703
1704 // We can convert integers to integral pointers, but not to non-integral
1705 // pointers.
1706 if (OldTy->isIntegerTy())
1707 return !DL.isNonIntegralPointerType(NewTy);
1708
1709 // We can convert integral pointers to integers, but non-integral pointers
1710 // need to remain pointers.
1711 if (!DL.isNonIntegralPointerType(OldTy))
1712 return NewTy->isIntegerTy();
1713
1714 return false;
1715 }
1716
1717 return true;
1718}
1719
1720/// Generic routine to convert an SSA value to a value of a different
1721/// type.
1722///
1723/// This will try various different casting techniques, such as bitcasts,
1724/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1725/// two types for viability with this routine.
1726static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1727 Type *NewTy) {
1728 Type *OldTy = V->getType();
1729 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type")(static_cast <bool> (canConvertValue(DL, OldTy, NewTy) &&
"Value not convertable to type") ? void (0) : __assert_fail (
"canConvertValue(DL, OldTy, NewTy) && \"Value not convertable to type\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1729, __extension__ __PRETTY_FUNCTION__
))
;
1730
1731 if (OldTy == NewTy)
1732 return V;
1733
1734 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&(static_cast <bool> (!(isa<IntegerType>(OldTy) &&
isa<IntegerType>(NewTy)) && "Integer types must be the exact same to convert."
) ? void (0) : __assert_fail ("!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) && \"Integer types must be the exact same to convert.\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1735, __extension__ __PRETTY_FUNCTION__
))
1735 "Integer types must be the exact same to convert.")(static_cast <bool> (!(isa<IntegerType>(OldTy) &&
isa<IntegerType>(NewTy)) && "Integer types must be the exact same to convert."
) ? void (0) : __assert_fail ("!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) && \"Integer types must be the exact same to convert.\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1735, __extension__ __PRETTY_FUNCTION__
))
;
1736
1737 // See if we need inttoptr for this type pair. May require additional bitcast.
1738 if (OldTy->isIntOrIntVectorTy() && NewTy->isPtrOrPtrVectorTy()) {
1739 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1740 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1741 // Expand <4 x i32> to <2 x i8*> --> <4 x i32> to <2 x i64> to <2 x i8*>
1742 // Directly handle i64 to i8*
1743 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1744 NewTy);
1745 }
1746
1747 // See if we need ptrtoint for this type pair. May require additional bitcast.
1748 if (OldTy->isPtrOrPtrVectorTy() && NewTy->isIntOrIntVectorTy()) {
1749 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1750 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1751 // Expand <2 x i8*> to <4 x i32> --> <2 x i8*> to <2 x i64> to <4 x i32>
1752 // Expand i8* to i64 --> i8* to i64 to i64
1753 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1754 NewTy);
1755 }
1756
1757 if (OldTy->isPtrOrPtrVectorTy() && NewTy->isPtrOrPtrVectorTy()) {
1758 unsigned OldAS = OldTy->getPointerAddressSpace();
1759 unsigned NewAS = NewTy->getPointerAddressSpace();
1760 // To convert pointers with different address spaces (they are already
1761 // checked convertible, i.e. they have the same pointer size), so far we
1762 // cannot use `bitcast` (which has restrict on the same address space) or
1763 // `addrspacecast` (which is not always no-op casting). Instead, use a pair
1764 // of no-op `ptrtoint`/`inttoptr` casts through an integer with the same bit
1765 // size.
1766 if (OldAS != NewAS) {
1767 assert(DL.getPointerSize(OldAS) == DL.getPointerSize(NewAS))(static_cast <bool> (DL.getPointerSize(OldAS) == DL.getPointerSize
(NewAS)) ? void (0) : __assert_fail ("DL.getPointerSize(OldAS) == DL.getPointerSize(NewAS)"
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1767, __extension__ __PRETTY_FUNCTION__
))
;
1768 return IRB.CreateIntToPtr(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1769 NewTy);
1770 }
1771 }
1772
1773 return IRB.CreateBitCast(V, NewTy);
1774}
1775
1776/// Test whether the given slice use can be promoted to a vector.
1777///
1778/// This function is called to test each entry in a partition which is slated
1779/// for a single slice.
1780static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
1781 VectorType *Ty,
1782 uint64_t ElementSize,
1783 const DataLayout &DL) {
1784 // First validate the slice offsets.
1785 uint64_t BeginOffset =
1786 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
1787 uint64_t BeginIndex = BeginOffset / ElementSize;
1788 if (BeginIndex * ElementSize != BeginOffset ||
1789 BeginIndex >= cast<FixedVectorType>(Ty)->getNumElements())
1790 return false;
1791 uint64_t EndOffset =
1792 std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
1793 uint64_t EndIndex = EndOffset / ElementSize;
1794 if (EndIndex * ElementSize != EndOffset ||
1795 EndIndex > cast<FixedVectorType>(Ty)->getNumElements())
1796 return false;
1797
1798 assert(EndIndex > BeginIndex && "Empty vector!")(static_cast <bool> (EndIndex > BeginIndex &&
"Empty vector!") ? void (0) : __assert_fail ("EndIndex > BeginIndex && \"Empty vector!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1798, __extension__ __PRETTY_FUNCTION__
))
;
1799 uint64_t NumElements = EndIndex - BeginIndex;
1800 Type *SliceTy = (NumElements == 1)
1801 ? Ty->getElementType()
1802 : FixedVectorType::get(Ty->getElementType(), NumElements);
1803
1804 Type *SplitIntTy =
1805 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1806
1807 Use *U = S.getUse();
1808
1809 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1810 if (MI->isVolatile())
1811 return false;
1812 if (!S.isSplittable())
1813 return false; // Skip any unsplittable intrinsics.
1814 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1815 if (!II->isLifetimeStartOrEnd() && !II->isDroppable())
1816 return false;
1817 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1818 if (LI->isVolatile())
1819 return false;
1820 Type *LTy = LI->getType();
1821 // Disable vector promotion when there are loads or stores of an FCA.
1822 if (LTy->isStructTy())
1823 return false;
1824 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
1825 assert(LTy->isIntegerTy())(static_cast <bool> (LTy->isIntegerTy()) ? void (0) :
__assert_fail ("LTy->isIntegerTy()", "llvm/lib/Transforms/Scalar/SROA.cpp"
, 1825, __extension__ __PRETTY_FUNCTION__))
;
1826 LTy = SplitIntTy;
1827 }
1828 if (!canConvertValue(DL, SliceTy, LTy))
1829 return false;
1830 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1831 if (SI->isVolatile())
1832 return false;
1833 Type *STy = SI->getValueOperand()->getType();
1834 // Disable vector promotion when there are loads or stores of an FCA.
1835 if (STy->isStructTy())
1836 return false;
1837 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
1838 assert(STy->isIntegerTy())(static_cast <bool> (STy->isIntegerTy()) ? void (0) :
__assert_fail ("STy->isIntegerTy()", "llvm/lib/Transforms/Scalar/SROA.cpp"
, 1838, __extension__ __PRETTY_FUNCTION__))
;
1839 STy = SplitIntTy;
1840 }
1841 if (!canConvertValue(DL, STy, SliceTy))
1842 return false;
1843 } else {
1844 return false;
1845 }
1846
1847 return true;
1848}
1849
1850/// Test whether a vector type is viable for promotion.
1851///
1852/// This implements the necessary checking for \c isVectorPromotionViable over
1853/// all slices of the alloca for the given VectorType.
1854static bool checkVectorTypeForPromotion(Partition &P, VectorType *VTy,
1855 const DataLayout &DL) {
1856 uint64_t ElementSize =
1857 DL.getTypeSizeInBits(VTy->getElementType()).getFixedSize();
1858
1859 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1860 // that aren't byte sized.
1861 if (ElementSize % 8)
1862 return false;
1863 assert((DL.getTypeSizeInBits(VTy).getFixedSize() % 8) == 0 &&(static_cast <bool> ((DL.getTypeSizeInBits(VTy).getFixedSize
() % 8) == 0 && "vector size not a multiple of element size?"
) ? void (0) : __assert_fail ("(DL.getTypeSizeInBits(VTy).getFixedSize() % 8) == 0 && \"vector size not a multiple of element size?\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1864, __extension__ __PRETTY_FUNCTION__
))
1864 "vector size not a multiple of element size?")(static_cast <bool> ((DL.getTypeSizeInBits(VTy).getFixedSize
() % 8) == 0 && "vector size not a multiple of element size?"
) ? void (0) : __assert_fail ("(DL.getTypeSizeInBits(VTy).getFixedSize() % 8) == 0 && \"vector size not a multiple of element size?\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1864, __extension__ __PRETTY_FUNCTION__
))
;
1865 ElementSize /= 8;
1866
1867 for (const Slice &S : P)
1868 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
1869 return false;
1870
1871 for (const Slice *S : P.splitSliceTails())
1872 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
1873 return false;
1874
1875 return true;
1876}
1877
1878/// Test whether the given alloca partitioning and range of slices can be
1879/// promoted to a vector.
1880///
1881/// This is a quick test to check whether we can rewrite a particular alloca
1882/// partition (and its newly formed alloca) into a vector alloca with only
1883/// whole-vector loads and stores such that it could be promoted to a vector
1884/// SSA value. We only can ensure this for a limited set of operations, and we
1885/// don't want to do the rewrites unless we are confident that the result will
1886/// be promotable, so we have an early test here.
1887static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) {
1888 // Collect the candidate types for vector-based promotion. Also track whether
1889 // we have different element types.
1890 SmallVector<VectorType *, 4> CandidateTys;
1891 Type *CommonEltTy = nullptr;
1892 bool HaveCommonEltTy = true;
1893 auto CheckCandidateType = [&](Type *Ty) {
1894 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1895 // Return if bitcast to vectors is different for total size in bits.
1896 if (!CandidateTys.empty()) {
1897 VectorType *V = CandidateTys[0];
1898 if (DL.getTypeSizeInBits(VTy).getFixedSize() !=
1899 DL.getTypeSizeInBits(V).getFixedSize()) {
1900 CandidateTys.clear();
1901 return;
1902 }
1903 }
1904 CandidateTys.push_back(VTy);
1905 if (!CommonEltTy)
1906 CommonEltTy = VTy->getElementType();
1907 else if (CommonEltTy != VTy->getElementType())
1908 HaveCommonEltTy = false;
1909 }
1910 };
1911 // Consider any loads or stores that are the exact size of the slice.
1912 for (const Slice &S : P)
1913 if (S.beginOffset() == P.beginOffset() &&
1914 S.endOffset() == P.endOffset()) {
1915 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1916 CheckCandidateType(LI->getType());
1917 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1918 CheckCandidateType(SI->getValueOperand()->getType());
1919 }
1920
1921 // If we didn't find a vector type, nothing to do here.
1922 if (CandidateTys.empty())
1923 return nullptr;
1924
1925 // Remove non-integer vector types if we had multiple common element types.
1926 // FIXME: It'd be nice to replace them with integer vector types, but we can't
1927 // do that until all the backends are known to produce good code for all
1928 // integer vector types.
1929 if (!HaveCommonEltTy) {
1930 llvm::erase_if(CandidateTys, [](VectorType *VTy) {
1931 return !VTy->getElementType()->isIntegerTy();
1932 });
1933
1934 // If there were no integer vector types, give up.
1935 if (CandidateTys.empty())
1936 return nullptr;
1937
1938 // Rank the remaining candidate vector types. This is easy because we know
1939 // they're all integer vectors. We sort by ascending number of elements.
1940 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
1941 (void)DL;
1942 assert(DL.getTypeSizeInBits(RHSTy).getFixedSize() ==(static_cast <bool> (DL.getTypeSizeInBits(RHSTy).getFixedSize
() == DL.getTypeSizeInBits(LHSTy).getFixedSize() && "Cannot have vector types of different sizes!"
) ? void (0) : __assert_fail ("DL.getTypeSizeInBits(RHSTy).getFixedSize() == DL.getTypeSizeInBits(LHSTy).getFixedSize() && \"Cannot have vector types of different sizes!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1944, __extension__ __PRETTY_FUNCTION__
))
1943 DL.getTypeSizeInBits(LHSTy).getFixedSize() &&(static_cast <bool> (DL.getTypeSizeInBits(RHSTy).getFixedSize
() == DL.getTypeSizeInBits(LHSTy).getFixedSize() && "Cannot have vector types of different sizes!"
) ? void (0) : __assert_fail ("DL.getTypeSizeInBits(RHSTy).getFixedSize() == DL.getTypeSizeInBits(LHSTy).getFixedSize() && \"Cannot have vector types of different sizes!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1944, __extension__ __PRETTY_FUNCTION__
))
1944 "Cannot have vector types of different sizes!")(static_cast <bool> (DL.getTypeSizeInBits(RHSTy).getFixedSize
() == DL.getTypeSizeInBits(LHSTy).getFixedSize() && "Cannot have vector types of different sizes!"
) ? void (0) : __assert_fail ("DL.getTypeSizeInBits(RHSTy).getFixedSize() == DL.getTypeSizeInBits(LHSTy).getFixedSize() && \"Cannot have vector types of different sizes!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1944, __extension__ __PRETTY_FUNCTION__
))
;
1945 assert(RHSTy->getElementType()->isIntegerTy() &&(static_cast <bool> (RHSTy->getElementType()->isIntegerTy
() && "All non-integer types eliminated!") ? void (0)
: __assert_fail ("RHSTy->getElementType()->isIntegerTy() && \"All non-integer types eliminated!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1946, __extension__ __PRETTY_FUNCTION__
))
1946 "All non-integer types eliminated!")(static_cast <bool> (RHSTy->getElementType()->isIntegerTy
() && "All non-integer types eliminated!") ? void (0)
: __assert_fail ("RHSTy->getElementType()->isIntegerTy() && \"All non-integer types eliminated!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1946, __extension__ __PRETTY_FUNCTION__
))
;
1947 assert(LHSTy->getElementType()->isIntegerTy() &&(static_cast <bool> (LHSTy->getElementType()->isIntegerTy
() && "All non-integer types eliminated!") ? void (0)
: __assert_fail ("LHSTy->getElementType()->isIntegerTy() && \"All non-integer types eliminated!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1948, __extension__ __PRETTY_FUNCTION__
))
1948 "All non-integer types eliminated!")(static_cast <bool> (LHSTy->getElementType()->isIntegerTy
() && "All non-integer types eliminated!") ? void (0)
: __assert_fail ("LHSTy->getElementType()->isIntegerTy() && \"All non-integer types eliminated!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1948, __extension__ __PRETTY_FUNCTION__
))
;
1949 return cast<FixedVectorType>(RHSTy)->getNumElements() <
1950 cast<FixedVectorType>(LHSTy)->getNumElements();
1951 };
1952 llvm::sort(CandidateTys, RankVectorTypes);
1953 CandidateTys.erase(
1954 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1955 CandidateTys.end());
1956 } else {
1957// The only way to have the same element type in every vector type is to
1958// have the same vector type. Check that and remove all but one.
1959#ifndef NDEBUG
1960 for (VectorType *VTy : CandidateTys) {
1961 assert(VTy->getElementType() == CommonEltTy &&(static_cast <bool> (VTy->getElementType() == CommonEltTy
&& "Unaccounted for element type!") ? void (0) : __assert_fail
("VTy->getElementType() == CommonEltTy && \"Unaccounted for element type!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1962, __extension__ __PRETTY_FUNCTION__
))
1962 "Unaccounted for element type!")(static_cast <bool> (VTy->getElementType() == CommonEltTy
&& "Unaccounted for element type!") ? void (0) : __assert_fail
("VTy->getElementType() == CommonEltTy && \"Unaccounted for element type!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1962, __extension__ __PRETTY_FUNCTION__
))
;
1963 assert(VTy == CandidateTys[0] &&(static_cast <bool> (VTy == CandidateTys[0] && "Different vector types with the same element type!"
) ? void (0) : __assert_fail ("VTy == CandidateTys[0] && \"Different vector types with the same element type!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1964, __extension__ __PRETTY_FUNCTION__
))
1964 "Different vector types with the same element type!")(static_cast <bool> (VTy == CandidateTys[0] && "Different vector types with the same element type!"
) ? void (0) : __assert_fail ("VTy == CandidateTys[0] && \"Different vector types with the same element type!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 1964, __extension__ __PRETTY_FUNCTION__
))
;
1965 }
1966#endif
1967 CandidateTys.resize(1);
1968 }
1969
1970 for (VectorType *VTy : CandidateTys)
1971 if (checkVectorTypeForPromotion(P, VTy, DL))
1972 return VTy;
1973
1974 return nullptr;
1975}
1976
1977/// Test whether a slice of an alloca is valid for integer widening.
1978///
1979/// This implements the necessary checking for the \c isIntegerWideningViable
1980/// test below on a single slice of the alloca.
1981static bool isIntegerWideningViableForSlice(const Slice &S,
1982 uint64_t AllocBeginOffset,
1983 Type *AllocaTy,
1984 const DataLayout &DL,
1985 bool &WholeAllocaOp) {
1986 uint64_t Size = DL.getTypeStoreSize(AllocaTy).getFixedSize();
1987
1988 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1989 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
1990
1991 Use *U = S.getUse();
1992
1993 // Lifetime intrinsics operate over the whole alloca whose sizes are usually
1994 // larger than other load/store slices (RelEnd > Size). But lifetime are
1995 // always promotable and should not impact other slices' promotability of the
1996 // partition.
1997 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1998 if (II->isLifetimeStartOrEnd() || II->isDroppable())
1999 return true;
2000 }
2001
2002 // We can't reasonably handle cases where the load or store extends past
2003 // the end of the alloca's type and into its padding.
2004 if (RelEnd > Size)
2005 return false;
2006
2007 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2008 if (LI->isVolatile())
2009 return false;
2010 // We can't handle loads that extend past the allocated memory.
2011 if (DL.getTypeStoreSize(LI->getType()).getFixedSize() > Size)
2012 return false;
2013 // So far, AllocaSliceRewriter does not support widening split slice tails
2014 // in rewriteIntegerLoad.
2015 if (S.beginOffset() < AllocBeginOffset)
2016 return false;
2017 // Note that we don't count vector loads or stores as whole-alloca
2018 // operations which enable integer widening because we would prefer to use
2019 // vector widening instead.
2020 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
2021 WholeAllocaOp = true;
2022 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2023 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy).getFixedSize())
2024 return false;
2025 } else if (RelBegin != 0 || RelEnd != Size ||
2026 !canConvertValue(DL, AllocaTy, LI->getType())) {
2027 // Non-integer loads need to be convertible from the alloca type so that
2028 // they are promotable.
2029 return false;
2030 }
2031 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2032 Type *ValueTy = SI->getValueOperand()->getType();
2033 if (SI->isVolatile())
2034 return false;
2035 // We can't handle stores that extend past the allocated memory.
2036 if (DL.getTypeStoreSize(ValueTy).getFixedSize() > Size)
2037 return false;
2038 // So far, AllocaSliceRewriter does not support widening split slice tails
2039 // in rewriteIntegerStore.
2040 if (S.beginOffset() < AllocBeginOffset)
2041 return false;
2042 // Note that we don't count vector loads or stores as whole-alloca
2043 // operations which enable integer widening because we would prefer to use
2044 // vector widening instead.
2045 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
2046 WholeAllocaOp = true;
2047 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2048 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy).getFixedSize())
2049 return false;
2050 } else if (RelBegin != 0 || RelEnd != Size ||
2051 !canConvertValue(DL, ValueTy, AllocaTy)) {
2052 // Non-integer stores need to be convertible to the alloca type so that
2053 // they are promotable.
2054 return false;
2055 }
2056 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2057 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2058 return false;
2059 if (!S.isSplittable())
2060 return false; // Skip any unsplittable intrinsics.
2061 } else {
2062 return false;
2063 }
2064
2065 return true;
2066}
2067
2068/// Test whether the given alloca partition's integer operations can be
2069/// widened to promotable ones.
2070///
2071/// This is a quick test to check whether we can rewrite the integer loads and
2072/// stores to a particular alloca into wider loads and stores and be able to
2073/// promote the resulting alloca.
2074static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
2075 const DataLayout &DL) {
2076 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy).getFixedSize();
2077 // Don't create integer types larger than the maximum bitwidth.
2078 if (SizeInBits > IntegerType::MAX_INT_BITS)
2079 return false;
2080
2081 // Don't try to handle allocas with bit-padding.
2082 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy).getFixedSize())
2083 return false;
2084
2085 // We need to ensure that an integer type with the appropriate bitwidth can
2086 // be converted to the alloca type, whatever that is. We don't want to force
2087 // the alloca itself to have an integer type if there is a more suitable one.
2088 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2089 if (!canConvertValue(DL, AllocaTy, IntTy) ||
2090 !canConvertValue(DL, IntTy, AllocaTy))
2091 return false;
2092
2093 // While examining uses, we ensure that the alloca has a covering load or
2094 // store. We don't want to widen the integer operations only to fail to
2095 // promote due to some other unsplittable entry (which we may make splittable
2096 // later). However, if there are only splittable uses, go ahead and assume
2097 // that we cover the alloca.
2098 // FIXME: We shouldn't consider split slices that happen to start in the
2099 // partition here...
2100 bool WholeAllocaOp = P.empty() && DL.isLegalInteger(SizeInBits);
2101
2102 for (const Slice &S : P)
2103 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2104 WholeAllocaOp))
2105 return false;
2106
2107 for (const Slice *S : P.splitSliceTails())
2108 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2109 WholeAllocaOp))
2110 return false;
2111
2112 return WholeAllocaOp;
2113}
2114
2115static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
2116 IntegerType *Ty, uint64_t Offset,
2117 const Twine &Name) {
2118 LLVM_DEBUG(dbgs() << " start: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " start: " << *V <<
"\n"; } } while (false)
;
2119 IntegerType *IntTy = cast<IntegerType>(V->getType());
2120 assert(DL.getTypeStoreSize(Ty).getFixedSize() + Offset <=(static_cast <bool> (DL.getTypeStoreSize(Ty).getFixedSize
() + Offset <= DL.getTypeStoreSize(IntTy).getFixedSize() &&
"Element extends past full value") ? void (0) : __assert_fail
("DL.getTypeStoreSize(Ty).getFixedSize() + Offset <= DL.getTypeStoreSize(IntTy).getFixedSize() && \"Element extends past full value\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2122, __extension__ __PRETTY_FUNCTION__
))
2121 DL.getTypeStoreSize(IntTy).getFixedSize() &&(static_cast <bool> (DL.getTypeStoreSize(Ty).getFixedSize
() + Offset <= DL.getTypeStoreSize(IntTy).getFixedSize() &&
"Element extends past full value") ? void (0) : __assert_fail
("DL.getTypeStoreSize(Ty).getFixedSize() + Offset <= DL.getTypeStoreSize(IntTy).getFixedSize() && \"Element extends past full value\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2122, __extension__ __PRETTY_FUNCTION__
))
2122 "Element extends past full value")(static_cast <bool> (DL.getTypeStoreSize(Ty).getFixedSize
() + Offset <= DL.getTypeStoreSize(IntTy).getFixedSize() &&
"Element extends past full value") ? void (0) : __assert_fail
("DL.getTypeStoreSize(Ty).getFixedSize() + Offset <= DL.getTypeStoreSize(IntTy).getFixedSize() && \"Element extends past full value\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2122, __extension__ __PRETTY_FUNCTION__
))
;
2123 uint64_t ShAmt = 8 * Offset;
2124 if (DL.isBigEndian())
2125 ShAmt = 8 * (DL.getTypeStoreSize(IntTy).getFixedSize() -
2126 DL.getTypeStoreSize(Ty).getFixedSize() - Offset);
2127 if (ShAmt) {
2128 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
2129 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " shifted: " << *V <<
"\n"; } } while (false)
;
2130 }
2131 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&(static_cast <bool> (Ty->getBitWidth() <= IntTy->
getBitWidth() && "Cannot extract to a larger integer!"
) ? void (0) : __assert_fail ("Ty->getBitWidth() <= IntTy->getBitWidth() && \"Cannot extract to a larger integer!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2132, __extension__ __PRETTY_FUNCTION__
))
2132 "Cannot extract to a larger integer!")(static_cast <bool> (Ty->getBitWidth() <= IntTy->
getBitWidth() && "Cannot extract to a larger integer!"
) ? void (0) : __assert_fail ("Ty->getBitWidth() <= IntTy->getBitWidth() && \"Cannot extract to a larger integer!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2132, __extension__ __PRETTY_FUNCTION__
))
;
2133 if (Ty != IntTy) {
2134 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
2135 LLVM_DEBUG(dbgs() << " trunced: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " trunced: " << *V <<
"\n"; } } while (false)
;
2136 }
2137 return V;
2138}
2139
2140static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
2141 Value *V, uint64_t Offset, const Twine &Name) {
2142 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2143 IntegerType *Ty = cast<IntegerType>(V->getType());
2144 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&(static_cast <bool> (Ty->getBitWidth() <= IntTy->
getBitWidth() && "Cannot insert a larger integer!") ?
void (0) : __assert_fail ("Ty->getBitWidth() <= IntTy->getBitWidth() && \"Cannot insert a larger integer!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2145, __extension__ __PRETTY_FUNCTION__
))
2145 "Cannot insert a larger integer!")(static_cast <bool> (Ty->getBitWidth() <= IntTy->
getBitWidth() && "Cannot insert a larger integer!") ?
void (0) : __assert_fail ("Ty->getBitWidth() <= IntTy->getBitWidth() && \"Cannot insert a larger integer!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2145, __extension__ __PRETTY_FUNCTION__
))
;
2146 LLVM_DEBUG(dbgs() << " start: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " start: " << *V <<
"\n"; } } while (false)
;
2147 if (Ty != IntTy) {
2148 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
2149 LLVM_DEBUG(dbgs() << " extended: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " extended: " << *V <<
"\n"; } } while (false)
;
2150 }
2151 assert(DL.getTypeStoreSize(Ty).getFixedSize() + Offset <=(static_cast <bool> (DL.getTypeStoreSize(Ty).getFixedSize
() + Offset <= DL.getTypeStoreSize(IntTy).getFixedSize() &&
"Element store outside of alloca store") ? void (0) : __assert_fail
("DL.getTypeStoreSize(Ty).getFixedSize() + Offset <= DL.getTypeStoreSize(IntTy).getFixedSize() && \"Element store outside of alloca store\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2153, __extension__ __PRETTY_FUNCTION__
))
2152 DL.getTypeStoreSize(IntTy).getFixedSize() &&(static_cast <bool> (DL.getTypeStoreSize(Ty).getFixedSize
() + Offset <= DL.getTypeStoreSize(IntTy).getFixedSize() &&
"Element store outside of alloca store") ? void (0) : __assert_fail
("DL.getTypeStoreSize(Ty).getFixedSize() + Offset <= DL.getTypeStoreSize(IntTy).getFixedSize() && \"Element store outside of alloca store\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2153, __extension__ __PRETTY_FUNCTION__
))
2153 "Element store outside of alloca store")(static_cast <bool> (DL.getTypeStoreSize(Ty).getFixedSize
() + Offset <= DL.getTypeStoreSize(IntTy).getFixedSize() &&
"Element store outside of alloca store") ? void (0) : __assert_fail
("DL.getTypeStoreSize(Ty).getFixedSize() + Offset <= DL.getTypeStoreSize(IntTy).getFixedSize() && \"Element store outside of alloca store\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2153, __extension__ __PRETTY_FUNCTION__
))
;
2154 uint64_t ShAmt = 8 * Offset;
2155 if (DL.isBigEndian())
2156 ShAmt = 8 * (DL.getTypeStoreSize(IntTy).getFixedSize() -
2157 DL.getTypeStoreSize(Ty).getFixedSize() - Offset);
2158 if (ShAmt) {
2159 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
2160 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " shifted: " << *V <<
"\n"; } } while (false)
;
2161 }
2162
2163 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2164 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2165 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
2166 LLVM_DEBUG(dbgs() << " masked: " << *Old << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " masked: " << *Old <<
"\n"; } } while (false)
;
2167 V = IRB.CreateOr(Old, V, Name + ".insert");
2168 LLVM_DEBUG(dbgs() << " inserted: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " inserted: " << *V <<
"\n"; } } while (false)
;
2169 }
2170 return V;
2171}
2172
2173static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2174 unsigned EndIndex, const Twine &Name) {
2175 auto *VecTy = cast<FixedVectorType>(V->getType());
2176 unsigned NumElements = EndIndex - BeginIndex;
2177 assert(NumElements <= VecTy->getNumElements() && "Too many elements!")(static_cast <bool> (NumElements <= VecTy->getNumElements
() && "Too many elements!") ? void (0) : __assert_fail
("NumElements <= VecTy->getNumElements() && \"Too many elements!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2177, __extension__ __PRETTY_FUNCTION__
))
;
2178
2179 if (NumElements == VecTy->getNumElements())
2180 return V;
2181
2182 if (NumElements == 1) {
2183 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2184 Name + ".extract");
2185 LLVM_DEBUG(dbgs() << " extract: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " extract: " << *V <<
"\n"; } } while (false)
;
2186 return V;
2187 }
2188
2189 auto Mask = llvm::to_vector<8>(llvm::seq<int>(BeginIndex, EndIndex));
2190 V = IRB.CreateShuffleVector(V, Mask, Name + ".extract");
2191 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " shuffle: " << *V <<
"\n"; } } while (false)
;
2192 return V;
2193}
2194
2195static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
2196 unsigned BeginIndex, const Twine &Name) {
2197 VectorType *VecTy = cast<VectorType>(Old->getType());
2198 assert(VecTy && "Can only insert a vector into a vector")(static_cast <bool> (VecTy && "Can only insert a vector into a vector"
) ? void (0) : __assert_fail ("VecTy && \"Can only insert a vector into a vector\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2198, __extension__ __PRETTY_FUNCTION__
))
;
2199
2200 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2201 if (!Ty) {
2202 // Single element to insert.
2203 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2204 Name + ".insert");
2205 LLVM_DEBUG(dbgs() << " insert: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " insert: " << *V <<
"\n"; } } while (false)
;
2206 return V;
2207 }
2208
2209 assert(cast<FixedVectorType>(Ty)->getNumElements() <=(static_cast <bool> (cast<FixedVectorType>(Ty)->
getNumElements() <= cast<FixedVectorType>(VecTy)->
getNumElements() && "Too many elements!") ? void (0) :
__assert_fail ("cast<FixedVectorType>(Ty)->getNumElements() <= cast<FixedVectorType>(VecTy)->getNumElements() && \"Too many elements!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2211, __extension__ __PRETTY_FUNCTION__
))
2210 cast<FixedVectorType>(VecTy)->getNumElements() &&(static_cast <bool> (cast<FixedVectorType>(Ty)->
getNumElements() <= cast<FixedVectorType>(VecTy)->
getNumElements() && "Too many elements!") ? void (0) :
__assert_fail ("cast<FixedVectorType>(Ty)->getNumElements() <= cast<FixedVectorType>(VecTy)->getNumElements() && \"Too many elements!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2211, __extension__ __PRETTY_FUNCTION__
))
2211 "Too many elements!")(static_cast <bool> (cast<FixedVectorType>(Ty)->
getNumElements() <= cast<FixedVectorType>(VecTy)->
getNumElements() && "Too many elements!") ? void (0) :
__assert_fail ("cast<FixedVectorType>(Ty)->getNumElements() <= cast<FixedVectorType>(VecTy)->getNumElements() && \"Too many elements!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2211, __extension__ __PRETTY_FUNCTION__
))
;
2212 if (cast<FixedVectorType>(Ty)->getNumElements() ==
2213 cast<FixedVectorType>(VecTy)->getNumElements()) {
2214 assert(V->getType() == VecTy && "Vector type mismatch")(static_cast <bool> (V->getType() == VecTy &&
"Vector type mismatch") ? void (0) : __assert_fail ("V->getType() == VecTy && \"Vector type mismatch\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2214, __extension__ __PRETTY_FUNCTION__
))
;
2215 return V;
2216 }
2217 unsigned EndIndex = BeginIndex + cast<FixedVectorType>(Ty)->getNumElements();
2218
2219 // When inserting a smaller vector into the larger to store, we first
2220 // use a shuffle vector to widen it with undef elements, and then
2221 // a second shuffle vector to select between the loaded vector and the
2222 // incoming vector.
2223 SmallVector<int, 8> Mask;
2224 Mask.reserve(cast<FixedVectorType>(VecTy)->getNumElements());
2225 for (unsigned i = 0; i != cast<FixedVectorType>(VecTy)->getNumElements(); ++i)
2226 if (i >= BeginIndex && i < EndIndex)
2227 Mask.push_back(i - BeginIndex);
2228 else
2229 Mask.push_back(-1);
2230 V = IRB.CreateShuffleVector(V, Mask, Name + ".expand");
2231 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " shuffle: " << *V <<
"\n"; } } while (false)
;
2232
2233 SmallVector<Constant *, 8> Mask2;
2234 Mask2.reserve(cast<FixedVectorType>(VecTy)->getNumElements());
2235 for (unsigned i = 0; i != cast<FixedVectorType>(VecTy)->getNumElements(); ++i)
2236 Mask2.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2237
2238 V = IRB.CreateSelect(ConstantVector::get(Mask2), V, Old, Name + "blend");
2239
2240 LLVM_DEBUG(dbgs() << " blend: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " blend: " << *V <<
"\n"; } } while (false)
;
2241 return V;
2242}
2243
2244/// Visitor to rewrite instructions using p particular slice of an alloca
2245/// to use a new alloca.
2246///
2247/// Also implements the rewriting to vector-based accesses when the partition
2248/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2249/// lives here.
2250class llvm::sroa::AllocaSliceRewriter
2251 : public InstVisitor<AllocaSliceRewriter, bool> {
2252 // Befriend the base class so it can delegate to private visit methods.
2253 friend class InstVisitor<AllocaSliceRewriter, bool>;
2254
2255 using Base = InstVisitor<AllocaSliceRewriter, bool>;
2256
2257 const DataLayout &DL;
2258 AllocaSlices &AS;
2259 SROAPass &Pass;
2260 AllocaInst &OldAI, &NewAI;
2261 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2262 Type *NewAllocaTy;
2263
2264 // This is a convenience and flag variable that will be null unless the new
2265 // alloca's integer operations should be widened to this integer type due to
2266 // passing isIntegerWideningViable above. If it is non-null, the desired
2267 // integer type will be stored here for easy access during rewriting.
2268 IntegerType *IntTy;
2269
2270 // If we are rewriting an alloca partition which can be written as pure
2271 // vector operations, we stash extra information here. When VecTy is
2272 // non-null, we have some strict guarantees about the rewritten alloca:
2273 // - The new alloca is exactly the size of the vector type here.
2274 // - The accesses all either map to the entire vector or to a single
2275 // element.
2276 // - The set of accessing instructions is only one of those handled above
2277 // in isVectorPromotionViable. Generally these are the same access kinds
2278 // which are promotable via mem2reg.
2279 VectorType *VecTy;
2280 Type *ElementTy;
2281 uint64_t ElementSize;
2282
2283 // The original offset of the slice currently being rewritten relative to
2284 // the original alloca.
2285 uint64_t BeginOffset = 0;
2286 uint64_t EndOffset = 0;
2287
2288 // The new offsets of the slice currently being rewritten relative to the
2289 // original alloca.
2290 uint64_t NewBeginOffset = 0, NewEndOffset = 0;
2291
2292 uint64_t SliceSize = 0;
2293 bool IsSplittable = false;
2294 bool IsSplit = false;
2295 Use *OldUse = nullptr;
2296 Instruction *OldPtr = nullptr;
2297
2298 // Track post-rewrite users which are PHI nodes and Selects.
2299 SmallSetVector<PHINode *, 8> &PHIUsers;
2300 SmallSetVector<SelectInst *, 8> &SelectUsers;
2301
2302 // Utility IR builder, whose name prefix is setup for each visited use, and
2303 // the insertion point is set to point to the user.
2304 IRBuilderTy IRB;
2305
2306public:
2307 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROAPass &Pass,
2308 AllocaInst &OldAI, AllocaInst &NewAI,
2309 uint64_t NewAllocaBeginOffset,
2310 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2311 VectorType *PromotableVecTy,
2312 SmallSetVector<PHINode *, 8> &PHIUsers,
2313 SmallSetVector<SelectInst *, 8> &SelectUsers)
2314 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
2315 NewAllocaBeginOffset(NewAllocaBeginOffset),
2316 NewAllocaEndOffset(NewAllocaEndOffset),
2317 NewAllocaTy(NewAI.getAllocatedType()),
2318 IntTy(
2319 IsIntegerPromotable
2320 ? Type::getIntNTy(NewAI.getContext(),
2321 DL.getTypeSizeInBits(NewAI.getAllocatedType())
2322 .getFixedSize())
2323 : nullptr),
2324 VecTy(PromotableVecTy),
2325 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2326 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy).getFixedSize() / 8
2327 : 0),
2328 PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2329 IRB(NewAI.getContext(), ConstantFolder()) {
2330 if (VecTy) {
2331 assert((DL.getTypeSizeInBits(ElementTy).getFixedSize() % 8) == 0 &&(static_cast <bool> ((DL.getTypeSizeInBits(ElementTy).getFixedSize
() % 8) == 0 && "Only multiple-of-8 sized vector elements are viable"
) ? void (0) : __assert_fail ("(DL.getTypeSizeInBits(ElementTy).getFixedSize() % 8) == 0 && \"Only multiple-of-8 sized vector elements are viable\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2332, __extension__ __PRETTY_FUNCTION__
))
2332 "Only multiple-of-8 sized vector elements are viable")(static_cast <bool> ((DL.getTypeSizeInBits(ElementTy).getFixedSize
() % 8) == 0 && "Only multiple-of-8 sized vector elements are viable"
) ? void (0) : __assert_fail ("(DL.getTypeSizeInBits(ElementTy).getFixedSize() % 8) == 0 && \"Only multiple-of-8 sized vector elements are viable\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2332, __extension__ __PRETTY_FUNCTION__
))
;
2333 ++NumVectorized;
2334 }
2335 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy))(static_cast <bool> ((!IntTy && !VecTy) || (IntTy
&& !VecTy) || (!IntTy && VecTy)) ? void (0) :
__assert_fail ("(!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy)"
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2335, __extension__ __PRETTY_FUNCTION__
))
;
2336 }
2337
2338 bool visit(AllocaSlices::const_iterator I) {
2339 bool CanSROA = true;
2340 BeginOffset = I->beginOffset();
2341 EndOffset = I->endOffset();
2342 IsSplittable = I->isSplittable();
2343 IsSplit =
2344 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2345 LLVM_DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " rewriting " << (IsSplit ?
"split " : ""); } } while (false)
;
2346 LLVM_DEBUG(AS.printSlice(dbgs(), I, ""))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { AS.printSlice(dbgs(), I, ""); } } while (false)
;
2347 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "\n"; } } while (false)
;
2348
2349 // Compute the intersecting offset range.
2350 assert(BeginOffset < NewAllocaEndOffset)(static_cast <bool> (BeginOffset < NewAllocaEndOffset
) ? void (0) : __assert_fail ("BeginOffset < NewAllocaEndOffset"
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2350, __extension__ __PRETTY_FUNCTION__
))
;
2351 assert(EndOffset > NewAllocaBeginOffset)(static_cast <bool> (EndOffset > NewAllocaBeginOffset
) ? void (0) : __assert_fail ("EndOffset > NewAllocaBeginOffset"
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2351, __extension__ __PRETTY_FUNCTION__
))
;
2352 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2353 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2354
2355 SliceSize = NewEndOffset - NewBeginOffset;
2356
2357 OldUse = I->getUse();
2358 OldPtr = cast<Instruction>(OldUse->get());
2359
2360 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2361 IRB.SetInsertPoint(OldUserI);
2362 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2363 IRB.getInserter().SetNamePrefix(
2364 Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2365
2366 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2367 if (VecTy || IntTy)
2368 assert(CanSROA)(static_cast <bool> (CanSROA) ? void (0) : __assert_fail
("CanSROA", "llvm/lib/Transforms/Scalar/SROA.cpp", 2368, __extension__
__PRETTY_FUNCTION__))
;
2369 return CanSROA;
2370 }
2371
2372private:
2373 // Make sure the other visit overloads are visible.
2374 using Base::visit;
2375
2376 // Every instruction which can end up as a user must have a rewrite rule.
2377 bool visitInstruction(Instruction &I) {
2378 LLVM_DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " !!!! Cannot rewrite: " <<
I << "\n"; } } while (false)
;
2379 llvm_unreachable("No rewrite rule for this instruction!")::llvm::llvm_unreachable_internal("No rewrite rule for this instruction!"
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2379)
;
2380 }
2381
2382 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2383 // Note that the offset computation can use BeginOffset or NewBeginOffset
2384 // interchangeably for unsplit slices.
2385 assert(IsSplit || BeginOffset == NewBeginOffset)(static_cast <bool> (IsSplit || BeginOffset == NewBeginOffset
) ? void (0) : __assert_fail ("IsSplit || BeginOffset == NewBeginOffset"
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2385, __extension__ __PRETTY_FUNCTION__
))
;
2386 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2387
2388#ifndef NDEBUG
2389 StringRef OldName = OldPtr->getName();
2390 // Skip through the last '.sroa.' component of the name.
2391 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2392 if (LastSROAPrefix != StringRef::npos) {
2393 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2394 // Look for an SROA slice index.
2395 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2396 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2397 // Strip the index and look for the offset.
2398 OldName = OldName.substr(IndexEnd + 1);
2399 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2400 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2401 // Strip the offset.
2402 OldName = OldName.substr(OffsetEnd + 1);
2403 }
2404 }
2405 // Strip any SROA suffixes as well.
2406 OldName = OldName.substr(0, OldName.find(".sroa_"));
2407#endif
2408
2409 return getAdjustedPtr(IRB, DL, &NewAI,
2410 APInt(DL.getIndexTypeSizeInBits(PointerTy), Offset),
2411 PointerTy,
2412#ifndef NDEBUG
2413 Twine(OldName) + "."
2414#else
2415 Twine()
2416#endif
2417 );
2418 }
2419
2420 /// Compute suitable alignment to access this slice of the *new*
2421 /// alloca.
2422 ///
2423 /// You can optionally pass a type to this routine and if that type's ABI
2424 /// alignment is itself suitable, this will return zero.
2425 Align getSliceAlign() {
2426 return commonAlignment(NewAI.getAlign(),
2427 NewBeginOffset - NewAllocaBeginOffset);
2428 }
2429
2430 unsigned getIndex(uint64_t Offset) {
2431 assert(VecTy && "Can only call getIndex when rewriting a vector")(static_cast <bool> (VecTy && "Can only call getIndex when rewriting a vector"
) ? void (0) : __assert_fail ("VecTy && \"Can only call getIndex when rewriting a vector\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2431, __extension__ __PRETTY_FUNCTION__
))
;
2432 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2433 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds")(static_cast <bool> (RelOffset / ElementSize < (4294967295U
) && "Index out of bounds") ? void (0) : __assert_fail
("RelOffset / ElementSize < UINT32_MAX && \"Index out of bounds\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2433, __extension__ __PRETTY_FUNCTION__
))
;
2434 uint32_t Index = RelOffset / ElementSize;
2435 assert(Index * ElementSize == RelOffset)(static_cast <bool> (Index * ElementSize == RelOffset) ?
void (0) : __assert_fail ("Index * ElementSize == RelOffset"
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2435, __extension__ __PRETTY_FUNCTION__
))
;
2436 return Index;
2437 }
2438
2439 void deleteIfTriviallyDead(Value *V) {
2440 Instruction *I = cast<Instruction>(V);
2441 if (isInstructionTriviallyDead(I))
2442 Pass.DeadInsts.push_back(I);
2443 }
2444
2445 Value *rewriteVectorizedLoadInst(LoadInst &LI) {
2446 unsigned BeginIndex = getIndex(NewBeginOffset);
2447 unsigned EndIndex = getIndex(NewEndOffset);
2448 assert(EndIndex > BeginIndex && "Empty vector!")(static_cast <bool> (EndIndex > BeginIndex &&
"Empty vector!") ? void (0) : __assert_fail ("EndIndex > BeginIndex && \"Empty vector!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2448, __extension__ __PRETTY_FUNCTION__
))
;
2449
2450 LoadInst *Load = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2451 NewAI.getAlign(), "load");
2452
2453 Load->copyMetadata(LI, {LLVMContext::MD_mem_parallel_loop_access,
2454 LLVMContext::MD_access_group});
2455 return extractVector(IRB, Load, BeginIndex, EndIndex, "vec");
2456 }
2457
2458 Value *rewriteIntegerLoad(LoadInst &LI) {
2459 assert(IntTy && "We cannot insert an integer to the alloca")(static_cast <bool> (IntTy && "We cannot insert an integer to the alloca"
) ? void (0) : __assert_fail ("IntTy && \"We cannot insert an integer to the alloca\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2459, __extension__ __PRETTY_FUNCTION__
))
;
2460 assert(!LI.isVolatile())(static_cast <bool> (!LI.isVolatile()) ? void (0) : __assert_fail
("!LI.isVolatile()", "llvm/lib/Transforms/Scalar/SROA.cpp", 2460
, __extension__ __PRETTY_FUNCTION__))
;
2461 Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2462 NewAI.getAlign(), "load");
2463 V = convertValue(DL, IRB, V, IntTy);
2464 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset")(static_cast <bool> (NewBeginOffset >= NewAllocaBeginOffset
&& "Out of bounds offset") ? void (0) : __assert_fail
("NewBeginOffset >= NewAllocaBeginOffset && \"Out of bounds offset\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2464, __extension__ __PRETTY_FUNCTION__
))
;
2465 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2466 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
2467 IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
2468 V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
2469 }
2470 // It is possible that the extracted type is not the load type. This
2471 // happens if there is a load past the end of the alloca, and as
2472 // a consequence the slice is narrower but still a candidate for integer
2473 // lowering. To handle this case, we just zero extend the extracted
2474 // integer.
2475 assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&(static_cast <bool> (cast<IntegerType>(LI.getType
())->getBitWidth() >= SliceSize * 8 && "Can only handle an extract for an overly wide load"
) ? void (0) : __assert_fail ("cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 && \"Can only handle an extract for an overly wide load\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2476, __extension__ __PRETTY_FUNCTION__
))
2476 "Can only handle an extract for an overly wide load")(static_cast <bool> (cast<IntegerType>(LI.getType
())->getBitWidth() >= SliceSize * 8 && "Can only handle an extract for an overly wide load"
) ? void (0) : __assert_fail ("cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 && \"Can only handle an extract for an overly wide load\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2476, __extension__ __PRETTY_FUNCTION__
))
;
2477 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
2478 V = IRB.CreateZExt(V, LI.getType());
2479 return V;
2480 }
2481
2482 bool visitLoadInst(LoadInst &LI) {
2483 LLVM_DEBUG(dbgs() << " original: " << LI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << LI <<
"\n"; } } while (false)
;
2484 Value *OldOp = LI.getOperand(0);
2485 assert(OldOp == OldPtr)(static_cast <bool> (OldOp == OldPtr) ? void (0) : __assert_fail
("OldOp == OldPtr", "llvm/lib/Transforms/Scalar/SROA.cpp", 2485
, __extension__ __PRETTY_FUNCTION__))
;
2486
2487 AAMDNodes AATags = LI.getAAMetadata();
2488
2489 unsigned AS = LI.getPointerAddressSpace();
2490
2491 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
2492 : LI.getType();
2493 const bool IsLoadPastEnd =
2494 DL.getTypeStoreSize(TargetTy).getFixedSize() > SliceSize;
2495 bool IsPtrAdjusted = false;
2496 Value *V;
2497 if (VecTy) {
2498 V = rewriteVectorizedLoadInst(LI);
2499 } else if (IntTy && LI.getType()->isIntegerTy()) {
2500 V = rewriteIntegerLoad(LI);
2501 } else if (NewBeginOffset == NewAllocaBeginOffset &&
2502 NewEndOffset == NewAllocaEndOffset &&
2503 (canConvertValue(DL, NewAllocaTy, TargetTy) ||
2504 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
2505 TargetTy->isIntegerTy()))) {
2506 LoadInst *NewLI = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2507 NewAI.getAlign(), LI.isVolatile(),
2508 LI.getName());
2509 if (AATags)
2510 NewLI->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
2511 if (LI.isVolatile())
2512 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
2513 if (NewLI->isAtomic())
2514 NewLI->setAlignment(LI.getAlign());
2515
2516 // Any !nonnull metadata or !range metadata on the old load is also valid
2517 // on the new load. This is even true in some cases even when the loads
2518 // are different types, for example by mapping !nonnull metadata to
2519 // !range metadata by modeling the null pointer constant converted to the
2520 // integer type.
2521 // FIXME: Add support for range metadata here. Currently the utilities
2522 // for this don't propagate range metadata in trivial cases from one
2523 // integer load to another, don't handle non-addrspace-0 null pointers
2524 // correctly, and don't have any support for mapping ranges as the
2525 // integer type becomes winder or narrower.
2526 if (MDNode *N = LI.getMetadata(LLVMContext::MD_nonnull))
2527 copyNonnullMetadata(LI, N, *NewLI);
2528
2529 // Try to preserve nonnull metadata
2530 V = NewLI;
2531
2532 // If this is an integer load past the end of the slice (which means the
2533 // bytes outside the slice are undef or this load is dead) just forcibly
2534 // fix the integer size with correct handling of endianness.
2535 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2536 if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
2537 if (AITy->getBitWidth() < TITy->getBitWidth()) {
2538 V = IRB.CreateZExt(V, TITy, "load.ext");
2539 if (DL.isBigEndian())
2540 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2541 "endian_shift");
2542 }
2543 } else {
2544 Type *LTy = TargetTy->getPointerTo(AS);
2545 LoadInst *NewLI =
2546 IRB.CreateAlignedLoad(TargetTy, getNewAllocaSlicePtr(IRB, LTy),
2547 getSliceAlign(), LI.isVolatile(), LI.getName());
2548 if (AATags)
2549 NewLI->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
2550 if (LI.isVolatile())
2551 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
2552 NewLI->copyMetadata(LI, {LLVMContext::MD_mem_parallel_loop_access,
2553 LLVMContext::MD_access_group});
2554
2555 V = NewLI;
2556 IsPtrAdjusted = true;
2557 }
2558 V = convertValue(DL, IRB, V, TargetTy);
2559
2560 if (IsSplit) {
2561 assert(!LI.isVolatile())(static_cast <bool> (!LI.isVolatile()) ? void (0) : __assert_fail
("!LI.isVolatile()", "llvm/lib/Transforms/Scalar/SROA.cpp", 2561
, __extension__ __PRETTY_FUNCTION__))
;
2562 assert(LI.getType()->isIntegerTy() &&(static_cast <bool> (LI.getType()->isIntegerTy() &&
"Only integer type loads and stores are split") ? void (0) :
__assert_fail ("LI.getType()->isIntegerTy() && \"Only integer type loads and stores are split\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2563, __extension__ __PRETTY_FUNCTION__
))
2563 "Only integer type loads and stores are split")(static_cast <bool> (LI.getType()->isIntegerTy() &&
"Only integer type loads and stores are split") ? void (0) :
__assert_fail ("LI.getType()->isIntegerTy() && \"Only integer type loads and stores are split\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2563, __extension__ __PRETTY_FUNCTION__
))
;
2564 assert(SliceSize < DL.getTypeStoreSize(LI.getType()).getFixedSize() &&(static_cast <bool> (SliceSize < DL.getTypeStoreSize
(LI.getType()).getFixedSize() && "Split load isn't smaller than original load"
) ? void (0) : __assert_fail ("SliceSize < DL.getTypeStoreSize(LI.getType()).getFixedSize() && \"Split load isn't smaller than original load\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2565, __extension__ __PRETTY_FUNCTION__
))
2565 "Split load isn't smaller than original load")(static_cast <bool> (SliceSize < DL.getTypeStoreSize
(LI.getType()).getFixedSize() && "Split load isn't smaller than original load"
) ? void (0) : __assert_fail ("SliceSize < DL.getTypeStoreSize(LI.getType()).getFixedSize() && \"Split load isn't smaller than original load\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2565, __extension__ __PRETTY_FUNCTION__
))
;
2566 assert(DL.typeSizeEqualsStoreSize(LI.getType()) &&(static_cast <bool> (DL.typeSizeEqualsStoreSize(LI.getType
()) && "Non-byte-multiple bit width") ? void (0) : __assert_fail
("DL.typeSizeEqualsStoreSize(LI.getType()) && \"Non-byte-multiple bit width\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2567, __extension__ __PRETTY_FUNCTION__
))
2567 "Non-byte-multiple bit width")(static_cast <bool> (DL.typeSizeEqualsStoreSize(LI.getType
()) && "Non-byte-multiple bit width") ? void (0) : __assert_fail
("DL.typeSizeEqualsStoreSize(LI.getType()) && \"Non-byte-multiple bit width\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2567, __extension__ __PRETTY_FUNCTION__
))
;
2568 // Move the insertion point just past the load so that we can refer to it.
2569 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
2570 // Create a placeholder value with the same type as LI to use as the
2571 // basis for the new value. This allows us to replace the uses of LI with
2572 // the computed value, and then replace the placeholder with LI, leaving
2573 // LI only used for this computation.
2574 Value *Placeholder = new LoadInst(
2575 LI.getType(), PoisonValue::get(LI.getType()->getPointerTo(AS)), "",
2576 false, Align(1));
2577 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2578 "insert");
2579 LI.replaceAllUsesWith(V);
2580 Placeholder->replaceAllUsesWith(&LI);
2581 Placeholder->deleteValue();
2582 } else {
2583 LI.replaceAllUsesWith(V);
2584 }
2585
2586 Pass.DeadInsts.push_back(&LI);
2587 deleteIfTriviallyDead(OldOp);
2588 LLVM_DEBUG(dbgs() << " to: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *V <<
"\n"; } } while (false)
;
2589 return !LI.isVolatile() && !IsPtrAdjusted;
2590 }
2591
2592 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2593 AAMDNodes AATags) {
2594 if (V->getType() != VecTy) {
2595 unsigned BeginIndex = getIndex(NewBeginOffset);
2596 unsigned EndIndex = getIndex(NewEndOffset);
2597 assert(EndIndex > BeginIndex && "Empty vector!")(static_cast <bool> (EndIndex > BeginIndex &&
"Empty vector!") ? void (0) : __assert_fail ("EndIndex > BeginIndex && \"Empty vector!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2597, __extension__ __PRETTY_FUNCTION__
))
;
2598 unsigned NumElements = EndIndex - BeginIndex;
2599 assert(NumElements <= cast<FixedVectorType>(VecTy)->getNumElements() &&(static_cast <bool> (NumElements <= cast<FixedVectorType
>(VecTy)->getNumElements() && "Too many elements!"
) ? void (0) : __assert_fail ("NumElements <= cast<FixedVectorType>(VecTy)->getNumElements() && \"Too many elements!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2600, __extension__ __PRETTY_FUNCTION__
))
2600 "Too many elements!")(static_cast <bool> (NumElements <= cast<FixedVectorType
>(VecTy)->getNumElements() && "Too many elements!"
) ? void (0) : __assert_fail ("NumElements <= cast<FixedVectorType>(VecTy)->getNumElements() && \"Too many elements!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2600, __extension__ __PRETTY_FUNCTION__
))
;
2601 Type *SliceTy = (NumElements == 1)
2602 ? ElementTy
2603 : FixedVectorType::get(ElementTy, NumElements);
2604 if (V->getType() != SliceTy)
2605 V = convertValue(DL, IRB, V, SliceTy);
2606
2607 // Mix in the existing elements.
2608 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2609 NewAI.getAlign(), "load");
2610 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2611 }
2612 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign());
2613 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2614 LLVMContext::MD_access_group});
2615 if (AATags)
2616 Store->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
2617 Pass.DeadInsts.push_back(&SI);
2618
2619 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *Store <<
"\n"; } } while (false)
;
2620 return true;
2621 }
2622
2623 bool rewriteIntegerStore(Value *V, StoreInst &SI, AAMDNodes AATags) {
2624 assert(IntTy && "We cannot extract an integer from the alloca")(static_cast <bool> (IntTy && "We cannot extract an integer from the alloca"
) ? void (0) : __assert_fail ("IntTy && \"We cannot extract an integer from the alloca\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2624, __extension__ __PRETTY_FUNCTION__
))
;
2625 assert(!SI.isVolatile())(static_cast <bool> (!SI.isVolatile()) ? void (0) : __assert_fail
("!SI.isVolatile()", "llvm/lib/Transforms/Scalar/SROA.cpp", 2625
, __extension__ __PRETTY_FUNCTION__))
;
2626 if (DL.getTypeSizeInBits(V->getType()).getFixedSize() !=
2627 IntTy->getBitWidth()) {
2628 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2629 NewAI.getAlign(), "oldload");
2630 Old = convertValue(DL, IRB, Old, IntTy);
2631 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset")(static_cast <bool> (BeginOffset >= NewAllocaBeginOffset
&& "Out of bounds offset") ? void (0) : __assert_fail
("BeginOffset >= NewAllocaBeginOffset && \"Out of bounds offset\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2631, __extension__ __PRETTY_FUNCTION__
))
;
2632 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2633 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
2634 }
2635 V = convertValue(DL, IRB, V, NewAllocaTy);
2636 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign());
2637 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2638 LLVMContext::MD_access_group});
2639 if (AATags)
2640 Store->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
2641 Pass.DeadInsts.push_back(&SI);
2642 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *Store <<
"\n"; } } while (false)
;
2643 return true;
2644 }
2645
2646 bool visitStoreInst(StoreInst &SI) {
2647 LLVM_DEBUG(dbgs() << " original: " << SI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << SI <<
"\n"; } } while (false)
;
2648 Value *OldOp = SI.getOperand(1);
2649 assert(OldOp == OldPtr)(static_cast <bool> (OldOp == OldPtr) ? void (0) : __assert_fail
("OldOp == OldPtr", "llvm/lib/Transforms/Scalar/SROA.cpp", 2649
, __extension__ __PRETTY_FUNCTION__))
;
2650
2651 AAMDNodes AATags = SI.getAAMetadata();
2652 Value *V = SI.getValueOperand();
2653
2654 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2655 // alloca that should be re-examined after promoting this alloca.
2656 if (V->getType()->isPointerTy())
2657 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2658 Pass.PostPromotionWorklist.insert(AI);
2659
2660 if (SliceSize < DL.getTypeStoreSize(V->getType()).getFixedSize()) {
2661 assert(!SI.isVolatile())(static_cast <bool> (!SI.isVolatile()) ? void (0) : __assert_fail
("!SI.isVolatile()", "llvm/lib/Transforms/Scalar/SROA.cpp", 2661
, __extension__ __PRETTY_FUNCTION__))
;
2662 assert(V->getType()->isIntegerTy() &&(static_cast <bool> (V->getType()->isIntegerTy() &&
"Only integer type loads and stores are split") ? void (0) :
__assert_fail ("V->getType()->isIntegerTy() && \"Only integer type loads and stores are split\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2663, __extension__ __PRETTY_FUNCTION__
))
2663 "Only integer type loads and stores are split")(static_cast <bool> (V->getType()->isIntegerTy() &&
"Only integer type loads and stores are split") ? void (0) :
__assert_fail ("V->getType()->isIntegerTy() && \"Only integer type loads and stores are split\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2663, __extension__ __PRETTY_FUNCTION__
))
;
2664 assert(DL.typeSizeEqualsStoreSize(V->getType()) &&(static_cast <bool> (DL.typeSizeEqualsStoreSize(V->getType
()) && "Non-byte-multiple bit width") ? void (0) : __assert_fail
("DL.typeSizeEqualsStoreSize(V->getType()) && \"Non-byte-multiple bit width\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2665, __extension__ __PRETTY_FUNCTION__
))
2665 "Non-byte-multiple bit width")(static_cast <bool> (DL.typeSizeEqualsStoreSize(V->getType
()) && "Non-byte-multiple bit width") ? void (0) : __assert_fail
("DL.typeSizeEqualsStoreSize(V->getType()) && \"Non-byte-multiple bit width\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2665, __extension__ __PRETTY_FUNCTION__
))
;
2666 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
2667 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2668 "extract");
2669 }
2670
2671 if (VecTy)
2672 return rewriteVectorizedStoreInst(V, SI, OldOp, AATags);
2673 if (IntTy && V->getType()->isIntegerTy())
2674 return rewriteIntegerStore(V, SI, AATags);
2675
2676 const bool IsStorePastEnd =
2677 DL.getTypeStoreSize(V->getType()).getFixedSize() > SliceSize;
2678 StoreInst *NewSI;
2679 if (NewBeginOffset == NewAllocaBeginOffset &&
2680 NewEndOffset == NewAllocaEndOffset &&
2681 (canConvertValue(DL, V->getType(), NewAllocaTy) ||
2682 (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
2683 V->getType()->isIntegerTy()))) {
2684 // If this is an integer store past the end of slice (and thus the bytes
2685 // past that point are irrelevant or this is unreachable), truncate the
2686 // value prior to storing.
2687 if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
2688 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2689 if (VITy->getBitWidth() > AITy->getBitWidth()) {
2690 if (DL.isBigEndian())
2691 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2692 "endian_shift");
2693 V = IRB.CreateTrunc(V, AITy, "load.trunc");
2694 }
2695
2696 V = convertValue(DL, IRB, V, NewAllocaTy);
2697 NewSI =
2698 IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign(), SI.isVolatile());
2699 } else {
2700 unsigned AS = SI.getPointerAddressSpace();
2701 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS));
2702 NewSI =
2703 IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(), SI.isVolatile());
2704 }
2705 NewSI->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2706 LLVMContext::MD_access_group});
2707 if (AATags)
2708 NewSI->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
2709 if (SI.isVolatile())
2710 NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
2711 if (NewSI->isAtomic())
2712 NewSI->setAlignment(SI.getAlign());
2713 Pass.DeadInsts.push_back(&SI);
2714 deleteIfTriviallyDead(OldOp);
2715
2716 LLVM_DEBUG(dbgs() << " to: " << *NewSI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *NewSI <<
"\n"; } } while (false)
;
2717 return NewSI->getPointerOperand() == &NewAI &&
2718 NewSI->getValueOperand()->getType() == NewAllocaTy &&
2719 !SI.isVolatile();
2720 }
2721
2722 /// Compute an integer value from splatting an i8 across the given
2723 /// number of bytes.
2724 ///
2725 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2726 /// call this routine.
2727 /// FIXME: Heed the advice above.
2728 ///
2729 /// \param V The i8 value to splat.
2730 /// \param Size The number of bytes in the output (assuming i8 is one byte)
2731 Value *getIntegerSplat(Value *V, unsigned Size) {
2732 assert(Size > 0 && "Expected a positive number of bytes.")(static_cast <bool> (Size > 0 && "Expected a positive number of bytes."
) ? void (0) : __assert_fail ("Size > 0 && \"Expected a positive number of bytes.\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2732, __extension__ __PRETTY_FUNCTION__
))
;
2733 IntegerType *VTy = cast<IntegerType>(V->getType());
2734 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte")(static_cast <bool> (VTy->getBitWidth() == 8 &&
"Expected an i8 value for the byte") ? void (0) : __assert_fail
("VTy->getBitWidth() == 8 && \"Expected an i8 value for the byte\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2734, __extension__ __PRETTY_FUNCTION__
))
;
2735 if (Size == 1)
2736 return V;
2737
2738 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2739 V = IRB.CreateMul(
2740 IRB.CreateZExt(V, SplatIntTy, "zext"),
2741 IRB.CreateUDiv(Constant::getAllOnesValue(SplatIntTy),
2742 IRB.CreateZExt(Constant::getAllOnesValue(V->getType()),
2743 SplatIntTy)),
2744 "isplat");
2745 return V;
2746 }
2747
2748 /// Compute a vector splat for a given element value.
2749 Value *getVectorSplat(Value *V, unsigned NumElements) {
2750 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
2751 LLVM_DEBUG(dbgs() << " splat: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " splat: " << *V <<
"\n"; } } while (false)
;
2752 return V;
2753 }
2754
2755 bool visitMemSetInst(MemSetInst &II) {
2756 LLVM_DEBUG(dbgs() << " original: " << II << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << II <<
"\n"; } } while (false)
;
2757 assert(II.getRawDest() == OldPtr)(static_cast <bool> (II.getRawDest() == OldPtr) ? void (
0) : __assert_fail ("II.getRawDest() == OldPtr", "llvm/lib/Transforms/Scalar/SROA.cpp"
, 2757, __extension__ __PRETTY_FUNCTION__))
;
2758
2759 AAMDNodes AATags = II.getAAMetadata();
2760
2761 // If the memset has a variable size, it cannot be split, just adjust the
2762 // pointer to the new alloca.
2763 if (!isa<ConstantInt>(II.getLength())) {
2764 assert(!IsSplit)(static_cast <bool> (!IsSplit) ? void (0) : __assert_fail
("!IsSplit", "llvm/lib/Transforms/Scalar/SROA.cpp", 2764, __extension__
__PRETTY_FUNCTION__))
;
2765 assert(NewBeginOffset == BeginOffset)(static_cast <bool> (NewBeginOffset == BeginOffset) ? void
(0) : __assert_fail ("NewBeginOffset == BeginOffset", "llvm/lib/Transforms/Scalar/SROA.cpp"
, 2765, __extension__ __PRETTY_FUNCTION__))
;
2766 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
2767 II.setDestAlignment(getSliceAlign());
2768
2769 deleteIfTriviallyDead(OldPtr);
2770 return false;
2771 }
2772
2773 // Record this instruction for deletion.
2774 Pass.DeadInsts.push_back(&II);
2775
2776 Type *AllocaTy = NewAI.getAllocatedType();
2777 Type *ScalarTy = AllocaTy->getScalarType();
2778
2779 const bool CanContinue = [&]() {
2780 if (VecTy || IntTy)
2781 return true;
2782 if (BeginOffset > NewAllocaBeginOffset ||
2783 EndOffset < NewAllocaEndOffset)
2784 return false;
2785 // Length must be in range for FixedVectorType.
2786 auto *C = cast<ConstantInt>(II.getLength());
2787 const uint64_t Len = C->getLimitedValue();
2788 if (Len > std::numeric_limits<unsigned>::max())
2789 return false;
2790 auto *Int8Ty = IntegerType::getInt8Ty(NewAI.getContext());
2791 auto *SrcTy = FixedVectorType::get(Int8Ty, Len);
2792 return canConvertValue(DL, SrcTy, AllocaTy) &&
2793 DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy).getFixedSize());
2794 }();
2795
2796 // If this doesn't map cleanly onto the alloca type, and that type isn't
2797 // a single value type, just emit a memset.
2798 if (!CanContinue) {
2799 Type *SizeTy = II.getLength()->getType();
2800 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2801 CallInst *New = IRB.CreateMemSet(
2802 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2803 MaybeAlign(getSliceAlign()), II.isVolatile());
2804 if (AATags)
2805 New->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
2806 LLVM_DEBUG(dbgs() << " to: " << *New << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *New <<
"\n"; } } while (false)
;
2807 return false;
2808 }
2809
2810 // If we can represent this as a simple value, we have to build the actual
2811 // value to store, which requires expanding the byte present in memset to
2812 // a sensible representation for the alloca type. This is essentially
2813 // splatting the byte to a sufficiently wide integer, splatting it across
2814 // any desired vector width, and bitcasting to the final type.
2815 Value *V;
2816
2817 if (VecTy) {
2818 // If this is a memset of a vectorized alloca, insert it.
2819 assert(ElementTy == ScalarTy)(static_cast <bool> (ElementTy == ScalarTy) ? void (0) :
__assert_fail ("ElementTy == ScalarTy", "llvm/lib/Transforms/Scalar/SROA.cpp"
, 2819, __extension__ __PRETTY_FUNCTION__))
;
2820
2821 unsigned BeginIndex = getIndex(NewBeginOffset);
2822 unsigned EndIndex = getIndex(NewEndOffset);
2823 assert(EndIndex > BeginIndex && "Empty vector!")(static_cast <bool> (EndIndex > BeginIndex &&
"Empty vector!") ? void (0) : __assert_fail ("EndIndex > BeginIndex && \"Empty vector!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2823, __extension__ __PRETTY_FUNCTION__
))
;
2824 unsigned NumElements = EndIndex - BeginIndex;
2825 assert(NumElements <= cast<FixedVectorType>(VecTy)->getNumElements() &&(static_cast <bool> (NumElements <= cast<FixedVectorType
>(VecTy)->getNumElements() && "Too many elements!"
) ? void (0) : __assert_fail ("NumElements <= cast<FixedVectorType>(VecTy)->getNumElements() && \"Too many elements!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2826, __extension__ __PRETTY_FUNCTION__
))
2826 "Too many elements!")(static_cast <bool> (NumElements <= cast<FixedVectorType
>(VecTy)->getNumElements() && "Too many elements!"
) ? void (0) : __assert_fail ("NumElements <= cast<FixedVectorType>(VecTy)->getNumElements() && \"Too many elements!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2826, __extension__ __PRETTY_FUNCTION__
))
;
2827
2828 Value *Splat = getIntegerSplat(
2829 II.getValue(), DL.getTypeSizeInBits(ElementTy).getFixedSize() / 8);
2830 Splat = convertValue(DL, IRB, Splat, ElementTy);
2831 if (NumElements > 1)
2832 Splat = getVectorSplat(Splat, NumElements);
2833
2834 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2835 NewAI.getAlign(), "oldload");
2836 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
2837 } else if (IntTy) {
2838 // If this is a memset on an alloca where we can widen stores, insert the
2839 // set integer.
2840 assert(!II.isVolatile())(static_cast <bool> (!II.isVolatile()) ? void (0) : __assert_fail
("!II.isVolatile()", "llvm/lib/Transforms/Scalar/SROA.cpp", 2840
, __extension__ __PRETTY_FUNCTION__))
;
2841
2842 uint64_t Size = NewEndOffset - NewBeginOffset;
2843 V = getIntegerSplat(II.getValue(), Size);
2844
2845 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2846 EndOffset != NewAllocaBeginOffset)) {
2847 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2848 NewAI.getAlign(), "oldload");
2849 Old = convertValue(DL, IRB, Old, IntTy);
2850 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2851 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
2852 } else {
2853 assert(V->getType() == IntTy &&(static_cast <bool> (V->getType() == IntTy &&
"Wrong type for an alloca wide integer!") ? void (0) : __assert_fail
("V->getType() == IntTy && \"Wrong type for an alloca wide integer!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2854, __extension__ __PRETTY_FUNCTION__
))
2854 "Wrong type for an alloca wide integer!")(static_cast <bool> (V->getType() == IntTy &&
"Wrong type for an alloca wide integer!") ? void (0) : __assert_fail
("V->getType() == IntTy && \"Wrong type for an alloca wide integer!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2854, __extension__ __PRETTY_FUNCTION__
))
;
2855 }
2856 V = convertValue(DL, IRB, V, AllocaTy);
2857 } else {
2858 // Established these invariants above.
2859 assert(NewBeginOffset == NewAllocaBeginOffset)(static_cast <bool> (NewBeginOffset == NewAllocaBeginOffset
) ? void (0) : __assert_fail ("NewBeginOffset == NewAllocaBeginOffset"
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2859, __extension__ __PRETTY_FUNCTION__
))
;
2860 assert(NewEndOffset == NewAllocaEndOffset)(static_cast <bool> (NewEndOffset == NewAllocaEndOffset
) ? void (0) : __assert_fail ("NewEndOffset == NewAllocaEndOffset"
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2860, __extension__ __PRETTY_FUNCTION__
))
;
2861
2862 V = getIntegerSplat(II.getValue(),
2863 DL.getTypeSizeInBits(ScalarTy).getFixedSize() / 8);
2864 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2865 V = getVectorSplat(
2866 V, cast<FixedVectorType>(AllocaVecTy)->getNumElements());
2867
2868 V = convertValue(DL, IRB, V, AllocaTy);
2869 }
2870
2871 StoreInst *New =
2872 IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign(), II.isVolatile());
2873 New->copyMetadata(II, {LLVMContext::MD_mem_parallel_loop_access,
2874 LLVMContext::MD_access_group});
2875 if (AATags)
2876 New->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
2877 LLVM_DEBUG(dbgs() << " to: " << *New << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *New <<
"\n"; } } while (false)
;
2878 return !II.isVolatile();
2879 }
2880
2881 bool visitMemTransferInst(MemTransferInst &II) {
2882 // Rewriting of memory transfer instructions can be a bit tricky. We break
2883 // them into two categories: split intrinsics and unsplit intrinsics.
2884
2885 LLVM_DEBUG(dbgs() << " original: " << II << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << II <<
"\n"; } } while (false)
;
1
Assuming 'DebugFlag' is false
2
Loop condition is false. Exiting loop
2886
2887 AAMDNodes AATags = II.getAAMetadata();
2888
2889 bool IsDest = &II.getRawDestUse() == OldUse;
2890 assert((IsDest && II.getRawDest() == OldPtr) ||(static_cast <bool> ((IsDest && II.getRawDest()
== OldPtr) || (!IsDest && II.getRawSource() == OldPtr
)) ? void (0) : __assert_fail ("(IsDest && II.getRawDest() == OldPtr) || (!IsDest && II.getRawSource() == OldPtr)"
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2891, __extension__ __PRETTY_FUNCTION__
))
3
Assuming 'IsDest' is false
4
Assuming pointer value is null
5
'?' condition is true
2891 (!IsDest && II.getRawSource() == OldPtr))(static_cast <bool> ((IsDest && II.getRawDest()
== OldPtr) || (!IsDest && II.getRawSource() == OldPtr
)) ? void (0) : __assert_fail ("(IsDest && II.getRawDest() == OldPtr) || (!IsDest && II.getRawSource() == OldPtr)"
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2891, __extension__ __PRETTY_FUNCTION__
))
;
2892
2893 Align SliceAlign = getSliceAlign();
2894
2895 // For unsplit intrinsics, we simply modify the source and destination
2896 // pointers in place. This isn't just an optimization, it is a matter of
2897 // correctness. With unsplit intrinsics we may be dealing with transfers
2898 // within a single alloca before SROA ran, or with transfers that have
2899 // a variable length. We may also be dealing with memmove instead of
2900 // memcpy, and so simply updating the pointers is the necessary for us to
2901 // update both source and dest of a single call.
2902 if (!IsSplittable) {
6
Assuming field 'IsSplittable' is false
7
Taking true branch
2903 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
8
Called C++ object pointer is null
2904 if (IsDest) {
2905 II.setDest(AdjustedPtr);
2906 II.setDestAlignment(SliceAlign);
2907 }
2908 else {
2909 II.setSource(AdjustedPtr);
2910 II.setSourceAlignment(SliceAlign);
2911 }
2912
2913 LLVM_DEBUG(dbgs() << " to: " << II << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << II <<
"\n"; } } while (false)
;
2914 deleteIfTriviallyDead(OldPtr);
2915 return false;
2916 }
2917 // For split transfer intrinsics we have an incredibly useful assurance:
2918 // the source and destination do not reside within the same alloca, and at
2919 // least one of them does not escape. This means that we can replace
2920 // memmove with memcpy, and we don't need to worry about all manner of
2921 // downsides to splitting and transforming the operations.
2922
2923 // If this doesn't map cleanly onto the alloca type, and that type isn't
2924 // a single value type, just emit a memcpy.
2925 bool EmitMemCpy =
2926 !VecTy && !IntTy &&
2927 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2928 SliceSize !=
2929 DL.getTypeStoreSize(NewAI.getAllocatedType()).getFixedSize() ||
2930 !NewAI.getAllocatedType()->isSingleValueType());
2931
2932 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2933 // size hasn't been shrunk based on analysis of the viable range, this is
2934 // a no-op.
2935 if (EmitMemCpy && &OldAI == &NewAI) {
2936 // Ensure the start lines up.
2937 assert(NewBeginOffset == BeginOffset)(static_cast <bool> (NewBeginOffset == BeginOffset) ? void
(0) : __assert_fail ("NewBeginOffset == BeginOffset", "llvm/lib/Transforms/Scalar/SROA.cpp"
, 2937, __extension__ __PRETTY_FUNCTION__))
;
2938
2939 // Rewrite the size as needed.
2940 if (NewEndOffset != EndOffset)
2941 II.setLength(ConstantInt::get(II.getLength()->getType(),
2942 NewEndOffset - NewBeginOffset));
2943 return false;
2944 }
2945 // Record this instruction for deletion.
2946 Pass.DeadInsts.push_back(&II);
2947
2948 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2949 // alloca that should be re-examined after rewriting this instruction.
2950 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2951 if (AllocaInst *AI =
2952 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2953 assert(AI != &OldAI && AI != &NewAI &&(static_cast <bool> (AI != &OldAI && AI != &
NewAI && "Splittable transfers cannot reach the same alloca on both ends."
) ? void (0) : __assert_fail ("AI != &OldAI && AI != &NewAI && \"Splittable transfers cannot reach the same alloca on both ends.\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2954, __extension__ __PRETTY_FUNCTION__
))
2954 "Splittable transfers cannot reach the same alloca on both ends.")(static_cast <bool> (AI != &OldAI && AI != &
NewAI && "Splittable transfers cannot reach the same alloca on both ends."
) ? void (0) : __assert_fail ("AI != &OldAI && AI != &NewAI && \"Splittable transfers cannot reach the same alloca on both ends.\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 2954, __extension__ __PRETTY_FUNCTION__
))
;
2955 Pass.Worklist.insert(AI);
2956 }
2957
2958 Type *OtherPtrTy = OtherPtr->getType();
2959 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2960
2961 // Compute the relative offset for the other pointer within the transfer.
2962 unsigned OffsetWidth = DL.getIndexSizeInBits(OtherAS);
2963 APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset);
2964 Align OtherAlign =
2965 (IsDest ? II.getSourceAlign() : II.getDestAlign()).valueOrOne();
2966 OtherAlign =
2967 commonAlignment(OtherAlign, OtherOffset.zextOrTrunc(64).getZExtValue());
2968
2969 if (EmitMemCpy) {
2970 // Compute the other pointer, folding as much as possible to produce
2971 // a single, simple GEP in most cases.
2972 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2973 OtherPtr->getName() + ".");
2974
2975 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2976 Type *SizeTy = II.getLength()->getType();
2977 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2978
2979 Value *DestPtr, *SrcPtr;
2980 MaybeAlign DestAlign, SrcAlign;
2981 // Note: IsDest is true iff we're copying into the new alloca slice
2982 if (IsDest) {
2983 DestPtr = OurPtr;
2984 DestAlign = SliceAlign;
2985 SrcPtr = OtherPtr;
2986 SrcAlign = OtherAlign;
2987 } else {
2988 DestPtr = OtherPtr;
2989 DestAlign = OtherAlign;
2990 SrcPtr = OurPtr;
2991 SrcAlign = SliceAlign;
2992 }
2993 CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign,
2994 Size, II.isVolatile());
2995 if (AATags)
2996 New->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
2997 LLVM_DEBUG(dbgs() << " to: " << *New << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *New <<
"\n"; } } while (false)
;
2998 return false;
2999 }
3000
3001 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
3002 NewEndOffset == NewAllocaEndOffset;
3003 uint64_t Size = NewEndOffset - NewBeginOffset;
3004 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
3005 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
3006 unsigned NumElements = EndIndex - BeginIndex;
3007 IntegerType *SubIntTy =
3008 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
3009
3010 // Reset the other pointer type to match the register type we're going to
3011 // use, but using the address space of the original other pointer.
3012 Type *OtherTy;
3013 if (VecTy && !IsWholeAlloca) {
3014 if (NumElements == 1)
3015 OtherTy = VecTy->getElementType();
3016 else
3017 OtherTy = FixedVectorType::get(VecTy->getElementType(), NumElements);
3018 } else if (IntTy && !IsWholeAlloca) {
3019 OtherTy = SubIntTy;
3020 } else {
3021 OtherTy = NewAllocaTy;
3022 }
3023 OtherPtrTy = OtherTy->getPointerTo(OtherAS);
3024
3025 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
3026 OtherPtr->getName() + ".");
3027 MaybeAlign SrcAlign = OtherAlign;
3028 Value *DstPtr = &NewAI;
3029 MaybeAlign DstAlign = SliceAlign;
3030 if (!IsDest) {
3031 std::swap(SrcPtr, DstPtr);
3032 std::swap(SrcAlign, DstAlign);
3033 }
3034
3035 Value *Src;
3036 if (VecTy && !IsWholeAlloca && !IsDest) {
3037 Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3038 NewAI.getAlign(), "load");
3039 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
3040 } else if (IntTy && !IsWholeAlloca && !IsDest) {
3041 Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3042 NewAI.getAlign(), "load");
3043 Src = convertValue(DL, IRB, Src, IntTy);
3044 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3045 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
3046 } else {
3047 LoadInst *Load = IRB.CreateAlignedLoad(OtherTy, SrcPtr, SrcAlign,
3048 II.isVolatile(), "copyload");
3049 Load->copyMetadata(II, {LLVMContext::MD_mem_parallel_loop_access,
3050 LLVMContext::MD_access_group});
3051 if (AATags)
3052 Load->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
3053 Src = Load;
3054 }
3055
3056 if (VecTy && !IsWholeAlloca && IsDest) {
3057 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3058 NewAI.getAlign(), "oldload");
3059 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
3060 } else if (IntTy && !IsWholeAlloca && IsDest) {
3061 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3062 NewAI.getAlign(), "oldload");
3063 Old = convertValue(DL, IRB, Old, IntTy);
3064 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3065 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
3066 Src = convertValue(DL, IRB, Src, NewAllocaTy);
3067 }
3068
3069 StoreInst *Store = cast<StoreInst>(
3070 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
3071 Store->copyMetadata(II, {LLVMContext::MD_mem_parallel_loop_access,
3072 LLVMContext::MD_access_group});
3073 if (AATags)
3074 Store->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
3075 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *Store <<
"\n"; } } while (false)
;
3076 return !II.isVolatile();
3077 }
3078
3079 bool visitIntrinsicInst(IntrinsicInst &II) {
3080 assert((II.isLifetimeStartOrEnd() || II.isDroppable()) &&(static_cast <bool> ((II.isLifetimeStartOrEnd() || II.isDroppable
()) && "Unexpected intrinsic!") ? void (0) : __assert_fail
("(II.isLifetimeStartOrEnd() || II.isDroppable()) && \"Unexpected intrinsic!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3081, __extension__ __PRETTY_FUNCTION__
))
3081 "Unexpected intrinsic!")(static_cast <bool> ((II.isLifetimeStartOrEnd() || II.isDroppable
()) && "Unexpected intrinsic!") ? void (0) : __assert_fail
("(II.isLifetimeStartOrEnd() || II.isDroppable()) && \"Unexpected intrinsic!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3081, __extension__ __PRETTY_FUNCTION__
))
;
3082 LLVM_DEBUG(dbgs() << " original: " << II << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << II <<
"\n"; } } while (false)
;
3083
3084 // Record this instruction for deletion.
3085 Pass.DeadInsts.push_back(&II);
3086
3087 if (II.isDroppable()) {
3088 assert(II.getIntrinsicID() == Intrinsic::assume && "Expected assume")(static_cast <bool> (II.getIntrinsicID() == Intrinsic::
assume && "Expected assume") ? void (0) : __assert_fail
("II.getIntrinsicID() == Intrinsic::assume && \"Expected assume\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3088, __extension__ __PRETTY_FUNCTION__
))
;
3089 // TODO For now we forget assumed information, this can be improved.
3090 OldPtr->dropDroppableUsesIn(II);
3091 return true;
3092 }
3093
3094 assert(II.getArgOperand(1) == OldPtr)(static_cast <bool> (II.getArgOperand(1) == OldPtr) ? void
(0) : __assert_fail ("II.getArgOperand(1) == OldPtr", "llvm/lib/Transforms/Scalar/SROA.cpp"
, 3094, __extension__ __PRETTY_FUNCTION__))
;
3095 // Lifetime intrinsics are only promotable if they cover the whole alloca.
3096 // Therefore, we drop lifetime intrinsics which don't cover the whole
3097 // alloca.
3098 // (In theory, intrinsics which partially cover an alloca could be
3099 // promoted, but PromoteMemToReg doesn't handle that case.)
3100 // FIXME: Check whether the alloca is promotable before dropping the
3101 // lifetime intrinsics?
3102 if (NewBeginOffset != NewAllocaBeginOffset ||
3103 NewEndOffset != NewAllocaEndOffset)
3104 return true;
3105
3106 ConstantInt *Size =
3107 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
3108 NewEndOffset - NewBeginOffset);
3109 // Lifetime intrinsics always expect an i8* so directly get such a pointer
3110 // for the new alloca slice.
3111 Type *PointerTy = IRB.getInt8PtrTy(OldPtr->getType()->getPointerAddressSpace());
3112 Value *Ptr = getNewAllocaSlicePtr(IRB, PointerTy);
3113 Value *New;
3114 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3115 New = IRB.CreateLifetimeStart(Ptr, Size);
3116 else
3117 New = IRB.CreateLifetimeEnd(Ptr, Size);
3118
3119 (void)New;
3120 LLVM_DEBUG(dbgs() << " to: " << *New << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *New <<
"\n"; } } while (false)
;
3121
3122 return true;
3123 }
3124
3125 void fixLoadStoreAlign(Instruction &Root) {
3126 // This algorithm implements the same visitor loop as
3127 // hasUnsafePHIOrSelectUse, and fixes the alignment of each load
3128 // or store found.
3129 SmallPtrSet<Instruction *, 4> Visited;
3130 SmallVector<Instruction *, 4> Uses;
3131 Visited.insert(&Root);
3132 Uses.push_back(&Root);
3133 do {
3134 Instruction *I = Uses.pop_back_val();
3135
3136 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3137 LI->setAlignment(std::min(LI->getAlign(), getSliceAlign()));
3138 continue;
3139 }
3140 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3141 SI->setAlignment(std::min(SI->getAlign(), getSliceAlign()));
3142 continue;
3143 }
3144
3145 assert(isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I) ||(static_cast <bool> (isa<BitCastInst>(I) || isa<
AddrSpaceCastInst>(I) || isa<PHINode>(I) || isa<SelectInst
>(I) || isa<GetElementPtrInst>(I)) ? void (0) : __assert_fail
("isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I) || isa<PHINode>(I) || isa<SelectInst>(I) || isa<GetElementPtrInst>(I)"
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3147, __extension__ __PRETTY_FUNCTION__
))
3146 isa<PHINode>(I) || isa<SelectInst>(I) ||(static_cast <bool> (isa<BitCastInst>(I) || isa<
AddrSpaceCastInst>(I) || isa<PHINode>(I) || isa<SelectInst
>(I) || isa<GetElementPtrInst>(I)) ? void (0) : __assert_fail
("isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I) || isa<PHINode>(I) || isa<SelectInst>(I) || isa<GetElementPtrInst>(I)"
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3147, __extension__ __PRETTY_FUNCTION__
))
3147 isa<GetElementPtrInst>(I))(static_cast <bool> (isa<BitCastInst>(I) || isa<
AddrSpaceCastInst>(I) || isa<PHINode>(I) || isa<SelectInst
>(I) || isa<GetElementPtrInst>(I)) ? void (0) : __assert_fail
("isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I) || isa<PHINode>(I) || isa<SelectInst>(I) || isa<GetElementPtrInst>(I)"
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3147, __extension__ __PRETTY_FUNCTION__
))
;
3148 for (User *U : I->users())
3149 if (Visited.insert(cast<Instruction>(U)).second)
3150 Uses.push_back(cast<Instruction>(U));
3151 } while (!Uses.empty());
3152 }
3153
3154 bool visitPHINode(PHINode &PN) {
3155 LLVM_DEBUG(dbgs() << " original: " << PN << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << PN <<
"\n"; } } while (false)
;
3156 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable")(static_cast <bool> (BeginOffset >= NewAllocaBeginOffset
&& "PHIs are unsplittable") ? void (0) : __assert_fail
("BeginOffset >= NewAllocaBeginOffset && \"PHIs are unsplittable\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3156, __extension__ __PRETTY_FUNCTION__
))
;
3157 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable")(static_cast <bool> (EndOffset <= NewAllocaEndOffset
&& "PHIs are unsplittable") ? void (0) : __assert_fail
("EndOffset <= NewAllocaEndOffset && \"PHIs are unsplittable\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3157, __extension__ __PRETTY_FUNCTION__
))
;
3158
3159 // We would like to compute a new pointer in only one place, but have it be
3160 // as local as possible to the PHI. To do that, we re-use the location of
3161 // the old pointer, which necessarily must be in the right position to
3162 // dominate the PHI.
3163 IRBuilderBase::InsertPointGuard Guard(IRB);
3164 if (isa<PHINode>(OldPtr))
3165 IRB.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
3166 else
3167 IRB.SetInsertPoint(OldPtr);
3168 IRB.SetCurrentDebugLocation(OldPtr->getDebugLoc());
3169
3170 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3171 // Replace the operands which were using the old pointer.
3172 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
3173
3174 LLVM_DEBUG(dbgs() << " to: " << PN << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << PN <<
"\n"; } } while (false)
;
3175 deleteIfTriviallyDead(OldPtr);
3176
3177 // Fix the alignment of any loads or stores using this PHI node.
3178 fixLoadStoreAlign(PN);
3179
3180 // PHIs can't be promoted on their own, but often can be speculated. We
3181 // check the speculation outside of the rewriter so that we see the
3182 // fully-rewritten alloca.
3183 PHIUsers.insert(&PN);
3184 return true;
3185 }
3186
3187 bool visitSelectInst(SelectInst &SI) {
3188 LLVM_DEBUG(dbgs() << " original: " << SI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << SI <<
"\n"; } } while (false)
;
3189 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&(static_cast <bool> ((SI.getTrueValue() == OldPtr || SI
.getFalseValue() == OldPtr) && "Pointer isn't an operand!"
) ? void (0) : __assert_fail ("(SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) && \"Pointer isn't an operand!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3190, __extension__ __PRETTY_FUNCTION__
))
3190 "Pointer isn't an operand!")(static_cast <bool> ((SI.getTrueValue() == OldPtr || SI
.getFalseValue() == OldPtr) && "Pointer isn't an operand!"
) ? void (0) : __assert_fail ("(SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) && \"Pointer isn't an operand!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3190, __extension__ __PRETTY_FUNCTION__
))
;
3191 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable")(static_cast <bool> (BeginOffset >= NewAllocaBeginOffset
&& "Selects are unsplittable") ? void (0) : __assert_fail
("BeginOffset >= NewAllocaBeginOffset && \"Selects are unsplittable\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3191, __extension__ __PRETTY_FUNCTION__
))
;
3192 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable")(static_cast <bool> (EndOffset <= NewAllocaEndOffset
&& "Selects are unsplittable") ? void (0) : __assert_fail
("EndOffset <= NewAllocaEndOffset && \"Selects are unsplittable\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3192, __extension__ __PRETTY_FUNCTION__
))
;
3193
3194 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3195 // Replace the operands which were using the old pointer.
3196 if (SI.getOperand(1) == OldPtr)
3197 SI.setOperand(1, NewPtr);
3198 if (SI.getOperand(2) == OldPtr)
3199 SI.setOperand(2, NewPtr);
3200
3201 LLVM_DEBUG(dbgs() << " to: " << SI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << SI <<
"\n"; } } while (false)
;
3202 deleteIfTriviallyDead(OldPtr);
3203
3204 // Fix the alignment of any loads or stores using this select.
3205 fixLoadStoreAlign(SI);
3206
3207 // Selects can't be promoted on their own, but often can be speculated. We
3208 // check the speculation outside of the rewriter so that we see the
3209 // fully-rewritten alloca.
3210 SelectUsers.insert(&SI);
3211 return true;
3212 }
3213};
3214
3215namespace {
3216
3217/// Visitor to rewrite aggregate loads and stores as scalar.
3218///
3219/// This pass aggressively rewrites all aggregate loads and stores on
3220/// a particular pointer (or any pointer derived from it which we can identify)
3221/// with scalar loads and stores.
3222class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3223 // Befriend the base class so it can delegate to private visit methods.
3224 friend class InstVisitor<AggLoadStoreRewriter, bool>;
3225
3226 /// Queue of pointer uses to analyze and potentially rewrite.
3227 SmallVector<Use *, 8> Queue;
3228
3229 /// Set to prevent us from cycling with phi nodes and loops.
3230 SmallPtrSet<User *, 8> Visited;
3231
3232 /// The current pointer use being rewritten. This is used to dig up the used
3233 /// value (as opposed to the user).
3234 Use *U = nullptr;
3235
3236 /// Used to calculate offsets, and hence alignment, of subobjects.
3237 const DataLayout &DL;
3238
3239 IRBuilderTy &IRB;
3240
3241public:
3242 AggLoadStoreRewriter(const DataLayout &DL, IRBuilderTy &IRB)
3243 : DL(DL), IRB(IRB) {}
3244
3245 /// Rewrite loads and stores through a pointer and all pointers derived from
3246 /// it.
3247 bool rewrite(Instruction &I) {
3248 LLVM_DEBUG(dbgs() << " Rewriting FCA loads and stores...\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Rewriting FCA loads and stores...\n"
; } } while (false)
;
3249 enqueueUsers(I);
3250 bool Changed = false;
3251 while (!Queue.empty()) {
3252 U = Queue.pop_back_val();
3253 Changed |= visit(cast<Instruction>(U->getUser()));
3254 }
3255 return Changed;
3256 }
3257
3258private:
3259 /// Enqueue all the users of the given instruction for further processing.
3260 /// This uses a set to de-duplicate users.
3261 void enqueueUsers(Instruction &I) {
3262 for (Use &U : I.uses())
3263 if (Visited.insert(U.getUser()).second)
3264 Queue.push_back(&U);
3265 }
3266
3267 // Conservative default is to not rewrite anything.
3268 bool visitInstruction(Instruction &I) { return false; }
3269
3270 /// Generic recursive split emission class.
3271 template <typename Derived> class OpSplitter {
3272 protected:
3273 /// The builder used to form new instructions.
3274 IRBuilderTy &IRB;
3275
3276 /// The indices which to be used with insert- or extractvalue to select the
3277 /// appropriate value within the aggregate.
3278 SmallVector<unsigned, 4> Indices;
3279
3280 /// The indices to a GEP instruction which will move Ptr to the correct slot
3281 /// within the aggregate.
3282 SmallVector<Value *, 4> GEPIndices;
3283
3284 /// The base pointer of the original op, used as a base for GEPing the
3285 /// split operations.
3286 Value *Ptr;
3287
3288 /// The base pointee type being GEPed into.
3289 Type *BaseTy;
3290
3291 /// Known alignment of the base pointer.
3292 Align BaseAlign;
3293
3294 /// To calculate offset of each component so we can correctly deduce
3295 /// alignments.
3296 const DataLayout &DL;
3297
3298 /// Initialize the splitter with an insertion point, Ptr and start with a
3299 /// single zero GEP index.
3300 OpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3301 Align BaseAlign, const DataLayout &DL, IRBuilderTy &IRB)
3302 : IRB(IRB), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr), BaseTy(BaseTy),
3303 BaseAlign(BaseAlign), DL(DL) {
3304 IRB.SetInsertPoint(InsertionPoint);
3305 }
3306
3307 public:
3308 /// Generic recursive split emission routine.
3309 ///
3310 /// This method recursively splits an aggregate op (load or store) into
3311 /// scalar or vector ops. It splits recursively until it hits a single value
3312 /// and emits that single value operation via the template argument.
3313 ///
3314 /// The logic of this routine relies on GEPs and insertvalue and
3315 /// extractvalue all operating with the same fundamental index list, merely
3316 /// formatted differently (GEPs need actual values).
3317 ///
3318 /// \param Ty The type being split recursively into smaller ops.
3319 /// \param Agg The aggregate value being built up or stored, depending on
3320 /// whether this is splitting a load or a store respectively.
3321 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3322 if (Ty->isSingleValueType()) {
3323 unsigned Offset = DL.getIndexedOffsetInType(BaseTy, GEPIndices);
3324 return static_cast<Derived *>(this)->emitFunc(
3325 Ty, Agg, commonAlignment(BaseAlign, Offset), Name);
3326 }
3327
3328 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3329 unsigned OldSize = Indices.size();
3330 (void)OldSize;
3331 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3332 ++Idx) {
3333 assert(Indices.size() == OldSize && "Did not return to the old size")(static_cast <bool> (Indices.size() == OldSize &&
"Did not return to the old size") ? void (0) : __assert_fail
("Indices.size() == OldSize && \"Did not return to the old size\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3333, __extension__ __PRETTY_FUNCTION__
))
;
3334 Indices.push_back(Idx);
3335 GEPIndices.push_back(IRB.getInt32(Idx));
3336 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3337 GEPIndices.pop_back();
3338 Indices.pop_back();
3339 }
3340 return;
3341 }
3342
3343 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3344 unsigned OldSize = Indices.size();
3345 (void)OldSize;
3346 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3347 ++Idx) {
3348 assert(Indices.size() == OldSize && "Did not return to the old size")(static_cast <bool> (Indices.size() == OldSize &&
"Did not return to the old size") ? void (0) : __assert_fail
("Indices.size() == OldSize && \"Did not return to the old size\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3348, __extension__ __PRETTY_FUNCTION__
))
;
3349 Indices.push_back(Idx);
3350 GEPIndices.push_back(IRB.getInt32(Idx));
3351 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3352 GEPIndices.pop_back();
3353 Indices.pop_back();
3354 }
3355 return;
3356 }
3357
3358 llvm_unreachable("Only arrays and structs are aggregate loadable types")::llvm::llvm_unreachable_internal("Only arrays and structs are aggregate loadable types"
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3358)
;
3359 }
3360 };
3361
3362 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
3363 AAMDNodes AATags;
3364
3365 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3366 AAMDNodes AATags, Align BaseAlign, const DataLayout &DL,
3367 IRBuilderTy &IRB)
3368 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign, DL,
3369 IRB),
3370 AATags(AATags) {}
3371
3372 /// Emit a leaf load of a single value. This is called at the leaves of the
3373 /// recursive emission to actually load values.
3374 void emitFunc(Type *Ty, Value *&Agg, Align Alignment, const Twine &Name) {
3375 assert(Ty->isSingleValueType())(static_cast <bool> (Ty->isSingleValueType()) ? void
(0) : __assert_fail ("Ty->isSingleValueType()", "llvm/lib/Transforms/Scalar/SROA.cpp"
, 3375, __extension__ __PRETTY_FUNCTION__))
;
3376 // Load the single value and insert it using the indices.
3377 Value *GEP =
3378 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
3379 LoadInst *Load =
3380 IRB.CreateAlignedLoad(Ty, GEP, Alignment, Name + ".load");
3381
3382 APInt Offset(
3383 DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace()), 0);
3384 if (AATags &&
3385 GEPOperator::accumulateConstantOffset(BaseTy, GEPIndices, DL, Offset))
3386 Load->setAAMetadata(AATags.shift(Offset.getZExtValue()));
3387
3388 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3389 LLVM_DEBUG(dbgs() << " to: " << *Load << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *Load <<
"\n"; } } while (false)
;
3390 }
3391 };
3392
3393 bool visitLoadInst(LoadInst &LI) {
3394 assert(LI.getPointerOperand() == *U)(static_cast <bool> (LI.getPointerOperand() == *U) ? void
(0) : __assert_fail ("LI.getPointerOperand() == *U", "llvm/lib/Transforms/Scalar/SROA.cpp"
, 3394, __extension__ __PRETTY_FUNCTION__))
;
3395 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3396 return false;
3397
3398 // We have an aggregate being loaded, split it apart.
3399 LLVM_DEBUG(dbgs() << " original: " << LI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << LI <<
"\n"; } } while (false)
;
3400 LoadOpSplitter Splitter(&LI, *U, LI.getType(), LI.getAAMetadata(),
3401 getAdjustedAlignment(&LI, 0), DL, IRB);
3402 Value *V = PoisonValue::get(LI.getType());
3403 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
3404 Visited.erase(&LI);
3405 LI.replaceAllUsesWith(V);
3406 LI.eraseFromParent();
3407 return true;
3408 }
3409
3410 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
3411 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3412 AAMDNodes AATags, Align BaseAlign, const DataLayout &DL,
3413 IRBuilderTy &IRB)
3414 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
3415 DL, IRB),
3416 AATags(AATags) {}
3417 AAMDNodes AATags;
3418 /// Emit a leaf store of a single value. This is called at the leaves of the
3419 /// recursive emission to actually produce stores.
3420 void emitFunc(Type *Ty, Value *&Agg, Align Alignment, const Twine &Name) {
3421 assert(Ty->isSingleValueType())(static_cast <bool> (Ty->isSingleValueType()) ? void
(0) : __assert_fail ("Ty->isSingleValueType()", "llvm/lib/Transforms/Scalar/SROA.cpp"
, 3421, __extension__ __PRETTY_FUNCTION__))
;
3422 // Extract the single value and store it using the indices.
3423 //
3424 // The gep and extractvalue values are factored out of the CreateStore
3425 // call to make the output independent of the argument evaluation order.
3426 Value *ExtractValue =
3427 IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
3428 Value *InBoundsGEP =
3429 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
3430 StoreInst *Store =
3431 IRB.CreateAlignedStore(ExtractValue, InBoundsGEP, Alignment);
3432
3433 APInt Offset(
3434 DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace()), 0);
3435 if (AATags &&
3436 GEPOperator::accumulateConstantOffset(BaseTy, GEPIndices, DL, Offset))
3437 Store->setAAMetadata(AATags.shift(Offset.getZExtValue()));
3438
3439 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *Store <<
"\n"; } } while (false)
;
3440 }
3441 };
3442
3443 bool visitStoreInst(StoreInst &SI) {
3444 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3445 return false;
3446 Value *V = SI.getValueOperand();
3447 if (V->getType()->isSingleValueType())
3448 return false;
3449
3450 // We have an aggregate being stored, split it apart.
3451 LLVM_DEBUG(dbgs() << " original: " << SI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << SI <<
"\n"; } } while (false)
;
3452 StoreOpSplitter Splitter(&SI, *U, V->getType(), SI.getAAMetadata(),
3453 getAdjustedAlignment(&SI, 0), DL, IRB);
3454 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
3455 Visited.erase(&SI);
3456 SI.eraseFromParent();
3457 return true;
3458 }
3459
3460 bool visitBitCastInst(BitCastInst &BC) {
3461 enqueueUsers(BC);
3462 return false;
3463 }
3464
3465 bool visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
3466 enqueueUsers(ASC);
3467 return false;
3468 }
3469
3470 // Fold gep (select cond, ptr1, ptr2) => select cond, gep(ptr1), gep(ptr2)
3471 bool foldGEPSelect(GetElementPtrInst &GEPI) {
3472 if (!GEPI.hasAllConstantIndices())
3473 return false;
3474
3475 SelectInst *Sel = cast<SelectInst>(GEPI.getPointerOperand());
3476
3477 LLVM_DEBUG(dbgs() << " Rewriting gep(select) -> select(gep):"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Rewriting gep(select) -> select(gep):"
<< "\n original: " << *Sel << "\n "
<< GEPI; } } while (false)
3478 << "\n original: " << *Seldo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Rewriting gep(select) -> select(gep):"
<< "\n original: " << *Sel << "\n "
<< GEPI; } } while (false)
3479 << "\n " << GEPI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Rewriting gep(select) -> select(gep):"
<< "\n original: " << *Sel << "\n "
<< GEPI; } } while (false)
;
3480
3481 IRB.SetInsertPoint(&GEPI);
3482 SmallVector<Value *, 4> Index(GEPI.indices());
3483 bool IsInBounds = GEPI.isInBounds();
3484
3485 Type *Ty = GEPI.getSourceElementType();
3486 Value *True = Sel->getTrueValue();
3487 Value *NTrue = IRB.CreateGEP(Ty, True, Index, True->getName() + ".sroa.gep",
3488 IsInBounds);
3489
3490 Value *False = Sel->getFalseValue();
3491
3492 Value *NFalse = IRB.CreateGEP(Ty, False, Index,
3493 False->getName() + ".sroa.gep", IsInBounds);
3494
3495 Value *NSel = IRB.CreateSelect(Sel->getCondition(), NTrue, NFalse,
3496 Sel->getName() + ".sroa.sel");
3497 Visited.erase(&GEPI);
3498 GEPI.replaceAllUsesWith(NSel);
3499 GEPI.eraseFromParent();
3500 Instruction *NSelI = cast<Instruction>(NSel);
3501 Visited.insert(NSelI);
3502 enqueueUsers(*NSelI);
3503
3504 LLVM_DEBUG(dbgs() << "\n to: " << *NTruedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "\n to: " << *NTrue
<< "\n " << *NFalse << "\n "
<< *NSel << '\n'; } } while (false)
3505 << "\n " << *NFalsedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "\n to: " << *NTrue
<< "\n " << *NFalse << "\n "
<< *NSel << '\n'; } } while (false)
3506 << "\n " << *NSel << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "\n to: " << *NTrue
<< "\n " << *NFalse << "\n "
<< *NSel << '\n'; } } while (false)
;
3507
3508 return true;
3509 }
3510
3511 // Fold gep (phi ptr1, ptr2) => phi gep(ptr1), gep(ptr2)
3512 bool foldGEPPhi(GetElementPtrInst &GEPI) {
3513 if (!GEPI.hasAllConstantIndices())
3514 return false;
3515
3516 PHINode *PHI = cast<PHINode>(GEPI.getPointerOperand());
3517 if (GEPI.getParent() != PHI->getParent() ||
3518 llvm::any_of(PHI->incoming_values(), [](Value *In)
3519 { Instruction *I = dyn_cast<Instruction>(In);
3520 return !I || isa<GetElementPtrInst>(I) || isa<PHINode>(I) ||
3521 succ_empty(I->getParent()) ||
3522 !I->getParent()->isLegalToHoistInto();
3523 }))
3524 return false;
3525
3526 LLVM_DEBUG(dbgs() << " Rewriting gep(phi) -> phi(gep):"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Rewriting gep(phi) -> phi(gep):"
<< "\n original: " << *PHI << "\n "
<< GEPI << "\n to: "; } } while (false)
3527 << "\n original: " << *PHIdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Rewriting gep(phi) -> phi(gep):"
<< "\n original: " << *PHI << "\n "
<< GEPI << "\n to: "; } } while (false)
3528 << "\n " << GEPIdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Rewriting gep(phi) -> phi(gep):"
<< "\n original: " << *PHI << "\n "
<< GEPI << "\n to: "; } } while (false)
3529 << "\n to: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Rewriting gep(phi) -> phi(gep):"
<< "\n original: " << *PHI << "\n "
<< GEPI << "\n to: "; } } while (false)
;
3530
3531 SmallVector<Value *, 4> Index(GEPI.indices());
3532 bool IsInBounds = GEPI.isInBounds();
3533 IRB.SetInsertPoint(GEPI.getParent()->getFirstNonPHI());
3534 PHINode *NewPN = IRB.CreatePHI(GEPI.getType(), PHI->getNumIncomingValues(),
3535 PHI->getName() + ".sroa.phi");
3536 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I != E; ++I) {
3537 BasicBlock *B = PHI->getIncomingBlock(I);
3538 Value *NewVal = nullptr;
3539 int Idx = NewPN->getBasicBlockIndex(B);
3540 if (Idx >= 0) {
3541 NewVal = NewPN->getIncomingValue(Idx);
3542 } else {
3543 Instruction *In = cast<Instruction>(PHI->getIncomingValue(I));
3544
3545 IRB.SetInsertPoint(In->getParent(), std::next(In->getIterator()));
3546 Type *Ty = GEPI.getSourceElementType();
3547 NewVal = IRB.CreateGEP(Ty, In, Index, In->getName() + ".sroa.gep",
3548 IsInBounds);
3549 }
3550 NewPN->addIncoming(NewVal, B);
3551 }
3552
3553 Visited.erase(&GEPI);
3554 GEPI.replaceAllUsesWith(NewPN);
3555 GEPI.eraseFromParent();
3556 Visited.insert(NewPN);
3557 enqueueUsers(*NewPN);
3558
3559 LLVM_DEBUG(for (Value *In : NewPN->incoming_values())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { for (Value *In : NewPN->incoming_values()) dbgs
() << "\n " << *In; dbgs() << "\n "
<< *NewPN << '\n'; } } while (false)
3560 dbgs() << "\n " << *In;do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { for (Value *In : NewPN->incoming_values()) dbgs
() << "\n " << *In; dbgs() << "\n "
<< *NewPN << '\n'; } } while (false)
3561 dbgs() << "\n " << *NewPN << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { for (Value *In : NewPN->incoming_values()) dbgs
() << "\n " << *In; dbgs() << "\n "
<< *NewPN << '\n'; } } while (false)
;
3562
3563 return true;
3564 }
3565
3566 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3567 if (isa<SelectInst>(GEPI.getPointerOperand()) &&
3568 foldGEPSelect(GEPI))
3569 return true;
3570
3571 if (isa<PHINode>(GEPI.getPointerOperand()) &&
3572 foldGEPPhi(GEPI))
3573 return true;
3574
3575 enqueueUsers(GEPI);
3576 return false;
3577 }
3578
3579 bool visitPHINode(PHINode &PN) {
3580 enqueueUsers(PN);
3581 return false;
3582 }
3583
3584 bool visitSelectInst(SelectInst &SI) {
3585 enqueueUsers(SI);
3586 return false;
3587 }
3588};
3589
3590} // end anonymous namespace
3591
3592/// Strip aggregate type wrapping.
3593///
3594/// This removes no-op aggregate types wrapping an underlying type. It will
3595/// strip as many layers of types as it can without changing either the type
3596/// size or the allocated size.
3597static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3598 if (Ty->isSingleValueType())
3599 return Ty;
3600
3601 uint64_t AllocSize = DL.getTypeAllocSize(Ty).getFixedSize();
3602 uint64_t TypeSize = DL.getTypeSizeInBits(Ty).getFixedSize();
3603
3604 Type *InnerTy;
3605 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3606 InnerTy = ArrTy->getElementType();
3607 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3608 const StructLayout *SL = DL.getStructLayout(STy);
3609 unsigned Index = SL->getElementContainingOffset(0);
3610 InnerTy = STy->getElementType(Index);
3611 } else {
3612 return Ty;
3613 }
3614
3615 if (AllocSize > DL.getTypeAllocSize(InnerTy).getFixedSize() ||
3616 TypeSize > DL.getTypeSizeInBits(InnerTy).getFixedSize())
3617 return Ty;
3618
3619 return stripAggregateTypeWrapping(DL, InnerTy);
3620}
3621
3622/// Try to find a partition of the aggregate type passed in for a given
3623/// offset and size.
3624///
3625/// This recurses through the aggregate type and tries to compute a subtype
3626/// based on the offset and size. When the offset and size span a sub-section
3627/// of an array, it will even compute a new array type for that sub-section,
3628/// and the same for structs.
3629///
3630/// Note that this routine is very strict and tries to find a partition of the
3631/// type which produces the *exact* right offset and size. It is not forgiving
3632/// when the size or offset cause either end of type-based partition to be off.
3633/// Also, this is a best-effort routine. It is reasonable to give up and not
3634/// return a type if necessary.
3635static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3636 uint64_t Size) {
3637 if (Offset == 0 && DL.getTypeAllocSize(Ty).getFixedSize() == Size)
3638 return stripAggregateTypeWrapping(DL, Ty);
3639 if (Offset > DL.getTypeAllocSize(Ty).getFixedSize() ||
3640 (DL.getTypeAllocSize(Ty).getFixedSize() - Offset) < Size)
3641 return nullptr;
3642
3643 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
3644 Type *ElementTy;
3645 uint64_t TyNumElements;
3646 if (auto *AT = dyn_cast<ArrayType>(Ty)) {
3647 ElementTy = AT->getElementType();
3648 TyNumElements = AT->getNumElements();
3649 } else {
3650 // FIXME: This isn't right for vectors with non-byte-sized or
3651 // non-power-of-two sized elements.
3652 auto *VT = cast<FixedVectorType>(Ty);
3653 ElementTy = VT->getElementType();
3654 TyNumElements = VT->getNumElements();
3655 }
3656 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy).getFixedSize();
3657 uint64_t NumSkippedElements = Offset / ElementSize;
3658 if (NumSkippedElements >= TyNumElements)
3659 return nullptr;
3660 Offset -= NumSkippedElements * ElementSize;
3661
3662 // First check if we need to recurse.
3663 if (Offset > 0 || Size < ElementSize) {
3664 // Bail if the partition ends in a different array element.
3665 if ((Offset + Size) > ElementSize)
3666 return nullptr;
3667 // Recurse through the element type trying to peel off offset bytes.
3668 return getTypePartition(DL, ElementTy, Offset, Size);
3669 }
3670 assert(Offset == 0)(static_cast <bool> (Offset == 0) ? void (0) : __assert_fail
("Offset == 0", "llvm/lib/Transforms/Scalar/SROA.cpp", 3670,
__extension__ __PRETTY_FUNCTION__))
;
3671
3672 if (Size == ElementSize)
3673 return stripAggregateTypeWrapping(DL, ElementTy);
3674 assert(Size > ElementSize)(static_cast <bool> (Size > ElementSize) ? void (0) :
__assert_fail ("Size > ElementSize", "llvm/lib/Transforms/Scalar/SROA.cpp"
, 3674, __extension__ __PRETTY_FUNCTION__))
;
3675 uint64_t NumElements = Size / ElementSize;
3676 if (NumElements * ElementSize != Size)
3677 return nullptr;
3678 return ArrayType::get(ElementTy, NumElements);
3679 }
3680
3681 StructType *STy = dyn_cast<StructType>(Ty);
3682 if (!STy)
3683 return nullptr;
3684
3685 const StructLayout *SL = DL.getStructLayout(STy);
3686 if (Offset >= SL->getSizeInBytes())
3687 return nullptr;
3688 uint64_t EndOffset = Offset + Size;
3689 if (EndOffset > SL->getSizeInBytes())
3690 return nullptr;
3691
3692 unsigned Index = SL->getElementContainingOffset(Offset);
3693 Offset -= SL->getElementOffset(Index);
3694
3695 Type *ElementTy = STy->getElementType(Index);
3696 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy).getFixedSize();
3697 if (Offset >= ElementSize)
3698 return nullptr; // The offset points into alignment padding.
3699
3700 // See if any partition must be contained by the element.
3701 if (Offset > 0 || Size < ElementSize) {
3702 if ((Offset + Size) > ElementSize)
3703 return nullptr;
3704 return getTypePartition(DL, ElementTy, Offset, Size);
3705 }
3706 assert(Offset == 0)(static_cast <bool> (Offset == 0) ? void (0) : __assert_fail
("Offset == 0", "llvm/lib/Transforms/Scalar/SROA.cpp", 3706,
__extension__ __PRETTY_FUNCTION__))
;
3707
3708 if (Size == ElementSize)
3709 return stripAggregateTypeWrapping(DL, ElementTy);
3710
3711 StructType::element_iterator EI = STy->element_begin() + Index,
3712 EE = STy->element_end();
3713 if (EndOffset < SL->getSizeInBytes()) {
3714 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3715 if (Index == EndIndex)
3716 return nullptr; // Within a single element and its padding.
3717
3718 // Don't try to form "natural" types if the elements don't line up with the
3719 // expected size.
3720 // FIXME: We could potentially recurse down through the last element in the
3721 // sub-struct to find a natural end point.
3722 if (SL->getElementOffset(EndIndex) != EndOffset)
3723 return nullptr;
3724
3725 assert(Index < EndIndex)(static_cast <bool> (Index < EndIndex) ? void (0) : __assert_fail
("Index < EndIndex", "llvm/lib/Transforms/Scalar/SROA.cpp"
, 3725, __extension__ __PRETTY_FUNCTION__))
;
3726 EE = STy->element_begin() + EndIndex;
3727 }
3728
3729 // Try to build up a sub-structure.
3730 StructType *SubTy =
3731 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
3732 const StructLayout *SubSL = DL.getStructLayout(SubTy);
3733 if (Size != SubSL->getSizeInBytes())
3734 return nullptr; // The sub-struct doesn't have quite the size needed.
3735
3736 return SubTy;
3737}
3738
3739/// Pre-split loads and stores to simplify rewriting.
3740///
3741/// We want to break up the splittable load+store pairs as much as
3742/// possible. This is important to do as a preprocessing step, as once we
3743/// start rewriting the accesses to partitions of the alloca we lose the
3744/// necessary information to correctly split apart paired loads and stores
3745/// which both point into this alloca. The case to consider is something like
3746/// the following:
3747///
3748/// %a = alloca [12 x i8]
3749/// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3750/// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3751/// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3752/// %iptr1 = bitcast i8* %gep1 to i64*
3753/// %iptr2 = bitcast i8* %gep2 to i64*
3754/// %fptr1 = bitcast i8* %gep1 to float*
3755/// %fptr2 = bitcast i8* %gep2 to float*
3756/// %fptr3 = bitcast i8* %gep3 to float*
3757/// store float 0.0, float* %fptr1
3758/// store float 1.0, float* %fptr2
3759/// %v = load i64* %iptr1
3760/// store i64 %v, i64* %iptr2
3761/// %f1 = load float* %fptr2
3762/// %f2 = load float* %fptr3
3763///
3764/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3765/// promote everything so we recover the 2 SSA values that should have been
3766/// there all along.
3767///
3768/// \returns true if any changes are made.
3769bool SROAPass::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
3770 LLVM_DEBUG(dbgs() << "Pre-splitting loads and stores\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "Pre-splitting loads and stores\n"
; } } while (false)
;
3771
3772 // Track the loads and stores which are candidates for pre-splitting here, in
3773 // the order they first appear during the partition scan. These give stable
3774 // iteration order and a basis for tracking which loads and stores we
3775 // actually split.
3776 SmallVector<LoadInst *, 4> Loads;
3777 SmallVector<StoreInst *, 4> Stores;
3778
3779 // We need to accumulate the splits required of each load or store where we
3780 // can find them via a direct lookup. This is important to cross-check loads
3781 // and stores against each other. We also track the slice so that we can kill
3782 // all the slices that end up split.
3783 struct SplitOffsets {
3784 Slice *S;
3785 std::vector<uint64_t> Splits;
3786 };
3787 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3788
3789 // Track loads out of this alloca which cannot, for any reason, be pre-split.
3790 // This is important as we also cannot pre-split stores of those loads!
3791 // FIXME: This is all pretty gross. It means that we can be more aggressive
3792 // in pre-splitting when the load feeding the store happens to come from
3793 // a separate alloca. Put another way, the effectiveness of SROA would be
3794 // decreased by a frontend which just concatenated all of its local allocas
3795 // into one big flat alloca. But defeating such patterns is exactly the job
3796 // SROA is tasked with! Sadly, to not have this discrepancy we would have
3797 // change store pre-splitting to actually force pre-splitting of the load
3798 // that feeds it *and all stores*. That makes pre-splitting much harder, but
3799 // maybe it would make it more principled?
3800 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3801
3802 LLVM_DEBUG(dbgs() << " Searching for candidate loads and stores\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Searching for candidate loads and stores\n"
; } } while (false)
;
3803 for (auto &P : AS.partitions()) {
3804 for (Slice &S : P) {
3805 Instruction *I = cast<Instruction>(S.getUse()->getUser());
3806 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
3807 // If this is a load we have to track that it can't participate in any
3808 // pre-splitting. If this is a store of a load we have to track that
3809 // that load also can't participate in any pre-splitting.
3810 if (auto *LI = dyn_cast<LoadInst>(I))
3811 UnsplittableLoads.insert(LI);
3812 else if (auto *SI = dyn_cast<StoreInst>(I))
3813 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
3814 UnsplittableLoads.insert(LI);
3815 continue;
3816 }
3817 assert(P.endOffset() > S.beginOffset() &&(static_cast <bool> (P.endOffset() > S.beginOffset()
&& "Empty or backwards partition!") ? void (0) : __assert_fail
("P.endOffset() > S.beginOffset() && \"Empty or backwards partition!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3818, __extension__ __PRETTY_FUNCTION__
))
3818 "Empty or backwards partition!")(static_cast <bool> (P.endOffset() > S.beginOffset()
&& "Empty or backwards partition!") ? void (0) : __assert_fail
("P.endOffset() > S.beginOffset() && \"Empty or backwards partition!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3818, __extension__ __PRETTY_FUNCTION__
))
;
3819
3820 // Determine if this is a pre-splittable slice.
3821 if (auto *LI = dyn_cast<LoadInst>(I)) {
3822 assert(!LI->isVolatile() && "Cannot split volatile loads!")(static_cast <bool> (!LI->isVolatile() && "Cannot split volatile loads!"
) ? void (0) : __assert_fail ("!LI->isVolatile() && \"Cannot split volatile loads!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3822, __extension__ __PRETTY_FUNCTION__
))
;
3823
3824 // The load must be used exclusively to store into other pointers for
3825 // us to be able to arbitrarily pre-split it. The stores must also be
3826 // simple to avoid changing semantics.
3827 auto IsLoadSimplyStored = [](LoadInst *LI) {
3828 for (User *LU : LI->users()) {
3829 auto *SI = dyn_cast<StoreInst>(LU);
3830 if (!SI || !SI->isSimple())
3831 return false;
3832 }
3833 return true;
3834 };
3835 if (!IsLoadSimplyStored(LI)) {
3836 UnsplittableLoads.insert(LI);
3837 continue;
3838 }
3839
3840 Loads.push_back(LI);
3841 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
3842 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3843 // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
3844 continue;
3845 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3846 if (!StoredLoad || !StoredLoad->isSimple())
3847 continue;
3848 assert(!SI->isVolatile() && "Cannot split volatile stores!")(static_cast <bool> (!SI->isVolatile() && "Cannot split volatile stores!"
) ? void (0) : __assert_fail ("!SI->isVolatile() && \"Cannot split volatile stores!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3848, __extension__ __PRETTY_FUNCTION__
))
;
3849
3850 Stores.push_back(SI);
3851 } else {
3852 // Other uses cannot be pre-split.
3853 continue;
3854 }
3855
3856 // Record the initial split.
3857 LLVM_DEBUG(dbgs() << " Candidate: " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Candidate: " << *I <<
"\n"; } } while (false)
;
3858 auto &Offsets = SplitOffsetsMap[I];
3859 assert(Offsets.Splits.empty() &&(static_cast <bool> (Offsets.Splits.empty() && "Should not have splits the first time we see an instruction!"
) ? void (0) : __assert_fail ("Offsets.Splits.empty() && \"Should not have splits the first time we see an instruction!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3860, __extension__ __PRETTY_FUNCTION__
))
3860 "Should not have splits the first time we see an instruction!")(static_cast <bool> (Offsets.Splits.empty() && "Should not have splits the first time we see an instruction!"
) ? void (0) : __assert_fail ("Offsets.Splits.empty() && \"Should not have splits the first time we see an instruction!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3860, __extension__ __PRETTY_FUNCTION__
))
;
3861 Offsets.S = &S;
3862 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
3863 }
3864
3865 // Now scan the already split slices, and add a split for any of them which
3866 // we're going to pre-split.
3867 for (Slice *S : P.splitSliceTails()) {
3868 auto SplitOffsetsMapI =
3869 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3870 if (SplitOffsetsMapI == SplitOffsetsMap.end())
3871 continue;
3872 auto &Offsets = SplitOffsetsMapI->second;
3873
3874 assert(Offsets.S == S && "Found a mismatched slice!")(static_cast <bool> (Offsets.S == S && "Found a mismatched slice!"
) ? void (0) : __assert_fail ("Offsets.S == S && \"Found a mismatched slice!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3874, __extension__ __PRETTY_FUNCTION__
))
;
3875 assert(!Offsets.Splits.empty() &&(static_cast <bool> (!Offsets.Splits.empty() &&
"Cannot have an empty set of splits on the second partition!"
) ? void (0) : __assert_fail ("!Offsets.Splits.empty() && \"Cannot have an empty set of splits on the second partition!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3876, __extension__ __PRETTY_FUNCTION__
))
3876 "Cannot have an empty set of splits on the second partition!")(static_cast <bool> (!Offsets.Splits.empty() &&
"Cannot have an empty set of splits on the second partition!"
) ? void (0) : __assert_fail ("!Offsets.Splits.empty() && \"Cannot have an empty set of splits on the second partition!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3876, __extension__ __PRETTY_FUNCTION__
))
;
3877 assert(Offsets.Splits.back() ==(static_cast <bool> (Offsets.Splits.back() == P.beginOffset
() - Offsets.S->beginOffset() && "Previous split does not end where this one begins!"
) ? void (0) : __assert_fail ("Offsets.Splits.back() == P.beginOffset() - Offsets.S->beginOffset() && \"Previous split does not end where this one begins!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3879, __extension__ __PRETTY_FUNCTION__
))
3878 P.beginOffset() - Offsets.S->beginOffset() &&(static_cast <bool> (Offsets.Splits.back() == P.beginOffset
() - Offsets.S->beginOffset() && "Previous split does not end where this one begins!"
) ? void (0) : __assert_fail ("Offsets.Splits.back() == P.beginOffset() - Offsets.S->beginOffset() && \"Previous split does not end where this one begins!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3879, __extension__ __PRETTY_FUNCTION__
))
3879 "Previous split does not end where this one begins!")(static_cast <bool> (Offsets.Splits.back() == P.beginOffset
() - Offsets.S->beginOffset() && "Previous split does not end where this one begins!"
) ? void (0) : __assert_fail ("Offsets.Splits.back() == P.beginOffset() - Offsets.S->beginOffset() && \"Previous split does not end where this one begins!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3879, __extension__ __PRETTY_FUNCTION__
))
;
3880
3881 // Record each split. The last partition's end isn't needed as the size
3882 // of the slice dictates that.
3883 if (S->endOffset() > P.endOffset())
3884 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
3885 }
3886 }
3887
3888 // We may have split loads where some of their stores are split stores. For
3889 // such loads and stores, we can only pre-split them if their splits exactly
3890 // match relative to their starting offset. We have to verify this prior to
3891 // any rewriting.
3892 llvm::erase_if(Stores, [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
3893 // Lookup the load we are storing in our map of split
3894 // offsets.
3895 auto *LI = cast<LoadInst>(SI->getValueOperand());
3896 // If it was completely unsplittable, then we're done,
3897 // and this store can't be pre-split.
3898 if (UnsplittableLoads.count(LI))
3899 return true;
3900
3901 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3902 if (LoadOffsetsI == SplitOffsetsMap.end())
3903 return false; // Unrelated loads are definitely safe.
3904 auto &LoadOffsets = LoadOffsetsI->second;
3905
3906 // Now lookup the store's offsets.
3907 auto &StoreOffsets = SplitOffsetsMap[SI];
3908
3909 // If the relative offsets of each split in the load and
3910 // store match exactly, then we can split them and we
3911 // don't need to remove them here.
3912 if (LoadOffsets.Splits == StoreOffsets.Splits)
3913 return false;
3914
3915 LLVM_DEBUG(dbgs() << " Mismatched splits for load and store:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Mismatched splits for load and store:\n"
<< " " << *LI << "\n" << " "
<< *SI << "\n"; } } while (false)
3916 << " " << *LI << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Mismatched splits for load and store:\n"
<< " " << *LI << "\n" << " "
<< *SI << "\n"; } } while (false)
3917 << " " << *SI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Mismatched splits for load and store:\n"
<< " " << *LI << "\n" << " "
<< *SI << "\n"; } } while (false)
;
3918
3919 // We've found a store and load that we need to split
3920 // with mismatched relative splits. Just give up on them
3921 // and remove both instructions from our list of
3922 // candidates.
3923 UnsplittableLoads.insert(LI);
3924 return true;
3925 });
3926 // Now we have to go *back* through all the stores, because a later store may
3927 // have caused an earlier store's load to become unsplittable and if it is
3928 // unsplittable for the later store, then we can't rely on it being split in
3929 // the earlier store either.
3930 llvm::erase_if(Stores, [&UnsplittableLoads](StoreInst *SI) {
3931 auto *LI = cast<LoadInst>(SI->getValueOperand());
3932 return UnsplittableLoads.count(LI);
3933 });
3934 // Once we've established all the loads that can't be split for some reason,
3935 // filter any that made it into our list out.
3936 llvm::erase_if(Loads, [&UnsplittableLoads](LoadInst *LI) {
3937 return UnsplittableLoads.count(LI);
3938 });
3939
3940 // If no loads or stores are left, there is no pre-splitting to be done for
3941 // this alloca.
3942 if (Loads.empty() && Stores.empty())
3943 return false;
3944
3945 // From here on, we can't fail and will be building new accesses, so rig up
3946 // an IR builder.
3947 IRBuilderTy IRB(&AI);
3948
3949 // Collect the new slices which we will merge into the alloca slices.
3950 SmallVector<Slice, 4> NewSlices;
3951
3952 // Track any allocas we end up splitting loads and stores for so we iterate
3953 // on them.
3954 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3955
3956 // At this point, we have collected all of the loads and stores we can
3957 // pre-split, and the specific splits needed for them. We actually do the
3958 // splitting in a specific order in order to handle when one of the loads in
3959 // the value operand to one of the stores.
3960 //
3961 // First, we rewrite all of the split loads, and just accumulate each split
3962 // load in a parallel structure. We also build the slices for them and append
3963 // them to the alloca slices.
3964 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3965 std::vector<LoadInst *> SplitLoads;
3966 const DataLayout &DL = AI.getModule()->getDataLayout();
3967 for (LoadInst *LI : Loads) {
3968 SplitLoads.clear();
3969
3970 auto &Offsets = SplitOffsetsMap[LI];
3971 unsigned SliceSize = Offsets.S->endOffset() - Offsets.S->beginOffset();
3972 assert(LI->getType()->getIntegerBitWidth() % 8 == 0 &&(static_cast <bool> (LI->getType()->getIntegerBitWidth
() % 8 == 0 && "Load must have type size equal to store size"
) ? void (0) : __assert_fail ("LI->getType()->getIntegerBitWidth() % 8 == 0 && \"Load must have type size equal to store size\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3973, __extension__ __PRETTY_FUNCTION__
))
3973 "Load must have type size equal to store size")(static_cast <bool> (LI->getType()->getIntegerBitWidth
() % 8 == 0 && "Load must have type size equal to store size"
) ? void (0) : __assert_fail ("LI->getType()->getIntegerBitWidth() % 8 == 0 && \"Load must have type size equal to store size\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3973, __extension__ __PRETTY_FUNCTION__
))
;
3974 assert(LI->getType()->getIntegerBitWidth() / 8 >= SliceSize &&(static_cast <bool> (LI->getType()->getIntegerBitWidth
() / 8 >= SliceSize && "Load must be >= slice size"
) ? void (0) : __assert_fail ("LI->getType()->getIntegerBitWidth() / 8 >= SliceSize && \"Load must be >= slice size\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3975, __extension__ __PRETTY_FUNCTION__
))
3975 "Load must be >= slice size")(static_cast <bool> (LI->getType()->getIntegerBitWidth
() / 8 >= SliceSize && "Load must be >= slice size"
) ? void (0) : __assert_fail ("LI->getType()->getIntegerBitWidth() / 8 >= SliceSize && \"Load must be >= slice size\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3975, __extension__ __PRETTY_FUNCTION__
))
;
3976
3977 uint64_t BaseOffset = Offsets.S->beginOffset();
3978 assert(BaseOffset + SliceSize > BaseOffset &&(static_cast <bool> (BaseOffset + SliceSize > BaseOffset
&& "Cannot represent alloca access size using 64-bit integers!"
) ? void (0) : __assert_fail ("BaseOffset + SliceSize > BaseOffset && \"Cannot represent alloca access size using 64-bit integers!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3979, __extension__ __PRETTY_FUNCTION__
))
3979 "Cannot represent alloca access size using 64-bit integers!")(static_cast <bool> (BaseOffset + SliceSize > BaseOffset
&& "Cannot represent alloca access size using 64-bit integers!"
) ? void (0) : __assert_fail ("BaseOffset + SliceSize > BaseOffset && \"Cannot represent alloca access size using 64-bit integers!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 3979, __extension__ __PRETTY_FUNCTION__
))
;
3980
3981 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
3982 IRB.SetInsertPoint(LI);
3983
3984 LLVM_DEBUG(dbgs() << " Splitting load: " << *LI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Splitting load: " << *LI
<< "\n"; } } while (false)
;
3985
3986 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3987 int Idx = 0, Size = Offsets.Splits.size();
3988 for (;;) {
3989 auto *PartTy = Type::getIntNTy(LI->getContext(), PartSize * 8);
3990 auto AS = LI->getPointerAddressSpace();
3991 auto *PartPtrTy = PartTy->getPointerTo(AS);
3992 LoadInst *PLoad = IRB.CreateAlignedLoad(
3993 PartTy,
3994 getAdjustedPtr(IRB, DL, BasePtr,
3995 APInt(DL.getIndexSizeInBits(AS), PartOffset),
3996 PartPtrTy, BasePtr->getName() + "."),
3997 getAdjustedAlignment(LI, PartOffset),
3998 /*IsVolatile*/ false, LI->getName());
3999 PLoad->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
4000 LLVMContext::MD_access_group});
4001
4002 // Append this load onto the list of split loads so we can find it later
4003 // to rewrite the stores.
4004 SplitLoads.push_back(PLoad);
4005
4006 // Now build a new slice for the alloca.
4007 NewSlices.push_back(
4008 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
4009 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
4010 /*IsSplittable*/ false));
4011 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " new slice [" << NewSlices
.back().beginOffset() << ", " << NewSlices.back()
.endOffset() << "): " << *PLoad << "\n"; } }
while (false)
4012 << ", " << NewSlices.back().endOffset()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " new slice [" << NewSlices
.back().beginOffset() << ", " << NewSlices.back()
.endOffset() << "): " << *PLoad << "\n"; } }
while (false)
4013 << "): " << *PLoad << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " new slice [" << NewSlices
.back().beginOffset() << ", " << NewSlices.back()
.endOffset() << "): " << *PLoad << "\n"; } }
while (false)
;
4014
4015 // See if we've handled all the splits.
4016 if (Idx >= Size)
4017 break;
4018
4019 // Setup the next partition.
4020 PartOffset = Offsets.Splits[Idx];
4021 ++Idx;
4022 PartSize = (Idx < Size ? Offsets.Splits[Idx] : SliceSize) - PartOffset;
4023 }
4024
4025 // Now that we have the split loads, do the slow walk over all uses of the
4026 // load and rewrite them as split stores, or save the split loads to use
4027 // below if the store is going to be split there anyways.
4028 bool DeferredStores = false;
4029 for (User *LU : LI->users()) {
4030 StoreInst *SI = cast<StoreInst>(LU);
4031 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
4032 DeferredStores = true;
4033 LLVM_DEBUG(dbgs() << " Deferred splitting of store: " << *SIdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Deferred splitting of store: "
<< *SI << "\n"; } } while (false)
4034 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Deferred splitting of store: "
<< *SI << "\n"; } } while (false)
;
4035 continue;
4036 }
4037
4038 Value *StoreBasePtr = SI->getPointerOperand();
4039 IRB.SetInsertPoint(SI);
4040
4041 LLVM_DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Splitting store of load: " <<
*SI << "\n"; } } while (false)
;
4042
4043 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
4044 LoadInst *PLoad = SplitLoads[Idx];
4045 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
4046 auto *PartPtrTy =
4047 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
4048
4049 auto AS = SI->getPointerAddressSpace();
4050 StoreInst *PStore = IRB.CreateAlignedStore(
4051 PLoad,
4052 getAdjustedPtr(IRB, DL, StoreBasePtr,
4053 APInt(DL.getIndexSizeInBits(AS), PartOffset),
4054 PartPtrTy, StoreBasePtr->getName() + "."),
4055 getAdjustedAlignment(SI, PartOffset),
4056 /*IsVolatile*/ false);
4057 PStore->copyMetadata(*SI, {LLVMContext::MD_mem_parallel_loop_access,
4058 LLVMContext::MD_access_group});
4059 LLVM_DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " +" << PartOffset <<
":" << *PStore << "\n"; } } while (false)
;
4060 }
4061
4062 // We want to immediately iterate on any allocas impacted by splitting
4063 // this store, and we have to track any promotable alloca (indicated by
4064 // a direct store) as needing to be resplit because it is no longer
4065 // promotable.
4066 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
4067 ResplitPromotableAllocas.insert(OtherAI);
4068 Worklist.insert(OtherAI);
4069 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
4070 StoreBasePtr->stripInBoundsOffsets())) {
4071 Worklist.insert(OtherAI);
4072 }
4073
4074 // Mark the original store as dead.
4075 DeadInsts.push_back(SI);
4076 }
4077
4078 // Save the split loads if there are deferred stores among the users.
4079 if (DeferredStores)
4080 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
4081
4082 // Mark the original load as dead and kill the original slice.
4083 DeadInsts.push_back(LI);
4084 Offsets.S->kill();
4085 }
4086
4087 // Second, we rewrite all of the split stores. At this point, we know that
4088 // all loads from this alloca have been split already. For stores of such
4089 // loads, we can simply look up the pre-existing split loads. For stores of
4090 // other loads, we split those loads first and then write split stores of
4091 // them.
4092 for (StoreInst *SI : Stores) {
4093 auto *LI = cast<LoadInst>(SI->getValueOperand());
4094 IntegerType *Ty = cast<IntegerType>(LI->getType());
4095 assert(Ty->getBitWidth() % 8 == 0)(static_cast <bool> (Ty->getBitWidth() % 8 == 0) ? void
(0) : __assert_fail ("Ty->getBitWidth() % 8 == 0", "llvm/lib/Transforms/Scalar/SROA.cpp"
, 4095, __extension__ __PRETTY_FUNCTION__))
;
4096 uint64_t StoreSize = Ty->getBitWidth() / 8;
4097 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!")(static_cast <bool> (StoreSize > 0 && "Cannot have a zero-sized integer store!"
) ? void (0) : __assert_fail ("StoreSize > 0 && \"Cannot have a zero-sized integer store!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 4097, __extension__ __PRETTY_FUNCTION__
))
;
4098
4099 auto &Offsets = SplitOffsetsMap[SI];
4100 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&(static_cast <bool> (StoreSize == Offsets.S->endOffset
() - Offsets.S->beginOffset() && "Slice size should always match load size exactly!"
) ? void (0) : __assert_fail ("StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() && \"Slice size should always match load size exactly!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 4101, __extension__ __PRETTY_FUNCTION__
))
4101 "Slice size should always match load size exactly!")(static_cast <bool> (StoreSize == Offsets.S->endOffset
() - Offsets.S->beginOffset() && "Slice size should always match load size exactly!"
) ? void (0) : __assert_fail ("StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() && \"Slice size should always match load size exactly!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 4101, __extension__ __PRETTY_FUNCTION__
))
;
4102 uint64_t BaseOffset = Offsets.S->beginOffset();
4103 assert(BaseOffset + StoreSize > BaseOffset &&(static_cast <bool> (BaseOffset + StoreSize > BaseOffset
&& "Cannot represent alloca access size using 64-bit integers!"
) ? void (0) : __assert_fail ("BaseOffset + StoreSize > BaseOffset && \"Cannot represent alloca access size using 64-bit integers!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 4104, __extension__ __PRETTY_FUNCTION__
))
4104 "Cannot represent alloca access size using 64-bit integers!")(static_cast <bool> (BaseOffset + StoreSize > BaseOffset
&& "Cannot represent alloca access size using 64-bit integers!"
) ? void (0) : __assert_fail ("BaseOffset + StoreSize > BaseOffset && \"Cannot represent alloca access size using 64-bit integers!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 4104, __extension__ __PRETTY_FUNCTION__
))
;
4105
4106 Value *LoadBasePtr = LI->getPointerOperand();
4107 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
4108
4109 LLVM_DEBUG(dbgs() << " Splitting store: " << *SI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Splitting store: " << *SI
<< "\n"; } } while (false)
;
4110
4111 // Check whether we have an already split load.
4112 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
4113 std::vector<LoadInst *> *SplitLoads = nullptr;
4114 if (SplitLoadsMapI != SplitLoadsMap.end()) {
4115 SplitLoads = &SplitLoadsMapI->second;
4116 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&(static_cast <bool> (SplitLoads->size() == Offsets.Splits
.size() + 1 && "Too few split loads for the number of splits in the store!"
) ? void (0) : __assert_fail ("SplitLoads->size() == Offsets.Splits.size() + 1 && \"Too few split loads for the number of splits in the store!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 4117, __extension__ __PRETTY_FUNCTION__
))
4117 "Too few split loads for the number of splits in the store!")(static_cast <bool> (SplitLoads->size() == Offsets.Splits
.size() + 1 && "Too few split loads for the number of splits in the store!"
) ? void (0) : __assert_fail ("SplitLoads->size() == Offsets.Splits.size() + 1 && \"Too few split loads for the number of splits in the store!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 4117, __extension__ __PRETTY_FUNCTION__
))
;
4118 } else {
4119 LLVM_DEBUG(dbgs() << " of load: " << *LI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " of load: " << *LI
<< "\n"; } } while (false)
;
4120 }
4121
4122 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
4123 int Idx = 0, Size = Offsets.Splits.size();
4124 for (;;) {
4125 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
4126 auto *LoadPartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
4127 auto *StorePartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
4128
4129 // Either lookup a split load or create one.
4130 LoadInst *PLoad;
4131 if (SplitLoads) {
4132 PLoad = (*SplitLoads)[Idx];
4133 } else {
4134 IRB.SetInsertPoint(LI);
4135 auto AS = LI->getPointerAddressSpace();
4136 PLoad = IRB.CreateAlignedLoad(
4137 PartTy,
4138 getAdjustedPtr(IRB, DL, LoadBasePtr,
4139 APInt(DL.getIndexSizeInBits(AS), PartOffset),
4140 LoadPartPtrTy, LoadBasePtr->getName() + "."),
4141 getAdjustedAlignment(LI, PartOffset),
4142 /*IsVolatile*/ false, LI->getName());
4143 PLoad->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
4144 LLVMContext::MD_access_group});
4145 }
4146
4147 // And store this partition.
4148 IRB.SetInsertPoint(SI);
4149 auto AS = SI->getPointerAddressSpace();
4150 StoreInst *PStore = IRB.CreateAlignedStore(
4151 PLoad,
4152 getAdjustedPtr(IRB, DL, StoreBasePtr,
4153 APInt(DL.getIndexSizeInBits(AS), PartOffset),
4154 StorePartPtrTy, StoreBasePtr->getName() + "."),
4155 getAdjustedAlignment(SI, PartOffset),
4156 /*IsVolatile*/ false);
4157 PStore->copyMetadata(*SI, {LLVMContext::MD_mem_parallel_loop_access,
4158 LLVMContext::MD_access_group});
4159
4160 // Now build a new slice for the alloca.
4161 NewSlices.push_back(
4162 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
4163 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
4164 /*IsSplittable*/ false));
4165 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " new slice [" << NewSlices
.back().beginOffset() << ", " << NewSlices.back()
.endOffset() << "): " << *PStore << "\n"; }
} while (false)
4166 << ", " << NewSlices.back().endOffset()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " new slice [" << NewSlices
.back().beginOffset() << ", " << NewSlices.back()
.endOffset() << "): " << *PStore << "\n"; }
} while (false)
4167 << "): " << *PStore << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " new slice [" << NewSlices
.back().beginOffset() << ", " << NewSlices.back()
.endOffset() << "): " << *PStore << "\n"; }
} while (false)
;
4168 if (!SplitLoads) {
4169 LLVM_DEBUG(dbgs() << " of split load: " << *PLoad << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " of split load: " << *
PLoad << "\n"; } } while (false)
;
4170 }
4171
4172 // See if we've finished all the splits.
4173 if (Idx >= Size)
4174 break;
4175
4176 // Setup the next partition.
4177 PartOffset = Offsets.Splits[Idx];
4178 ++Idx;
4179 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
4180 }
4181
4182 // We want to immediately iterate on any allocas impacted by splitting
4183 // this load, which is only relevant if it isn't a load of this alloca and
4184 // thus we didn't already split the loads above. We also have to keep track
4185 // of any promotable allocas we split loads on as they can no longer be
4186 // promoted.
4187 if (!SplitLoads) {
4188 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
4189 assert(OtherAI != &AI && "We can't re-split our own alloca!")(static_cast <bool> (OtherAI != &AI && "We can't re-split our own alloca!"
) ? void (0) : __assert_fail ("OtherAI != &AI && \"We can't re-split our own alloca!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 4189, __extension__ __PRETTY_FUNCTION__
))
;
4190 ResplitPromotableAllocas.insert(OtherAI);
4191 Worklist.insert(OtherAI);
4192 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
4193 LoadBasePtr->stripInBoundsOffsets())) {
4194 assert(OtherAI != &AI && "We can't re-split our own alloca!")(static_cast <bool> (OtherAI != &AI && "We can't re-split our own alloca!"
) ? void (0) : __assert_fail ("OtherAI != &AI && \"We can't re-split our own alloca!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 4194, __extension__ __PRETTY_FUNCTION__
))
;
4195 Worklist.insert(OtherAI);
4196 }
4197 }
4198
4199 // Mark the original store as dead now that we've split it up and kill its
4200 // slice. Note that we leave the original load in place unless this store
4201 // was its only use. It may in turn be split up if it is an alloca load
4202 // for some other alloca, but it may be a normal load. This may introduce
4203 // redundant loads, but where those can be merged the rest of the optimizer
4204 // should handle the merging, and this uncovers SSA splits which is more
4205 // important. In practice, the original loads will almost always be fully
4206 // split and removed eventually, and the splits will be merged by any
4207 // trivial CSE, including instcombine.
4208 if (LI->hasOneUse()) {
4209 assert(*LI->user_begin() == SI && "Single use isn't this store!")(static_cast <bool> (*LI->user_begin() == SI &&
"Single use isn't this store!") ? void (0) : __assert_fail (
"*LI->user_begin() == SI && \"Single use isn't this store!\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 4209, __extension__ __PRETTY_FUNCTION__
))
;
4210 DeadInsts.push_back(LI);
4211 }
4212 DeadInsts.push_back(SI);
4213 Offsets.S->kill();
4214 }
4215
4216 // Remove the killed slices that have ben pre-split.
4217 llvm::erase_if(AS, [](const Slice &S) { return S.isDead(); });
4218
4219 // Insert our new slices. This will sort and merge them into the sorted
4220 // sequence.
4221 AS.insert(NewSlices);
4222
4223 LLVM_DEBUG(dbgs() << " Pre-split slices:\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Pre-split slices:\n"; } } while
(false)
;
4224#ifndef NDEBUG
4225 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
4226 LLVM_DEBUG(AS.print(dbgs(), I, " "))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { AS.print(dbgs(), I, " "); } } while (false)
;
4227#endif
4228
4229 // Finally, don't try to promote any allocas that new require re-splitting.
4230 // They have already been added to the worklist above.
4231 llvm::erase_if(PromotableAllocas, [&](AllocaInst *AI) {
4232 return ResplitPromotableAllocas.count(AI);
4233 });
4234
4235 return true;
4236}
4237
4238/// Rewrite an alloca partition's users.
4239///
4240/// This routine drives both of the rewriting goals of the SROA pass. It tries
4241/// to rewrite uses of an alloca partition to be conducive for SSA value
4242/// promotion. If the partition needs a new, more refined alloca, this will
4243/// build that new alloca, preserving as much type information as possible, and
4244/// rewrite the uses of the old alloca to point at the new one and have the
4245/// appropriate new offsets. It also evaluates how successful the rewrite was
4246/// at enabling promotion and if it was successful queues the alloca to be
4247/// promoted.
4248AllocaInst *SROAPass::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
4249 Partition &P) {
4250 // Try to compute a friendly type for this partition of the alloca. This
4251 // won't always succeed, in which case we fall back to a legal integer type
4252 // or an i8 array of an appropriate size.
4253 Type *SliceTy = nullptr;
4254 VectorType *SliceVecTy = nullptr;
4255 const DataLayout &DL = AI.getModule()->getDataLayout();
4256 std::pair<Type *, IntegerType *> CommonUseTy =
4257 findCommonType(P.begin(), P.end(), P.endOffset());
4258 // Do all uses operate on the same type?
4259 if (CommonUseTy.first)
4260 if (DL.getTypeAllocSize(CommonUseTy.first).getFixedSize() >= P.size()) {
4261 SliceTy = CommonUseTy.first;
4262 SliceVecTy = dyn_cast<VectorType>(SliceTy);
4263 }
4264 // If not, can we find an appropriate subtype in the original allocated type?
4265 if (!SliceTy)
4266 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
4267 P.beginOffset(), P.size()))
4268 SliceTy = TypePartitionTy;
4269
4270 // If still not, can we use the largest bitwidth integer type used?
4271 if (!SliceTy && CommonUseTy.second)
4272 if (DL.getTypeAllocSize(CommonUseTy.second).getFixedSize() >= P.size()) {
4273 SliceTy = CommonUseTy.second;
4274 SliceVecTy = dyn_cast<VectorType>(SliceTy);
4275 }
4276 if ((!SliceTy || (SliceTy->isArrayTy() &&
4277 SliceTy->getArrayElementType()->isIntegerTy())) &&
4278 DL.isLegalInteger(P.size() * 8)) {
4279 SliceTy = Type::getIntNTy(*C, P.size() * 8);
4280 }
4281
4282 // If the common use types are not viable for promotion then attempt to find
4283 // another type that is viable.
4284 if (SliceVecTy && !checkVectorTypeForPromotion(P, SliceVecTy, DL))
4285 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
4286 P.beginOffset(), P.size())) {
4287 VectorType *TypePartitionVecTy = dyn_cast<VectorType>(TypePartitionTy);
4288 if (TypePartitionVecTy &&
4289 checkVectorTypeForPromotion(P, TypePartitionVecTy, DL))
4290 SliceTy = TypePartitionTy;
4291 }
4292
4293 if (!SliceTy)
4294 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
4295 assert(DL.getTypeAllocSize(SliceTy).getFixedSize() >= P.size())(static_cast <bool> (DL.getTypeAllocSize(SliceTy).getFixedSize
() >= P.size()) ? void (0) : __assert_fail ("DL.getTypeAllocSize(SliceTy).getFixedSize() >= P.size()"
, "llvm/lib/Transforms/Scalar/SROA.cpp", 4295, __extension__ __PRETTY_FUNCTION__
))
;
4296
4297 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
4298
4299 VectorType *VecTy =
4300 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
4301 if (VecTy)
4302 SliceTy = VecTy;
4303
4304 // Check for the case where we're going to rewrite to a new alloca of the
4305 // exact same type as the original, and with the same access offsets. In that
4306 // case, re-use the existing alloca, but still run through the rewriter to
4307 // perform phi and select speculation.
4308 // P.beginOffset() can be non-zero even with the same type in a case with
4309 // out-of-bounds access (e.g. @PR35657 function in SROA/basictest.ll).
4310 AllocaInst *NewAI;
4311 if (SliceTy == AI.getAllocatedType() && P.beginOffset() == 0) {
4312 NewAI = &AI;
4313 // FIXME: We should be able to bail at this point with "nothing changed".
4314 // FIXME: We might want to defer PHI speculation until after here.
4315 // FIXME: return nullptr;
4316 } else {
4317 // Make sure the alignment is compatible with P.beginOffset().
4318 const Align Alignment = commonAlignment(AI.getAlign(), P.beginOffset());
4319 // If we will get at least this much alignment from the type alone, leave
4320 // the alloca's alignment unconstrained.
4321 const bool IsUnconstrained = Alignment <= DL.getABITypeAlign(SliceTy);
4322 NewAI = new AllocaInst(
4323 SliceTy, AI.getAddressSpace(), nullptr,
4324 IsUnconstrained ? DL.getPrefTypeAlign(SliceTy) : Alignment,
4325 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
4326 // Copy the old AI debug location over to the new one.
4327 NewAI->setDebugLoc(AI.getDebugLoc());
4328 ++NumNewAllocas;
4329 }
4330
4331 LLVM_DEBUG(dbgs() << "Rewriting alloca partition "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "Rewriting alloca partition " <<
"[" << P.beginOffset() << "," << P.endOffset
() << ") to: " << *NewAI << "\n"; } } while
(false)
4332 << "[" << P.beginOffset() << "," << P.endOffset()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "Rewriting alloca partition " <<
"[" << P.beginOffset() << "," << P.endOffset
() << ") to: " << *NewAI << "\n"; } } while
(false)
4333 << ") to: " << *NewAI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "Rewriting alloca partition " <<
"[" << P.beginOffset() << "," << P.endOffset
() << ") to: " << *NewAI << "\n"; } } while
(false)
;
4334
4335 // Track the high watermark on the worklist as it is only relevant for
4336 // promoted allocas. We will reset it to this point if the alloca is not in
4337 // fact scheduled for promotion.
4338 unsigned PPWOldSize = PostPromotionWorklist.size();
4339 unsigned NumUses = 0;
4340 SmallSetVector<PHINode *, 8> PHIUsers;
4341 SmallSetVector<SelectInst *, 8> SelectUsers;
4342
4343 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
4344 P.endOffset(), IsIntegerPromotable, VecTy,
4345 PHIUsers, SelectUsers);
4346 bool Promotable = true;
4347 for (Slice *S : P.splitSliceTails()) {
4348 Promotable &= Rewriter.visit(S);
4349 ++NumUses;
4350 }
4351 for (Slice &S : P) {
4352 Promotable &= Rewriter.visit(&S);
4353 ++NumUses;
4354 }
4355
4356 NumAllocaPartitionUses += NumUses;
4357 MaxUsesPerAllocaPartition.updateMax(NumUses);
4358
4359 // Now that we've processed all the slices in the new partition, check if any
4360 // PHIs or Selects would block promotion.
4361 for (PHINode *PHI : PHIUsers)
4362 if (!isSafePHIToSpeculate(*PHI)) {
4363 Promotable = false;
4364 PHIUsers.clear();
4365 SelectUsers.clear();
4366 break;
4367 }
4368
4369 for (SelectInst *Sel : SelectUsers)
4370 if (!isSafeSelectToSpeculate(*Sel)) {
4371 Promotable = false;
4372 PHIUsers.clear();
4373 SelectUsers.clear();
4374 break;
4375 }
4376
4377 if (Promotable) {
4378 for (Use *U : AS.getDeadUsesIfPromotable()) {
4379 auto *OldInst = dyn_cast<Instruction>(U->get());
4380 Value::dropDroppableUse(*U);
4381 if (OldInst)
4382 if (isInstructionTriviallyDead(OldInst))
4383 DeadInsts.push_back(OldInst);
4384 }
4385 if (PHIUsers.empty() && SelectUsers.empty()) {
4386 // Promote the alloca.
4387 PromotableAllocas.push_back(NewAI);
4388 } else {
4389 // If we have either PHIs or Selects to speculate, add them to those
4390 // worklists and re-queue the new alloca so that we promote in on the
4391 // next iteration.
4392 for (PHINode *PHIUser : PHIUsers)
4393 SpeculatablePHIs.insert(PHIUser);
4394 for (SelectInst *SelectUser : SelectUsers)
4395 SpeculatableSelects.insert(SelectUser);
4396 Worklist.insert(NewAI);
4397 }
4398 } else {
4399 // Drop any post-promotion work items if promotion didn't happen.
4400 while (PostPromotionWorklist.size() > PPWOldSize)
4401 PostPromotionWorklist.pop_back();
4402
4403 // We couldn't promote and we didn't create a new partition, nothing
4404 // happened.
4405 if (NewAI == &AI)
4406 return nullptr;
4407
4408 // If we can't promote the alloca, iterate on it to check for new
4409 // refinements exposed by splitting the current alloca. Don't iterate on an
4410 // alloca which didn't actually change and didn't get promoted.
4411 Worklist.insert(NewAI);
4412 }
4413
4414 return NewAI;
4415}
4416
4417/// Walks the slices of an alloca and form partitions based on them,
4418/// rewriting each of their uses.
4419bool SROAPass::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
4420 if (AS.begin() == AS.end())
4421 return false;
4422
4423 unsigned NumPartitions = 0;
4424 bool Changed = false;
4425 const DataLayout &DL = AI.getModule()->getDataLayout();
4426
4427 // First try to pre-split loads and stores.
4428 Changed |= presplitLoadsAndStores(AI, AS);
4429
4430 // Now that we have identified any pre-splitting opportunities,
4431 // mark loads and stores unsplittable except for the following case.
4432 // We leave a slice splittable if all other slices are disjoint or fully
4433 // included in the slice, such as whole-alloca loads and stores.
4434 // If we fail to split these during pre-splitting, we want to force them
4435 // to be rewritten into a partition.
4436 bool IsSorted = true;
4437
4438 uint64_t AllocaSize =
4439 DL.getTypeAllocSize(AI.getAllocatedType()).getFixedSize();
4440 const uint64_t MaxBitVectorSize = 1024;
4441 if (AllocaSize <= MaxBitVectorSize) {
4442 // If a byte boundary is included in any load or store, a slice starting or
4443 // ending at the boundary is not splittable.
4444 SmallBitVector SplittableOffset(AllocaSize + 1, true);
4445 for (Slice &S : AS)
4446 for (unsigned O = S.beginOffset() + 1;
4447 O < S.endOffset() && O < AllocaSize; O++)
4448 SplittableOffset.reset(O);
4449
4450 for (Slice &S : AS) {
4451 if (!S.isSplittable())
4452 continue;
4453
4454 if ((S.beginOffset() > AllocaSize || SplittableOffset[S.beginOffset()]) &&
4455 (S.endOffset() > AllocaSize || SplittableOffset[S.endOffset()]))
4456 continue;
4457
4458 if (isa<LoadInst>(S.getUse()->getUser()) ||
4459 isa<StoreInst>(S.getUse()->getUser())) {
4460 S.makeUnsplittable();
4461 IsSorted = false;
4462 }
4463 }
4464 }
4465 else {
4466 // We only allow whole-alloca splittable loads and stores
4467 // for a large alloca to avoid creating too large BitVector.
4468 for (Slice &S : AS) {
4469 if (!S.isSplittable())
4470 continue;
4471
4472 if (S.beginOffset() == 0 && S.endOffset() >= AllocaSize)
4473 continue;
4474
4475 if (isa<LoadInst>(S.getUse()->getUser()) ||
4476 isa<StoreInst>(S.getUse()->getUser())) {
4477 S.makeUnsplittable();
4478 IsSorted = false;
4479 }
4480 }
4481 }
4482
4483 if (!IsSorted)
4484 llvm::sort(AS);
4485
4486 /// Describes the allocas introduced by rewritePartition in order to migrate
4487 /// the debug info.
4488 struct Fragment {
4489 AllocaInst *Alloca;
4490 uint64_t Offset;
4491 uint64_t Size;
4492 Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
4493 : Alloca(AI), Offset(O), Size(S) {}
4494 };
4495 SmallVector<Fragment, 4> Fragments;
4496
4497 // Rewrite each partition.
4498 for (auto &P : AS.partitions()) {
4499 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4500 Changed = true;
4501 if (NewAI != &AI) {
4502 uint64_t SizeOfByte = 8;
4503 uint64_t AllocaSize =
4504 DL.getTypeSizeInBits(NewAI->getAllocatedType()).getFixedSize();
4505 // Don't include any padding.
4506 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
4507 Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
4508 }
4509 }
4510 ++NumPartitions;
4511 }
4512
4513 NumAllocaPartitions += NumPartitions;
4514 MaxPartitionsPerAlloca.updateMax(NumPartitions);
4515
4516 // Migrate debug information from the old alloca to the new alloca(s)
4517 // and the individual partitions.
4518 TinyPtrVector<DbgVariableIntrinsic *> DbgDeclares = FindDbgAddrUses(&AI);
4519 for (DbgVariableIntrinsic *DbgDeclare : DbgDeclares) {
4520 auto *Expr = DbgDeclare->getExpression();
4521 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
4522 uint64_t AllocaSize =
4523 DL.getTypeSizeInBits(AI.getAllocatedType()).getFixedSize();
4524 for (auto Fragment : Fragments) {
4525 // Create a fragment expression describing the new partition or reuse AI's
4526 // expression if there is only one partition.
4527 auto *FragmentExpr = Expr;
4528 if (Fragment.Size < AllocaSize || Expr->isFragment()) {
4529 // If this alloca is already a scalar replacement of a larger aggregate,
4530 // Fragment.Offset describes the offset inside the scalar.
4531 auto ExprFragment = Expr->getFragmentInfo();
4532 uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0;
4533 uint64_t Start = Offset + Fragment.Offset;
4534 uint64_t Size = Fragment.Size;
4535 if (ExprFragment) {
4536 uint64_t AbsEnd =
4537 ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
4538 if (Start >= AbsEnd)
4539 // No need to describe a SROAed padding.
4540 continue;
4541 Size = std::min(Size, AbsEnd - Start);
4542 }
4543 // The new, smaller fragment is stenciled out from the old fragment.
4544 if (auto OrigFragment = FragmentExpr->getFragmentInfo()) {
4545 assert(Start >= OrigFragment->OffsetInBits &&(static_cast <bool> (Start >= OrigFragment->OffsetInBits
&& "new fragment is outside of original fragment") ?
void (0) : __assert_fail ("Start >= OrigFragment->OffsetInBits && \"new fragment is outside of original fragment\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 4546, __extension__ __PRETTY_FUNCTION__
))
4546 "new fragment is outside of original fragment")(static_cast <bool> (Start >= OrigFragment->OffsetInBits
&& "new fragment is outside of original fragment") ?
void (0) : __assert_fail ("Start >= OrigFragment->OffsetInBits && \"new fragment is outside of original fragment\""
, "llvm/lib/Transforms/Scalar/SROA.cpp", 4546, __extension__ __PRETTY_FUNCTION__
))
;
4547 Start -= OrigFragment->OffsetInBits;
4548 }
4549
4550 // The alloca may be larger than the variable.
4551 auto VarSize = DbgDeclare->getVariable()->getSizeInBits();
4552 if (VarSize) {
4553 if (Size > *VarSize)
4554 Size = *VarSize;
4555 if (Size == 0 || Start + Size > *VarSize)
4556 continue;
4557 }
4558
4559 // Avoid creating a fragment expression that covers the entire variable.
4560 if (!VarSize || *VarSize != Size) {
4561 if (auto E =
4562 DIExpression::createFragmentExpression(Expr, Start, Size))
4563 FragmentExpr = *E;
4564 else
4565 continue;
4566 }
4567 }
4568
4569 // Remove any existing intrinsics on the new alloca describing
4570 // the variable fragment.
4571 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(Fragment.Alloca)) {
4572 auto SameVariableFragment = [](const DbgVariableIntrinsic *LHS,
4573 const DbgVariableIntrinsic *RHS) {
4574 return LHS->getVariable() == RHS->getVariable() &&
4575 LHS->getDebugLoc()->getInlinedAt() ==
4576 RHS->getDebugLoc()->getInlinedAt();
4577 };
4578 if (SameVariableFragment(OldDII, DbgDeclare))
4579 OldDII->eraseFromParent();
4580 }
4581
4582 DIB.insertDeclare(Fragment.Alloca, DbgDeclare->getVariable(), FragmentExpr,
4583 DbgDeclare->getDebugLoc(), &AI);
4584 }
4585 }
4586 return Changed;
4587}
4588
4589/// Clobber a use with poison, deleting the used value if it becomes dead.
4590void SROAPass::clobberUse(Use &U) {
4591 Value *OldV = U;
4592 // Replace the use with an poison value.
4593 U = PoisonValue::get(OldV->getType());
4594
4595 // Check for this making an instruction dead. We have to garbage collect
4596 // all the dead instructions to ensure the uses of any alloca end up being
4597 // minimal.
4598 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4599 if (isInstructionTriviallyDead(OldI)) {
4600 DeadInsts.push_back(OldI);
4601 }
4602}
4603
4604/// Analyze an alloca for SROA.
4605///
4606/// This analyzes the alloca to ensure we can reason about it, builds
4607/// the slices of the alloca, and then hands it off to be split and
4608/// rewritten as needed.
4609bool SROAPass::runOnAlloca(AllocaInst &AI) {
4610 LLVM_DEBUG(dbgs() << "SROA alloca: " << AI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "SROA alloca: " << AI <<
"\n"; } } while (false)
;
4611 ++NumAllocasAnalyzed;
4612
4613 // Special case dead allocas, as they're trivial.
4614 if (AI.use_empty()) {
4615 AI.eraseFromParent();
4616 return true;
4617 }
4618 const DataLayout &DL = AI.getModule()->getDataLayout();
4619
4620 // Skip alloca forms that this analysis can't handle.
4621 auto *AT = AI.getAllocatedType();
4622 if (AI.isArrayAllocation() || !AT->isSized() || isa<ScalableVectorType>(AT) ||
4623 DL.getTypeAllocSize(AT).getFixedSize() == 0)
4624 return false;
4625
4626 bool Changed = false;
4627
4628 // First, split any FCA loads and stores touching this alloca to promote
4629 // better splitting and promotion opportunities.
4630 IRBuilderTy IRB(&AI);
4631 AggLoadStoreRewriter AggRewriter(DL, IRB);
4632 Changed |= AggRewriter.rewrite(AI);
4633
4634 // Build the slices using a recursive instruction-visiting builder.
4635 AllocaSlices AS(DL, AI);
4636 LLVM_DEBUG(AS.print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { AS.print(dbgs()); } } while (false)
;
4637 if (AS.isEscaped())
4638 return Changed;
4639
4640 // Delete all the dead users of this alloca before splitting and rewriting it.
4641 for (Instruction *DeadUser : AS.getDeadUsers()) {
4642 // Free up everything used by this instruction.
4643 for (Use &DeadOp : DeadUser->operands())
4644 clobberUse(DeadOp);
4645
4646 // Now replace the uses of this instruction.
4647 DeadUser->replaceAllUsesWith(PoisonValue::get(DeadUser->getType()));
4648
4649 // And mark it for deletion.
4650 DeadInsts.push_back(DeadUser);
4651 Changed = true;
4652 }
4653 for (Use *DeadOp : AS.getDeadOperands()) {
4654 clobberUse(*DeadOp);
4655 Changed = true;
4656 }
4657
4658 // No slices to split. Leave the dead alloca for a later pass to clean up.
4659 if (AS.begin() == AS.end())
4660 return Changed;
4661
4662 Changed |= splitAlloca(AI, AS);
4663
4664 LLVM_DEBUG(dbgs() << " Speculating PHIs\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Speculating PHIs\n"; } } while
(false)
;
4665 while (!SpeculatablePHIs.empty())
4666 speculatePHINodeLoads(IRB, *SpeculatablePHIs.pop_back_val());
4667
4668 LLVM_DEBUG(dbgs() << " Speculating Selects\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Speculating Selects\n"; } } while
(false)
;
4669 while (!SpeculatableSelects.empty())
4670 speculateSelectInstLoads(IRB, *SpeculatableSelects.pop_back_val());
4671
4672 return Changed;
4673}
4674
4675/// Delete the dead instructions accumulated in this run.
4676///
4677/// Recursively deletes the dead instructions we've accumulated. This is done
4678/// at the very end to maximize locality of the recursive delete and to
4679/// minimize the problems of invalidated instruction pointers as such pointers
4680/// are used heavily in the intermediate stages of the algorithm.
4681///
4682/// We also record the alloca instructions deleted here so that they aren't
4683/// subsequently handed to mem2reg to promote.
4684bool SROAPass::deleteDeadInstructions(
4685 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
4686 bool Changed = false;
4687 while (!DeadInsts.empty()) {
4688 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
4689 if (!I) continue;
4690 LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "Deleting dead instruction: " <<
*I << "\n"; } } while (false)
;
4691
4692 // If the instruction is an alloca, find the possible dbg.declare connected
4693 // to it, and remove it too. We must do this before calling RAUW or we will
4694 // not be able to find it.
4695 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4696 DeletedAllocas.insert(AI);
4697 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(AI))
4698 OldDII->eraseFromParent();
4699 }
4700
4701 I->replaceAllUsesWith(UndefValue::get(I->getType()));
4702
4703 for (Use &Operand : I->operands())
4704 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
4705 // Zero out the operand and see if it becomes trivially dead.
4706 Operand = nullptr;
4707 if (isInstructionTriviallyDead(U))
4708 DeadInsts.push_back(U);
4709 }
4710
4711 ++NumDeleted;
4712 I->eraseFromParent();
4713 Changed = true;
4714 }
4715 return Changed;
4716}
4717
4718/// Promote the allocas, using the best available technique.
4719///
4720/// This attempts to promote whatever allocas have been identified as viable in
4721/// the PromotableAllocas list. If that list is empty, there is nothing to do.
4722/// This function returns whether any promotion occurred.
4723bool SROAPass::promoteAllocas(Function &F) {
4724 if (PromotableAllocas.empty())
4725 return false;
4726
4727 NumPromoted += PromotableAllocas.size();
4728
4729 LLVM_DEBUG(dbgs() << "Promoting allocas with mem2reg...\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "Promoting allocas with mem2reg...\n"
; } } while (false)
;
4730 PromoteMemToReg(PromotableAllocas, *DT, AC);
4731 PromotableAllocas.clear();
4732 return true;
4733}
4734
4735PreservedAnalyses SROAPass::runImpl(Function &F, DominatorTree &RunDT,
4736 AssumptionCache &RunAC) {
4737 LLVM_DEBUG(dbgs() << "SROA function: " << F.getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "SROA function: " << F.getName
() << "\n"; } } while (false)
;
4738 C = &F.getContext();
4739 DT = &RunDT;
4740 AC = &RunAC;
4741
4742 BasicBlock &EntryBB = F.getEntryBlock();
4743 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
4744 I != E; ++I) {
4745 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4746 if (isa<ScalableVectorType>(AI->getAllocatedType())) {
4747 if (isAllocaPromotable(AI))
4748 PromotableAllocas.push_back(AI);
4749 } else {
4750 Worklist.insert(AI);
4751 }
4752 }
4753 }
4754
4755 bool Changed = false;
4756 // A set of deleted alloca instruction pointers which should be removed from
4757 // the list of promotable allocas.
4758 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4759
4760 do {
4761 while (!Worklist.empty()) {
4762 Changed |= runOnAlloca(*Worklist.pop_back_val());
4763 Changed |= deleteDeadInstructions(DeletedAllocas);
4764
4765 // Remove the deleted allocas from various lists so that we don't try to
4766 // continue processing them.
4767 if (!DeletedAllocas.empty()) {
4768 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
4769 Worklist.remove_if(IsInSet);
4770 PostPromotionWorklist.remove_if(IsInSet);
4771 llvm::erase_if(PromotableAllocas, IsInSet);
4772 DeletedAllocas.clear();
4773 }
4774 }
4775
4776 Changed |= promoteAllocas(F);
4777
4778 Worklist = PostPromotionWorklist;
4779 PostPromotionWorklist.clear();
4780 } while (!Worklist.empty());
4781
4782 if (!Changed)
4783 return PreservedAnalyses::all();
4784
4785 PreservedAnalyses PA;
4786 PA.preserveSet<CFGAnalyses>();
4787 return PA;
4788}
4789
4790PreservedAnalyses SROAPass::run(Function &F, FunctionAnalysisManager &AM) {
4791 return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F),
4792 AM.getResult<AssumptionAnalysis>(F));
4793}
4794
4795/// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
4796///
4797/// This is in the llvm namespace purely to allow it to be a friend of the \c
4798/// SROA pass.
4799class llvm::sroa::SROALegacyPass : public FunctionPass {
4800 /// The SROA implementation.
4801 SROAPass Impl;
4802
4803public:
4804 static char ID;
4805
4806 SROALegacyPass() : FunctionPass(ID) {
4807 initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
4808 }
4809
4810 bool runOnFunction(Function &F) override {
4811 if (skipFunction(F))
4812 return false;
4813
4814 auto PA = Impl.runImpl(
4815 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4816 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
4817 return !PA.areAllPreserved();
4818 }
4819
4820 void getAnalysisUsage(AnalysisUsage &AU) const override {
4821 AU.addRequired<AssumptionCacheTracker>();
4822 AU.addRequired<DominatorTreeWrapperPass>();
4823 AU.addPreserved<GlobalsAAWrapperPass>();
4824 AU.setPreservesCFG();
4825 }
4826
4827 StringRef getPassName() const override { return "SROA"; }
4828};
4829
4830char SROALegacyPass::ID = 0;
4831
4832FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); }
4833
4834INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",static void *initializeSROALegacyPassPassOnce(PassRegistry &
Registry) {
4835 "Scalar Replacement Of Aggregates", false, false)static void *initializeSROALegacyPassPassOnce(PassRegistry &
Registry) {
4836INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry);
4837INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)initializeDominatorTreeWrapperPassPass(Registry);
4838INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",PassInfo *PI = new PassInfo( "Scalar Replacement Of Aggregates"
, "sroa", &SROALegacyPass::ID, PassInfo::NormalCtor_t(callDefaultCtor
<SROALegacyPass>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeSROALegacyPassPassFlag
; void llvm::initializeSROALegacyPassPass(PassRegistry &Registry
) { llvm::call_once(InitializeSROALegacyPassPassFlag, initializeSROALegacyPassPassOnce
, std::ref(Registry)); }
4839 false, false)PassInfo *PI = new PassInfo( "Scalar Replacement Of Aggregates"
, "sroa", &SROALegacyPass::ID, PassInfo::NormalCtor_t(callDefaultCtor
<SROALegacyPass>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeSROALegacyPassPassFlag
; void llvm::initializeSROALegacyPassPass(PassRegistry &Registry
) { llvm::call_once(InitializeSROALegacyPassPassFlag, initializeSROALegacyPassPassOnce
, std::ref(Registry)); }