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"
63#include "llvm/Support/Debug.h"
70#include <optional>
71
72using namespace llvm;
73using namespace llvm::SCEVPatternMatch;
74
75#define DEBUG_TYPE "loop-split-utils"
76
77//===----------------------------------------------------------------------===//
78// LoopSplitUtils - construction, partition list, induction analysis
79//===----------------------------------------------------------------------===//
80
81/// Per-split() scratch shared by the phase helpers; lives for one split() call.
83 // Partition 0 reuses the original loop's preheader, exit, and entry guard;
84 // those blocks live in Partitions[0] rather than being duplicated here.
85 BasicBlock *FinalExit = nullptr; // where live-outs merge.
86 Loop *OuterLoop = nullptr; // parent of the new blocks, if any.
87 PHINode *Induction = nullptr; // the loop's induction variable.
88 bool Descending = false; // step is negative (loop counts down).
89 bool LatchComparesPHI = false; // latch compares the PHI, not the step.
90
91 /// A value that must be reconstructed after cloning because it is
92 /// loop-carried (feeds a later partition), live-out (used after the loop), or
93 /// both.
95 EscapingValue() = default;
97
98 /// The value as it exists in partition 0 (the original).
99 Value *Def = nullptr;
100 /// The carried header PHI in partition 0, or null if \c Def needs no
101 /// per-partition start value seeded.
103 /// True if \c Def is used outside the loop and must be merged at the final
104 /// exit.
105 bool EscapesOutside = false;
106 /// \c Def and \c CarriedHeaderPHI cloned into each partition (index 0 is
107 /// the original; \c PerPartitionPHI[0] is unused).
110 };
111
112 /// Values that must survive across partitions (carried and/or live-out).
114
115 EscapingValue &addEscaping(Value *Def) { return Escaping.emplace_back(Def); }
116};
117
118// Record a new partition with the given inclusive iteration range.
119void LoopSplitUtils::addPartition(const SCEV *Start, const SCEV *End) {
120 Partitions.emplace_back(Start, End);
121}
122
123// Mark a partition so split() emits no entry guard for it.
124void LoopSplitUtils::avoidPartitionGuard(unsigned PartitionIndex) {
125 assert(PartitionIndex < Partitions.size() &&
126 "avoidPartitionGuard() called for an unknown partition");
127 Partitions[PartitionIndex].Guarded = false;
128}
129
130// Return a partition's original-to-clone map, or null if it has none.
131const ValueToValueMapTy *
132LoopSplitUtils::getPartitionValueMap(unsigned PartitionIndex) const {
133 if (PartitionIndex >= Partitions.size())
134 return nullptr;
135 return Partitions[PartitionIndex].VMap.get();
136}
137
138// Look up the counterpart of an original value in a given partition.
140 unsigned PartitionIndex) const {
141 assert(PartitionIndex < getNumPartitions() && "partition index out of range");
142 // Partition 0 reuses the original loop: every value maps to itself.
143 if (PartitionIndex == 0)
144 return V;
145 const ValueToValueMapTy *VMap = getPartitionValueMap(PartitionIndex);
146 if (!VMap)
147 return nullptr;
148 return VMap->lookup(V);
149}
150
151// Find the induction variable and the latch operand it is compared against;
152// returns the induction's add-recurrence, or null if the loop is unsuitable.
153// On success \p LatchIndOperand is set to the compared induction operand.
155 Value *&LatchIndOperand) {
156 ICmpInst *LatchCmp = L->getLatchCmpInst();
157
158 // SCEV's induction variable, restricted to a unit-step affine recurrence.
159 PHINode *Induction = L->getInductionVariable(*SE);
160 if (!Induction)
161 return nullptr;
162 const SCEV *IndSCEV = SE->getSCEV(Induction);
163 // Match an affine add-recurrence and capture its constant step; accept a unit
164 // step in either direction: +1 (ascending) or -1 (descending).
165 const APInt *Step;
166 if (!match(IndSCEV, m_scev_AffineAddRec(m_SCEV(), m_scev_APInt(Step))))
167 return nullptr;
168 if (!Step->isOne() && !Step->isAllOnes())
169 return nullptr;
170 const auto *AR = cast<SCEVAddRecExpr>(IndSCEV);
171
172 // The induction's "next" value (i + 1), produced in the latch.
173 auto *StepInst = dyn_cast<Instruction>(
174 Induction->getIncomingValueForBlock(L->getLoopLatch()));
175 if (!StepInst)
176 return nullptr;
177
178 // Select the compare operand that is the induction (PHI or its step).
179 if (LatchCmp->getOperand(0) == Induction ||
180 LatchCmp->getOperand(0) == StepInst)
181 LatchIndOperand = LatchCmp->getOperand(0);
182 else if (LatchCmp->getOperand(1) == Induction ||
183 LatchCmp->getOperand(1) == StepInst)
184 LatchIndOperand = LatchCmp->getOperand(1);
185 else
186 return nullptr;
187 return AR;
188}
189
190// Decide whether the iteration ordering is signed or unsigned; returns the
191// signedness, or nullopt if it cannot be proven.
192static std::optional<bool> computeSignedness(Loop *L,
193 const SCEVAddRecExpr *IndAR) {
194 ICmpInst::Predicate P = L->getLatchCmpInst()->getPredicate();
195 // A relational predicate gives the ordering directly; for eq/ne fall back to
196 // the recurrence's no-wrap flags.
198 return ICmpInst::isSigned(P);
199 if (IndAR->hasNoSignedWrap())
200 return true;
201 if (IndAR->hasNoUnsignedWrap())
202 return false;
204 ": cannot prove iteration ordering signedness\n");
205 return std::nullopt;
206}
207
208// Check every structural precondition and record the induction analysis.
210 // Require a bottom-tested single-exit loop in LCSSA form with a preheader.
211 if (!L->getLoopPreheader() || !L->getLoopLatch() || !L->getExitingBlock() ||
212 !L->getExitBlock() || L->getExitingBlock() != L->getLoopLatch() ||
213 !L->isLCSSAForm(*DT)) {
214 LLVM_DEBUG(dbgs() << DEBUG_TYPE ": loop not in expected form\n");
215 return false;
216 }
217
218 // The latch compare must exist and reside in the latch.
219 ICmpInst *LatchCmp = L->getLatchCmpInst();
220 if (!LatchCmp || LatchCmp->getParent() != L->getLoopLatch()) {
221 LLVM_DEBUG(dbgs() << DEBUG_TYPE ": latch compare not in the loop latch\n");
222 return false;
223 }
224
225 // A computable backedge-taken count fixes the iteration space we rebuild.
226 const SCEV *BTC = SE->getBackedgeTakenCount(L);
227 if (isa<SCEVCouldNotCompute>(BTC)) {
228 LLVM_DEBUG(dbgs() << DEBUG_TYPE ": loop trip count uncomputable\n");
229 return false;
230 }
231
232 const SCEVAddRecExpr *IndAR = analyzeInduction(L, SE, LatchIndOperand);
233 if (!IndAR) {
235 ": no unique unit-step integer induction\n");
236 return false;
237 }
238
239 std::optional<bool> Signed = computeSignedness(L, IndAR);
240 if (!Signed)
241 return false;
242 InductionIsSigned = *Signed;
243
244 InductionEnd = IndAR->evaluateAtIteration(BTC, *SE);
245 // Start and end must share the induction type; reject any width mismatch.
246 if (InductionEnd->getType() != IndAR->getStart()->getType()) {
247 LLVM_DEBUG(dbgs() << DEBUG_TYPE ": induction end/start type mismatch\n");
248 return false;
249 }
250 return true;
251}
252
253//===----------------------------------------------------------------------===//
254// Transform
255//===----------------------------------------------------------------------===//
256
257// Latch "keep iterating" predicate (ascending </<=, descending >/>=); inclusive
258// when the latch compares the step value, strict when it compares the PHI.
259static ICmpInst::Predicate continuePredicate(bool Signed, bool Descending,
260 bool Inclusive) {
261 if (Descending)
262 return Inclusive ? (Signed ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE)
264 return Inclusive ? (Signed ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE)
266}
267
268// Guard "enter this partition" predicate: Start <= sel ascending, Start >= sel
269// descending.
270static ICmpInst::Predicate guardPredicate(bool Signed, bool Descending) {
271 if (Descending)
274}
275
276static void buildEntryGuard(BasicBlock *&Preheader, BasicBlock *&EntryGuard,
277 DominatorTree *DT, LoopInfo *LI);
278
279// Drive the whole transform: set up scratch state and run each phase in order.
281 PHINode *Induction = L->getInductionVariable(*SE);
282 assert(Induction && "split() requires a successful isLegal()");
283 if (getNumPartitions() < 2)
284 return false;
285
286 if (!L->hasDedicatedExits() &&
287 !formDedicatedExitBlocks(L, DT, LI, /*MSSAU=*/nullptr,
288 /*PreserveLCSSA=*/true))
289 return false;
290
291 SplitState S;
292 // Partition 0 reuses the original loop; record its preheader/exit/guard up
293 // front.
294 PartitionInfo &P0 = Partitions[0];
295 P0.Preheader = L->getLoopPreheader();
296 P0.Exit = L->getExitBlock();
297 P0.SubLoop = L;
298 P0.LatchIndOp = LatchIndOperand;
299 S.OuterLoop = LI->getLoopFor(P0.Exit);
300 S.Induction = Induction;
301 // Derive the iteration direction and latch shape once, before transforming.
302 const auto *IndAR = cast<SCEVAddRecExpr>(SE->getSCEV(Induction));
303 S.Descending = cast<SCEVConstant>(IndAR->getStepRecurrence(*SE))
304 ->getValue()
305 ->isMinusOne();
306 S.LatchComparesPHI = (LatchIndOperand == Induction);
307
308 collectEscapingValues(S);
309 buildEntryGuard(P0.Preheader, P0.GuardBlock, DT, LI);
310
311 // Keep the expander (and its cleaner) alive for the whole transform: the
312 // bounds it materializes are consumed by the later phases. If we bail before
313 // committing, the cleaner reclaims the expanded instructions; on success we
314 // mark them used so they are kept.
315 SCEVExpander Expander(*SE, DEBUG_TYPE);
316 SCEVExpanderCleaner ExpanderCleaner(Expander);
317 expandPartitionBounds(S, Expander);
318 clonePartitions(S);
319 chainPartitions(S);
320 reconstructSSA(S);
321 ExpanderCleaner.markResultUsed();
322 return true;
323}
324
325// Find loop-carried and live-out values and split the final-exit block off the
326// loop exit, seeding partition 0's slots for each escaping value.
327void LoopSplitUtils::collectEscapingValues(SplitState &S) {
328 BasicBlock *Latch = L->getLoopLatch();
329 BasicBlock *OrigExit = Partitions[0].Exit;
330 BasicBlock *OrigPreheader = Partitions[0].Preheader;
331
332 // Separate FinalExit from the loop exit. Split at begin() so the LCSSA PHIs
333 // move into FinalExit (SplitBlock would advance past them).
334 S.FinalExit = OrigExit->splitBasicBlock(OrigExit->begin(), "ls.final.exit");
335 if (S.OuterLoop)
336 S.OuterLoop->addBasicBlockToLoop(S.FinalExit, *LI);
337 // splitBasicBlock does not update the dominator tree; the new exit's sole
338 // predecessor is the original exit block.
339 DT->addNewBlock(S.FinalExit, OrigExit);
340
341 // (1) Carried values: each non-induction header PHI whose backedge value
342 // differs from its initial value must resume in later partitions.
343 DenseMap<Value *, unsigned> CarriedDefToEscapingIdx;
344 for (PHINode &HeaderPHI : L->getHeader()->phis()) {
345 if (&HeaderPHI == S.Induction)
346 continue;
347 Value *CarriedValue = HeaderPHI.getIncomingValueForBlock(Latch);
348 Value *InitialValue = HeaderPHI.getIncomingValueForBlock(OrigPreheader);
349 if (CarriedValue == InitialValue)
350 continue; // invariant and equal to the initial value: nothing to carry.
351 auto &EV = S.addEscaping(CarriedValue);
352 EV.CarriedHeaderPHI = &HeaderPHI;
353 // Track in-loop carried defs so a matching live-out in (2) merges onto
354 // them.
355 if (auto *CarriedInst = dyn_cast<Instruction>(CarriedValue);
356 CarriedInst && L->contains(CarriedInst))
357 CarriedDefToEscapingIdx[CarriedValue] = S.Escaping.size() - 1;
358 }
359
360 // (2) Live-outs: dissolve each LCSSA PHI into its def and mark it escaping,
361 // merging onto a pass-(1) entry if also carried. Uses are repaired later.
362 for (PHINode &LCSSAPhi : make_early_inc_range(S.FinalExit->phis())) {
363 assert(LCSSAPhi.getNumIncomingValues() == 1 &&
364 "exit block not in LCSSA form");
365 Value *LiveOutDef = LCSSAPhi.getIncomingValue(0);
366 auto Existing = CarriedDefToEscapingIdx.find(LiveOutDef);
367 auto &EV = Existing != CarriedDefToEscapingIdx.end()
368 ? S.Escaping[Existing->second]
369 : S.addEscaping(LiveOutDef);
370 EV.EscapesOutside = true;
371 LCSSAPhi.replaceAllUsesWith(LiveOutDef);
372 LCSSAPhi.eraseFromParent();
373 }
374
375 // Seed partition 0 with the originals; later partitions are filled when
376 // cloned.
377 const unsigned N = getNumPartitions();
378 for (auto &EV : S.Escaping) {
379 EV.PerPartitionDef.assign(N, nullptr);
380 EV.PerPartitionPHI.assign(N, nullptr);
381 EV.PerPartitionDef[0] = EV.Def;
382 EV.PerPartitionPHI[0] = EV.CarriedHeaderPHI;
383 }
384}
385
386// Insert the entry guard ahead of partition 0's preheader and update the
387// dominator tree. On return \p Preheader is the clean preheader and
388// \p EntryGuard is the new guard block dominating the chain.
389static void buildEntryGuard(BasicBlock *&Preheader, BasicBlock *&EntryGuard,
390 DominatorTree *DT, LoopInfo *LI) {
391 // Split the preheader: the upper half becomes the guard dominating the chain,
392 // the lower half a clean preheader.
393 BasicBlock *NewPreheader =
394 SplitBlock(Preheader, Preheader->getTerminator(), DT, LI);
395 EntryGuard = Preheader;
396 Preheader = NewPreheader;
397 // Move the original preheader's name onto the new preheader, then name the
398 // guard.
399 Preheader->takeName(EntryGuard);
400 EntryGuard->setName("ls.guard0");
401}
402
403// Materialize each partition's start and clamped end in the entry guard and
404// flag the partitions that are provably empty at compile time.
405void LoopSplitUtils::expandPartitionBounds(SplitState &S,
406 SCEVExpander &Expander) {
407 Type *IndTy = S.Induction->getType();
408 Instruction *EntryGuardTerm = Partitions[0].GuardBlock->getTerminator();
409
410 // Expand all partition bounds in the entry guard, which dominates the whole
411 // chain (a skipped partition bypasses the original preheader).
412 const unsigned N = getNumPartitions();
413 for (unsigned I = 0; I < N; ++I) {
414 PartitionInfo &P = Partitions[I];
415
416 // Provably empty when Start overshoots End by exactly one step.
417 // Compile-time only: a runtime overshoot wraps at the type extreme and
418 // would falsely enter.
419 const SCEV *PartWidth = SE->getMinusSCEV(P.StartExpr, P.EndExpr);
420 if (auto *PartWidthConst = dyn_cast<SCEVConstant>(PartWidth)) {
421 const APInt &W = PartWidthConst->getAPInt();
422 P.Empty = S.Descending ? W.isAllOnes() : W.isOne();
423 }
424
425 P.StartVal = Expander.expandCodeFor(P.StartExpr, IndTy, EntryGuardTerm);
426
427 // Clamp the end to the induction end (min ascending, max descending) so a
428 // short trip count keeps the last iteration in the right partition.
429 const SCEV *ClampedEndSCEV;
430 if (S.Descending)
431 ClampedEndSCEV = InductionIsSigned
432 ? SE->getSMaxExpr(P.EndExpr, InductionEnd)
433 : SE->getUMaxExpr(P.EndExpr, InductionEnd);
434 else
435 ClampedEndSCEV = InductionIsSigned
436 ? SE->getSMinExpr(P.EndExpr, InductionEnd)
437 : SE->getUMinExpr(P.EndExpr, InductionEnd);
438 P.SelEnd = Expander.expandCodeFor(ClampedEndSCEV, IndTy, EntryGuardTerm);
439 }
440}
441
442// Pass 1: clone each later partition's sub-loop and create its guard and exit
443// blocks (partition 0 reuses the original loop).
444void LoopSplitUtils::clonePartitions(SplitState &S) {
445 Function &F = *L->getHeader()->getParent();
446 LLVMContext &Ctx = F.getContext();
447
448 const unsigned N = getNumPartitions();
449 // Partition 0 reuses the original loop; clone the rest off its preheader.
450 BasicBlock *OrigPreheader = Partitions[0].Preheader;
451
452 for (unsigned I = 1; I < N; ++I) {
453 PartitionInfo &P = Partitions[I];
454 // Persist this partition's original-to-clone map so callers can later
455 // query the counterpart of an original loop value (getPartitionValue()).
456 P.VMap = std::make_unique<ValueToValueMapTy>();
457 ValueToValueMapTy &VMap = *P.VMap;
458 SmallVector<BasicBlock *, 8> ClonedBlocks;
459 Loop *PL = cloneLoopWithPreheader(S.FinalExit, OrigPreheader, L, VMap,
460 ".ls" + Twine(I), LI, DT, ClonedBlocks);
461 remapInstructionsInBlocks(ClonedBlocks, VMap);
462 BasicBlock *PHi = PL->getLoopPreheader();
463
464 BasicBlock *Exiti =
465 BasicBlock::Create(Ctx, "ls.exit" + Twine(I), &F, S.FinalExit);
466 BasicBlock *Guardi =
467 BasicBlock::Create(Ctx, "ls.guard" + Twine(I), &F, PHi);
468 if (S.OuterLoop) {
469 S.OuterLoop->addBasicBlockToLoop(Exiti, *LI);
470 S.OuterLoop->addBasicBlockToLoop(Guardi, *LI);
471 }
472 // Placeholder terminators; both are re-pointed at the merge in pass 2.
473 UncondBrInst::Create(S.FinalExit, Exiti);
474 UncondBrInst::Create(S.FinalExit, Guardi);
475
476 // Seed the clone's induction PHI with this partition's start value.
477 auto *ClonedInduction = cast<PHINode>(VMap[S.Induction]);
478 ClonedInduction->setIncomingValueForBlock(PHi, P.StartVal);
479
480 P.GuardBlock = Guardi;
481 P.Preheader = PHi;
482 P.Exit = Exiti;
483 P.SubLoop = PL;
484 P.LatchIndOp = VMap.lookup_or(LatchIndOperand, LatchIndOperand);
485
486 for (auto &EV : S.Escaping) {
487 EV.PerPartitionDef[I] = VMap.lookup_or(EV.Def, EV.Def);
488 if (EV.CarriedHeaderPHI)
489 EV.PerPartitionPHI[I] = cast<PHINode>(VMap[EV.CarriedHeaderPHI]);
490 }
491 }
492}
493
494// Replace a partition's latch test so it iterates only within [start, SelEnd].
495static void rewriteLatch(Loop *PL, Value *IndOp, Value *SelEnd,
496 BasicBlock *Exit, bool Signed, bool Descending,
497 bool LatchComparesPHI) {
498 auto *Term = cast<CondBrInst>(PL->getLoopLatch()->getTerminator());
499 auto *Cmp = cast<ICmpInst>(Term->getCondition());
500 IRBuilder<> B(Cmp);
501 Value *Bound = SelEnd;
502 if (Bound->getType() != IndOp->getType())
503 Bound = B.CreateIntCast(Bound, IndOp->getType(), Signed);
504 // Strict when the PHI itself is compared, inclusive when the step value is.
506 /*Inclusive=*/!LatchComparesPHI);
507 Value *NewCmp = B.CreateICmp(Pred, IndOp, Bound, "itr.chk");
508 B.SetInsertPoint(Term);
509 B.CreateCondBr(NewCmp, PL->getHeader(), Exit);
510 Term->eraseFromParent();
511 if (Cmp->use_empty())
512 Cmp->eraseFromParent();
513}
514
515// Pass 2: emit each partition's guard branch, clamp its latch, wire the
516// partitions into a chain, and update the dominator tree.
517void LoopSplitUtils::chainPartitions(SplitState &S) {
518 const ICmpInst::Predicate GuardPred =
519 guardPredicate(InductionIsSigned, S.Descending);
520
521 // Emit each guard, clamp each latch, and chain partitions; a skipped
522 // partition falls through to the next guard.
523 const unsigned N = getNumPartitions();
524
525 // Enters unconditionally when the caller opted out of the guard and the
526 // partition is not provably empty; a proven-empty partition always skips.
527 auto EntersUnconditionally = [](const PartitionInfo &P) {
528 return !P.Empty && !P.Guarded;
529 };
530
531 // Where control goes when partition Idx is skipped or after it finishes: the
532 // next partition's guard, or the final merge block for the last partition.
533 auto MergeTargetAfter = [&](unsigned Idx) -> BasicBlock * {
534 bool IsLastPartition = Idx + 1 == N;
535 return IsLastPartition ? S.FinalExit : Partitions[Idx + 1].GuardBlock;
536 };
537
538 for (unsigned I = 0; I < N; ++I) {
539 PartitionInfo &P = Partitions[I];
540 BasicBlock *MergeAfter = MergeTargetAfter(I);
541
542 Instruction *GuardTerm = P.GuardBlock->getTerminator();
543 IRBuilder<> B(GuardTerm);
544 if (P.Empty) {
545 // Provably empty: skip to the next partition. The unreachable loop body
546 // is removed by later passes.
547 B.CreateBr(MergeAfter);
548 } else if (!P.Guarded) {
549 // Caller guaranteed at least one iteration: enter unconditionally. The
550 // skip edge to MergeAfter is omitted (see DT update below).
551 B.CreateBr(P.Preheader);
552 } else {
553 Value *Enter = B.CreateICmp(GuardPred, P.StartVal, P.SelEnd, "itr.chk");
554 B.CreateCondBr(Enter, P.Preheader, MergeAfter);
555 }
556 GuardTerm->eraseFromParent();
557
558 rewriteLatch(P.SubLoop, P.LatchIndOp, P.SelEnd, P.Exit, InductionIsSigned,
559 S.Descending, S.LatchComparesPHI);
560 P.Exit->getTerminator()->setSuccessor(0, MergeAfter);
561 }
562
563 // Patch the dominator tree directly: a merge target is dominated by the prior
564 // partition's exit when it enters unconditionally, otherwise by its guard.
565 auto MergeTargetIDom = [&](const PartitionInfo &P) {
566 return EntersUnconditionally(P) ? P.Exit : P.GuardBlock;
567 };
568
569 for (unsigned I = 1; I < N; ++I) {
570 PartitionInfo &Prev = Partitions[I - 1];
571 PartitionInfo &Cur = Partitions[I];
572 DT->addNewBlock(Cur.GuardBlock, MergeTargetIDom(Prev));
573 DT->changeImmediateDominator(Cur.Preheader, Cur.GuardBlock);
574 DT->addNewBlock(Cur.Exit, Cur.SubLoop->getLoopLatch());
575 }
576 // The final exit is the last partition's merge target.
577 DT->changeImmediateDominator(S.FinalExit, MergeTargetIDom(Partitions.back()));
578}
579
580// Rebuild SSA for every escaping value, repairing outside uses and seeding each
581// later partition's carried PHI, using one SSAUpdater per value.
582void LoopSplitUtils::reconstructSSA(SplitState &S) {
583 const unsigned N = getNumPartitions();
584 for (auto &EV : S.Escaping) {
585 SSAUpdater Updater;
586 Updater.Initialize(EV.Def->getType(), EV.Def->getName());
587
588 // Value before any partition runs: carried PHI's initial value, else
589 // poison.
590 Value *Init = EV.CarriedHeaderPHI
591 ? EV.CarriedHeaderPHI->getIncomingValueForBlock(
592 Partitions[0].Preheader)
593 : PoisonValue::get(EV.Def->getType());
594 Updater.AddAvailableValue(Partitions[0].GuardBlock, Init);
595 for (unsigned I = 0; I < N; ++I)
596 Updater.AddAvailableValue(Partitions[I].Exit, EV.PerPartitionDef[I]);
597
598 // Repair outside uses before the carried-PHI seeds add new in-clone uses.
599 // make_early_inc_range advances past each use before RewriteUse() unlinks
600 // it from Def's use-list, so the rewrite cannot invalidate the iteration.
601 if (EV.EscapesOutside)
602 for (Use &U : make_early_inc_range(EV.Def->uses()))
603 if (auto *User = dyn_cast<Instruction>(U.getUser()))
604 if (!L->contains(User))
605 Updater.RewriteUse(U);
606
607 // Seed each later partition's carried PHI from the preceding partitions.
608 if (EV.CarriedHeaderPHI)
609 for (unsigned I = 1; I < N; ++I) {
610 PHINode *CarriedPHI = EV.PerPartitionPHI[I];
611 int PreheaderEntryIdx =
612 CarriedPHI->getBasicBlockIndex(Partitions[I].Preheader);
613 assert(PreheaderEntryIdx >= 0 && "cloned preheader edge missing");
614 Updater.RewriteUse(CarriedPHI->getOperandUse(PreheaderEntryIdx));
615 }
616 }
617}
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)
#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.
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
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
#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)