76#define DEBUG_TYPE "loop-split-utils"
121 Partitions.emplace_back(Start, End);
126 assert(PartitionIndex < Partitions.size() &&
127 "avoidPartitionGuard() called for an unknown partition");
128 Partitions[PartitionIndex].Guarded =
false;
134 if (PartitionIndex >= Partitions.size())
136 return Partitions[PartitionIndex].VMap.get();
141 unsigned PartitionIndex)
const {
144 if (PartitionIndex == 0)
156 Value *&LatchIndOperand) {
157 ICmpInst *LatchCmp = L->getLatchCmpInst();
160 PHINode *Induction = L->getInductionVariable(*SE);
183 else if (LatchCmp->
getOperand(1) == Induction ||
205 ": cannot prove iteration ordering signedness\n");
212 if (!L->getLoopPreheader() || !L->getLoopLatch() || !L->getExitingBlock() ||
213 !L->getExitBlock() || L->getExitingBlock() != L->getLoopLatch() ||
214 !L->isLCSSAForm(*DT)) {
220 ICmpInst *LatchCmp = L->getLatchCmpInst();
221 if (!LatchCmp || LatchCmp->
getParent() != L->getLoopLatch()) {
227 const SCEV *BTC = SE->getBackedgeTakenCount(L);
236 ": no unique unit-step integer induction\n");
243 InductionIsSigned = *
Signed;
282 PHINode *Induction = L->getInductionVariable(*SE);
283 assert(Induction &&
"split() requires a successful isLegal()");
287 if (!L->hasDedicatedExits() &&
295 PartitionInfo &P0 = Partitions[0];
296 P0.Preheader = L->getLoopPreheader();
297 P0.Exit = L->getExitBlock();
299 P0.LatchIndOp = LatchIndOperand;
309 collectEscapingValues(S);
318 expandPartitionBounds(S, Expander);
328void LoopSplitUtils::collectEscapingValues(SplitState &S) {
331 BasicBlock *OrigPreheader = Partitions[0].Preheader;
337 S.OuterLoop->addBasicBlockToLoop(S.FinalExit, *LI);
346 if (&HeaderPHI == S.Induction)
348 Value *CarriedValue = HeaderPHI.getIncomingValueForBlock(Latch);
349 Value *InitialValue = HeaderPHI.getIncomingValueForBlock(OrigPreheader);
350 if (CarriedValue == InitialValue)
352 auto &EV = S.addEscaping(CarriedValue);
353 EV.CarriedHeaderPHI = &HeaderPHI;
357 CarriedInst && L->
contains(CarriedInst))
358 CarriedDefToEscapingIdx[CarriedValue] = S.Escaping.
size() - 1;
364 assert(LCSSAPhi.getNumIncomingValues() == 1 &&
365 "exit block not in LCSSA form");
366 Value *LiveOutDef = LCSSAPhi.getIncomingValue(0);
367 auto Existing = CarriedDefToEscapingIdx.
find(LiveOutDef);
368 auto &EV = Existing != CarriedDefToEscapingIdx.
end()
369 ? S.Escaping[Existing->second]
370 : S.addEscaping(LiveOutDef);
371 EV.EscapesOutside =
true;
372 LCSSAPhi.replaceAllUsesWith(LiveOutDef);
373 LCSSAPhi.eraseFromParent();
379 for (
auto &EV : S.Escaping) {
380 EV.PerPartitionDef.assign(
N,
nullptr);
381 EV.PerPartitionPHI.assign(
N,
nullptr);
382 EV.PerPartitionDef[0] = EV.Def;
383 EV.PerPartitionPHI[0] = EV.CarriedHeaderPHI;
396 EntryGuard = Preheader;
397 Preheader = NewPreheader;
401 EntryGuard->
setName(
"ls.guard0");
406void LoopSplitUtils::expandPartitionBounds(SplitState &S,
408 Type *IndTy = S.Induction->getType();
409 Instruction *EntryGuardTerm = Partitions[0].GuardBlock->getTerminator();
414 for (
unsigned I = 0;
I <
N; ++
I) {
415 PartitionInfo &
P = Partitions[
I];
420 const SCEV *PartWidth = SE->getMinusSCEV(
P.StartExpr,
P.EndExpr);
422 const APInt &
W = PartWidthConst->getAPInt();
423 P.Empty = S.Descending ?
W.isAllOnes() :
W.isOne();
426 P.StartVal = Expander.
expandCodeFor(
P.StartExpr, IndTy, EntryGuardTerm);
430 const SCEV *ClampedEndSCEV;
432 ClampedEndSCEV = InductionIsSigned
433 ? SE->getSMaxExpr(
P.EndExpr, InductionEnd)
434 : SE->getUMaxExpr(
P.EndExpr, InductionEnd);
436 ClampedEndSCEV = InductionIsSigned
437 ? SE->getSMinExpr(
P.EndExpr, InductionEnd)
438 : SE->getUMinExpr(
P.EndExpr, InductionEnd);
439 P.SelEnd = Expander.
expandCodeFor(ClampedEndSCEV, IndTy, EntryGuardTerm);
445void LoopSplitUtils::clonePartitions(SplitState &S) {
446 Function &
F = *L->getHeader()->getParent();
447 LLVMContext &Ctx =
F.getContext();
451 BasicBlock *OrigPreheader = Partitions[0].Preheader;
453 for (
unsigned I = 1;
I <
N; ++
I) {
454 PartitionInfo &
P = Partitions[
I];
457 P.VMap = std::make_unique<ValueToValueMapTy>();
459 SmallVector<BasicBlock *, 8> ClonedBlocks;
461 ".ls" + Twine(
I), LI, DT, ClonedBlocks);
470 S.OuterLoop->addBasicBlockToLoop(Exiti, *LI);
471 S.OuterLoop->addBasicBlockToLoop(Guardi, *LI);
479 ClonedInduction->setIncomingValueForBlock(PHi,
P.StartVal);
481 P.GuardBlock = Guardi;
485 P.LatchIndOp = VMap.
lookup_or(LatchIndOperand, LatchIndOperand);
487 for (
auto &EV : S.Escaping) {
488 EV.PerPartitionDef[
I] = VMap.
lookup_or(EV.Def, EV.Def);
489 if (EV.CarriedHeaderPHI)
498 bool LatchComparesPHI) {
502 Value *Bound = SelEnd;
508 Value *NewCmp =
B.CreateICmp(Pred, IndOp, Bound,
"itr.chk");
509 B.SetInsertPoint(Term);
510 auto *NewBr =
B.CreateCondBr(NewCmp, PL->getHeader(), Exit);
515 bool Succ0InLoop = PL->contains(Term->getSuccessor(0));
517 *NewBr, {Succ0InLoop ? TrueW : FalseW, Succ0InLoop ? FalseW : TrueW},
520 Term->eraseFromParent();
521 if (Cmp->use_empty())
522 Cmp->eraseFromParent();
527void LoopSplitUtils::chainPartitions(SplitState &S) {
537 auto EntersUnconditionally = [](
const PartitionInfo &
P) {
538 return !
P.Empty && !
P.Guarded;
543 auto MergeTargetAfter = [&](
unsigned Idx) -> BasicBlock * {
544 bool IsLastPartition = Idx + 1 ==
N;
545 return IsLastPartition ? S.FinalExit : Partitions[Idx + 1].GuardBlock;
548 for (
unsigned I = 0;
I <
N; ++
I) {
549 PartitionInfo &
P = Partitions[
I];
557 B.CreateBr(MergeAfter);
558 }
else if (!
P.Guarded) {
561 B.CreateBr(
P.Preheader);
563 Value *Enter =
B.CreateICmp(GuardPred,
P.StartVal,
P.SelEnd,
"itr.chk");
564 auto *GuardBr =
B.CreateCondBr(Enter,
P.Preheader, MergeAfter);
572 S.Descending, S.LatchComparesPHI);
573 P.Exit->getTerminator()->setSuccessor(0, MergeAfter);
578 auto MergeTargetIDom = [&](
const PartitionInfo &
P) {
579 return EntersUnconditionally(
P) ?
P.Exit :
P.GuardBlock;
582 for (
unsigned I = 1;
I <
N; ++
I) {
583 PartitionInfo &Prev = Partitions[
I - 1];
584 PartitionInfo &Cur = Partitions[
I];
585 DT->addNewBlock(Cur.GuardBlock, MergeTargetIDom(Prev));
586 DT->changeImmediateDominator(Cur.Preheader, Cur.GuardBlock);
587 DT->addNewBlock(Cur.Exit, Cur.SubLoop->getLoopLatch());
590 DT->changeImmediateDominator(S.FinalExit, MergeTargetIDom(Partitions.back()));
595void LoopSplitUtils::reconstructSSA(SplitState &S) {
597 for (
auto &EV : S.Escaping) {
599 Updater.
Initialize(EV.Def->getType(), EV.Def->getName());
603 Value *Init = EV.CarriedHeaderPHI
604 ? EV.CarriedHeaderPHI->getIncomingValueForBlock(
605 Partitions[0].Preheader)
608 for (
unsigned I = 0;
I <
N; ++
I)
614 if (EV.EscapesOutside)
617 if (!L->contains(User))
621 if (EV.CarriedHeaderPHI)
622 for (
unsigned I = 1;
I <
N; ++
I) {
623 PHINode *CarriedPHI = EV.PerPartitionPHI[
I];
624 int PreheaderEntryIdx =
626 assert(PreheaderEntryIdx >= 0 &&
"cloned preheader edge missing");
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static ICmpInst::Predicate continuePredicate(bool Signed, bool Descending, bool Inclusive)
static const SCEVAddRecExpr * analyzeInduction(Loop *L, ScalarEvolution *SE, Value *&LatchIndOperand)
static ICmpInst::Predicate guardPredicate(bool Signed, bool Descending)
static void rewriteLatch(Loop *PL, Value *IndOp, Value *SelEnd, BasicBlock *Exit, bool Signed, bool Descending, bool LatchComparesPHI)
static std::optional< bool > computeSignedness(Loop *L, const SCEVAddRecExpr *IndAR)
static void buildEntryGuard(BasicBlock *&Preheader, BasicBlock *&EntryGuard, DominatorTree *DT, LoopInfo *LI)
This file contains the declarations for profiling metadata utility functions.
Class for arbitrary precision integers.
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
bool isOne() const
Determine if this is a value of 1.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ ICMP_ULT
unsigned less than
@ ICMP_SGE
signed greater or equal
@ ICMP_ULE
unsigned less or equal
iterator find(const_arg_type_t< KeyT > Val)
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
This instruction compares its operands according to the predicate given to the constructor.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
BlockT * getHeader() const
LLVM_ABI bool split()
Perform the split.
LLVM_ABI unsigned getNumPartitions() const
LLVM_ABI bool isLegal()
Analyze L and return true if it is a counted loop this utility can split: a bottom-tested single-exit...
LLVM_ABI void addPartition(const SCEV *Start, const SCEV *End)
Append an inclusive partition range [Start, End] in iteration order.
LLVM_ABI Value * getPartitionValue(Value *V, unsigned PartitionIndex) const
Return the counterpart of original-loop value V in partition PartitionIndex (0-based).
LLVM_ABI const ValueToValueMapTy * getPartitionValueMap(unsigned PartitionIndex) const
Return the original-to-clone value map for the partition at PartitionIndex, for callers that want to ...
LLVM_ABI void avoidPartitionGuard(unsigned PartitionIndex)
Suppress the entry guard for partition PartitionIndex (already added).
Represents a single loop in the control flow graph.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This node represents a polynomial recurrence on the trip count of the specified loop.
LLVM_ABI const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
Helper to remove instructions inserted during SCEV expansion, unless they are marked as used.
void markResultUsed()
Indicate that the result of the expansion is used.
This class uses information about analyze scalars to rewrite expressions in canonical form.
LLVM_ABI Value * expandCodeFor(SCEVUse SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
bool hasNoUnsignedWrap() const
bool hasNoSignedWrap() const
This class represents an analyzed expression in the program.
Type * getType() const
Return the LLVM type of this SCEV expression.
LLVM_ABI void RewriteUse(Use &U)
Rewrite a use of the symbolic value.
LLVM_ABI void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
LLVM_ABI void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value.
The main scalar evolution driver.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
const Use & getOperandUse(unsigned i) const
Value * getOperand(unsigned i) const
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
ValueT lookup_or(const KeyT &Val, U &&Default) const
Return the entry for the specified key, or Default.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
const ParentTy * getParent() const
@ BasicBlock
Various leaf nodes.
bool match(Val *V, const Pattern &P)
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
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...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI Loop * cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB, Loop *OrigLoop, ValueToValueMapTy &VMap, const Twine &NameSuffix, LoopInfo *LI, DominatorTree *DT, SmallVectorImpl< BasicBlock * > &Blocks)
Clones a loop OrigLoop.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
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...
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
LLVM_ABI bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Ensure that all exit blocks of the loop are dedicated exits.
LLVM_ABI void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI void setFittedBranchWeights(Instruction &I, ArrayRef< uint64_t > Weights, bool IsExpected, bool ElideAllZero=false)
Variant of setBranchWeights where the Weights will be fit first to uint32_t by shifting right.
A value that must be reconstructed after cloning because it is loop-carried (feeds a later partition)...
PHINode * CarriedHeaderPHI
The carried header PHI in partition 0, or null if Def needs no per-partition start value seeded.
Value * Def
The value as it exists in partition 0 (the original).
bool EscapesOutside
True if Def is used outside the loop and must be merged at the final exit.
EscapingValue(Value *Def)
SmallVector< Value *, 4 > PerPartitionDef
Def and CarriedHeaderPHI cloned into each partition (index 0 is the original; PerPartitionPHI[0] is u...
SmallVector< PHINode *, 4 > PerPartitionPHI
Per-split() scratch shared by the phase helpers; lives for one split() call.
SmallVector< EscapingValue, 8 > Escaping
Values that must survive across partitions (carried and/or live-out).
EscapingValue & addEscaping(Value *Def)