LLVM 24.0.0git
LoopSplitUtils.cpp
Go to the documentation of this file.
1//===- LoopSplitUtils.cpp - Split a loop's iteration space ----------------===//
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//
9// Splits a counted loop's iteration space into a chain of per-partition
10// sub-loops. See LoopSplitUtils.h for the high-level usage guidelines.
11//
12// Structure produced for partitions [S0,E0], [S1,E1], ... where E is the loop's
13// last iteration and each clamped end sel_i = min(E_i, E):
14//
15// guard0: ; every S_i and sel_i is computed here
16// if (S0 <= sel0) goto preheader0 else goto guard1 ; default guard check
17// loop0: ... ; latch stops at sel0
18// exit0 -> guard1
19// guard1:
20// if (S1 <= sel1) goto preheader1 else goto guard2 ; default guard check
21// loop1: ... ; latch stops at sel1
22// exit1 -> guard2
23// ...
24// final.exit: ; merges every partition's live-outs
25//
26// Each guard holds the "S_i <= sel_i" check and skips an empty partition by
27// falling through to the next guard. The check is replaced by an unconditional
28// branch when a partition is proven empty (to the next guard) or the caller
29// exempts it via avoidPartitionGuard() (to its preheader). All S_i/sel_i are
30// materialized once in guard0; the end clamp keeps the "runs at least once"
31// iteration in the right partition; live-outs are rebuilt one SSAUpdater each.
32//
33// A descending (step -1) loop uses the same structure mirrored: partitions run
34// high-to-low and the empty test, clamp, and predicates flip (>=/>).
35//
36// Usage guidelines:
37// - Caller bounds must not wrap the induction type. The clamp absorbs a bound
38// past the runtime trip count, but a Start +/- offset that overshoots the
39// type extreme wraps in the bound arithmetic and cannot be repaired here.
40// - Bounds must be loop-invariant: they are expanded in guard0 (the
41// preheader),
42// so a bound depending on a value defined inside the loop cannot be placed.
43// - The partitions must tile the original iteration space exactly -- same
44// iterations, same order -- so the split preserves program behaviour.
45// - A caller that drops a guard via avoidPartitionGuard() must itself ensure
46// that partition runs at least once, or the result is a spurious iteration.
47//
48//===----------------------------------------------------------------------===//
49
51#include "llvm/ADT/DenseMap.h"
56#include "llvm/IR/BasicBlock.h"
57#include "llvm/IR/CFG.h"
58#include "llvm/IR/Constants.h"
59#include "llvm/IR/Dominators.h"
60#include "llvm/IR/Function.h"
61#include "llvm/IR/IRBuilder.h"
64#include "llvm/Support/Debug.h"
71#include <optional>
72
73using namespace llvm;
74using namespace llvm::SCEVPatternMatch;
75
76#define DEBUG_TYPE "loop-split-utils"
77
78//===----------------------------------------------------------------------===//
79// LoopSplitUtils - construction, partition list, induction analysis
80//===----------------------------------------------------------------------===//
81
82/// Per-split() scratch shared by the phase helpers; lives for one split() call.
84 // Partition 0 reuses the original loop's preheader, exit, and entry guard;
85 // those blocks live in Partitions[0] rather than being duplicated here.
86 BasicBlock *FinalExit = nullptr; // where live-outs merge.
87 Loop *OuterLoop = nullptr; // parent of the new blocks, if any.
88 PHINode *Induction = nullptr; // the loop's induction variable.
89 bool Descending = false; // step is negative (loop counts down).
90 bool LatchComparesPHI = false; // latch compares the PHI, not the step.
91
92 /// A value that must be reconstructed after cloning because it is
93 /// loop-carried (feeds a later partition), live-out (used after the loop), or
94 /// both.
96 EscapingValue() = default;
98
99 /// The value as it exists in partition 0 (the original).
100 Value *Def = nullptr;
101 /// The carried header PHI in partition 0, or null if \c Def needs no
102 /// per-partition start value seeded.
104 /// True if \c Def is used outside the loop and must be merged at the final
105 /// exit.
106 bool EscapesOutside = false;
107 /// \c Def and \c CarriedHeaderPHI cloned into each partition (index 0 is
108 /// the original; \c PerPartitionPHI[0] is unused).
111 };
112
113 /// Values that must survive across partitions (carried and/or live-out).
115
116 EscapingValue &addEscaping(Value *Def) { return Escaping.emplace_back(Def); }
117};
118
119// Record a new partition with the given inclusive iteration range.
120void LoopSplitUtils::addPartition(const SCEV *Start, const SCEV *End) {
121 Partitions.emplace_back(Start, End);
122}
123
124// Mark a partition so split() emits no entry guard for it.
125void LoopSplitUtils::avoidPartitionGuard(unsigned PartitionIndex) {
126 assert(PartitionIndex < Partitions.size() &&
127 "avoidPartitionGuard() called for an unknown partition");
128 Partitions[PartitionIndex].Guarded = false;
129}
130
131// Return a partition's original-to-clone map, or null if it has none.
132const ValueToValueMapTy *
133LoopSplitUtils::getPartitionValueMap(unsigned PartitionIndex) const {
134 if (PartitionIndex >= Partitions.size())
135 return nullptr;
136 return Partitions[PartitionIndex].VMap.get();
137}
138
139// Look up the counterpart of an original value in a given partition.
141 unsigned PartitionIndex) const {
142 assert(PartitionIndex < getNumPartitions() && "partition index out of range");
143 // Partition 0 reuses the original loop: every value maps to itself.
144 if (PartitionIndex == 0)
145 return V;
146 const ValueToValueMapTy *VMap = getPartitionValueMap(PartitionIndex);
147 if (!VMap)
148 return nullptr;
149 return VMap->lookup(V);
150}
151
152// Find the induction variable and the latch operand it is compared against;
153// returns the induction's add-recurrence, or null if the loop is unsuitable.
154// On success \p LatchIndOperand is set to the compared induction operand.
156 Value *&LatchIndOperand) {
157 ICmpInst *LatchCmp = L->getLatchCmpInst();
158
159 // SCEV's induction variable, restricted to a unit-step affine recurrence.
160 PHINode *Induction = L->getInductionVariable(*SE);
161 if (!Induction)
162 return nullptr;
163 const SCEV *IndSCEV = SE->getSCEV(Induction);
164 // Match an affine add-recurrence and capture its constant step; accept a unit
165 // step in either direction: +1 (ascending) or -1 (descending).
166 const APInt *Step;
167 if (!match(IndSCEV, m_scev_AffineAddRec(m_SCEV(), m_scev_APInt(Step))))
168 return nullptr;
169 if (!Step->isOne() && !Step->isAllOnes())
170 return nullptr;
171 const auto *AR = cast<SCEVAddRecExpr>(IndSCEV);
172
173 // The induction's "next" value (i + 1), produced in the latch.
174 auto *StepInst = dyn_cast<Instruction>(
175 Induction->getIncomingValueForBlock(L->getLoopLatch()));
176 if (!StepInst)
177 return nullptr;
178
179 // Select the compare operand that is the induction (PHI or its step).
180 if (LatchCmp->getOperand(0) == Induction ||
181 LatchCmp->getOperand(0) == StepInst)
182 LatchIndOperand = LatchCmp->getOperand(0);
183 else if (LatchCmp->getOperand(1) == Induction ||
184 LatchCmp->getOperand(1) == StepInst)
185 LatchIndOperand = LatchCmp->getOperand(1);
186 else
187 return nullptr;
188 return AR;
189}
190
191// Decide whether the iteration ordering is signed or unsigned; returns the
192// signedness, or nullopt if it cannot be proven.
193static std::optional<bool> computeSignedness(Loop *L,
194 const SCEVAddRecExpr *IndAR) {
195 ICmpInst::Predicate P = L->getLatchCmpInst()->getPredicate();
196 // A relational predicate gives the ordering directly; for eq/ne fall back to
197 // the recurrence's no-wrap flags.
199 return ICmpInst::isSigned(P);
200 if (IndAR->hasNoSignedWrap())
201 return true;
202 if (IndAR->hasNoUnsignedWrap())
203 return false;
205 ": cannot prove iteration ordering signedness\n");
206 return std::nullopt;
207}
208
209// Check every structural precondition and record the induction analysis.
211 // Require a bottom-tested single-exit loop in LCSSA form with a preheader.
212 if (!L->getLoopPreheader() || !L->getLoopLatch() || !L->getExitingBlock() ||
213 !L->getExitBlock() || L->getExitingBlock() != L->getLoopLatch() ||
214 !L->isLCSSAForm(*DT)) {
215 LLVM_DEBUG(dbgs() << DEBUG_TYPE ": loop not in expected form\n");
216 return false;
217 }
218
219 // The latch compare must exist and reside in the latch.
220 ICmpInst *LatchCmp = L->getLatchCmpInst();
221 if (!LatchCmp || LatchCmp->getParent() != L->getLoopLatch()) {
222 LLVM_DEBUG(dbgs() << DEBUG_TYPE ": latch compare not in the loop latch\n");
223 return false;
224 }
225
226 // A computable backedge-taken count fixes the iteration space we rebuild.
227 const SCEV *BTC = SE->getBackedgeTakenCount(L);
228 if (isa<SCEVCouldNotCompute>(BTC)) {
229 LLVM_DEBUG(dbgs() << DEBUG_TYPE ": loop trip count uncomputable\n");
230 return false;
231 }
232
233 const SCEVAddRecExpr *IndAR = analyzeInduction(L, SE, LatchIndOperand);
234 if (!IndAR) {
236 ": no unique unit-step integer induction\n");
237 return false;
238 }
239
240 std::optional<bool> Signed = computeSignedness(L, IndAR);
241 if (!Signed)
242 return false;
243 InductionIsSigned = *Signed;
244
245 InductionEnd = IndAR->evaluateAtIteration(BTC, *SE);
246 // Start and end must share the induction type; reject any width mismatch.
247 if (InductionEnd->getType() != IndAR->getStart()->getType()) {
248 LLVM_DEBUG(dbgs() << DEBUG_TYPE ": induction end/start type mismatch\n");
249 return false;
250 }
251 return true;
252}
253
254//===----------------------------------------------------------------------===//
255// Transform
256//===----------------------------------------------------------------------===//
257
258// Latch "keep iterating" predicate (ascending </<=, descending >/>=); inclusive
259// when the latch compares the step value, strict when it compares the PHI.
260static ICmpInst::Predicate continuePredicate(bool Signed, bool Descending,
261 bool Inclusive) {
262 if (Descending)
263 return Inclusive ? (Signed ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE)
265 return Inclusive ? (Signed ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE)
267}
268
269// Guard "enter this partition" predicate: Start <= sel ascending, Start >= sel
270// descending.
271static ICmpInst::Predicate guardPredicate(bool Signed, bool Descending) {
272 if (Descending)
275}
276
277static void buildEntryGuard(BasicBlock *&Preheader, BasicBlock *&EntryGuard,
278 DominatorTree *DT, LoopInfo *LI);
279
280// Drive the whole transform: set up scratch state and run each phase in order.
282 PHINode *Induction = L->getInductionVariable(*SE);
283 assert(Induction && "split() requires a successful isLegal()");
284 if (getNumPartitions() < 2)
285 return false;
286
287 if (!L->hasDedicatedExits() &&
288 !formDedicatedExitBlocks(L, DT, LI, /*MSSAU=*/nullptr,
289 /*PreserveLCSSA=*/true))
290 return false;
291
292 SplitState S;
293 // Partition 0 reuses the original loop; record its preheader/exit/guard up
294 // front.
295 PartitionInfo &P0 = Partitions[0];
296 P0.Preheader = L->getLoopPreheader();
297 P0.Exit = L->getExitBlock();
298 P0.SubLoop = L;
299 P0.LatchIndOp = LatchIndOperand;
300 S.OuterLoop = LI->getLoopFor(P0.Exit);
301 S.Induction = Induction;
302 // Derive the iteration direction and latch shape once, before transforming.
303 const auto *IndAR = cast<SCEVAddRecExpr>(SE->getSCEV(Induction));
304 S.Descending = cast<SCEVConstant>(IndAR->getStepRecurrence(*SE))
305 ->getValue()
306 ->isMinusOne();
307 S.LatchComparesPHI = (LatchIndOperand == Induction);
308
309 collectEscapingValues(S);
310 buildEntryGuard(P0.Preheader, P0.GuardBlock, DT, LI);
311
312 // Keep the expander (and its cleaner) alive for the whole transform: the
313 // bounds it materializes are consumed by the later phases. If we bail before
314 // committing, the cleaner reclaims the expanded instructions; on success we
315 // mark them used so they are kept.
316 SCEVExpander Expander(*SE, DEBUG_TYPE);
317 SCEVExpanderCleaner ExpanderCleaner(Expander);
318 expandPartitionBounds(S, Expander);
319 clonePartitions(S);
320 chainPartitions(S);
321 reconstructSSA(S);
322 ExpanderCleaner.markResultUsed();
323 return true;
324}
325
326// Find loop-carried and live-out values and split the final-exit block off the
327// loop exit, seeding partition 0's slots for each escaping value.
328void LoopSplitUtils::collectEscapingValues(SplitState &S) {
329 BasicBlock *Latch = L->getLoopLatch();
330 BasicBlock *OrigExit = Partitions[0].Exit;
331 BasicBlock *OrigPreheader = Partitions[0].Preheader;
332
333 // Separate FinalExit from the loop exit. Split at begin() so the LCSSA PHIs
334 // move into FinalExit (SplitBlock would advance past them).
335 S.FinalExit = OrigExit->splitBasicBlock(OrigExit->begin(), "ls.final.exit");
336 if (S.OuterLoop)
337 S.OuterLoop->addBasicBlockToLoop(S.FinalExit, *LI);
338 // splitBasicBlock does not update the dominator tree; the new exit's sole
339 // predecessor is the original exit block.
340 DT->addNewBlock(S.FinalExit, OrigExit);
341
342 // (1) Carried values: each non-induction header PHI whose backedge value
343 // differs from its initial value must resume in later partitions.
344 DenseMap<Value *, unsigned> CarriedDefToEscapingIdx;
345 for (PHINode &HeaderPHI : L->getHeader()->phis()) {
346 if (&HeaderPHI == S.Induction)
347 continue;
348 Value *CarriedValue = HeaderPHI.getIncomingValueForBlock(Latch);
349 Value *InitialValue = HeaderPHI.getIncomingValueForBlock(OrigPreheader);
350 if (CarriedValue == InitialValue)
351 continue; // invariant and equal to the initial value: nothing to carry.
352 auto &EV = S.addEscaping(CarriedValue);
353 EV.CarriedHeaderPHI = &HeaderPHI;
354 // Track in-loop carried defs so a matching live-out in (2) merges onto
355 // them.
356 if (auto *CarriedInst = dyn_cast<Instruction>(CarriedValue);
357 CarriedInst && L->contains(CarriedInst))
358 CarriedDefToEscapingIdx[CarriedValue] = S.Escaping.size() - 1;
359 }
360
361 // (2) Live-outs: dissolve each LCSSA PHI into its def and mark it escaping,
362 // merging onto a pass-(1) entry if also carried. Uses are repaired later.
363 for (PHINode &LCSSAPhi : make_early_inc_range(S.FinalExit->phis())) {
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();
374 }
375
376 // Seed partition 0 with the originals; later partitions are filled when
377 // cloned.
378 const unsigned N = getNumPartitions();
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;
384 }
385}
386
387// Insert the entry guard ahead of partition 0's preheader and update the
388// dominator tree. On return \p Preheader is the clean preheader and
389// \p EntryGuard is the new guard block dominating the chain.
390static void buildEntryGuard(BasicBlock *&Preheader, BasicBlock *&EntryGuard,
391 DominatorTree *DT, LoopInfo *LI) {
392 // Split the preheader: the upper half becomes the guard dominating the chain,
393 // the lower half a clean preheader.
394 BasicBlock *NewPreheader =
395 SplitBlock(Preheader, Preheader->getTerminator(), DT, LI);
396 EntryGuard = Preheader;
397 Preheader = NewPreheader;
398 // Move the original preheader's name onto the new preheader, then name the
399 // guard.
400 Preheader->takeName(EntryGuard);
401 EntryGuard->setName("ls.guard0");
402}
403
404// Materialize each partition's start and clamped end in the entry guard and
405// flag the partitions that are provably empty at compile time.
406void LoopSplitUtils::expandPartitionBounds(SplitState &S,
407 SCEVExpander &Expander) {
408 Type *IndTy = S.Induction->getType();
409 Instruction *EntryGuardTerm = Partitions[0].GuardBlock->getTerminator();
410
411 // Expand all partition bounds in the entry guard, which dominates the whole
412 // chain (a skipped partition bypasses the original preheader).
413 const unsigned N = getNumPartitions();
414 for (unsigned I = 0; I < N; ++I) {
415 PartitionInfo &P = Partitions[I];
416
417 // Provably empty when Start overshoots End by exactly one step.
418 // Compile-time only: a runtime overshoot wraps at the type extreme and
419 // would falsely enter.
420 const SCEV *PartWidth = SE->getMinusSCEV(P.StartExpr, P.EndExpr);
421 if (auto *PartWidthConst = dyn_cast<SCEVConstant>(PartWidth)) {
422 const APInt &W = PartWidthConst->getAPInt();
423 P.Empty = S.Descending ? W.isAllOnes() : W.isOne();
424 }
425
426 P.StartVal = Expander.expandCodeFor(P.StartExpr, IndTy, EntryGuardTerm);
427
428 // Clamp the end to the induction end (min ascending, max descending) so a
429 // short trip count keeps the last iteration in the right partition.
430 const SCEV *ClampedEndSCEV;
431 if (S.Descending)
432 ClampedEndSCEV = InductionIsSigned
433 ? SE->getSMaxExpr(P.EndExpr, InductionEnd)
434 : SE->getUMaxExpr(P.EndExpr, InductionEnd);
435 else
436 ClampedEndSCEV = InductionIsSigned
437 ? SE->getSMinExpr(P.EndExpr, InductionEnd)
438 : SE->getUMinExpr(P.EndExpr, InductionEnd);
439 P.SelEnd = Expander.expandCodeFor(ClampedEndSCEV, IndTy, EntryGuardTerm);
440 }
441}
442
443// Pass 1: clone each later partition's sub-loop and create its guard and exit
444// blocks (partition 0 reuses the original loop).
445void LoopSplitUtils::clonePartitions(SplitState &S) {
446 Function &F = *L->getHeader()->getParent();
447 LLVMContext &Ctx = F.getContext();
448
449 const unsigned N = getNumPartitions();
450 // Partition 0 reuses the original loop; clone the rest off its preheader.
451 BasicBlock *OrigPreheader = Partitions[0].Preheader;
452
453 for (unsigned I = 1; I < N; ++I) {
454 PartitionInfo &P = Partitions[I];
455 // Persist this partition's original-to-clone map so callers can later
456 // query the counterpart of an original loop value (getPartitionValue()).
457 P.VMap = std::make_unique<ValueToValueMapTy>();
458 ValueToValueMapTy &VMap = *P.VMap;
459 SmallVector<BasicBlock *, 8> ClonedBlocks;
460 Loop *PL = cloneLoopWithPreheader(S.FinalExit, OrigPreheader, L, VMap,
461 ".ls" + Twine(I), LI, DT, ClonedBlocks);
462 remapInstructionsInBlocks(ClonedBlocks, VMap);
463 BasicBlock *PHi = PL->getLoopPreheader();
464
465 BasicBlock *Exiti =
466 BasicBlock::Create(Ctx, "ls.exit" + Twine(I), &F, S.FinalExit);
467 BasicBlock *Guardi =
468 BasicBlock::Create(Ctx, "ls.guard" + Twine(I), &F, PHi);
469 if (S.OuterLoop) {
470 S.OuterLoop->addBasicBlockToLoop(Exiti, *LI);
471 S.OuterLoop->addBasicBlockToLoop(Guardi, *LI);
472 }
473 // Placeholder terminators; both are re-pointed at the merge in pass 2.
474 UncondBrInst::Create(S.FinalExit, Exiti);
475 UncondBrInst::Create(S.FinalExit, Guardi);
476
477 // Seed the clone's induction PHI with this partition's start value.
478 auto *ClonedInduction = cast<PHINode>(VMap[S.Induction]);
479 ClonedInduction->setIncomingValueForBlock(PHi, P.StartVal);
480
481 P.GuardBlock = Guardi;
482 P.Preheader = PHi;
483 P.Exit = Exiti;
484 P.SubLoop = PL;
485 P.LatchIndOp = VMap.lookup_or(LatchIndOperand, LatchIndOperand);
486
487 for (auto &EV : S.Escaping) {
488 EV.PerPartitionDef[I] = VMap.lookup_or(EV.Def, EV.Def);
489 if (EV.CarriedHeaderPHI)
490 EV.PerPartitionPHI[I] = cast<PHINode>(VMap[EV.CarriedHeaderPHI]);
491 }
492 }
493}
494
495// Replace a partition's latch test so it iterates only within [start, SelEnd].
496static void rewriteLatch(Loop *PL, Value *IndOp, Value *SelEnd,
497 BasicBlock *Exit, bool Signed, bool Descending,
498 bool LatchComparesPHI) {
499 auto *Term = cast<CondBrInst>(PL->getLoopLatch()->getTerminator());
500 auto *Cmp = cast<ICmpInst>(Term->getCondition());
501 IRBuilder<> B(Cmp);
502 Value *Bound = SelEnd;
503 if (Bound->getType() != IndOp->getType())
504 Bound = B.CreateIntCast(Bound, IndOp->getType(), Signed);
505 // Strict when the PHI itself is compared, inclusive when the step value is.
507 /*Inclusive=*/!LatchComparesPHI);
508 Value *NewCmp = B.CreateICmp(Pred, IndOp, Bound, "itr.chk");
509 B.SetInsertPoint(Term);
510 auto *NewBr = B.CreateCondBr(NewCmp, PL->getHeader(), Exit);
511 // Carry the original latch's weights over, mapping by which successor stayed
512 // in the loop.
513 uint64_t TrueW, FalseW;
514 if (extractBranchWeights(*Term, TrueW, FalseW)) {
515 bool Succ0InLoop = PL->contains(Term->getSuccessor(0));
517 *NewBr, {Succ0InLoop ? TrueW : FalseW, Succ0InLoop ? FalseW : TrueW},
518 /*IsExpected=*/false);
519 }
520 Term->eraseFromParent();
521 if (Cmp->use_empty())
522 Cmp->eraseFromParent();
523}
524
525// Pass 2: emit each partition's guard branch, clamp its latch, wire the
526// partitions into a chain, and update the dominator tree.
527void LoopSplitUtils::chainPartitions(SplitState &S) {
528 const ICmpInst::Predicate GuardPred =
529 guardPredicate(InductionIsSigned, S.Descending);
530
531 // Emit each guard, clamp each latch, and chain partitions; a skipped
532 // partition falls through to the next guard.
533 const unsigned N = getNumPartitions();
534
535 // Enters unconditionally when the caller opted out of the guard and the
536 // partition is not provably empty; a proven-empty partition always skips.
537 auto EntersUnconditionally = [](const PartitionInfo &P) {
538 return !P.Empty && !P.Guarded;
539 };
540
541 // Where control goes when partition Idx is skipped or after it finishes: the
542 // next partition's guard, or the final merge block for the last partition.
543 auto MergeTargetAfter = [&](unsigned Idx) -> BasicBlock * {
544 bool IsLastPartition = Idx + 1 == N;
545 return IsLastPartition ? S.FinalExit : Partitions[Idx + 1].GuardBlock;
546 };
547
548 for (unsigned I = 0; I < N; ++I) {
549 PartitionInfo &P = Partitions[I];
550 BasicBlock *MergeAfter = MergeTargetAfter(I);
551
552 Instruction *GuardTerm = P.GuardBlock->getTerminator();
553 IRBuilder<> B(GuardTerm);
554 if (P.Empty) {
555 // Provably empty: skip to the next partition. The unreachable loop body
556 // is removed by later passes.
557 B.CreateBr(MergeAfter);
558 } else if (!P.Guarded) {
559 // Caller guaranteed at least one iteration: enter unconditionally. The
560 // skip edge to MergeAfter is omitted (see DT update below).
561 B.CreateBr(P.Preheader);
562 } else {
563 Value *Enter = B.CreateICmp(GuardPred, P.StartVal, P.SelEnd, "itr.chk");
564 auto *GuardBr = B.CreateCondBr(Enter, P.Preheader, MergeAfter);
565 // New control flow with no source profile; record the weights as unknown
566 // so profile-tracking passes are not misled.
568 }
569 GuardTerm->eraseFromParent();
570
571 rewriteLatch(P.SubLoop, P.LatchIndOp, P.SelEnd, P.Exit, InductionIsSigned,
572 S.Descending, S.LatchComparesPHI);
573 P.Exit->getTerminator()->setSuccessor(0, MergeAfter);
574 }
575
576 // Patch the dominator tree directly: a merge target is dominated by the prior
577 // partition's exit when it enters unconditionally, otherwise by its guard.
578 auto MergeTargetIDom = [&](const PartitionInfo &P) {
579 return EntersUnconditionally(P) ? P.Exit : P.GuardBlock;
580 };
581
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());
588 }
589 // The final exit is the last partition's merge target.
590 DT->changeImmediateDominator(S.FinalExit, MergeTargetIDom(Partitions.back()));
591}
592
593// Rebuild SSA for every escaping value, repairing outside uses and seeding each
594// later partition's carried PHI, using one SSAUpdater per value.
595void LoopSplitUtils::reconstructSSA(SplitState &S) {
596 const unsigned N = getNumPartitions();
597 for (auto &EV : S.Escaping) {
598 SSAUpdater Updater;
599 Updater.Initialize(EV.Def->getType(), EV.Def->getName());
600
601 // Value before any partition runs: carried PHI's initial value, else
602 // poison.
603 Value *Init = EV.CarriedHeaderPHI
604 ? EV.CarriedHeaderPHI->getIncomingValueForBlock(
605 Partitions[0].Preheader)
606 : PoisonValue::get(EV.Def->getType());
607 Updater.AddAvailableValue(Partitions[0].GuardBlock, Init);
608 for (unsigned I = 0; I < N; ++I)
609 Updater.AddAvailableValue(Partitions[I].Exit, EV.PerPartitionDef[I]);
610
611 // Repair outside uses before the carried-PHI seeds add new in-clone uses.
612 // make_early_inc_range advances past each use before RewriteUse() unlinks
613 // it from Def's use-list, so the rewrite cannot invalidate the iteration.
614 if (EV.EscapesOutside)
615 for (Use &U : make_early_inc_range(EV.Def->uses()))
616 if (auto *User = dyn_cast<Instruction>(U.getUser()))
617 if (!L->contains(User))
618 Updater.RewriteUse(U);
619
620 // Seed each later partition's carried PHI from the preceding partitions.
621 if (EV.CarriedHeaderPHI)
622 for (unsigned I = 1; I < N; ++I) {
623 PHINode *CarriedPHI = EV.PerPartitionPHI[I];
624 int PreheaderEntryIdx =
625 CarriedPHI->getBasicBlockIndex(Partitions[I].Preheader);
626 assert(PreheaderEntryIdx >= 0 && "cloned preheader edge missing");
627 Updater.RewriteUse(CarriedPHI->getOperandUse(PreheaderEntryIdx));
628 }
629 }
630}
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.
#define DEBUG_TYPE
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)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define P(N)
This file contains the declarations for profiling metadata utility functions.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Class for arbitrary precision integers.
Definition APInt.h:78
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:372
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:390
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:530
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.
Definition BasicBlock.h:206
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
bool isSigned() const
Definition InstrTypes.h:993
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
unsigned size() const
Definition DenseMap.h:172
iterator end()
Definition DenseMap.h:141
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.
Definition Dominators.h:122
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...
Definition IRBuilder.h:2893
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.
Definition LoopInfo.h:40
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.
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
Definition User.h:220
Value * getOperand(unsigned i) const
Definition User.h:207
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition ValueMap.h:167
ValueT lookup_or(const KeyT &Val, U &&Default) const
Return the entry for the specified key, or Default.
Definition ValueMap.h:176
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
const ParentTy * getParent() const
Definition ilist_node.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
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.
Definition BasicBlock.h:73
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.
Definition Casting.h:643
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:633
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
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.
Definition Debug.cpp:209
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
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.
Definition LoopUtils.cpp:61
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.
Definition Casting.h:559
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.
#define N
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.
SmallVector< Value *, 4 > PerPartitionDef
Def and CarriedHeaderPHI cloned into each partition (index 0 is the original; PerPartitionPHI[0] is u...
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)