LLVM 24.0.0git
SROA.cpp
Go to the documentation of this file.
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
26#include "ScalarOptions.h"
27#include "llvm/ADT/APInt.h"
28#include "llvm/ADT/ArrayRef.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/MapVector.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/SetVector.h"
37#include "llvm/ADT/Statistic.h"
38#include "llvm/ADT/StringRef.h"
39#include "llvm/ADT/Twine.h"
40#include "llvm/ADT/iterator.h"
45#include "llvm/Analysis/Loads.h"
49#include "llvm/IR/BasicBlock.h"
50#include "llvm/IR/Constant.h"
52#include "llvm/IR/Constants.h"
53#include "llvm/IR/DIBuilder.h"
54#include "llvm/IR/DataLayout.h"
55#include "llvm/IR/DebugInfo.h"
58#include "llvm/IR/Dominators.h"
59#include "llvm/IR/Function.h"
60#include "llvm/IR/GlobalAlias.h"
61#include "llvm/IR/IRBuilder.h"
62#include "llvm/IR/InstVisitor.h"
63#include "llvm/IR/Instruction.h"
66#include "llvm/IR/LLVMContext.h"
67#include "llvm/IR/Metadata.h"
68#include "llvm/IR/Module.h"
69#include "llvm/IR/Operator.h"
70#include "llvm/IR/PassManager.h"
71#include "llvm/IR/Type.h"
72#include "llvm/IR/Use.h"
73#include "llvm/IR/User.h"
74#include "llvm/IR/Value.h"
75#include "llvm/IR/ValueHandle.h"
77#include "llvm/Pass.h"
80#include "llvm/Support/Debug.h"
88#include <algorithm>
89#include <cassert>
90#include <cstddef>
91#include <cstdint>
92#include <cstring>
93#include <iterator>
94#include <string>
95#include <tuple>
96#include <utility>
97#include <variant>
98#include <vector>
99
100using namespace llvm;
101
102#define DEBUG_TYPE "sroa"
103
104STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
105STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
106STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
107STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
108STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
109STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
110STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
111STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
112STATISTIC(NumLoadsPredicated,
113 "Number of loads rewritten into predicated loads to allow promotion");
115 NumStoresPredicated,
116 "Number of stores rewritten into predicated stores to allow promotion");
117STATISTIC(NumDeleted, "Number of instructions deleted");
118STATISTIC(NumVectorized, "Number of vectorized aggregates");
119
120namespace {
121
122class AllocaSliceRewriter;
123class AllocaSlices;
124class Partition;
125class Slice;
126
127class SelectHandSpeculativity {
128 unsigned char Storage = 0; // None are speculatable by default.
129 using TrueVal = Bitfield::Element<bool, 0, 1>; // Low 0'th bit.
130 using FalseVal = Bitfield::Element<bool, 1, 1>; // Low 1'th bit.
131public:
132 SelectHandSpeculativity() = default;
133 SelectHandSpeculativity &setAsSpeculatable(bool isTrueVal);
134 bool isSpeculatable(bool isTrueVal) const;
135 bool areAllSpeculatable() const;
136 bool areAnySpeculatable() const;
137 bool areNoneSpeculatable() const;
138 // For interop as int half of PointerIntPair.
139 explicit operator intptr_t() const { return static_cast<intptr_t>(Storage); }
140 explicit SelectHandSpeculativity(intptr_t Storage_) : Storage(Storage_) {}
141};
142static_assert(sizeof(SelectHandSpeculativity) == sizeof(unsigned char));
143
144using PossiblySpeculatableLoad =
146using UnspeculatableStore = StoreInst *;
147using RewriteableMemOp =
148 std::variant<PossiblySpeculatableLoad, UnspeculatableStore>;
149using RewriteableMemOps = SmallVector<RewriteableMemOp, 2>;
150using InstructionSliceMap =
152
153/// An optimization pass providing Scalar Replacement of Aggregates.
154///
155/// This pass takes allocations which can be completely analyzed (that is, they
156/// don't escape) and tries to turn them into scalar SSA values. There are
157/// a few steps to this process.
158///
159/// 1) It takes allocations of aggregates and analyzes the ways in which they
160/// are used to try to split them into smaller allocations, ideally of
161/// a single scalar data type. It will split up memcpy and memset accesses
162/// as necessary and try to isolate individual scalar accesses.
163/// 2) It will transform accesses into forms which are suitable for SSA value
164/// promotion. This can be replacing a memset with a scalar store of an
165/// integer value, or it can involve speculating operations on a PHI or
166/// select to be a PHI or select of the results.
167/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
168/// onto insert and extract operations on a vector value, and convert them to
169/// this form. By doing so, it will enable promotion of vector aggregates to
170/// SSA vector values.
171class SROA {
172 LLVMContext *const C;
173 DomTreeUpdater *const DTU;
174 AssumptionCache *const AC;
175 const bool PreserveCFG;
176 const bool AggregateToVector;
177
178 /// Worklist of alloca instructions to simplify.
179 ///
180 /// Each alloca in the function is added to this. Each new alloca formed gets
181 /// added to it as well to recursively simplify unless that alloca can be
182 /// directly promoted. Finally, each time we rewrite a use of an alloca other
183 /// the one being actively rewritten, we add it back onto the list if not
184 /// already present to ensure it is re-visited.
185 SmallSetVector<AllocaInst *, 16> Worklist;
186
187 /// A collection of instructions to delete.
188 /// We try to batch deletions to simplify code and make things a bit more
189 /// efficient. We also make sure there is no dangling pointers.
190 SmallVector<WeakVH, 8> DeadInsts;
191
192 /// Post-promotion worklist.
193 ///
194 /// Sometimes we discover an alloca which has a high probability of becoming
195 /// viable for SROA after a round of promotion takes place. In those cases,
196 /// the alloca is enqueued here for re-processing.
197 ///
198 /// Note that we have to be very careful to clear allocas out of this list in
199 /// the event they are deleted.
200 SmallSetVector<AllocaInst *, 16> PostPromotionWorklist;
201
202 /// A collection of alloca instructions we can directly promote.
203 SetVector<AllocaInst *, SmallVector<AllocaInst *>,
204 SmallPtrSet<AllocaInst *, 16>, 16>
205 PromotableAllocas;
206
207 /// A worklist of PHIs to speculate prior to promoting allocas.
208 ///
209 /// All of these PHIs have been checked for the safety of speculation and by
210 /// being speculated will allow promoting allocas currently in the promotable
211 /// queue.
212 SmallSetVector<PHINode *, 8> SpeculatablePHIs;
213
214 /// A worklist of PHIs whose stores should be predicated onto incoming edges.
215 ///
216 /// All of these PHIs have been checked so that rewriting their stores will
217 /// allow the corresponding allocas to be promoted. Edges which require
218 /// splitting are only present when CFG modification is allowed.
219 SmallSetVector<PHINode *, 8> PHIsWithStoreToRewrite;
220
221 /// A worklist of select instructions to rewrite prior to promoting
222 /// allocas.
223 SmallMapVector<SelectInst *, RewriteableMemOps, 8> SelectsToRewrite;
224
225 /// Check whether the loads and stores of the select can be speculatively
226 /// executed or predicated (if \p PreserveCFG is false).
227 ///
228 /// Speculation converts a load like
229 ///
230 /// %P = select i1 %cond, ptr %Alloca, ptr %Other
231 /// %V = load <type>, ptr %P
232 ///
233 /// to:
234 ///
235 /// %V1 = load <type>, ptr %Alloca -> will be mem2reg'd
236 /// %V2 = load <type>, ptr %Other
237 /// %V = select i1 %cond, <type> %V1, <type> %V2
238 ///
239 /// For stores and some kinds of loads that can't be speculated, we need to
240 /// predicate. Predication changes the CFG, so it requires \p PreserveCFG to
241 /// be false. Predication converts a store like:
242 ///
243 /// block:
244 /// %P = select i1 %cond, ptr %Alloca, ptr %Other
245 /// store <type> %Value, ptr %P
246 ///
247 /// to:
248 ///
249 /// block:
250 /// br i1 %cond, label %block.then, label %block.else
251 ///
252 /// block.then:
253 /// store <type> %Value, ptr %Alloca
254 /// br label %block.cont
255 ///
256 /// block.else:
257 /// store <type> %Value, ptr %Other
258 /// br label %block.cont
259 ///
260 /// Returns `std::nullopt` when
261 /// - the select has users other than loads or stores, or
262 /// - at least one of the loads and stores is volatile, or
263 /// - the loads and stores can't be speculated and can't be predicated because
264 /// we're not allowed to modify the CFG. (\p PreserveCFG is true)
265 ///
266 /// Otherwise the stores and loads in the returned vector can either be
267 /// speculated or predicated.
268 static std::optional<RewriteableMemOps>
269 isSafeSelectToSpeculateOrPredicate(SelectInst &SI, bool PreserveCFG);
270
271public:
272 SROA(LLVMContext *C, DomTreeUpdater *DTU, AssumptionCache *AC,
273 SROAOptions Options)
274 : C(C), DTU(DTU), AC(AC),
275 PreserveCFG(Options.CFG == SROAOptions::PreserveCFG),
276 AggregateToVector(Options.AggregateToVector) {}
277
278 /// Main run method used by both the SROAPass and by the legacy pass.
279 std::pair<bool /*Changed*/, bool /*CFGChanged*/> runSROA(Function &F);
280
281private:
282 friend class AllocaSliceRewriter;
283
284 bool presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS);
285 std::pair<AllocaInst *, uint64_t>
286 rewritePartition(AllocaInst &AI, AllocaSlices &AS, Partition &P);
287 bool splitAlloca(AllocaInst &AI, AllocaSlices &AS);
288 bool propagateStoredValuesToLoads(AllocaInst &AI, AllocaSlices &AS);
289 std::pair<bool /*Changed*/, bool /*CFGChanged*/> runOnAlloca(AllocaInst &AI);
290 void clobberUse(Use &U);
291 bool deleteDeadInstructions(AllocaInst *AI,
292 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
293 bool promoteAllocas();
294};
295
296} // end anonymous namespace
297
298/// Calculate the fragment of a variable to use when slicing a store
299/// based on the slice dimensions, existing fragment, and base storage
300/// fragment.
301/// Results:
302/// UseFrag - Use Target as the new fragment.
303/// UseNoFrag - The new slice already covers the whole variable.
304/// Skip - The new alloca slice doesn't include this variable.
305/// FIXME: Can we use calculateFragmentIntersect instead?
306namespace {
307enum FragCalcResult { UseFrag, UseNoFrag, Skip };
308}
309static FragCalcResult
311 uint64_t NewStorageSliceOffsetInBits,
312 uint64_t NewStorageSliceSizeInBits,
313 std::optional<DIExpression::FragmentInfo> StorageFragment,
314 std::optional<DIExpression::FragmentInfo> CurrentFragment,
316 // If the base storage describes part of the variable apply the offset and
317 // the size constraint.
318 if (StorageFragment) {
319 Target.SizeInBits =
320 std::min(NewStorageSliceSizeInBits, StorageFragment->SizeInBits);
321 Target.OffsetInBits =
322 NewStorageSliceOffsetInBits + StorageFragment->OffsetInBits;
323 } else {
324 Target.SizeInBits = NewStorageSliceSizeInBits;
325 Target.OffsetInBits = NewStorageSliceOffsetInBits;
326 }
327
328 // If this slice extracts the entirety of an independent variable from a
329 // larger alloca, do not produce a fragment expression, as the variable is
330 // not fragmented.
331 if (!CurrentFragment) {
332 if (auto Size = Variable->getSizeInBits()) {
333 // Treat the current fragment as covering the whole variable.
334 CurrentFragment = DIExpression::FragmentInfo(*Size, 0);
335 if (Target == CurrentFragment)
336 return UseNoFrag;
337 }
338 }
339
340 // No additional work to do if there isn't a fragment already, or there is
341 // but it already exactly describes the new assignment.
342 if (!CurrentFragment || *CurrentFragment == Target)
343 return UseFrag;
344
345 // Reject the target fragment if it doesn't fit wholly within the current
346 // fragment. TODO: We could instead chop up the target to fit in the case of
347 // a partial overlap.
348 if (Target.startInBits() < CurrentFragment->startInBits() ||
349 Target.endInBits() > CurrentFragment->endInBits())
350 return Skip;
351
352 // Target fits within the current fragment, return it.
353 return UseFrag;
354}
355
357 return DebugVariable(DVR->getVariable(), std::nullopt,
358 DVR->getDebugLoc().getInlinedAt());
359}
360
361/// Find linked dbg.assign and generate a new one with the correct
362/// FragmentInfo. Link Inst to the new dbg.assign. If Value is nullptr the
363/// value component is copied from the old dbg.assign to the new.
364/// \param OldAlloca Alloca for the variable before splitting.
365/// \param IsSplit True if the store (not necessarily alloca)
366/// is being split.
367/// \param OldAllocaOffsetInBits Offset of the slice taken from OldAlloca.
368/// \param SliceSizeInBits New number of bits being written to.
369/// \param OldInst Instruction that is being split.
370/// \param Inst New instruction performing this part of the
371/// split store.
372/// \param Dest Store destination.
373/// \param Value Stored value.
374/// \param DL Datalayout.
375static void migrateDebugInfo(AllocaInst *OldAlloca, bool IsSplit,
376 uint64_t OldAllocaOffsetInBits,
377 uint64_t SliceSizeInBits, Instruction *OldInst,
378 Instruction *Inst, Value *Dest, Value *Value,
379 const DataLayout &DL) {
380 // If we want allocas to be migrated using this helper then we need to ensure
381 // that the BaseFragments map code still works. A simple solution would be
382 // to choose to always clone alloca dbg_assigns (rather than sometimes
383 // "stealing" them).
384 assert(!isa<AllocaInst>(Inst) && "Unexpected alloca");
385
386 auto DVRAssignMarkerRange = at::getDVRAssignmentMarkers(OldInst);
387 // Nothing to do if OldInst has no linked dbg.assign intrinsics.
388 if (DVRAssignMarkerRange.empty())
389 return;
390
391 LLVM_DEBUG(dbgs() << " migrateDebugInfo\n");
392 LLVM_DEBUG(dbgs() << " OldAlloca: " << *OldAlloca << "\n");
393 LLVM_DEBUG(dbgs() << " IsSplit: " << IsSplit << "\n");
394 LLVM_DEBUG(dbgs() << " OldAllocaOffsetInBits: " << OldAllocaOffsetInBits
395 << "\n");
396 LLVM_DEBUG(dbgs() << " SliceSizeInBits: " << SliceSizeInBits << "\n");
397 LLVM_DEBUG(dbgs() << " OldInst: " << *OldInst << "\n");
398 LLVM_DEBUG(dbgs() << " Inst: " << *Inst << "\n");
399 LLVM_DEBUG(dbgs() << " Dest: " << *Dest << "\n");
400 if (Value)
401 LLVM_DEBUG(dbgs() << " Value: " << *Value << "\n");
402
403 /// Map of aggregate variables to their fragment associated with OldAlloca.
405 BaseFragments;
406 for (auto *DVR : at::getDVRAssignmentMarkers(OldAlloca))
407 BaseFragments[getAggregateVariable(DVR)] =
408 DVR->getExpression()->getFragmentInfo();
409
410 // The new inst needs a DIAssignID unique metadata tag (if OldInst has
411 // one). It shouldn't already have one: assert this assumption.
412 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID));
413 DIAssignID *NewID = nullptr;
414 auto &Ctx = Inst->getContext();
415 DIBuilder DIB(*OldInst->getModule(), /*AllowUnresolved*/ false);
416 assert(OldAlloca->isStaticAlloca());
417
418 auto MigrateDbgAssign = [&](DbgVariableRecord *DbgAssign) {
419 LLVM_DEBUG(dbgs() << " existing dbg.assign is: " << *DbgAssign
420 << "\n");
421 auto *Expr = DbgAssign->getExpression();
422 bool SetKillLocation = false;
423
424 if (IsSplit) {
425 std::optional<DIExpression::FragmentInfo> BaseFragment;
426 {
427 auto R = BaseFragments.find(getAggregateVariable(DbgAssign));
428 if (R == BaseFragments.end())
429 return;
430 BaseFragment = R->second;
431 }
432 std::optional<DIExpression::FragmentInfo> CurrentFragment =
433 Expr->getFragmentInfo();
434 DIExpression::FragmentInfo NewFragment;
435 FragCalcResult Result = calculateFragment(
436 DbgAssign->getVariable(), OldAllocaOffsetInBits, SliceSizeInBits,
437 BaseFragment, CurrentFragment, NewFragment);
438
439 if (Result == Skip)
440 return;
441 if (Result == UseFrag && !(NewFragment == CurrentFragment)) {
442 if (CurrentFragment) {
443 // Rewrite NewFragment to be relative to the existing one (this is
444 // what createFragmentExpression wants). CalculateFragment has
445 // already resolved the size for us. FIXME: Should it return the
446 // relative fragment too?
447 NewFragment.OffsetInBits -= CurrentFragment->OffsetInBits;
448 }
449 // Add the new fragment info to the existing expression if possible.
451 Expr, NewFragment.OffsetInBits, NewFragment.SizeInBits)) {
452 Expr = *E;
453 } else {
454 // Otherwise, add the new fragment info to an empty expression and
455 // discard the value component of this dbg.assign as the value cannot
456 // be computed with the new fragment.
458 DIExpression::get(Expr->getContext(), {}),
459 NewFragment.OffsetInBits, NewFragment.SizeInBits);
460 SetKillLocation = true;
461 }
462 }
463 }
464
465 // If we haven't created a DIAssignID ID do that now and attach it to Inst.
466 if (!NewID) {
467 NewID = DIAssignID::getDistinct(Ctx);
468 Inst->setMetadata(LLVMContext::MD_DIAssignID, NewID);
469 }
470
471 DbgVariableRecord *NewAssign;
472 if (IsSplit) {
473 ::Value *NewValue = Value ? Value : DbgAssign->getValue();
475 Inst, NewValue, DbgAssign->getVariable(), Expr, Dest,
476 DIExpression::get(Expr->getContext(), {}), DbgAssign->getDebugLoc()));
477 } else {
478 // The store is not split, simply steal the existing dbg_assign.
479 NewAssign = DbgAssign;
480 NewAssign->setAssignId(NewID); // FIXME: Can we avoid generating new IDs?
481 NewAssign->setAddress(Dest);
482 if (Value)
483 NewAssign->replaceVariableLocationOp(0u, Value);
484 assert(Expr == NewAssign->getExpression());
485 }
486
487 // If we've updated the value but the original dbg.assign has an arglist
488 // then kill it now - we can't use the requested new value.
489 // We can't replace the DIArgList with the new value as it'd leave
490 // the DIExpression in an invalid state (DW_OP_LLVM_arg operands without
491 // an arglist). And we can't keep the DIArgList in case the linked store
492 // is being split - in which case the DIArgList + expression may no longer
493 // be computing the correct value.
494 // This should be a very rare situation as it requires the value being
495 // stored to differ from the dbg.assign (i.e., the value has been
496 // represented differently in the debug intrinsic for some reason).
497 SetKillLocation |=
498 Value && (DbgAssign->hasArgList() ||
499 !DbgAssign->getExpression()->isSingleLocationExpression());
500 if (SetKillLocation)
501 NewAssign->setKillLocation();
502
503 // We could use more precision here at the cost of some additional (code)
504 // complexity - if the original dbg.assign was adjacent to its store, we
505 // could position this new dbg.assign adjacent to its store rather than the
506 // old dbg.assgn. That would result in interleaved dbg.assigns rather than
507 // what we get now:
508 // split store !1
509 // split store !2
510 // dbg.assign !1
511 // dbg.assign !2
512 // This (current behaviour) results results in debug assignments being
513 // noted as slightly offset (in code) from the store. In practice this
514 // should have little effect on the debugging experience due to the fact
515 // that all the split stores should get the same line number.
516 if (NewAssign != DbgAssign) {
517 NewAssign->moveBefore(DbgAssign->getIterator());
518 NewAssign->setDebugLoc(DbgAssign->getDebugLoc());
519 }
520 LLVM_DEBUG(dbgs() << "Created new assign: " << *NewAssign << "\n");
521 };
522
523 for_each(DVRAssignMarkerRange, MigrateDbgAssign);
524}
525
526namespace {
527
528/// A custom IRBuilder inserter which prefixes all names, but only in
529/// Assert builds.
530class IRBuilderPrefixedInserter final : public IRBuilderDefaultInserter {
531 std::string Prefix;
532
533 Twine getNameWithPrefix(const Twine &Name) const {
534 return Name.isTriviallyEmpty() ? Name : Prefix + Name;
535 }
536
537public:
538 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
539
540 void InsertHelper(Instruction *I, const Twine &Name,
542 IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name),
543 InsertPt);
544 }
545};
546
547/// Provide a type for IRBuilder that drops names in release builds.
549
550/// A used slice of an alloca.
551///
552/// This structure represents a slice of an alloca used by some instruction. It
553/// stores both the begin and end offsets of this use, a pointer to the use
554/// itself, and a flag indicating whether we can classify the use as splittable
555/// or not when forming partitions of the alloca.
556class Slice {
557 /// The beginning offset of the range.
558 uint64_t BeginOffset = 0;
559
560 /// The ending offset, not included in the range.
561 uint64_t EndOffset = 0;
562
563 /// Storage for both the use of this slice and whether it can be
564 /// split.
565 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
566
567public:
568 Slice() = default;
569
570 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
571 : BeginOffset(BeginOffset), EndOffset(EndOffset),
572 UseAndIsSplittable(U, IsSplittable) {}
573
574 uint64_t beginOffset() const { return BeginOffset; }
575 uint64_t endOffset() const { return EndOffset; }
576
577 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
578 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
579
580 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
581
582 bool isDead() const { return getUse() == nullptr; }
583 void kill() { UseAndIsSplittable.setPointer(nullptr); }
584
585 /// Support for ordering ranges.
586 ///
587 /// This provides an ordering over ranges such that start offsets are
588 /// always increasing, and within equal start offsets, the end offsets are
589 /// decreasing. Thus the spanning range comes first in a cluster with the
590 /// same start position.
591 bool operator<(const Slice &RHS) const {
592 if (beginOffset() < RHS.beginOffset())
593 return true;
594 if (beginOffset() > RHS.beginOffset())
595 return false;
596 if (isSplittable() != RHS.isSplittable())
597 return !isSplittable();
598 if (endOffset() > RHS.endOffset())
599 return true;
600 return false;
601 }
602
603 /// Support comparison with a single offset to allow binary searches.
604 [[maybe_unused]] friend bool operator<(const Slice &LHS, uint64_t RHSOffset) {
605 return LHS.beginOffset() < RHSOffset;
606 }
607 [[maybe_unused]] friend bool operator<(uint64_t LHSOffset, const Slice &RHS) {
608 return LHSOffset < RHS.beginOffset();
609 }
610
611 bool operator==(const Slice &RHS) const {
612 return isSplittable() == RHS.isSplittable() &&
613 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
614 }
615 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
616};
617
618/// Representation of the alloca slices.
619///
620/// This class represents the slices of an alloca which are formed by its
621/// various uses. If a pointer escapes, we can't fully build a representation
622/// for the slices used and we reflect that in this structure. The uses are
623/// stored, sorted by increasing beginning offset and with unsplittable slices
624/// starting at a particular offset before splittable slices.
625class AllocaSlices {
626public:
627 /// Construct the slices of a particular alloca.
628 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
629
630 /// Test whether a pointer to the allocation escapes our analysis.
631 ///
632 /// If this is true, the slices are never fully built and should be
633 /// ignored.
634 bool isEscaped() const { return PointerEscapingInstr; }
635 bool isEscapedReadOnly() const { return PointerEscapingInstrReadOnly; }
636
637 /// Support for iterating over the slices.
638 /// @{
639 using iterator = SmallVectorImpl<Slice>::iterator;
640 using range = iterator_range<iterator>;
641
642 iterator begin() { return Slices.begin(); }
643 iterator end() { return Slices.end(); }
644
645 using const_iterator = SmallVectorImpl<Slice>::const_iterator;
646
647 const_iterator begin() const { return Slices.begin(); }
648 const_iterator end() const { return Slices.end(); }
649 /// @}
650
651 /// Erase a range of slices.
652 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
653
654 /// Insert new slices for this alloca.
655 ///
656 /// This moves the slices into the alloca's slices collection, and re-sorts
657 /// everything so that the usual ordering properties of the alloca's slices
658 /// hold.
659 void insert(ArrayRef<Slice> NewSlices) {
660 int OldSize = Slices.size();
661 Slices.append(NewSlices.begin(), NewSlices.end());
662 auto SliceI = Slices.begin() + OldSize;
663 std::stable_sort(SliceI, Slices.end());
664 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
665 }
666
667 // Forward declare the iterator and range accessor for walking the
668 // partitions.
669 class partition_iterator;
671
672 /// Access the dead users for this alloca.
673 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
674
675 /// Access Uses that should be dropped if the alloca is promotable.
676 ArrayRef<Use *> getDeadUsesIfPromotable() const {
677 return DeadUseIfPromotable;
678 }
679
680 /// Access the dead operands referring to this alloca.
681 ///
682 /// These are operands which have cannot actually be used to refer to the
683 /// alloca as they are outside its range and the user doesn't correct for
684 /// that. These mostly consist of PHI node inputs and the like which we just
685 /// need to replace with undef.
686 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
687
688#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
689 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
690 void printSlice(raw_ostream &OS, const_iterator I,
691 StringRef Indent = " ") const;
692 void printUse(raw_ostream &OS, const_iterator I,
693 StringRef Indent = " ") const;
694 void print(raw_ostream &OS) const;
695 void dump(const_iterator I) const;
696 void dump() const;
697#endif
698
699private:
700 class SliceBuilder;
701
702 friend class AllocaSlices::SliceBuilder;
703
704#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
705 /// Handle to alloca instruction to simplify method interfaces.
706 AllocaInst &AI;
707#endif
708
709 /// The instruction responsible for this alloca not having a known set
710 /// of slices.
711 ///
712 /// When an instruction (potentially) escapes the pointer to the alloca, we
713 /// store a pointer to that here and abort trying to form slices of the
714 /// alloca. This will be null if the alloca slices are analyzed successfully.
715 Instruction *PointerEscapingInstr;
716 Instruction *PointerEscapingInstrReadOnly;
717
718 /// The slices of the alloca.
719 ///
720 /// We store a vector of the slices formed by uses of the alloca here. This
721 /// vector is sorted by increasing begin offset, and then the unsplittable
722 /// slices before the splittable ones. See the Slice inner class for more
723 /// details.
725
726 /// Instructions which will become dead if we rewrite the alloca.
727 ///
728 /// Note that these are not separated by slice. This is because we expect an
729 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
730 /// all these instructions can simply be removed and replaced with poison as
731 /// they come from outside of the allocated space.
732 SmallVector<Instruction *, 8> DeadUsers;
733
734 /// Uses which will become dead if can promote the alloca.
735 SmallVector<Use *, 8> DeadUseIfPromotable;
736
737 /// Operands which will become dead if we rewrite the alloca.
738 ///
739 /// These are operands that in their particular use can be replaced with
740 /// poison when we rewrite the alloca. These show up in out-of-bounds inputs
741 /// to PHI nodes and the like. They aren't entirely dead (there might be
742 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
743 /// want to swap this particular input for poison to simplify the use lists of
744 /// the alloca.
745 SmallVector<Use *, 8> DeadOperands;
746};
747
748/// A partition of the slices.
749///
750/// An ephemeral representation for a range of slices which can be viewed as
751/// a partition of the alloca. This range represents a span of the alloca's
752/// memory which cannot be split, and provides access to all of the slices
753/// overlapping some part of the partition.
754///
755/// Objects of this type are produced by traversing the alloca's slices, but
756/// are only ephemeral and not persistent.
757class Partition {
758private:
759 friend class AllocaSlices;
760 friend class AllocaSlices::partition_iterator;
761
762 using iterator = AllocaSlices::iterator;
763
764 /// The beginning and ending offsets of the alloca for this
765 /// partition.
766 uint64_t BeginOffset = 0, EndOffset = 0;
767
768 /// The start and end iterators of this partition.
769 iterator SI, SJ;
770
771 /// A collection of split slice tails overlapping the partition.
772 SmallVector<Slice *, 4> SplitTails;
773
774 /// Raw constructor builds an empty partition starting and ending at
775 /// the given iterator.
776 Partition(iterator SI) : SI(SI), SJ(SI) {}
777
778public:
779 /// The start offset of this partition.
780 ///
781 /// All of the contained slices start at or after this offset.
782 uint64_t beginOffset() const { return BeginOffset; }
783
784 /// The end offset of this partition.
785 ///
786 /// All of the contained slices end at or before this offset.
787 uint64_t endOffset() const { return EndOffset; }
788
789 /// The size of the partition.
790 ///
791 /// Note that this can never be zero.
792 uint64_t size() const {
793 assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
794 return EndOffset - BeginOffset;
795 }
796
797 /// Test whether this partition contains no slices, and merely spans
798 /// a region occupied by split slices.
799 bool empty() const { return SI == SJ; }
800
801 /// \name Iterate slices that start within the partition.
802 /// These may be splittable or unsplittable. They have a begin offset >= the
803 /// partition begin offset.
804 /// @{
805 // FIXME: We should probably define a "concat_iterator" helper and use that
806 // to stitch together pointee_iterators over the split tails and the
807 // contiguous iterators of the partition. That would give a much nicer
808 // interface here. We could then additionally expose filtered iterators for
809 // split, unsplit, and unsplittable splices based on the usage patterns.
810 iterator begin() const { return SI; }
811 iterator end() const { return SJ; }
812 /// @}
813
814 /// Get the sequence of split slice tails.
815 ///
816 /// These tails are of slices which start before this partition but are
817 /// split and overlap into the partition. We accumulate these while forming
818 /// partitions.
819 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
820};
821
822} // end anonymous namespace
823
824/// An iterator over partitions of the alloca's slices.
825///
826/// This iterator implements the core algorithm for partitioning the alloca's
827/// slices. It is a forward iterator as we don't support backtracking for
828/// efficiency reasons, and re-use a single storage area to maintain the
829/// current set of split slices.
830///
831/// It is templated on the slice iterator type to use so that it can operate
832/// with either const or non-const slice iterators.
834 : public iterator_facade_base<partition_iterator, std::forward_iterator_tag,
835 Partition> {
836 friend class AllocaSlices;
837
838 /// Most of the state for walking the partitions is held in a class
839 /// with a nice interface for examining them.
840 Partition P;
841
842 /// We need to keep the end of the slices to know when to stop.
843 AllocaSlices::iterator SE;
844
845 /// We also need to keep track of the maximum split end offset seen.
846 /// FIXME: Do we really?
847 uint64_t MaxSplitSliceEndOffset = 0;
848
849 /// Sets the partition to be empty at given iterator, and sets the
850 /// end iterator.
851 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
852 : P(SI), SE(SE) {
853 // If not already at the end, advance our state to form the initial
854 // partition.
855 if (SI != SE)
856 advance();
857 }
858
859 /// Advance the iterator to the next partition.
860 ///
861 /// Requires that the iterator not be at the end of the slices.
862 void advance() {
863 assert((P.SI != SE || !P.SplitTails.empty()) &&
864 "Cannot advance past the end of the slices!");
865
866 // Clear out any split uses which have ended.
867 if (!P.SplitTails.empty()) {
868 if (P.EndOffset >= MaxSplitSliceEndOffset) {
869 // If we've finished all splits, this is easy.
870 P.SplitTails.clear();
871 MaxSplitSliceEndOffset = 0;
872 } else {
873 // Remove the uses which have ended in the prior partition. This
874 // cannot change the max split slice end because we just checked that
875 // the prior partition ended prior to that max.
876 llvm::erase_if(P.SplitTails,
877 [&](Slice *S) { return S->endOffset() <= P.EndOffset; });
878 assert(llvm::any_of(P.SplitTails,
879 [&](Slice *S) {
880 return S->endOffset() == MaxSplitSliceEndOffset;
881 }) &&
882 "Could not find the current max split slice offset!");
883 assert(llvm::all_of(P.SplitTails,
884 [&](Slice *S) {
885 return S->endOffset() <= MaxSplitSliceEndOffset;
886 }) &&
887 "Max split slice end offset is not actually the max!");
888 }
889 }
890
891 // If P.SI is already at the end, then we've cleared the split tail and
892 // now have an end iterator.
893 if (P.SI == SE) {
894 assert(P.SplitTails.empty() && "Failed to clear the split slices!");
895 return;
896 }
897
898 // If we had a non-empty partition previously, set up the state for
899 // subsequent partitions.
900 if (P.SI != P.SJ) {
901 // Accumulate all the splittable slices which started in the old
902 // partition into the split list.
903 for (Slice &S : P)
904 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
905 P.SplitTails.push_back(&S);
906 MaxSplitSliceEndOffset =
907 std::max(S.endOffset(), MaxSplitSliceEndOffset);
908 }
909
910 // Start from the end of the previous partition.
911 P.SI = P.SJ;
912
913 // If P.SI is now at the end, we at most have a tail of split slices.
914 if (P.SI == SE) {
915 P.BeginOffset = P.EndOffset;
916 P.EndOffset = MaxSplitSliceEndOffset;
917 return;
918 }
919
920 // If the we have split slices and the next slice is after a gap and is
921 // not splittable immediately form an empty partition for the split
922 // slices up until the next slice begins.
923 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
924 !P.SI->isSplittable()) {
925 P.BeginOffset = P.EndOffset;
926 P.EndOffset = P.SI->beginOffset();
927 return;
928 }
929 }
930
931 // OK, we need to consume new slices. Set the end offset based on the
932 // current slice, and step SJ past it. The beginning offset of the
933 // partition is the beginning offset of the next slice unless we have
934 // pre-existing split slices that are continuing, in which case we begin
935 // at the prior end offset.
936 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
937 P.EndOffset = P.SI->endOffset();
938 ++P.SJ;
939
940 // There are two strategies to form a partition based on whether the
941 // partition starts with an unsplittable slice or a splittable slice.
942 if (!P.SI->isSplittable()) {
943 // When we're forming an unsplittable region, it must always start at
944 // the first slice and will extend through its end.
945 assert(P.BeginOffset == P.SI->beginOffset());
946
947 // Form a partition including all of the overlapping slices with this
948 // unsplittable slice.
949 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
950 if (!P.SJ->isSplittable())
951 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
952 ++P.SJ;
953 }
954
955 // We have a partition across a set of overlapping unsplittable
956 // partitions.
957 return;
958 }
959
960 // If we're starting with a splittable slice, then we need to form
961 // a synthetic partition spanning it and any other overlapping splittable
962 // splices.
963 assert(P.SI->isSplittable() && "Forming a splittable partition!");
964
965 // Collect all of the overlapping splittable slices.
966 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
967 P.SJ->isSplittable()) {
968 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
969 ++P.SJ;
970 }
971
972 // Back upiP.EndOffset if we ended the span early when encountering an
973 // unsplittable slice. This synthesizes the early end offset of
974 // a partition spanning only splittable slices.
975 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
976 assert(!P.SJ->isSplittable());
977 P.EndOffset = P.SJ->beginOffset();
978 }
979 }
980
981public:
982 bool operator==(const partition_iterator &RHS) const {
983 assert(SE == RHS.SE &&
984 "End iterators don't match between compared partition iterators!");
985
986 // The observed positions of partitions is marked by the P.SI iterator and
987 // the emptiness of the split slices. The latter is only relevant when
988 // P.SI == SE, as the end iterator will additionally have an empty split
989 // slices list, but the prior may have the same P.SI and a tail of split
990 // slices.
991 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
992 assert(P.SJ == RHS.P.SJ &&
993 "Same set of slices formed two different sized partitions!");
994 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
995 "Same slice position with differently sized non-empty split "
996 "slice tails!");
997 return true;
998 }
999 return false;
1000 }
1001
1002 partition_iterator &operator++() {
1003 advance();
1004 return *this;
1005 }
1006
1007 Partition &operator*() { return P; }
1008};
1009
1010/// A forward range over the partitions of the alloca's slices.
1011///
1012/// This accesses an iterator range over the partitions of the alloca's
1013/// slices. It computes these partitions on the fly based on the overlapping
1014/// offsets of the slices and the ability to split them. It will visit "empty"
1015/// partitions to cover regions of the alloca only accessed via split
1016/// slices.
1017iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() {
1018 return make_range(partition_iterator(begin(), end()),
1019 partition_iterator(end(), end()));
1020}
1021
1023 // If the condition being selected on is a constant or the same value is
1024 // being selected between, fold the select. Yes this does (rarely) happen
1025 // early on.
1026 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
1027 return SI.getOperand(1 + CI->isZero());
1028 if (SI.getOperand(1) == SI.getOperand(2))
1029 return SI.getOperand(1);
1030
1031 return nullptr;
1032}
1033
1034/// A helper that folds a PHI node or a select.
1036 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
1037 // If PN merges together the same value, return that value.
1038 return PN->hasConstantValue();
1039 }
1041}
1042
1043/// Builder for the alloca slices.
1044///
1045/// This class builds a set of alloca slices by recursively visiting the uses
1046/// of an alloca and making a slice for each load and store at each offset.
1047class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
1048 friend class PtrUseVisitor<SliceBuilder>;
1049 friend class InstVisitor<SliceBuilder>;
1050
1051 using Base = PtrUseVisitor<SliceBuilder>;
1052
1053 const uint64_t AllocSize;
1054 AllocaSlices &AS;
1055
1056 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
1058
1059 /// Set to de-duplicate dead instructions found in the use walk.
1060 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
1061
1062public:
1063 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
1065 AllocSize(AI.getAllocationSize(DL)->getFixedValue()), AS(AS) {}
1066
1067private:
1068 void markAsDead(Instruction &I) {
1069 if (VisitedDeadInsts.insert(&I).second)
1070 AS.DeadUsers.push_back(&I);
1071 }
1072
1073 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
1074 bool IsSplittable = false) {
1075 // Completely skip uses which have a zero size or start either before or
1076 // past the end of the allocation.
1077 if (Size == 0 || Offset.uge(AllocSize)) {
1078 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @"
1079 << Offset
1080 << " which has zero size or starts outside of the "
1081 << AllocSize << " byte alloca:\n"
1082 << " alloca: " << AS.AI << "\n"
1083 << " use: " << I << "\n");
1084 return markAsDead(I);
1085 }
1086
1087 uint64_t BeginOffset = Offset.getZExtValue();
1088 uint64_t EndOffset = BeginOffset + Size;
1089
1090 // Clamp the end offset to the end of the allocation. Note that this is
1091 // formulated to handle even the case where "BeginOffset + Size" overflows.
1092 // This may appear superficially to be something we could ignore entirely,
1093 // but that is not so! There may be widened loads or PHI-node uses where
1094 // some instructions are dead but not others. We can't completely ignore
1095 // them, and so have to record at least the information here.
1096 assert(AllocSize >= BeginOffset); // Established above.
1097 if (Size > AllocSize - BeginOffset) {
1098 LLVM_DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @"
1099 << Offset << " to remain within the " << AllocSize
1100 << " byte alloca:\n"
1101 << " alloca: " << AS.AI << "\n"
1102 << " use: " << I << "\n");
1103 EndOffset = AllocSize;
1104 }
1105
1106 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
1107 }
1108
1109 void visitBitCastInst(BitCastInst &BC) {
1110 if (BC.use_empty())
1111 return markAsDead(BC);
1112
1113 return Base::visitBitCastInst(BC);
1114 }
1115
1116 void visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
1117 if (ASC.use_empty())
1118 return markAsDead(ASC);
1119
1120 return Base::visitAddrSpaceCastInst(ASC);
1121 }
1122
1123 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1124 if (GEPI.use_empty())
1125 return markAsDead(GEPI);
1126
1127 return Base::visitGetElementPtrInst(GEPI);
1128 }
1129
1130 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
1131 uint64_t Size, bool IsVolatile) {
1132 // We allow splitting of non-volatile loads and stores where the type is an
1133 // integer type. These may be used to implement 'memcpy' or other "transfer
1134 // of bits" patterns.
1135 bool IsSplittable =
1136 Ty->isIntegerTy() && !IsVolatile && DL.typeSizeEqualsStoreSize(Ty);
1137
1138 insertUse(I, Offset, Size, IsSplittable);
1139 }
1140
1141 void visitLoadInst(LoadInst &LI) {
1142 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
1143 "All simple FCA loads should have been pre-split");
1144
1145 // If there is a load with an unknown offset, we can still perform store
1146 // to load forwarding for other known-offset loads.
1147 if (!IsOffsetKnown)
1148 return PI.setEscapedReadOnly(&LI);
1149
1150 TypeSize Size = DL.getTypeStoreSize(LI.getType());
1151 if (Size.isScalable()) {
1152 unsigned VScale = LI.getFunction()->getVScaleValue();
1153 if (!VScale)
1154 return PI.setAborted(&LI);
1155
1156 Size = TypeSize::getFixed(Size.getKnownMinValue() * VScale);
1157 }
1158
1159 return handleLoadOrStore(LI.getType(), LI, Offset, Size.getFixedValue(),
1160 LI.isVolatile());
1161 }
1162
1163 void visitStoreInst(StoreInst &SI) {
1164 Value *ValOp = SI.getValueOperand();
1165 if (ValOp == *U)
1166 return PI.setEscapedAndAborted(&SI);
1167 if (!IsOffsetKnown)
1168 return PI.setAborted(&SI);
1169
1170 TypeSize StoreSize = DL.getTypeStoreSize(ValOp->getType());
1171 if (StoreSize.isScalable()) {
1172 unsigned VScale = SI.getFunction()->getVScaleValue();
1173 if (!VScale)
1174 return PI.setAborted(&SI);
1175
1176 StoreSize = TypeSize::getFixed(StoreSize.getKnownMinValue() * VScale);
1177 }
1178
1179 uint64_t Size = StoreSize.getFixedValue();
1180
1181 // If this memory access can be shown to *statically* extend outside the
1182 // bounds of the allocation, it's behavior is undefined, so simply
1183 // ignore it. Note that this is more strict than the generic clamping
1184 // behavior of insertUse. We also try to handle cases which might run the
1185 // risk of overflow.
1186 // FIXME: We should instead consider the pointer to have escaped if this
1187 // function is being instrumented for addressing bugs or race conditions.
1188 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
1189 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @"
1190 << Offset << " which extends past the end of the "
1191 << AllocSize << " byte alloca:\n"
1192 << " alloca: " << AS.AI << "\n"
1193 << " use: " << SI << "\n");
1194 return markAsDead(SI);
1195 }
1196
1197 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
1198 "All simple FCA stores should have been pre-split");
1199 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
1200 }
1201
1202 void visitMemSetInst(MemSetInst &II) {
1203 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
1204 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
1205 if ((Length && Length->getValue() == 0) ||
1206 (IsOffsetKnown && Offset.uge(AllocSize)))
1207 // Zero-length mem transfer intrinsics can be ignored entirely.
1208 return markAsDead(II);
1209
1210 if (!IsOffsetKnown)
1211 return PI.setAborted(&II);
1212
1213 insertUse(II, Offset,
1214 Length ? Length->getLimitedValue()
1215 : AllocSize - Offset.getLimitedValue(),
1216 (bool)Length);
1217 }
1218
1219 void visitMemTransferInst(MemTransferInst &II) {
1220 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
1221 if (Length && Length->getValue() == 0)
1222 // Zero-length mem transfer intrinsics can be ignored entirely.
1223 return markAsDead(II);
1224
1225 // Because we can visit these intrinsics twice, also check to see if the
1226 // first time marked this instruction as dead. If so, skip it.
1227 if (VisitedDeadInsts.count(&II))
1228 return;
1229
1230 if (!IsOffsetKnown)
1231 return PI.setAborted(&II);
1232
1233 // This side of the transfer is completely out-of-bounds, and so we can
1234 // nuke the entire transfer. However, we also need to nuke the other side
1235 // if already added to our partitions.
1236 // FIXME: Yet another place we really should bypass this when
1237 // instrumenting for ASan.
1238 if (Offset.uge(AllocSize)) {
1239 auto MTPI = MemTransferSliceMap.find(&II);
1240 if (MTPI != MemTransferSliceMap.end())
1241 AS.Slices[MTPI->second].kill();
1242 return markAsDead(II);
1243 }
1244
1245 uint64_t RawOffset = Offset.getLimitedValue();
1246 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
1247
1248 // Check for the special case where the same exact value is used for both
1249 // source and dest.
1250 if (*U == II.getRawDest() && *U == II.getRawSource()) {
1251 // For non-volatile transfers this is a no-op.
1252 if (!II.isVolatile())
1253 return markAsDead(II);
1254
1255 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
1256 }
1257
1258 // If we have seen both source and destination for a mem transfer, then
1259 // they both point to the same alloca.
1260 bool Inserted;
1261 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
1262 std::tie(MTPI, Inserted) =
1263 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
1264 unsigned PrevIdx = MTPI->second;
1265 if (!Inserted) {
1266 Slice &PrevP = AS.Slices[PrevIdx];
1267
1268 // Check if the begin offsets match and this is a non-volatile transfer.
1269 // In that case, we can completely elide the transfer.
1270 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
1271 PrevP.kill();
1272 return markAsDead(II);
1273 }
1274
1275 // Otherwise we have an offset transfer within the same alloca. We can't
1276 // split those.
1277 PrevP.makeUnsplittable();
1278 }
1279
1280 // Insert the use now that we've fixed up the splittable nature.
1281 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
1282
1283 // Check that we ended up with a valid index in the map.
1284 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
1285 "Map index doesn't point back to a slice with this user.");
1286 }
1287
1288 // Disable SRoA for any intrinsics except for lifetime invariants.
1289 // FIXME: What about debug intrinsics? This matches old behavior, but
1290 // doesn't make sense.
1291 void visitIntrinsicInst(IntrinsicInst &II) {
1292 if (II.isDroppable()) {
1293 AS.DeadUseIfPromotable.push_back(U);
1294 return;
1295 }
1296
1297 if (!IsOffsetKnown)
1298 return PI.setAborted(&II);
1299
1300 if (II.isLifetimeStartOrEnd()) {
1301 insertUse(II, Offset, AllocSize, true);
1302 return;
1303 }
1304
1305 Base::visitIntrinsicInst(II);
1306 }
1307
1308 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
1309 // We consider any PHI or select that results in a direct load or store of
1310 // the same offset to be a viable use for slicing purposes. These uses
1311 // are considered unsplittable and the size is the maximum loaded or stored
1312 // size.
1313 SmallPtrSet<Instruction *, 4> Visited;
1315 Visited.insert(Root);
1316 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
1317 const DataLayout &DL = Root->getDataLayout();
1318 // If there are no loads or stores, the access is dead. We mark that as
1319 // a size zero access.
1320 Size = 0;
1321 do {
1322 Instruction *I, *UsedI;
1323 std::tie(UsedI, I) = Uses.pop_back_val();
1324
1325 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1326 TypeSize LoadSize = DL.getTypeStoreSize(LI->getType());
1327 if (LoadSize.isScalable()) {
1328 PI.setAborted(LI);
1329 return nullptr;
1330 }
1331 Size = std::max(Size, LoadSize.getFixedValue());
1332 continue;
1333 }
1334 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1335 Value *Op = SI->getOperand(0);
1336 if (Op == UsedI)
1337 return SI;
1338 TypeSize StoreSize = DL.getTypeStoreSize(Op->getType());
1339 if (StoreSize.isScalable()) {
1340 PI.setAborted(SI);
1341 return nullptr;
1342 }
1343 Size = std::max(Size, StoreSize.getFixedValue());
1344 continue;
1345 }
1346
1347 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
1348 if (!GEP->hasAllZeroIndices())
1349 return GEP;
1350 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
1352 return I;
1353 }
1354
1355 for (User *U : I->users())
1356 if (Visited.insert(cast<Instruction>(U)).second)
1357 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
1358 } while (!Uses.empty());
1359
1360 return nullptr;
1361 }
1362
1363 void visitPHINodeOrSelectInst(Instruction &I) {
1365 if (I.use_empty())
1366 return markAsDead(I);
1367
1368 // If this is a PHI node before a catchswitch, we cannot insert any non-PHI
1369 // instructions in this BB, which may be required during rewriting. Bail out
1370 // on these cases.
1371 if (isa<PHINode>(I) && !I.getParent()->hasInsertionPt())
1372 return PI.setAborted(&I);
1373
1374 // TODO: We could use simplifyInstruction here to fold PHINodes and
1375 // SelectInsts. However, doing so requires to change the current
1376 // dead-operand-tracking mechanism. For instance, suppose neither loading
1377 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
1378 // trap either. However, if we simply replace %U with undef using the
1379 // current dead-operand-tracking mechanism, "load (select undef, undef,
1380 // %other)" may trap because the select may return the first operand
1381 // "undef".
1382 if (Value *Result = foldPHINodeOrSelectInst(I)) {
1383 if (Result == *U)
1384 // If the result of the constant fold will be the pointer, recurse
1385 // through the PHI/select as if we had RAUW'ed it.
1386 enqueueUsers(I);
1387 else
1388 // Otherwise the operand to the PHI/select is dead, and we can replace
1389 // it with poison.
1390 AS.DeadOperands.push_back(U);
1391
1392 return;
1393 }
1394
1395 if (!IsOffsetKnown)
1396 return PI.setAborted(&I);
1397
1398 // See if we already have computed info on this node.
1399 uint64_t &Size = PHIOrSelectSizes[&I];
1400 if (!Size) {
1401 // This is a new PHI/Select, check for an unsafe use of it.
1402 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
1403 return PI.setAborted(UnsafeI);
1404 }
1405
1406 // For PHI and select operands outside the alloca, we can't nuke the entire
1407 // phi or select -- the other side might still be relevant, so we special
1408 // case them here and use a separate structure to track the operands
1409 // themselves which should be replaced with poison.
1410 // FIXME: This should instead be escaped in the event we're instrumenting
1411 // for address sanitization.
1412 if (Offset.uge(AllocSize)) {
1413 AS.DeadOperands.push_back(U);
1414 return;
1415 }
1416
1417 insertUse(I, Offset, Size);
1418 }
1419
1420 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
1421
1422 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
1423
1424 /// Disable SROA entirely if there are unhandled users of the alloca.
1425 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
1426
1427 void visitCallBase(CallBase &CB) {
1428 // If the call operand is read-only and only does a read-only or address
1429 // capture, then we mark it as EscapedReadOnly.
1430 if (CB.isDataOperand(U) &&
1431 !capturesFullProvenance(CB.getCaptureInfo(U->getOperandNo())) &&
1432 CB.onlyReadsMemory(U->getOperandNo())) {
1433 PI.setEscapedReadOnly(&CB);
1434 return;
1435 }
1436
1437 Base::visitCallBase(CB);
1438 }
1439};
1440
1441AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
1442 :
1443#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1444 AI(AI),
1445#endif
1446 PointerEscapingInstr(nullptr), PointerEscapingInstrReadOnly(nullptr) {
1447 SliceBuilder PB(DL, AI, *this);
1448 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
1449 if (PtrI.isEscaped() || PtrI.isAborted()) {
1450 // FIXME: We should sink the escape vs. abort info into the caller nicely,
1451 // possibly by just storing the PtrInfo in the AllocaSlices.
1452 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1453 : PtrI.getAbortingInst();
1454 assert(PointerEscapingInstr && "Did not track a bad instruction");
1455 return;
1456 }
1457 PointerEscapingInstrReadOnly = PtrI.getEscapedReadOnlyInst();
1458
1459 llvm::erase_if(Slices, [](const Slice &S) { return S.isDead(); });
1460
1461 // Sort the uses. This arranges for the offsets to be in ascending order,
1462 // and the sizes to be in descending order.
1463 llvm::stable_sort(Slices);
1464}
1465
1466#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1467
1468void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1469 StringRef Indent) const {
1470 printSlice(OS, I, Indent);
1471 OS << "\n";
1472 printUse(OS, I, Indent);
1473}
1474
1475void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1476 StringRef Indent) const {
1477 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
1478 << " slice #" << (I - begin())
1479 << (I->isSplittable() ? " (splittable)" : "");
1480}
1481
1482void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1483 StringRef Indent) const {
1484 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
1485}
1486
1487void AllocaSlices::print(raw_ostream &OS) const {
1488 if (PointerEscapingInstr) {
1489 OS << "Can't analyze slices for alloca: " << AI << "\n"
1490 << " A pointer to this alloca escaped by:\n"
1491 << " " << *PointerEscapingInstr << "\n";
1492 return;
1493 }
1494
1495 if (PointerEscapingInstrReadOnly)
1496 OS << "Escapes into ReadOnly: " << *PointerEscapingInstrReadOnly << "\n";
1497
1498 OS << "Slices of alloca: " << AI << "\n";
1499 for (const_iterator I = begin(), E = end(); I != E; ++I)
1500 print(OS, I);
1501}
1502
1503LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1504 print(dbgs(), I);
1505}
1506LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
1507
1508#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1509
1510/// Find a common load/store type used through a pointer PHI or select.
1511///
1512/// Look through a PHI or select to see if all of its users are loads or stores
1513/// of one common type. Whether those accesses can be speculated does not affect
1514/// the type they use and is checked separately when attempting promotion.
1516 assert((isa<PHINode, SelectInst>(I)) && "expected a PHI or select");
1517 Type *Ty = nullptr;
1518
1519 for (User *U : I.users()) {
1520 Type *UserTy = nullptr;
1521 if (auto *LI = dyn_cast<LoadInst>(U))
1522 UserTy = LI->getType();
1523 else if (auto *Store = dyn_cast<StoreInst>(U))
1524 // Slice building rejects stores of the PHI-or-select-derived pointer, so
1525 // it must be the store's pointer operand here.
1526 UserTy = Store->getValueOperand()->getType();
1527
1528 if (!UserTy || (Ty && Ty != UserTy))
1529 return nullptr;
1530 Ty = UserTy;
1531 }
1532
1533 return Ty;
1534}
1535
1536/// Walk the range of a partitioning looking for a common type to cover this
1537/// sequence of slices.
1538static std::pair<Type *, IntegerType *>
1539findCommonType(AllocaSlices::const_iterator B, AllocaSlices::const_iterator E,
1540 uint64_t EndOffset) {
1541 Type *Ty = nullptr;
1542 bool TyIsCommon = true;
1543 IntegerType *ITy = nullptr;
1544
1545 // Note that we need to look at *every* alloca slice's Use to ensure we
1546 // always get consistent results regardless of the order of slices.
1547 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
1548 Use *U = I->getUse();
1549 if (isa<IntrinsicInst>(*U->getUser()))
1550 continue;
1551 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1552 continue;
1553
1554 Type *UserTy = nullptr;
1555 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1556 UserTy = LI->getType();
1557 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1558 UserTy = SI->getValueOperand()->getType();
1559 } else if (isa<PHINode, SelectInst>(U->getUser())) {
1560 UserTy =
1562 }
1563
1564 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
1565 // If the type is larger than the partition, skip it. We only encounter
1566 // this for split integer operations where we want to use the type of the
1567 // entity causing the split. Also skip if the type is not a byte width
1568 // multiple.
1569 if (UserITy->getBitWidth() % 8 != 0 ||
1570 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
1571 continue;
1572
1573 // Track the largest bitwidth integer type used in this way in case there
1574 // is no common type.
1575 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1576 ITy = UserITy;
1577 }
1578
1579 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1580 // depend on types skipped above.
1581 if (!UserTy || (Ty && Ty != UserTy))
1582 TyIsCommon = false; // Give up on anything but an iN type.
1583 else
1584 Ty = UserTy;
1585 }
1586
1587 return {TyIsCommon ? Ty : nullptr, ITy};
1588}
1589
1590/// PHI instructions that use an alloca and are subsequently loaded can be
1591/// rewritten to load both input pointers in the pred blocks and then PHI the
1592/// results, allowing the load of the alloca to be promoted.
1593/// From this:
1594/// %P2 = phi [i32* %Alloca, i32* %Other]
1595/// %V = load i32* %P2
1596/// to:
1597/// %V1 = load i32* %Alloca -> will be mem2reg'd
1598/// ...
1599/// %V2 = load i32* %Other
1600/// ...
1601/// %V = phi [i32 %V1, i32 %V2]
1602///
1603/// We can do this to a PHI if its only uses are loads and if any loads moved
1604/// across other outgoing edges can be executed unconditionally.
1605///
1606/// FIXME: This should be hoisted into a generic utility, likely in
1607/// Transforms/Util/Local.h
1609 const DataLayout &DL = PN.getDataLayout();
1610
1611 // For now, we can only do this promotion if the load is in the same block
1612 // as the PHI, and if there are no stores between the phi and load.
1613 // TODO: Allow recursive phi users.
1614 BasicBlock *BB = PN.getParent();
1615 Align MaxAlign;
1616 uint64_t APWidth = DL.getIndexTypeSizeInBits(PN.getType());
1617 Type *LoadType = nullptr;
1618 for (User *U : PN.users()) {
1620 if (!LI || !LI->isSimple())
1621 return false;
1622
1623 // For now we only allow loads in the same block as the PHI. This is
1624 // a common case that happens when instcombine merges two loads through
1625 // a PHI.
1626 if (LI->getParent() != BB)
1627 return false;
1628
1629 if (LoadType) {
1630 if (LoadType != LI->getType())
1631 return false;
1632 } else {
1633 LoadType = LI->getType();
1634 }
1635
1636 // Ensure that there are no instructions between the PHI and the load that
1637 // could store.
1638 for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
1639 if (BBI->mayWriteToMemory())
1640 return false;
1641
1642 MaxAlign = std::max(MaxAlign, LI->getAlign());
1643 }
1644
1645 if (!LoadType)
1646 return false;
1647
1648 APInt LoadSize =
1649 APInt(APWidth, DL.getTypeStoreSize(LoadType).getFixedValue());
1650
1651 // We can only transform this if it is safe to push the loads into the
1652 // predecessor blocks. The only thing to watch out for is that we can't put
1653 // a possibly trapping load in the predecessor if it is a critical edge.
1654 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1656 Value *InVal = PN.getIncomingValue(Idx);
1657
1658 // If the value is produced by the terminator of the predecessor (an
1659 // invoke) or it has side-effects, there is no valid place to put a load
1660 // in the predecessor.
1661 if (TI == InVal || TI->mayHaveSideEffects())
1662 return false;
1663
1664 // If the predecessor has a single successor, then the edge isn't
1665 // critical.
1666 if (TI->getNumSuccessors() == 1)
1667 continue;
1668
1669 // If this pointer is always safe to load, or if we can prove that there
1670 // is already a load in the block, then we can move the load to the pred
1671 // block.
1672 if (isSafeToLoadUnconditionally(InVal, MaxAlign, LoadSize,
1673 SimplifyQuery(DL, TI)))
1674 continue;
1675
1676 return false;
1677 }
1678
1679 return true;
1680}
1681
1682/// Check whether a single store through PN can be moved onto each incoming
1683/// edge.
1684static StoreInst *getPHIStoreToRewrite(PHINode &PN, bool PreserveCFG,
1685 DominatorTree &DT) {
1686 // TODO: Support multiple stores and mixed load/store users.
1687 // TODO: Look through other instructions, such as other phis or addrspacecasts
1688 if (!PN.hasOneUse())
1689 return nullptr;
1690
1691 auto *SI = dyn_cast<StoreInst>(PN.user_back());
1692 if (!SI || SI->getPointerOperand() != &PN)
1693 return nullptr;
1694
1695 if (SI->isVolatile())
1696 return nullptr;
1697
1698 BasicBlock *BB = PN.getParent();
1699 // TODO: Allow a harmless prefix between the PHIs and the store.
1700 if (&*BB->getFirstNonPHIOrPseudoProbe() != SI)
1701 return nullptr;
1702
1703 Value *StoredValue = SI->getValueOperand();
1705 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1706 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1707
1708 // Only one store is needed for duplicate edges from the same predecessor.
1709 if (!SeenPreds.insert(Pred).second)
1710 continue;
1711
1712 // TODO: Support other terminators.
1713 Instruction *TI = Pred->getTerminator();
1715 return nullptr;
1716
1717 if (Pred == BB)
1718 return nullptr;
1719
1720 // TODO: If StoredValue is another PHI in BB, use its corresponding
1721 // incoming value instead of requiring it to dominate every predecessor.
1722 if (!DT.dominates(StoredValue, TI))
1723 return nullptr;
1724
1725 if (TI->getNumSuccessors() == 1)
1726 continue;
1727
1728 // If the predecessor has more than one successor, then we will need to
1729 // split it so that we can insert the store only on the path to this BB.
1730 if (PreserveCFG || !BB->canSplitPredecessors())
1731 return nullptr;
1732 }
1733
1734 return SI;
1735}
1736
1737static void speculatePHINodeLoads(IRBuilderTy &IRB, PHINode &PN) {
1738 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
1739
1740 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
1741 Type *LoadTy = SomeLoad->getType();
1742 IRB.SetInsertPoint(&PN);
1743 PHINode *NewPN = IRB.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1744 PN.getName() + ".sroa.speculated");
1745
1746 // Get the AA tags and alignment to use from one of the loads. It does not
1747 // matter which one we get and if any differ.
1748 AAMDNodes AATags = SomeLoad->getAAMetadata();
1749 Align Alignment = SomeLoad->getAlign();
1750
1751 // Rewrite all loads of the PN to use the new PHI.
1752 while (!PN.use_empty()) {
1753 LoadInst *LI = cast<LoadInst>(PN.user_back());
1754 LI->replaceAllUsesWith(NewPN);
1755 LI->eraseFromParent();
1756 }
1757
1758 // Inject loads into all of the pred blocks.
1759 DenseMap<BasicBlock *, Value *> InjectedLoads;
1760 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1761 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1762 Value *InVal = PN.getIncomingValue(Idx);
1763
1764 // A PHI node is allowed to have multiple (duplicated) entries for the same
1765 // basic block, as long as the value is the same. So if we already injected
1766 // a load in the predecessor, then we should reuse the same load for all
1767 // duplicated entries.
1768 if (Value *V = InjectedLoads.lookup(Pred)) {
1769 NewPN->addIncoming(V, Pred);
1770 continue;
1771 }
1772
1773 Instruction *TI = Pred->getTerminator();
1774 IRB.SetInsertPoint(TI);
1775
1776 LoadInst *Load = IRB.CreateAlignedLoad(
1777 LoadTy, InVal, Alignment,
1778 (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1779 ++NumLoadsSpeculated;
1780 if (AATags)
1781 Load->setAAMetadata(AATags);
1782 NewPN->addIncoming(Load, Pred);
1783 InjectedLoads[Pred] = Load;
1784 }
1785
1786 LLVM_DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1787 PN.eraseFromParent();
1788}
1789
1790/// Move a store through a pointer PHI onto each of the PHI's incoming edges.
1791/// Returns whether this required modifying the CFG.
1794 LLVM_DEBUG(dbgs() << " original: " << PN << "\n"
1795 << " " << SI << "\n");
1796
1797 // Splitting one edge rewrites all PHIs in the destination block. Snapshot
1798 // the original predecessor/value pairs before making any CFG changes.
1801 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1802 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1803 if (!SeenPreds.insert(Pred).second)
1804 continue;
1805 Value *InVal = PN.getIncomingValue(Idx);
1806 IncomingValues.emplace_back(Pred, InVal);
1807
1808 // Revisit every alloca exposed by removing the pointer PHI.
1809 if (auto *AI = dyn_cast<AllocaInst>(getUnderlyingObject(InVal)))
1810 Worklist.insert(AI);
1811 }
1812
1813 bool CFGChanged = false;
1814 BasicBlock *BB = PN.getParent();
1815 for (auto [Pred, InVal] : IncomingValues) {
1816 BasicBlock *StoreBB = Pred;
1817 if (Pred->getTerminator()->getNumSuccessors() != 1) {
1818 StoreBB = SplitBlockPredecessors(BB, {Pred}, ".sroa.store", &DTU);
1819 assert(StoreBB && "store edge was not checked for splitting");
1820 CFGChanged = true;
1821 }
1822
1823 auto *NewStore = cast<StoreInst>(SI.clone());
1824 NewStore->setOperand(StoreInst::getPointerOperandIndex(), InVal);
1825 NewStore->insertBefore(StoreBB->getTerminator()->getIterator());
1826 ++NumStoresPredicated;
1827 LLVM_DEBUG(dbgs() << " to: " << *NewStore << "\n");
1828 }
1829
1830 SI.eraseFromParent();
1831 PN.eraseFromParent();
1832 return CFGChanged;
1833}
1834
1835SelectHandSpeculativity &
1836SelectHandSpeculativity::setAsSpeculatable(bool isTrueVal) {
1837 if (isTrueVal)
1839 else
1841 return *this;
1842}
1843
1844bool SelectHandSpeculativity::isSpeculatable(bool isTrueVal) const {
1845 return isTrueVal ? Bitfield::get<SelectHandSpeculativity::TrueVal>(Storage)
1846 : Bitfield::get<SelectHandSpeculativity::FalseVal>(Storage);
1847}
1848
1849bool SelectHandSpeculativity::areAllSpeculatable() const {
1850 return isSpeculatable(/*isTrueVal=*/true) &&
1851 isSpeculatable(/*isTrueVal=*/false);
1852}
1853
1854bool SelectHandSpeculativity::areAnySpeculatable() const {
1855 return isSpeculatable(/*isTrueVal=*/true) ||
1856 isSpeculatable(/*isTrueVal=*/false);
1857}
1858bool SelectHandSpeculativity::areNoneSpeculatable() const {
1859 return !areAnySpeculatable();
1860}
1861
1862static SelectHandSpeculativity
1864 assert(LI.isSimple() && "Only for simple loads");
1865 SelectHandSpeculativity Spec;
1866
1867 const DataLayout &DL = SI.getDataLayout();
1868 for (Value *Value : {SI.getTrueValue(), SI.getFalseValue()})
1870 SimplifyQuery(DL, &LI)))
1871 Spec.setAsSpeculatable(/*isTrueVal=*/Value == SI.getTrueValue());
1872 else if (PreserveCFG)
1873 return Spec;
1874
1875 return Spec;
1876}
1877
1878std::optional<RewriteableMemOps>
1879SROA::isSafeSelectToSpeculateOrPredicate(SelectInst &SI, bool PreserveCFG) {
1880 RewriteableMemOps Ops;
1881
1883 for (User *U : SI.users()) {
1885 append_range(Users, U->users());
1886 else
1887 Users.push_back(U);
1888 }
1889
1890 for (User *U : Users) {
1891 if (auto *Store = dyn_cast<StoreInst>(U)) {
1892 // We don't care about atomicity of stores as they're always predicated.
1893 if (Store->isVolatile() || PreserveCFG)
1894 return {}; // Give up on this `select`.
1895 Ops.emplace_back(Store);
1896 continue;
1897 }
1898
1899 auto *LI = dyn_cast<LoadInst>(U);
1900
1901 if (!LI || LI->isVolatile())
1902 return {}; // Give up on this `select`.
1903
1904 PossiblySpeculatableLoad Load(LI);
1905
1906 // Atomic loads need to be predicated: speculation emits plain loads, which
1907 // would drop the atomicity of the load when one of the hands is non-local,
1908 // introducing a race.
1909 // We could allow this when both hands are allocas (atomicity doesn't mean
1910 // anything on allocas), but for now we give up if we're not allowed to
1911 // predicate.
1912 if (!LI->isSimple()) { // or `LI->isAtomic()`, `isVolatile` already checked
1913 if (PreserveCFG)
1914 return {}; // Give up on this `select`.
1915 Ops.emplace_back(Load);
1916 continue;
1917 }
1918
1919 SelectHandSpeculativity Spec =
1920 isSafeLoadOfSelectToSpeculate(*LI, SI, PreserveCFG);
1921 if (PreserveCFG && !Spec.areAllSpeculatable())
1922 return {}; // Give up on this `select`.
1923
1924 Load.setInt(Spec);
1925 Ops.emplace_back(Load);
1926 }
1927
1928 return Ops;
1929}
1930
1932 IRBuilderTy &IRB) {
1933 LLVM_DEBUG(dbgs() << " original load: " << SI << "\n");
1934
1935 Value *TV = SI.getTrueValue();
1936 Value *FV = SI.getFalseValue();
1937 // Replace the given load of the select with a select of two loads.
1938
1939 assert(LI.isSimple() && "We only speculate simple loads");
1940
1941 IRB.SetInsertPoint(&LI);
1942
1943 // Casts may separate the load from the select.
1944 TV = IRB.CreateAddrSpaceCast(TV, LI.getPointerOperandType(),
1945 LI.getName() + ".sroa.speculate.cast.true");
1946 FV = IRB.CreateAddrSpaceCast(FV, LI.getPointerOperandType(),
1947 LI.getName() + ".sroa.speculate.cast.false");
1948
1949 LoadInst *TL =
1950 IRB.CreateAlignedLoad(LI.getType(), TV, LI.getAlign(),
1951 LI.getName() + ".sroa.speculate.load.true");
1952 LoadInst *FL =
1953 IRB.CreateAlignedLoad(LI.getType(), FV, LI.getAlign(),
1954 LI.getName() + ".sroa.speculate.load.false");
1955 NumLoadsSpeculated += 2;
1956
1957 // Transfer alignment and AA info if present.
1958 TL->setAlignment(LI.getAlign());
1959 FL->setAlignment(LI.getAlign());
1960
1961 AAMDNodes Tags = LI.getAAMetadata();
1962 if (Tags) {
1963 TL->setAAMetadata(Tags);
1964 FL->setAAMetadata(Tags);
1965 }
1966
1967 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1968 LI.getName() + ".sroa.speculated", &SI);
1969
1970 LLVM_DEBUG(dbgs() << " speculated to: " << *V << "\n");
1972}
1973
1974template <typename T>
1976 SelectHandSpeculativity Spec, IRBuilderTy &IRB,
1977 DomTreeUpdater &DTU) {
1978 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) && "Only for load and store!");
1979 LLVM_DEBUG(dbgs() << " original mem op: " << I << "\n");
1980 BasicBlock *Head = I.getParent();
1981 Instruction *ThenTerm = nullptr;
1982 Instruction *ElseTerm = nullptr;
1983 if (Spec.areNoneSpeculatable())
1984 SplitBlockAndInsertIfThenElse(SI.getCondition(), &I, &ThenTerm, &ElseTerm,
1985 SI.getMetadata(LLVMContext::MD_prof), &DTU);
1986 else {
1987 SplitBlockAndInsertIfThen(SI.getCondition(), &I, /*Unreachable=*/false,
1988 SI.getMetadata(LLVMContext::MD_prof), &DTU,
1989 /*LI=*/nullptr, /*ThenBlock=*/nullptr);
1990 if (Spec.isSpeculatable(/*isTrueVal=*/true))
1991 cast<CondBrInst>(Head->getTerminator())->swapSuccessors();
1992 }
1993 auto *HeadBI = cast<CondBrInst>(Head->getTerminator());
1994 Spec = {}; // Do not use `Spec` beyond this point.
1995 BasicBlock *Tail = I.getParent();
1996 Tail->setName(Head->getName() + ".cont");
1997 PHINode *PN;
1998 if (isa<LoadInst>(I))
1999 PN = PHINode::Create(I.getType(), 2, "", I.getIterator());
2000 for (BasicBlock *SuccBB : successors(Head)) {
2001 bool IsThen = SuccBB == HeadBI->getSuccessor(0);
2002 int SuccIdx = IsThen ? 0 : 1;
2003 auto *NewMemOpBB = SuccBB == Tail ? Head : SuccBB;
2004 auto &CondMemOp = cast<T>(*I.clone());
2005 if (NewMemOpBB != Head) {
2006 NewMemOpBB->setName(Head->getName() + (IsThen ? ".then" : ".else"));
2007 if (isa<LoadInst>(I))
2008 ++NumLoadsPredicated;
2009 else
2010 ++NumStoresPredicated;
2011 } else {
2012 CondMemOp.dropUBImplyingAttrsAndMetadata();
2013 ++NumLoadsSpeculated;
2014 }
2015 CondMemOp.insertBefore(NewMemOpBB->getTerminator()->getIterator());
2016 Value *Ptr = SI.getOperand(1 + SuccIdx);
2017 // Casts may separate the memory operation from the select. Keep the
2018 // original access pointer type, e.g. its address space.
2019 IRB.SetInsertPoint(&CondMemOp);
2020 Ptr = IRB.CreateAddrSpaceCast(Ptr, I.getPointerOperandType(),
2021 I.getName() + (IsThen ? ".then" : ".else") +
2022 ".cast");
2023 CondMemOp.setOperand(I.getPointerOperandIndex(), Ptr);
2024 if (isa<LoadInst>(I)) {
2025 CondMemOp.setName(I.getName() + (IsThen ? ".then" : ".else") + ".val");
2026 PN->addIncoming(&CondMemOp, NewMemOpBB);
2027 } else
2028 LLVM_DEBUG(dbgs() << " to: " << CondMemOp << "\n");
2029 }
2030 if (isa<LoadInst>(I)) {
2031 PN->takeName(&I);
2032 LLVM_DEBUG(dbgs() << " to: " << *PN << "\n");
2033 I.replaceAllUsesWith(PN);
2034 }
2035}
2036
2038 SelectHandSpeculativity Spec, IRBuilderTy &IRB,
2039 DomTreeUpdater &DTU) {
2040 if (auto *LI = dyn_cast<LoadInst>(&I))
2041 rewriteMemOpOfSelect(SelInst, *LI, Spec, IRB, DTU);
2042 else if (auto *SI = dyn_cast<StoreInst>(&I))
2043 rewriteMemOpOfSelect(SelInst, *SI, Spec, IRB, DTU);
2044 else
2045 llvm_unreachable_internal("Only for load and store.");
2046}
2047
2049 const RewriteableMemOps &Ops,
2050 IRBuilderTy &IRB, DomTreeUpdater *DTU) {
2051 bool CFGChanged = false;
2052 LLVM_DEBUG(dbgs() << " original select: " << SI << "\n");
2053
2054 for (const RewriteableMemOp &Op : Ops) {
2055 SelectHandSpeculativity Spec;
2056 Instruction *I;
2057 if (auto *const *US = std::get_if<UnspeculatableStore>(&Op)) {
2058 I = *US;
2059 } else {
2060 auto PSL = std::get<PossiblySpeculatableLoad>(Op);
2061 I = PSL.getPointer();
2062 Spec = PSL.getInt();
2063 }
2064 if (Spec.areAllSpeculatable()) {
2066 } else {
2067 assert(DTU && "Should not get here when not allowed to modify the CFG!");
2068 rewriteMemOpOfSelect(SI, *I, Spec, IRB, *DTU);
2069 CFGChanged = true;
2070 }
2071 I->eraseFromParent();
2072 }
2073
2074 for (User *U : make_early_inc_range(SI.users()))
2075 cast<AddrSpaceCastInst>(U)->eraseFromParent();
2076 SI.eraseFromParent();
2077 return CFGChanged;
2078}
2079
2080/// Compute an adjusted pointer from Ptr by Offset bytes where the
2081/// resulting pointer has PointerTy.
2082static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
2084 const Twine &NamePrefix) {
2085 if (Offset != 0)
2086 Ptr = IRB.CreateInBoundsPtrAdd(Ptr, IRB.getInt(Offset),
2087 NamePrefix + "sroa_idx");
2088 return IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr, PointerTy,
2089 NamePrefix + "sroa_cast");
2090}
2091
2092/// Compute the adjusted alignment for a load or store from an offset.
2096
2097/// Test whether we can convert a value from the old to the new type.
2098///
2099/// This predicate should be used to guard calls to convertValue in order to
2100/// ensure that we only try to convert viable values. The strategy is that we
2101/// will peel off single element struct and array wrappings to get to an
2102/// underlying value, and convert that value.
2103static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy,
2104 unsigned VScale = 0) {
2105 if (OldTy == NewTy)
2106 return true;
2107
2108 // For integer types, we can't handle any bit-width differences. This would
2109 // break both vector conversions with extension and introduce endianness
2110 // issues when in conjunction with loads and stores.
2111 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
2113 cast<IntegerType>(NewTy)->getBitWidth() &&
2114 "We can't have the same bitwidth for different int types");
2115 return false;
2116 }
2117
2118 TypeSize NewSize = DL.getTypeSizeInBits(NewTy);
2119 TypeSize OldSize = DL.getTypeSizeInBits(OldTy);
2120
2121 if ((isa<ScalableVectorType>(NewTy) && isa<FixedVectorType>(OldTy)) ||
2122 (isa<ScalableVectorType>(OldTy) && isa<FixedVectorType>(NewTy))) {
2123 // Conversion is only possible when the size of scalable vectors is known.
2124 if (!VScale)
2125 return false;
2126
2127 // For ptr-to-int and int-to-ptr casts, the pointer side is resolved within
2128 // a single domain (either fixed or scalable). Any additional conversion
2129 // between fixed and scalable types is handled through integer types.
2130 auto OldVTy = OldTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(OldTy) : OldTy;
2131 auto NewVTy = NewTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(NewTy) : NewTy;
2132
2133 if (isa<ScalableVectorType>(NewTy)) {
2135 return false;
2136
2137 NewSize = TypeSize::getFixed(NewSize.getKnownMinValue() * VScale);
2138 } else {
2140 return false;
2141
2142 OldSize = TypeSize::getFixed(OldSize.getKnownMinValue() * VScale);
2143 }
2144 }
2145
2146 if (NewSize != OldSize)
2147 return false;
2148 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
2149 return false;
2150
2151 // We can convert pointers to integers and vice-versa. Same for vectors
2152 // of pointers and integers.
2153 OldTy = OldTy->getScalarType();
2154 NewTy = NewTy->getScalarType();
2155 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
2156 if (NewTy->isPointerTy() && OldTy->isPointerTy()) {
2157 unsigned OldAS = OldTy->getPointerAddressSpace();
2158 unsigned NewAS = NewTy->getPointerAddressSpace();
2159 // Convert pointers if they are pointers from the same address space or
2160 // different integral (not non-integral) address spaces with the same
2161 // pointer size.
2162 return OldAS == NewAS ||
2163 (!DL.isNonIntegralAddressSpace(OldAS) &&
2164 !DL.isNonIntegralAddressSpace(NewAS) &&
2165 DL.getPointerSize(OldAS) == DL.getPointerSize(NewAS));
2166 }
2167
2168 // We can convert integers to integral pointers, but not to non-integral
2169 // pointers.
2170 if (OldTy->isIntegerTy())
2171 return !DL.isNonIntegralPointerType(NewTy);
2172
2173 // We can convert integral pointers to integers, but non-integral pointers
2174 // need to remain pointers.
2175 if (!DL.isNonIntegralPointerType(OldTy))
2176 return NewTy->isIntegerTy();
2177
2178 return false;
2179 }
2180
2181 if (OldTy->isTargetExtTy() || NewTy->isTargetExtTy())
2182 return false;
2183
2184 return true;
2185}
2186
2187/// Test whether the given slice use can be promoted to a vector.
2188///
2189/// This function is called to test each entry in a partition which is slated
2190/// for a single slice.
2191static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
2192 VectorType *Ty,
2193 uint64_t ElementBits,
2194 const DataLayout &DL,
2195 unsigned VScale) {
2196 // First validate the slice offsets. Slices are byte-aligned, but elements
2197 // may be narrower than a byte.
2198 uint64_t BeginBit =
2199 (std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset()) * 8;
2200 uint64_t BeginIndex = BeginBit / ElementBits;
2201 if (BeginIndex * ElementBits != BeginBit ||
2202 BeginIndex >= cast<FixedVectorType>(Ty)->getNumElements())
2203 return false;
2204 uint64_t EndBit =
2205 (std::min(S.endOffset(), P.endOffset()) - P.beginOffset()) * 8;
2206 uint64_t EndIndex = EndBit / ElementBits;
2207 if (EndIndex * ElementBits != EndBit ||
2208 EndIndex > cast<FixedVectorType>(Ty)->getNumElements())
2209 return false;
2210
2211 assert(EndIndex > BeginIndex && "Empty vector!");
2212 uint64_t NumElements = EndIndex - BeginIndex;
2213 Type *SliceTy = (NumElements == 1)
2214 ? Ty->getElementType()
2215 : FixedVectorType::get(Ty->getElementType(), NumElements);
2216
2217 Type *SplitIntTy =
2218 Type::getIntNTy(Ty->getContext(), NumElements * ElementBits);
2219
2220 Use *U = S.getUse();
2221
2222 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2223 if (MI->isVolatile())
2224 return false;
2225 if (!S.isSplittable())
2226 return false; // Skip any unsplittable intrinsics.
2227 if (isa<MemSetInst>(MI)) {
2228 // The splatted byte pattern is converted to one element, or to the
2229 // whole slice if the elements are narrower than a byte.
2230 Type *SplatDstTy = ElementBits % 8 ? SliceTy : Ty->getElementType();
2231 Type *SplatTy = Type::getIntNTy(
2232 Ty->getContext(), DL.getTypeSizeInBits(SplatDstTy).getFixedValue());
2233 if (!canConvertValue(DL, SplatTy, SplatDstTy, VScale))
2234 return false;
2235 }
2236 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2237 if (!II->isLifetimeStartOrEnd() && !II->isDroppable())
2238 return false;
2239 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2240 if (LI->isVolatile())
2241 return false;
2242 Type *LTy = LI->getType();
2243 // Disable vector promotion when there are loads or stores of an FCA.
2244 if (LTy->isStructTy())
2245 return false;
2246 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
2247 assert(LTy->isIntegerTy());
2248 LTy = SplitIntTy;
2249 }
2250 if (!canConvertValue(DL, SliceTy, LTy, VScale))
2251 return false;
2252 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2253 if (SI->isVolatile())
2254 return false;
2255 Type *STy = SI->getValueOperand()->getType();
2256 // Disable vector promotion when there are loads or stores of an FCA.
2257 if (STy->isStructTy())
2258 return false;
2259 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
2260 assert(STy->isIntegerTy());
2261 STy = SplitIntTy;
2262 }
2263 if (!canConvertValue(DL, STy, SliceTy, VScale))
2264 return false;
2265 } else {
2266 return false;
2267 }
2268
2269 return true;
2270}
2271
2272/// Test whether any vector type in \p CandidateTys is viable for promotion.
2273///
2274/// This implements the necessary checking for \c isVectorPromotionViable over
2275/// all slices of the alloca for the given VectorType.
2276static VectorType *
2278 SmallVectorImpl<VectorType *> &CandidateTys,
2279 bool HaveCommonEltTy, Type *CommonEltTy,
2280 bool HaveVecPtrTy, bool HaveCommonVecPtrTy,
2281 VectorType *CommonVecPtrTy, unsigned VScale) {
2282 // If we didn't find a vector type, nothing to do here.
2283 if (CandidateTys.empty())
2284 return nullptr;
2285
2286 // Pointer-ness is sticky, if we had a vector-of-pointers candidate type,
2287 // then we should choose it, not some other alternative.
2288 // But, we can't perform a no-op pointer address space change via bitcast,
2289 // so if we didn't have a common pointer element type, bail.
2290 if (HaveVecPtrTy && !HaveCommonVecPtrTy)
2291 return nullptr;
2292
2293 // Try to pick the "best" element type out of the choices.
2294 if (!HaveCommonEltTy && HaveVecPtrTy) {
2295 // If there was a pointer element type, there's really only one choice.
2296 CandidateTys.clear();
2297 CandidateTys.push_back(CommonVecPtrTy);
2298 } else if (!HaveCommonEltTy && !HaveVecPtrTy) {
2299 // Integer-ify vector types.
2300 for (VectorType *&VTy : CandidateTys) {
2301 if (!VTy->getElementType()->isIntegerTy())
2302 VTy = cast<VectorType>(VTy->getWithNewType(IntegerType::getIntNTy(
2303 VTy->getContext(), VTy->getScalarSizeInBits())));
2304 }
2305
2306 // Rank the remaining candidate vector types. This is easy because we know
2307 // they're all integer vectors. We sort by ascending number of elements.
2308 auto RankVectorTypesComp = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
2309 (void)DL;
2310 assert(DL.getTypeSizeInBits(RHSTy).getFixedValue() ==
2311 DL.getTypeSizeInBits(LHSTy).getFixedValue() &&
2312 "Cannot have vector types of different sizes!");
2313 assert(RHSTy->getElementType()->isIntegerTy() &&
2314 "All non-integer types eliminated!");
2315 assert(LHSTy->getElementType()->isIntegerTy() &&
2316 "All non-integer types eliminated!");
2317 return cast<FixedVectorType>(RHSTy)->getNumElements() <
2318 cast<FixedVectorType>(LHSTy)->getNumElements();
2319 };
2320 auto RankVectorTypesEq = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
2321 (void)DL;
2322 assert(DL.getTypeSizeInBits(RHSTy).getFixedValue() ==
2323 DL.getTypeSizeInBits(LHSTy).getFixedValue() &&
2324 "Cannot have vector types of different sizes!");
2325 assert(RHSTy->getElementType()->isIntegerTy() &&
2326 "All non-integer types eliminated!");
2327 assert(LHSTy->getElementType()->isIntegerTy() &&
2328 "All non-integer types eliminated!");
2329 return cast<FixedVectorType>(RHSTy)->getNumElements() ==
2330 cast<FixedVectorType>(LHSTy)->getNumElements();
2331 };
2332 llvm::sort(CandidateTys, RankVectorTypesComp);
2333 CandidateTys.erase(llvm::unique(CandidateTys, RankVectorTypesEq),
2334 CandidateTys.end());
2335 } else {
2336// The only way to have the same element type in every vector type is to
2337// have the same vector type. Check that and remove all but one.
2338#ifndef NDEBUG
2339 for (VectorType *VTy : CandidateTys) {
2340 assert(VTy->getElementType() == CommonEltTy &&
2341 "Unaccounted for element type!");
2342 assert(VTy == CandidateTys[0] &&
2343 "Different vector types with the same element type!");
2344 }
2345#endif
2346 CandidateTys.resize(1);
2347 }
2348
2349 // FIXME: hack. Do we have a named constant for this?
2350 // SDAG SDNode can't have more than 65535 operands.
2351 llvm::erase_if(CandidateTys, [](VectorType *VTy) {
2352 return cast<FixedVectorType>(VTy)->getNumElements() >
2353 std::numeric_limits<unsigned short>::max();
2354 });
2355
2356 // Find a vector type viable for promotion by iterating over all slices.
2357 auto *VTy = llvm::find_if(CandidateTys, [&](VectorType *VTy) -> bool {
2358 uint64_t ElementBits =
2359 DL.getTypeSizeInBits(VTy->getElementType()).getFixedValue();
2360
2361 // Vectors are bit-packed, so elements may be narrower than a byte, but
2362 // wider elements must be whole bytes.
2363 if (ElementBits > 8 && ElementBits % 8)
2364 return false;
2365
2366 for (const Slice &S : P)
2367 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementBits, DL, VScale))
2368 return false;
2369
2370 for (const Slice *S : P.splitSliceTails())
2371 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementBits, DL, VScale))
2372 return false;
2373
2374 return true;
2375 });
2376 return VTy != CandidateTys.end() ? *VTy : nullptr;
2377}
2378
2380 SetVector<Type *> &OtherTys, ArrayRef<VectorType *> CandidateTysCopy,
2381 function_ref<void(Type *)> CheckCandidateType, Partition &P,
2382 const DataLayout &DL, SmallVectorImpl<VectorType *> &CandidateTys,
2383 bool &HaveCommonEltTy, Type *&CommonEltTy, bool &HaveVecPtrTy,
2384 bool &HaveCommonVecPtrTy, VectorType *&CommonVecPtrTy, unsigned VScale) {
2385 [[maybe_unused]] VectorType *OriginalElt =
2386 CandidateTysCopy.size() ? CandidateTysCopy[0] : nullptr;
2387 // Consider additional vector types where the element type size is a
2388 // multiple of load/store element size.
2389 for (Type *Ty : OtherTys) {
2391 continue;
2392 unsigned TypeSize = DL.getTypeSizeInBits(Ty).getFixedValue();
2393 // Make a copy of CandidateTys and iterate through it, because we
2394 // might append to CandidateTys in the loop.
2395 for (VectorType *const VTy : CandidateTysCopy) {
2396 // The elements in the copy should remain invariant throughout the loop
2397 assert(CandidateTysCopy[0] == OriginalElt && "Different Element");
2398 unsigned VectorSize = DL.getTypeSizeInBits(VTy).getFixedValue();
2399 unsigned ElementSize =
2400 DL.getTypeSizeInBits(VTy->getElementType()).getFixedValue();
2401 if (TypeSize != VectorSize && TypeSize != ElementSize &&
2402 VectorSize % TypeSize == 0) {
2403 VectorType *NewVTy = VectorType::get(Ty, VectorSize / TypeSize, false);
2404 CheckCandidateType(NewVTy);
2405 }
2406 }
2407 }
2408
2410 P, DL, CandidateTys, HaveCommonEltTy, CommonEltTy, HaveVecPtrTy,
2411 HaveCommonVecPtrTy, CommonVecPtrTy, VScale);
2412}
2413
2414/// Test whether the given alloca partitioning and range of slices can be
2415/// promoted to a vector.
2416///
2417/// This is a quick test to check whether we can rewrite a particular alloca
2418/// partition (and its newly formed alloca) into a vector alloca with only
2419/// whole-vector loads and stores such that it could be promoted to a vector
2420/// SSA value. We only can ensure this for a limited set of operations, and we
2421/// don't want to do the rewrites unless we are confident that the result will
2422/// be promotable, so we have an early test here.
2424 unsigned VScale) {
2425 // Collect the candidate types for vector-based promotion. Also track whether
2426 // we have different element types.
2427 SmallVector<VectorType *, 4> CandidateTys;
2428 SetVector<Type *> LoadStoreTys;
2429 SetVector<Type *> DeferredTys;
2430 Type *CommonEltTy = nullptr;
2431 VectorType *CommonVecPtrTy = nullptr;
2432 bool HaveVecPtrTy = false;
2433 bool HaveCommonEltTy = true;
2434 bool HaveCommonVecPtrTy = true;
2435 auto CheckCandidateType = [&](Type *Ty) {
2436 if (auto *VTy = dyn_cast<FixedVectorType>(Ty)) {
2437 // Return if bitcast to vectors is different for total size in bits.
2438 if (!CandidateTys.empty()) {
2439 VectorType *V = CandidateTys[0];
2440 if (DL.getTypeSizeInBits(VTy).getFixedValue() !=
2441 DL.getTypeSizeInBits(V).getFixedValue()) {
2442 CandidateTys.clear();
2443 return;
2444 }
2445 }
2446 CandidateTys.push_back(VTy);
2447 Type *EltTy = VTy->getElementType();
2448
2449 if (!CommonEltTy)
2450 CommonEltTy = EltTy;
2451 else if (CommonEltTy != EltTy)
2452 HaveCommonEltTy = false;
2453
2454 if (EltTy->isPointerTy()) {
2455 HaveVecPtrTy = true;
2456 if (!CommonVecPtrTy)
2457 CommonVecPtrTy = VTy;
2458 else if (CommonVecPtrTy != VTy)
2459 HaveCommonVecPtrTy = false;
2460 }
2461 }
2462 };
2463
2464 // Put load and store types into a set for de-duplication.
2465 for (const Slice &S : P) {
2466 Type *Ty;
2467 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
2468 Ty = LI->getType();
2469 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
2470 Ty = SI->getValueOperand()->getType();
2471 else
2472 continue;
2473
2474 auto CandTy = Ty->getScalarType();
2475 if (CandTy->isPointerTy() && (S.beginOffset() != P.beginOffset() ||
2476 S.endOffset() != P.endOffset())) {
2477 DeferredTys.insert(Ty);
2478 continue;
2479 }
2480
2481 LoadStoreTys.insert(Ty);
2482 // Consider any loads or stores that are the exact size of the slice.
2483 if (S.beginOffset() == P.beginOffset() && S.endOffset() == P.endOffset())
2484 CheckCandidateType(Ty);
2485 }
2486
2487 SmallVector<VectorType *, 4> CandidateTysCopy = CandidateTys;
2489 LoadStoreTys, CandidateTysCopy, CheckCandidateType, P, DL,
2490 CandidateTys, HaveCommonEltTy, CommonEltTy, HaveVecPtrTy,
2491 HaveCommonVecPtrTy, CommonVecPtrTy, VScale))
2492 return VTy;
2493
2494 CandidateTys.clear();
2496 DeferredTys, CandidateTysCopy, CheckCandidateType, P, DL, CandidateTys,
2497 HaveCommonEltTy, CommonEltTy, HaveVecPtrTy, HaveCommonVecPtrTy,
2498 CommonVecPtrTy, VScale);
2499}
2500
2501/// Test whether a slice of an alloca is valid for integer widening.
2502///
2503/// This implements the necessary checking for the \c isIntegerWideningViable
2504/// test below on a single slice of the alloca.
2505static bool isIntegerWideningViableForSlice(const Slice &S,
2506 uint64_t AllocBeginOffset,
2507 Type *AllocaTy,
2508 const DataLayout &DL,
2509 bool &WholeAllocaOp) {
2510 uint64_t Size = DL.getTypeStoreSize(AllocaTy).getFixedValue();
2511
2512 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
2513 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
2514
2515 Use *U = S.getUse();
2516
2517 // Lifetime intrinsics operate over the whole alloca whose sizes are usually
2518 // larger than other load/store slices (RelEnd > Size). But lifetime are
2519 // always promotable and should not impact other slices' promotability of the
2520 // partition.
2521 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2522 if (II->isLifetimeStartOrEnd() || II->isDroppable())
2523 return true;
2524 }
2525
2526 // We can't reasonably handle cases where the load or store extends past
2527 // the end of the alloca's type and into its padding.
2528 if (RelEnd > Size)
2529 return false;
2530
2531 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2532 if (LI->isVolatile())
2533 return false;
2534 // We can't handle loads that extend past the allocated memory.
2535 TypeSize LoadSize = DL.getTypeStoreSize(LI->getType());
2536 if (!LoadSize.isFixed() || LoadSize.getFixedValue() > Size)
2537 return false;
2538 // So far, AllocaSliceRewriter does not support widening split slice tails
2539 // in rewriteIntegerLoad.
2540 if (S.beginOffset() < AllocBeginOffset)
2541 return false;
2542 // Note that we don't count vector loads or stores as whole-alloca
2543 // operations which enable integer widening because we would prefer to use
2544 // vector widening instead.
2545 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
2546 WholeAllocaOp = true;
2547 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2548 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy).getFixedValue())
2549 return false;
2550 } else if (RelBegin != 0 || RelEnd != Size ||
2551 !canConvertValue(DL, AllocaTy, LI->getType())) {
2552 // Non-integer loads need to be convertible from the alloca type so that
2553 // they are promotable.
2554 return false;
2555 }
2556 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2557 Type *ValueTy = SI->getValueOperand()->getType();
2558 if (SI->isVolatile())
2559 return false;
2560 // We can't handle stores that extend past the allocated memory.
2561 TypeSize StoreSize = DL.getTypeStoreSize(ValueTy);
2562 if (!StoreSize.isFixed() || StoreSize.getFixedValue() > Size)
2563 return false;
2564 // So far, AllocaSliceRewriter does not support widening split slice tails
2565 // in rewriteIntegerStore.
2566 if (S.beginOffset() < AllocBeginOffset)
2567 return false;
2568 // Note that we don't count vector loads or stores as whole-alloca
2569 // operations which enable integer widening because we would prefer to use
2570 // vector widening instead.
2571 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
2572 WholeAllocaOp = true;
2573 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2574 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy).getFixedValue())
2575 return false;
2576 } else if (RelBegin != 0 || RelEnd != Size ||
2577 !canConvertValue(DL, ValueTy, AllocaTy)) {
2578 // Non-integer stores need to be convertible to the alloca type so that
2579 // they are promotable.
2580 return false;
2581 }
2582 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2583 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2584 return false;
2585 if (!S.isSplittable())
2586 return false; // Skip any unsplittable intrinsics.
2587 } else {
2588 return false;
2589 }
2590
2591 return true;
2592}
2593
2594/// Test whether the given alloca partition's integer operations can be
2595/// widened to promotable ones.
2596///
2597/// This is a quick test to check whether we can rewrite the integer loads and
2598/// stores to a particular alloca into wider loads and stores and be able to
2599/// promote the resulting alloca.
2600static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
2601 const DataLayout &DL) {
2602 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy).getFixedValue();
2603 // Don't create integer types larger than the maximum bitwidth.
2604 if (SizeInBits > IntegerType::MAX_INT_BITS)
2605 return false;
2606
2607 // Don't try to handle allocas with bit-padding.
2608 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy).getFixedValue())
2609 return false;
2610
2611 // We need to ensure that an integer type with the appropriate bitwidth can
2612 // be converted to the alloca type, whatever that is. We don't want to force
2613 // the alloca itself to have an integer type if there is a more suitable one.
2614 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2615 if (!canConvertValue(DL, AllocaTy, IntTy) ||
2616 !canConvertValue(DL, IntTy, AllocaTy))
2617 return false;
2618
2619 // While examining uses, we ensure that the alloca has a covering load or
2620 // store. We don't want to widen the integer operations only to fail to
2621 // promote due to some other unsplittable entry (which we may make splittable
2622 // later). However, if there are only splittable uses, go ahead and assume
2623 // that we cover the alloca.
2624 // FIXME: We shouldn't consider split slices that happen to start in the
2625 // partition here...
2626 bool WholeAllocaOp = P.empty() && DL.isLegalInteger(SizeInBits);
2627
2628 for (const Slice &S : P)
2629 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2630 WholeAllocaOp))
2631 return false;
2632
2633 for (const Slice *S : P.splitSliceTails())
2634 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2635 WholeAllocaOp))
2636 return false;
2637
2638 return WholeAllocaOp;
2639}
2640
2641static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
2643 const Twine &Name) {
2644 LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
2645 IntegerType *IntTy = cast<IntegerType>(V->getType());
2646 assert(DL.getTypeStoreSize(Ty).getFixedValue() + Offset <=
2647 DL.getTypeStoreSize(IntTy).getFixedValue() &&
2648 "Element extends past full value");
2649 uint64_t ShAmt = 8 * Offset;
2650 if (DL.isBigEndian())
2651 ShAmt = 8 * (DL.getTypeStoreSize(IntTy).getFixedValue() -
2652 DL.getTypeStoreSize(Ty).getFixedValue() - Offset);
2653 if (ShAmt) {
2654 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
2655 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
2656 }
2657 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2658 "Cannot extract to a larger integer!");
2659 if (Ty != IntTy) {
2660 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
2661 LLVM_DEBUG(dbgs() << " trunced: " << *V << "\n");
2662 }
2663 return V;
2664}
2665
2666static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
2667 Value *V, uint64_t Offset, const Twine &Name) {
2668 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2669 IntegerType *Ty = cast<IntegerType>(V->getType());
2670 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2671 "Cannot insert a larger integer!");
2672 LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
2673 if (Ty != IntTy) {
2674 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
2675 LLVM_DEBUG(dbgs() << " extended: " << *V << "\n");
2676 }
2677 assert(DL.getTypeStoreSize(Ty).getFixedValue() + Offset <=
2678 DL.getTypeStoreSize(IntTy).getFixedValue() &&
2679 "Element store outside of alloca store");
2680 uint64_t ShAmt = 8 * Offset;
2681 if (DL.isBigEndian())
2682 ShAmt = 8 * (DL.getTypeStoreSize(IntTy).getFixedValue() -
2683 DL.getTypeStoreSize(Ty).getFixedValue() - Offset);
2684 if (ShAmt) {
2685 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
2686 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
2687 }
2688
2689 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2690 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2691 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
2692 LLVM_DEBUG(dbgs() << " masked: " << *Old << "\n");
2693 V = IRB.CreateOr(Old, V, Name + ".insert");
2694 LLVM_DEBUG(dbgs() << " inserted: " << *V << "\n");
2695 }
2696 return V;
2697}
2698
2699static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2700 unsigned EndIndex, const Twine &Name) {
2701 auto *VecTy = cast<FixedVectorType>(V->getType());
2702 unsigned NumElements = EndIndex - BeginIndex;
2703 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2704
2705 if (NumElements == VecTy->getNumElements())
2706 return V;
2707
2708 if (NumElements == 1) {
2709 V = IRB.CreateExtractElement(V, BeginIndex, Name + ".extract");
2710 LLVM_DEBUG(dbgs() << " extract: " << *V << "\n");
2711 return V;
2712 }
2713
2714 auto Mask = llvm::to_vector<8>(llvm::seq<int>(BeginIndex, EndIndex));
2715 V = IRB.CreateShuffleVector(V, Mask, Name + ".extract");
2716 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
2717 return V;
2718}
2719
2720static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
2721 unsigned BeginIndex, const Twine &Name) {
2722 VectorType *VecTy = cast<VectorType>(Old->getType());
2723 assert(VecTy && "Can only insert a vector into a vector");
2724
2725 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2726 if (!Ty) {
2727 // Single element to insert.
2728 V = IRB.CreateInsertElement(Old, V, BeginIndex, Name + ".insert");
2729 LLVM_DEBUG(dbgs() << " insert: " << *V << "\n");
2730 return V;
2731 }
2732
2733 unsigned NumSubElements = cast<FixedVectorType>(Ty)->getNumElements();
2734 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
2735
2736 assert(NumSubElements <= NumElements && "Too many elements!");
2737 if (NumSubElements == NumElements) {
2738 assert(V->getType() == VecTy && "Vector type mismatch");
2739 return V;
2740 }
2741 unsigned EndIndex = BeginIndex + NumSubElements;
2742
2743 // When inserting a smaller vector into the larger to store, we first
2744 // use a shuffle vector to widen it with undef elements, and then
2745 // a second shuffle vector to select between the loaded vector and the
2746 // incoming vector.
2748 Mask.reserve(NumElements);
2749 for (unsigned Idx = 0; Idx != NumElements; ++Idx)
2750 if (Idx >= BeginIndex && Idx < EndIndex)
2751 Mask.push_back(Idx - BeginIndex);
2752 else
2753 Mask.push_back(-1);
2754 V = IRB.CreateShuffleVector(V, Mask, Name + ".expand");
2755 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
2756
2757 Mask.clear();
2758 for (unsigned Idx = 0; Idx != NumElements; ++Idx)
2759 if (Idx >= BeginIndex && Idx < EndIndex)
2760 Mask.push_back(Idx);
2761 else
2762 Mask.push_back(Idx + NumElements);
2763 V = IRB.CreateShuffleVector(V, Old, Mask, Name + "blend");
2764 LLVM_DEBUG(dbgs() << " blend: " << *V << "\n");
2765 return V;
2766}
2767
2768/// This function takes two vector values and combines them into a single vector
2769/// by concatenating their elements. The function handles:
2770///
2771/// 1. Element type mismatch: If either vector's element type differs from
2772/// NewAIEltType, the function bitcasts the vector to use NewAIEltType while
2773/// preserving the total bit width (adjusting the number of elements
2774/// accordingly).
2775///
2776/// 2. Size mismatch: After transforming the vectors to have the desired element
2777/// type, if the two vectors have different numbers of elements, the smaller
2778/// vector is extended with poison values to match the size of the larger
2779/// vector before concatenation.
2780///
2781/// 3. Concatenation: The vectors are merged using a shuffle operation that
2782/// places all elements of V0 first, followed by all elements of V1.
2783///
2784/// \param V0 The first vector to merge (must be a vector type)
2785/// \param V1 The second vector to merge (must be a vector type)
2786/// \param DL The data layout for size calculations
2787/// \param NewAIEltTy The desired element type for the result vector
2788/// \param Builder IRBuilder for creating new instructions
2789/// \return A new vector containing all elements from V0 followed by all
2790/// elements from V1
2792 Type *NewAIEltTy, IRBuilder<> &Builder) {
2793 // V0 and V1 are vectors
2794 // Create a new vector type with combined elements
2795 // Use ShuffleVector to concatenate the vectors
2796 auto *VecType0 = cast<FixedVectorType>(V0->getType());
2797 auto *VecType1 = cast<FixedVectorType>(V1->getType());
2798
2799 // If V0/V1 element types are different from NewAllocaElementType,
2800 // we need to introduce bitcasts before merging them
2801 auto BitcastIfNeeded = [&](Value *&V, FixedVectorType *&VecType,
2802 const char *DebugName) {
2803 Type *EltType = VecType->getElementType();
2804 if (EltType != NewAIEltTy) {
2805 // Calculate new number of elements to maintain same bit width
2806 unsigned TotalBits =
2807 VecType->getNumElements() * DL.getTypeSizeInBits(EltType);
2808 unsigned NewNumElts = TotalBits / DL.getTypeSizeInBits(NewAIEltTy);
2809
2810 auto *NewVecType = FixedVectorType::get(NewAIEltTy, NewNumElts);
2811 V = Builder.CreateBitCast(V, NewVecType);
2812 VecType = NewVecType;
2813 LLVM_DEBUG(dbgs() << " bitcast " << DebugName << ": " << *V << "\n");
2814 }
2815 };
2816
2817 BitcastIfNeeded(V0, VecType0, "V0");
2818 BitcastIfNeeded(V1, VecType1, "V1");
2819
2820 unsigned NumElts0 = VecType0->getNumElements();
2821 unsigned NumElts1 = VecType1->getNumElements();
2822
2823 SmallVector<int, 16> ShuffleMask;
2824
2825 if (NumElts0 == NumElts1) {
2826 for (unsigned i = 0; i < NumElts0 + NumElts1; ++i)
2827 ShuffleMask.push_back(i);
2828 } else {
2829 // If two vectors have different sizes, we need to extend
2830 // the smaller vector to the size of the larger vector.
2831 unsigned SmallSize = std::min(NumElts0, NumElts1);
2832 unsigned LargeSize = std::max(NumElts0, NumElts1);
2833 bool IsV0Smaller = NumElts0 < NumElts1;
2834 Value *&ExtendedVec = IsV0Smaller ? V0 : V1;
2835 SmallVector<int, 16> ExtendMask;
2836 for (unsigned i = 0; i < SmallSize; ++i)
2837 ExtendMask.push_back(i);
2838 for (unsigned i = SmallSize; i < LargeSize; ++i)
2839 ExtendMask.push_back(PoisonMaskElem);
2840 ExtendedVec = Builder.CreateShuffleVector(
2841 ExtendedVec, PoisonValue::get(ExtendedVec->getType()), ExtendMask);
2842 LLVM_DEBUG(dbgs() << " shufflevector: " << *ExtendedVec << "\n");
2843 for (unsigned i = 0; i < NumElts0; ++i)
2844 ShuffleMask.push_back(i);
2845 for (unsigned i = 0; i < NumElts1; ++i)
2846 ShuffleMask.push_back(LargeSize + i);
2847 }
2848
2849 return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2850}
2851
2852namespace {
2853
2854/// Visitor to rewrite instructions using p particular slice of an alloca
2855/// to use a new alloca.
2856///
2857/// Also implements the rewriting to vector-based accesses when the partition
2858/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2859/// lives here.
2860class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
2861 // Befriend the base class so it can delegate to private visit methods.
2862 friend class InstVisitor<AllocaSliceRewriter, bool>;
2863
2864 using Base = InstVisitor<AllocaSliceRewriter, bool>;
2865
2866 const DataLayout &DL;
2867 AllocaSlices &AS;
2868 SROA &Pass;
2869 AllocaInst &OldAI, &NewAI;
2870 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2871 Type *NewAllocaTy;
2872
2873 // This is a convenience and flag variable that will be null unless the new
2874 // alloca's integer operations should be widened to this integer type due to
2875 // passing isIntegerWideningViable above. If it is non-null, the desired
2876 // integer type will be stored here for easy access during rewriting.
2877 IntegerType *IntTy;
2878
2879 // If we are rewriting an alloca partition which can be written as pure
2880 // vector operations, we stash extra information here. When VecTy is
2881 // non-null, we have some strict guarantees about the rewritten alloca:
2882 // - The new alloca is exactly the size of the vector type here.
2883 // - The accesses all either map to the entire vector or to a single
2884 // element.
2885 // - The set of accessing instructions is only one of those handled above
2886 // in isVectorPromotionViable. Generally these are the same access kinds
2887 // which are promotable via mem2reg.
2888 VectorType *VecTy;
2889 Type *ElementTy;
2890 uint64_t ElementBits;
2891
2892 // The original offset of the slice currently being rewritten relative to
2893 // the original alloca.
2894 uint64_t BeginOffset = 0;
2895 uint64_t EndOffset = 0;
2896
2897 // The new offsets of the slice currently being rewritten relative to the
2898 // original alloca.
2899 uint64_t NewBeginOffset = 0, NewEndOffset = 0;
2900
2901 uint64_t SliceSize = 0;
2902 bool IsSplittable = false;
2903 bool IsSplit = false;
2904 Use *OldUse = nullptr;
2905 Instruction *OldPtr = nullptr;
2906
2907 // Track post-rewrite users which are PHI nodes and Selects.
2908 SmallSetVector<PHINode *, 8> &PHIUsers;
2909 SmallSetVector<SelectInst *, 8> &SelectUsers;
2910
2911 // Utility IR builder, whose name prefix is setup for each visited use, and
2912 // the insertion point is set to point to the user.
2913 IRBuilderTy IRB;
2914
2915 // Return the new alloca, addrspacecasted if required to avoid changing the
2916 // addrspace of a volatile access.
2917 Value *getPtrToNewAI(unsigned AddrSpace, bool IsVolatile) {
2918 if (!IsVolatile || AddrSpace == NewAI.getType()->getPointerAddressSpace())
2919 return &NewAI;
2920
2921 Type *AccessTy = IRB.getPtrTy(AddrSpace);
2922 return IRB.CreateAddrSpaceCast(&NewAI, AccessTy);
2923 }
2924
2925public:
2926 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
2927 AllocaInst &OldAI, AllocaInst &NewAI, Type *NewAllocaTy,
2928 uint64_t NewAllocaBeginOffset,
2929 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2930 VectorType *PromotableVecTy,
2931 SmallSetVector<PHINode *, 8> &PHIUsers,
2932 SmallSetVector<SelectInst *, 8> &SelectUsers)
2933 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
2934 NewAllocaBeginOffset(NewAllocaBeginOffset),
2935 NewAllocaEndOffset(NewAllocaEndOffset), NewAllocaTy(NewAllocaTy),
2936 IntTy(IsIntegerPromotable
2937 ? Type::getIntNTy(
2938 NewAI.getContext(),
2939 DL.getTypeSizeInBits(NewAllocaTy).getFixedValue())
2940 : nullptr),
2941 VecTy(PromotableVecTy),
2942 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2943 ElementBits(VecTy ? DL.getTypeSizeInBits(ElementTy).getFixedValue()
2944 : 0),
2945 PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2946 IRB(*NewAI.getModule(), ConstantFolder()) {
2947 if (VecTy) {
2948 assert((DL.getTypeSizeInBits(VecTy).getFixedValue() % 8) == 0 &&
2949 "Only vectors of whole bytes are viable");
2950 ++NumVectorized;
2951 }
2952 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
2953 }
2954
2955 bool visit(AllocaSlices::const_iterator I) {
2956 bool CanSROA = true;
2957 BeginOffset = I->beginOffset();
2958 EndOffset = I->endOffset();
2959 IsSplittable = I->isSplittable();
2960 IsSplit =
2961 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2962 LLVM_DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2963 LLVM_DEBUG(AS.printSlice(dbgs(), I, ""));
2964 LLVM_DEBUG(dbgs() << "\n");
2965
2966 // Compute the intersecting offset range.
2967 assert(BeginOffset < NewAllocaEndOffset);
2968 assert(EndOffset > NewAllocaBeginOffset);
2969 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2970 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2971
2972 SliceSize = NewEndOffset - NewBeginOffset;
2973 LLVM_DEBUG(dbgs() << " Begin:(" << BeginOffset << ", " << EndOffset
2974 << ") NewBegin:(" << NewBeginOffset << ", "
2975 << NewEndOffset << ") NewAllocaBegin:("
2976 << NewAllocaBeginOffset << ", " << NewAllocaEndOffset
2977 << ")\n");
2978 assert(IsSplit || NewBeginOffset == BeginOffset);
2979 OldUse = I->getUse();
2980 OldPtr = cast<Instruction>(OldUse->get());
2981
2982 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2983 IRB.SetInsertPoint(OldUserI);
2984 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2985 // Avoid materializing the name prefix when it is discarded anyway.
2986 if (!IRB.getContext().shouldDiscardValueNames())
2987 IRB.getInserter().SetNamePrefix(Twine(NewAI.getName()) + "." +
2988 Twine(BeginOffset) + ".");
2989
2990 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2991 if (VecTy || IntTy)
2992 assert(CanSROA);
2993 return CanSROA;
2994 }
2995
2996 /// Attempts to rewrite a partition using tree-structured merge optimization.
2997 ///
2998 /// This function handles two patterns. Both produce an O(log n) tree of
2999 /// shufflevectors in place of the linear expand+blend chain that SROA would
3000 /// otherwise emit for each partial store.
3001 ///
3002 /// Pattern 1 (stores-only):
3003 /// Multiple non-overlapping partial stores completely fill the alloca
3004 /// and there is exactly one full-width load coming after the stores.
3005 /// The stores are tree-merged into a single vector and stored once.
3006 ///
3007 /// Example transformation:
3008 /// Before: (stores do not have to be in order)
3009 /// %alloca = alloca <8 x float>
3010 /// store <2 x float> %val0, ptr %alloca ; offset 0-1
3011 /// store <2 x float> %val2, ptr %alloca+16 ; offset 4-5
3012 /// store <2 x float> %val1, ptr %alloca+8 ; offset 2-3
3013 /// store <2 x float> %val3, ptr %alloca+24 ; offset 6-7
3014 /// %r = load <8 x float>, ptr %alloca
3015 ///
3016 /// After: tree of shufflevectors producing <8 x float> directly.
3017 ///
3018 /// Pattern 2 (init + RMW, possibly multi-round):
3019 /// A single full-width init store, followed by partial loads and
3020 /// partial stores that read-modify-write the alloca one or more
3021 /// times, optionally followed by a full-width load. The only
3022 /// structural requirement is that the distinct [begin, end) ranges
3023 /// touched by the partial loads and stores, taken together, tile
3024 /// the alloca disjointly.
3025 ///
3026 /// We keep a map from each slice range to the SSA value that
3027 /// currently lives there, `SliceValues[r] -> Value*`:
3028 /// - initialize each entry to the corresponding piece of the
3029 /// init store's value (via a shufflevector picking the
3030 /// range's elements out of the init value),
3031 /// - walk partial loads and stores in block order,
3032 /// - for a partial load at range r: RAUW with `SliceValues[r]`,
3033 /// - for a partial store at range r: update `SliceValues[r]` to
3034 /// the stored value and drop the store.
3035 /// At the end, the final `SliceValues[r]` entries are tree-merged
3036 /// (in range order) into a single store to the alloca, and the
3037 /// optional full-width load is replaced by a load of the alloca.
3038 ///
3039 /// Because the ranges are disjoint by construction, a store at one
3040 /// range cannot affect another range's tracked value, so a single
3041 /// block-order walk correctly tracks the memory state at each
3042 /// range. The algorithm handles multi-round RMW, partial loads
3043 /// and stores interleaved in any order, read-only slices (the
3044 /// tracked value stays at the init extract), and write-only
3045 /// slices (the tracked value never flows into a load).
3046 ///
3047 /// \param P The partition to analyze and potentially rewrite
3048 /// \return An optional vector of values that were deleted during the
3049 /// rewrite, or std::nullopt if the partition cannot be optimized.
3050 std::optional<SmallVector<Value *, 4>>
3051 rewriteTreeStructuredMerge(Partition &P) {
3052 // No tail slices that overlap with the partition
3053 if (P.splitSliceTails().size() > 0)
3054 return std::nullopt;
3055
3056 // Structure to hold store information
3057 struct StoreInfo {
3058 StoreInst *Store;
3059 uint64_t BeginOffset;
3060 uint64_t EndOffset;
3061 Value *StoredValue;
3062 StoreInfo(StoreInst *SI, uint64_t Begin, uint64_t End, Value *Val)
3063 : Store(SI), BeginOffset(Begin), EndOffset(End), StoredValue(Val) {}
3064 };
3065 struct LoadInfo {
3066 LoadInst *Load;
3067 uint64_t BeginOffset;
3068 uint64_t EndOffset;
3069 };
3070
3071 SmallVector<StoreInfo, 4> StoreInfos; // partial stores only
3072 SmallVector<LoadInfo, 4> LoadInfos; // partial loads only
3073 LoadInst *FullLoad = nullptr; // optional full-width load
3074 StoreInst *InitStore = nullptr; // optional full-width init store
3075
3076 // If the new alloca is a fixed vector type, we use its element type as the
3077 // allocated element type, otherwise we use i8 as the allocated element
3078 Type *AllocatedEltTy =
3079 isa<FixedVectorType>(NewAllocaTy)
3080 ? cast<FixedVectorType>(NewAllocaTy)->getElementType()
3081 : Type::getInt8Ty(NewAI.getContext());
3082 unsigned AllocatedEltTySize = DL.getTypeSizeInBits(AllocatedEltTy);
3083
3084 // Helper to check if a type is
3085 // 1. A fixed vector type
3086 // 2. The element type is not a pointer
3087 // 3. The element type size is byte-aligned
3088 // We only handle the cases that the ld/st meet these conditions
3089 auto IsTypeValidForTreeStructuredMerge = [&](Type *Ty) -> bool {
3090 auto *FixedVecTy = dyn_cast<FixedVectorType>(Ty);
3091 return FixedVecTy &&
3092 DL.getTypeSizeInBits(FixedVecTy->getElementType()) % 8 == 0 &&
3093 !FixedVecTy->getElementType()->isPointerTy();
3094 };
3095
3096 for (Slice &S : P) {
3097 auto *User = cast<Instruction>(S.getUse()->getUser());
3098 // A "full-width" slice spans the entire alloca; it's either the single
3099 // init store (Pattern 2) or the single final load (both patterns).
3100 bool IsFullWidth = (S.beginOffset() == NewAllocaBeginOffset &&
3101 S.endOffset() == NewAllocaEndOffset);
3102 if (auto *LI = dyn_cast<LoadInst>(User)) {
3103 // Only handle simple (non-volatile, non-atomic) loads.
3104 if (!LI->isSimple() ||
3105 !IsTypeValidForTreeStructuredMerge(LI->getType()))
3106 return std::nullopt;
3107 if (IsFullWidth) {
3108 // We accept at most one full-width load (the "final" load, after
3109 // all the partial stores).
3110 if (FullLoad)
3111 return std::nullopt;
3112 FullLoad = LI;
3113 } else {
3114 // Partial load (RMW pattern only).
3115 LoadInfos.push_back({LI, S.beginOffset(), S.endOffset()});
3116 }
3117 } else if (auto *SI = dyn_cast<StoreInst>(User)) {
3118 // Do not handle the case if
3119 // 1. The store does not meet the conditions in the helper function
3120 // 2. The store is not simple — we drop stores as part of the
3121 // rewrite, so volatile stores (which must be kept) and atomic
3122 // stores (which carry memory-ordering semantics) are unsound
3123 // to replace with SSA bookkeeping.
3124 // 3. The total store size is not a multiple of the allocated
3125 // element type size (required so the tree merge can produce a
3126 // vector whose element type matches the alloca).
3127 if (!SI->isSimple() || !IsTypeValidForTreeStructuredMerge(
3128 SI->getValueOperand()->getType()))
3129 return std::nullopt;
3130 auto *StVecTy = cast<FixedVectorType>(SI->getValueOperand()->getType());
3131 unsigned NumElts = StVecTy->getNumElements();
3132 unsigned EltSize = DL.getTypeSizeInBits(StVecTy->getElementType());
3133 if (NumElts * EltSize % AllocatedEltTySize != 0)
3134 return std::nullopt;
3135 if (IsFullWidth) {
3136 // At most one full-width store is allowed — it's the init store
3137 // for the RMW pattern.
3138 if (InitStore)
3139 return std::nullopt;
3140 InitStore = SI;
3141 } else {
3142 StoreInfos.emplace_back(SI, S.beginOffset(), S.endOffset(),
3143 SI->getValueOperand());
3144 }
3145 } else {
3146 // If we have instructions other than load and store, we cannot do
3147 // the tree structured merge.
3148 return std::nullopt;
3149 }
3150 }
3151
3152 // Need at least two partial stores to benefit from tree-merging; a
3153 // single store is already optimal as-is. This applies to both patterns
3154 // below, so check it before classifying.
3155 if (StoreInfos.size() < 2)
3156 return std::nullopt;
3157
3158 // Classify the pattern by looking at what we collected:
3159 // Pattern 1 (stores-only): only partial stores + exactly one full load.
3160 // Pattern 2 (RMW): one full init store + partial loads + partial stores
3161 // (+ optional full final load). RMW also needs VecTy to be set
3162 // because we use getIndex() to convert byte offsets to element
3163 // indices, which requires a promoted vector alloca.
3164 bool IsRMWPattern = InitStore && VecTy && !LoadInfos.empty();
3165 bool IsStoresOnlyPattern = !InitStore && FullLoad && LoadInfos.empty();
3166 if (!IsRMWPattern && !IsStoresOnlyPattern)
3167 return std::nullopt;
3168
3169 // All partial stores must live in the same basic block — the tree merge
3170 // is built in a single BB using block-order ordering (comesBefore).
3171 BasicBlock *StoreBB = StoreInfos[0].Store->getParent();
3172 for (auto &Info : StoreInfos)
3173 if (Info.Store->getParent() != StoreBB)
3174 return std::nullopt;
3175
3176 SmallVector<Value *, 4> DeletedValues;
3177
3178 // Helper: pairwise tree-merge a list of vectors into a single vector.
3179 // At each iteration we merge each adjacent pair via mergeTwoVectors,
3180 // collect the merged values into Next, and (if Vals had odd length)
3181 // carry the trailing element through unchanged. Loop until one value
3182 // remains — the fully-merged vector.
3183 auto TreeMerge = [&](SmallVectorImpl<Value *> &Vals,
3184 IRBuilder<> &B) -> Value * {
3185 LLVM_DEBUG(dbgs() << " Rewrite stores into shufflevectors:\n");
3186 while (Vals.size() > 1) {
3187 SmallVector<Value *, 8> Next;
3188 for (unsigned I = 0, E = Vals.size(); I + 1 < E; I += 2) {
3189 Value *M =
3190 mergeTwoVectors(Vals[I], Vals[I + 1], DL, AllocatedEltTy, B);
3191 LLVM_DEBUG(dbgs() << " shufflevector: " << *M << "\n");
3192 Next.push_back(M);
3193 }
3194 if (Vals.size() % 2 == 1)
3195 Next.push_back(Vals.back());
3196 Vals = std::move(Next);
3197 }
3198 return Vals[0];
3199 };
3200
3201 // Replace a full-width load with a load of the freshly-merged alloca.
3202 // The merge stored a value of type Merged->getType() into NewAI; we load
3203 // that same type back so every access to NewAI stays consistently typed
3204 // (otherwise the alloca is no longer promotable).
3205 auto ReplaceFullLoad = [&](LoadInst *LoadToReplace, Value *Merged) {
3206 IRBuilder<> LoadBuilder(LoadToReplace);
3207 Value *NewLoad = LoadBuilder.CreateAlignedLoad(
3208 Merged->getType(), &NewAI, getSliceAlign(),
3209 LoadToReplace->isVolatile(),
3210 LoadToReplace->getName() + ".sroa.new.load");
3211 if (NewLoad->getType() != LoadToReplace->getType())
3212 NewLoad = LoadBuilder.CreateBitCast(NewLoad, LoadToReplace->getType());
3213 LoadToReplace->replaceAllUsesWith(NewLoad);
3214 DeletedValues.push_back(LoadToReplace);
3215 };
3216
3217 if (IsStoresOnlyPattern) {
3218 // Stores should not overlap and should cover the whole alloca.
3219 // Sort by begin offset to verify this with a single linear scan.
3220 llvm::sort(StoreInfos, [](const StoreInfo &A, const StoreInfo &B) {
3221 return A.BeginOffset < B.BeginOffset;
3222 });
3223 // Check for gap or overlap: each begin offset must equal the previous
3224 // end offset, i.e. the store ranges must tile [NewAllocaBeginOffset,
3225 // NewAllocaEndOffset) exactly.
3226 uint64_t Expected = NewAllocaBeginOffset;
3227 for (auto &Info : StoreInfos) {
3228 if (Info.BeginOffset != Expected)
3229 return std::nullopt;
3230 Expected = Info.EndOffset;
3231 }
3232 // Stores cover the entire alloca (no trailing gap either).
3233 if (Expected != NewAllocaEndOffset)
3234 return std::nullopt;
3235
3236 // The load should not be in the middle of the stores.
3237 // Note:
3238 // If the load is in a different basic block from the stores, we can
3239 // still do the tree-structured merge. We don't have store->load
3240 // forwarding here — the merged vector is stored back to NewAI and
3241 // the new load loads from NewAI. The forwarding will be handled
3242 // later when NewAI is promoted.
3243 BasicBlock *LoadBB = FullLoad->getParent();
3244 if (LoadBB == StoreBB) {
3245 for (auto &Info : StoreInfos)
3246 if (!Info.Store->comesBefore(FullLoad))
3247 return std::nullopt;
3248 }
3249
3250 LLVM_DEBUG({
3251 dbgs() << "Tree structured merge rewrite (stores-only):\n";
3252 dbgs() << " Load: " << *FullLoad << "\n Ordered stores:\n";
3253 for (auto [I, Info] : enumerate(StoreInfos)) {
3254 dbgs() << " [" << I << "] Range[" << Info.BeginOffset << ", "
3255 << Info.EndOffset << ") \tStore: " << *Info.Store
3256 << "\tValue: " << *Info.StoredValue << "\n";
3257 }
3258 });
3259
3260 // StoreInfos is sorted by offset, not by block order. Anchoring to
3261 // StoreInfos.back().Store (last by offset) can place shuffles before
3262 // operands that appear later in the block (invalid SSA). Insert before
3263 // FullLoad when it shares the store block (after all stores, before
3264 // any later IR in that block). Otherwise insert before the store
3265 // block's terminator so the merge runs after every store and any
3266 // trailing instructions in that block.
3267 IRBuilder<> Builder(LoadBB == StoreBB ? cast<Instruction>(FullLoad)
3268 : StoreBB->getTerminator());
3269 SmallVector<Value *, 8> Vals;
3270 for (const auto &Info : StoreInfos) {
3271 DeletedValues.push_back(Info.Store);
3272 Vals.push_back(Info.StoredValue);
3273 }
3274 // Merge all stored values and store the merged value into the alloca.
3275 Value *Merged = TreeMerge(Vals, Builder);
3276 Builder.CreateAlignedStore(Merged, &NewAI, getSliceAlign());
3277
3278 // Replace the original load with a load of the newly-merged alloca.
3279 ReplaceFullLoad(FullLoad, Merged);
3280 return DeletedValues;
3281 }
3282
3283 // RMW pattern handling starts from here.
3284 // Like StoreBB above: keep the init store, all partial loads and all
3285 // partial stores in one basic block so we can reason about ordering
3286 // with comesBefore and build SSA without PHIs.
3287 if (InitStore->getParent() != StoreBB)
3288 return std::nullopt;
3289 if (any_of(LoadInfos, [&](const LoadInfo &I) {
3290 return I.Load->getParent() != StoreBB;
3291 }))
3292 return std::nullopt;
3293 // FullLoad (if any) is allowed to live in a different basic block. See
3294 // the note on the stores-only path: we don't do store->load forwarding
3295 // directly — the merged vector is stored to NewAI and the new load
3296 // loads from NewAI, so cross-BB ordering is resolved later when NewAI
3297 // is promoted.
3298
3299 // Collect the combined partial-load/partial-store accesses sorted
3300 // by block order. Used both for ordering checks and for the rewrite
3301 // walk below.
3302 struct Access {
3303 Instruction *Inst;
3304 uint64_t BeginOffset, EndOffset;
3305 bool IsStore;
3306 };
3308 Accesses.reserve(LoadInfos.size() + StoreInfos.size());
3309 for (const auto &L : LoadInfos)
3310 Accesses.push_back({L.Load, L.BeginOffset, L.EndOffset, false});
3311 for (const auto &S : StoreInfos)
3312 Accesses.push_back({S.Store, S.BeginOffset, S.EndOffset, true});
3313 llvm::sort(Accesses, [](const Access &A, const Access &B) {
3314 return A.Inst->comesBefore(B.Inst);
3315 });
3316
3317 // Ordering constraint 1: InitStore must come before every partial
3318 // access — they read/write the RMW state initialised by InitStore.
3319 // Accesses is sorted by block order, so the first element is the
3320 // earliest; checking it is enough.
3321 if (!InitStore->comesBefore(Accesses.front().Inst))
3322 return std::nullopt;
3323 // Ordering constraint 2: when FullLoad shares the block with the
3324 // partial accesses, it must come after every one of them — otherwise
3325 // it could read a stale value. Accesses is sorted, so the last
3326 // element is the latest; checking it is enough. If FullLoad is in
3327 // another block, mem2reg forwards the merged store to it.
3328 if (FullLoad && FullLoad->getParent() == StoreBB &&
3329 !Accesses.back().Inst->comesBefore(FullLoad))
3330 return std::nullopt;
3331
3332 // Coverage check: the distinct [begin, end) ranges touched by the
3333 // partial loads and stores must tile the alloca disjointly. That is
3334 // the only precondition the per-range SliceValues tracking below
3335 // needs — a disjoint tile guarantees the entries don't alias each
3336 // other. We don't check per-range load/store counts: a range with
3337 // only loads ends with SliceValues[r] = the init extract
3338 // (contributed to the final tree-merge), and a range with only
3339 // stores ends with SliceValues[r] = its last stored value. Both are
3340 // correct.
3341 using SliceRange = std::pair<uint64_t, uint64_t>;
3342 SmallVector<SliceRange, 8> SortedRanges;
3343 SortedRanges.reserve(Accesses.size());
3344 for (auto &Acc : Accesses)
3345 SortedRanges.emplace_back(Acc.BeginOffset, Acc.EndOffset);
3346 llvm::sort(SortedRanges);
3347 SortedRanges.erase(llvm::unique(SortedRanges), SortedRanges.end());
3348 // Disjoint + contiguous tile of the whole alloca.
3349 uint64_t Expected = NewAllocaBeginOffset;
3350 for (auto &Range : SortedRanges) {
3351 if (Range.first != Expected)
3352 return std::nullopt;
3353 Expected = Range.second;
3354 }
3355 if (Expected != NewAllocaEndOffset)
3356 return std::nullopt;
3357
3358 LLVM_DEBUG({
3359 dbgs() << "Tree structured merge rewrite (RMW):\n";
3360 dbgs() << " Init store: " << *InitStore << "\n";
3361 if (FullLoad)
3362 dbgs() << " Final load: " << *FullLoad << "\n";
3363 dbgs() << " Slice ranges (" << SortedRanges.size() << "):\n";
3364 for (auto &Range : SortedRanges)
3365 dbgs() << " [" << Range.first << ", " << Range.second << ")\n";
3366 });
3367
3368 // Initialize SliceValues: one SSA value per slice range, tracking
3369 // the value the alloca currently holds at that range. Each entry
3370 // starts at the corresponding piece of the init store, obtained by
3371 // bitcasting the init value to the alloca's vector type (if needed)
3372 // and extracting the slice's sub-range.
3373 IRB.SetInsertPoint(InitStore->getNextNode());
3374 Value *InitVec = InitStore->getValueOperand();
3375 if (InitVec->getType() != NewAllocaTy)
3376 InitVec = IRB.CreateBitCast(InitVec, NewAllocaTy, "init.cast");
3377 DenseMap<SliceRange, Value *> SliceValues;
3378 for (auto &Range : SortedRanges) {
3379 unsigned BeginIdx = getIndex(Range.first);
3380 unsigned EndIdx = getIndex(Range.second);
3381 SliceValues[Range] = IRB.CreateShuffleVector(
3382 InitVec, createSequentialMask(BeginIdx, EndIdx - BeginIdx, 0),
3383 "init.extract");
3384 }
3385 // The init store itself becomes dead — its value is consumed via the
3386 // extracts above.
3387 DeletedValues.push_back(InitStore);
3388
3389 // Walk accesses in block order:
3390 // - partial load at range r: replace with SliceValues[r] (bitcast
3391 // if the load's type differs from the current tracked value's
3392 // type, e.g. because a previous store wrote a vector with a
3393 // different element type);
3394 // - partial store at range r: update SliceValues[r] to the stored
3395 // value and drop the store.
3396 for (auto &Acc : Accesses) {
3397 SliceRange Range{Acc.BeginOffset, Acc.EndOffset};
3398 if (!Acc.IsStore) {
3399 Value *V = SliceValues[Range];
3400 if (V->getType() != Acc.Inst->getType()) {
3401 IRB.SetInsertPoint(cast<LoadInst>(Acc.Inst));
3402 V = IRB.CreateBitCast(V, Acc.Inst->getType());
3403 }
3404 Acc.Inst->replaceAllUsesWith(V);
3405 } else {
3406 SliceValues[Range] = cast<StoreInst>(Acc.Inst)->getValueOperand();
3407 }
3408 DeletedValues.push_back(Acc.Inst);
3409 }
3410
3411 // Tree-merge the final per-range values (in range order) into the
3412 // alloca's final vector value. Anchor the IRBuilder to FullLoad (when it
3413 // shares the partial-access block) or otherwise to the block's
3414 // terminator — never to a partial access, since those are queued for
3415 // deletion. Both anchors are guaranteed to dominate every SliceValues
3416 // entry: each one is either an init extract (before any access) or a
3417 // stored value defined before its (now-deleted) store.
3418 IRBuilder<> Builder(FullLoad && FullLoad->getParent() == StoreBB
3419 ? cast<Instruction>(FullLoad)
3420 : StoreBB->getTerminator());
3421 SmallVector<Value *, 8> Vals;
3422 for (auto &Range : SortedRanges)
3423 Vals.push_back(SliceValues[Range]);
3424 Value *Merged = TreeMerge(Vals, Builder);
3425 Builder.CreateAlignedStore(Merged, &NewAI, getSliceAlign());
3426
3427 // Replace the optional final full-width load with a load of the newly
3428 // merged alloca. Later promotion will forward the store above to it.
3429 if (FullLoad)
3430 ReplaceFullLoad(FullLoad, Merged);
3431
3432 return DeletedValues;
3433 }
3434
3435private:
3436 // Make sure the other visit overloads are visible.
3437 using Base::visit;
3438
3439 // Every instruction which can end up as a user must have a rewrite rule.
3440 bool visitInstruction(Instruction &I) {
3441 LLVM_DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
3442 llvm_unreachable("No rewrite rule for this instruction!");
3443 }
3444
3445 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
3446 // Note that the offset computation can use BeginOffset or NewBeginOffset
3447 // interchangeably for unsplit slices.
3448 assert(IsSplit || BeginOffset == NewBeginOffset);
3449 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3450
3451 StringRef OldName = OldPtr->getName();
3452 // Skip through the last '.sroa.' component of the name.
3453 size_t LastSROAPrefix = OldName.rfind(".sroa.");
3454 if (LastSROAPrefix != StringRef::npos) {
3455 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
3456 // Look for an SROA slice index.
3457 size_t IndexEnd = OldName.find_first_not_of("0123456789");
3458 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
3459 // Strip the index and look for the offset.
3460 OldName = OldName.substr(IndexEnd + 1);
3461 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
3462 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
3463 // Strip the offset.
3464 OldName = OldName.substr(OffsetEnd + 1);
3465 }
3466 }
3467 // Strip any SROA suffixes as well.
3468 OldName = OldName.substr(0, OldName.find(".sroa_"));
3469
3470 return getAdjustedPtr(
3471 IRB, DL, &NewAI,
3472 APInt(DL.getIndexTypeSizeInBits(NewAI.getType()), Offset), PointerTy,
3473 Twine(OldName) + ".");
3474 }
3475
3476 /// Compute suitable alignment to access this slice of the *new*
3477 /// alloca.
3478 ///
3479 /// You can optionally pass a type to this routine and if that type's ABI
3480 /// alignment is itself suitable, this will return zero.
3481 Align getSliceAlign() {
3482 return commonAlignment(NewAI.getAlign(),
3483 NewBeginOffset - NewAllocaBeginOffset);
3484 }
3485
3486 unsigned getIndex(uint64_t Offset) {
3487 assert(VecTy && "Can only call getIndex when rewriting a vector");
3488 uint64_t RelBit = (Offset - NewAllocaBeginOffset) * 8;
3489 assert(RelBit / ElementBits < UINT32_MAX && "Index out of bounds");
3490 uint32_t Index = RelBit / ElementBits;
3491 assert(Index * ElementBits == RelBit);
3492 return Index;
3493 }
3494
3495 void deleteIfTriviallyDead(Value *V) {
3498 Pass.DeadInsts.push_back(I);
3499 }
3500
3501 Value *rewriteVectorizedLoadInst(LoadInst &LI) {
3502 unsigned BeginIndex = getIndex(NewBeginOffset);
3503 unsigned EndIndex = getIndex(NewEndOffset);
3504 assert(EndIndex > BeginIndex && "Empty vector!");
3505
3506 LoadInst *Load =
3507 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(), "load");
3508
3509 Load->copyMetadata(LI, {LLVMContext::MD_mem_parallel_loop_access,
3510 LLVMContext::MD_access_group});
3511 return extractVector(IRB, Load, BeginIndex, EndIndex, "vec");
3512 }
3513
3514 Value *rewriteIntegerLoad(LoadInst &LI) {
3515 assert(IntTy && "We cannot insert an integer to the alloca");
3516 assert(!LI.isVolatile());
3517 Value *V =
3518 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(), "load");
3519 V = IRB.CreateBitPreservingCastChain(DL, V, IntTy);
3520 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
3521 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3522 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
3523 IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
3524 V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
3525 }
3526 // It is possible that the extracted type is not the load type. This
3527 // happens if there is a load past the end of the alloca, and as
3528 // a consequence the slice is narrower but still a candidate for integer
3529 // lowering. To handle this case, we just zero extend the extracted
3530 // integer.
3531 assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&
3532 "Can only handle an extract for an overly wide load");
3533 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
3534 V = IRB.CreateZExt(V, LI.getType());
3535 return V;
3536 }
3537
3538 bool visitLoadInst(LoadInst &LI) {
3539 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
3540 Value *OldOp = LI.getOperand(0);
3541 assert(OldOp == OldPtr);
3542
3543 AAMDNodes AATags = LI.getAAMetadata();
3544
3545 unsigned AS = LI.getPointerAddressSpace();
3546
3547 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
3548 : LI.getType();
3549 bool IsPtrAdjusted = false;
3550 Value *V;
3551 if (VecTy) {
3552 V = rewriteVectorizedLoadInst(LI);
3553 } else if (IntTy && LI.getType()->isIntegerTy()) {
3554 V = rewriteIntegerLoad(LI);
3555 } else if (NewBeginOffset == NewAllocaBeginOffset &&
3556 NewEndOffset == NewAllocaEndOffset &&
3557 (canConvertValue(DL, NewAllocaTy, TargetTy) ||
3558 (NewAllocaTy->isIntegerTy() && TargetTy->isIntegerTy() &&
3559 DL.getTypeStoreSize(TargetTy).getFixedValue() > SliceSize &&
3560 !LI.isVolatile()))) {
3561 Value *NewPtr =
3562 getPtrToNewAI(LI.getPointerAddressSpace(), LI.isVolatile());
3563 LoadInst *NewLI = IRB.CreateAlignedLoad(
3564 NewAllocaTy, NewPtr, NewAI.getAlign(), LI.isVolatile(), LI.getName());
3565 if (LI.isVolatile())
3566 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
3567 if (NewLI->isAtomic())
3568 NewLI->setAlignment(LI.getAlign());
3569
3570 // Copy any metadata that is valid for the new load. This may require
3571 // conversion to a different kind of metadata, e.g. !nonnull might change
3572 // to !range or vice versa.
3573 copyMetadataForLoad(*NewLI, LI);
3574
3575 // Do this after copyMetadataForLoad() to preserve the TBAA shift.
3576 if (AATags)
3577 NewLI->setAAMetadata(AATags.adjustForAccess(
3578 NewBeginOffset - BeginOffset, NewLI->getType(), DL));
3579
3580 // Try to preserve nonnull metadata
3581 V = NewLI;
3582
3583 // If this is an integer load past the end of the slice (which means the
3584 // bytes outside the slice are undef or this load is dead) just forcibly
3585 // fix the integer size with correct handling of endianness.
3586 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
3587 if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
3588 if (AITy->getBitWidth() < TITy->getBitWidth()) {
3589 V = IRB.CreateZExt(V, TITy, "load.ext");
3590 if (DL.isBigEndian())
3591 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
3592 "endian_shift");
3593 }
3594 } else {
3595 Type *LTy = IRB.getPtrTy(AS);
3596 LoadInst *NewLI =
3597 IRB.CreateAlignedLoad(TargetTy, getNewAllocaSlicePtr(IRB, LTy),
3598 getSliceAlign(), LI.isVolatile(), LI.getName());
3599
3600 if (AATags)
3601 NewLI->setAAMetadata(AATags.adjustForAccess(
3602 NewBeginOffset - BeginOffset, NewLI->getType(), DL));
3603
3604 if (LI.isVolatile())
3605 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
3606 NewLI->copyMetadata(LI, {LLVMContext::MD_mem_parallel_loop_access,
3607 LLVMContext::MD_access_group});
3608
3609 V = NewLI;
3610 IsPtrAdjusted = true;
3611 }
3612 V = IRB.CreateBitPreservingCastChain(DL, V, TargetTy);
3613
3614 if (IsSplit) {
3615 assert(!LI.isVolatile());
3616 assert(LI.getType()->isIntegerTy() &&
3617 "Only integer type loads and stores are split");
3618 assert(SliceSize < DL.getTypeStoreSize(LI.getType()).getFixedValue() &&
3619 "Split load isn't smaller than original load");
3620 assert(DL.typeSizeEqualsStoreSize(LI.getType()) &&
3621 "Non-byte-multiple bit width");
3622 // Move the insertion point just past the load so that we can refer to it.
3623 BasicBlock::iterator LIIt = std::next(LI.getIterator());
3624 // Ensure the insertion point comes before any debug-info immediately
3625 // after the load, so that variable values referring to the load are
3626 // dominated by it.
3627 LIIt.setHeadBit(true);
3628 IRB.SetInsertPoint(LIIt);
3629 // Create a placeholder value with the same type as LI to use as the
3630 // basis for the new value. This allows us to replace the uses of LI with
3631 // the computed value, and then replace the placeholder with LI, leaving
3632 // LI only used for this computation.
3633 Value *Placeholder =
3634 new LoadInst(LI.getType(), PoisonValue::get(IRB.getPtrTy(AS)), "",
3635 false, Align(1));
3636 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
3637 "insert");
3639 Placeholder->replaceAllUsesWith(&LI);
3640 Placeholder->deleteValue();
3641 } else {
3643 }
3644
3645 Pass.DeadInsts.push_back(&LI);
3646 deleteIfTriviallyDead(OldOp);
3647 LLVM_DEBUG(dbgs() << " to: " << *V << "\n");
3648 return !LI.isVolatile() && !IsPtrAdjusted;
3649 }
3650
3651 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
3652 AAMDNodes AATags) {
3653 // Capture V for the purpose of debug-info accounting once it's converted
3654 // to a vector store.
3655 Value *OrigV = V;
3656 if (V->getType() != VecTy) {
3657 unsigned BeginIndex = getIndex(NewBeginOffset);
3658 unsigned EndIndex = getIndex(NewEndOffset);
3659 assert(EndIndex > BeginIndex && "Empty vector!");
3660 unsigned NumElements = EndIndex - BeginIndex;
3661 assert(NumElements <= cast<FixedVectorType>(VecTy)->getNumElements() &&
3662 "Too many elements!");
3663 Type *SliceTy = (NumElements == 1)
3664 ? ElementTy
3665 : FixedVectorType::get(ElementTy, NumElements);
3666 if (V->getType() != SliceTy)
3667 V = IRB.CreateBitPreservingCastChain(DL, V, SliceTy);
3668
3669 // Mix in the existing elements.
3670 Value *Old =
3671 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(), "load");
3672 V = insertVector(IRB, Old, V, BeginIndex, "vec");
3673 }
3674 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign());
3675 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
3676 LLVMContext::MD_access_group});
3677 if (AATags)
3678 Store->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
3679 V->getType(), DL));
3680 Pass.DeadInsts.push_back(&SI);
3681
3682 // NOTE: Careful to use OrigV rather than V.
3683 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &SI,
3684 Store, Store->getPointerOperand(), OrigV, DL);
3685 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
3686 return true;
3687 }
3688
3689 bool rewriteIntegerStore(Value *V, StoreInst &SI, AAMDNodes AATags) {
3690 assert(IntTy && "We cannot extract an integer from the alloca");
3691 assert(!SI.isVolatile());
3692 if (DL.getTypeSizeInBits(V->getType()).getFixedValue() !=
3693 IntTy->getBitWidth()) {
3694 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(),
3695 "oldload");
3696 Old = IRB.CreateBitPreservingCastChain(DL, Old, IntTy);
3697 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
3698 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
3699 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
3700 }
3701 V = IRB.CreateBitPreservingCastChain(DL, V, NewAllocaTy);
3702 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign());
3703 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
3704 LLVMContext::MD_access_group});
3705 if (AATags)
3706 Store->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
3707 V->getType(), DL));
3708
3709 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &SI,
3710 Store, Store->getPointerOperand(),
3711 Store->getValueOperand(), DL);
3712
3713 Pass.DeadInsts.push_back(&SI);
3714 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
3715 return true;
3716 }
3717
3718 bool visitStoreInst(StoreInst &SI) {
3719 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
3720 Value *OldOp = SI.getOperand(1);
3721 assert(OldOp == OldPtr);
3722
3723 AAMDNodes AATags = SI.getAAMetadata();
3724 Value *V = SI.getValueOperand();
3725
3726 // Strip all inbounds GEPs and pointer casts to try to dig out any root
3727 // alloca that should be re-examined after promoting this alloca.
3728 if (V->getType()->isPointerTy())
3729 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
3730 Pass.PostPromotionWorklist.insert(AI);
3731
3732 TypeSize StoreSize = DL.getTypeStoreSize(V->getType());
3733 if (StoreSize.isFixed() && SliceSize < StoreSize.getFixedValue()) {
3734 assert(!SI.isVolatile());
3735 assert(V->getType()->isIntegerTy() &&
3736 "Only integer type loads and stores are split");
3737 assert(DL.typeSizeEqualsStoreSize(V->getType()) &&
3738 "Non-byte-multiple bit width");
3739 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
3740 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
3741 "extract");
3742 }
3743
3744 if (VecTy)
3745 return rewriteVectorizedStoreInst(V, SI, OldOp, AATags);
3746 if (IntTy && V->getType()->isIntegerTy())
3747 return rewriteIntegerStore(V, SI, AATags);
3748
3749 StoreInst *NewSI;
3750 if (NewBeginOffset == NewAllocaBeginOffset &&
3751 NewEndOffset == NewAllocaEndOffset &&
3752 canConvertValue(DL, V->getType(), NewAllocaTy)) {
3753 V = IRB.CreateBitPreservingCastChain(DL, V, NewAllocaTy);
3754 Value *NewPtr =
3755 getPtrToNewAI(SI.getPointerAddressSpace(), SI.isVolatile());
3756
3757 NewSI =
3758 IRB.CreateAlignedStore(V, NewPtr, NewAI.getAlign(), SI.isVolatile());
3759 } else {
3760 unsigned AS = SI.getPointerAddressSpace();
3761 Value *NewPtr = getNewAllocaSlicePtr(IRB, IRB.getPtrTy(AS));
3762 NewSI =
3763 IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(), SI.isVolatile());
3764 }
3765 NewSI->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
3766 LLVMContext::MD_access_group});
3767 if (AATags)
3768 NewSI->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
3769 V->getType(), DL));
3770 if (SI.isVolatile())
3771 NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
3772 if (NewSI->isAtomic())
3773 NewSI->setAlignment(SI.getAlign());
3774
3775 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &SI,
3776 NewSI, NewSI->getPointerOperand(),
3777 NewSI->getValueOperand(), DL);
3778
3779 Pass.DeadInsts.push_back(&SI);
3780 deleteIfTriviallyDead(OldOp);
3781
3782 LLVM_DEBUG(dbgs() << " to: " << *NewSI << "\n");
3783 return NewSI->getPointerOperand() == &NewAI &&
3784 NewSI->getValueOperand()->getType() == NewAllocaTy &&
3785 !SI.isVolatile();
3786 }
3787
3788 /// Compute an integer value from splatting an i8 across the given
3789 /// number of bytes.
3790 ///
3791 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
3792 /// call this routine.
3793 /// FIXME: Heed the advice above.
3794 ///
3795 /// \param V The i8 value to splat.
3796 /// \param Size The number of bytes in the output (assuming i8 is one byte)
3797 Value *getIntegerSplat(Value *V, unsigned Size) {
3798 assert(Size > 0 && "Expected a positive number of bytes.");
3799 IntegerType *VTy = cast<IntegerType>(V->getType());
3800 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
3801 if (Size == 1)
3802 return V;
3803
3804 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
3805 V = IRB.CreateMul(
3806 IRB.CreateZExt(V, SplatIntTy, "zext"),
3807 IRB.CreateUDiv(Constant::getAllOnesValue(SplatIntTy),
3808 IRB.CreateZExt(Constant::getAllOnesValue(V->getType()),
3809 SplatIntTy)),
3810 "isplat");
3811 return V;
3812 }
3813
3814 /// Compute a vector splat for a given element value.
3815 Value *getVectorSplat(Value *V, unsigned NumElements) {
3816 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
3817 LLVM_DEBUG(dbgs() << " splat: " << *V << "\n");
3818 return V;
3819 }
3820
3821 bool visitMemSetInst(MemSetInst &II) {
3822 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
3823 assert(II.getRawDest() == OldPtr);
3824
3825 AAMDNodes AATags = II.getAAMetadata();
3826
3827 // If the memset has a variable size, it cannot be split, just adjust the
3828 // pointer to the new alloca.
3829 if (!isa<ConstantInt>(II.getLength())) {
3830 assert(!IsSplit);
3831 assert(NewBeginOffset == BeginOffset);
3832 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
3833 II.setDestAlignment(getSliceAlign());
3834 // In theory we should call migrateDebugInfo here. However, we do not
3835 // emit dbg.assign intrinsics for mem intrinsics storing through non-
3836 // constant geps, or storing a variable number of bytes.
3838 "AT: Unexpected link to non-const GEP");
3839 deleteIfTriviallyDead(OldPtr);
3840 return false;
3841 }
3842
3843 // Record this instruction for deletion.
3844 Pass.DeadInsts.push_back(&II);
3845
3846 Type *ScalarTy = NewAllocaTy->getScalarType();
3847
3848 const bool CanContinue = [&]() {
3849 if (VecTy || IntTy)
3850 return true;
3851 if (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset)
3852 return false;
3853 // Length must be in range for FixedVectorType.
3854 auto *C = cast<ConstantInt>(II.getLength());
3855 const uint64_t Len = C->getLimitedValue();
3856 if (Len > std::numeric_limits<unsigned>::max())
3857 return false;
3858 auto *Int8Ty = IntegerType::getInt8Ty(NewAI.getContext());
3859 auto *SrcTy = FixedVectorType::get(Int8Ty, Len);
3860 return canConvertValue(DL, SrcTy, NewAllocaTy) &&
3861 DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy).getFixedValue());
3862 }();
3863
3864 // If this doesn't map cleanly onto the alloca type, and that type isn't
3865 // a single value type, just emit a memset.
3866 if (!CanContinue) {
3867 Type *SizeTy = II.getLength()->getType();
3868 unsigned Sz = NewEndOffset - NewBeginOffset;
3869 Constant *Size = ConstantInt::get(SizeTy, Sz);
3870 MemIntrinsic *New = cast<MemIntrinsic>(IRB.CreateMemSet(
3871 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
3872 MaybeAlign(getSliceAlign()), II.isVolatile()));
3873 if (AATags)
3874 New->setAAMetadata(
3875 AATags.adjustForAccess(NewBeginOffset - BeginOffset, Sz));
3876
3877 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &II,
3878 New, New->getRawDest(), nullptr, DL);
3879
3880 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
3881 return false;
3882 }
3883
3884 // If we can represent this as a simple value, we have to build the actual
3885 // value to store, which requires expanding the byte present in memset to
3886 // a sensible representation for the alloca type. This is essentially
3887 // splatting the byte to a sufficiently wide integer, splatting it across
3888 // any desired vector width, and bitcasting to the final type.
3889 Value *V;
3890
3891 if (VecTy) {
3892 // If this is a memset of a vectorized alloca, insert it.
3893 assert(ElementTy == ScalarTy);
3894
3895 unsigned BeginIndex = getIndex(NewBeginOffset);
3896 unsigned EndIndex = getIndex(NewEndOffset);
3897 assert(EndIndex > BeginIndex && "Empty vector!");
3898 unsigned NumElements = EndIndex - BeginIndex;
3899 assert(NumElements <= cast<FixedVectorType>(VecTy)->getNumElements() &&
3900 "Too many elements!");
3901
3902 Value *Splat;
3903 if (ElementBits % 8) {
3904 // A byte pattern isn't a splat of sub-byte elements, so splat the
3905 // bytes the slice covers and cast them to its elements.
3906 Splat = getIntegerSplat(II.getValue(), NewEndOffset - NewBeginOffset);
3907 Splat = IRB.CreateBitPreservingCastChain(
3908 DL, Splat, FixedVectorType::get(ElementTy, NumElements));
3909 } else {
3910 Splat = getIntegerSplat(II.getValue(), ElementBits / 8);
3911 Splat = IRB.CreateBitPreservingCastChain(DL, Splat, ElementTy);
3912 if (NumElements > 1)
3913 Splat = getVectorSplat(Splat, NumElements);
3914 }
3915
3916 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(),
3917 "oldload");
3918 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
3919 } else if (IntTy) {
3920 // If this is a memset on an alloca where we can widen stores, insert the
3921 // set integer.
3922 assert(!II.isVolatile());
3923
3924 uint64_t Size = NewEndOffset - NewBeginOffset;
3925 V = getIntegerSplat(II.getValue(), Size);
3926
3927 if (IntTy && (NewBeginOffset != NewAllocaBeginOffset ||
3928 NewEndOffset != NewAllocaEndOffset)) {
3929 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI,
3930 NewAI.getAlign(), "oldload");
3931 Old = IRB.CreateBitPreservingCastChain(DL, Old, IntTy);
3932 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3933 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
3934 } else {
3935 assert(V->getType() == IntTy &&
3936 "Wrong type for an alloca wide integer!");
3937 }
3938 V = IRB.CreateBitPreservingCastChain(DL, V, NewAllocaTy);
3939 } else {
3940 // Established these invariants above.
3941 assert(NewBeginOffset == NewAllocaBeginOffset);
3942 assert(NewEndOffset == NewAllocaEndOffset);
3943
3944 V = getIntegerSplat(II.getValue(),
3945 DL.getTypeSizeInBits(ScalarTy).getFixedValue() / 8);
3946 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(NewAllocaTy))
3947 V = getVectorSplat(
3948 V, cast<FixedVectorType>(AllocaVecTy)->getNumElements());
3949
3950 V = IRB.CreateBitPreservingCastChain(DL, V, NewAllocaTy);
3951 }
3952
3953 Value *NewPtr = getPtrToNewAI(II.getDestAddressSpace(), II.isVolatile());
3954 StoreInst *New =
3955 IRB.CreateAlignedStore(V, NewPtr, NewAI.getAlign(), II.isVolatile());
3956 New->copyMetadata(II, {LLVMContext::MD_mem_parallel_loop_access,
3957 LLVMContext::MD_access_group});
3958 if (AATags)
3959 New->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
3960 V->getType(), DL));
3961
3962 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &II,
3963 New, New->getPointerOperand(), V, DL);
3964
3965 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
3966 return !II.isVolatile();
3967 }
3968
3969 bool visitMemTransferInst(MemTransferInst &II) {
3970 // Rewriting of memory transfer instructions can be a bit tricky. We break
3971 // them into two categories: split intrinsics and unsplit intrinsics.
3972
3973 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
3974
3975 AAMDNodes AATags = II.getAAMetadata();
3976
3977 bool IsDest = &II.getRawDestUse() == OldUse;
3978 assert((IsDest && II.getRawDest() == OldPtr) ||
3979 (!IsDest && II.getRawSource() == OldPtr));
3980
3981 Align SliceAlign = getSliceAlign();
3982 // For unsplit intrinsics, we simply modify the source and destination
3983 // pointers in place. This isn't just an optimization, it is a matter of
3984 // correctness. With unsplit intrinsics we may be dealing with transfers
3985 // within a single alloca before SROA ran, or with transfers that have
3986 // a variable length. We may also be dealing with memmove instead of
3987 // memcpy, and so simply updating the pointers is the necessary for us to
3988 // update both source and dest of a single call.
3989 if (!IsSplittable) {
3990 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3991 if (IsDest) {
3992 // Update the address component of linked dbg.assigns.
3993 for (DbgVariableRecord *DbgAssign : at::getDVRAssignmentMarkers(&II)) {
3994 if (llvm::is_contained(DbgAssign->location_ops(), II.getDest()) ||
3995 DbgAssign->getAddress() == II.getDest())
3996 DbgAssign->replaceVariableLocationOp(II.getDest(), AdjustedPtr);
3997 }
3998 II.setDest(AdjustedPtr);
3999 II.setDestAlignment(SliceAlign);
4000 } else {
4001 II.setSource(AdjustedPtr);
4002 II.setSourceAlignment(SliceAlign);
4003 }
4004
4005 LLVM_DEBUG(dbgs() << " to: " << II << "\n");
4006 deleteIfTriviallyDead(OldPtr);
4007 return false;
4008 }
4009 // For split transfer intrinsics we have an incredibly useful assurance:
4010 // the source and destination do not reside within the same alloca, and at
4011 // least one of them does not escape. This means that we can replace
4012 // memmove with memcpy, and we don't need to worry about all manner of
4013 // downsides to splitting and transforming the operations.
4014
4015 // If this doesn't map cleanly onto the alloca type, and that type isn't
4016 // a single value type, just emit a memcpy.
4017 bool EmitMemCpy =
4018 !VecTy && !IntTy &&
4019 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
4020 SliceSize != DL.getTypeStoreSize(NewAllocaTy).getFixedValue() ||
4021 !DL.typeSizeEqualsStoreSize(NewAllocaTy) ||
4022 !NewAllocaTy->isSingleValueType());
4023
4024 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
4025 // size hasn't been shrunk based on analysis of the viable range, this is
4026 // a no-op.
4027 if (EmitMemCpy && &OldAI == &NewAI) {
4028 // Ensure the start lines up.
4029 assert(NewBeginOffset == BeginOffset);
4030
4031 // Rewrite the size as needed.
4032 if (NewEndOffset != EndOffset)
4033 II.setLength(NewEndOffset - NewBeginOffset);
4034 return false;
4035 }
4036 // Record this instruction for deletion.
4037 Pass.DeadInsts.push_back(&II);
4038
4039 // Strip all inbounds GEPs and pointer casts to try to dig out any root
4040 // alloca that should be re-examined after rewriting this instruction.
4041 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
4042 if (AllocaInst *AI =
4044 assert(AI != &OldAI && AI != &NewAI &&
4045 "Splittable transfers cannot reach the same alloca on both ends.");
4046 Pass.Worklist.insert(AI);
4047 }
4048
4049 Type *OtherPtrTy = OtherPtr->getType();
4050 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
4051
4052 // Compute the relative offset for the other pointer within the transfer.
4053 unsigned OffsetWidth = DL.getIndexSizeInBits(OtherAS);
4054 APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset);
4055 Align OtherAlign =
4056 (IsDest ? II.getSourceAlign() : II.getDestAlign()).valueOrOne();
4057 OtherAlign =
4058 commonAlignment(OtherAlign, OtherOffset.zextOrTrunc(64).getZExtValue());
4059
4060 if (EmitMemCpy) {
4061 // Compute the other pointer, folding as much as possible to produce
4062 // a single, simple GEP in most cases.
4063 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
4064 OtherPtr->getName() + ".");
4065
4066 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
4067 Type *SizeTy = II.getLength()->getType();
4068 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
4069
4070 Value *DestPtr, *SrcPtr;
4071 MaybeAlign DestAlign, SrcAlign;
4072 // Note: IsDest is true iff we're copying into the new alloca slice
4073 if (IsDest) {
4074 DestPtr = OurPtr;
4075 DestAlign = SliceAlign;
4076 SrcPtr = OtherPtr;
4077 SrcAlign = OtherAlign;
4078 } else {
4079 DestPtr = OtherPtr;
4080 DestAlign = OtherAlign;
4081 SrcPtr = OurPtr;
4082 SrcAlign = SliceAlign;
4083 }
4084 CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign,
4085 Size, II.isVolatile());
4086 if (AATags)
4087 New->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
4088
4089 APInt Offset(DL.getIndexTypeSizeInBits(DestPtr->getType()), 0);
4090 if (IsDest) {
4091 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8,
4092 &II, New, DestPtr, nullptr, DL);
4093 } else if (AllocaInst *Base = dyn_cast<AllocaInst>(
4095 DL, Offset, /*AllowNonInbounds*/ true))) {
4096 migrateDebugInfo(Base, IsSplit, Offset.getZExtValue() * 8,
4097 SliceSize * 8, &II, New, DestPtr, nullptr, DL);
4098 }
4099 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
4100 return false;
4101 }
4102
4103 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
4104 NewEndOffset == NewAllocaEndOffset;
4105 uint64_t Size = NewEndOffset - NewBeginOffset;
4106 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
4107 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
4108 unsigned NumElements = EndIndex - BeginIndex;
4109 IntegerType *SubIntTy =
4110 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
4111
4112 // Reset the other pointer type to match the register type we're going to
4113 // use, but using the address space of the original other pointer.
4114 Type *OtherTy;
4115 if (VecTy && !IsWholeAlloca) {
4116 if (NumElements == 1)
4117 OtherTy = VecTy->getElementType();
4118 else
4119 OtherTy = FixedVectorType::get(VecTy->getElementType(), NumElements);
4120 } else if (IntTy && !IsWholeAlloca) {
4121 OtherTy = SubIntTy;
4122 } else {
4123 OtherTy = NewAllocaTy;
4124 }
4125
4126 Value *AdjPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
4127 OtherPtr->getName() + ".");
4128 MaybeAlign SrcAlign = OtherAlign;
4129 MaybeAlign DstAlign = SliceAlign;
4130 if (!IsDest)
4131 std::swap(SrcAlign, DstAlign);
4132
4133 Value *SrcPtr;
4134 Value *DstPtr;
4135
4136 if (IsDest) {
4137 DstPtr = getPtrToNewAI(II.getDestAddressSpace(), II.isVolatile());
4138 SrcPtr = AdjPtr;
4139 } else {
4140 DstPtr = AdjPtr;
4141 SrcPtr = getPtrToNewAI(II.getSourceAddressSpace(), II.isVolatile());
4142 }
4143
4144 Value *Src;
4145 if (VecTy && !IsWholeAlloca && !IsDest) {
4146 Src =
4147 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(), "load");
4148 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
4149 } else if (IntTy && !IsWholeAlloca && !IsDest) {
4150 Src =
4151 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(), "load");
4152 Src = IRB.CreateBitPreservingCastChain(DL, Src, IntTy);
4153 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
4154 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
4155 } else {
4156 LoadInst *Load = IRB.CreateAlignedLoad(OtherTy, SrcPtr, SrcAlign,
4157 II.isVolatile(), "copyload");
4158 Load->copyMetadata(II, {LLVMContext::MD_mem_parallel_loop_access,
4159 LLVMContext::MD_access_group});
4160 if (AATags)
4161 Load->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
4162 Load->getType(), DL));
4163 Src = Load;
4164 }
4165
4166 if (VecTy && !IsWholeAlloca && IsDest) {
4167 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(),
4168 "oldload");
4169 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
4170 } else if (IntTy && !IsWholeAlloca && IsDest) {
4171 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(),
4172 "oldload");
4173 Old = IRB.CreateBitPreservingCastChain(DL, Old, IntTy);
4174 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
4175 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
4176 Src = IRB.CreateBitPreservingCastChain(DL, Src, NewAllocaTy);
4177 }
4178
4179 StoreInst *Store = cast<StoreInst>(
4180 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
4181 Store->copyMetadata(II, {LLVMContext::MD_mem_parallel_loop_access,
4182 LLVMContext::MD_access_group});
4183 if (AATags)
4184 Store->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
4185 Src->getType(), DL));
4186
4187 APInt Offset(DL.getIndexTypeSizeInBits(DstPtr->getType()), 0);
4188 if (IsDest) {
4189
4190 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &II,
4191 Store, DstPtr, Src, DL);
4192 } else if (AllocaInst *Base = dyn_cast<AllocaInst>(
4194 DL, Offset, /*AllowNonInbounds*/ true))) {
4195 migrateDebugInfo(Base, IsSplit, Offset.getZExtValue() * 8, SliceSize * 8,
4196 &II, Store, DstPtr, Src, DL);
4197 }
4198
4199 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
4200 return !II.isVolatile();
4201 }
4202
4203 bool visitIntrinsicInst(IntrinsicInst &II) {
4204 assert((II.isLifetimeStartOrEnd() || II.isDroppable()) &&
4205 "Unexpected intrinsic!");
4206 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
4207
4208 // Record this instruction for deletion.
4209 Pass.DeadInsts.push_back(&II);
4210
4211 if (II.isDroppable()) {
4212 assert(II.getIntrinsicID() == Intrinsic::assume && "Expected assume");
4213 // TODO For now we forget assumed information, this can be improved.
4214 OldPtr->dropDroppableUsesIn(II);
4215 return true;
4216 }
4217
4218 assert(II.getArgOperand(0) == OldPtr);
4219 Type *PointerTy = IRB.getPtrTy(OldPtr->getType()->getPointerAddressSpace());
4220 Value *Ptr = getNewAllocaSlicePtr(IRB, PointerTy);
4221 Value *New;
4222 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
4223 New = IRB.CreateLifetimeStart(Ptr);
4224 else
4225 New = IRB.CreateLifetimeEnd(Ptr);
4226
4227 (void)New;
4228 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
4229
4230 return true;
4231 }
4232
4233 void fixLoadStoreAlign(Instruction &Root) {
4234 // This algorithm implements the same visitor loop as
4235 // hasUnsafePHIOrSelectUse, and fixes the alignment of each load
4236 // or store found.
4237 SmallPtrSet<Instruction *, 4> Visited;
4238 SmallVector<Instruction *, 4> Uses;
4239 Visited.insert(&Root);
4240 Uses.push_back(&Root);
4241 do {
4242 Instruction *I = Uses.pop_back_val();
4243
4244 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4245 LI->setAlignment(std::min(LI->getAlign(), getSliceAlign()));
4246 continue;
4247 }
4248 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
4249 SI->setAlignment(std::min(SI->getAlign(), getSliceAlign()));
4250 continue;
4251 }
4252
4256 for (User *U : I->users())
4257 if (Visited.insert(cast<Instruction>(U)).second)
4258 Uses.push_back(cast<Instruction>(U));
4259 } while (!Uses.empty());
4260 }
4261
4262 bool visitPHINode(PHINode &PN) {
4263 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
4264 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
4265 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
4266
4267 // We would like to compute a new pointer in only one place, but have it be
4268 // as local as possible to the PHI. To do that, we re-use the location of
4269 // the old pointer, which necessarily must be in the right position to
4270 // dominate the PHI.
4271 IRBuilderBase::InsertPointGuard Guard(IRB);
4272 if (isa<PHINode>(OldPtr))
4273 IRB.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
4274 else
4275 IRB.SetInsertPoint(OldPtr);
4276 IRB.SetCurrentDebugLocation(OldPtr->getDebugLoc());
4277
4278 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
4279 // Replace the operands which were using the old pointer.
4280 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
4281
4282 LLVM_DEBUG(dbgs() << " to: " << PN << "\n");
4283 deleteIfTriviallyDead(OldPtr);
4284
4285 // Fix the alignment of any loads or stores using this PHI node.
4286 fixLoadStoreAlign(PN);
4287
4288 // PHIs can't be promoted on their own, but often can be speculated. We
4289 // check the speculation outside of the rewriter so that we see the
4290 // fully-rewritten alloca.
4291 PHIUsers.insert(&PN);
4292 return true;
4293 }
4294
4295 bool visitSelectInst(SelectInst &SI) {
4296 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
4297 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
4298 "Pointer isn't an operand!");
4299 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
4300 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
4301
4302 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
4303 // Replace the operands which were using the old pointer.
4304 if (SI.getOperand(1) == OldPtr)
4305 SI.setOperand(1, NewPtr);
4306 if (SI.getOperand(2) == OldPtr)
4307 SI.setOperand(2, NewPtr);
4308
4309 LLVM_DEBUG(dbgs() << " to: " << SI << "\n");
4310 deleteIfTriviallyDead(OldPtr);
4311
4312 // Fix the alignment of any loads or stores using this select.
4313 fixLoadStoreAlign(SI);
4314
4315 // Selects can't be promoted on their own, but often can be speculated. We
4316 // check the speculation outside of the rewriter so that we see the
4317 // fully-rewritten alloca.
4318 SelectUsers.insert(&SI);
4319 return true;
4320 }
4321};
4322
4323/// Visitor to rewrite aggregate loads and stores as scalar.
4324///
4325/// This pass aggressively rewrites all aggregate loads and stores on
4326/// a particular pointer (or any pointer derived from it which we can identify)
4327/// with scalar loads and stores.
4328class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
4329 // Befriend the base class so it can delegate to private visit methods.
4330 friend class InstVisitor<AggLoadStoreRewriter, bool>;
4331
4332 /// Queue of pointer uses to analyze and potentially rewrite.
4334
4335 /// Set to prevent us from cycling with phi nodes and loops.
4336 SmallPtrSet<User *, 8> Visited;
4337
4338 /// The current pointer use being rewritten. This is used to dig up the used
4339 /// value (as opposed to the user).
4340 Use *U = nullptr;
4341
4342 /// Used to calculate offsets, and hence alignment, of subobjects.
4343 const DataLayout &DL;
4344
4345 IRBuilderTy &IRB;
4346
4347public:
4348 AggLoadStoreRewriter(const DataLayout &DL, IRBuilderTy &IRB)
4349 : DL(DL), IRB(IRB) {}
4350
4351 /// Rewrite loads and stores through a pointer and all pointers derived from
4352 /// it.
4353 bool rewrite(Instruction &I) {
4354 LLVM_DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
4355 enqueueUsers(I);
4356 bool Changed = false;
4357 while (!Queue.empty()) {
4358 U = Queue.pop_back_val();
4359 Changed |= visit(cast<Instruction>(U->getUser()));
4360 }
4361 return Changed;
4362 }
4363
4364private:
4365 /// Enqueue all the users of the given instruction for further processing.
4366 /// This uses a set to de-duplicate users.
4367 void enqueueUsers(Instruction &I) {
4368 for (Use &U : I.uses())
4369 if (Visited.insert(U.getUser()).second)
4370 Queue.push_back(&U);
4371 }
4372
4373 // Conservative default is to not rewrite anything.
4374 bool visitInstruction(Instruction &I) { return false; }
4375
4376 /// Generic recursive split emission class.
4377 template <typename Derived> class OpSplitter {
4378 protected:
4379 /// The builder used to form new instructions.
4380 IRBuilderTy &IRB;
4381
4382 /// The indices which to be used with insert- or extractvalue to select the
4383 /// appropriate value within the aggregate.
4384 SmallVector<unsigned, 4> Indices;
4385
4386 /// The indices to a GEP instruction which will move Ptr to the correct slot
4387 /// within the aggregate.
4388 SmallVector<Value *, 4> GEPIndices;
4389
4390 /// The base pointer of the original op, used as a base for GEPing the
4391 /// split operations.
4392 Value *Ptr;
4393
4394 /// The base pointee type being GEPed into.
4395 Type *BaseTy;
4396
4397 /// Known alignment of the base pointer.
4398 Align BaseAlign;
4399
4400 /// To calculate offset of each component so we can correctly deduce
4401 /// alignments.
4402 const DataLayout &DL;
4403
4404 /// Initialize the splitter with an insertion point, Ptr and start with a
4405 /// single zero GEP index.
4406 OpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
4407 Align BaseAlign, const DataLayout &DL, IRBuilderTy &IRB)
4408 : IRB(IRB), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr), BaseTy(BaseTy),
4409 BaseAlign(BaseAlign), DL(DL) {
4410 IRB.SetInsertPoint(InsertionPoint);
4411 }
4412
4413 public:
4414 /// Generic recursive split emission routine.
4415 ///
4416 /// This method recursively splits an aggregate op (load or store) into
4417 /// scalar or vector ops. It splits recursively until it hits a single value
4418 /// and emits that single value operation via the template argument.
4419 ///
4420 /// The logic of this routine relies on GEPs and insertvalue and
4421 /// extractvalue all operating with the same fundamental index list, merely
4422 /// formatted differently (GEPs need actual values).
4423 ///
4424 /// \param Ty The type being split recursively into smaller ops.
4425 /// \param Agg The aggregate value being built up or stored, depending on
4426 /// whether this is splitting a load or a store respectively.
4427 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
4428 if (Ty->isSingleValueType()) {
4429 unsigned Offset = DL.getIndexedOffsetInType(BaseTy, GEPIndices);
4430 return static_cast<Derived *>(this)->emitFunc(
4431 Ty, Agg, commonAlignment(BaseAlign, Offset), Name);
4432 }
4433
4434 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
4435 unsigned OldSize = Indices.size();
4436 (void)OldSize;
4437 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
4438 ++Idx) {
4439 assert(Indices.size() == OldSize && "Did not return to the old size");
4440 Indices.push_back(Idx);
4441 GEPIndices.push_back(IRB.getInt32(Idx));
4442 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
4443 GEPIndices.pop_back();
4444 Indices.pop_back();
4445 }
4446 return;
4447 }
4448
4449 if (StructType *STy = dyn_cast<StructType>(Ty)) {
4450 unsigned OldSize = Indices.size();
4451 (void)OldSize;
4452 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
4453 ++Idx) {
4454 assert(Indices.size() == OldSize && "Did not return to the old size");
4455 Indices.push_back(Idx);
4456 GEPIndices.push_back(IRB.getInt32(Idx));
4457 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
4458 GEPIndices.pop_back();
4459 Indices.pop_back();
4460 }
4461 return;
4462 }
4463
4464 llvm_unreachable("Only arrays and structs are aggregate loadable types");
4465 }
4466 };
4467
4468 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
4469 AAMDNodes AATags;
4470 // A vector to hold the split components that we want to emit
4471 // separate fake uses for.
4472 SmallVector<Value *, 4> Components;
4473 // A vector to hold all the fake uses of the struct that we are splitting.
4474 // Usually there should only be one, but we are handling the general case.
4476
4477 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
4478 AAMDNodes AATags, Align BaseAlign, const DataLayout &DL,
4479 IRBuilderTy &IRB)
4480 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign, DL,
4481 IRB),
4482 AATags(AATags) {}
4483
4484 /// Emit a leaf load of a single value. This is called at the leaves of the
4485 /// recursive emission to actually load values.
4486 void emitFunc(Type *Ty, Value *&Agg, Align Alignment, const Twine &Name) {
4488 // Load the single value and insert it using the indices.
4489 Value *GEP =
4490 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
4491 LoadInst *Load =
4492 IRB.CreateAlignedLoad(Ty, GEP, Alignment, Name + ".load");
4493
4494 APInt Offset(
4495 DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace()), 0);
4496 if (AATags &&
4497 GEPOperator::accumulateConstantOffset(BaseTy, GEPIndices, DL, Offset))
4498 Load->setAAMetadata(
4499 AATags.adjustForAccess(Offset.getZExtValue(), Load->getType(), DL));
4500 // Record the load so we can generate a fake use for this aggregate
4501 // component.
4502 Components.push_back(Load);
4503
4504 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
4505 LLVM_DEBUG(dbgs() << " to: " << *Load << "\n");
4506 }
4507
4508 // Stash the fake uses that use the value generated by this instruction.
4509 void recordFakeUses(LoadInst &LI) {
4510 for (Use &U : LI.uses())
4511 if (auto *II = dyn_cast<IntrinsicInst>(U.getUser()))
4512 if (II->getIntrinsicID() == Intrinsic::fake_use)
4513 FakeUses.push_back(II);
4514 }
4515
4516 // Replace all fake uses of the aggregate with a series of fake uses, one
4517 // for each split component.
4518 void emitFakeUses() {
4519 for (Instruction *I : FakeUses) {
4520 IRB.SetInsertPoint(I);
4521 for (auto *V : Components)
4522 IRB.CreateIntrinsic(Intrinsic::fake_use, {V});
4523 I->eraseFromParent();
4524 }
4525 }
4526 };
4527
4528 bool visitLoadInst(LoadInst &LI) {
4529 assert(LI.getPointerOperand() == *U);
4530 if (!LI.isSimple() || LI.getType()->isSingleValueType())
4531 return false;
4532
4533 // We have an aggregate being loaded, split it apart.
4534 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
4535 LoadOpSplitter Splitter(&LI, *U, LI.getType(), LI.getAAMetadata(),
4536 getAdjustedAlignment(&LI, 0), DL, IRB);
4537 Splitter.recordFakeUses(LI);
4539 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
4540 Splitter.emitFakeUses();
4541 Visited.erase(&LI);
4543 LI.eraseFromParent();
4544 return true;
4545 }
4546
4547 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
4548 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
4549 AAMDNodes AATags, StoreInst *AggStore, Align BaseAlign,
4550 const DataLayout &DL, IRBuilderTy &IRB)
4551 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
4552 DL, IRB),
4553 AATags(AATags), AggStore(AggStore) {}
4554 AAMDNodes AATags;
4555 StoreInst *AggStore;
4556 /// Emit a leaf store of a single value. This is called at the leaves of the
4557 /// recursive emission to actually produce stores.
4558 void emitFunc(Type *Ty, Value *&Agg, Align Alignment, const Twine &Name) {
4560 // Extract the single value and store it using the indices.
4561 //
4562 // The gep and extractvalue values are factored out of the CreateStore
4563 // call to make the output independent of the argument evaluation order.
4564 Value *ExtractValue =
4565 IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
4566 Value *InBoundsGEP =
4567 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
4568 StoreInst *Store =
4569 IRB.CreateAlignedStore(ExtractValue, InBoundsGEP, Alignment);
4570
4571 APInt Offset(
4572 DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace()), 0);
4573 GEPOperator::accumulateConstantOffset(BaseTy, GEPIndices, DL, Offset);
4574 if (AATags) {
4575 Store->setAAMetadata(AATags.adjustForAccess(
4576 Offset.getZExtValue(), ExtractValue->getType(), DL));
4577 }
4578
4579 // migrateDebugInfo requires the base Alloca. Walk to it from this gep.
4580 // If we cannot (because there's an intervening non-const or unbounded
4581 // gep) then we wouldn't expect to see dbg.assign intrinsics linked to
4582 // this instruction.
4584 if (auto *OldAI = dyn_cast<AllocaInst>(Base)) {
4585 uint64_t SizeInBits =
4586 DL.getTypeSizeInBits(Store->getValueOperand()->getType());
4587 migrateDebugInfo(OldAI, /*IsSplit*/ true, Offset.getZExtValue() * 8,
4588 SizeInBits, AggStore, Store,
4589 Store->getPointerOperand(), Store->getValueOperand(),
4590 DL);
4591 } else {
4593 "AT: unexpected debug.assign linked to store through "
4594 "unbounded GEP");
4595 }
4596 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
4597 }
4598 };
4599
4600 bool visitStoreInst(StoreInst &SI) {
4601 if (!SI.isSimple() || SI.getPointerOperand() != *U)
4602 return false;
4603 Value *V = SI.getValueOperand();
4604 if (V->getType()->isSingleValueType())
4605 return false;
4606
4607 // We have an aggregate being stored, split it apart.
4608 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
4609 StoreOpSplitter Splitter(&SI, *U, V->getType(), SI.getAAMetadata(), &SI,
4610 getAdjustedAlignment(&SI, 0), DL, IRB);
4611 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
4612 Visited.erase(&SI);
4613 // The stores replacing SI each have markers describing fragments of the
4614 // assignment so delete the assignment markers linked to SI.
4616 SI.eraseFromParent();
4617 return true;
4618 }
4619
4620 bool visitBitCastInst(BitCastInst &BC) {
4621 enqueueUsers(BC);
4622 return false;
4623 }
4624
4625 bool visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
4626 enqueueUsers(ASC);
4627 return false;
4628 }
4629
4630 // Unfold gep (select cond, ptr1, ptr2), idx
4631 // => select cond, gep(ptr1, idx), gep(ptr2, idx)
4632 // and gep ptr, (select cond, idx1, idx2)
4633 // => select cond, gep(ptr, idx1), gep(ptr, idx2)
4634 // We also allow for i1 zext indices, which are equivalent to selects.
4635 bool unfoldGEPSelect(GetElementPtrInst &GEPI) {
4636 // Check whether the GEP has exactly one select operand and all indices
4637 // will become constant after the transform.
4639 for (Value *Op : GEPI.indices()) {
4640 if (auto *SI = dyn_cast<SelectInst>(Op)) {
4641 if (Sel)
4642 return false;
4643
4644 Sel = SI;
4645 if (!isa<ConstantInt>(SI->getTrueValue()) ||
4646 !isa<ConstantInt>(SI->getFalseValue()))
4647 return false;
4648 continue;
4649 }
4650 if (auto *ZI = dyn_cast<ZExtInst>(Op)) {
4651 if (Sel)
4652 return false;
4653 Sel = ZI;
4654 if (!ZI->getSrcTy()->isIntegerTy(1))
4655 return false;
4656 continue;
4657 }
4658
4659 if (!isa<ConstantInt>(Op))
4660 return false;
4661 }
4662
4663 if (!Sel)
4664 return false;
4665
4666 LLVM_DEBUG(dbgs() << " Rewriting gep(select) -> select(gep):\n";
4667 dbgs() << " original: " << *Sel << "\n";
4668 dbgs() << " " << GEPI << "\n";);
4669
4670 auto GetNewOps = [&](Value *SelOp) {
4671 SmallVector<Value *> NewOps;
4672 for (Value *Op : GEPI.operands())
4673 if (Op == Sel)
4674 NewOps.push_back(SelOp);
4675 else
4676 NewOps.push_back(Op);
4677 return NewOps;
4678 };
4679
4680 Value *Cond, *True, *False;
4681 Instruction *MDFrom = nullptr;
4682 if (auto *SI = dyn_cast<SelectInst>(Sel)) {
4683 Cond = SI->getCondition();
4684 True = SI->getTrueValue();
4685 False = SI->getFalseValue();
4686 MDFrom = SI;
4687 } else {
4688 Cond = Sel->getOperand(0);
4689 True = ConstantInt::get(Sel->getType(), 1);
4690 False = ConstantInt::get(Sel->getType(), 0);
4691 }
4692 SmallVector<Value *> TrueOps = GetNewOps(True);
4693 SmallVector<Value *> FalseOps = GetNewOps(False);
4694
4695 IRB.SetInsertPoint(&GEPI);
4696 GEPNoWrapFlags NW = GEPI.getNoWrapFlags();
4697
4698 Type *Ty = GEPI.getSourceElementType();
4699 Value *NTrue = IRB.CreateGEP(Ty, TrueOps[0], ArrayRef(TrueOps).drop_front(),
4700 True->getName() + ".sroa.gep", NW);
4701
4702 Value *NFalse =
4703 IRB.CreateGEP(Ty, FalseOps[0], ArrayRef(FalseOps).drop_front(),
4704 False->getName() + ".sroa.gep", NW);
4705
4706 Value *NSel = MDFrom
4707 ? IRB.CreateSelect(Cond, NTrue, NFalse,
4708 Sel->getName() + ".sroa.sel", MDFrom)
4709 : IRB.CreateSelectWithUnknownProfile(
4710 Cond, NTrue, NFalse, DEBUG_TYPE,
4711 Sel->getName() + ".sroa.sel");
4712 Visited.erase(&GEPI);
4713 GEPI.replaceAllUsesWith(NSel);
4714 GEPI.eraseFromParent();
4715 Instruction *NSelI = cast<Instruction>(NSel);
4716 Visited.insert(NSelI);
4717 enqueueUsers(*NSelI);
4718
4719 LLVM_DEBUG(dbgs() << " to: " << *NTrue << "\n";
4720 dbgs() << " " << *NFalse << "\n";
4721 dbgs() << " " << *NSel << "\n";);
4722
4723 return true;
4724 }
4725
4726 // Unfold gep (phi ptr1, ptr2), idx
4727 // => phi ((gep ptr1, idx), (gep ptr2, idx))
4728 // and gep ptr, (phi idx1, idx2)
4729 // => phi ((gep ptr, idx1), (gep ptr, idx2))
4730 bool unfoldGEPPhi(GetElementPtrInst &GEPI) {
4731 // To prevent infinitely expanding recursive phis, bail if the GEP pointer
4732 // operand (looking through the phi if it is the phi we want to unfold) is
4733 // an instruction besides a static alloca.
4734 PHINode *Phi = dyn_cast<PHINode>(GEPI.getPointerOperand());
4735 auto IsInvalidPointerOperand = [](Value *V) {
4736 if (!isa<Instruction>(V))
4737 return false;
4738 if (auto *AI = dyn_cast<AllocaInst>(V))
4739 return !AI->isStaticAlloca();
4740 return true;
4741 };
4742 if (Phi) {
4743 if (any_of(Phi->operands(), IsInvalidPointerOperand))
4744 return false;
4745 } else {
4746 if (IsInvalidPointerOperand(GEPI.getPointerOperand()))
4747 return false;
4748 }
4749 // Check whether the GEP has exactly one phi operand (including the pointer
4750 // operand) and all indices will become constant after the transform.
4751 for (Value *Op : GEPI.indices()) {
4752 if (auto *SI = dyn_cast<PHINode>(Op)) {
4753 if (Phi)
4754 return false;
4755
4756 Phi = SI;
4757 if (!all_of(Phi->incoming_values(),
4758 [](Value *V) { return isa<ConstantInt>(V); }))
4759 return false;
4760 continue;
4761 }
4762
4763 if (!isa<ConstantInt>(Op))
4764 return false;
4765 }
4766
4767 if (!Phi)
4768 return false;
4769
4770 LLVM_DEBUG(dbgs() << " Rewriting gep(phi) -> phi(gep):\n";
4771 dbgs() << " original: " << *Phi << "\n";
4772 dbgs() << " " << GEPI << "\n";);
4773
4774 auto GetNewOps = [&](Value *PhiOp) {
4775 SmallVector<Value *> NewOps;
4776 for (Value *Op : GEPI.operands())
4777 if (Op == Phi)
4778 NewOps.push_back(PhiOp);
4779 else
4780 NewOps.push_back(Op);
4781 return NewOps;
4782 };
4783
4784 IRB.SetInsertPoint(Phi);
4785 PHINode *NewPhi = IRB.CreatePHI(GEPI.getType(), Phi->getNumIncomingValues(),
4786 Phi->getName() + ".sroa.phi");
4787
4788 Type *SourceTy = GEPI.getSourceElementType();
4789 // We only handle arguments, constants, and static allocas here, so we can
4790 // insert GEPs at the end of the entry block.
4791 IRB.SetInsertPoint(GEPI.getFunction()->getEntryBlock().getTerminator());
4792 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
4793 Value *Op = Phi->getIncomingValue(I);
4794 BasicBlock *BB = Phi->getIncomingBlock(I);
4795 Value *NewGEP;
4796 if (int NI = NewPhi->getBasicBlockIndex(BB); NI >= 0) {
4797 NewGEP = NewPhi->getIncomingValue(NI);
4798 } else {
4799 SmallVector<Value *> NewOps = GetNewOps(Op);
4800 NewGEP =
4801 IRB.CreateGEP(SourceTy, NewOps[0], ArrayRef(NewOps).drop_front(),
4802 Phi->getName() + ".sroa.gep", GEPI.getNoWrapFlags());
4803 }
4804 NewPhi->addIncoming(NewGEP, BB);
4805 }
4806
4807 Visited.erase(&GEPI);
4808 GEPI.replaceAllUsesWith(NewPhi);
4809 GEPI.eraseFromParent();
4810 Visited.insert(NewPhi);
4811 enqueueUsers(*NewPhi);
4812
4813 LLVM_DEBUG(dbgs() << " to: ";
4814 for (Value *In
4815 : NewPhi->incoming_values()) dbgs()
4816 << "\n " << *In;
4817 dbgs() << "\n " << *NewPhi << '\n');
4818
4819 return true;
4820 }
4821
4822 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
4823 if (unfoldGEPSelect(GEPI))
4824 return true;
4825
4826 if (unfoldGEPPhi(GEPI))
4827 return true;
4828
4829 enqueueUsers(GEPI);
4830 return false;
4831 }
4832
4833 bool visitPHINode(PHINode &PN) {
4834 enqueueUsers(PN);
4835 return false;
4836 }
4837
4838 bool visitSelectInst(SelectInst &SI) {
4839 enqueueUsers(SI);
4840 return false;
4841 }
4842};
4843
4844} // end anonymous namespace
4845
4846/// Strip aggregate type wrapping.
4847///
4848/// This removes no-op aggregate types wrapping an underlying type. It will
4849/// strip as many layers of types as it can without changing either the type
4850/// size or the allocated size.
4852 if (Ty->isSingleValueType())
4853 return Ty;
4854
4855 uint64_t AllocSize = DL.getTypeAllocSize(Ty).getFixedValue();
4856 uint64_t TypeSize = DL.getTypeSizeInBits(Ty).getFixedValue();
4857
4858 Type *InnerTy;
4859 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
4860 InnerTy = ArrTy->getElementType();
4861 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
4862 const StructLayout *SL = DL.getStructLayout(STy);
4863 unsigned Index = SL->getElementContainingOffset(0);
4864 InnerTy = STy->getElementType(Index);
4865 } else {
4866 return Ty;
4867 }
4868
4869 if (AllocSize > DL.getTypeAllocSize(InnerTy).getFixedValue() ||
4870 TypeSize > DL.getTypeSizeInBits(InnerTy).getFixedValue())
4871 return Ty;
4872
4873 return stripAggregateTypeWrapping(DL, InnerTy);
4874}
4875
4876/// Try to find a partition of the aggregate type passed in for a given
4877/// offset and size.
4878///
4879/// This recurses through the aggregate type and tries to compute a subtype
4880/// based on the offset and size. When the offset and size span a sub-section
4881/// of an array, it will even compute a new array type for that sub-section,
4882/// and the same for structs.
4883///
4884/// Note that this routine is very strict and tries to find a partition of the
4885/// type which produces the *exact* right offset and size. It is not forgiving
4886/// when the size or offset cause either end of type-based partition to be off.
4887/// Also, this is a best-effort routine. It is reasonable to give up and not
4888/// return a type if necessary.
4890 uint64_t Size) {
4891 if (Offset == 0 && DL.getTypeAllocSize(Ty).getFixedValue() == Size)
4892 return stripAggregateTypeWrapping(DL, Ty);
4893 if (Offset > DL.getTypeAllocSize(Ty).getFixedValue() ||
4894 (DL.getTypeAllocSize(Ty).getFixedValue() - Offset) < Size)
4895 return nullptr;
4896
4897 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
4898 Type *ElementTy;
4899 uint64_t TyNumElements;
4900 if (auto *AT = dyn_cast<ArrayType>(Ty)) {
4901 ElementTy = AT->getElementType();
4902 TyNumElements = AT->getNumElements();
4903 } else {
4904 // FIXME: This isn't right for vectors with non-byte-sized or
4905 // non-power-of-two sized elements.
4906 auto *VT = cast<FixedVectorType>(Ty);
4907 ElementTy = VT->getElementType();
4908 TyNumElements = VT->getNumElements();
4909 }
4910 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy).getFixedValue();
4911 uint64_t NumSkippedElements = Offset / ElementSize;
4912 if (NumSkippedElements >= TyNumElements)
4913 return nullptr;
4914 Offset -= NumSkippedElements * ElementSize;
4915
4916 // First check if we need to recurse.
4917 if (Offset > 0 || Size < ElementSize) {
4918 // Bail if the partition ends in a different array element.
4919 if ((Offset + Size) > ElementSize)
4920 return nullptr;
4921 // Recurse through the element type trying to peel off offset bytes.
4922 return getTypePartition(DL, ElementTy, Offset, Size);
4923 }
4924 assert(Offset == 0);
4925
4926 if (Size == ElementSize)
4927 return stripAggregateTypeWrapping(DL, ElementTy);
4928 assert(Size > ElementSize);
4929 uint64_t NumElements = Size / ElementSize;
4930 if (NumElements * ElementSize != Size)
4931 return nullptr;
4932 return ArrayType::get(ElementTy, NumElements);
4933 }
4934
4936 if (!STy)
4937 return nullptr;
4938
4939 const StructLayout *SL = DL.getStructLayout(STy);
4940
4941 if (SL->getSizeInBits().isScalable())
4942 return nullptr;
4943
4944 if (Offset >= SL->getSizeInBytes())
4945 return nullptr;
4946 uint64_t EndOffset = Offset + Size;
4947 if (EndOffset > SL->getSizeInBytes())
4948 return nullptr;
4949
4950 unsigned Index = SL->getElementContainingOffset(Offset);
4951 Offset -= SL->getElementOffset(Index);
4952
4953 Type *ElementTy = STy->getElementType(Index);
4954 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy).getFixedValue();
4955 if (Offset >= ElementSize)
4956 return nullptr; // The offset points into alignment padding.
4957
4958 // See if any partition must be contained by the element.
4959 if (Offset > 0 || Size < ElementSize) {
4960 if ((Offset + Size) > ElementSize)
4961 return nullptr;
4962 return getTypePartition(DL, ElementTy, Offset, Size);
4963 }
4964 assert(Offset == 0);
4965
4966 if (Size == ElementSize)
4967 return stripAggregateTypeWrapping(DL, ElementTy);
4968
4969 StructType::element_iterator EI = STy->element_begin() + Index,
4970 EE = STy->element_end();
4971 if (EndOffset < SL->getSizeInBytes()) {
4972 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
4973 if (Index == EndIndex)
4974 return nullptr; // Within a single element and its padding.
4975
4976 // Don't try to form "natural" types if the elements don't line up with the
4977 // expected size.
4978 // FIXME: We could potentially recurse down through the last element in the
4979 // sub-struct to find a natural end point.
4980 if (SL->getElementOffset(EndIndex) != EndOffset)
4981 return nullptr;
4982
4983 assert(Index < EndIndex);
4984 EE = STy->element_begin() + EndIndex;
4985 }
4986
4987 // Try to build up a sub-structure.
4988 StructType *SubTy =
4989 StructType::get(STy->getContext(), ArrayRef(EI, EE), STy->isPacked());
4990 const StructLayout *SubSL = DL.getStructLayout(SubTy);
4991 if (Size != SubSL->getSizeInBytes())
4992 return nullptr; // The sub-struct doesn't have quite the size needed.
4993
4994 return SubTy;
4995}
4996
4997/// This is a helper class that's used by presplitLoadsAndStores to split a
4998/// slice into smaller slices, including splitting the corresponding load/store
4999/// instruction.
5001 IRBuilderTy &IRB;
5002 const DataLayout &DL;
5003
5004 /// The split points that the slice is being split at. These are byte offsets
5005 /// within the slice, and are used to form the start/end offsets of the slices
5006 /// that we generate, plus the implicit offsets from the start and end of the
5007 /// slice that's being split.
5008 const std::vector<uint64_t> &Splits;
5009
5010 /// The size of the slice that's being split.
5011 unsigned SliceSize;
5012
5013public:
5014 SliceSplitter(IRBuilderTy &IRB, const DataLayout &DL,
5015 std::vector<uint64_t> &Splits, unsigned SliceSize)
5016 : IRB(IRB), DL(DL), Splits(Splits), SliceSize(SliceSize) {}
5017
5018 /// An iterator which iterates over the sub-slices that we want to split the
5019 /// slice into.
5021 : public iterator_facade_base<Iterator, std::forward_iterator_tag,
5022 const Iterator> {
5024 unsigned Idx;
5025 Iterator(SliceSplitter &SS, bool IsEnd) : SS(SS) {
5026 Idx = IsEnd ? SS.Splits.size() + 1 : 0;
5027 }
5028 bool operator==(const Iterator &Other) const { return Idx == Other.Idx; }
5029 uint64_t getOffset() const { return Idx == 0 ? 0 : SS.Splits[Idx - 1]; }
5030 uint64_t getSize() const {
5031 uint64_t NextOffset =
5032 Idx < SS.Splits.size() ? SS.Splits[Idx] : SS.SliceSize;
5033 return NextOffset - getOffset();
5034 }
5036 ++Idx;
5037 return *this;
5038 }
5039 const Iterator &operator*() const { return *this; }
5040 };
5041
5042 Iterator begin() { return Iterator(*this, false); }
5043
5044 Iterator end() { return Iterator(*this, true); }
5045
5046 LoadInst *createLoad(Value *BasePtr, Iterator &It, Instruction *SplitI) {
5047 Type *PartTy = Type::getIntNTy(SplitI->getContext(), It.getSize() * 8);
5048 Type *PartPtrTy = BasePtr->getType();
5049 unsigned AS = getLoadStoreAddressSpace(SplitI);
5050 LoadInst *PLoad = IRB.CreateAlignedLoad(
5051 PartTy,
5052 getAdjustedPtr(IRB, DL, BasePtr,
5053 APInt(DL.getIndexSizeInBits(AS), It.getOffset()),
5054 PartPtrTy, BasePtr->getName() + "."),
5055 getAdjustedAlignment(SplitI, It.getOffset()),
5056 /*IsVolatile*/ false, SplitI->getName());
5057 PLoad->copyMetadata(*SplitI, {LLVMContext::MD_mem_parallel_loop_access,
5058 LLVMContext::MD_access_group});
5059 return PLoad;
5060 }
5061
5062 StoreInst *createStore(Value *StoreVal, Value *BasePtr, Iterator &It,
5063 Instruction *SplitI) {
5064 Type *PartPtrTy = BasePtr->getType();
5065 unsigned AS = getLoadStoreAddressSpace(SplitI);
5066 StoreInst *PStore = IRB.CreateAlignedStore(
5067 StoreVal,
5068 getAdjustedPtr(IRB, DL, BasePtr,
5069 APInt(DL.getIndexSizeInBits(AS), It.getOffset()),
5070 PartPtrTy, BasePtr->getName() + "."),
5071 getAdjustedAlignment(SplitI, It.getOffset()),
5072 /*IsVolatile*/ false);
5073 PStore->copyMetadata(*SplitI, {LLVMContext::MD_mem_parallel_loop_access,
5074 LLVMContext::MD_access_group,
5075 LLVMContext::MD_DIAssignID});
5076 AAMDNodes AATags = SplitI->getAAMetadata();
5077 if (AATags)
5078 PStore->setAAMetadata(
5079 AATags.adjustForAccess(It.getOffset(), StoreVal->getType(), DL));
5080
5081 return PStore;
5082 }
5083
5084 Slice createSlice(Instruction *I, uint64_t BaseOffset, Iterator &It) {
5085 unsigned PtrIdx = 0;
5086 if (auto *LI = dyn_cast<LoadInst>(I))
5087 PtrIdx = LI->getPointerOperandIndex();
5088 else if (auto *SI = dyn_cast<StoreInst>(I))
5089 PtrIdx = SI->getPointerOperandIndex();
5090 else
5091 llvm_unreachable("Slice must be for a load or store");
5092 // BaseOffset is the offset of the original slice within the alloca, so the
5093 // start and end offsets of this slice are offset from that.
5094 Slice S(BaseOffset + It.getOffset(),
5095 BaseOffset + It.getOffset() + It.getSize(),
5096 &I->getOperandUse(PtrIdx), /*IsSplittable*/ false);
5097 LLVM_DEBUG(dbgs() << " new slice [" << S.beginOffset() << ", "
5098 << S.endOffset() << "): " << *I << "\n");
5099 return S;
5100 }
5101};
5102
5103/// Try to find a slice in the map that partially overlaps with S, i.e. some but
5104/// not all of its range is contained within the range of S, and which forms a
5105/// load/store pair with S (i.e. the two slices are used to perform a
5106/// memmove-like copy). SliceMap is expected to contain the slices for a single
5107/// Partition.
5108static Slice *findOverlappingCopySlice(Slice &S,
5109 InstructionSliceMap &SliceMap) {
5110 // Single byte slices can't partially overlap anything
5111 if (S.endOffset() - S.beginOffset() == 1)
5112 return nullptr;
5113 // The source/destination of this slice needs to be a memory instruction
5114 // whose slice overlaps this one.
5115 Instruction *I = cast<Instruction>(S.getUse()->getUser());
5116 Instruction *J = nullptr;
5117 if (auto *LI = dyn_cast<LoadInst>(I)) {
5118 if (!LI->hasOneUser())
5119 return nullptr;
5120 J = cast<Instruction>(*LI->user_begin());
5121 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
5122 J = dyn_cast<Instruction>(SI->getValueOperand());
5123 if (!J || !J->hasOneUser())
5124 return nullptr;
5125 } else {
5126 return nullptr;
5127 }
5128 // Check if there's a slice that corresponds to J that overlaps this slice
5129 for (Slice *JS : SliceMap[J]) {
5130 if (S.beginOffset() > JS->beginOffset() &&
5131 S.beginOffset() < JS->endOffset())
5132 return JS;
5133 if (JS->beginOffset() > S.beginOffset() &&
5134 JS->beginOffset() < S.endOffset())
5135 return JS;
5136 }
5137 return nullptr;
5138}
5139
5140/// Pre-split loads and stores to simplify rewriting.
5141///
5142/// We want to break up the splittable load+store pairs as much as
5143/// possible. This is important to do as a preprocessing step, as once we
5144/// start rewriting the accesses to partitions of the alloca we lose the
5145/// necessary information to correctly split apart paired loads and stores
5146/// which both point into this alloca. The case to consider is something like
5147/// the following:
5148///
5149/// %a = alloca [12 x i8]
5150/// %gep1 = getelementptr i8, ptr %a, i32 0
5151/// %gep2 = getelementptr i8, ptr %a, i32 4
5152/// %gep3 = getelementptr i8, ptr %a, i32 8
5153/// store float 0.0, ptr %gep1
5154/// store float 1.0, ptr %gep2
5155/// %v = load i64, ptr %gep1
5156/// store i64 %v, ptr %gep2
5157/// %f1 = load float, ptr %gep2
5158/// %f2 = load float, ptr %gep3
5159///
5160/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
5161/// promote everything so we recover the 2 SSA values that should have been
5162/// there all along.
5163///
5164/// \returns true if any changes are made.
5165bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
5166 LLVM_DEBUG(dbgs() << "Pre-splitting loads and stores\n");
5167
5168 // Track the loads and stores which are candidates for pre-splitting here, in
5169 // the order they first appear during the partition scan. These give stable
5170 // iteration order and a basis for tracking which loads and stores we
5171 // actually split.
5174
5175 // We need to accumulate the splits required of each load or store where we
5176 // can find them via a direct lookup. This is important to cross-check loads
5177 // and stores against each other. We also track the slice so that we can kill
5178 // all the slices that end up split.
5179 struct SplitOffsets {
5180 Slice *S;
5181 std::vector<uint64_t> Splits;
5182 };
5183 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
5184
5185 // Track loads out of this alloca which cannot, for any reason, be pre-split.
5186 // This is important as we also cannot pre-split stores of those loads!
5187 // FIXME: This is all pretty gross. It means that we can be more aggressive
5188 // in pre-splitting when the load feeding the store happens to come from
5189 // a separate alloca. Put another way, the effectiveness of SROA would be
5190 // decreased by a frontend which just concatenated all of its local allocas
5191 // into one big flat alloca. But defeating such patterns is exactly the job
5192 // SROA is tasked with! Sadly, to not have this discrepancy we would have
5193 // change store pre-splitting to actually force pre-splitting of the load
5194 // that feeds it *and all stores*. That makes pre-splitting much harder, but
5195 // maybe it would make it more principled?
5196 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
5197
5198 LLVM_DEBUG(dbgs() << " Searching for candidate loads and stores\n");
5199 for (auto &P : AS.partitions()) {
5200 InstructionSliceMap SliceMap;
5201 for (Slice &S : P) {
5202 SliceMap[cast<Instruction>(S.getUse()->getUser())].insert(&S);
5203 }
5204 for (Slice &S : P) {
5205 Instruction *I = cast<Instruction>(S.getUse()->getUser());
5206 bool ExtendsPastPartitionEnd = S.endOffset() > P.endOffset();
5207 Slice *CopyOverlap = findOverlappingCopySlice(S, SliceMap);
5208 if (!S.isSplittable() || (!ExtendsPastPartitionEnd && !CopyOverlap)) {
5209 // If this is a load we have to track that it can't participate in any
5210 // pre-splitting. If this is a store of a load we have to track that
5211 // that load also can't participate in any pre-splitting.
5212 if (auto *LI = dyn_cast<LoadInst>(I))
5213 UnsplittableLoads.insert(LI);
5214 else if (auto *SI = dyn_cast<StoreInst>(I))
5215 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
5216 UnsplittableLoads.insert(LI);
5217 continue;
5218 }
5219 assert(P.endOffset() > S.beginOffset() &&
5220 "Empty or backwards partition!");
5221
5222 // Determine if this is a pre-splittable slice.
5223 if (auto *LI = dyn_cast<LoadInst>(I)) {
5224 assert(!LI->isVolatile() && "Cannot split volatile loads!");
5225
5226 // The load must be used exclusively to store into other pointers for
5227 // us to be able to arbitrarily pre-split it. The stores must also be
5228 // simple to avoid changing semantics.
5229 auto IsLoadSimplyStored = [](LoadInst *LI) {
5230 for (User *LU : LI->users()) {
5231 auto *SI = dyn_cast<StoreInst>(LU);
5232 if (!SI || !SI->isSimple())
5233 return false;
5234 }
5235 return true;
5236 };
5237 if (!IsLoadSimplyStored(LI)) {
5238 UnsplittableLoads.insert(LI);
5239 continue;
5240 }
5241
5242 Loads.push_back(LI);
5243 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
5244 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
5245 // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
5246 continue;
5247 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
5248 if (!StoredLoad || !StoredLoad->isSimple())
5249 continue;
5250 assert(!SI->isVolatile() && "Cannot split volatile stores!");
5251
5252 Stores.push_back(SI);
5253 } else {
5254 // Other uses cannot be pre-split.
5255 continue;
5256 }
5257
5258 // Record the initial split.
5259 LLVM_DEBUG(dbgs() << " Candidate: " << *I << "\n");
5260 auto &Offsets = SplitOffsetsMap[I];
5261 assert(Offsets.Splits.empty() &&
5262 "Should not have splits the first time we see an instruction!");
5263 Offsets.S = &S;
5264 if (CopyOverlap) {
5265 // S is being moved to CopyOverlap, which overlaps with S, so we split S
5266 // into three parts:
5267 // * Initially outside the overlap and copied into the overlap.
5268 // * Either initially inside the overlap and remains inside it after
5269 // the copy, or initially outside and remains outside, depending on
5270 // if the overlap or non-overlap area is larger, and which will be
5271 // empty if they are equal.
5272 // * Initially inside the overlap and copied outside the overlap.
5273 // This should result in the first and last parts being promoted to
5274 // scalars. If the middle part is an overlapping copy then we repeat
5275 // this process until it isn't.
5276 uint64_t OverlapStart =
5277 std::max(S.beginOffset(), CopyOverlap->beginOffset());
5278 uint64_t OverlapEnd = std::min(S.endOffset(), CopyOverlap->endOffset());
5279 uint64_t OverlapSize = OverlapEnd - OverlapStart;
5280 uint64_t SliceSize = S.endOffset() - S.beginOffset();
5281 uint64_t NonOverlapSize = SliceSize - OverlapSize;
5282 if (OverlapSize < NonOverlapSize) {
5283 // When the overlap area is smaller the middle part is initially and
5284 // remains outside the overlap, so splitting once is enough. The size
5285 // of the first and last part both equal the overlap size, so the
5286 // split points are that amount from the start and end of the slice.
5287 Offsets.Splits.push_back(OverlapSize);
5288 Offsets.Splits.push_back(SliceSize - OverlapSize);
5289 } else if (OverlapSize > NonOverlapSize) {
5290 // When the overlap area is larger the middle part is initially and
5291 // remains inside the overlap, so we repeatedly split it.
5292 for (uint64_t Split = NonOverlapSize; Split <= SliceSize / 2;
5293 Split += NonOverlapSize) {
5294 Offsets.Splits.push_back(Split);
5295 if (Split != SliceSize - Split) {
5296 Offsets.Splits.push_back(SliceSize - Split);
5297 }
5298 }
5299 // Sort the splits as they need to be in ascending order.
5300 llvm::sort(Offsets.Splits);
5301 } else {
5302 // Here the overlap and non-overlap size are the same, so the middle
5303 // part is empty and the slice is split exactly in the center.
5304 Offsets.Splits.push_back(OverlapSize);
5305 }
5306 } else {
5307 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
5308 }
5309 }
5310 }
5311
5312 // We may have split loads where some of their stores are split stores. For
5313 // such loads and stores, we can only pre-split them if their splits exactly
5314 // match relative to their starting offset. We have to verify this prior to
5315 // any rewriting.
5316 llvm::erase_if(Stores, [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
5317 // Lookup the load we are storing in our map of split
5318 // offsets.
5319 auto *LI = cast<LoadInst>(SI->getValueOperand());
5320 // If it was completely unsplittable, then we're done,
5321 // and this store can't be pre-split.
5322 if (UnsplittableLoads.count(LI))
5323 return true;
5324
5325 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
5326 if (LoadOffsetsI == SplitOffsetsMap.end())
5327 return false; // Unrelated loads are definitely safe.
5328 auto &LoadOffsets = LoadOffsetsI->second;
5329
5330 // Now lookup the store's offsets.
5331 auto &StoreOffsets = SplitOffsetsMap[SI];
5332
5333 // If the relative offsets of each split in the load and
5334 // store match exactly, then we can split them and we
5335 // don't need to remove them here.
5336 if (LoadOffsets.Splits == StoreOffsets.Splits)
5337 return false;
5338
5339 LLVM_DEBUG(dbgs() << " Mismatched splits for load and store:\n"
5340 << " " << *LI << "\n"
5341 << " " << *SI << "\n");
5342
5343 // We've found a store and load that we need to split
5344 // with mismatched relative splits. Just give up on them
5345 // and remove both instructions from our list of
5346 // candidates.
5347 UnsplittableLoads.insert(LI);
5348 return true;
5349 });
5350 // Now we have to go *back* through all the stores, because a later store may
5351 // have caused an earlier store's load to become unsplittable and if it is
5352 // unsplittable for the later store, then we can't rely on it being split in
5353 // the earlier store either.
5354 llvm::erase_if(Stores, [&UnsplittableLoads](StoreInst *SI) {
5355 auto *LI = cast<LoadInst>(SI->getValueOperand());
5356 return UnsplittableLoads.count(LI);
5357 });
5358 // Once we've established all the loads that can't be split for some reason,
5359 // filter any that made it into our list out.
5360 llvm::erase_if(Loads, [&UnsplittableLoads](LoadInst *LI) {
5361 return UnsplittableLoads.count(LI);
5362 });
5363
5364 // If no loads or stores are left, there is no pre-splitting to be done for
5365 // this alloca.
5366 if (Loads.empty() && Stores.empty())
5367 return false;
5368
5369 // From here on, we can't fail and will be building new accesses, so rig up
5370 // an IR builder.
5371 IRBuilderTy IRB(&AI);
5372 IRB.disableGEPCanonicalization();
5373
5374 // Collect the new slices which we will merge into the alloca slices.
5375 SmallVector<Slice, 4> NewSlices;
5376
5377 // Track any allocas we end up splitting loads and stores for so we iterate
5378 // on them.
5379 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
5380
5381 // At this point, we have collected all of the loads and stores we can
5382 // pre-split, and the specific splits needed for them. We actually do the
5383 // splitting in a specific order in order to handle when one of the loads in
5384 // the value operand to one of the stores.
5385 //
5386 // First, we rewrite all of the split loads, and just accumulate each split
5387 // load in a parallel structure. We also build the slices for them and append
5388 // them to the alloca slices.
5389 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
5390 std::vector<LoadInst *> SplitLoads;
5391 const DataLayout &DL = AI.getDataLayout();
5392 for (LoadInst *LI : Loads) {
5393 SplitLoads.clear();
5394
5395 auto &Offsets = SplitOffsetsMap[LI];
5396 unsigned SliceSize = Offsets.S->endOffset() - Offsets.S->beginOffset();
5397 assert(LI->getType()->getIntegerBitWidth() % 8 == 0 &&
5398 "Load must have type size equal to store size");
5399 assert(LI->getType()->getIntegerBitWidth() / 8 >= SliceSize &&
5400 "Load must be >= slice size");
5401
5402 uint64_t BaseOffset = Offsets.S->beginOffset();
5403 assert(BaseOffset + SliceSize > BaseOffset &&
5404 "Cannot represent alloca access size using 64-bit integers!");
5405
5407 IRB.SetInsertPoint(LI);
5408
5409 LLVM_DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
5410
5411 SliceSplitter Splitter(IRB, DL, Offsets.Splits, SliceSize);
5412 for (auto Part : Splitter) {
5413 LoadInst *PLoad = Splitter.createLoad(BasePtr, Part, LI);
5414
5415 // Append this load onto the list of split loads so we can find it later
5416 // to rewrite the stores.
5417 SplitLoads.push_back(PLoad);
5418
5419 // Now build a new slice for the alloca.
5420 NewSlices.push_back(Splitter.createSlice(PLoad, BaseOffset, Part));
5421 }
5422
5423 // Now that we have the split loads, do the slow walk over all uses of the
5424 // load and rewrite them as split stores, or save the split loads to use
5425 // below if the store is going to be split there anyways.
5426 bool DeferredStores = false;
5427 for (User *LU : LI->users()) {
5428 StoreInst *SI = cast<StoreInst>(LU);
5429 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
5430 DeferredStores = true;
5431 LLVM_DEBUG(dbgs() << " Deferred splitting of store: " << *SI
5432 << "\n");
5433 continue;
5434 }
5435
5436 Value *StoreBasePtr = SI->getPointerOperand();
5437 IRB.SetInsertPoint(SI);
5438
5439 LLVM_DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
5440
5441 for (auto Part : Splitter) {
5442 LoadInst *PLoad = SplitLoads[Part.Idx];
5443 StoreInst *PStore = Splitter.createStore(PLoad, StoreBasePtr, Part, SI);
5444 (void)PStore;
5445 LLVM_DEBUG(dbgs() << " +" << Part.getOffset() << ":" << *PStore
5446 << "\n");
5447 }
5448
5449 // We want to immediately iterate on any allocas impacted by splitting
5450 // this store, and we have to track any promotable alloca (indicated by
5451 // a direct store) as needing to be resplit because it is no longer
5452 // promotable.
5453 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
5454 ResplitPromotableAllocas.insert(OtherAI);
5455 Worklist.insert(OtherAI);
5456 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
5457 StoreBasePtr->stripInBoundsOffsets())) {
5458 Worklist.insert(OtherAI);
5459 }
5460
5461 // Mark the original store as dead.
5462 DeadInsts.push_back(SI);
5463 }
5464
5465 // Save the split loads if there are deferred stores among the users.
5466 if (DeferredStores)
5467 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
5468
5469 // Mark the original load as dead and kill the original slice.
5470 DeadInsts.push_back(LI);
5471 Offsets.S->kill();
5472 }
5473
5474 // Second, we rewrite all of the split stores. At this point, we know that
5475 // all loads from this alloca have been split already. For stores of such
5476 // loads, we can simply look up the pre-existing split loads. For stores of
5477 // other loads, we split those loads first and then write split stores of
5478 // them.
5479 for (StoreInst *SI : Stores) {
5480 auto *LI = cast<LoadInst>(SI->getValueOperand());
5481 IntegerType *Ty = cast<IntegerType>(LI->getType());
5482 assert(Ty->getBitWidth() % 8 == 0);
5483 uint64_t StoreSize = Ty->getBitWidth() / 8;
5484 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
5485
5486 auto &Offsets = SplitOffsetsMap[SI];
5487 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
5488 "Slice size should always match load size exactly!");
5489 uint64_t BaseOffset = Offsets.S->beginOffset();
5490 assert(BaseOffset + StoreSize > BaseOffset &&
5491 "Cannot represent alloca access size using 64-bit integers!");
5492
5493 Value *LoadBasePtr = LI->getPointerOperand();
5494 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
5495
5496 LLVM_DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
5497
5498 // Check whether we have an already split load.
5499 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
5500 std::vector<LoadInst *> *SplitLoads = nullptr;
5501 if (SplitLoadsMapI != SplitLoadsMap.end()) {
5502 SplitLoads = &SplitLoadsMapI->second;
5503 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
5504 "Too few split loads for the number of splits in the store!");
5505 } else {
5506 LLVM_DEBUG(dbgs() << " of load: " << *LI << "\n");
5507 }
5508
5509 SliceSplitter Splitter(IRB, DL, Offsets.Splits, StoreSize);
5510 for (auto Part : Splitter) {
5511 // Either lookup a split load or create one.
5512 LoadInst *PLoad;
5513 if (SplitLoads) {
5514 PLoad = (*SplitLoads)[Part.Idx];
5515 } else {
5516 IRB.SetInsertPoint(LI);
5517 PLoad = Splitter.createLoad(LoadBasePtr, Part, LI);
5518 }
5519
5520 // And store this partition.
5521 IRB.SetInsertPoint(SI);
5522 StoreInst *PStore = Splitter.createStore(PLoad, StoreBasePtr, Part, SI);
5523
5524 // Now build a new slice for the alloca.
5525 NewSlices.push_back(Splitter.createSlice(PStore, BaseOffset, Part));
5526 if (!SplitLoads) {
5527 LLVM_DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
5528 }
5529 }
5530
5531 // We want to immediately iterate on any allocas impacted by splitting
5532 // this load, which is only relevant if it isn't a load of this alloca and
5533 // thus we didn't already split the loads above. We also have to keep track
5534 // of any promotable allocas we split loads on as they can no longer be
5535 // promoted.
5536 if (!SplitLoads) {
5537 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
5538 assert(OtherAI != &AI && "We can't re-split our own alloca!");
5539 ResplitPromotableAllocas.insert(OtherAI);
5540 Worklist.insert(OtherAI);
5541 } else if (AllocaInst *StrippedAI = dyn_cast<AllocaInst>(
5542 LoadBasePtr->stripInBoundsOffsets())) {
5543 assert(StrippedAI != &AI && "We can't re-split our own alloca!");
5544 Worklist.insert(StrippedAI);
5545 }
5546 }
5547
5548 // Mark the original store as dead now that we've split it up and kill its
5549 // slice. Note that we leave the original load in place unless this store
5550 // was its only use. It may in turn be split up if it is an alloca load
5551 // for some other alloca, but it may be a normal load. This may introduce
5552 // redundant loads, but where those can be merged the rest of the optimizer
5553 // should handle the merging, and this uncovers SSA splits which is more
5554 // important. In practice, the original loads will almost always be fully
5555 // split and removed eventually, and the splits will be merged by any
5556 // trivial CSE, including instcombine.
5557 if (LI->hasOneUse()) {
5558 assert(*LI->user_begin() == SI && "Single use isn't this store!");
5559 DeadInsts.push_back(LI);
5560 }
5561 DeadInsts.push_back(SI);
5562 Offsets.S->kill();
5563 }
5564
5565 // Remove the killed slices that have ben pre-split.
5566 llvm::erase_if(AS, [](const Slice &S) { return S.isDead(); });
5567
5568 // Insert our new slices. This will sort and merge them into the sorted
5569 // sequence.
5570 AS.insert(NewSlices);
5571
5572 LLVM_DEBUG(dbgs() << " Pre-split slices:\n");
5573#ifndef NDEBUG
5574 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
5575 LLVM_DEBUG(AS.print(dbgs(), I, " "));
5576#endif
5577
5578 // Finally, don't try to promote any allocas that new require re-splitting.
5579 // They have already been added to the worklist above.
5580 PromotableAllocas.set_subtract(ResplitPromotableAllocas);
5581
5582 return true;
5583}
5584
5585/// Try to canonicalize a homogeneous struct partition to a vector type.
5586///
5587/// We can do this if all the elements of the struct are the same and the
5588/// corresponding vector has the same byte-level layout. This can sometimes
5589/// eliminate allocas because structs cannot get promoted to LLVM values, but
5590/// vectors can.
5591///
5592/// We only apply this transformation when all users of the partition are memory
5593/// intrinsics. Otherwise, if there is a load or store of some other type to the
5594/// partition, SROA would select that type.
5595///
5596/// Applying this transformation too early may hinder memcpyopt, which may
5597/// generate better code when eliminating allocas. For example, see
5598/// `struct-to-vector-fp-store-only-tail.ll`, which demonstrates that applying
5599/// this before memcpyopt can initialize previously uninitialized memory when
5600/// the alloca gets promoted to an SSA value. For another example, see
5601/// `struct-to-vector-before-memcpyopt.ll`, which demonstrates that applying
5602/// this before memcpyopt can result in promoting an alloca so that we load a
5603/// temporary value instead of copying the temporary value into memory, whereas
5604/// memcpyopt eliminates the temporary altogether.
5605///
5606/// As such, we only apply this transformation after memcpyopt has run. We gate
5607/// this transformation by the "AggregateToVector" pass option.
5609 Partition &P,
5610 const DataLayout &DL) {
5611 unsigned NumElts = STy->getNumElements();
5612
5613 Type *EltTy = STy->getElementType(0);
5614 if (!llvm::all_equal(STy->elements()))
5615 return nullptr;
5616
5617 bool IsIntegralPointerTy =
5618 EltTy->isPointerTy() && !DL.isNonIntegralPointerType(EltTy);
5619 if (!EltTy->isIntegerTy() && !EltTy->isFloatingPointTy() &&
5620 !IsIntegralPointerTy)
5621 return nullptr;
5622
5623 // Ensure the struct is tightly packed so that the bit-layout is the same as
5624 // the corresponding vector. For example, this prevents a miscompile for
5625 // { i5, i5 }, which has padding after each i5 field, whereas <i5, i5> has
5626 // tightly packed elements and trailing padding.
5627 if (DL.getTypeSizeInBits(EltTy) != DL.getTypeAllocSizeInBits(EltTy))
5628 return nullptr;
5629
5630 auto *VTy = FixedVectorType::get(EltTy, NumElts);
5631 TypeSize StructSize = DL.getStructLayout(STy)->getSizeInBytes();
5632 TypeSize VectorSize = DL.getTypeStoreSize(VTy);
5633 // After ruling out per-element padding, make sure a vector load/store
5634 // covers the same number of bytes as the struct layout.
5635 if (StructSize != VectorSize)
5636 return nullptr;
5637
5638 auto IsIgnorableOrMemIntrinsicSlice = [](const Slice &S) {
5639 if (S.isDead())
5640 return true;
5641 auto *U = S.getUse();
5642 return !U || isa<LifetimeIntrinsic, MemIntrinsic>(U->getUser());
5643 };
5644
5645 for (const Slice &S : P)
5646 if (!IsIgnorableOrMemIntrinsicSlice(S))
5647 return nullptr;
5648
5649 for (const Slice *S : P.splitSliceTails())
5650 if (!IsIgnorableOrMemIntrinsicSlice(*S))
5651 return nullptr;
5652
5653 return VTy;
5654}
5655
5656/// Select a partition type for an alloca partition.
5657///
5658/// Try to compute a friendly type for this partition of the alloca. This
5659/// won't always succeed, in which case we fall back to a legal integer type
5660/// or an i8 array of an appropriate size.
5661///
5662/// \returns A tuple with the following elements:
5663/// - PartitionType: The computed type for this partition.
5664/// - IsIntegerWideningViable: True if integer widening promotion is used.
5665/// - VectorType: The vector type if vector promotion is used, otherwise
5666/// nullptr.
5667static std::tuple<Type *, bool, VectorType *>
5669 LLVMContext &C, bool AggregateToVector) {
5670 auto LogSelection = [&](StringRef Path, Type *SelectedTy,
5671 VectorType *SelectedVecTy, bool SelectedIntWidening) {
5672 LLVM_DEBUG({
5673 dbgs() << "selectPartitionType path=" << Path
5674 << " func=" << AI.getFunction()->getName() << " alloca=";
5675 if (AI.hasName())
5676 dbgs() << AI.getName();
5677 else
5678 dbgs() << "<unnamed>";
5679 dbgs() << " partition=[" << P.beginOffset() << "," << P.endOffset()
5680 << ") size=" << P.size();
5681 if (std::optional<TypeSize> AllocSize = AI.getAllocationSize(DL))
5682 dbgs() << " alloc-size=" << AllocSize->getKnownMinValue();
5683 if (SelectedTy)
5684 dbgs() << " chosen=" << *SelectedTy;
5685 if (SelectedVecTy)
5686 dbgs() << " vec=" << *SelectedVecTy;
5687 dbgs() << " intwiden=" << SelectedIntWidening << "\n";
5688 });
5689 };
5690 // First check if the partition is viable for vector promotion.
5691 //
5692 // We prefer vector promotion over integer widening promotion when:
5693 // - The vector element type is a floating-point type.
5694 // - All the loads/stores to the alloca are vector loads/stores to the
5695 // entire alloca or load/store a single element of the vector.
5696 //
5697 // Otherwise when there is an integer vector with mixed type loads/stores we
5698 // prefer integer widening promotion because it's more likely the user is
5699 // doing bitwise arithmetic and we generate better code.
5700 VectorType *VecTy =
5702 // If the vector element type is a floating-point type, we prefer vector
5703 // promotion. If the vector has one element, let the below code select
5704 // whether we promote with the vector or scalar.
5705 if (VecTy && VecTy->getElementType()->isFloatingPointTy() &&
5706 VecTy->getElementCount().getFixedValue() > 1) {
5707 LogSelection("direct-fp-vecty", VecTy, VecTy, false);
5708 return {VecTy, false, VecTy};
5709 }
5710
5711 // Check if there is a common type that all slices of the partition use that
5712 // spans the partition.
5713 auto [CommonUseTy, LargestIntTy] =
5714 findCommonType(P.begin(), P.end(), P.endOffset());
5715 if (CommonUseTy) {
5716 TypeSize CommonUseSize = DL.getTypeAllocSize(CommonUseTy);
5717 if (CommonUseSize.isFixed() && CommonUseSize.getFixedValue() >= P.size()) {
5718 // We prefer vector promotion here because if vector promotion is viable
5719 // and there is a common type used, then it implies the second listed
5720 // condition for preferring vector promotion is true.
5721 if (VecTy) {
5722 LogSelection("common-type-vecty", VecTy, VecTy, false);
5723 return {VecTy, false, VecTy};
5724 }
5725 bool IntWiden = isIntegerWideningViable(P, CommonUseTy, DL);
5726 LogSelection("common-type", CommonUseTy, nullptr, IntWiden);
5727 return {CommonUseTy, IntWiden, nullptr};
5728 }
5729 }
5730
5731 // Can we find an appropriate subtype in the original allocated
5732 // type?
5733 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
5734 P.beginOffset(), P.size())) {
5735 // If the partition is an integer array that can be spanned by a legal
5736 // integer type, prefer to represent it as a legal integer type because
5737 // it's more likely to be promotable.
5738 if (TypePartitionTy->isArrayTy() &&
5739 TypePartitionTy->getArrayElementType()->isIntegerTy() &&
5740 DL.isLegalInteger(P.size() * 8))
5741 TypePartitionTy = Type::getIntNTy(C, P.size() * 8);
5742 // There was no common type used, so we prefer integer widening promotion.
5743 if (isIntegerWideningViable(P, TypePartitionTy, DL)) {
5744 LogSelection("type-partition-int-widen", TypePartitionTy, nullptr, true);
5745 return {TypePartitionTy, true, nullptr};
5746 }
5747 if (VecTy) {
5748 LogSelection("type-partition-vecty", VecTy, VecTy, false);
5749 return {VecTy, false, VecTy};
5750 }
5751 // If we couldn't promote with TypePartitionTy, try with the largest
5752 // integer type used.
5753 if (LargestIntTy &&
5754 DL.getTypeAllocSize(LargestIntTy).getFixedValue() >= P.size() &&
5755 isIntegerWideningViable(P, LargestIntTy, DL)) {
5756 LogSelection("largest-int-int-widen", LargestIntTy, nullptr, true);
5757 return {LargestIntTy, true, nullptr};
5758 }
5759
5760 // Try homogeneous struct to vector canonicalization when requested. Running
5761 // this too early can hide memcpy chains from MemCpyOpt.
5762 if (AggregateToVector) {
5763 if (auto *STy = dyn_cast<StructType>(TypePartitionTy)) {
5764 if (auto *VTy = tryCanonicalizeStructToVector(STy, P, DL)) {
5765 LogSelection("struct-fallback-vecty", VTy, nullptr, false);
5766 return {VTy, false, nullptr};
5767 }
5768 }
5769 }
5770
5771 // Fallback to TypePartitionTy and we probably won't promote.
5772 LogSelection("type-partition-fallback", TypePartitionTy, nullptr, false);
5773 return {TypePartitionTy, false, nullptr};
5774 }
5775
5776 // Select the largest integer type used if it spans the partition.
5777 if (LargestIntTy &&
5778 DL.getTypeAllocSize(LargestIntTy).getFixedValue() >= P.size()) {
5779 LogSelection("largest-int-fallback", LargestIntTy, nullptr, false);
5780 return {LargestIntTy, false, nullptr};
5781 }
5782
5783 // Select a legal integer type if it spans the partition.
5784 if (DL.isLegalInteger(P.size() * 8)) {
5785 Type *IntTy = Type::getIntNTy(C, P.size() * 8);
5786 LogSelection("legal-int-fallback", IntTy, nullptr, false);
5787 return {IntTy, false, nullptr};
5788 }
5789
5790 // Fallback to an i8 array.
5791 Type *ArrayTy = ArrayType::get(Type::getInt8Ty(C), P.size());
5792 LogSelection("byte-array-fallback", ArrayTy, nullptr, false);
5793 return {ArrayTy, false, nullptr};
5794}
5795
5796/// Rewrite an alloca partition's users.
5797///
5798/// This routine drives both of the rewriting goals of the SROA pass. It tries
5799/// to rewrite uses of an alloca partition to be conducive for SSA value
5800/// promotion. If the partition needs a new, more refined alloca, this will
5801/// build that new alloca, preserving as much type information as possible, and
5802/// rewrite the uses of the old alloca to point at the new one and have the
5803/// appropriate new offsets. It also evaluates how successful the rewrite was
5804/// at enabling promotion and if it was successful queues the alloca to be
5805/// promoted.
5806std::pair<AllocaInst *, uint64_t>
5807SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS, Partition &P) {
5808 const DataLayout &DL = AI.getDataLayout();
5809 // Select the type for the new alloca that spans the partition.
5810 auto [PartitionTy, IsIntegerWideningViable, VecTy] =
5811 selectPartitionType(P, DL, AI, *C, AggregateToVector);
5812
5813 // Check for the case where we're going to rewrite to a new alloca of the
5814 // exact same type as the original, and with the same access offsets. In that
5815 // case, re-use the existing alloca, but still run through the rewriter to
5816 // perform phi and select speculation.
5817 // P.beginOffset() can be non-zero even with the same type in a case with
5818 // out-of-bounds access (e.g. @PR35657 function in SROA/basictest.ll).
5819 AllocaInst *NewAI;
5820 if (PartitionTy == AI.getAllocatedType() && P.beginOffset() == 0) {
5821 NewAI = &AI;
5822 // FIXME: We should be able to bail at this point with "nothing changed".
5823 // FIXME: We might want to defer PHI speculation until after here.
5824 // FIXME: return nullptr;
5825 } else {
5826 // Make sure the alignment is compatible with P.beginOffset().
5827 const Align Alignment = commonAlignment(AI.getAlign(), P.beginOffset());
5828 NewAI =
5829 new AllocaInst(PartitionTy, AI.getAddressSpace(), nullptr, Alignment,
5830 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()),
5831 AI.getIterator());
5832 tryEnforceAlignment(NewAI, DL.getPrefTypeAlign(PartitionTy), DL);
5833 // Copy the old AI debug location over to the new one.
5834 NewAI->setDebugLoc(AI.getDebugLoc());
5835 ++NumNewAllocas;
5836 }
5837
5838 LLVM_DEBUG(dbgs() << "Rewriting alloca partition " << "[" << P.beginOffset()
5839 << "," << P.endOffset() << ") to: " << *NewAI << "\n");
5840
5841 // Track the high watermark on the worklist as it is only relevant for
5842 // promoted allocas. We will reset it to this point if the alloca is not in
5843 // fact scheduled for promotion.
5844 unsigned PPWOldSize = PostPromotionWorklist.size();
5845 unsigned NumUses = 0;
5846 SmallSetVector<PHINode *, 8> PHIUsers;
5847 SmallSetVector<SelectInst *, 8> SelectUsers;
5848
5849 AllocaSliceRewriter Rewriter(
5850 DL, AS, *this, AI, *NewAI, PartitionTy, P.beginOffset(), P.endOffset(),
5851 IsIntegerWideningViable, VecTy, PHIUsers, SelectUsers);
5852 bool Promotable = true;
5853 // Check whether we can have tree-structured merge.
5854 if (auto DeletedValues = Rewriter.rewriteTreeStructuredMerge(P)) {
5855 NumUses += DeletedValues->size() + 1;
5856 for (Value *V : *DeletedValues)
5857 DeadInsts.push_back(V);
5858 } else {
5859 for (Slice *S : P.splitSliceTails()) {
5860 Promotable &= Rewriter.visit(S);
5861 ++NumUses;
5862 }
5863 for (Slice &S : P) {
5864 Promotable &= Rewriter.visit(&S);
5865 ++NumUses;
5866 }
5867 }
5868
5869 NumAllocaPartitionUses += NumUses;
5870 MaxUsesPerAllocaPartition.updateMax(NumUses);
5871
5872 // Now that we've processed all the slices in the new partition, check if any
5873 // PHIs or Selects would block promotion.
5874 SmallVector<PHINode *, 8> NewSpeculatablePHIs;
5875 SmallVector<PHINode *, 2> NewPHIsWithStoreToRewrite;
5876 for (PHINode *PHI : PHIUsers) {
5877 if (isSafePHIToSpeculate(*PHI)) {
5878 NewSpeculatablePHIs.push_back(PHI);
5879 continue;
5880 }
5881 if (getPHIStoreToRewrite(*PHI, PreserveCFG, DTU->getDomTree())) {
5882 NewPHIsWithStoreToRewrite.push_back(PHI);
5883 continue;
5884 }
5885
5886 Promotable = false;
5887 SelectUsers.clear();
5888 break;
5889 }
5890
5892 NewSelectsToRewrite;
5893 NewSelectsToRewrite.reserve(SelectUsers.size());
5894 for (SelectInst *Sel : SelectUsers) {
5895 std::optional<RewriteableMemOps> Ops =
5896 isSafeSelectToSpeculateOrPredicate(*Sel, PreserveCFG);
5897 if (!Ops) {
5898 Promotable = false;
5899 break;
5900 }
5901 NewSelectsToRewrite.emplace_back(std::make_pair(Sel, *Ops));
5902 }
5903
5904 if (Promotable) {
5905 for (Use *U : AS.getDeadUsesIfPromotable()) {
5906 auto *OldInst = dyn_cast<Instruction>(U->get());
5907 Value::dropDroppableUse(*U);
5908 if (OldInst)
5909 if (isInstructionTriviallyDead(OldInst))
5910 DeadInsts.push_back(OldInst);
5911 }
5912 if (NewSpeculatablePHIs.empty() && NewPHIsWithStoreToRewrite.empty() &&
5913 SelectUsers.empty()) {
5914 // Promote the alloca.
5915 PromotableAllocas.insert(NewAI);
5916 } else {
5917 // If we have either PHIs or Selects to rewrite, add them to those
5918 // worklists and re-queue the new alloca so that we promote it on the next
5919 // iteration.
5920 SpeculatablePHIs.insert_range(NewSpeculatablePHIs);
5921 PHIsWithStoreToRewrite.insert_range(NewPHIsWithStoreToRewrite);
5922 SelectsToRewrite.reserve(SelectsToRewrite.size() +
5923 NewSelectsToRewrite.size());
5924 for (auto &&KV : llvm::make_range(
5925 std::make_move_iterator(NewSelectsToRewrite.begin()),
5926 std::make_move_iterator(NewSelectsToRewrite.end())))
5927 SelectsToRewrite.insert(std::move(KV));
5928 Worklist.insert(NewAI);
5929 }
5930 } else {
5931 // Drop any post-promotion work items if promotion didn't happen.
5932 while (PostPromotionWorklist.size() > PPWOldSize)
5933 PostPromotionWorklist.pop_back();
5934
5935 // We couldn't promote and we didn't create a new partition, nothing
5936 // happened.
5937 if (NewAI == &AI)
5938 return {nullptr, 0};
5939
5940 // If we can't promote the alloca, iterate on it to check for new
5941 // refinements exposed by splitting the current alloca. Don't iterate on an
5942 // alloca which didn't actually change and didn't get promoted.
5943 Worklist.insert(NewAI);
5944 }
5945
5946 return {NewAI, DL.getTypeSizeInBits(PartitionTy).getFixedValue()};
5947}
5948
5949// There isn't a shared interface to get the "address" parts out of a
5950// dbg.declare and dbg.assign, so provide some wrappers.
5953 return DVR->isKillAddress();
5954 return DVR->isKillLocation();
5955}
5956
5959 return DVR->getAddressExpression();
5960 return DVR->getExpression();
5961}
5962
5963/// Create or replace an existing fragment in a DIExpression with \p Frag.
5964/// If the expression already contains a DW_OP_LLVM_extract_bits_[sz]ext
5965/// operation, add \p BitExtractOffset to the offset part.
5966///
5967/// Returns the new expression, or nullptr if this fails (see details below).
5968///
5969/// This function is similar to DIExpression::createFragmentExpression except
5970/// for 3 important distinctions:
5971/// 1. The new fragment isn't relative to an existing fragment.
5972/// 2. It assumes the computed location is a memory location. This means we
5973/// don't need to perform checks that creating the fragment preserves the
5974/// expression semantics.
5975/// 3. Existing extract_bits are modified independently of fragment changes
5976/// using \p BitExtractOffset. A change to the fragment offset or size
5977/// may affect a bit extract. But a bit extract offset can change
5978/// independently of the fragment dimensions.
5979///
5980/// Returns the new expression, or nullptr if one couldn't be created.
5981/// Ideally this is only used to signal that a bit-extract has become
5982/// zero-sized (and thus the new debug record has no size and can be
5983/// dropped), however, it fails for other reasons too - see the FIXME below.
5984///
5985/// FIXME: To keep the change that introduces this function NFC it bails
5986/// in some situations unecessarily, e.g. when fragment and bit extract
5987/// sizes differ.
5990 int64_t BitExtractOffset) {
5992 bool HasFragment = false;
5993 bool HasBitExtract = false;
5994
5995 for (auto &Op : Expr->expr_ops()) {
5996 if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
5997 HasFragment = true;
5998 continue;
5999 }
6000 if (auto Extract = dyn_cast<DIExpression::ExtractBitsOp>(Op)) {
6001 HasBitExtract = true;
6002 int64_t ExtractOffsetInBits = Extract.getOffsetInBits();
6003 int64_t ExtractSizeInBits = Extract.getSizeInBits();
6004
6005 // DIExpression::createFragmentExpression doesn't know how to handle
6006 // a fragment that is smaller than the extract. Copy the behaviour
6007 // (bail) to avoid non-NFC changes.
6008 // FIXME: Don't do this.
6009 if (Frag.SizeInBits < uint64_t(ExtractSizeInBits))
6010 return nullptr;
6011
6012 assert(BitExtractOffset <= 0);
6013 int64_t AdjustedOffset = ExtractOffsetInBits + BitExtractOffset;
6014
6015 // DIExpression::createFragmentExpression doesn't know what to do
6016 // if the new extract starts "outside" the existing one. Copy the
6017 // behaviour (bail) to avoid non-NFC changes.
6018 // FIXME: Don't do this.
6019 if (AdjustedOffset < 0)
6020 return nullptr;
6021
6022 Ops.push_back(Op.getOp());
6023 Ops.push_back(std::max<int64_t>(0, AdjustedOffset));
6024 Ops.push_back(ExtractSizeInBits);
6025 continue;
6026 }
6027 Op.appendToVector(Ops);
6028 }
6029
6030 // Unsupported by createFragmentExpression, so don't support it here yet to
6031 // preserve NFC-ness.
6032 if (HasFragment && HasBitExtract)
6033 return nullptr;
6034
6035 if (!HasBitExtract) {
6037 Ops.push_back(Frag.OffsetInBits);
6038 Ops.push_back(Frag.SizeInBits);
6039 }
6040 return DIExpression::get(Expr->getContext(), Ops);
6041}
6042
6043/// Insert a new DbgRecord.
6044/// \p Orig Original to copy record type, debug loc and variable from, and
6045/// additionally value and value expression for dbg_assign records.
6046/// \p NewAddr Location's new base address.
6047/// \p NewAddrExpr New expression to apply to address.
6048/// \p BeforeInst Insert position.
6049/// \p NewFragment New fragment (absolute, non-relative).
6050/// \p BitExtractAdjustment Offset to apply to any extract_bits op.
6051static void
6053 DIExpression *NewAddrExpr, Instruction *BeforeInst,
6054 std::optional<DIExpression::FragmentInfo> NewFragment,
6055 int64_t BitExtractAdjustment) {
6056 (void)DIB;
6057
6058 // A dbg_assign puts fragment info in the value expression only. The address
6059 // expression has already been built: NewAddrExpr. A dbg_declare puts the
6060 // new fragment info into NewAddrExpr (as it only has one expression).
6061 DIExpression *NewFragmentExpr =
6062 Orig->isDbgAssign() ? Orig->getExpression() : NewAddrExpr;
6063 if (NewFragment)
6064 NewFragmentExpr = createOrReplaceFragment(NewFragmentExpr, *NewFragment,
6065 BitExtractAdjustment);
6066 if (!NewFragmentExpr)
6067 return;
6068
6069 if (Orig->isDbgDeclare()) {
6071 NewAddr, Orig->getVariable(), NewFragmentExpr, Orig->getDebugLoc());
6072 BeforeInst->getParent()->insertDbgRecordBefore(DVR,
6073 BeforeInst->getIterator());
6074 return;
6075 }
6076
6077 if (Orig->isDbgValue()) {
6079 NewAddr, Orig->getVariable(), NewFragmentExpr, Orig->getDebugLoc());
6080 // Drop debug information if the expression doesn't start with a
6081 // DW_OP_deref. This is because without a DW_OP_deref, the #dbg_value
6082 // describes the address of alloca rather than the value inside the alloca.
6083 if (!NewFragmentExpr->startsWithDeref())
6084 DVR->setKillAddress();
6085 BeforeInst->getParent()->insertDbgRecordBefore(DVR,
6086 BeforeInst->getIterator());
6087 return;
6088 }
6089
6090 // Apply a DIAssignID to the store if it doesn't already have it.
6091 if (!NewAddr->hasMetadata(LLVMContext::MD_DIAssignID)) {
6092 NewAddr->setMetadata(LLVMContext::MD_DIAssignID,
6094 }
6095
6097 NewAddr, Orig->getValue(), Orig->getVariable(), NewFragmentExpr, NewAddr,
6098 NewAddrExpr, Orig->getDebugLoc());
6099 LLVM_DEBUG(dbgs() << "Created new DVRAssign: " << *NewAssign << "\n");
6100 (void)NewAssign;
6101}
6102
6103/// Walks the slices of an alloca and form partitions based on them,
6104/// rewriting each of their uses.
6105bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
6106 if (AS.begin() == AS.end())
6107 return false;
6108
6109 unsigned NumPartitions = 0;
6110 bool Changed = false;
6111 const DataLayout &DL = AI.getDataLayout();
6112
6113 // First try to pre-split loads and stores.
6114 Changed |= presplitLoadsAndStores(AI, AS);
6115
6116 // Now that we have identified any pre-splitting opportunities,
6117 // mark loads and stores unsplittable except for the following case.
6118 // We leave a slice splittable if all other slices are disjoint or fully
6119 // included in the slice, such as whole-alloca loads and stores.
6120 // If we fail to split these during pre-splitting, we want to force them
6121 // to be rewritten into a partition.
6122 bool IsSorted = true;
6123
6124 uint64_t AllocaSize = AI.getAllocationSize(DL)->getFixedValue();
6125 // We can split at the begin and end offsets of each slice, but only if those
6126 // offsets don't lie inside another slice. Because slices are ordered by
6127 // increasing begin offset, and then decreasing end offset, we can consider
6128 // the slices as being split up into sets with the same begin offset where we
6129 // can ignore every slice except the first (the begin offset will already be
6130 // handled as the begin offset of the set, and the end offset we know is not a
6131 // splittable offset as it's inside the first slice of the set).
6132 SparseBitVector<> SplittableOffset;
6133 uint64_t CurBegin = 0, CurEnd = 0;
6134 for (Slice &S : AS) {
6135 // Check if we have a new set of slices
6136 if (S.beginOffset() > CurBegin || S.endOffset() > CurEnd) {
6137 // If the start isn't inside the previous set it's splittable
6138 if (S.beginOffset() >= CurEnd) {
6139 SplittableOffset.set(S.beginOffset());
6140 }
6141 // If the previous end is inside this slice then remove it
6142 if (CurEnd > S.beginOffset() && CurEnd < S.endOffset()) {
6143 SplittableOffset.reset(CurEnd);
6144 }
6145 CurBegin = S.beginOffset();
6146 // If the end offset isn't inside the previous set it's splittable. We
6147 // also don't update the end offset in that case, as the next set may also
6148 // be inside the previous set.
6149 if (S.endOffset() > CurEnd) {
6150 CurEnd = S.endOffset();
6151 SplittableOffset.set(CurEnd);
6152 }
6153 }
6154 }
6155
6156 for (Slice &S : AS) {
6157 if (!S.isSplittable())
6158 continue;
6159
6160 if ((S.beginOffset() > AllocaSize ||
6161 SplittableOffset.test(S.beginOffset())) &&
6162 (S.endOffset() > AllocaSize || SplittableOffset.test(S.endOffset())))
6163 continue;
6164
6165 if (isa<LoadInst>(S.getUse()->getUser()) ||
6166 isa<StoreInst>(S.getUse()->getUser())) {
6167 S.makeUnsplittable();
6168 IsSorted = false;
6169 }
6170 }
6171
6172 if (!IsSorted)
6174
6175 /// Describes the allocas introduced by rewritePartition in order to migrate
6176 /// the debug info.
6177 struct Fragment {
6178 AllocaInst *Alloca;
6180 uint64_t Size;
6181 Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
6182 : Alloca(AI), Offset(O), Size(S) {}
6183 };
6184 SmallVector<Fragment, 4> Fragments;
6185
6186 // Rewrite each partition.
6187 for (auto &P : AS.partitions()) {
6188 auto [NewAI, ActiveBits] = rewritePartition(AI, AS, P);
6189 if (NewAI) {
6190 Changed = true;
6191 if (NewAI != &AI) {
6192 uint64_t SizeOfByte = 8;
6193 // Don't include any padding.
6194 uint64_t Size = std::min(ActiveBits, P.size() * SizeOfByte);
6195 Fragments.push_back(
6196 Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
6197 }
6198 }
6199 ++NumPartitions;
6200 }
6201
6202 NumAllocaPartitions += NumPartitions;
6203 MaxPartitionsPerAlloca.updateMax(NumPartitions);
6204
6205 // Migrate debug information from the old alloca to the new alloca(s)
6206 // and the individual partitions.
6207 auto MigrateOne = [&](DbgVariableRecord *DbgVariable) {
6208 // Can't overlap with undef memory.
6209 if (isKillAddress(DbgVariable))
6210 return;
6211
6212 const Value *DbgPtr = DbgVariable->getAddress();
6214 DbgVariable->getFragmentOrEntireVariable();
6215 // Get the address expression constant offset if one exists and the ops
6216 // that come after it.
6217 int64_t CurrentExprOffsetInBytes = 0;
6218 SmallVector<uint64_t> PostOffsetOps;
6219 if (!getAddressExpression(DbgVariable)
6220 ->extractLeadingOffset(CurrentExprOffsetInBytes, PostOffsetOps))
6221 return; // Couldn't interpret this DIExpression - drop the var.
6222
6223 // Offset defined by a DW_OP_LLVM_extract_bits_[sz]ext.
6224 int64_t ExtractOffsetInBits = 0;
6225 for (auto Op : getAddressExpression(DbgVariable)->expr_ops()) {
6226 if (auto Extract = dyn_cast<DIExpression::ExtractBitsOp>(Op)) {
6227 ExtractOffsetInBits = Extract.getOffsetInBits();
6228 break;
6229 }
6230 }
6231
6232 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
6233 for (auto Fragment : Fragments) {
6234 int64_t OffsetFromLocationInBits;
6235 std::optional<DIExpression::FragmentInfo> NewDbgFragment;
6236 // Find the variable fragment that the new alloca slice covers.
6237 // Drop debug info for this variable fragment if we can't compute an
6238 // intersect between it and the alloca slice.
6240 DL, &AI, Fragment.Offset, Fragment.Size, DbgPtr,
6241 CurrentExprOffsetInBytes * 8, ExtractOffsetInBits, VarFrag,
6242 NewDbgFragment, OffsetFromLocationInBits))
6243 continue; // Do not migrate this fragment to this slice.
6244
6245 // Zero sized fragment indicates there's no intersect between the variable
6246 // fragment and the alloca slice. Skip this slice for this variable
6247 // fragment.
6248 if (NewDbgFragment && !NewDbgFragment->SizeInBits)
6249 continue; // Do not migrate this fragment to this slice.
6250
6251 // No fragment indicates DbgVariable's variable or fragment exactly
6252 // overlaps the slice; copy its fragment (or nullopt if there isn't one).
6253 if (!NewDbgFragment)
6254 NewDbgFragment = DbgVariable->getFragment();
6255
6256 // Reduce the new expression offset by the bit-extract offset since
6257 // we'll be keeping that.
6258 int64_t OffestFromNewAllocaInBits =
6259 OffsetFromLocationInBits - ExtractOffsetInBits;
6260 // We need to adjust an existing bit extract if the offset expression
6261 // can't eat the slack (i.e., if the new offset would be negative).
6262 int64_t BitExtractOffset =
6263 std::min<int64_t>(0, OffestFromNewAllocaInBits);
6264 // The magnitude of a negative value indicates the number of bits into
6265 // the existing variable fragment that the memory region begins. The new
6266 // variable fragment already excludes those bits - the new DbgPtr offset
6267 // only needs to be applied if it's positive.
6268 OffestFromNewAllocaInBits =
6269 std::max(int64_t(0), OffestFromNewAllocaInBits);
6270
6271 // Rebuild the expression:
6272 // {Offset(OffestFromNewAllocaInBits), PostOffsetOps, NewDbgFragment}
6273 // Add NewDbgFragment later, because dbg.assigns don't want it in the
6274 // address expression but the value expression instead.
6275 DIExpression *NewExpr = DIExpression::get(AI.getContext(), PostOffsetOps);
6276 if (OffestFromNewAllocaInBits > 0) {
6277 int64_t OffsetInBytes = (OffestFromNewAllocaInBits + 7) / 8;
6278 NewExpr = DIExpression::prepend(NewExpr, /*flags=*/0, OffsetInBytes);
6279 }
6280
6281 // Remove any existing intrinsics on the new alloca describing
6282 // the variable fragment.
6283 auto RemoveOne = [DbgVariable](auto *OldDII) {
6284 auto SameVariableFragment = [](const auto *LHS, const auto *RHS) {
6285 return LHS->getVariable() == RHS->getVariable() &&
6286 LHS->getDebugLoc()->getInlinedAt() ==
6287 RHS->getDebugLoc()->getInlinedAt();
6288 };
6289 if (SameVariableFragment(OldDII, DbgVariable))
6290 OldDII->eraseFromParent();
6291 };
6292 for_each(findDVRDeclares(Fragment.Alloca), RemoveOne);
6293 for_each(findDVRValues(Fragment.Alloca), RemoveOne);
6294 insertNewDbgInst(DIB, DbgVariable, Fragment.Alloca, NewExpr, &AI,
6295 NewDbgFragment, BitExtractOffset);
6296 }
6297 };
6298
6299 // Migrate debug information from the old alloca to the new alloca(s)
6300 // and the individual partitions.
6301 for_each(findDVRDeclares(&AI), MigrateOne);
6302 for_each(findDVRValues(&AI), MigrateOne);
6303 for_each(at::getDVRAssignmentMarkers(&AI), MigrateOne);
6304
6305 return Changed;
6306}
6307
6308/// Clobber a use with poison, deleting the used value if it becomes dead.
6309void SROA::clobberUse(Use &U) {
6310 Value *OldV = U;
6311 // Replace the use with an poison value.
6312 U = PoisonValue::get(OldV->getType());
6313
6314 // Check for this making an instruction dead. We have to garbage collect
6315 // all the dead instructions to ensure the uses of any alloca end up being
6316 // minimal.
6317 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
6318 if (isInstructionTriviallyDead(OldI)) {
6319 DeadInsts.push_back(OldI);
6320 }
6321}
6322
6323/// A basic LoadAndStorePromoter that does not remove store nodes.
6325public:
6327 Type *ZeroType)
6328 : LoadAndStorePromoter(Insts, S), ZeroType(ZeroType) {}
6329 bool shouldDelete(Instruction *I) const override {
6330 return !isa<StoreInst>(I) && !isa<AllocaInst>(I);
6331 }
6332
6334 return UndefValue::get(ZeroType);
6335 }
6336
6337private:
6338 Type *ZeroType;
6339};
6340
6341bool SROA::propagateStoredValuesToLoads(AllocaInst &AI, AllocaSlices &AS) {
6342 // Look through each "partition", looking for slices with the same start/end
6343 // that do not overlap with any before them. The slices are sorted by
6344 // increasing beginOffset. We don't use AS.partitions(), as it will use a more
6345 // sophisticated algorithm that takes splittable slices into account.
6346 LLVM_DEBUG(dbgs() << "Attempting to propagate values on " << AI << "\n");
6347 bool AllSameAndValid = true;
6348 Type *PartitionType = nullptr;
6349 SmallVector<Instruction *> Insts;
6350 uint64_t BeginOffset = 0;
6351 uint64_t EndOffset = 0;
6352
6353 auto Flush = [&]() {
6354 if (AllSameAndValid && !Insts.empty()) {
6355 LLVM_DEBUG(dbgs() << "Propagate values on slice [" << BeginOffset << ", "
6356 << EndOffset << ")\n");
6358 SSAUpdater SSA(&NewPHIs);
6359 Insts.push_back(&AI);
6360 BasicLoadAndStorePromoter Promoter(Insts, SSA, PartitionType);
6361 Promoter.run(Insts);
6362 }
6363 AllSameAndValid = true;
6364 PartitionType = nullptr;
6365 Insts.clear();
6366 };
6367
6368 for (Slice &S : AS) {
6369 auto *User = cast<Instruction>(S.getUse()->getUser());
6370 if (isAssumeLikeIntrinsic(User)) {
6371 LLVM_DEBUG({
6372 dbgs() << "Ignoring slice: ";
6373 AS.print(dbgs(), &S);
6374 });
6375 continue;
6376 }
6377 if (S.beginOffset() >= EndOffset) {
6378 Flush();
6379 BeginOffset = S.beginOffset();
6380 EndOffset = S.endOffset();
6381 } else if (S.beginOffset() != BeginOffset || S.endOffset() != EndOffset) {
6382 if (AllSameAndValid) {
6383 LLVM_DEBUG({
6384 dbgs() << "Slice does not match range [" << BeginOffset << ", "
6385 << EndOffset << ")";
6386 AS.print(dbgs(), &S);
6387 });
6388 AllSameAndValid = false;
6389 }
6390 EndOffset = std::max(EndOffset, S.endOffset());
6391 continue;
6392 }
6393
6394 if (auto *LI = dyn_cast<LoadInst>(User)) {
6395 Type *UserTy = LI->getType();
6396 // LoadAndStorePromoter requires all the types to be the same.
6397 if (!LI->isSimple() || (PartitionType && UserTy != PartitionType))
6398 AllSameAndValid = false;
6399 PartitionType = UserTy;
6400 Insts.push_back(User);
6401 } else if (auto *SI = dyn_cast<StoreInst>(User)) {
6402 Type *UserTy = SI->getValueOperand()->getType();
6403 if (!SI->isSimple() || (PartitionType && UserTy != PartitionType))
6404 AllSameAndValid = false;
6405 PartitionType = UserTy;
6406 Insts.push_back(User);
6407 } else {
6408 AllSameAndValid = false;
6409 }
6410 }
6411
6412 Flush();
6413 return true;
6414}
6415
6416/// Analyze an alloca for SROA.
6417///
6418/// This analyzes the alloca to ensure we can reason about it, builds
6419/// the slices of the alloca, and then hands it off to be split and
6420/// rewritten as needed.
6421std::pair<bool /*Changed*/, bool /*CFGChanged*/>
6422SROA::runOnAlloca(AllocaInst &AI) {
6423 bool Changed = false;
6424 bool CFGChanged = false;
6425
6426 LLVM_DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
6427 ++NumAllocasAnalyzed;
6428
6429 // Special case dead allocas, as they're trivial.
6430 if (AI.use_empty()) {
6431 DeadInsts.push_back(&AI);
6432 Changed = true;
6433 return {Changed, CFGChanged};
6434 }
6435 const DataLayout &DL = AI.getDataLayout();
6436
6437 // Skip alloca forms that this analysis can't handle.
6438 std::optional<TypeSize> Size = AI.getAllocationSize(DL);
6439 if (AI.isArrayAllocation() || !Size || Size->isScalable() || Size->isZero())
6440 return {Changed, CFGChanged};
6441
6442 // First, split any FCA loads and stores touching this alloca to promote
6443 // better splitting and promotion opportunities.
6444 IRBuilderTy IRB(&AI);
6445 IRB.disableGEPCanonicalization();
6446 AggLoadStoreRewriter AggRewriter(DL, IRB);
6447 Changed |= AggRewriter.rewrite(AI);
6448
6449 // Build the slices using a recursive instruction-visiting builder.
6450 AllocaSlices AS(DL, AI);
6451 LLVM_DEBUG(AS.print(dbgs()));
6452 if (AS.isEscaped())
6453 return {Changed, CFGChanged};
6454
6455 if (AS.isEscapedReadOnly()) {
6456 Changed |= propagateStoredValuesToLoads(AI, AS);
6457 return {Changed, CFGChanged};
6458 }
6459
6460 // Delete all the dead users of this alloca before splitting and rewriting it.
6461 for (Instruction *DeadUser : AS.getDeadUsers()) {
6462 // Free up everything used by this instruction.
6463 for (Use &DeadOp : DeadUser->operands())
6464 clobberUse(DeadOp);
6465
6466 // Now replace the uses of this instruction.
6467 DeadUser->replaceAllUsesWith(PoisonValue::get(DeadUser->getType()));
6468
6469 // And mark it for deletion.
6470 DeadInsts.push_back(DeadUser);
6471 Changed = true;
6472 }
6473 for (Use *DeadOp : AS.getDeadOperands()) {
6474 clobberUse(*DeadOp);
6475 Changed = true;
6476 }
6477
6478 // No slices to split. Leave the dead alloca for a later pass to clean up.
6479 if (AS.begin() == AS.end())
6480 return {Changed, CFGChanged};
6481
6482 Changed |= splitAlloca(AI, AS);
6483
6484 LLVM_DEBUG(dbgs() << " Speculating PHIs\n");
6485 while (!SpeculatablePHIs.empty())
6486 speculatePHINodeLoads(IRB, *SpeculatablePHIs.pop_back_val());
6487
6488 LLVM_DEBUG(dbgs() << " Rewriting stores through PHIs\n");
6489 auto RemainingPHIsWithStoreToRewrite = PHIsWithStoreToRewrite.takeVector();
6490 while (!RemainingPHIsWithStoreToRewrite.empty()) {
6491 PHINode *PN = RemainingPHIsWithStoreToRewrite.pop_back_val();
6492 auto *SI = cast<StoreInst>(PN->user_back());
6493 CFGChanged |= rewritePHINodeStore(*PN, *SI, *DTU, Worklist);
6494 }
6495
6496 LLVM_DEBUG(dbgs() << " Rewriting Selects\n");
6497 auto RemainingSelectsToRewrite = SelectsToRewrite.takeVector();
6498 while (!RemainingSelectsToRewrite.empty()) {
6499 const auto [K, V] = RemainingSelectsToRewrite.pop_back_val();
6500 CFGChanged |=
6501 rewriteSelectInstMemOps(*K, V, IRB, PreserveCFG ? nullptr : DTU);
6502 }
6503
6504 return {Changed, CFGChanged};
6505}
6506
6507/// Delete the dead instructions accumulated in this run.
6508///
6509/// Recursively deletes the dead instructions we've accumulated. This is done
6510/// at the very end to maximize locality of the recursive delete and to
6511/// minimize the problems of invalidated instruction pointers as such pointers
6512/// are used heavily in the intermediate stages of the algorithm.
6513///
6514/// We also record the alloca instructions deleted here so that they aren't
6515/// subsequently handed to mem2reg to promote.
6516bool SROA::deleteDeadInstructions(
6517 AllocaInst *AI, SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
6518 bool Changed = false;
6519 while (!DeadInsts.empty()) {
6520 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
6521 if (!I)
6522 continue;
6523 LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
6524
6525 // If the instruction is an alloca, find the possible dbg.declare connected
6526 // to it, and remove it too. We must do this before calling RAUW or we will
6527 // not be able to find it.
6528 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
6529 DeletedAllocas.insert(AI);
6530 for (DbgVariableRecord *OldDII : findDVRDeclares(AI))
6531 OldDII->eraseFromParent();
6532 }
6533
6535 I->replaceAllUsesWith(UndefValue::get(I->getType()));
6536
6537 for (Use &Operand : I->operands())
6538 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
6539 // Zero out the operand and see if it becomes trivially dead.
6540 Operand = nullptr;
6542 DeadInsts.push_back(U);
6543 }
6544
6545 ++NumDeleted;
6546 I->eraseFromParent();
6547 Changed = true;
6548 }
6549
6550 if (!DeletedAllocas.contains(AI) && AI->hasNUndroppableUses(0)) {
6551 DeletedAllocas.insert(AI);
6552 AI->dropDroppableUses();
6553 for (DbgVariableRecord *OldDII : findDVRDeclares(AI))
6554 OldDII->eraseFromParent();
6555 ++NumDeleted;
6556 AI->eraseFromParent();
6557 Changed = true;
6558 }
6559
6560 return Changed;
6561}
6562/// Promote the allocas, using the best available technique.
6563///
6564/// This attempts to promote whatever allocas have been identified as viable in
6565/// the PromotableAllocas list. If that list is empty, there is nothing to do.
6566/// This function returns whether any promotion occurred.
6567bool SROA::promoteAllocas() {
6568 if (PromotableAllocas.empty())
6569 return false;
6570
6571 if (getScalarOptions(*C).sroa_skip_mem2reg) {
6572 LLVM_DEBUG(dbgs() << "Not promoting allocas with mem2reg!\n");
6573 } else {
6574 LLVM_DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
6575 NumPromoted += PromotableAllocas.size();
6576 PromoteMemToReg(PromotableAllocas.getArrayRef(), DTU->getDomTree(), AC);
6577 }
6578
6579 PromotableAllocas.clear();
6580 return true;
6581}
6582
6583std::pair<bool /*Changed*/, bool /*CFGChanged*/> SROA::runSROA(Function &F) {
6584 LLVM_DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
6585
6586 const DataLayout &DL = F.getDataLayout();
6587 BasicBlock &EntryBB = F.getEntryBlock();
6588 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
6589 I != E; ++I) {
6590 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
6591 std::optional<TypeSize> Size = AI->getAllocationSize(DL);
6592 if (Size && Size->isScalable() && isAllocaPromotable(AI))
6593 PromotableAllocas.insert(AI);
6594 else
6595 Worklist.insert(AI);
6596 }
6597 }
6598
6599 bool Changed = false;
6600 bool CFGChanged = false;
6601 // A set of deleted alloca instruction pointers which should be removed from
6602 // the list of promotable allocas.
6603 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
6604
6605 do {
6606 while (!Worklist.empty()) {
6607 AllocaInst *AI = Worklist.pop_back_val();
6608 auto [IterationChanged, IterationCFGChanged] = runOnAlloca(*AI);
6609 Changed |= IterationChanged;
6610 CFGChanged |= IterationCFGChanged;
6611
6612 Changed |= deleteDeadInstructions(AI, DeletedAllocas);
6613
6614 // Remove the deleted allocas from various lists so that we don't try to
6615 // continue processing them.
6616 if (!DeletedAllocas.empty()) {
6617 Worklist.set_subtract(DeletedAllocas);
6618 PostPromotionWorklist.set_subtract(DeletedAllocas);
6619 PromotableAllocas.set_subtract(DeletedAllocas);
6620 DeletedAllocas.clear();
6621 }
6622 }
6623
6624 Changed |= promoteAllocas();
6625
6626 Worklist = PostPromotionWorklist;
6627 PostPromotionWorklist.clear();
6628 } while (!Worklist.empty());
6629
6630 assert((!CFGChanged || Changed) && "Can not only modify the CFG.");
6631 assert((!CFGChanged || !PreserveCFG) &&
6632 "Should not have modified the CFG when told to preserve it.");
6633
6634 if (Changed && isAssignmentTrackingEnabled(*F.getParent())) {
6635 for (auto &BB : F) {
6637 }
6638 }
6639
6640 return {Changed, CFGChanged};
6641}
6642
6646 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
6647 auto [Changed, CFGChanged] =
6648 SROA(&F.getContext(), &DTU, &AC, Options).runSROA(F);
6649 if (!Changed)
6650 return PreservedAnalyses::all();
6652 if (!CFGChanged)
6655 return PA;
6656}
6657
6659 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
6660 static_cast<PassInfoMixin<SROAPass> *>(this)->printPipeline(
6661 OS, MapClassName2PassName);
6662 OS << '<'
6663 << (Options.CFG == SROAOptions::PreserveCFG ? "preserve-cfg"
6664 : "modify-cfg");
6665 if (Options.AggregateToVector)
6666 OS << ";aggregate-to-vector";
6667 OS << '>';
6668}
6669
6670SROAPass::SROAPass(SROAOptions Options) : Options(Options) {}
6671
6672namespace {
6673
6674/// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
6675class SROALegacyPass : public FunctionPass {
6677
6678public:
6679 static char ID;
6680
6682 : FunctionPass(ID), Options(Options) {
6684 }
6685
6686 bool runOnFunction(Function &F) override {
6687 if (skipFunction(F))
6688 return false;
6689
6690 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
6691 AssumptionCache &AC =
6692 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
6693 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
6694 auto [Changed, _] = SROA(&F.getContext(), &DTU, &AC, Options).runSROA(F);
6695 return Changed;
6696 }
6697
6698 void getAnalysisUsage(AnalysisUsage &AU) const override {
6699 AU.addRequired<AssumptionCacheTracker>();
6700 AU.addRequired<DominatorTreeWrapperPass>();
6701 AU.addPreserved<GlobalsAAWrapperPass>();
6702 AU.addPreserved<DominatorTreeWrapperPass>();
6703 }
6704
6705 StringRef getPassName() const override { return "SROA"; }
6706};
6707
6708} // end anonymous namespace
6709
6710char SROALegacyPass::ID = 0;
6711
6712FunctionPass *llvm::createSROAPass(bool PreserveCFG, bool AggregateToVector) {
6713 return new SROALegacyPass(SROAOptions(PreserveCFG ? SROAOptions::PreserveCFG
6715 AggregateToVector));
6716}
6717
6718INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
6719 "Scalar Replacement Of Aggregates", false, false)
6722INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
uint64_t uint64_t
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Forward Handle Accesses
DXIL Resource Access
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
Flatten the CFG
#define DEBUG_TYPE
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
#define _
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
iv Induction Variable Users
Definition IVUsers.cpp:48
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
print mir2vec MIR2Vec Vocabulary Printer Pass
Definition MIR2Vec.cpp:656
This file implements a map that provides insertion order iteration.
static std::optional< AllocFnsTy > getAllocationSize(const CallBase *CB, const TargetLibraryInfo *TLI)
static std::optional< uint64_t > getSizeInBytes(std::optional< uint64_t > SizeInBits)
Memory SSA
Definition MemorySSA.cpp:69
This file contains the declarations for metadata subclasses.
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PassBuilder PB(Mod->getContext(), Machine, PassOpts->PTO, std::nullopt, &PIC)
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file defines the PointerIntPair class.
This file provides a collection of visitors which walk the (instruction) uses of a pointer.
SmallVector< MachineOperand, 4 > Cond
Remove Loads Into Fake Uses
bool isDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
static void migrateDebugInfo(AllocaInst *OldAlloca, bool IsSplit, uint64_t OldAllocaOffsetInBits, uint64_t SliceSizeInBits, Instruction *OldInst, Instruction *Inst, Value *Dest, Value *Value, const DataLayout &DL)
Find linked dbg.assign and generate a new one with the correct FragmentInfo.
Definition SROA.cpp:375
static VectorType * isVectorPromotionViable(Partition &P, const DataLayout &DL, unsigned VScale)
Test whether the given alloca partitioning and range of slices can be promoted to a vector.
Definition SROA.cpp:2423
static Align getAdjustedAlignment(Instruction *I, uint64_t Offset)
Compute the adjusted alignment for a load or store from an offset.
Definition SROA.cpp:2093
static VectorType * checkVectorTypesForPromotion(Partition &P, const DataLayout &DL, SmallVectorImpl< VectorType * > &CandidateTys, bool HaveCommonEltTy, Type *CommonEltTy, bool HaveVecPtrTy, bool HaveCommonVecPtrTy, VectorType *CommonVecPtrTy, unsigned VScale)
Test whether any vector type in CandidateTys is viable for promotion.
Definition SROA.cpp:2277
static std::pair< Type *, IntegerType * > findCommonType(AllocaSlices::const_iterator B, AllocaSlices::const_iterator E, uint64_t EndOffset)
Walk the range of a partitioning looking for a common type to cover this sequence of slices.
Definition SROA.cpp:1539
static Type * stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty)
Strip aggregate type wrapping.
Definition SROA.cpp:4851
static void rewriteMemOpOfSelect(SelectInst &SI, T &I, SelectHandSpeculativity Spec, IRBuilderTy &IRB, DomTreeUpdater &DTU)
Definition SROA.cpp:1975
static FragCalcResult calculateFragment(DILocalVariable *Variable, uint64_t NewStorageSliceOffsetInBits, uint64_t NewStorageSliceSizeInBits, std::optional< DIExpression::FragmentInfo > StorageFragment, std::optional< DIExpression::FragmentInfo > CurrentFragment, DIExpression::FragmentInfo &Target)
Definition SROA.cpp:310
static DIExpression * createOrReplaceFragment(const DIExpression *Expr, DIExpression::FragmentInfo Frag, int64_t BitExtractOffset)
Create or replace an existing fragment in a DIExpression with Frag.
Definition SROA.cpp:5988
static Value * insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old, Value *V, uint64_t Offset, const Twine &Name)
Definition SROA.cpp:2666
static Value * getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr, APInt Offset, Type *PointerTy, const Twine &NamePrefix)
Compute an adjusted pointer from Ptr by Offset bytes where the resulting pointer has PointerTy.
Definition SROA.cpp:2082
static bool isIntegerWideningViableForSlice(const Slice &S, uint64_t AllocBeginOffset, Type *AllocaTy, const DataLayout &DL, bool &WholeAllocaOp)
Test whether a slice of an alloca is valid for integer widening.
Definition SROA.cpp:2505
static bool rewritePHINodeStore(PHINode &PN, StoreInst &SI, DomTreeUpdater &DTU, SmallSetVector< AllocaInst *, 16 > &Worklist)
Move a store through a pointer PHI onto each of the PHI's incoming edges.
Definition SROA.cpp:1792
static Value * extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex, unsigned EndIndex, const Twine &Name)
Definition SROA.cpp:2699
static Value * foldPHINodeOrSelectInst(Instruction &I)
A helper that folds a PHI node or a select.
Definition SROA.cpp:1035
static bool rewriteSelectInstMemOps(SelectInst &SI, const RewriteableMemOps &Ops, IRBuilderTy &IRB, DomTreeUpdater *DTU)
Definition SROA.cpp:2048
static Slice * findOverlappingCopySlice(Slice &S, InstructionSliceMap &SliceMap)
Try to find a slice in the map that partially overlaps with S, i.e.
Definition SROA.cpp:5108
static Value * foldSelectInst(SelectInst &SI)
Definition SROA.cpp:1022
bool isKillAddress(const DbgVariableRecord *DVR)
Definition SROA.cpp:5951
static Value * insertVector(IRBuilderTy &IRB, Value *Old, Value *V, unsigned BeginIndex, const Twine &Name)
Definition SROA.cpp:2720
static bool isIntegerWideningViable(Partition &P, Type *AllocaTy, const DataLayout &DL)
Test whether the given alloca partition's integer operations can be widened to promotable ones.
Definition SROA.cpp:2600
static void speculatePHINodeLoads(IRBuilderTy &IRB, PHINode &PN)
Definition SROA.cpp:1737
static VectorType * createAndCheckVectorTypesForPromotion(SetVector< Type * > &OtherTys, ArrayRef< VectorType * > CandidateTysCopy, function_ref< void(Type *)> CheckCandidateType, Partition &P, const DataLayout &DL, SmallVectorImpl< VectorType * > &CandidateTys, bool &HaveCommonEltTy, Type *&CommonEltTy, bool &HaveVecPtrTy, bool &HaveCommonVecPtrTy, VectorType *&CommonVecPtrTy, unsigned VScale)
Definition SROA.cpp:2379
static DebugVariable getAggregateVariable(DbgVariableRecord *DVR)
Definition SROA.cpp:356
static std::tuple< Type *, bool, VectorType * > selectPartitionType(Partition &P, const DataLayout &DL, AllocaInst &AI, LLVMContext &C, bool AggregateToVector)
Select a partition type for an alloca partition.
Definition SROA.cpp:5668
static bool isSafePHIToSpeculate(PHINode &PN)
PHI instructions that use an alloca and are subsequently loaded can be rewritten to load both input p...
Definition SROA.cpp:1608
static FixedVectorType * tryCanonicalizeStructToVector(StructType *STy, Partition &P, const DataLayout &DL)
Try to canonicalize a homogeneous struct partition to a vector type.
Definition SROA.cpp:5608
static Value * extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V, IntegerType *Ty, uint64_t Offset, const Twine &Name)
Definition SROA.cpp:2641
static void insertNewDbgInst(DIBuilder &DIB, DbgVariableRecord *Orig, AllocaInst *NewAddr, DIExpression *NewAddrExpr, Instruction *BeforeInst, std::optional< DIExpression::FragmentInfo > NewFragment, int64_t BitExtractAdjustment)
Insert a new DbgRecord.
Definition SROA.cpp:6052
static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S, VectorType *Ty, uint64_t ElementBits, const DataLayout &DL, unsigned VScale)
Test whether the given slice use can be promoted to a vector.
Definition SROA.cpp:2191
static void speculateSelectInstLoads(SelectInst &SI, LoadInst &LI, IRBuilderTy &IRB)
Definition SROA.cpp:1931
static Value * mergeTwoVectors(Value *V0, Value *V1, const DataLayout &DL, Type *NewAIEltTy, IRBuilder<> &Builder)
This function takes two vector values and combines them into a single vector by concatenating their e...
Definition SROA.cpp:2791
const DIExpression * getAddressExpression(const DbgVariableRecord *DVR)
Definition SROA.cpp:5957
static Type * getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset, uint64_t Size)
Try to find a partition of the aggregate type passed in for a given offset and size.
Definition SROA.cpp:4889
static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy, unsigned VScale=0)
Test whether we can convert a value from the old to the new type.
Definition SROA.cpp:2103
static SelectHandSpeculativity isSafeLoadOfSelectToSpeculate(LoadInst &LI, SelectInst &SI, bool PreserveCFG)
Definition SROA.cpp:1863
static StoreInst * getPHIStoreToRewrite(PHINode &PN, bool PreserveCFG, DominatorTree &DT)
Check whether a single store through PN can be moved onto each incoming edge.
Definition SROA.cpp:1684
static Type * findCommonTypeThroughPHIOrSelect(Instruction &I)
Find a common load/store type used through a pointer PHI or select.
Definition SROA.cpp:1515
This file provides the interface for LLVM's Scalar Replacement of Aggregates pass.
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the SparseBitVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
virt reg Virtual Register Rewriter
Value * RHS
Value * LHS
Builder for the alloca slices.
Definition SROA.cpp:1047
SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
Definition SROA.cpp:1063
An iterator over partitions of the alloca's slices.
Definition SROA.cpp:835
bool operator==(const partition_iterator &RHS) const
Definition SROA.cpp:982
partition_iterator & operator++()
Definition SROA.cpp:1002
bool shouldDelete(Instruction *I) const override
Return false if a sub-class wants to keep one of the loads/stores after the SSA construction.
Definition SROA.cpp:6329
BasicLoadAndStorePromoter(ArrayRef< const Instruction * > Insts, SSAUpdater &S, Type *ZeroType)
Definition SROA.cpp:6326
Value * getValueToUseForAlloca(Instruction *I) const override
Return the value to use for the point in the code that the alloca is positioned.
Definition SROA.cpp:6333
SliceSplitter(IRBuilderTy &IRB, const DataLayout &DL, std::vector< uint64_t > &Splits, unsigned SliceSize)
Definition SROA.cpp:5014
StoreInst * createStore(Value *StoreVal, Value *BasePtr, Iterator &It, Instruction *SplitI)
Definition SROA.cpp:5062
Iterator begin()
Definition SROA.cpp:5042
Slice createSlice(Instruction *I, uint64_t BaseOffset, Iterator &It)
Definition SROA.cpp:5084
LoadInst * createLoad(Value *BasePtr, Iterator &It, Instruction *SplitI)
Definition SROA.cpp:5046
Iterator end()
Definition SROA.cpp:5044
Class for arbitrary precision integers.
Definition APInt.h:78
an instruction to allocate memory on the stack
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
PointerType * getType() const
Overload to return most specific pointer type.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrPseudoProbe() const
Returns an iterator to the first instruction in this block that is not a PHINode or a pseudo operatio...
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI bool canSplitPredecessors() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
LLVM_ABI CaptureInfo getCaptureInfo(unsigned OpNo) const
Return which pointer components this operand may capture.
bool onlyReadsMemory(unsigned OpNo) const
bool isDataOperand(const Use *U) const
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static DIAssignID * getDistinct(LLVMContext &Context)
LLVM_ABI DbgRecord * insertDbgAssign(Instruction *LinkedInstr, Value *Val, DILocalVariable *SrcVar, DIExpression *ValExpr, Value *Addr, DIExpression *AddrExpr, const DILocation *DL)
Insert a new dbg_assign record.
DWARF expression.
iterator_range< expr_op_iterator > expr_ops() const
DbgVariableFragmentInfo FragmentInfo
LLVM_ABI bool startsWithDeref() const
Return whether the first element a DW_OP_deref.
static LLVM_ABI bool calculateFragmentIntersect(const DataLayout &DL, const Value *SliceStart, uint64_t SliceOffsetInBits, uint64_t SliceSizeInBits, const Value *DbgPtr, int64_t DbgPtrOffsetInBits, int64_t DbgExtractOffsetInBits, DIExpression::FragmentInfo VarFrag, std::optional< DIExpression::FragmentInfo > &Result, int64_t &OffsetFromLocationInBits)
Computes a fragment, bit-extract operation if needed, and new constant offset to describe a part of a...
static LLVM_ABI std::optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
static LLVM_ABI DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI void moveBefore(DbgRecord *MoveBefore)
DebugLoc getDebugLoc() const
void setDebugLoc(DebugLoc Loc)
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI void setKillAddress()
Kill the address component.
LLVM_ABI bool isKillLocation() const
LLVM_ABI bool isKillAddress() const
Check whether this kills the address component.
LLVM_ABI void replaceVariableLocationOp(Value *OldValue, Value *NewValue, bool AllowEmpty=false)
Value * getValue(unsigned OpIdx=0) const
static LLVM_ABI DbgVariableRecord * createLinkedDVRAssign(Instruction *LinkedInstr, Value *Val, DILocalVariable *Variable, DIExpression *Expression, Value *Address, DIExpression *AddressExpression, const DILocation *DI)
LLVM_ABI void setAssignId(DIAssignID *New)
DIExpression * getExpression() const
static LLVM_ABI DbgVariableRecord * createDVRDeclare(Value *Address, DILocalVariable *DV, DIExpression *Expr, const DILocation *DI)
static LLVM_ABI DbgVariableRecord * createDbgVariableRecord(Value *Location, DILocalVariable *DV, DIExpression *Expr, const DILocation *DI)
DILocalVariable * getVariable() const
DIExpression * getAddressExpression() const
LLVM_ABI DILocation * getInlinedAt() const
Definition DebugLoc.cpp:58
Identifies a unique instance of a variable.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Class to represent fixed width SIMD vectors.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
unsigned getVScaleValue() const
Return the value for vscale based on the vscale_range attribute or 0 when unknown.
const BasicBlock & getEntryBlock() const
Definition Function.h:803
LLVM_ABI bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset, function_ref< bool(Value &, APInt &)> ExternalAnalysis=nullptr) const
Accumulate the constant address offset of this GEP if possible.
Definition Operator.cpp:130
iterator_range< op_iterator > indices()
Type * getSourceElementType() const
LLVM_ABI GEPNoWrapFlags getNoWrapFlags() const
Get the nowrap flags for the GEP instruction.
This provides the default implementation of the IRBuilder 'InsertHelper' method that is called whenev...
Definition IRBuilder.h:62
void InsertHelper(Instruction *I, const Twine &Name, BasicBlock::iterator InsertPt) const
Definition IRBuilder.h:64
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
Base class for instruction visitors.
Definition InstVisitor.h:78
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
user_iterator user_begin()
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Class to represent integer types.
@ MAX_INT_BITS
Maximum number of bits that can be specified.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI LoadAndStorePromoter(ArrayRef< const Instruction * > Insts, SSAUpdater &S, StringRef Name=StringRef())
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
void setAlignment(Align Align)
Value * getPointerOperand()
bool isVolatile() const
Return true if this is a load from a volatile memory location.
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this load instruction.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
Type * getPointerOperandType() const
static unsigned getPointerOperandIndex()
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
bool isSimple() const
Align getAlign() const
Return the alignment of the access that is being performed.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
LLVMContext & getContext() const
Definition Metadata.h:1251
This is the common base class for memset/memcpy/memmove.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
op_range incoming_values()
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:152
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:133
PtrUseVisitor(const DataLayout &DL)
LLVM_ABI SROAPass(SROAOptions Options)
If PreserveCFG is set, then the pass is not allowed to modify CFG in any way, even if it would update...
Definition SROA.cpp:6670
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
Definition SROA.cpp:6643
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition SROA.cpp:6658
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition SSAUpdater.h:39
This class represents the LLVM 'select' instruction.
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
void clear()
Completely clear the SetVector.
Definition SetVector.h:273
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
typename SuperClass::const_iterator const_iterator
typename SuperClass::iterator iterator
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
void set(unsigned Idx)
bool test(unsigned Idx) const
void reset(unsigned Idx)
An instruction for storing to memory.
bool isAtomic() const
Return true if this store has an atomic ordering.
void setAlignment(Align Align)
Value * getValueOperand()
static unsigned getPointerOperandIndex()
Value * getPointerOperand()
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this store instruction.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:589
LLVM_ABI size_t rfind(char C, size_t From=npos) const
Search for the last character C in the string.
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
LLVM_ABI size_t find_first_not_of(char C, size_t From=0) const
Find the first character in the string that is not C or npos if not found.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:746
TypeSize getSizeInBytes() const
Definition DataLayout.h:755
LLVM_ABI unsigned getElementContainingOffset(uint64_t FixedOffset) const
Given a valid byte offset into the structure, returns the structure index that contains it.
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:777
TypeSize getSizeInBits() const
Definition DataLayout.h:757
Class to represent struct types.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:462
element_iterator element_end() const
ArrayRef< Type * > elements() const
element_iterator element_begin() const
bool isPacked() const
unsigned getNumElements() const
Random access to the elements.
Type * getElementType(unsigned N) const
Type::subtype_iterator element_iterator
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Definition Type.h:306
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:271
bool isTargetExtTy() const
Return true if this is a target extension type.
Definition Type.h:205
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
op_iterator op_begin()
Definition User.h:259
Value * getOperand(unsigned i) const
Definition User.h:207
op_iterator op_end()
Definition User.h:261
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
Definition Value.cpp:158
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition Value.cpp:823
LLVM_ABI void dropDroppableUsesIn(User &Usr)
Remove every use of this value in User that can safely be removed.
Definition Value.cpp:210
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
bool hasName() const
Definition Value.h:263
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static VectorType * getWithSizeAndScalar(VectorType *SizeTy, Type *EltTy)
This static method attempts to construct a VectorType with the same size-in-bits as SizeTy but with a...
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
Definition TypeSize.h:172
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition iterator.h:80
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
Offsets
Offsets in bytes from the start of the input buffer.
SmallVector< DbgVariableRecord * > getDVRAssignmentMarkers(const Instruction *Inst)
Return a range of dbg_assign records for which Inst performs the assignment they encode.
Definition DebugInfo.h:209
LLVM_ABI void deleteAssignmentMarkers(const Instruction *Inst)
Delete the llvm.dbg.assign intrinsics linked to Inst.
@ DW_OP_LLVM_fragment
Only used in LLVM metadata.
Definition Dwarf.h:144
@ User
could "use" a pointer
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
bool empty() const
Definition BasicBlock.h:101
iterator end() const
Definition BasicBlock.h:89
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI iterator begin() const
unsigned getNumElements(Type *Ty)
Definition SLPUtils.cpp:117
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
void stable_sort(R &&Range)
Definition STLExtras.h:2132
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1748
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
unsigned getLoadStoreAddressSpace(const Value *I)
A helper function that returns the address space of the pointer operand of load or store instruction.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
LLVM_ABI void PromoteMemToReg(ArrayRef< AllocaInst * > Allocas, DominatorTree &DT, AssumptionCache *AC=nullptr)
Promote the specified list of alloca instructions into scalar registers, inserting PHI nodes as appro...
LLVM_ABI bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2139
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
void * PointerTy
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
const ScalarOptions & getScalarOptions(const LLVMContext &C)
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2150
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
LLVM_ABI bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
static Error getOffset(const SymbolRef &Sym, SectionRef Sec, uint64_t &Result)
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2220
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:408
bool capturesFullProvenance(CaptureComponents CC)
Definition ModRef.h:396
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void initializeSROALegacyPassPass(PassRegistry &)
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
LLVM_ABI TinyPtrVector< DbgVariableRecord * > findDVRValues(Value *V)
As above, for DVRValues.
Definition DebugInfo.cpp:82
LLVM_ABI void llvm_unreachable_internal(const char *msg=nullptr, const char *file=nullptr, unsigned line=0)
This function calls abort(), and prints the optional message to stderr.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
constexpr int PoisonMaskElem
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
@ Other
Any other memory.
Definition ModRef.h:68
LLVM_ABI bool isSafeToLoadUnconditionally(Value *V, Align Alignment, const APInt &Size, const SimplifyQuery &SQ, bool IgnoreFree=false)
Return true if we know that executing a load from this value cannot trap.
Definition Loads.cpp:456
LLVM_ABI bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
DWARFExpression::Operation Op
LLVM_ABI Align tryEnforceAlignment(Value *V, Align PrefAlign, const DataLayout &DL)
If the specified pointer points to an object that we control, try to modify the object's alignment to...
Definition Local.cpp:1558
LLVM_ABI FunctionPass * createSROAPass(bool PreserveCFG=true, bool AggregateToVector=false)
Definition SROA.cpp:6712
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
LLVM_ABI TinyPtrVector< DbgVariableRecord * > findDVRDeclares(Value *V)
Finds dbg.declare records declaring local variables as living in the memory that 'V' points to.
Definition DebugInfo.cpp:48
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
LLVM_ABI std::optional< Register > getVectorSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI)
Definition Utils.cpp:1605
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI llvm::SmallVector< int, 16 > createSequentialMask(unsigned Start, unsigned NumInts, unsigned NumUndefs)
Create a sequential shuffle mask.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define NDEBUG
Definition regutils.h:48
An iterator which iterates over the sub-slices that we want to split the slice into.
Definition SROA.cpp:5022
Iterator & operator++()
Definition SROA.cpp:5035
SliceSplitter & SS
Definition SROA.cpp:5023
uint64_t getSize() const
Definition SROA.cpp:5030
bool operator==(const Iterator &Other) const
Definition SROA.cpp:5028
const Iterator & operator*() const
Definition SROA.cpp:5039
uint64_t getOffset() const
Definition SROA.cpp:5029
Iterator(SliceSplitter &SS, bool IsEnd)
Definition SROA.cpp:5025
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:775
AAMDNodes shift(size_t Offset) const
Create a new AAMDNode that describes this AAMDNode after applying a constant offset to the start of t...
Definition Metadata.h:835
LLVM_ABI AAMDNodes adjustForAccess(unsigned AccessSize)
Create a new AAMDNode for accessing AccessSize bytes of this AAMDNode.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Describes an element of a Bitfield.
Definition Bitfields.h:176
static Bitfield::Type get(StorageType Packed)
Unpacks the field from the Packed value.
Definition Bitfields.h:207
static void set(StorageType &Packed, typename Bitfield::Type Value)
Sets the typed value in the provided Packed value.
Definition Bitfields.h:223