LLVM 22.0.0git
LoopConstrainer.cpp
Go to the documentation of this file.
10
11using namespace llvm;
12
13static const char *ClonedLoopTag = "loop_constrainer.loop.clone";
14
15#define DEBUG_TYPE "loop-constrainer"
16
17/// Given a loop with an deccreasing induction variable, is it possible to
18/// safely calculate the bounds of a new loop using the given Predicate.
19static bool isSafeDecreasingBound(const SCEV *Start, const SCEV *BoundSCEV,
20 const SCEV *Step, ICmpInst::Predicate Pred,
21 unsigned LatchBrExitIdx, Loop *L,
22 ScalarEvolution &SE) {
23 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT &&
24 Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT)
25 return false;
26
27 if (!SE.isAvailableAtLoopEntry(BoundSCEV, L))
28 return false;
29
30 assert(SE.isKnownNegative(Step) && "expecting negative step");
31
32 LLVM_DEBUG(dbgs() << "isSafeDecreasingBound with:\n");
33 LLVM_DEBUG(dbgs() << "Start: " << *Start << "\n");
34 LLVM_DEBUG(dbgs() << "Step: " << *Step << "\n");
35 LLVM_DEBUG(dbgs() << "BoundSCEV: " << *BoundSCEV << "\n");
36 LLVM_DEBUG(dbgs() << "Pred: " << Pred << "\n");
37 LLVM_DEBUG(dbgs() << "LatchExitBrIdx: " << LatchBrExitIdx << "\n");
38
39 bool IsSigned = ICmpInst::isSigned(Pred);
40 // The predicate that we need to check that the induction variable lies
41 // within bounds.
42 ICmpInst::Predicate BoundPred =
44
45 auto StartLG = SE.applyLoopGuards(Start, L);
46 auto BoundLG = SE.applyLoopGuards(BoundSCEV, L);
47
48 if (LatchBrExitIdx == 1)
49 return SE.isLoopEntryGuardedByCond(L, BoundPred, StartLG, BoundLG);
50
51 assert(LatchBrExitIdx == 0 && "LatchBrExitIdx should be either 0 or 1");
52
53 const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType()));
54 unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth();
57 const SCEV *Limit = SE.getMinusSCEV(SE.getConstant(Min), StepPlusOne);
58
59 const SCEV *MinusOne =
60 SE.getMinusSCEV(BoundLG, SE.getOne(BoundLG->getType()));
61
62 return SE.isLoopEntryGuardedByCond(L, BoundPred, StartLG, MinusOne) &&
63 SE.isLoopEntryGuardedByCond(L, BoundPred, BoundLG, Limit);
64}
65
66/// Given a loop with an increasing induction variable, is it possible to
67/// safely calculate the bounds of a new loop using the given Predicate.
68static bool isSafeIncreasingBound(const SCEV *Start, const SCEV *BoundSCEV,
69 const SCEV *Step, ICmpInst::Predicate Pred,
70 unsigned LatchBrExitIdx, Loop *L,
71 ScalarEvolution &SE) {
72 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT &&
73 Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT)
74 return false;
75
76 if (!SE.isAvailableAtLoopEntry(BoundSCEV, L))
77 return false;
78
79 LLVM_DEBUG(dbgs() << "isSafeIncreasingBound with:\n");
80 LLVM_DEBUG(dbgs() << "Start: " << *Start << "\n");
81 LLVM_DEBUG(dbgs() << "Step: " << *Step << "\n");
82 LLVM_DEBUG(dbgs() << "BoundSCEV: " << *BoundSCEV << "\n");
83 LLVM_DEBUG(dbgs() << "Pred: " << Pred << "\n");
84 LLVM_DEBUG(dbgs() << "LatchExitBrIdx: " << LatchBrExitIdx << "\n");
85
86 bool IsSigned = ICmpInst::isSigned(Pred);
87 // The predicate that we need to check that the induction variable lies
88 // within bounds.
89 ICmpInst::Predicate BoundPred =
91
92 auto StartLG = SE.applyLoopGuards(Start, L);
93 auto BoundLG = SE.applyLoopGuards(BoundSCEV, L);
94
95 if (LatchBrExitIdx == 1)
96 return SE.isLoopEntryGuardedByCond(L, BoundPred, StartLG, BoundLG);
97
98 assert(LatchBrExitIdx == 0 && "LatchBrExitIdx should be 0 or 1");
99
100 const SCEV *StepMinusOne = SE.getMinusSCEV(Step, SE.getOne(Step->getType()));
101 unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth();
102 APInt Max = IsSigned ? APInt::getSignedMaxValue(BitWidth)
104 const SCEV *Limit = SE.getMinusSCEV(SE.getConstant(Max), StepMinusOne);
105
106 return (SE.isLoopEntryGuardedByCond(L, BoundPred, StartLG,
107 SE.getAddExpr(BoundLG, Step)) &&
108 SE.isLoopEntryGuardedByCond(L, BoundPred, BoundLG, Limit));
109}
110
111/// Returns estimate for max latch taken count of the loop of the narrowest
112/// available type. If the latch block has such estimate, it is returned.
113/// Otherwise, we use max exit count of whole loop (that is potentially of wider
114/// type than latch check itself), which is still better than no estimate.
116 const Loop &L) {
117 const SCEV *FromBlock =
118 SE.getExitCount(&L, L.getLoopLatch(), ScalarEvolution::SymbolicMaximum);
119 if (isa<SCEVCouldNotCompute>(FromBlock))
121 return FromBlock;
122}
123
124std::optional<LoopStructure>
126 bool AllowUnsignedLatchCond,
127 const char *&FailureReason) {
128 if (!L.isLoopSimplifyForm()) {
129 FailureReason = "loop not in LoopSimplify form";
130 return std::nullopt;
131 }
132
133 BasicBlock *Latch = L.getLoopLatch();
134 assert(Latch && "Simplified loops only have one latch!");
135
136 if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
137 FailureReason = "loop has already been cloned";
138 return std::nullopt;
139 }
140
141 if (!L.isLoopExiting(Latch)) {
142 FailureReason = "no loop latch";
143 return std::nullopt;
144 }
145
146 BasicBlock *Header = L.getHeader();
147 BasicBlock *Preheader = L.getLoopPreheader();
148 if (!Preheader) {
149 FailureReason = "no preheader";
150 return std::nullopt;
151 }
152
153 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
154 if (!LatchBr || LatchBr->isUnconditional()) {
155 FailureReason = "latch terminator not conditional branch";
156 return std::nullopt;
157 }
158
159 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
160
161 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
162 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
163 FailureReason = "latch terminator branch not conditional on integral icmp";
164 return std::nullopt;
165 }
166
167 const SCEV *MaxBETakenCount = getNarrowestLatchMaxTakenCountEstimate(SE, L);
168 if (isa<SCEVCouldNotCompute>(MaxBETakenCount)) {
169 FailureReason = "could not compute latch count";
170 return std::nullopt;
171 }
172 assert(SE.getLoopDisposition(MaxBETakenCount, &L) ==
174 "loop variant exit count doesn't make sense!");
175
176 ICmpInst::Predicate Pred = ICI->getPredicate();
177 Value *LeftValue = ICI->getOperand(0);
178 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
179 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
180
181 Value *RightValue = ICI->getOperand(1);
182 const SCEV *RightSCEV = SE.getSCEV(RightValue);
183
184 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
185 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
186 if (isa<SCEVAddRecExpr>(RightSCEV)) {
187 std::swap(LeftSCEV, RightSCEV);
188 std::swap(LeftValue, RightValue);
190 } else {
191 FailureReason = "no add recurrences in the icmp";
192 return std::nullopt;
193 }
194 }
195
196 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
197 if (AR->getNoWrapFlags(SCEV::FlagNSW))
198 return true;
199
200 IntegerType *Ty = cast<IntegerType>(AR->getType());
201 IntegerType *WideTy =
202 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
203
204 const SCEVAddRecExpr *ExtendAfterOp =
206 if (ExtendAfterOp) {
207 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
208 const SCEV *ExtendedStep =
209 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
210
211 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
212 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
213
214 if (NoSignedWrap)
215 return true;
216 }
217
218 // We may have proved this when computing the sign extension above.
219 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
220 };
221
222 // `ICI` is interpreted as taking the backedge if the *next* value of the
223 // induction variable satisfies some constraint.
224
226 if (IndVarBase->getLoop() != &L) {
227 FailureReason = "LHS in cmp is not an AddRec for this loop";
228 return std::nullopt;
229 }
230 if (!IndVarBase->isAffine()) {
231 FailureReason = "LHS in icmp not induction variable";
232 return std::nullopt;
233 }
234 const SCEV *StepRec = IndVarBase->getStepRecurrence(SE);
235 if (!isa<SCEVConstant>(StepRec)) {
236 FailureReason = "LHS in icmp not induction variable";
237 return std::nullopt;
238 }
239 ConstantInt *StepCI = cast<SCEVConstant>(StepRec)->getValue();
240
241 if (ICI->isEquality() && !HasNoSignedWrap(IndVarBase)) {
242 FailureReason = "LHS in icmp needs nsw for equality predicates";
243 return std::nullopt;
244 }
245
246 assert(!StepCI->isZero() && "Zero step?");
247 bool IsIncreasing = !StepCI->isNegative();
249 const SCEV *StartNext = IndVarBase->getStart();
250 const SCEV *Addend = SE.getNegativeSCEV(IndVarBase->getStepRecurrence(SE));
251 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
252 const SCEV *Step = SE.getSCEV(StepCI);
253
254 const SCEV *FixedRightSCEV = nullptr;
255
256 // If RightValue resides within loop (but still being loop invariant),
257 // regenerate it as preheader.
258 if (auto *I = dyn_cast<Instruction>(RightValue))
259 if (L.contains(I->getParent()))
260 FixedRightSCEV = RightSCEV;
261
262 if (IsIncreasing) {
263 bool DecreasedRightValueByOne = false;
264 if (StepCI->isOne()) {
265 // Try to turn eq/ne predicates to those we can work with.
266 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
267 // while (++i != len) { while (++i < len) {
268 // ... ---> ...
269 // } }
270 // If both parts are known non-negative, it is profitable to use
271 // unsigned comparison in increasing loop. This allows us to make the
272 // comparison check against "RightSCEV + 1" more optimistic.
274 isKnownNonNegativeInLoop(RightSCEV, &L, SE))
275 Pred = ICmpInst::ICMP_ULT;
276 else
277 Pred = ICmpInst::ICMP_SLT;
278 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0) {
279 // while (true) { while (true) {
280 // if (++i == len) ---> if (++i > len - 1)
281 // break; break;
282 // ... ...
283 // } }
284 if (IndVarBase->getNoWrapFlags(SCEV::FlagNUW) &&
285 cannotBeMinInLoop(RightSCEV, &L, SE, /*Signed*/ false)) {
286 Pred = ICmpInst::ICMP_UGT;
287 RightSCEV =
288 SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType()));
289 DecreasedRightValueByOne = true;
290 } else if (cannotBeMinInLoop(RightSCEV, &L, SE, /*Signed*/ true)) {
291 Pred = ICmpInst::ICMP_SGT;
292 RightSCEV =
293 SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType()));
294 DecreasedRightValueByOne = true;
295 }
296 }
297 }
298
299 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
300 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
301 bool FoundExpectedPred =
302 (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0);
303
304 if (!FoundExpectedPred) {
305 FailureReason = "expected icmp slt semantically, found something else";
306 return std::nullopt;
307 }
308
310 if (!IsSignedPredicate && !AllowUnsignedLatchCond) {
311 FailureReason = "unsigned latch conditions are explicitly prohibited";
312 return std::nullopt;
313 }
314
315 if (!isSafeIncreasingBound(IndVarStart, RightSCEV, Step, Pred,
316 LatchBrExitIdx, &L, SE)) {
317 FailureReason = "Unsafe loop bounds";
318 return std::nullopt;
319 }
320 if (LatchBrExitIdx == 0) {
321 // We need to increase the right value unless we have already decreased
322 // it virtually when we replaced EQ with SGT.
323 if (!DecreasedRightValueByOne)
324 FixedRightSCEV =
325 SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
326 } else {
327 assert(!DecreasedRightValueByOne &&
328 "Right value can be decreased only for LatchBrExitIdx == 0!");
329 }
330 } else {
331 bool IncreasedRightValueByOne = false;
332 if (StepCI->isMinusOne()) {
333 // Try to turn eq/ne predicates to those we can work with.
334 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
335 // while (--i != len) { while (--i > len) {
336 // ... ---> ...
337 // } }
338 // We intentionally don't turn the predicate into UGT even if we know
339 // that both operands are non-negative, because it will only pessimize
340 // our check against "RightSCEV - 1".
341 Pred = ICmpInst::ICMP_SGT;
342 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0) {
343 // while (true) { while (true) {
344 // if (--i == len) ---> if (--i < len + 1)
345 // break; break;
346 // ... ...
347 // } }
348 if (IndVarBase->getNoWrapFlags(SCEV::FlagNUW) &&
349 cannotBeMaxInLoop(RightSCEV, &L, SE, /* Signed */ false)) {
350 Pred = ICmpInst::ICMP_ULT;
351 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
352 IncreasedRightValueByOne = true;
353 } else if (cannotBeMaxInLoop(RightSCEV, &L, SE, /* Signed */ true)) {
354 Pred = ICmpInst::ICMP_SLT;
355 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
356 IncreasedRightValueByOne = true;
357 }
358 }
359 }
360
361 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
362 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
363
364 bool FoundExpectedPred =
365 (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0);
366
367 if (!FoundExpectedPred) {
368 FailureReason = "expected icmp sgt semantically, found something else";
369 return std::nullopt;
370 }
371
373 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
374
375 if (!IsSignedPredicate && !AllowUnsignedLatchCond) {
376 FailureReason = "unsigned latch conditions are explicitly prohibited";
377 return std::nullopt;
378 }
379
380 if (!isSafeDecreasingBound(IndVarStart, RightSCEV, Step, Pred,
381 LatchBrExitIdx, &L, SE)) {
382 FailureReason = "Unsafe bounds";
383 return std::nullopt;
384 }
385
386 if (LatchBrExitIdx == 0) {
387 // We need to decrease the right value unless we have already increased
388 // it virtually when we replaced EQ with SLT.
389 if (!IncreasedRightValueByOne)
390 FixedRightSCEV =
391 SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType()));
392 } else {
393 assert(!IncreasedRightValueByOne &&
394 "Right value can be increased only for LatchBrExitIdx == 0!");
395 }
396 }
397 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
398
399 assert(!L.contains(LatchExit) && "expected an exit block!");
400 SCEVExpander Expander(SE, "loop-constrainer");
401 Instruction *Ins = Preheader->getTerminator();
402
403 if (FixedRightSCEV)
404 RightValue =
405 Expander.expandCodeFor(FixedRightSCEV, FixedRightSCEV->getType(), Ins);
406
407 Value *IndVarStartV = Expander.expandCodeFor(IndVarStart, IndVarTy, Ins);
408 IndVarStartV->setName("indvar.start");
409
410 LoopStructure Result;
411
412 Result.Tag = "main";
413 Result.Header = Header;
414 Result.Latch = Latch;
415 Result.LatchBr = LatchBr;
416 Result.LatchExit = LatchExit;
417 Result.LatchBrExitIdx = LatchBrExitIdx;
418 Result.IndVarStart = IndVarStartV;
419 Result.IndVarStep = StepCI;
420 Result.IndVarBase = LeftValue;
421 Result.IndVarIncreasing = IsIncreasing;
422 Result.LoopExitAt = RightValue;
423 Result.IsSignedPredicate = IsSignedPredicate;
424 Result.ExitCountTy = cast<IntegerType>(MaxBETakenCount->getType());
425
426 FailureReason = nullptr;
427
428 return Result;
429}
430
431// Add metadata to the loop L to disable loop optimizations. Callers need to
432// confirm that optimizing loop L is not beneficial.
434 // We do not care about any existing loopID related metadata for L, since we
435 // are setting all loop metadata to false.
436 LLVMContext &Context = L.getHeader()->getContext();
437 // Reserve first location for self reference to the LoopID metadata node.
438 MDNode *Dummy = MDNode::get(Context, {});
439 MDNode *DisableUnroll = MDNode::get(
440 Context, {MDString::get(Context, "llvm.loop.unroll.disable")});
441 Metadata *FalseVal =
442 ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0));
443 MDNode *DisableVectorize = MDNode::get(
444 Context,
445 {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal});
446 MDNode *DisableLICMVersioning = MDNode::get(
447 Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")});
448 MDNode *DisableDistribution = MDNode::get(
449 Context,
450 {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal});
451 MDNode *NewLoopID =
452 MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize,
453 DisableLICMVersioning, DisableDistribution});
454 // Set operand 0 to refer to the loop id itself.
455 NewLoopID->replaceOperandWith(0, NewLoopID);
456 L.setLoopID(NewLoopID);
457}
458
460 function_ref<void(Loop *, bool)> LPMAddNewLoop,
461 const LoopStructure &LS, ScalarEvolution &SE,
462 DominatorTree &DT, Type *T, SubRanges SR)
463 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()), SE(SE),
464 DT(DT), LI(LI), LPMAddNewLoop(LPMAddNewLoop), OriginalLoop(L), RangeTy(T),
465 MainLoopStructure(LS), SR(SR) {}
466
467void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
468 const char *Tag) const {
469 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
470 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
471 Result.Blocks.push_back(Clone);
472 Result.Map[BB] = Clone;
473 }
474
475 auto GetClonedValue = [&Result](Value *V) {
476 assert(V && "null values not in domain!");
477 auto It = Result.Map.find(V);
478 if (It == Result.Map.end())
479 return V;
480 return static_cast<Value *>(It->second);
481 };
482
483 auto *ClonedLatch =
484 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
485 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
486 MDNode::get(Ctx, {}));
487
488 Result.Structure = MainLoopStructure.map(GetClonedValue);
489 Result.Structure.Tag = Tag;
490
491 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
492 BasicBlock *ClonedBB = Result.Blocks[i];
493 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
494
495 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
496
497 for (Instruction &I : *ClonedBB)
500
501 // Exit blocks will now have one more predecessor and their PHI nodes need
502 // to be edited to reflect that. No phi nodes need to be introduced because
503 // the loop is in LCSSA.
504
505 for (auto *SBB : successors(OriginalBB)) {
506 if (OriginalLoop.contains(SBB))
507 continue; // not an exit block
508
509 for (PHINode &PN : SBB->phis()) {
510 Value *OldIncoming = PN.getIncomingValueForBlock(OriginalBB);
511 PN.addIncoming(GetClonedValue(OldIncoming), ClonedBB);
512 SE.forgetLcssaPhiWithNewPredecessor(&OriginalLoop, &PN);
513 }
514 }
515 }
516}
517
518LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
519 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
520 BasicBlock *ContinuationBlock) const {
521 // We start with a loop with a single latch:
522 //
523 // +--------------------+
524 // | |
525 // | preheader |
526 // | |
527 // +--------+-----------+
528 // | ----------------\
529 // | / |
530 // +--------v----v------+ |
531 // | | |
532 // | header | |
533 // | | |
534 // +--------------------+ |
535 // |
536 // ..... |
537 // |
538 // +--------------------+ |
539 // | | |
540 // | latch >----------/
541 // | |
542 // +-------v------------+
543 // |
544 // |
545 // | +--------------------+
546 // | | |
547 // +---> original exit |
548 // | |
549 // +--------------------+
550 //
551 // We change the control flow to look like
552 //
553 //
554 // +--------------------+
555 // | |
556 // | preheader >-------------------------+
557 // | | |
558 // +--------v-----------+ |
559 // | /-------------+ |
560 // | / | |
561 // +--------v--v--------+ | |
562 // | | | |
563 // | header | | +--------+ |
564 // | | | | | |
565 // +--------------------+ | | +-----v-----v-----------+
566 // | | | |
567 // | | | .pseudo.exit |
568 // | | | |
569 // | | +-----------v-----------+
570 // | | |
571 // ..... | | |
572 // | | +--------v-------------+
573 // +--------------------+ | | | |
574 // | | | | | ContinuationBlock |
575 // | latch >------+ | | |
576 // | | | +----------------------+
577 // +---------v----------+ |
578 // | |
579 // | |
580 // | +---------------^-----+
581 // | | |
582 // +-----> .exit.selector |
583 // | |
584 // +----------v----------+
585 // |
586 // +--------------------+ |
587 // | | |
588 // | original exit <----+
589 // | |
590 // +--------------------+
591
592 RewrittenRangeInfo RRI;
593
594 BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
595 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
596 &F, BBInsertLocation);
597 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
598 BBInsertLocation);
599
600 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
601 bool Increasing = LS.IndVarIncreasing;
602 bool IsSignedPredicate = LS.IsSignedPredicate;
603
604 IRBuilder<> B(PreheaderJump);
605 auto NoopOrExt = [&](Value *V) {
606 if (V->getType() == RangeTy)
607 return V;
608 return IsSignedPredicate ? B.CreateSExt(V, RangeTy, "wide." + V->getName())
609 : B.CreateZExt(V, RangeTy, "wide." + V->getName());
610 };
611
612 // EnterLoopCond - is it okay to start executing this `LS'?
613 Value *EnterLoopCond = nullptr;
614 auto Pred =
615 Increasing
616 ? (IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT)
617 : (IsSignedPredicate ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
618 Value *IndVarStart = NoopOrExt(LS.IndVarStart);
619 EnterLoopCond = B.CreateICmp(Pred, IndVarStart, ExitSubloopAt);
620
621 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
622 PreheaderJump->eraseFromParent();
623
624 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
625 B.SetInsertPoint(LS.LatchBr);
626 Value *IndVarBase = NoopOrExt(LS.IndVarBase);
627 Value *TakeBackedgeLoopCond = B.CreateICmp(Pred, IndVarBase, ExitSubloopAt);
628
629 Value *CondForBranch = LS.LatchBrExitIdx == 1
630 ? TakeBackedgeLoopCond
631 : B.CreateNot(TakeBackedgeLoopCond);
632
633 LS.LatchBr->setCondition(CondForBranch);
634
635 B.SetInsertPoint(RRI.ExitSelector);
636
637 // IterationsLeft - are there any more iterations left, given the original
638 // upper bound on the induction variable? If not, we branch to the "real"
639 // exit.
640 Value *LoopExitAt = NoopOrExt(LS.LoopExitAt);
641 Value *IterationsLeft = B.CreateICmp(Pred, IndVarBase, LoopExitAt);
642 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
643
644 BranchInst *BranchToContinuation =
645 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
646
647 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
648 // each of the PHI nodes in the loop header. This feeds into the initial
649 // value of the same PHI nodes if/when we continue execution.
650 for (PHINode &PN : LS.Header->phis()) {
651 PHINode *NewPHI = PHINode::Create(PN.getType(), 2, PN.getName() + ".copy",
652 BranchToContinuation->getIterator());
653
654 NewPHI->addIncoming(PN.getIncomingValueForBlock(Preheader), Preheader);
655 NewPHI->addIncoming(PN.getIncomingValueForBlock(LS.Latch),
656 RRI.ExitSelector);
657 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
658 }
659
660 RRI.IndVarEnd = PHINode::Create(IndVarBase->getType(), 2, "indvar.end",
661 BranchToContinuation->getIterator());
662 RRI.IndVarEnd->addIncoming(IndVarStart, Preheader);
663 RRI.IndVarEnd->addIncoming(IndVarBase, RRI.ExitSelector);
664
665 // The latch exit now has a branch from `RRI.ExitSelector' instead of
666 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
667 LS.LatchExit->replacePhiUsesWith(LS.Latch, RRI.ExitSelector);
668
669 return RRI;
670}
671
672void LoopConstrainer::rewriteIncomingValuesForPHIs(
673 LoopStructure &LS, BasicBlock *ContinuationBlock,
674 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
675 unsigned PHIIndex = 0;
676 for (PHINode &PN : LS.Header->phis())
677 PN.setIncomingValueForBlock(ContinuationBlock,
678 RRI.PHIValuesAtPseudoExit[PHIIndex++]);
679
680 LS.IndVarStart = RRI.IndVarEnd;
681}
682
683BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
684 BasicBlock *OldPreheader,
685 const char *Tag) const {
686 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
687 BranchInst::Create(LS.Header, Preheader);
688
689 LS.Header->replacePhiUsesWith(OldPreheader, Preheader);
690
691 return Preheader;
692}
693
694void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
695 Loop *ParentLoop = OriginalLoop.getParentLoop();
696 if (!ParentLoop)
697 return;
698
699 for (BasicBlock *BB : BBs)
700 ParentLoop->addBasicBlockToLoop(BB, LI);
701}
702
703Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
705 bool IsSubloop) {
706 Loop &New = *LI.AllocateLoop();
707 if (Parent)
708 Parent->addChildLoop(&New);
709 else
710 LI.addTopLevelLoop(&New);
711 LPMAddNewLoop(&New, IsSubloop);
712
713 // Add all of the blocks in Original to the new loop.
714 for (auto *BB : Original->blocks())
715 if (LI.getLoopFor(BB) == Original)
716 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
717
718 // Add all of the subloops to the new loop.
719 for (Loop *SubLoop : *Original)
720 createClonedLoopStructure(SubLoop, &New, VM, /* IsSubloop */ true);
721
722 return &New;
723}
724
726 BasicBlock *Preheader = OriginalLoop.getLoopPreheader();
727 assert(Preheader != nullptr && "precondition!");
728
729 OriginalPreheader = Preheader;
730 MainLoopPreheader = Preheader;
731 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
732 bool Increasing = MainLoopStructure.IndVarIncreasing;
733 IntegerType *IVTy = cast<IntegerType>(RangeTy);
734
735 SCEVExpander Expander(SE, "loop-constrainer");
736 Instruction *InsertPt = OriginalPreheader->getTerminator();
737
738 // It would have been better to make `PreLoop' and `PostLoop'
739 // `std::optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
740 // constructor.
741 ClonedLoop PreLoop, PostLoop;
742 bool NeedsPreLoop =
743 Increasing ? SR.LowLimit.has_value() : SR.HighLimit.has_value();
744 bool NeedsPostLoop =
745 Increasing ? SR.HighLimit.has_value() : SR.LowLimit.has_value();
746
747 Value *ExitPreLoopAt = nullptr;
748 Value *ExitMainLoopAt = nullptr;
749 const SCEVConstant *MinusOneS =
750 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
751
752 if (NeedsPreLoop) {
753 const SCEV *ExitPreLoopAtSCEV = nullptr;
754
755 if (Increasing)
756 ExitPreLoopAtSCEV = *SR.LowLimit;
757 else if (cannotBeMinInLoop(*SR.HighLimit, &OriginalLoop, SE,
758 IsSignedPredicate))
759 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
760 else {
761 LLVM_DEBUG(dbgs() << "could not prove no-overflow when computing "
762 << "preloop exit limit. HighLimit = "
763 << *(*SR.HighLimit) << "\n");
764 return false;
765 }
766
767 if (!Expander.isSafeToExpandAt(ExitPreLoopAtSCEV, InsertPt)) {
768 LLVM_DEBUG(dbgs() << "could not prove that it is safe to expand the"
769 << " preloop exit limit " << *ExitPreLoopAtSCEV
770 << " at block " << InsertPt->getParent()->getName()
771 << "\n");
772 return false;
773 }
774
775 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
776 ExitPreLoopAt->setName("exit.preloop.at");
777 }
778
779 if (NeedsPostLoop) {
780 const SCEV *ExitMainLoopAtSCEV = nullptr;
781
782 if (Increasing)
783 ExitMainLoopAtSCEV = *SR.HighLimit;
784 else if (cannotBeMinInLoop(*SR.LowLimit, &OriginalLoop, SE,
785 IsSignedPredicate))
786 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
787 else {
788 LLVM_DEBUG(dbgs() << "could not prove no-overflow when computing "
789 << "mainloop exit limit. LowLimit = "
790 << *(*SR.LowLimit) << "\n");
791 return false;
792 }
793
794 if (!Expander.isSafeToExpandAt(ExitMainLoopAtSCEV, InsertPt)) {
795 LLVM_DEBUG(dbgs() << "could not prove that it is safe to expand the"
796 << " main loop exit limit " << *ExitMainLoopAtSCEV
797 << " at block " << InsertPt->getParent()->getName()
798 << "\n");
799 return false;
800 }
801
802 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
803 ExitMainLoopAt->setName("exit.mainloop.at");
804 }
805
806 // We clone these ahead of time so that we don't have to deal with changing
807 // and temporarily invalid IR as we transform the loops.
808 if (NeedsPreLoop)
809 cloneLoop(PreLoop, "preloop");
810 if (NeedsPostLoop)
811 cloneLoop(PostLoop, "postloop");
812
813 RewrittenRangeInfo PreLoopRRI;
814
815 if (NeedsPreLoop) {
816 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
817 PreLoop.Structure.Header);
818
819 MainLoopPreheader =
820 createPreheader(MainLoopStructure, Preheader, "mainloop");
821 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
822 ExitPreLoopAt, MainLoopPreheader);
823 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
824 PreLoopRRI);
825 }
826
827 BasicBlock *PostLoopPreheader = nullptr;
828 RewrittenRangeInfo PostLoopRRI;
829
830 if (NeedsPostLoop) {
831 PostLoopPreheader =
832 createPreheader(PostLoop.Structure, Preheader, "postloop");
833 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
834 ExitMainLoopAt, PostLoopPreheader);
835 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
836 PostLoopRRI);
837 }
838
839 BasicBlock *NewMainLoopPreheader =
840 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
841 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
842 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
843 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
844
845 // Some of the above may be nullptr, filter them out before passing to
846 // addToParentLoopIfNeeded.
847 auto NewBlocksEnd =
848 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
849
850 addToParentLoopIfNeeded(ArrayRef(std::begin(NewBlocks), NewBlocksEnd));
851
852 DT.recalculate(F);
853
854 // We need to first add all the pre and post loop blocks into the loop
855 // structures (as part of createClonedLoopStructure), and then update the
856 // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating
857 // LI when LoopSimplifyForm is generated.
858 Loop *PreL = nullptr, *PostL = nullptr;
859 if (!PreLoop.Blocks.empty()) {
860 PreL = createClonedLoopStructure(&OriginalLoop,
861 OriginalLoop.getParentLoop(), PreLoop.Map,
862 /* IsSubLoop */ false);
863 }
864
865 if (!PostLoop.Blocks.empty()) {
866 PostL =
867 createClonedLoopStructure(&OriginalLoop, OriginalLoop.getParentLoop(),
868 PostLoop.Map, /* IsSubLoop */ false);
869 }
870
871 // This function canonicalizes the loop into Loop-Simplify and LCSSA forms.
872 auto CanonicalizeLoop = [&](Loop *L, bool IsOriginalLoop) {
873 formLCSSARecursively(*L, DT, &LI, &SE);
874 simplifyLoop(L, &DT, &LI, &SE, nullptr, nullptr, true);
875 // Pre/post loops are slow paths, we do not need to perform any loop
876 // optimizations on them.
877 if (!IsOriginalLoop)
879 };
880 if (PreL)
881 CanonicalizeLoop(PreL, false);
882 if (PostL)
883 CanonicalizeLoop(PostL, false);
884 CanonicalizeLoop(&OriginalLoop, true);
885
886 /// At this point:
887 /// - We've broken a "main loop" out of the loop in a way that the "main loop"
888 /// runs with the induction variable in a subset of [Begin, End).
889 /// - There is no overflow when computing "main loop" exit limit.
890 /// - Max latch taken count of the loop is limited.
891 /// It guarantees that induction variable will not overflow iterating in the
892 /// "main loop".
893 if (isa<OverflowingBinaryOperator>(MainLoopStructure.IndVarBase))
894 if (IsSignedPredicate)
895 cast<BinaryOperator>(MainLoopStructure.IndVarBase)
896 ->setHasNoSignedWrap(true);
897 /// TODO: support unsigned predicate.
898 /// To add NUW flag we need to prove that both operands of BO are
899 /// non-negative. E.g:
900 /// ...
901 /// %iv.next = add nsw i32 %iv, -1
902 /// %cmp = icmp ult i32 %iv.next, %n
903 /// br i1 %cmp, label %loopexit, label %loop
904 ///
905 /// -1 is MAX_UINT in terms of unsigned int. Adding anything but zero will
906 /// overflow, therefore NUW flag is not legal here.
907
908 return true;
909}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static const Function * getParent(const Value *V)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static const char * ClonedLoopTag
static const SCEV * getNarrowestLatchMaxTakenCountEstimate(ScalarEvolution &SE, const Loop &L)
Returns estimate for max latch taken count of the loop of the narrowest available type.
static bool isSafeDecreasingBound(const SCEV *Start, const SCEV *BoundSCEV, const SCEV *Step, ICmpInst::Predicate Pred, unsigned LatchBrExitIdx, Loop *L, ScalarEvolution &SE)
Given a loop with an deccreasing induction variable, is it possible to safely calculate the bounds of...
static void DisableAllLoopOptsOnLoop(Loop &L)
static bool isSafeIncreasingBound(const SCEV *Start, const SCEV *BoundSCEV, const SCEV *Step, ICmpInst::Predicate Pred, unsigned LatchBrExitIdx, Loop *L, ScalarEvolution &SE)
Given a loop with an increasing induction variable, is it possible to safely calculate the bounds of ...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#define LLVM_DEBUG(...)
Definition Debug.h:114
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:207
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:217
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
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 if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ ICMP_SLT
signed less than
Definition InstrTypes.h:705
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:703
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
@ ICMP_NE
not equal
Definition InstrTypes.h:698
bool isSigned() const
Definition InstrTypes.h:930
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:827
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:765
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:536
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Definition Constants.h:231
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:225
bool isNegative() const
Definition Constants.h:214
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:164
This instruction compares its operands according to the predicate given to the constructor.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:318
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
iterator_range< block_iterator > blocks() const
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
LoopConstrainer(Loop &L, LoopInfo &LI, function_ref< void(Loop *, bool)> LPMAddNewLoop, const LoopStructure &LS, ScalarEvolution &SE, DominatorTree &DT, Type *T, SubRanges SR)
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1078
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1569
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:608
Root of the metadata hierarchy.
Definition Metadata.h:64
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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...
This node represents a polynomial recurrence on the trip count of the specified loop.
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class represents a constant integer value.
This class uses information about analyze scalars to rewrite expressions in canonical form.
LLVM_ABI bool isSafeToExpandAt(const SCEV *S, const Instruction *InsertionPoint) const
Return true if the given expression is safe to expand in the sense that all materialized values are d...
LLVM_ABI Value * expandCodeFor(const SCEV *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.
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
LLVM_ABI bool isLoopEntryGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L)
Return the "disposition" of the given SCEV with respect to the given loop.
LLVM_ABI const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
@ LoopInvariant
The SCEV is loop-invariant.
LLVM_ABI bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L)
Determine if the SCEV can be evaluated at loop's entry.
LLVM_ABI const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
LLVM_ABI const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
@ SymbolicMaximum
An expression which provides an upper bound on the exact trip count.
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
const SCEV * getSymbolicMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEV that is greater than or equal to (i.e.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:293
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:24
Value * getOperand(unsigned i) const
Definition User.h:232
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
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
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
LLVM_ABI BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, bool MapAtoms=true)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
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)
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition LCSSA.cpp:449
LLVM_ABI bool cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, bool Signed)
Returns true if S is defined and never is equal to signed/unsigned max.
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition ValueMapper.h:98
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition ValueMapper.h:80
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
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 >
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
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
LLVM_ABI bool cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, bool Signed)
Returns true if S is defined and never is equal to signed/unsigned min.
LLVM_ABI bool isKnownNonNegativeInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE)
Returns true if we can prove that S is defined and always non-negative in loop L.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
LoopStructure()=default
static std::optional< LoopStructure > parseLoopStructure(ScalarEvolution &, Loop &, bool, const char *&)