LLVM 18.0.0git
LoopFlatten.cpp
Go to the documentation of this file.
1//===- LoopFlatten.cpp - Loop flattening pass------------------------------===//
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// This pass flattens pairs nested loops into a single loop.
10//
11// The intention is to optimise loop nests like this, which together access an
12// array linearly:
13//
14// for (int i = 0; i < N; ++i)
15// for (int j = 0; j < M; ++j)
16// f(A[i*M+j]);
17//
18// into one loop:
19//
20// for (int i = 0; i < (N*M); ++i)
21// f(A[i]);
22//
23// It can also flatten loops where the induction variables are not used in the
24// loop. This is only worth doing if the induction variables are only used in an
25// expression like i*M+j. If they had any other uses, we would have to insert a
26// div/mod to reconstruct the original values, so this wouldn't be profitable.
27//
28// We also need to prove that N*M will not overflow. The preferred solution is
29// to widen the IV, which avoids overflow checks, so that is tried first. If
30// the IV cannot be widened, then we try to determine that this new tripcount
31// expression won't overflow.
32//
33// Q: Does LoopFlatten use SCEV?
34// Short answer: Yes and no.
35//
36// Long answer:
37// For this transformation to be valid, we require all uses of the induction
38// variables to be linear expressions of the form i*M+j. The different Loop
39// APIs are used to get some loop components like the induction variable,
40// compare statement, etc. In addition, we do some pattern matching to find the
41// linear expressions and other loop components like the loop increment. The
42// latter are examples of expressions that do use the induction variable, but
43// are safe to ignore when we check all uses to be of the form i*M+j. We keep
44// track of all of this in bookkeeping struct FlattenInfo.
45// We assume the loops to be canonical, i.e. starting at 0 and increment with
46// 1. This makes RHS of the compare the loop tripcount (with the right
47// predicate). We use SCEV to then sanity check that this tripcount matches
48// with the tripcount as computed by SCEV.
49//
50//===----------------------------------------------------------------------===//
51
53
54#include "llvm/ADT/Statistic.h"
63#include "llvm/IR/Dominators.h"
64#include "llvm/IR/Function.h"
65#include "llvm/IR/IRBuilder.h"
66#include "llvm/IR/Module.h"
68#include "llvm/Support/Debug.h"
75#include <optional>
76
77using namespace llvm;
78using namespace llvm::PatternMatch;
79
80#define DEBUG_TYPE "loop-flatten"
81
82STATISTIC(NumFlattened, "Number of loops flattened");
83
85 "loop-flatten-cost-threshold", cl::Hidden, cl::init(2),
86 cl::desc("Limit on the cost of instructions that can be repeated due to "
87 "loop flattening"));
88
89static cl::opt<bool>
90 AssumeNoOverflow("loop-flatten-assume-no-overflow", cl::Hidden,
91 cl::init(false),
92 cl::desc("Assume that the product of the two iteration "
93 "trip counts will never overflow"));
94
95static cl::opt<bool>
96 WidenIV("loop-flatten-widen-iv", cl::Hidden, cl::init(true),
97 cl::desc("Widen the loop induction variables, if possible, so "
98 "overflow checks won't reject flattening"));
99
100namespace {
101// We require all uses of both induction variables to match this pattern:
102//
103// (OuterPHI * InnerTripCount) + InnerPHI
104//
105// I.e., it needs to be a linear expression of the induction variables and the
106// inner loop trip count. We keep track of all different expressions on which
107// checks will be performed in this bookkeeping struct.
108//
109struct FlattenInfo {
110 Loop *OuterLoop = nullptr; // The loop pair to be flattened.
111 Loop *InnerLoop = nullptr;
112
113 PHINode *InnerInductionPHI = nullptr; // These PHINodes correspond to loop
114 PHINode *OuterInductionPHI = nullptr; // induction variables, which are
115 // expected to start at zero and
116 // increment by one on each loop.
117
118 Value *InnerTripCount = nullptr; // The product of these two tripcounts
119 Value *OuterTripCount = nullptr; // will be the new flattened loop
120 // tripcount. Also used to recognise a
121 // linear expression that will be replaced.
122
123 SmallPtrSet<Value *, 4> LinearIVUses; // Contains the linear expressions
124 // of the form i*M+j that will be
125 // replaced.
126
127 BinaryOperator *InnerIncrement = nullptr; // Uses of induction variables in
128 BinaryOperator *OuterIncrement = nullptr; // loop control statements that
129 BranchInst *InnerBranch = nullptr; // are safe to ignore.
130
131 BranchInst *OuterBranch = nullptr; // The instruction that needs to be
132 // updated with new tripcount.
133
134 SmallPtrSet<PHINode *, 4> InnerPHIsToTransform;
135
136 bool Widened = false; // Whether this holds the flatten info before or after
137 // widening.
138
139 PHINode *NarrowInnerInductionPHI = nullptr; // Holds the old/narrow induction
140 PHINode *NarrowOuterInductionPHI = nullptr; // phis, i.e. the Phis before IV
141 // has been applied. Used to skip
142 // checks on phi nodes.
143
144 FlattenInfo(Loop *OL, Loop *IL) : OuterLoop(OL), InnerLoop(IL){};
145
146 bool isNarrowInductionPhi(PHINode *Phi) {
147 // This can't be the narrow phi if we haven't widened the IV first.
148 if (!Widened)
149 return false;
150 return NarrowInnerInductionPHI == Phi || NarrowOuterInductionPHI == Phi;
151 }
152 bool isInnerLoopIncrement(User *U) {
153 return InnerIncrement == U;
154 }
155 bool isOuterLoopIncrement(User *U) {
156 return OuterIncrement == U;
157 }
158 bool isInnerLoopTest(User *U) {
159 return InnerBranch->getCondition() == U;
160 }
161
162 bool checkOuterInductionPhiUsers(SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
163 for (User *U : OuterInductionPHI->users()) {
164 if (isOuterLoopIncrement(U))
165 continue;
166
167 auto IsValidOuterPHIUses = [&] (User *U) -> bool {
168 LLVM_DEBUG(dbgs() << "Found use of outer induction variable: "; U->dump());
169 if (!ValidOuterPHIUses.count(U)) {
170 LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n");
171 return false;
172 }
173 LLVM_DEBUG(dbgs() << "Use is optimisable\n");
174 return true;
175 };
176
177 if (auto *V = dyn_cast<TruncInst>(U)) {
178 for (auto *K : V->users()) {
179 if (!IsValidOuterPHIUses(K))
180 return false;
181 }
182 continue;
183 }
184
185 if (!IsValidOuterPHIUses(U))
186 return false;
187 }
188 return true;
189 }
190
191 bool matchLinearIVUser(User *U, Value *InnerTripCount,
192 SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
193 LLVM_DEBUG(dbgs() << "Checking linear i*M+j expression for: "; U->dump());
194 Value *MatchedMul = nullptr;
195 Value *MatchedItCount = nullptr;
196
197 bool IsAdd = match(U, m_c_Add(m_Specific(InnerInductionPHI),
198 m_Value(MatchedMul))) &&
199 match(MatchedMul, m_c_Mul(m_Specific(OuterInductionPHI),
200 m_Value(MatchedItCount)));
201
202 // Matches the same pattern as above, except it also looks for truncs
203 // on the phi, which can be the result of widening the induction variables.
204 bool IsAddTrunc =
205 match(U, m_c_Add(m_Trunc(m_Specific(InnerInductionPHI)),
206 m_Value(MatchedMul))) &&
207 match(MatchedMul, m_c_Mul(m_Trunc(m_Specific(OuterInductionPHI)),
208 m_Value(MatchedItCount)));
209
210 if (!MatchedItCount)
211 return false;
212
213 LLVM_DEBUG(dbgs() << "Matched multiplication: "; MatchedMul->dump());
214 LLVM_DEBUG(dbgs() << "Matched iteration count: "; MatchedItCount->dump());
215
216 // The mul should not have any other uses. Widening may leave trivially dead
217 // uses, which can be ignored.
218 if (count_if(MatchedMul->users(), [](User *U) {
219 return !isInstructionTriviallyDead(cast<Instruction>(U));
220 }) > 1) {
221 LLVM_DEBUG(dbgs() << "Multiply has more than one use\n");
222 return false;
223 }
224
225 // Look through extends if the IV has been widened. Don't look through
226 // extends if we already looked through a trunc.
227 if (Widened && IsAdd &&
228 (isa<SExtInst>(MatchedItCount) || isa<ZExtInst>(MatchedItCount))) {
229 assert(MatchedItCount->getType() == InnerInductionPHI->getType() &&
230 "Unexpected type mismatch in types after widening");
231 MatchedItCount = isa<SExtInst>(MatchedItCount)
232 ? dyn_cast<SExtInst>(MatchedItCount)->getOperand(0)
233 : dyn_cast<ZExtInst>(MatchedItCount)->getOperand(0);
234 }
235
236 LLVM_DEBUG(dbgs() << "Looking for inner trip count: ";
237 InnerTripCount->dump());
238
239 if ((IsAdd || IsAddTrunc) && MatchedItCount == InnerTripCount) {
240 LLVM_DEBUG(dbgs() << "Found. This sse is optimisable\n");
241 ValidOuterPHIUses.insert(MatchedMul);
242 LinearIVUses.insert(U);
243 return true;
244 }
245
246 LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n");
247 return false;
248 }
249
250 bool checkInnerInductionPhiUsers(SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
251 Value *SExtInnerTripCount = InnerTripCount;
252 if (Widened &&
253 (isa<SExtInst>(InnerTripCount) || isa<ZExtInst>(InnerTripCount)))
254 SExtInnerTripCount = cast<Instruction>(InnerTripCount)->getOperand(0);
255
256 for (User *U : InnerInductionPHI->users()) {
257 LLVM_DEBUG(dbgs() << "Checking User: "; U->dump());
258 if (isInnerLoopIncrement(U)) {
259 LLVM_DEBUG(dbgs() << "Use is inner loop increment, continuing\n");
260 continue;
261 }
262
263 // After widening the IVs, a trunc instruction might have been introduced,
264 // so look through truncs.
265 if (isa<TruncInst>(U)) {
266 if (!U->hasOneUse())
267 return false;
268 U = *U->user_begin();
269 }
270
271 // If the use is in the compare (which is also the condition of the inner
272 // branch) then the compare has been altered by another transformation e.g
273 // icmp ult %inc, tripcount -> icmp ult %j, tripcount-1, where tripcount is
274 // a constant. Ignore this use as the compare gets removed later anyway.
275 if (isInnerLoopTest(U)) {
276 LLVM_DEBUG(dbgs() << "Use is the inner loop test, continuing\n");
277 continue;
278 }
279
280 if (!matchLinearIVUser(U, SExtInnerTripCount, ValidOuterPHIUses)) {
281 LLVM_DEBUG(dbgs() << "Not a linear IV user\n");
282 return false;
283 }
284 LLVM_DEBUG(dbgs() << "Linear IV users found!\n");
285 }
286 return true;
287 }
288};
289} // namespace
290
291static bool
292setLoopComponents(Value *&TC, Value *&TripCount, BinaryOperator *&Increment,
293 SmallPtrSetImpl<Instruction *> &IterationInstructions) {
294 TripCount = TC;
295 IterationInstructions.insert(Increment);
296 LLVM_DEBUG(dbgs() << "Found Increment: "; Increment->dump());
297 LLVM_DEBUG(dbgs() << "Found trip count: "; TripCount->dump());
298 LLVM_DEBUG(dbgs() << "Successfully found all loop components\n");
299 return true;
300}
301
302// Given the RHS of the loop latch compare instruction, verify with SCEV
303// that this is indeed the loop tripcount.
304// TODO: This used to be a straightforward check but has grown to be quite
305// complicated now. It is therefore worth revisiting what the additional
306// benefits are of this (compared to relying on canonical loops and pattern
307// matching).
308static bool verifyTripCount(Value *RHS, Loop *L,
309 SmallPtrSetImpl<Instruction *> &IterationInstructions,
310 PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment,
311 BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) {
312 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
313 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
314 LLVM_DEBUG(dbgs() << "Backedge-taken count is not predictable\n");
315 return false;
316 }
317
318 // Evaluating in the trip count's type can not overflow here as the overflow
319 // checks are performed in checkOverflow, but are first tried to avoid by
320 // widening the IV.
321 const SCEV *SCEVTripCount =
322 SE->getTripCountFromExitCount(BackedgeTakenCount,
323 BackedgeTakenCount->getType(), L);
324
325 const SCEV *SCEVRHS = SE->getSCEV(RHS);
326 if (SCEVRHS == SCEVTripCount)
327 return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
328 ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(RHS);
329 if (ConstantRHS) {
330 const SCEV *BackedgeTCExt = nullptr;
331 if (IsWidened) {
332 const SCEV *SCEVTripCountExt;
333 // Find the extended backedge taken count and extended trip count using
334 // SCEV. One of these should now match the RHS of the compare.
335 BackedgeTCExt = SE->getZeroExtendExpr(BackedgeTakenCount, RHS->getType());
336 SCEVTripCountExt = SE->getTripCountFromExitCount(BackedgeTCExt,
337 RHS->getType(), L);
338 if (SCEVRHS != BackedgeTCExt && SCEVRHS != SCEVTripCountExt) {
339 LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
340 return false;
341 }
342 }
343 // If the RHS of the compare is equal to the backedge taken count we need
344 // to add one to get the trip count.
345 if (SCEVRHS == BackedgeTCExt || SCEVRHS == BackedgeTakenCount) {
346 ConstantInt *One = ConstantInt::get(ConstantRHS->getType(), 1);
347 Value *NewRHS = ConstantInt::get(
348 ConstantRHS->getContext(), ConstantRHS->getValue() + One->getValue());
349 return setLoopComponents(NewRHS, TripCount, Increment,
350 IterationInstructions);
351 }
352 return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
353 }
354 // If the RHS isn't a constant then check that the reason it doesn't match
355 // the SCEV trip count is because the RHS is a ZExt or SExt instruction
356 // (and take the trip count to be the RHS).
357 if (!IsWidened) {
358 LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
359 return false;
360 }
361 auto *TripCountInst = dyn_cast<Instruction>(RHS);
362 if (!TripCountInst) {
363 LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
364 return false;
365 }
366 if ((!isa<ZExtInst>(TripCountInst) && !isa<SExtInst>(TripCountInst)) ||
367 SE->getSCEV(TripCountInst->getOperand(0)) != SCEVTripCount) {
368 LLVM_DEBUG(dbgs() << "Could not find valid extended trip count\n");
369 return false;
370 }
371 return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
372}
373
374// Finds the induction variable, increment and trip count for a simple loop that
375// we can flatten.
377 Loop *L, SmallPtrSetImpl<Instruction *> &IterationInstructions,
378 PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment,
379 BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) {
380 LLVM_DEBUG(dbgs() << "Finding components of loop: " << L->getName() << "\n");
381
382 if (!L->isLoopSimplifyForm()) {
383 LLVM_DEBUG(dbgs() << "Loop is not in normal form\n");
384 return false;
385 }
386
387 // Currently, to simplify the implementation, the Loop induction variable must
388 // start at zero and increment with a step size of one.
389 if (!L->isCanonical(*SE)) {
390 LLVM_DEBUG(dbgs() << "Loop is not canonical\n");
391 return false;
392 }
393
394 // There must be exactly one exiting block, and it must be the same at the
395 // latch.
396 BasicBlock *Latch = L->getLoopLatch();
397 if (L->getExitingBlock() != Latch) {
398 LLVM_DEBUG(dbgs() << "Exiting and latch block are different\n");
399 return false;
400 }
401
402 // Find the induction PHI. If there is no induction PHI, we can't do the
403 // transformation. TODO: could other variables trigger this? Do we have to
404 // search for the best one?
405 InductionPHI = L->getInductionVariable(*SE);
406 if (!InductionPHI) {
407 LLVM_DEBUG(dbgs() << "Could not find induction PHI\n");
408 return false;
409 }
410 LLVM_DEBUG(dbgs() << "Found induction PHI: "; InductionPHI->dump());
411
412 bool ContinueOnTrue = L->contains(Latch->getTerminator()->getSuccessor(0));
413 auto IsValidPredicate = [&](ICmpInst::Predicate Pred) {
414 if (ContinueOnTrue)
415 return Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT;
416 else
417 return Pred == CmpInst::ICMP_EQ;
418 };
419
420 // Find Compare and make sure it is valid. getLatchCmpInst checks that the
421 // back branch of the latch is conditional.
422 ICmpInst *Compare = L->getLatchCmpInst();
423 if (!Compare || !IsValidPredicate(Compare->getUnsignedPredicate()) ||
424 Compare->hasNUsesOrMore(2)) {
425 LLVM_DEBUG(dbgs() << "Could not find valid comparison\n");
426 return false;
427 }
428 BackBranch = cast<BranchInst>(Latch->getTerminator());
429 IterationInstructions.insert(BackBranch);
430 LLVM_DEBUG(dbgs() << "Found back branch: "; BackBranch->dump());
431 IterationInstructions.insert(Compare);
432 LLVM_DEBUG(dbgs() << "Found comparison: "; Compare->dump());
433
434 // Find increment and trip count.
435 // There are exactly 2 incoming values to the induction phi; one from the
436 // pre-header and one from the latch. The incoming latch value is the
437 // increment variable.
438 Increment =
439 cast<BinaryOperator>(InductionPHI->getIncomingValueForBlock(Latch));
440 if ((Compare->getOperand(0) != Increment || !Increment->hasNUses(2)) &&
441 !Increment->hasNUses(1)) {
442 LLVM_DEBUG(dbgs() << "Could not find valid increment\n");
443 return false;
444 }
445 // The trip count is the RHS of the compare. If this doesn't match the trip
446 // count computed by SCEV then this is because the trip count variable
447 // has been widened so the types don't match, or because it is a constant and
448 // another transformation has changed the compare (e.g. icmp ult %inc,
449 // tripcount -> icmp ult %j, tripcount-1), or both.
450 Value *RHS = Compare->getOperand(1);
451
452 return verifyTripCount(RHS, L, IterationInstructions, InductionPHI, TripCount,
453 Increment, BackBranch, SE, IsWidened);
454}
455
456static bool checkPHIs(FlattenInfo &FI, const TargetTransformInfo *TTI) {
457 // All PHIs in the inner and outer headers must either be:
458 // - The induction PHI, which we are going to rewrite as one induction in
459 // the new loop. This is already checked by findLoopComponents.
460 // - An outer header PHI with all incoming values from outside the loop.
461 // LoopSimplify guarantees we have a pre-header, so we don't need to
462 // worry about that here.
463 // - Pairs of PHIs in the inner and outer headers, which implement a
464 // loop-carried dependency that will still be valid in the new loop. To
465 // be valid, this variable must be modified only in the inner loop.
466
467 // The set of PHI nodes in the outer loop header that we know will still be
468 // valid after the transformation. These will not need to be modified (with
469 // the exception of the induction variable), but we do need to check that
470 // there are no unsafe PHI nodes.
471 SmallPtrSet<PHINode *, 4> SafeOuterPHIs;
472 SafeOuterPHIs.insert(FI.OuterInductionPHI);
473
474 // Check that all PHI nodes in the inner loop header match one of the valid
475 // patterns.
476 for (PHINode &InnerPHI : FI.InnerLoop->getHeader()->phis()) {
477 // The induction PHIs break these rules, and that's OK because we treat
478 // them specially when doing the transformation.
479 if (&InnerPHI == FI.InnerInductionPHI)
480 continue;
481 if (FI.isNarrowInductionPhi(&InnerPHI))
482 continue;
483
484 // Each inner loop PHI node must have two incoming values/blocks - one
485 // from the pre-header, and one from the latch.
486 assert(InnerPHI.getNumIncomingValues() == 2);
487 Value *PreHeaderValue =
488 InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopPreheader());
489 Value *LatchValue =
490 InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopLatch());
491
492 // The incoming value from the outer loop must be the PHI node in the
493 // outer loop header, with no modifications made in the top of the outer
494 // loop.
495 PHINode *OuterPHI = dyn_cast<PHINode>(PreHeaderValue);
496 if (!OuterPHI || OuterPHI->getParent() != FI.OuterLoop->getHeader()) {
497 LLVM_DEBUG(dbgs() << "value modified in top of outer loop\n");
498 return false;
499 }
500
501 // The other incoming value must come from the inner loop, without any
502 // modifications in the tail end of the outer loop. We are in LCSSA form,
503 // so this will actually be a PHI in the inner loop's exit block, which
504 // only uses values from inside the inner loop.
505 PHINode *LCSSAPHI = dyn_cast<PHINode>(
506 OuterPHI->getIncomingValueForBlock(FI.OuterLoop->getLoopLatch()));
507 if (!LCSSAPHI) {
508 LLVM_DEBUG(dbgs() << "could not find LCSSA PHI\n");
509 return false;
510 }
511
512 // The value used by the LCSSA PHI must be the same one that the inner
513 // loop's PHI uses.
514 if (LCSSAPHI->hasConstantValue() != LatchValue) {
516 dbgs() << "LCSSA PHI incoming value does not match latch value\n");
517 return false;
518 }
519
520 LLVM_DEBUG(dbgs() << "PHI pair is safe:\n");
521 LLVM_DEBUG(dbgs() << " Inner: "; InnerPHI.dump());
522 LLVM_DEBUG(dbgs() << " Outer: "; OuterPHI->dump());
523 SafeOuterPHIs.insert(OuterPHI);
524 FI.InnerPHIsToTransform.insert(&InnerPHI);
525 }
526
527 for (PHINode &OuterPHI : FI.OuterLoop->getHeader()->phis()) {
528 if (FI.isNarrowInductionPhi(&OuterPHI))
529 continue;
530 if (!SafeOuterPHIs.count(&OuterPHI)) {
531 LLVM_DEBUG(dbgs() << "found unsafe PHI in outer loop: "; OuterPHI.dump());
532 return false;
533 }
534 }
535
536 LLVM_DEBUG(dbgs() << "checkPHIs: OK\n");
537 return true;
538}
539
540static bool
541checkOuterLoopInsts(FlattenInfo &FI,
542 SmallPtrSetImpl<Instruction *> &IterationInstructions,
543 const TargetTransformInfo *TTI) {
544 // Check for instructions in the outer but not inner loop. If any of these
545 // have side-effects then this transformation is not legal, and if there is
546 // a significant amount of code here which can't be optimised out that it's
547 // not profitable (as these instructions would get executed for each
548 // iteration of the inner loop).
549 InstructionCost RepeatedInstrCost = 0;
550 for (auto *B : FI.OuterLoop->getBlocks()) {
551 if (FI.InnerLoop->contains(B))
552 continue;
553
554 for (auto &I : *B) {
555 if (!isa<PHINode>(&I) && !I.isTerminator() &&
557 LLVM_DEBUG(dbgs() << "Cannot flatten because instruction may have "
558 "side effects: ";
559 I.dump());
560 return false;
561 }
562 // The execution count of the outer loop's iteration instructions
563 // (increment, compare and branch) will be increased, but the
564 // equivalent instructions will be removed from the inner loop, so
565 // they make a net difference of zero.
566 if (IterationInstructions.count(&I))
567 continue;
568 // The unconditional branch to the inner loop's header will turn into
569 // a fall-through, so adds no cost.
570 BranchInst *Br = dyn_cast<BranchInst>(&I);
571 if (Br && Br->isUnconditional() &&
572 Br->getSuccessor(0) == FI.InnerLoop->getHeader())
573 continue;
574 // Multiplies of the outer iteration variable and inner iteration
575 // count will be optimised out.
576 if (match(&I, m_c_Mul(m_Specific(FI.OuterInductionPHI),
577 m_Specific(FI.InnerTripCount))))
578 continue;
581 LLVM_DEBUG(dbgs() << "Cost " << Cost << ": "; I.dump());
582 RepeatedInstrCost += Cost;
583 }
584 }
585
586 LLVM_DEBUG(dbgs() << "Cost of instructions that will be repeated: "
587 << RepeatedInstrCost << "\n");
588 // Bail out if flattening the loops would cause instructions in the outer
589 // loop but not in the inner loop to be executed extra times.
590 if (RepeatedInstrCost > RepeatedInstructionThreshold) {
591 LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: not profitable, bailing.\n");
592 return false;
593 }
594
595 LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: OK\n");
596 return true;
597}
598
599
600
601// We require all uses of both induction variables to match this pattern:
602//
603// (OuterPHI * InnerTripCount) + InnerPHI
604//
605// Any uses of the induction variables not matching that pattern would
606// require a div/mod to reconstruct in the flattened loop, so the
607// transformation wouldn't be profitable.
608static bool checkIVUsers(FlattenInfo &FI) {
609 // Check that all uses of the inner loop's induction variable match the
610 // expected pattern, recording the uses of the outer IV.
611 SmallPtrSet<Value *, 4> ValidOuterPHIUses;
612 if (!FI.checkInnerInductionPhiUsers(ValidOuterPHIUses))
613 return false;
614
615 // Check that there are no uses of the outer IV other than the ones found
616 // as part of the pattern above.
617 if (!FI.checkOuterInductionPhiUsers(ValidOuterPHIUses))
618 return false;
619
620 LLVM_DEBUG(dbgs() << "checkIVUsers: OK\n";
621 dbgs() << "Found " << FI.LinearIVUses.size()
622 << " value(s) that can be replaced:\n";
623 for (Value *V : FI.LinearIVUses) {
624 dbgs() << " ";
625 V->dump();
626 });
627 return true;
628}
629
630// Return an OverflowResult dependant on if overflow of the multiplication of
631// InnerTripCount and OuterTripCount can be assumed not to happen.
632static OverflowResult checkOverflow(FlattenInfo &FI, DominatorTree *DT,
633 AssumptionCache *AC) {
634 Function *F = FI.OuterLoop->getHeader()->getParent();
635 const DataLayout &DL = F->getParent()->getDataLayout();
636
637 // For debugging/testing.
639 return OverflowResult::NeverOverflows;
640
641 // Check if the multiply could not overflow due to known ranges of the
642 // input values.
644 FI.InnerTripCount, FI.OuterTripCount,
645 SimplifyQuery(DL, DT, AC,
646 FI.OuterLoop->getLoopPreheader()->getTerminator()));
647 if (OR != OverflowResult::MayOverflow)
648 return OR;
649
650 for (Value *V : FI.LinearIVUses) {
651 for (Value *U : V->users()) {
652 if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
653 for (Value *GEPUser : U->users()) {
654 auto *GEPUserInst = cast<Instruction>(GEPUser);
655 if (!isa<LoadInst>(GEPUserInst) &&
656 !(isa<StoreInst>(GEPUserInst) &&
657 GEP == GEPUserInst->getOperand(1)))
658 continue;
660 FI.InnerLoop))
661 continue;
662 // The IV is used as the operand of a GEP which dominates the loop
663 // latch, and the IV is at least as wide as the address space of the
664 // GEP. In this case, the GEP would wrap around the address space
665 // before the IV increment wraps, which would be UB.
666 if (GEP->isInBounds() &&
667 V->getType()->getIntegerBitWidth() >=
668 DL.getPointerTypeSizeInBits(GEP->getType())) {
670 dbgs() << "use of linear IV would be UB if overflow occurred: ";
671 GEP->dump());
672 return OverflowResult::NeverOverflows;
673 }
674 }
675 }
676 }
677 }
678
679 return OverflowResult::MayOverflow;
680}
681
682static bool CanFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
684 const TargetTransformInfo *TTI) {
685 SmallPtrSet<Instruction *, 8> IterationInstructions;
686 if (!findLoopComponents(FI.InnerLoop, IterationInstructions,
687 FI.InnerInductionPHI, FI.InnerTripCount,
688 FI.InnerIncrement, FI.InnerBranch, SE, FI.Widened))
689 return false;
690 if (!findLoopComponents(FI.OuterLoop, IterationInstructions,
691 FI.OuterInductionPHI, FI.OuterTripCount,
692 FI.OuterIncrement, FI.OuterBranch, SE, FI.Widened))
693 return false;
694
695 // Both of the loop trip count values must be invariant in the outer loop
696 // (non-instructions are all inherently invariant).
697 if (!FI.OuterLoop->isLoopInvariant(FI.InnerTripCount)) {
698 LLVM_DEBUG(dbgs() << "inner loop trip count not invariant\n");
699 return false;
700 }
701 if (!FI.OuterLoop->isLoopInvariant(FI.OuterTripCount)) {
702 LLVM_DEBUG(dbgs() << "outer loop trip count not invariant\n");
703 return false;
704 }
705
706 if (!checkPHIs(FI, TTI))
707 return false;
708
709 // FIXME: it should be possible to handle different types correctly.
710 if (FI.InnerInductionPHI->getType() != FI.OuterInductionPHI->getType())
711 return false;
712
713 if (!checkOuterLoopInsts(FI, IterationInstructions, TTI))
714 return false;
715
716 // Find the values in the loop that can be replaced with the linearized
717 // induction variable, and check that there are no other uses of the inner
718 // or outer induction variable. If there were, we could still do this
719 // transformation, but we'd have to insert a div/mod to calculate the
720 // original IVs, so it wouldn't be profitable.
721 if (!checkIVUsers(FI))
722 return false;
723
724 LLVM_DEBUG(dbgs() << "CanFlattenLoopPair: OK\n");
725 return true;
726}
727
728static bool DoFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
731 MemorySSAUpdater *MSSAU) {
732 Function *F = FI.OuterLoop->getHeader()->getParent();
733 LLVM_DEBUG(dbgs() << "Checks all passed, doing the transformation\n");
734 {
735 using namespace ore;
736 OptimizationRemark Remark(DEBUG_TYPE, "Flattened", FI.InnerLoop->getStartLoc(),
737 FI.InnerLoop->getHeader());
739 Remark << "Flattened into outer loop";
740 ORE.emit(Remark);
741 }
742
743 Value *NewTripCount = BinaryOperator::CreateMul(
744 FI.InnerTripCount, FI.OuterTripCount, "flatten.tripcount",
745 FI.OuterLoop->getLoopPreheader()->getTerminator());
746 LLVM_DEBUG(dbgs() << "Created new trip count in preheader: ";
747 NewTripCount->dump());
748
749 // Fix up PHI nodes that take values from the inner loop back-edge, which
750 // we are about to remove.
751 FI.InnerInductionPHI->removeIncomingValue(FI.InnerLoop->getLoopLatch());
752
753 // The old Phi will be optimised away later, but for now we can't leave
754 // leave it in an invalid state, so are updating them too.
755 for (PHINode *PHI : FI.InnerPHIsToTransform)
756 PHI->removeIncomingValue(FI.InnerLoop->getLoopLatch());
757
758 // Modify the trip count of the outer loop to be the product of the two
759 // trip counts.
760 cast<User>(FI.OuterBranch->getCondition())->setOperand(1, NewTripCount);
761
762 // Replace the inner loop backedge with an unconditional branch to the exit.
763 BasicBlock *InnerExitBlock = FI.InnerLoop->getExitBlock();
764 BasicBlock *InnerExitingBlock = FI.InnerLoop->getExitingBlock();
765 InnerExitingBlock->getTerminator()->eraseFromParent();
766 BranchInst::Create(InnerExitBlock, InnerExitingBlock);
767
768 // Update the DomTree and MemorySSA.
769 DT->deleteEdge(InnerExitingBlock, FI.InnerLoop->getHeader());
770 if (MSSAU)
771 MSSAU->removeEdge(InnerExitingBlock, FI.InnerLoop->getHeader());
772
773 // Replace all uses of the polynomial calculated from the two induction
774 // variables with the one new one.
775 IRBuilder<> Builder(FI.OuterInductionPHI->getParent()->getTerminator());
776 for (Value *V : FI.LinearIVUses) {
777 Value *OuterValue = FI.OuterInductionPHI;
778 if (FI.Widened)
779 OuterValue = Builder.CreateTrunc(FI.OuterInductionPHI, V->getType(),
780 "flatten.trunciv");
781
782 LLVM_DEBUG(dbgs() << "Replacing: "; V->dump(); dbgs() << "with: ";
783 OuterValue->dump());
784 V->replaceAllUsesWith(OuterValue);
785 }
786
787 // Tell LoopInfo, SCEV and the pass manager that the inner loop has been
788 // deleted, and invalidate any outer loop information.
789 SE->forgetLoop(FI.OuterLoop);
791 if (U)
792 U->markLoopAsDeleted(*FI.InnerLoop, FI.InnerLoop->getName());
793 LI->erase(FI.InnerLoop);
794
795 // Increment statistic value.
796 NumFlattened++;
797
798 return true;
799}
800
801static bool CanWidenIV(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
803 const TargetTransformInfo *TTI) {
804 if (!WidenIV) {
805 LLVM_DEBUG(dbgs() << "Widening the IVs is disabled\n");
806 return false;
807 }
808
809 LLVM_DEBUG(dbgs() << "Try widening the IVs\n");
810 Module *M = FI.InnerLoop->getHeader()->getParent()->getParent();
811 auto &DL = M->getDataLayout();
812 auto *InnerType = FI.InnerInductionPHI->getType();
813 auto *OuterType = FI.OuterInductionPHI->getType();
814 unsigned MaxLegalSize = DL.getLargestLegalIntTypeSizeInBits();
815 auto *MaxLegalType = DL.getLargestLegalIntType(M->getContext());
816
817 // If both induction types are less than the maximum legal integer width,
818 // promote both to the widest type available so we know calculating
819 // (OuterTripCount * InnerTripCount) as the new trip count is safe.
820 if (InnerType != OuterType ||
821 InnerType->getScalarSizeInBits() >= MaxLegalSize ||
822 MaxLegalType->getScalarSizeInBits() <
823 InnerType->getScalarSizeInBits() * 2) {
824 LLVM_DEBUG(dbgs() << "Can't widen the IV\n");
825 return false;
826 }
827
828 SCEVExpander Rewriter(*SE, DL, "loopflatten");
830 unsigned ElimExt = 0;
831 unsigned Widened = 0;
832
833 auto CreateWideIV = [&](WideIVInfo WideIV, bool &Deleted) -> bool {
834 PHINode *WidePhi =
835 createWideIV(WideIV, LI, SE, Rewriter, DT, DeadInsts, ElimExt, Widened,
836 true /* HasGuards */, true /* UsePostIncrementRanges */);
837 if (!WidePhi)
838 return false;
839 LLVM_DEBUG(dbgs() << "Created wide phi: "; WidePhi->dump());
840 LLVM_DEBUG(dbgs() << "Deleting old phi: "; WideIV.NarrowIV->dump());
842 return true;
843 };
844
845 bool Deleted;
846 if (!CreateWideIV({FI.InnerInductionPHI, MaxLegalType, false}, Deleted))
847 return false;
848 // Add the narrow phi to list, so that it will be adjusted later when the
849 // the transformation is performed.
850 if (!Deleted)
851 FI.InnerPHIsToTransform.insert(FI.InnerInductionPHI);
852
853 if (!CreateWideIV({FI.OuterInductionPHI, MaxLegalType, false}, Deleted))
854 return false;
855
856 assert(Widened && "Widened IV expected");
857 FI.Widened = true;
858
859 // Save the old/narrow induction phis, which we need to ignore in CheckPHIs.
860 FI.NarrowInnerInductionPHI = FI.InnerInductionPHI;
861 FI.NarrowOuterInductionPHI = FI.OuterInductionPHI;
862
863 // After widening, rediscover all the loop components.
864 return CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI);
865}
866
867static bool FlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
870 MemorySSAUpdater *MSSAU) {
872 dbgs() << "Loop flattening running on outer loop "
873 << FI.OuterLoop->getHeader()->getName() << " and inner loop "
874 << FI.InnerLoop->getHeader()->getName() << " in "
875 << FI.OuterLoop->getHeader()->getParent()->getName() << "\n");
876
877 if (!CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI))
878 return false;
879
880 // Check if we can widen the induction variables to avoid overflow checks.
881 bool CanFlatten = CanWidenIV(FI, DT, LI, SE, AC, TTI);
882
883 // It can happen that after widening of the IV, flattening may not be
884 // possible/happening, e.g. when it is deemed unprofitable. So bail here if
885 // that is the case.
886 // TODO: IV widening without performing the actual flattening transformation
887 // is not ideal. While this codegen change should not matter much, it is an
888 // unnecessary change which is better to avoid. It's unlikely this happens
889 // often, because if it's unprofitibale after widening, it should be
890 // unprofitabe before widening as checked in the first round of checks. But
891 // 'RepeatedInstructionThreshold' is set to only 2, which can probably be
892 // relaxed. Because this is making a code change (the IV widening, but not
893 // the flattening), we return true here.
894 if (FI.Widened && !CanFlatten)
895 return true;
896
897 // If we have widened and can perform the transformation, do that here.
898 if (CanFlatten)
899 return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
900
901 // Otherwise, if we haven't widened the IV, check if the new iteration
902 // variable might overflow. In this case, we need to version the loop, and
903 // select the original version at runtime if the iteration space is too
904 // large.
905 // TODO: We currently don't version the loop.
906 OverflowResult OR = checkOverflow(FI, DT, AC);
907 if (OR == OverflowResult::AlwaysOverflowsHigh ||
908 OR == OverflowResult::AlwaysOverflowsLow) {
909 LLVM_DEBUG(dbgs() << "Multiply would always overflow, so not profitable\n");
910 return false;
911 } else if (OR == OverflowResult::MayOverflow) {
912 LLVM_DEBUG(dbgs() << "Multiply might overflow, not flattening\n");
913 return false;
914 }
915
916 LLVM_DEBUG(dbgs() << "Multiply cannot overflow, modifying loop in-place\n");
917 return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
918}
919
922 LPMUpdater &U) {
923
924 bool Changed = false;
925
926 std::optional<MemorySSAUpdater> MSSAU;
927 if (AR.MSSA) {
928 MSSAU = MemorySSAUpdater(AR.MSSA);
929 if (VerifyMemorySSA)
930 AR.MSSA->verifyMemorySSA();
931 }
932
933 // The loop flattening pass requires loops to be
934 // in simplified form, and also needs LCSSA. Running
935 // this pass will simplify all loops that contain inner loops,
936 // regardless of whether anything ends up being flattened.
937 for (Loop *InnerLoop : LN.getLoops()) {
938 auto *OuterLoop = InnerLoop->getParentLoop();
939 if (!OuterLoop)
940 continue;
941 FlattenInfo FI(OuterLoop, InnerLoop);
942 Changed |= FlattenLoopPair(FI, &AR.DT, &AR.LI, &AR.SE, &AR.AC, &AR.TTI, &U,
943 MSSAU ? &*MSSAU : nullptr);
944 }
945
946 if (!Changed)
947 return PreservedAnalyses::all();
948
949 if (AR.MSSA && VerifyMemorySSA)
950 AR.MSSA->verifyMemorySSA();
951
953 if (AR.MSSA)
954 PA.preserve<MemorySSAAnalysis>();
955 return PA;
956}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Rewrite undef for PHI
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DEBUG(X)
Definition: Debug.h:101
Hexagon Common GEP
static bool CanWidenIV(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, const TargetTransformInfo *TTI)
static bool verifyTripCount(Value *RHS, Loop *L, SmallPtrSetImpl< Instruction * > &IterationInstructions, PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment, BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened)
static bool FlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, const TargetTransformInfo *TTI, LPMUpdater *U, MemorySSAUpdater *MSSAU)
static cl::opt< bool > WidenIV("loop-flatten-widen-iv", cl::Hidden, cl::init(true), cl::desc("Widen the loop induction variables, if possible, so " "overflow checks won't reject flattening"))
static bool setLoopComponents(Value *&TC, Value *&TripCount, BinaryOperator *&Increment, SmallPtrSetImpl< Instruction * > &IterationInstructions)
static bool DoFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, const TargetTransformInfo *TTI, LPMUpdater *U, MemorySSAUpdater *MSSAU)
static bool checkIVUsers(FlattenInfo &FI)
static bool CanFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, const TargetTransformInfo *TTI)
static bool findLoopComponents(Loop *L, SmallPtrSetImpl< Instruction * > &IterationInstructions, PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment, BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened)
static OverflowResult checkOverflow(FlattenInfo &FI, DominatorTree *DT, AssumptionCache *AC)
static bool checkPHIs(FlattenInfo &FI, const TargetTransformInfo *TTI)
static cl::opt< unsigned > RepeatedInstructionThreshold("loop-flatten-cost-threshold", cl::Hidden, cl::init(2), cl::desc("Limit on the cost of instructions that can be repeated due to " "loop flattening"))
#define DEBUG_TYPE
Definition: LoopFlatten.cpp:80
static cl::opt< bool > AssumeNoOverflow("loop-flatten-assume-no-overflow", cl::Hidden, cl::init(false), cl::desc("Assume that the product of the two iteration " "trip counts will never overflow"))
static bool checkOuterLoopInsts(FlattenInfo &FI, SmallPtrSetImpl< Instruction * > &IterationInstructions, const TargetTransformInfo *TTI)
This file defines the interface for the loop nest analysis.
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Module.h This file contains the declarations for the Module class.
LoopAnalysisManager LAM
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
This pass exposes codegen information to IR-level passes.
Virtual Register Rewriter
Definition: VirtRegMap.cpp:237
Value * RHS
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:649
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
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:220
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
Value * getCondition() const
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:748
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:773
@ ICMP_EQ
equal
Definition: InstrTypes.h:769
@ ICMP_NE
not equal
Definition: InstrTypes.h:770
This is the shared class of boolean and integer constants.
Definition: Constants.h:78
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
Definition: Constants.h:176
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:888
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:136
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
void deleteEdge(NodeT *From, NodeT *To)
Inform the dominator tree about a CFG edge deletion and update the tree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:165
This instruction compares its operands according to the predicate given to the constructor.
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1993
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2636
const BasicBlock * getParent() const
Definition: Instruction.h:134
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:93
BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
PreservedAnalyses run(LoopNest &LN, LoopAnalysisManager &LAM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Definition: LoopInfo.cpp:876
This class represents a loop nest and can be used to query its properties.
ArrayRef< Loop * > getLoops() const
Get the loops in the nest.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:44
An analysis that produces MemorySSA for a function.
Definition: MemorySSA.h:923
void removeEdge(BasicBlock *From, BasicBlock *To)
Update the MemoryPhi in To following an edge deletion between From and To.
void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
Definition: MemorySSA.cpp:1857
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
The optimization diagnostic interface.
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for applied optimization remarks.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
Value * hasConstantValue() const
If the specified PHI node always merges together the same value, return the value,...
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:172
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:178
This class uses information about analyze scalars to rewrite expressions in canonical form.
This class represents an analyzed expression in the program.
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:345
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:384
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:366
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:451
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
iterator_range< user_iterator > users()
Definition: Value.h:421
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1074
void dump() const
Support for debugging, callable in GDB: V->dump()
Definition: AsmWriter.cpp:5052
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:780
CastOperator_match< OpTy, Instruction::Trunc > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:76
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:445
NodeAddr< PhiNode * > Phi
Definition: RDFGraph.h:390
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
OverflowResult
PHINode * createWideIV(const WideIVInfo &WI, LoopInfo *LI, ScalarEvolution *SE, SCEVExpander &Rewriter, DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, unsigned &NumElimExt, unsigned &NumWidened, bool HasGuards, bool UsePostIncrementRanges)
Widen Induction Variables - Extend the width of an IV to cover its widest uses.
OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
bool isGuaranteedToExecuteForEveryIteration(const Instruction *I, const Loop *L)
Return true if this function can prove that the instruction I is executed for every iteration of the ...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition: MemorySSA.cpp:83
bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition: STLExtras.h:1925
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
Definition: Local.cpp:644
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
Collect information about induction variables that are used by sign/zero extend operations.
PHINode * NarrowIV