LLVM 24.0.0git
LoopInterchange.cpp
Go to the documentation of this file.
1//===- LoopInterchange.cpp - Loop interchange 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 handles loop interchange transform.
10// This pass interchanges loops to provide a more cache-friendly memory access
11// patterns.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/StringMap.h"
21#include "llvm/ADT/StringRef.h"
30#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/Dominators.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/IRBuilder.h"
35#include "llvm/IR/InstrTypes.h"
36#include "llvm/IR/Instruction.h"
38#include "llvm/IR/User.h"
39#include "llvm/IR/Value.h"
40#include "llvm/IR/Verifier.h"
43#include "llvm/Support/Debug.h"
50#include <cassert>
51#include <utility>
52#include <vector>
53
54using namespace llvm;
55
56#define DEBUG_TYPE "loop-interchange"
57
58STATISTIC(LoopsInterchanged, "Number of loops interchanged");
59
61 "loop-interchange-threshold", cl::init(0), cl::Hidden,
62 cl::desc("Interchange if you gain more than this number"));
63
65 "loop-interchange-max-mem-instr-ratio", cl::init(4), cl::Hidden,
66 cl::desc("Maximum number of load/store instructions squared in relation to "
67 "the total number of instructions. Higher value may lead to more "
68 "interchanges at the cost of compile-time"));
69
70namespace {
71
73
74/// A list of direction vectors. Each entry represents a direction vector
75/// corresponding to one or more dependencies existing in the loop nest. The
76/// length of all direction vectors is equal and is N + 1, where N is the depth
77/// of the loop nest. The first N elements correspond to the dependency
78/// direction of each N loops. The last one indicates whether this entry is
79/// forward dependency ('<') or not ('*'). The term "forward" aligns with what
80/// is defined in LoopAccessAnalysis.
81// TODO: Check if we can use a sparse matrix here.
82using CharMatrix = std::vector<std::vector<char>>;
83
84/// Types of rules used in profitability check.
85enum class RuleTy {
86 PerLoopCacheAnalysis,
87 PerInstrOrderCost,
88 ForVectorization,
89 Ignore
90};
91
92} // end anonymous namespace
93
94// Minimum loop depth supported.
96 "loop-interchange-min-loop-nest-depth", cl::init(2), cl::Hidden,
97 cl::desc("Minimum depth of loop nest considered for the transform"));
98
99// Maximum loop depth supported.
101 "loop-interchange-max-loop-nest-depth", cl::init(10), cl::Hidden,
102 cl::desc("Maximum depth of loop nest considered for the transform"));
103
104// We prefer cache cost to vectorization by default.
106 "loop-interchange-profitabilities", cl::MiscFlags::CommaSeparated,
108 cl::desc("List of profitability heuristics to be used. They are applied in "
109 "the given order"),
110 cl::list_init<RuleTy>({RuleTy::PerInstrOrderCost,
111 RuleTy::ForVectorization}),
112 cl::values(clEnumValN(RuleTy::PerLoopCacheAnalysis, "cache",
113 "Prioritize loop cache cost"),
114 clEnumValN(RuleTy::PerInstrOrderCost, "instorder",
115 "Prioritize the IVs order of each instruction"),
116 clEnumValN(RuleTy::ForVectorization, "vectorize",
117 "Prioritize vectorization"),
118 clEnumValN(RuleTy::Ignore, "ignore",
119 "Ignore profitability, force interchange (does not "
120 "work with other options)")));
121
122// Support for the inner-loop reduction pattern.
124 "loop-interchange-reduction-to-mem", cl::init(false), cl::Hidden,
125 cl::desc("Support for the inner-loop reduction pattern."));
126
127#ifndef NDEBUG
130 for (RuleTy Rule : Rules) {
131 if (!Set.insert(Rule).second)
132 return false;
133 if (Rule == RuleTy::Ignore)
134 return false;
135 }
136 return true;
137}
138
139static void printDepMatrix(CharMatrix &DepMatrix) {
140 for (auto &Row : DepMatrix) {
141 // Drop the last element because it is a flag indicating whether this is
142 // forward dependency or not, which doesn't affect the legality check.
143 for (char D : drop_end(Row))
144 LLVM_DEBUG(dbgs() << D << " ");
145 LLVM_DEBUG(dbgs() << "\n");
146 }
147}
148
149/// Return true if \p Src appears before \p Dst in the same basic block.
150/// Precondition: \p Src and \Dst are distinct instructions within the same
151/// basic block.
152static bool inThisOrder(const Instruction *Src, const Instruction *Dst) {
153 assert(Src->getParent() == Dst->getParent() && Src != Dst &&
154 "Expected Src and Dst to be different instructions in the same BB");
155
156 bool FoundSrc = false;
157 for (const Instruction &I : *(Src->getParent())) {
158 if (&I == Src) {
159 FoundSrc = true;
160 continue;
161 }
162 if (&I == Dst)
163 return FoundSrc;
164 }
165
166 llvm_unreachable("Dst not found");
167}
168#endif
169
170static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level,
171 Loop *L, DependenceInfo *DI,
172 ScalarEvolution *SE,
175
176 ValueVector MemInstr;
177 unsigned NumInsts = 0;
178
179 // For each block.
180 for (BasicBlock *BB : L->blocks()) {
181 // Scan the BB and collect legal loads and stores.
182 for (Instruction &I : *BB) {
183 NumInsts++;
184 if (auto *Ld = dyn_cast<LoadInst>(&I)) {
185 if (!Ld->isSimple())
186 return false;
187 MemInstr.push_back(&I);
188 } else if (auto *St = dyn_cast<StoreInst>(&I)) {
189 if (!St->isSimple())
190 return false;
191 MemInstr.push_back(&I);
192 }
193 }
194 }
195
196 // To populate the dependence matrix, we perform dependence test for each pair
197 // of memory instructions, which has O(NumMemInstr^2) complexity. This implies
198 // that even if the number of memory instructions is small, the analysis can
199 // still be expensive if the most of the instructions in the loop are memory
200 // instructions. On the other hand, if the number of memory instructions is
201 // not small, but the loop is large (i.e., it contains many non-memory
202 // instructions), the analysis can still be affordable.
203 unsigned NumMemInstr = MemInstr.size();
204 LLVM_DEBUG(dbgs() << "Found " << NumMemInstr
205 << " Loads and Stores to analyze\n");
206 if (MaxMemInstrRatio * NumInsts < NumMemInstr * NumMemInstr) {
207 ORE->emit([&]() {
208 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedLoop",
209 L->getStartLoc(), L->getHeader())
210 << "Number of loads/stores exceeded, the supported maximum can be "
211 "increased with option -loop-interchange-max-mem-instr-ratio.";
212 });
213 return false;
214 }
215 ValueVector::iterator I, IE, J, JE;
216
217 // Manage direction vectors that are already seen. Map each direction vector
218 // to an index of DepMatrix at which it is stored.
220
221 for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) {
222 for (J = I, JE = MemInstr.end(); J != JE; ++J) {
223 std::vector<char> Dep;
226 // Ignore Input dependencies.
227 if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))
228 continue;
229 // Track Output, Flow, and Anti dependencies.
230 if (auto D = DI->depends(Src, Dst)) {
231 assert(D->isOrdered() && "Expected an output, flow or anti dep.");
232 // If the direction vector is negative, normalize it to
233 // make it non-negative.
234 if (D->normalize(SE))
235 LLVM_DEBUG(dbgs() << "Negative dependence vector normalized.\n");
236 LLVM_DEBUG(StringRef DepType =
237 D->isFlow() ? "flow" : D->isAnti() ? "anti" : "output";
238 dbgs() << "Found " << DepType
239 << " dependency between Src and Dst\n"
240 << " Src:" << *Src << "\n Dst:" << *Dst << '\n');
241 unsigned Levels = D->getLevels();
242 char Direction;
243 for (unsigned II = 1; II <= Levels; ++II) {
244 // `DVEntry::LE` is converted to `*`. This is because `LE` means `<`
245 // or `=`, for which we don't have an equivalent representation, so
246 // that the conservative approximation is necessary. The same goes for
247 // `DVEntry::GE`.
248 // TODO: Use of fine-grained expressions allows for more accurate
249 // analysis.
250 unsigned Dir = D->getDirection(II);
251 if (Dir == Dependence::DVEntry::LT)
252 Direction = '<';
253 else if (Dir == Dependence::DVEntry::GT)
254 Direction = '>';
255 else if (Dir == Dependence::DVEntry::EQ)
256 Direction = '=';
257 else
258 Direction = '*';
259 Dep.push_back(Direction);
260 }
261
262 // If the Dependence object doesn't have any information, fill the
263 // dependency vector with '*'.
264 if (D->isConfused()) {
265 assert(Dep.empty() && "Expected empty dependency vector");
266 Dep.assign(Level, '*');
267 }
268
269 while (Dep.size() != Level) {
270 Dep.push_back('I');
271 }
272
273 // If all the elements of any direction vector have only '*', legality
274 // can't be proven. Exit early to save compile time.
275 if (all_of(Dep, equal_to('*'))) {
276 ORE->emit([&]() {
277 return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence",
278 L->getStartLoc(), L->getHeader())
279 << "All loops have dependencies in all directions.";
280 });
281 return false;
282 }
283
284 // Test whether the dependency is forward or not.
285 bool IsKnownForward = true;
286 if (Src->getParent() != Dst->getParent()) {
287 // In general, when Src and Dst are in different BBs, the execution
288 // order of them within a single iteration is not guaranteed. Treat
289 // conservatively as not-forward dependency in this case.
290 IsKnownForward = false;
291 } else {
292 // Src and Dst are in the same BB. If they are the different
293 // instructions, Src should appear before Dst in the BB as they are
294 // stored to MemInstr in that order.
295 assert((Src == Dst || inThisOrder(Src, Dst)) &&
296 "Unexpected instructions");
297
298 // If the Dependence object is reversed (due to normalization), it
299 // represents the dependency from Dst to Src, meaning it is a backward
300 // dependency. Otherwise it should be a forward dependency.
301 bool IsReversed = D->getSrc() != Src;
302 if (IsReversed)
303 IsKnownForward = false;
304 }
305
306 // Initialize the last element. Assume forward dependencies only; it
307 // will be updated later if there is any non-forward dependency.
308 Dep.push_back('<');
309
310 // The last element should express the "summary" among one or more
311 // direction vectors whose first N elements are the same (where N is
312 // the depth of the loop nest). Hence we exclude the last element from
313 // the Seen map.
314 auto [Ite, Inserted] = Seen.try_emplace(
315 StringRef(Dep.data(), Dep.size() - 1), DepMatrix.size());
316
317 // Make sure we only add unique entries to the dependency matrix.
318 if (Inserted)
319 DepMatrix.push_back(Dep);
320
321 // If we cannot prove that this dependency is forward, change the last
322 // element of the corresponding entry. Since a `[... *]` dependency
323 // includes a `[... <]` dependency, we do not need to keep both and
324 // change the existing entry instead.
325 if (!IsKnownForward)
326 DepMatrix[Ite->second].back() = '*';
327 }
328 }
329 }
330
331 return true;
332}
333
334// A loop is moved from index 'from' to an index 'to'. Update the Dependence
335// matrix by exchanging the two columns.
336static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx,
337 unsigned ToIndx) {
338 for (auto &Row : DepMatrix)
339 std::swap(Row[ToIndx], Row[FromIndx]);
340}
341
342// Check if a direction vector is lexicographically positive. Return true if it
343// is positive, nullopt if it is "zero", otherwise false.
344// [Theorem] A permutation of the loops in a perfect nest is legal if and only
345// if the direction matrix, after the same permutation is applied to its
346// columns, has no ">" direction as the leftmost non-"=" direction in any row.
347static std::optional<bool>
348isLexicographicallyPositive(ArrayRef<char> DV, unsigned Begin, unsigned End) {
349 for (unsigned char Direction : DV.slice(Begin, End - Begin)) {
350 if (Direction == '<')
351 return true;
352 if (Direction == '>' || Direction == '*')
353 return false;
354 }
355 return std::nullopt;
356}
357
358// Checks if it is legal to interchange 2 loops.
359static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix,
360 unsigned InnerLoopId,
361 unsigned OuterLoopId) {
362 unsigned NumRows = DepMatrix.size();
363 std::vector<char> Cur;
364 // For each row check if it is valid to interchange.
365 for (unsigned Row = 0; Row < NumRows; ++Row) {
366 // Create temporary DepVector check its lexicographical order
367 // before and after swapping OuterLoop vs InnerLoop
368 Cur = DepMatrix[Row];
369
370 // If the surrounding loops already ensure that the direction vector is
371 // lexicographically positive, nothing within the loop will be able to break
372 // the dependence. In such a case we can skip the subsequent check.
373 if (isLexicographicallyPositive(Cur, 0, OuterLoopId) == true)
374 continue;
375
376 // Check if the direction vector is lexicographically positive (or zero)
377 // for both before/after exchanged. Ignore the last element because it
378 // doesn't affect the legality.
379 if (isLexicographicallyPositive(Cur, OuterLoopId, Cur.size() - 1) == false)
380 return false;
381 std::swap(Cur[InnerLoopId], Cur[OuterLoopId]);
382 if (isLexicographicallyPositive(Cur, OuterLoopId, Cur.size() - 1) == false)
383 return false;
384 }
385 return true;
386}
387
388static void populateWorklist(Loop &L, LoopVector &LoopList) {
389 LLVM_DEBUG(dbgs() << "Calling populateWorklist on Func: "
390 << L.getHeader()->getParent()->getName() << " Loop: %"
391 << L.getHeader()->getName() << '\n');
392 assert(LoopList.empty() && "LoopList should initially be empty!");
393 Loop *CurrentLoop = &L;
394 const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops();
395 while (!Vec->empty()) {
396 // The current loop has multiple subloops in it hence it is not tightly
397 // nested.
398 // Discard all loops above it added into Worklist.
399 if (Vec->size() != 1) {
400 LoopList = {};
401 return;
402 }
403
404 LoopList.push_back(CurrentLoop);
405 CurrentLoop = Vec->front();
406 Vec = &CurrentLoop->getSubLoops();
407 }
408 LoopList.push_back(CurrentLoop);
409}
410
413 unsigned LoopNestDepth = LoopList.size();
414 if (LoopNestDepth < MinLoopNestDepth || LoopNestDepth > MaxLoopNestDepth) {
415 LLVM_DEBUG(dbgs() << "Unsupported depth of loop nest " << LoopNestDepth
416 << ", the supported range is [" << MinLoopNestDepth
417 << ", " << MaxLoopNestDepth << "].\n");
418 Loop *OuterLoop = LoopList.front();
419 ORE.emit([&]() {
420 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedLoopNestDepth",
421 OuterLoop->getStartLoc(),
422 OuterLoop->getHeader())
423 << "Unsupported depth of loop nest, the supported range is ["
424 << std::to_string(MinLoopNestDepth) << ", "
425 << std::to_string(MaxLoopNestDepth) << "].\n";
426 });
427 return false;
428 }
429 return true;
430}
431
433 ArrayRef<Loop *> LoopList) {
434 for (Loop *L : LoopList) {
435 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L);
436 if (isa<SCEVCouldNotCompute>(ExitCountOuter)) {
437 LLVM_DEBUG(dbgs() << "Couldn't compute backedge count\n");
438 return false;
439 }
440 if (L->getNumBackEdges() != 1) {
441 LLVM_DEBUG(dbgs() << "NumBackEdges is not equal to 1\n");
442 return false;
443 }
444 if (!L->getExitingBlock()) {
445 LLVM_DEBUG(dbgs() << "Loop doesn't have unique exit block\n");
446 return false;
447 }
448 }
449 return true;
450}
451
452namespace {
453
454/// LoopInterchangeLegality checks if it is legal to interchange the loop.
455class LoopInterchangeLegality {
456public:
457 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
458 OptimizationRemarkEmitter *ORE, DominatorTree *DT)
459 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), DT(DT), ORE(ORE) {}
460
461 /// Check if the loops can be interchanged.
462 bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId,
463 CharMatrix &DepMatrix);
464
465 /// Check if the loop structure is understood. We do not handle triangular
466 /// loops for now.
467 bool isLoopStructureUnderstood();
468
469 bool currentLimitations();
470
471 const SmallPtrSetImpl<PHINode *> &getOuterInnerReductions() const {
472 return OuterInnerReductions;
473 }
474
475 const ArrayRef<PHINode *> getInnerLoopInductions() const {
476 return InnerLoopInductions;
477 }
478
479 ArrayRef<Instruction *> getHasNoWrapReductions() const {
480 return HasNoWrapReductions;
481 }
482
483 ArrayRef<Instruction *> getHasNoInfInsts() const { return HasNoInfInsts; }
484
485 /// Record reductions in the inner loop. Currently supported reductions:
486 /// - initialized from a constant.
487 /// - reduction PHI node has only one user.
488 /// - located in the innermost loop.
489 struct InnerReduction {
490 /// The reduction itself.
491 PHINode *Reduction;
492 Value *Init;
493 Value *Next;
494 /// The Lcssa PHI.
495 PHINode *LcssaPhi;
496 /// Store reduction result into memory object.
497 StoreInst *LcssaStore;
498 /// The memory Location.
499 Value *MemRef;
500 Type *ElemTy;
501 };
502
503 ArrayRef<InnerReduction> getInnerReductions() const {
504 return InnerReductions;
505 }
506
507private:
508 bool tightlyNested(Loop *Outer, Loop *Inner);
509 bool containsUnsafeInstructions(BasicBlock *BB, Instruction *Skip);
510
511 /// Traverse all PHI nodes in the header of each loop in the loop nest
512 /// starting from \p OuterLoop, and perform the following checks:
513 ///
514 /// - Identify induction variables in the child loop of \p OuterLoop.
515 /// - Check for reductions across the inner loop and \p OuterLoop.
516 /// - Detect unsupported PHI nodes.
517 ///
518 /// Return false if any unsupported PHI node is found or if no induction
519 /// variable is found in the child loop of \p OuterLoop. Otherwise return
520 /// true.
521 bool checkInductionsAndReductions(Loop *OuterLoop);
522
523 /// Detect and record the reduction of the inner loop. Add them to
524 /// InnerReductions.
525 ///
526 /// innerloop:
527 /// Re = phi<0.0, Next>
528 /// Next = Re op ...
529 /// OuterLoopLatch:
530 /// Lcssa = phi<Next> ; lcssa phi
531 /// store Lcssa, MemRef ; LcssaStore
532 ///
533 bool isInnerReduction(Loop *L, PHINode *Phi,
534 SmallVectorImpl<Instruction *> &HasNoWrapInsts);
535
536 Loop *OuterLoop;
537 Loop *InnerLoop;
538
539 ScalarEvolution *SE;
540 DominatorTree *DT;
541
542 /// Interface to emit optimization remarks.
543 OptimizationRemarkEmitter *ORE;
544
545 /// Set of reduction PHIs taking part of a reduction across the inner and
546 /// outer loop.
547 SmallPtrSet<PHINode *, 4> OuterInnerReductions;
548
549 /// Set of inner loop induction PHIs
550 SmallVector<PHINode *, 8> InnerLoopInductions;
551
552 /// Hold instructions that have nuw/nsw flags and involved in reductions,
553 /// like integer addition/multiplication. Those flags must be dropped when
554 /// interchanging the loops.
555 SmallVector<Instruction *, 4> HasNoWrapReductions;
556
557 /// Hold instructions that have ninf flags and involved in reductions. Those
558 /// flags must be dropped when interchanging the loops.
559 SmallVector<Instruction *, 4> HasNoInfInsts;
560
561 /// Vector of reductions in the inner loop.
562 SmallVector<InnerReduction, 8> InnerReductions;
563};
564
565/// Manages information utilized by the profitability check for cache. The main
566/// purpose of this class is to delay the computation of CacheCost until it is
567/// actually needed.
568class CacheCostManager {
569 Loop *OutermostLoop;
570 LoopStandardAnalysisResults *AR;
571 DependenceInfo *DI;
572
573 /// CacheCost for \ref OutermostLoop. Once it is computed, it is cached. Note
574 /// that the result can be nullptr.
575 std::optional<std::unique_ptr<CacheCost>> CC;
576
577 /// Maps each loop to an index representing the optimal position within the
578 /// loop-nest, as determined by the cache cost analysis.
579 DenseMap<const Loop *, unsigned> CostMap;
580
581 void computeIfUnitinialized();
582
583public:
584 CacheCostManager(Loop *OutermostLoop, LoopStandardAnalysisResults *AR,
585 DependenceInfo *DI)
586 : OutermostLoop(OutermostLoop), AR(AR), DI(DI) {}
587 CacheCost *getCacheCost();
588 const DenseMap<const Loop *, unsigned> &getCostMap();
589};
590
591/// LoopInterchangeProfitability checks if it is profitable to interchange the
592/// loop.
593class LoopInterchangeProfitability {
594public:
595 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
596 OptimizationRemarkEmitter *ORE)
597 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
598
599 /// Check if the loop interchange is profitable.
600 bool isProfitable(const Loop *InnerLoop, const Loop *OuterLoop,
601 unsigned InnerLoopId, unsigned OuterLoopId,
602 CharMatrix &DepMatrix, CacheCostManager &CCM);
603
604private:
605 int getInstrOrderCost();
606 std::optional<bool> isProfitablePerLoopCacheAnalysis(
607 const DenseMap<const Loop *, unsigned> &CostMap, CacheCost *CC);
608 std::optional<bool> isProfitablePerInstrOrderCost();
609 std::optional<bool> isProfitableForVectorization(unsigned InnerLoopId,
610 unsigned OuterLoopId,
611 CharMatrix &DepMatrix);
612 Loop *OuterLoop;
613 Loop *InnerLoop;
614
615 /// Scev analysis.
616 ScalarEvolution *SE;
617
618 /// Interface to emit optimization remarks.
619 OptimizationRemarkEmitter *ORE;
620};
621
622/// LoopInterchangeTransform interchanges the loop.
623class LoopInterchangeTransform {
624public:
625 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
626 LoopInfo *LI, DominatorTree *DT,
627 const LoopInterchangeLegality &LIL)
628 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), LIL(LIL) {}
629
630 /// Interchange OuterLoop and InnerLoop.
631 void transform(ArrayRef<Instruction *> DropNoWrapInsts,
632 ArrayRef<Instruction *> DropNoInfInsts);
633 void reduction2Memory();
634 void restructureLoops(Loop *NewInner, Loop *NewOuter,
635 BasicBlock *OrigInnerPreHeader,
636 BasicBlock *OrigOuterPreHeader);
637 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop);
638
639private:
640 void adjustLoopBranches();
641
642 Loop *OuterLoop;
643 Loop *InnerLoop;
644
645 /// Scev analysis.
646 ScalarEvolution *SE;
647
648 LoopInfo *LI;
649 DominatorTree *DT;
650
651 const LoopInterchangeLegality &LIL;
652};
653
654struct LoopInterchange {
655 ScalarEvolution *SE = nullptr;
656 LoopInfo *LI = nullptr;
657 DependenceInfo *DI = nullptr;
658 DominatorTree *DT = nullptr;
659 LoopStandardAnalysisResults *AR = nullptr;
660
661 /// Interface to emit optimization remarks.
662 OptimizationRemarkEmitter *ORE;
663
664 LoopInterchange(ScalarEvolution *SE, LoopInfo *LI, DependenceInfo *DI,
665 DominatorTree *DT, LoopStandardAnalysisResults *AR,
666 OptimizationRemarkEmitter *ORE)
667 : SE(SE), LI(LI), DI(DI), DT(DT), AR(AR), ORE(ORE) {}
668
669 bool run(Loop *L) {
670 if (L->getParentLoop())
671 return false;
672 SmallVector<Loop *, 8> LoopList;
673 populateWorklist(*L, LoopList);
674 return processLoopList(LoopList);
675 }
676
677 bool run(LoopNest &LN) {
678 SmallVector<Loop *, 8> LoopList(LN.getLoops());
679 for (unsigned I = 1; I < LoopList.size(); ++I)
680 if (LoopList[I]->getParentLoop() != LoopList[I - 1])
681 return false;
682 return processLoopList(LoopList);
683 }
684
685 unsigned selectLoopForInterchange(ArrayRef<Loop *> LoopList) {
686 // TODO: Add a better heuristic to select the loop to be interchanged based
687 // on the dependence matrix. Currently we select the innermost loop.
688 return LoopList.size() - 1;
689 }
690
691 bool processLoopList(SmallVectorImpl<Loop *> &LoopList) {
692 bool Changed = false;
693
694 // Ensure proper loop nest depth.
695 assert(hasSupportedLoopDepth(LoopList, *ORE) &&
696 "Unsupported depth of loop nest.");
697
698 unsigned LoopNestDepth = LoopList.size();
699
700 LLVM_DEBUG({
701 dbgs() << "Processing LoopList of size = " << LoopNestDepth
702 << " containing the following loops:\n";
703 for (auto *L : LoopList) {
704 dbgs() << " - ";
705 L->print(dbgs());
706 }
707 });
708
709 CharMatrix DependencyMatrix;
710 Loop *OuterMostLoop = *(LoopList.begin());
711 if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth,
712 OuterMostLoop, DI, SE, ORE)) {
713 LLVM_DEBUG(dbgs() << "Populating dependency matrix failed\n");
714 return false;
715 }
716
717 LLVM_DEBUG(dbgs() << "Dependency matrix before interchange:\n";
718 printDepMatrix(DependencyMatrix));
719
720 // Get the Outermost loop exit.
721 BasicBlock *LoopNestExit = OuterMostLoop->getExitBlock();
722 if (!LoopNestExit) {
723 LLVM_DEBUG(dbgs() << "OuterMostLoop '" << OuterMostLoop->getName()
724 << "' needs an unique exit block");
725 return false;
726 }
727
728 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
729 CacheCostManager CCM(LoopList[0], AR, DI);
730 // We try to achieve the globally optimal memory access for the loopnest,
731 // and do interchange based on a bubble-sort fasion. We start from
732 // the innermost loop, move it outwards to the best possible position
733 // and repeat this process.
734 for (unsigned j = SelecLoopId; j > 0; j--) {
735 bool ChangedPerIter = false;
736 for (unsigned i = SelecLoopId; i > SelecLoopId - j; i--) {
737 bool Interchanged =
738 processLoop(LoopList, i, i - 1, DependencyMatrix, CCM);
739 ChangedPerIter |= Interchanged;
740 Changed |= Interchanged;
741 }
742 // Early abort if there was no interchange during an entire round of
743 // moving loops outwards.
744 if (!ChangedPerIter)
745 break;
746 }
747 return Changed;
748 }
749
750 bool processLoop(SmallVectorImpl<Loop *> &LoopList, unsigned InnerLoopId,
751 unsigned OuterLoopId,
752 std::vector<std::vector<char>> &DependencyMatrix,
753 CacheCostManager &CCM) {
754 Loop *OuterLoop = LoopList[OuterLoopId];
755 Loop *InnerLoop = LoopList[InnerLoopId];
756 LLVM_DEBUG(dbgs() << "Processing InnerLoopId = " << InnerLoopId
757 << " and OuterLoopId = " << OuterLoopId << "\n");
758 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, ORE, DT);
759 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
760 LLVM_DEBUG(dbgs() << "Cannot prove legality, not interchanging loops '"
761 << OuterLoop->getName() << "' and '"
762 << InnerLoop->getName() << "'\n");
763 return false;
764 }
765 LLVM_DEBUG(dbgs() << "Loops '" << OuterLoop->getName() << "' and '"
766 << InnerLoop->getName()
767 << "' are legal to interchange\n");
768 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE);
769 if (!LIP.isProfitable(InnerLoop, OuterLoop, InnerLoopId, OuterLoopId,
770 DependencyMatrix, CCM)) {
771 LLVM_DEBUG(dbgs() << "Interchanging loops '" << OuterLoop->getName()
772 << "' and '" << InnerLoop->getName()
773 << "' not profitable.\n");
774 return false;
775 }
776
777 ORE->emit([&]() {
778 return OptimizationRemark(DEBUG_TYPE, "Interchanged",
779 InnerLoop->getStartLoc(),
780 InnerLoop->getHeader())
781 << "Loop interchanged with enclosing loop.";
782 });
783
784 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, LIL);
785 LIT.transform(LIL.getHasNoWrapReductions(), LIL.getHasNoInfInsts());
786 LLVM_DEBUG(dbgs() << "Loops interchanged: outer loop '"
787 << OuterLoop->getName() << "' and inner loop '"
788 << InnerLoop->getName() << "'\n");
789 LoopsInterchanged++;
790
791 llvm::formLCSSARecursively(*OuterLoop, *DT, LI, SE);
792
793 // Loops interchanged, update LoopList accordingly.
794 std::swap(LoopList[OuterLoopId], LoopList[InnerLoopId]);
795 // Update the DependencyMatrix
796 interChangeDependencies(DependencyMatrix, InnerLoopId, OuterLoopId);
797
798 LLVM_DEBUG(dbgs() << "Dependency matrix after interchange:\n";
799 printDepMatrix(DependencyMatrix));
800
801 return true;
802 }
803};
804
805} // end anonymous namespace
806
807bool LoopInterchangeLegality::containsUnsafeInstructions(BasicBlock *BB,
808 Instruction *Skip) {
809 return any_of(*BB, [Skip](const Instruction &I) {
810 if (&I == Skip)
811 return false;
812 return I.mayHaveSideEffects() || I.mayReadFromMemory();
813 });
814}
815
817 Loop *InnerLoop) {
818 // adjustLoopBranches swaps the preheader bodies after changing their loop
819 // roles, so the original outer-preheader body remains outside the new outer
820 // loop and retains its execution count.
821 BasicBlock *Blocks[] = {
822 OuterLoop->getHeader(),
823 OuterLoop->getLoopLatch(),
824 InnerLoop->getLoopPreheader(),
825 InnerLoop->getExitBlock(),
826 };
827 for (BasicBlock *BB : Blocks)
828 if (BB)
829 for (Instruction &I : *BB)
830 if (auto *Freeze = dyn_cast<FreezeInst>(&I))
831 return Freeze;
832 return nullptr;
833}
834
835static FreezeInst *
837 ArrayRef<PHINode *> InnerLoopInductions) {
838 // Mirror the latch-condition and induction-update operand closure cloned by
839 // MoveInstructions in LoopInterchangeTransform::transform.
841 auto IsDirectInnerLoopBlock = [InnerLoop](BasicBlock *BB) {
842 return InnerLoop->contains(BB) &&
843 none_of(InnerLoop->getSubLoops(),
844 [BB](Loop *SubLoop) { return SubLoop->contains(BB); });
845 };
846 auto *LatchBranch =
848 if (LatchBranch)
849 if (auto *Condition = dyn_cast<Instruction>(LatchBranch->getCondition()))
850 Worklist.insert(Condition);
851
852 for (PHINode *Induction : InnerLoopInductions) {
853 auto *Incoming = dyn_cast<Instruction>(
854 Induction->getIncomingValueForBlock(InnerLoop->getLoopLatch()));
855 if (Incoming && !is_contained(InnerLoopInductions, Incoming))
856 Worklist.insert(Incoming);
857 }
858
859 for (unsigned I = 0; I < Worklist.size(); ++I) {
860 Instruction *Current = Worklist[I];
861 if (auto *Freeze = dyn_cast<FreezeInst>(Current))
862 return Freeze;
863 for (Value *Operand : Current->operands()) {
864 auto *OperandI = dyn_cast<Instruction>(Operand);
865 if (!OperandI || !IsDirectInnerLoopBlock(OperandI->getParent()) ||
866 is_contained(InnerLoopInductions, OperandI))
867 continue;
868 Worklist.insert(OperandI);
869 }
870 }
871 return nullptr;
872}
873
874bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
875 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
876 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
877 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
878
879 LLVM_DEBUG(dbgs() << "Checking if loops '" << OuterLoop->getName()
880 << "' and '" << InnerLoop->getName()
881 << "' are tightly nested\n");
882
883 // In a perfectly nested loop the outer header branches only into the inner
884 // loop. If it can also reach the outer latch, it conditionally guards the
885 // inner loop (an imperfect nest), so the inner loop runs on only a subset of
886 // the outer iterations. Interchanging such a nest would run the inner loop on
887 // every outer iteration, including the guarded-off ones, which is illegal
888 // when the inner loop relies on the guard to terminate (e.g. an eq/ne exit
889 // whose trip count is degenerate once the guard is false). Reject by allowing
890 // the outer header to branch only into the inner loop.
891 //
892 // TODO: This is conservative. A guarded nest is still safe to interchange
893 // when the inner loop has a computable trip count that is empty exactly when
894 // the guard is false, e.g.:
895 // for (i = 0; i < N; i++)
896 // if (M > 0) // loop-invariant guard
897 // for (j = 0; j < M; j++) // empty when M <= 0
898 // A[j][i] = ...;
899 // Interchanging is legal here because the inner loop runs zero times on the
900 // guarded-off iterations.
901 for (BasicBlock *Succ : successors(OuterLoopHeader))
902 if (Succ != InnerLoopPreHeader && Succ != InnerLoop->getHeader())
903 return false;
904
905 LLVM_DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n");
906
907 // The inner loop reduction pattern requires storing the LCSSA PHI in
908 // the OuterLoop Latch. Therefore, when reduction2Memory is enabled, skip
909 // that store during checks.
910 Instruction *Skip = nullptr;
911 assert(InnerReductions.size() <= 1 &&
912 "So far we only support at most one reduction.");
913 if (InnerReductions.size() == 1)
914 Skip = InnerReductions[0].LcssaStore;
915
916 // We do not have any basic block in between now make sure the outer header
917 // and outer loop latch doesn't contain any unsafe instructions.
918 if (containsUnsafeInstructions(OuterLoopHeader, Skip) ||
919 containsUnsafeInstructions(OuterLoopLatch, Skip))
920 return false;
921
922 // Also make sure the inner loop preheader does not contain any unsafe
923 // instructions. Note that all instructions in the preheader will be moved to
924 // the outer loop header when interchanging.
925 if (InnerLoopPreHeader != OuterLoopHeader &&
926 containsUnsafeInstructions(InnerLoopPreHeader, Skip))
927 return false;
928
929 BasicBlock *InnerLoopExit = InnerLoop->getExitBlock();
930 // Ensure the inner loop exit block flows to the outer loop latch possibly
931 // through empty blocks.
932 const BasicBlock &SuccInner =
933 LoopNest::skipEmptyBlockUntil(InnerLoopExit, OuterLoopLatch);
934 if (&SuccInner != OuterLoopLatch) {
935 LLVM_DEBUG(dbgs() << "Inner loop exit block " << *InnerLoopExit
936 << " does not lead to the outer loop latch.\n";);
937 return false;
938 }
939 // The inner loop exit block does flow to the outer loop latch and not some
940 // other BBs, now make sure it contains safe instructions, since it will be
941 // moved into the (new) inner loop after interchange.
942 if (containsUnsafeInstructions(InnerLoopExit, Skip))
943 return false;
944
945 LLVM_DEBUG(dbgs() << "Loops are perfectly nested\n");
946 // We have a perfect loop nest.
947 return true;
948}
949
950bool LoopInterchangeLegality::isLoopStructureUnderstood() {
951 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
952 for (PHINode *InnerInduction : InnerLoopInductions) {
953 unsigned Num = InnerInduction->getNumOperands();
954 for (unsigned i = 0; i < Num; ++i) {
955 Value *Val = InnerInduction->getOperand(i);
956 if (isa<Constant>(Val))
957 continue;
959 if (!I)
960 return false;
961 // TODO: Handle triangular loops.
962 // e.g. for(int i=0;i<N;i++)
963 // for(int j=i;j<N;j++)
964 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i);
965 if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
966 InnerLoopPreheader &&
967 !OuterLoop->isLoopInvariant(I)) {
968 return false;
969 }
970 }
971 }
972
973 // TODO: Handle triangular loops of another form.
974 // e.g. for(int i=0;i<N;i++)
975 // for(int j=0;j<i;j++)
976 // or,
977 // for(int i=0;i<N;i++)
978 // for(int j=0;j*i<N;j++)
979 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
980 CondBrInst *InnerLoopLatchBI =
981 dyn_cast<CondBrInst>(InnerLoopLatch->getTerminator());
982 if (!InnerLoopLatchBI)
983 return false;
984
985 CmpInst *InnerLoopCmp = dyn_cast<CmpInst>(InnerLoopLatchBI->getCondition());
986 if (!InnerLoopCmp)
987 return false;
988
989 Value *Op0 = InnerLoopCmp->getOperand(0);
990 Value *Op1 = InnerLoopCmp->getOperand(1);
991
992 // LHS and RHS of the inner loop exit condition, e.g.,
993 // in "for(int j=0;j<i;j++)", LHS is j and RHS is i.
994 Value *Left = nullptr;
995 Value *Right = nullptr;
996
997 // Check if V only involves inner loop induction variable.
998 // Return true if V is InnerInduction, or a cast from
999 // InnerInduction, or a binary operator that involves
1000 // InnerInduction and a constant.
1001 std::function<bool(Value *)> IsPathToInnerIndVar;
1002 IsPathToInnerIndVar = [this, &IsPathToInnerIndVar](const Value *V) -> bool {
1003 if (llvm::is_contained(InnerLoopInductions, V))
1004 return true;
1005 if (isa<Constant>(V))
1006 return true;
1008 if (!I)
1009 return false;
1010 if (isa<CastInst>(I))
1011 return IsPathToInnerIndVar(I->getOperand(0));
1013 return IsPathToInnerIndVar(I->getOperand(0)) &&
1014 IsPathToInnerIndVar(I->getOperand(1));
1015 return false;
1016 };
1017
1018 // In case of multiple inner loop indvars, it is okay if LHS and RHS
1019 // are both inner indvar related variables.
1020 if (IsPathToInnerIndVar(Op0) && IsPathToInnerIndVar(Op1))
1021 return true;
1022
1023 // Otherwise we check if the cmp instruction compares an inner indvar
1024 // related variable (Left) with a outer loop invariant (Right).
1025 if (IsPathToInnerIndVar(Op0) && !isa<Constant>(Op0)) {
1026 Left = Op0;
1027 Right = Op1;
1028 } else if (IsPathToInnerIndVar(Op1) && !isa<Constant>(Op1)) {
1029 Left = Op1;
1030 Right = Op0;
1031 }
1032
1033 if (Left == nullptr)
1034 return false;
1035
1036 const SCEV *S = SE->getSCEV(Right);
1037 if (!SE->isLoopInvariant(S, OuterLoop))
1038 return false;
1039
1040 return true;
1041}
1042
1043// If SV is a LCSSA PHI node with a single incoming value, return the incoming
1044// value.
1047 if (!PHI)
1048 return SV;
1049
1050 if (PHI->getNumIncomingValues() != 1)
1051 return SV;
1052 return followLCSSA(PHI->getIncomingValue(0));
1053}
1054
1056 SmallVectorImpl<Instruction *> &HasNoWrapInsts,
1057 SmallVectorImpl<Instruction *> &HasNoInfInsts) {
1060 // Detect floating point reduction only when it can be reordered.
1061 if (RD.getExactFPMathInst() != nullptr)
1062 return false;
1063
1064 // The extra uses of a reduction phi outside of its reduction chain make
1065 // the order in which the elements are visited observable.
1067 return false;
1068
1069 RecurKind RK = RD.getRecurrenceKind();
1070 switch (RK) {
1071 case RecurKind::Or:
1072 case RecurKind::And:
1073 case RecurKind::Xor:
1074 case RecurKind::SMin:
1075 case RecurKind::SMax:
1076 case RecurKind::UMin:
1077 case RecurKind::UMax:
1078 return true;
1079
1080 // Interchanging the loops that contain AnyOf reduction is not always legal.
1081 // Especially, when the result value of the AnyOf is not loop-invariant with
1082 // respect to the outer loop, interchanging may change the semantics. The
1083 // following is an example of such case:
1084 // int A = {{ 1, 0 }, { 0, 1 }};
1085 // int red = 0;
1086 // for (int i = 0; i < 2; i++)
1087 // for (int j = 0; j < 2; j++)
1088 // red = (A[j][i] == 0) ? i + 1 : red;
1089 //
1090 // TODO: We may be able to support interchanging loops with AnyOf reduction
1091 // by checking the operand of the reduction is loop-invariant with respect
1092 // to the outer loop as well.
1093 case RecurKind::AnyOf:
1094 return false;
1095
1096 // Changing the order of floating-point operations may alter the results. If
1097 // a certain instruction has the ninf flag, it means that reordering can
1098 // produce a poison value, which may lead to undefined behavior. To prevent
1099 // this, we must drop the ninf flags if we decide to apply the
1100 // transformation.
1101 case RecurKind::FAdd:
1102 case RecurKind::FMul:
1103 case RecurKind::FMin:
1104 case RecurKind::FMax:
1109 case RecurKind::FMulAdd:
1110 for (Instruction *I : RD.getReductionOpChain(PHI, L))
1111 if (isa<FPMathOperator>(I) && I->hasNoInfs())
1112 HasNoInfInsts.push_back(I);
1113 return true;
1114
1115 // Change the order of integer addition/multiplication may change the
1116 // semantics. Consider the following case:
1117 //
1118 // int A[2][2] = {{ INT_MAX, INT_MAX }, { INT_MIN, INT_MIN }};
1119 // int sum = 0;
1120 // for (int i = 0; i < 2; i++)
1121 // for (int j = 0; j < 2; j++)
1122 // sum += A[j][i];
1123 //
1124 // If the above loops are exchanged, the addition will cause an
1125 // overflow. To prevent this, we must drop the nuw/nsw flags from the
1126 // addition/multiplication instructions when we actually exchanges the
1127 // loops.
1128 case RecurKind::Add:
1129 case RecurKind::Mul: {
1130 unsigned OpCode = RecurrenceDescriptor::getOpcode(RK);
1132
1133 // Bail out when we fail to collect reduction instructions chain.
1134 if (Ops.empty())
1135 return false;
1136
1137 for (Instruction *I : Ops) {
1138 assert(I->getOpcode() == OpCode &&
1139 "Expected the instruction to be the reduction operation");
1140 (void)OpCode;
1141
1142 // If the instruction has nuw/nsw flags, we must drop them when the
1143 // transformation is actually performed.
1144 if (I->hasNoSignedWrap() || I->hasNoUnsignedWrap())
1145 HasNoWrapInsts.push_back(I);
1146 }
1147 return true;
1148 }
1149
1150 default:
1151 return false;
1152 }
1153 } else
1154 return false;
1155}
1156
1157// Check V's users to see if it is involved in a reduction in L.
1158static PHINode *
1160 SmallVectorImpl<Instruction *> &HasNoWrapInsts,
1161 SmallVectorImpl<Instruction *> &HasNoInfInsts) {
1162 // Reduction variables cannot be constants.
1163 if (isa<Constant>(V))
1164 return nullptr;
1165
1166 for (Value *User : V->users()) {
1168 if (PHI->getNumIncomingValues() == 1)
1169 continue;
1170
1171 if (checkReductionKind(L, PHI, HasNoWrapInsts, HasNoInfInsts))
1172 return PHI;
1173 else
1174 return nullptr;
1175 }
1176 }
1177
1178 return nullptr;
1179}
1180
1181bool LoopInterchangeLegality::isInnerReduction(
1182 Loop *L, PHINode *Phi, SmallVectorImpl<Instruction *> &HasNoWrapInsts) {
1183
1184 // Only support reduction2Mem when the loop nest to be interchanged is
1185 // the innermost two loops.
1186 if (!L->isInnermost()) {
1187 LLVM_DEBUG(dbgs() << "Only supported when the loop is the innermost.\n");
1188 ORE->emit([&]() {
1189 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedInnerReduction",
1190 L->getStartLoc(), L->getHeader())
1191 << "Only supported when the loop is the innermost.";
1192 });
1193 return false;
1194 }
1195
1196 if (Phi->getNumIncomingValues() != 2)
1197 return false;
1198
1199 Value *Init = Phi->getIncomingValueForBlock(L->getLoopPreheader());
1200 Value *Next = Phi->getIncomingValueForBlock(L->getLoopLatch());
1201
1202 // So far only supports constant initial value.
1203 if (!isa<Constant>(Init)) {
1204 LLVM_DEBUG(
1205 dbgs()
1206 << "Only supported for the reduction with a constant initial value.\n");
1207 ORE->emit([&]() {
1208 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedInnerReduction",
1209 L->getStartLoc(), L->getHeader())
1210 << "Only supported for the reduction with a constant initial "
1211 "value.";
1212 });
1213 return false;
1214 }
1215
1216 // The reduction result must live in the inner loop.
1217 if (Instruction *I = dyn_cast<Instruction>(Next)) {
1218 BasicBlock *BB = I->getParent();
1219 if (!L->contains(BB))
1220 return false;
1221 }
1222
1223 // The reduction should have only one user.
1224 if (!Phi->hasOneUser())
1225 return false;
1226
1227 // Check the reduction kind.
1228 if (!checkReductionKind(L, Phi, HasNoWrapInsts, HasNoInfInsts))
1229 return false;
1230
1231 // Find lcssa_phi in OuterLoop's Latch
1232 BasicBlock *ExitBlock = L->getExitBlock();
1233 if (!ExitBlock)
1234 return false;
1235
1236 PHINode *Lcssa = NULL;
1237 for (auto *U : Next->users()) {
1238 if (auto *P = dyn_cast<PHINode>(U)) {
1239 if (P == Phi)
1240 continue;
1241
1242 if (Lcssa == NULL && P->getParent() == ExitBlock &&
1243 P->getIncomingValueForBlock(L->getLoopLatch()) == Next)
1244 Lcssa = P;
1245 else
1246 return false;
1247 } else
1248 return false;
1249 }
1250 if (!Lcssa)
1251 return false;
1252
1253 if (!Lcssa->hasOneUser()) {
1254 LLVM_DEBUG(dbgs() << "Only supported when the reduction is used once in "
1255 "the outer loop.\n");
1256 ORE->emit([&]() {
1257 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedInnerReduction",
1258 L->getStartLoc(), L->getHeader())
1259 << "Only supported when the reduction is used once in the outer "
1260 "loop.";
1261 });
1262 return false;
1263 }
1264
1265 StoreInst *LcssaStore =
1267 if (!LcssaStore || LcssaStore->getParent() != ExitBlock)
1268 return false;
1269
1270 Value *MemRef = LcssaStore->getOperand(1);
1271 Type *ElemTy = LcssaStore->getOperand(0)->getType();
1272
1273 // LcssaStore stores the reduction result in BB.
1274 // When the reduction is initialized from a constant value, we need to load
1275 // from the memory object into the target basic block of the inner loop. This
1276 // means the memory reference was used prematurely. So we must ensure that the
1277 // memory reference does not dominate the target basic block.
1278 // TODO: Move the memory reference definition into the loop header.
1279 if (!DT->dominates(dyn_cast<Instruction>(MemRef), L->getHeader())) {
1280 LLVM_DEBUG(dbgs() << "Only supported when memory reference dominate "
1281 "the inner loop.\n");
1282 ORE->emit([&]() {
1283 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedInnerReduction",
1284 L->getStartLoc(), L->getHeader())
1285 << "Only supported when memory reference dominate the inner "
1286 "loop.";
1287 });
1288 return false;
1289 }
1290
1291 // Found a reduction in the inner loop.
1292 InnerReduction SR;
1293 SR.Reduction = Phi;
1294 SR.Init = Init;
1295 SR.Next = Next;
1296 SR.LcssaPhi = Lcssa;
1297 SR.LcssaStore = LcssaStore;
1298 SR.MemRef = MemRef;
1299 SR.ElemTy = ElemTy;
1300
1301 InnerReductions.push_back(SR);
1302 return true;
1303}
1304
1305bool LoopInterchangeLegality::checkInductionsAndReductions(Loop *OuterLoop) {
1306 auto ChildLoop = [](Loop *L) {
1307 assert(L->getSubLoops().size() <= 1 &&
1308 "Expect at most one child loop for now.");
1309 return L->getSubLoops().empty() ? nullptr : L->getSubLoops().front();
1310 };
1311
1312 Loop *InnerLoop = ChildLoop(OuterLoop);
1313 for (Loop *CurLoop = OuterLoop; CurLoop; CurLoop = ChildLoop(CurLoop)) {
1314 for (PHINode &PHI : CurLoop->getHeader()->phis()) {
1315 InductionDescriptor ID;
1316 if (InductionDescriptor::isInductionPHI(&PHI, CurLoop, SE, ID)) {
1317 if (CurLoop == InnerLoop) {
1318 const SCEV *Step = ID.getStep();
1319 if (!SE->isLoopInvariant(Step, OuterLoop))
1320 return false;
1321 InnerLoopInductions.push_back(&PHI);
1322 }
1323 continue;
1324 }
1325
1326 if (CurLoop == OuterLoop) {
1327 // PHIs in inner loops need to be part of a reduction in the outer loop,
1328 if (PHI.getNumIncomingValues() != 2) {
1329 LLVM_DEBUG(dbgs() << "Only PHI nodes in the outer loop header with 2 "
1330 "incoming values are supported.\n");
1331 return false;
1332 }
1333 // Check if we have a PHI node in the outer loop that has a reduction
1334 // result from the inner loop as an incoming value.
1335 Value *V = followLCSSA(
1336 PHI.getIncomingValueForBlock(OuterLoop->getLoopLatch()));
1337 PHINode *InnerRedPhi = findInnerReductionPhi(
1338 InnerLoop, V, HasNoWrapReductions, HasNoInfInsts);
1339
1340 // Reject if PHI has users other than InnerRedPhi. The typical case is
1341 // as follows:
1342 //
1343 // o.header:
1344 // %red.o = phi [ 0, ... ], [ %red.next, %o.latch ]
1345 // br label %i.header
1346 //
1347 // i.header:
1348 // %red.i = phi [ %red.o, %o.header ], [ %red.next, %i.latch ]
1349 // br label %i.body
1350 //
1351 // i.body:
1352 // store %red.o to %mem
1353 // ...
1354 //
1355 if (!InnerRedPhi ||
1356 !llvm::is_contained(InnerRedPhi->incoming_values(), &PHI) ||
1357 !all_of(PHI.users(),
1358 [InnerRedPhi](User *U) { return U == InnerRedPhi; })) {
1359 LLVM_DEBUG(
1360 dbgs()
1361 << "Failed to recognize PHI as an induction or reduction.\n");
1362 ORE->emit([&]() {
1363 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIOuter",
1364 OuterLoop->getStartLoc(),
1365 OuterLoop->getHeader())
1366 << "Only outer loops with induction or reduction PHI nodes "
1367 "can be interchanged currently.";
1368 });
1369 return false;
1370 }
1371
1372 OuterInnerReductions.insert(&PHI);
1373 OuterInnerReductions.insert(InnerRedPhi);
1374 } else {
1375 if (OuterInnerReductions.count(&PHI)) {
1376 LLVM_DEBUG(dbgs() << "Found a reduction across the outer loop.\n");
1377 } else if (EnableReduction2Memory &&
1378 isInnerReduction(CurLoop, &PHI, HasNoWrapReductions)) {
1379 LLVM_DEBUG(dbgs() << "Found a reduction in the inner loop: \n"
1380 << PHI << '\n');
1381 } else {
1382 ORE->emit([&]() {
1383 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIInner",
1384 CurLoop->getStartLoc(),
1385 CurLoop->getHeader())
1386 << "Only inner loops with induction or reduction PHI nodes "
1387 "can be interchanged currently.";
1388 });
1389 return false;
1390 }
1391 }
1392 }
1393
1394 // For now we only support at most one reduction.
1395 if (InnerReductions.size() > 1) {
1396 LLVM_DEBUG(dbgs() << "Only supports at most one reduction.\n");
1397 ORE->emit([&]() {
1398 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedInnerReduction",
1399 CurLoop->getStartLoc(),
1400 CurLoop->getHeader())
1401 << "Only supports at most one reduction.";
1402 });
1403 return false;
1404 }
1405 }
1406
1407 return !InnerLoopInductions.empty();
1408}
1409
1410// This function indicates the current limitations in the transform as a result
1411// of which we do not proceed.
1412bool LoopInterchangeLegality::currentLimitations() {
1413 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1414
1415 // transform currently expects the loop latches to also be the exiting
1416 // blocks.
1417 if (InnerLoop->getExitingBlock() != InnerLoopLatch ||
1418 OuterLoop->getExitingBlock() != OuterLoop->getLoopLatch() ||
1419 !isa<CondBrInst>(InnerLoopLatch->getTerminator()) ||
1420 !isa<CondBrInst>(OuterLoop->getLoopLatch()->getTerminator())) {
1421 LLVM_DEBUG(
1422 dbgs() << "Loops where the latch is not the exiting block are not"
1423 << " supported currently.\n");
1424 ORE->emit([&]() {
1425 return OptimizationRemarkMissed(DEBUG_TYPE, "ExitingNotLatch",
1426 OuterLoop->getStartLoc(),
1427 OuterLoop->getHeader())
1428 << "Loops where the latch is not the exiting block cannot be"
1429 " interchange currently.";
1430 });
1431 return true;
1432 }
1433
1434 // TODO: Triangular loops are not handled for now.
1435 if (!isLoopStructureUnderstood()) {
1436 LLVM_DEBUG(dbgs() << "Loop structure not understood by pass\n");
1437 ORE->emit([&]() {
1438 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedStructureInner",
1439 InnerLoop->getStartLoc(),
1440 InnerLoop->getHeader())
1441 << "Inner loop structure not understood currently.";
1442 });
1443 return true;
1444 }
1445
1446 // Currently, we do not support loops that have a predecessor entering the
1447 // loop via an indirectbr.
1448 for (Loop *L : {OuterLoop, InnerLoop}) {
1449 BasicBlock *Header = L->getHeader();
1450 for (BasicBlock *Pred : predecessors(Header)) {
1451 if (L->contains(Pred))
1452 continue;
1453 if (isa<IndirectBrInst>(Pred->getTerminator())) {
1454 LLVM_DEBUG(
1455 dbgs() << "Indirect branch found in the loop predecessor.\n");
1456 ORE->emit([&]() {
1457 return OptimizationRemarkMissed(DEBUG_TYPE, "IndirectBranchPreheader",
1458 L->getStartLoc(), L->getHeader())
1459 << "Indirect branch found in the loop predecessor.";
1460 });
1461 return true;
1462 }
1463 }
1464 }
1465
1466 // Currently, we do not support loops where the inner loop header has
1467 // duplicate successors.
1468 SmallPtrSet<BasicBlock *, 2> InnerLoopHeaderSuccs;
1469 for (BasicBlock *Succ : successors(InnerLoop->getHeader()))
1470 if (!InnerLoopHeaderSuccs.insert(Succ).second)
1471 return true;
1472
1473 return false;
1474}
1475
1476/// We currently only support LCSSA PHI nodes in the inner loop exit if their
1477/// users are either of the following:
1478///
1479/// - Reduction PHIs
1480/// - PHIs outside the outer loop
1481/// - PHIs belonging to the latch of the outer loop
1482///
1483/// These conditions mean that we are only interested in the final value after
1484/// the inner loop.
1485static bool
1488 PHINode *LcssaReduction) {
1489 BasicBlock *InnerExit = InnerL->getUniqueExitBlock();
1490 for (PHINode &PHI : InnerExit->phis()) {
1491 // The reduction LCSSA PHI will have only one incoming block, which comes
1492 // from the loop latch.
1493 if (PHI.getNumIncomingValues() > 1)
1494 return false;
1495 // The reduction LCSSA PHI's store user is rewritten by reduction2Memory();
1496 // skip its user-check but keep validating the remaining LCSSA PHIs.
1497 if (&PHI == LcssaReduction)
1498 continue;
1499 if (any_of(PHI.users(), [&Reductions, OuterL](User *U) {
1500 PHINode *PN = dyn_cast<PHINode>(U);
1501 if (!PN)
1502 return true;
1503 if (Reductions.count(PN))
1504 return false;
1505 BasicBlock *PB = PN->getParent();
1506 if (!OuterL->contains(PB))
1507 return false;
1508 return PB != OuterL->getLoopLatch();
1509 }))
1510 return false;
1511 }
1512 return true;
1513}
1514
1515// We currently support LCSSA PHI nodes in the outer loop exit, if their
1516// incoming values do not come from the outer loop latch or if the
1517// outer loop latch has a single predecessor. In that case, the value will
1518// be available if both the inner and outer loop conditions are true, which
1519// will still be true after interchanging. If we have multiple predecessor,
1520// that may not be the case, e.g. because the outer loop latch may be executed
1521// if the inner loop is not executed.
1522static bool areOuterLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop) {
1523 BasicBlock *LoopNestExit = OuterLoop->getUniqueExitBlock();
1524 for (PHINode &PHI : LoopNestExit->phis()) {
1525 for (Value *Incoming : PHI.incoming_values()) {
1526 Instruction *IncomingI = dyn_cast<Instruction>(Incoming);
1527 if (!IncomingI || IncomingI->getParent() != OuterLoop->getLoopLatch())
1528 continue;
1529
1530 // The incoming value is defined in the outer loop latch. Currently we
1531 // only support that in case the outer loop latch has a single predecessor.
1532 // This guarantees that the outer loop latch is executed if and only if
1533 // the inner loop is executed (because tightlyNested() guarantees that the
1534 // outer loop header only branches to the inner loop or the outer loop
1535 // latch).
1536 // FIXME: We could weaken this logic and allow multiple predecessors,
1537 // if the values are produced outside the loop latch. We would need
1538 // additional logic to update the PHI nodes in the exit block as
1539 // well.
1540 if (OuterLoop->getLoopLatch()->getUniquePredecessor() == nullptr)
1541 return false;
1542 }
1543 }
1544 return true;
1545}
1546
1547/// The transform partially clones the inner loop's latch block, but PHI nodes
1548/// cannot be cloned this way. This function follows the instruction trees that
1549/// would be cloned and checks whether any PHI node other than the induction
1550/// PHIs feeds them. If such a PHI is found, the interchange is rejected.
1551///
1552/// TODO: This check strongly depends on the current implementation of the
1553/// transform. Ideally, the transform should be able to handle such PHI nodes in
1554/// the inner loop latch.
1556 ArrayRef<PHINode *> InductionPHIs) {
1557 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1558
1559 // Seed the worklist with the roots of the use-def chains the transform
1560 // clones: the latch's exit condition and the incoming values of the induction
1561 // PHIs from the latch.
1563 if (auto *LatchBI = dyn_cast<CondBrInst>(InnerLoopLatch->getTerminator()))
1564 if (auto *CondI = dyn_cast<Instruction>(LatchBI->getCondition()))
1565 Worklist.insert(CondI);
1566 for (PHINode *InductionPHI : InductionPHIs) {
1567 if (auto *IncomingI = dyn_cast<Instruction>(
1568 InductionPHI->getIncomingValueForBlock(InnerLoopLatch)))
1569 if (!is_contained(InductionPHIs, IncomingI))
1570 Worklist.insert(IncomingI);
1571 }
1572
1573 // Bail if a PHI node other than the induction PHIs feeds the cloned
1574 // instructions, walking the operand trees within the inner loop.
1575 SmallPtrSet<Instruction *, 4> InductionPHISet(InductionPHIs.begin(),
1576 InductionPHIs.end());
1577 for (unsigned I = 0; I < Worklist.size(); ++I) {
1578 Instruction *Cur = Worklist[I];
1579 if (isa<PHINode>(Cur) && !InductionPHISet.contains(Cur))
1580 return false;
1581 for (Value *Op : Cur->operands())
1582 if (auto *OpI = dyn_cast<Instruction>(Op))
1583 if (InnerLoop->contains(OpI))
1584 Worklist.insert(OpI);
1585 }
1586 return true;
1587}
1588
1589bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId,
1590 unsigned OuterLoopId,
1591 CharMatrix &DepMatrix) {
1592 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) {
1593 LLVM_DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId
1594 << " and OuterLoopId = " << OuterLoopId
1595 << " due to dependence\n");
1596 ORE->emit([&]() {
1597 return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence",
1598 InnerLoop->getStartLoc(),
1599 InnerLoop->getHeader())
1600 << "Cannot interchange loops due to dependences.";
1601 });
1602 return false;
1603 }
1604 // Check if outer and inner loop contain legal instructions only.
1605 for (auto *BB : OuterLoop->blocks())
1606 for (Instruction &I : *BB) {
1607 // Loads and stores are checked separately, so we can skip them here.
1609 continue;
1610
1611 // We cannot ignore potential memory reads, e.g., loads inside the called
1612 // function.
1613 if (!I.mayHaveSideEffects() && !I.mayReadFromMemory())
1614 continue;
1615
1616 LLVM_DEBUG(
1617 dbgs()
1618 << "Loops contain instructions that cannot be safely interchanged\n");
1619 ORE->emit([&]() {
1620 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsafeInst",
1621 I.getDebugLoc(), I.getParent())
1622 << "Cannot interchange loops due to instruction that is "
1623 "potentially unsafe to interchange.";
1624 });
1625
1626 return false;
1627 }
1628
1629 if (!checkInductionsAndReductions(OuterLoop)) {
1630 LLVM_DEBUG(dbgs() << "Failed to find inner loop inductions or found "
1631 "unsupported reductions.\n");
1632 return false;
1633 }
1634
1635 if (!areInnerLoopLatchPHIsSupported(InnerLoop, InnerLoopInductions)) {
1636 LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in inner loop latch.\n");
1637 ORE->emit([&]() {
1638 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedInnerLatchPHI",
1639 InnerLoop->getStartLoc(),
1640 InnerLoop->getHeader())
1641 << "Cannot interchange loops because unsupported PHI nodes found "
1642 "in inner loop latch.";
1643 });
1644 return false;
1645 }
1646
1647 FreezeInst *Freeze = findFreezeInReNestedBlocks(OuterLoop, InnerLoop);
1648 if (!Freeze)
1649 Freeze = findFreezeInInnerLatchCloneSet(InnerLoop, InnerLoopInductions);
1650 if (Freeze) {
1651 LLVM_DEBUG(dbgs() << "Interchange would re-nest or duplicate freeze\n");
1652 ORE->emit([&]() {
1653 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsafeInst",
1654 Freeze->getDebugLoc(),
1655 Freeze->getParent())
1656 << "Cannot interchange loops because re-nesting or duplicating "
1657 "freeze may change its sampling behavior.";
1658 });
1659 return false;
1660 }
1661
1662 // TODO: The loops could not be interchanged due to current limitations in the
1663 // transform module.
1664 if (currentLimitations()) {
1665 LLVM_DEBUG(dbgs() << "Not legal because of current transform limitation\n");
1666 return false;
1667 }
1668
1669 // Check if the loops are tightly nested.
1670 if (!tightlyNested(OuterLoop, InnerLoop)) {
1671 LLVM_DEBUG(dbgs() << "Loops not tightly nested\n");
1672 ORE->emit([&]() {
1673 return OptimizationRemarkMissed(DEBUG_TYPE, "NotTightlyNested",
1674 InnerLoop->getStartLoc(),
1675 InnerLoop->getHeader())
1676 << "Cannot interchange loops because they are not tightly "
1677 "nested.";
1678 });
1679 return false;
1680 }
1681
1682 // The LCSSA PHI for the reduction has passed checks before; its user
1683 // is a store instruction.
1684 PHINode *LcssaReduction = nullptr;
1685 assert(InnerReductions.size() <= 1 &&
1686 "So far we only support at most one reduction.");
1687 if (InnerReductions.size() == 1)
1688 LcssaReduction = InnerReductions[0].LcssaPhi;
1689
1690 if (!areInnerLoopExitPHIsSupported(OuterLoop, InnerLoop, OuterInnerReductions,
1691 LcssaReduction)) {
1692 LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in inner loop exit.\n");
1693 ORE->emit([&]() {
1694 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedExitPHI",
1695 InnerLoop->getStartLoc(),
1696 InnerLoop->getHeader())
1697 << "Found unsupported PHI node in loop exit.";
1698 });
1699 return false;
1700 }
1701
1702 if (!areOuterLoopExitPHIsSupported(OuterLoop, InnerLoop)) {
1703 LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in outer loop exit.\n");
1704 ORE->emit([&]() {
1705 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedExitPHI",
1706 OuterLoop->getStartLoc(),
1707 OuterLoop->getHeader())
1708 << "Found unsupported PHI node in loop exit.";
1709 });
1710 return false;
1711 }
1712
1713 if (any_of(OuterLoop->getLoopLatch()->phis(),
1714 [](PHINode &PHI) { return PHI.getNumIncomingValues() != 1; })) {
1715 LLVM_DEBUG(dbgs() << "Only outer loop latch PHI nodes with one incoming "
1716 "value are supported.\n");
1717 ORE->emit([&]() {
1718 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedLatchPHI",
1719 OuterLoop->getStartLoc(),
1720 OuterLoop->getHeader())
1721 << "Only outer loop latch PHI nodes with one incoming value are "
1722 "supported.";
1723 });
1724 return false;
1725 }
1726
1727 // Regarding def-use chains that begin at an LCSSA PHI in the inner loop exit
1728 // and end at any instruction in the outer loop latch, we currently support
1729 // only the case where the chain contains only PHI nodes. Since we already
1730 // call `tightlyNested()`, we know that if there is a def-use chain that we
1731 // don't support (i.e., a chain that contains a non-PHI user), then the
1732 // non-PHI user must be in the outer loop latch.
1733 if (InnerLoop->getExitBlock() != OuterLoop->getLoopLatch())
1734 for (PHINode &PHI : OuterLoop->getLoopLatch()->phis())
1735 if (any_of(PHI.users(), [](const User *U) { return !isa<PHINode>(U); })) {
1736 LLVM_DEBUG(dbgs() << "Outer loop latch PHI has a non-PHI user.\n");
1737 ORE->emit([&]() {
1738 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedLatchPHI",
1739 OuterLoop->getStartLoc(),
1740 OuterLoop->getHeader())
1741 << "Cannot interchange loops because an outer loop latch PHI "
1742 "node has a non-PHI user.";
1743 });
1744 return false;
1745 }
1746
1747 return true;
1748}
1749
1750void CacheCostManager::computeIfUnitinialized() {
1751 if (CC.has_value())
1752 return;
1753
1754 LLVM_DEBUG(dbgs() << "Compute CacheCost.\n");
1755 CC = CacheCost::getCacheCost(*OutermostLoop, *AR, *DI);
1756 // Obtain the loop vector returned from loop cache analysis beforehand,
1757 // and put each <Loop, index> pair into a map for constant time query
1758 // later. Indices in loop vector reprsent the optimal order of the
1759 // corresponding loop, e.g., given a loopnest with depth N, index 0
1760 // indicates the loop should be placed as the outermost loop and index N
1761 // indicates the loop should be placed as the innermost loop.
1762 //
1763 // For the old pass manager CacheCost would be null.
1764 if (*CC != nullptr)
1765 for (const auto &[Idx, Cost] : enumerate((*CC)->getLoopCosts()))
1766 CostMap[Cost.first] = Idx;
1767}
1768
1769CacheCost *CacheCostManager::getCacheCost() {
1770 computeIfUnitinialized();
1771 return CC->get();
1772}
1773
1774const DenseMap<const Loop *, unsigned> &CacheCostManager::getCostMap() {
1775 computeIfUnitinialized();
1776 return CostMap;
1777}
1778
1779/// If \S contains an affine addrec for \p L, return the step recurrence of it.
1780/// If \S is loop invariant with respect to \p L, return nullptr. Otherwise,
1781/// return std::nullopt, which indicates we cannot determine the coefficient of
1782/// the addrec for \p L in \S.
1783/// TODO: Handle more complex cases. Maybe using SCEVTraversal is a good way to
1784/// do that.
1785static std::optional<const SCEV *>
1788 if (!AR) {
1789 if (SE.isLoopInvariant(S, L))
1790 return nullptr;
1791 return std::nullopt;
1792 }
1793
1794 if (!AR->isAffine()) {
1795 LLVM_DEBUG(dbgs() << "Unexpected non-affine addrec\n");
1796 return std::nullopt;
1797 }
1798
1799 std::optional<const SCEV *> Coeff =
1800 getAddRecCoefficient(SE, AR->getStart(), L);
1801 if (!Coeff.has_value())
1802 return std::nullopt;
1803
1804 if (AR->getLoop() == L) {
1805 assert(!*Coeff && "Found more than one addrec for the same loop");
1806 Coeff = AR->getStepRecurrence(SE);
1807 }
1808 return Coeff;
1809}
1810
1811int LoopInterchangeProfitability::getInstrOrderCost() {
1812 SmallPtrSet<const SCEV *, 4> GoodBasePtrs, BadBasePtrs;
1813 for (BasicBlock *BB : InnerLoop->blocks()) {
1814 for (Instruction &Ins : *BB) {
1815 if (!isa<LoadInst, StoreInst>(&Ins))
1816 continue;
1817 const SCEV *Access = SE->getSCEV(getLoadStorePointerOperand(&Ins));
1818 const SCEV *BasePtr = SE->getPointerBase(Access);
1819 std::optional<const SCEV *> OuterCoeff =
1820 getAddRecCoefficient(*SE, Access, OuterLoop);
1821 std::optional<const SCEV *> InnerCoeff =
1822 getAddRecCoefficient(*SE, Access, InnerLoop);
1823
1824 if (!OuterCoeff.has_value() || !*OuterCoeff || !InnerCoeff.has_value() ||
1825 !*InnerCoeff)
1826 continue;
1827
1828 // This heuristic assumes that a smaller step recurrence implies that the
1829 // induction variable corresponding to the loop is used in the inner
1830 // dimension of the array. Placing such a loop in the inner position would
1831 // be beneficial in terms of locality. If the array access is of the form
1832 // like `A[3*i + 2*j]`, this heuristic may lead to an unprofitable
1833 // interchange, but we expect such cases to be rare.
1834 const SCEV *OuterStep = SE->getAbsExpr(*OuterCoeff, /*IsNSW=*/false);
1835 const SCEV *InnerStep = SE->getAbsExpr(*InnerCoeff, /*IsNSW=*/false);
1836 // If we find the inner induction after an outer induction e.g.
1837 //
1838 // for(int i=0;i<N;i++)
1839 // for(int j=0;j<N;j++)
1840 // A[i][j] = A[i-1][j-1]+k;
1841 //
1842 //
1843 // then it is a good order. If we find the outer induction after an inner
1844 // induction e.g.
1845 //
1846 // for(int i=0;i<N;i++)
1847 // for(int j=0;j<N;j++)
1848 // A[j][i] = A[j-1][i-1]+k;
1849 //
1850 // then it is a bad order.
1851 //
1852 // To avoid counting the same base pointers multiple times, we deduplicate
1853 // them by using a set of base pointers.
1854 if (SE->isKnownPredicate(ICmpInst::ICMP_SLT, InnerStep, OuterStep))
1855 GoodBasePtrs.insert(BasePtr);
1856 else if (SE->isKnownPredicate(ICmpInst::ICMP_SLT, OuterStep, InnerStep))
1857 BadBasePtrs.insert(BasePtr);
1858 }
1859 }
1860
1861 int GoodOrder = GoodBasePtrs.size();
1862 int BadOrder = BadBasePtrs.size();
1863 return GoodOrder - BadOrder;
1864}
1865
1866std::optional<bool>
1867LoopInterchangeProfitability::isProfitablePerLoopCacheAnalysis(
1868 const DenseMap<const Loop *, unsigned> &CostMap, CacheCost *CC) {
1869 // This is the new cost model returned from loop cache analysis.
1870 // A smaller index means the loop should be placed an outer loop, and vice
1871 // versa.
1872 auto InnerLoopIt = CostMap.find(InnerLoop);
1873 if (InnerLoopIt == CostMap.end())
1874 return std::nullopt;
1875 auto OuterLoopIt = CostMap.find(OuterLoop);
1876 if (OuterLoopIt == CostMap.end())
1877 return std::nullopt;
1878
1879 if (CC->getLoopCost(*OuterLoop) == CC->getLoopCost(*InnerLoop))
1880 return std::nullopt;
1881 unsigned InnerIndex = InnerLoopIt->second;
1882 unsigned OuterIndex = OuterLoopIt->second;
1883 LLVM_DEBUG(dbgs() << "InnerIndex = " << InnerIndex
1884 << ", OuterIndex = " << OuterIndex << "\n");
1885 assert(InnerIndex != OuterIndex && "CostMap should assign unique "
1886 "numbers to each loop");
1887 return std::optional<bool>(InnerIndex < OuterIndex);
1888}
1889
1890std::optional<bool>
1891LoopInterchangeProfitability::isProfitablePerInstrOrderCost() {
1892 // Legacy cost model: this is rough cost estimation algorithm. It counts the
1893 // good and bad order of induction variables in the instruction and allows
1894 // reordering if number of bad orders is more than good.
1895 int Cost = getInstrOrderCost();
1896 LLVM_DEBUG(dbgs() << "Cost = " << Cost << "\n");
1898 return std::optional<bool>(true);
1899
1900 return std::nullopt;
1901}
1902
1903/// Return true if we can vectorize the loop specified by \p LoopId.
1904static bool canVectorize(const CharMatrix &DepMatrix, unsigned LoopId) {
1905 for (const auto &Dep : DepMatrix) {
1906 char Dir = Dep[LoopId];
1907 char DepType = Dep.back();
1908 assert((DepType == '<' || DepType == '*') &&
1909 "Unexpected element in dependency vector");
1910
1911 // There are no loop-carried dependencies.
1912 if (Dir == '=' || Dir == 'I')
1913 continue;
1914
1915 // DepType being '<' means that this direction vector represents a forward
1916 // dependency. In principle, a loop with '<' direction can be vectorized in
1917 // this case.
1918 if (Dir == '<' && DepType == '<')
1919 continue;
1920
1921 // We cannot prove that the loop is vectorizable.
1922 return false;
1923 }
1924 return true;
1925}
1926
1927std::optional<bool> LoopInterchangeProfitability::isProfitableForVectorization(
1928 unsigned InnerLoopId, unsigned OuterLoopId, CharMatrix &DepMatrix) {
1929 // If the outer loop cannot be vectorized, it is not profitable to move this
1930 // to inner position.
1931 if (!canVectorize(DepMatrix, OuterLoopId))
1932 return false;
1933
1934 // If the inner loop cannot be vectorized but the outer loop can be, then it
1935 // is profitable to interchange to enable inner loop parallelism.
1936 if (!canVectorize(DepMatrix, InnerLoopId))
1937 return true;
1938
1939 // If both the inner and the outer loop can be vectorized, it is necessary to
1940 // check the cost of each vectorized loop for profitability decision. At this
1941 // time we do not have a cost model to estimate them, so return nullopt.
1942 // TODO: Estimate the cost of vectorized loop when both the outer and the
1943 // inner loop can be vectorized.
1944 return std::nullopt;
1945}
1946
1947bool LoopInterchangeProfitability::isProfitable(
1948 const Loop *InnerLoop, const Loop *OuterLoop, unsigned InnerLoopId,
1949 unsigned OuterLoopId, CharMatrix &DepMatrix, CacheCostManager &CCM) {
1950 // Do not consider loops with a backedge that isn't taken, e.g. an
1951 // unconditional branch true/false, as candidates for interchange.
1952 // TODO: when interchange is forced, we should probably also allow
1953 // interchange for these loops, and thus this logic should be moved just
1954 // below the cost-model ignore check below. But this check is done first
1955 // to avoid the issue in #163954.
1956 const SCEV *InnerBTC = SE->getBackedgeTakenCount(InnerLoop);
1957 const SCEV *OuterBTC = SE->getBackedgeTakenCount(OuterLoop);
1958 if (InnerBTC && InnerBTC->isZero()) {
1959 LLVM_DEBUG(dbgs() << "Inner loop back-edge isn't taken, rejecting "
1960 "single iteration loop\n");
1961 return false;
1962 }
1963 if (OuterBTC && OuterBTC->isZero()) {
1964 LLVM_DEBUG(dbgs() << "Outer loop back-edge isn't taken, rejecting "
1965 "single iteration loop\n");
1966 return false;
1967 }
1968
1969 // Return true if interchange is forced and the cost-model ignored.
1970 if (Profitabilities.size() == 1 && Profitabilities[0] == RuleTy::Ignore)
1971 return true;
1973 "Duplicate rules and option 'ignore' are not allowed");
1974
1975 // isProfitable() is structured to avoid endless loop interchange. If the
1976 // highest priority rule (isProfitablePerLoopCacheAnalysis by default) could
1977 // decide the profitability then, profitability check will stop and return the
1978 // analysis result. If it failed to determine it (e.g., cache analysis failed
1979 // to analyze the loopnest due to delinearization issues) then go ahead the
1980 // second highest priority rule (isProfitablePerInstrOrderCost by default).
1981 // Likewise, if it failed to analysis the profitability then only, the last
1982 // rule (isProfitableForVectorization by default) will decide.
1983 std::optional<bool> shouldInterchange;
1984 for (RuleTy RT : Profitabilities) {
1985 switch (RT) {
1986 case RuleTy::PerLoopCacheAnalysis: {
1987 CacheCost *CC = CCM.getCacheCost();
1988 const DenseMap<const Loop *, unsigned> &CostMap = CCM.getCostMap();
1989 shouldInterchange = isProfitablePerLoopCacheAnalysis(CostMap, CC);
1990 break;
1991 }
1992 case RuleTy::PerInstrOrderCost:
1993 shouldInterchange = isProfitablePerInstrOrderCost();
1994 break;
1995 case RuleTy::ForVectorization:
1996 shouldInterchange =
1997 isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix);
1998 break;
1999 case RuleTy::Ignore:
2000 llvm_unreachable("Option 'ignore' is not supported with other options");
2001 break;
2002 }
2003
2004 // If this rule could determine the profitability, don't call subsequent
2005 // rules.
2006 if (shouldInterchange.has_value())
2007 break;
2008 }
2009
2010 if (!shouldInterchange.has_value()) {
2011 ORE->emit([&]() {
2012 return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable",
2013 InnerLoop->getStartLoc(),
2014 InnerLoop->getHeader())
2015 << "Insufficient information to calculate the cost of loop for "
2016 "interchange.";
2017 });
2018 return false;
2019 } else if (!shouldInterchange.value()) {
2020 ORE->emit([&]() {
2021 return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable",
2022 InnerLoop->getStartLoc(),
2023 InnerLoop->getHeader())
2024 << "Interchanging loops is not considered to improve cache "
2025 "locality nor vectorization.";
2026 });
2027 return false;
2028 }
2029 return true;
2030}
2031
2032void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop,
2033 Loop *InnerLoop) {
2034 for (Loop *L : *OuterLoop)
2035 if (L == InnerLoop) {
2036 OuterLoop->removeChildLoop(L);
2037 return;
2038 }
2039 llvm_unreachable("Couldn't find loop");
2040}
2041
2042/// Update LoopInfo, after interchanging. NewInner and NewOuter refer to the
2043/// new inner and outer loop after interchanging: NewInner is the original
2044/// outer loop and NewOuter is the original inner loop.
2045///
2046/// Before interchanging, we have the following structure
2047/// Outer preheader
2048// Outer header
2049// Inner preheader
2050// Inner header
2051// Inner body
2052// Inner latch
2053// outer bbs
2054// Outer latch
2055//
2056// After interchanging:
2057// Inner preheader
2058// Inner header
2059// Outer preheader
2060// Outer header
2061// Inner body
2062// outer bbs
2063// Outer latch
2064// Inner latch
2065void LoopInterchangeTransform::restructureLoops(
2066 Loop *NewInner, Loop *NewOuter, BasicBlock *OrigInnerPreHeader,
2067 BasicBlock *OrigOuterPreHeader) {
2068 Loop *OuterLoopParent = OuterLoop->getParentLoop();
2069 // The original inner loop preheader moves from the new inner loop to
2070 // the parent loop, if there is one.
2071 NewInner->removeBlockFromLoop(OrigInnerPreHeader);
2072 LI->changeLoopFor(OrigInnerPreHeader, OuterLoopParent);
2073
2074 // Switch the loop levels.
2075 if (OuterLoopParent) {
2076 // Remove the loop from its parent loop.
2077 removeChildLoop(OuterLoopParent, NewInner);
2078 removeChildLoop(NewInner, NewOuter);
2079 OuterLoopParent->addChildLoop(NewOuter);
2080 } else {
2081 removeChildLoop(NewInner, NewOuter);
2082 LI->changeTopLevelLoop(NewInner, NewOuter);
2083 }
2084 while (!NewOuter->isInnermost())
2085 NewInner->addChildLoop(NewOuter->removeChildLoop(NewOuter->begin()));
2086 NewOuter->addChildLoop(NewInner);
2087
2088 // BBs from the original inner loop.
2089 SmallVector<BasicBlock *, 8> OrigInnerBBs(NewOuter->blocks());
2090
2091 // Add BBs from the original outer loop to the original inner loop (excluding
2092 // BBs already in inner loop)
2093 for (BasicBlock *BB : NewInner->blocks())
2094 if (LI->getLoopFor(BB) == NewInner)
2095 NewOuter->addBlockEntry(BB);
2096
2097 // Now remove inner loop header and latch from the new inner loop and move
2098 // other BBs (the loop body) to the new inner loop.
2099 BasicBlock *OuterHeader = NewOuter->getHeader();
2100 BasicBlock *OuterLatch = NewOuter->getLoopLatch();
2101 for (BasicBlock *BB : OrigInnerBBs) {
2102 // Nothing will change for BBs in child loops.
2103 if (LI->getLoopFor(BB) != NewOuter)
2104 continue;
2105 // Remove the new outer loop header and latch from the new inner loop.
2106 if (BB == OuterHeader || BB == OuterLatch)
2107 NewInner->removeBlockFromLoop(BB);
2108 else
2109 LI->changeLoopFor(BB, NewInner);
2110 }
2111
2112 // The preheader of the original outer loop becomes part of the new
2113 // outer loop.
2114 NewOuter->addBlockEntry(OrigOuterPreHeader);
2115 LI->changeLoopFor(OrigOuterPreHeader, NewOuter);
2116
2117 // Tell SE that we move the loops around.
2118 SE->forgetLoop(NewOuter);
2119}
2120
2121/// User can write, or optimizers can generate the reduction for inner loop.
2122/// To make the interchange valid, apply Reduction2Mem by moving the
2123/// initializer and store instructions into the inner loop. So far we only
2124/// handle cases where the reduction variable is initialized to a constant.
2125/// For example, below code:
2126///
2127/// loop:
2128/// re = phi<0.0, next>
2129/// next = re op ...
2130/// endloop
2131/// reduc_sum = phi<next> // lcssa phi
2132/// MEM_REF[idx] = reduc_sum // LcssaStore
2133///
2134/// is transformed into:
2135///
2136/// loop:
2137/// tmp = MEM_REF[idx];
2138/// new_var = !first_iteration ? tmp : 0.0;
2139/// next = new_var op ...
2140/// MEM_REF[idx] = next; // after moving
2141/// endloop
2142///
2143/// In this way the initial const is used in the first iteration of loop.
2144void LoopInterchangeTransform::reduction2Memory() {
2146 LIL.getInnerReductions();
2147
2148 assert(InnerReductions.size() == 1 &&
2149 "So far we only support at most one reduction.");
2150
2151 LoopInterchangeLegality::InnerReduction SR = InnerReductions[0];
2152 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
2153 IRBuilder<> Builder(InnerLoopHeader, InnerLoopHeader->getFirstNonPHIIt());
2154
2155 // Check if it's the first iteration.
2156 LLVMContext &Context = InnerLoopHeader->getContext();
2157 PHINode *FirstIter =
2158 Builder.CreatePHI(Type::getInt1Ty(Context), 2, "first.iter");
2159 FirstIter->addIncoming(ConstantInt::get(Type::getInt1Ty(Context), 1),
2160 InnerLoop->getLoopPreheader());
2161 FirstIter->addIncoming(ConstantInt::get(Type::getInt1Ty(Context), 0),
2162 InnerLoop->getLoopLatch());
2163 assert(FirstIter->isComplete() && "The FirstIter PHI node is not complete.");
2164
2165 // When the reduction is initialized from a constant value, we need to add
2166 // a stmt loading from the memory object to target basic block in inner
2167 // loop.
2168 Instruction *LoadMem = Builder.CreateLoad(SR.ElemTy, SR.MemRef);
2169
2170 // Init new_var to MEM_REF or CONST depending on if it is the first iteration.
2171 Value *NewVar = Builder.CreateSelect(FirstIter, SR.Init, LoadMem, "new.var");
2172
2173 // Replace all uses of the reduction variable with a new variable.
2174 SR.Reduction->replaceAllUsesWith(NewVar);
2175
2176 // Move store instruction into inner loop, just after reduction next's
2177 // definition.
2178 SR.LcssaStore->setOperand(0, SR.Next);
2179 SR.LcssaStore->moveAfter(dyn_cast<Instruction>(SR.Next));
2180}
2181
2182void LoopInterchangeTransform::transform(
2183 ArrayRef<Instruction *> DropNoWrapInsts,
2184 ArrayRef<Instruction *> DropNoInfInsts) {
2185
2187 LIL.getInnerReductions();
2188 if (InnerReductions.size() == 1)
2189 reduction2Memory();
2190
2191 LLVM_DEBUG(dbgs() << "Splitting the inner loop latch\n");
2192 auto &InductionPHIs = LIL.getInnerLoopInductions();
2193 assert(!InductionPHIs.empty() &&
2194 "Expected at least one induction variable in the inner loop");
2195
2196 SmallVector<Instruction *, 8> InnerIndexVarList;
2197 for (PHINode *CurInductionPHI : InductionPHIs) {
2198 Instruction *IncomingValue = dyn_cast<Instruction>(
2199 CurInductionPHI->getIncomingValueForBlock(InnerLoop->getLoopLatch()));
2200 assert(IncomingValue &&
2201 "Incoming value from loop latch isn't an instruction");
2202 if (is_contained(InductionPHIs, IncomingValue))
2203 continue;
2204 InnerIndexVarList.push_back(IncomingValue);
2205 }
2206
2207 // Create a new latch block for the inner loop. We split at the
2208 // current latch's terminator and then move the condition and all
2209 // operands that are not either loop-invariant or the induction PHI into the
2210 // new latch block.
2211 BasicBlock *NewLatch =
2212 SplitBlock(InnerLoop->getLoopLatch(),
2213 InnerLoop->getLoopLatch()->getTerminator(), DT, LI);
2214
2215 // Keep these seeds and the operand filter aligned with
2216 // findFreezeInInnerLatchCloneSet.
2217 SmallSetVector<Instruction *, 4> WorkList;
2218 unsigned i = 0;
2219 auto MoveInstructions = [&i, &WorkList, this, &InductionPHIs, NewLatch]() {
2220 for (; i < WorkList.size(); i++) {
2221 // PHI nodes cannot be cloned and moved here; the legality check
2222 // (areInnerLoopLatchPHIsSupported) ensures none reach the worklist.
2223 assert(!isa<PHINode>(WorkList[i]) &&
2224 "MoveInstructions does not support PHI nodes");
2225 // Duplicate instruction and move it to the new latch. Update uses that
2226 // have been moved.
2227 Instruction *NewI = WorkList[i]->clone();
2228 NewI->insertBefore(NewLatch->getFirstNonPHIIt());
2229 assert(!NewI->mayHaveSideEffects() &&
2230 "Moving instructions with side-effects may change behavior of "
2231 "the loop nest!");
2232 for (Use &U : llvm::make_early_inc_range(WorkList[i]->uses())) {
2233 Instruction *UserI = cast<Instruction>(U.getUser());
2234 if (!InnerLoop->contains(UserI->getParent()) ||
2235 UserI->getParent() == NewLatch ||
2236 llvm::is_contained(InductionPHIs, UserI))
2237 U.set(NewI);
2238 }
2239 // Add operands of moved instruction to the worklist, except if they are
2240 // outside the inner loop or are the induction PHI.
2241 for (Value *Op : WorkList[i]->operands()) {
2243 if (!OpI || this->LI->getLoopFor(OpI->getParent()) != this->InnerLoop ||
2244 llvm::is_contained(InductionPHIs, OpI))
2245 continue;
2246 WorkList.insert(OpI);
2247 }
2248 }
2249 };
2250
2251 // FIXME: Should we interchange when we have a constant condition?
2254 ->getCondition());
2255 if (CondI)
2256 WorkList.insert(CondI);
2257 MoveInstructions();
2258 for (Instruction *InnerIndexVar : InnerIndexVarList)
2259 WorkList.insert(cast<Instruction>(InnerIndexVar));
2260 MoveInstructions();
2261
2262 // Split the inner header so that it has a unique successor.
2263 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
2264 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHIIt(), DT, LI);
2265 LLVM_DEBUG(dbgs() << "splitting InnerLoopHeader done\n");
2266
2267 // Instructions in the original inner loop preheader may depend on values
2268 // defined in the outer loop header. Move them there, because the original
2269 // inner loop preheader will become the entry into the interchanged loop nest.
2270 // Currently we move all instructions and rely on LICM to move invariant
2271 // instructions outside the loop nest.
2272 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
2273 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
2274
2275 if (InnerLoopPreHeader != OuterLoopHeader) {
2276 // Eliminate PHIs in the inner-loop preheader.
2277 for (PHINode &P : make_early_inc_range(InnerLoopPreHeader->phis())) {
2278 assert(all_equal(P.incoming_values()) &&
2279 "Expected equivalent incoming values in inner loop preheader");
2280 P.replaceAllUsesWith(P.getIncomingValue(0));
2281 P.eraseFromParent();
2282 }
2283 for (Instruction &I :
2284 make_early_inc_range(make_range(InnerLoopPreHeader->begin(),
2285 std::prev(InnerLoopPreHeader->end()))))
2286 I.moveBeforePreserving(OuterLoopHeader->getTerminator()->getIterator());
2287 }
2288
2289 adjustLoopBranches();
2290
2291 // Finally, drop the nsw/nuw/ninf flags from the instructions for reduction
2292 // calculations.
2293 for (Instruction *Reduction : DropNoWrapInsts) {
2294 Reduction->setHasNoSignedWrap(false);
2295 Reduction->setHasNoUnsignedWrap(false);
2296 }
2297 for (Instruction *I : DropNoInfInsts)
2298 I->setHasNoInfs(false);
2299}
2300
2301/// \brief Move all instructions except the terminator from FromBB right before
2302/// InsertBefore
2303static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) {
2304 BasicBlock *ToBB = InsertBefore->getParent();
2305
2306 ToBB->splice(InsertBefore->getIterator(), FromBB, FromBB->begin(),
2307 FromBB->getTerminator()->getIterator());
2308}
2309
2310/// Swap instructions between \p BB1 and \p BB2 but keep terminators intact.
2311static void swapBBContents(BasicBlock *BB1, BasicBlock *BB2) {
2312 // Save all non-terminator instructions of BB1 into TempInstrs and unlink them
2313 // from BB1 afterwards.
2314 auto Iter = map_range(*BB1, [](Instruction &I) { return &I; });
2315 SmallVector<Instruction *, 4> TempInstrs(Iter.begin(), std::prev(Iter.end()));
2316 for (Instruction *I : TempInstrs)
2317 I->removeFromParent();
2318
2319 // Move instructions from BB2 to BB1.
2320 moveBBContents(BB2, BB1->getTerminator());
2321
2322 // Move instructions from TempInstrs to BB2.
2323 for (Instruction *I : TempInstrs)
2324 I->insertBefore(BB2->getTerminator()->getIterator());
2325}
2326
2327// Update BI to jump to NewBB instead of OldBB. Records updates to the
2328// dominator tree in DTUpdates. If \p MustUpdateOnce is true, assert that
2329// \p OldBB is exactly once in BI's successor list.
2330static void updateSuccessor(Instruction *Term, BasicBlock *OldBB,
2331 BasicBlock *NewBB,
2332 std::vector<DominatorTree::UpdateType> &DTUpdates,
2333 bool MustUpdateOnce = true) {
2334 assert((!MustUpdateOnce || llvm::count(successors(Term), OldBB) == 1) &&
2335 "BI must jump to OldBB exactly once.");
2336 bool Changed = false;
2337 for (Use &Op : Term->operands())
2338 if (Op == OldBB) {
2339 Op.set(NewBB);
2340 Changed = true;
2341 }
2342
2343 if (Changed) {
2344 DTUpdates.push_back(
2345 {DominatorTree::UpdateKind::Insert, Term->getParent(), NewBB});
2346 DTUpdates.push_back(
2347 {DominatorTree::UpdateKind::Delete, Term->getParent(), OldBB});
2348 }
2349 assert(Changed && "Expected a successor to be updated");
2350}
2351
2352// Move Lcssa PHIs to the right place.
2353static void moveLCSSAPhis(BasicBlock *InnerExit, BasicBlock *InnerHeader,
2354 BasicBlock *InnerLatch, BasicBlock *OuterHeader,
2355 BasicBlock *OuterLatch, BasicBlock *OuterExit,
2356 Loop *InnerLoop, LoopInfo *LI) {
2357
2358 // Deal with LCSSA PHI nodes in the exit block of the inner loop, that are
2359 // defined either in the header or latch. Those blocks will become header and
2360 // latch of the new outer loop, and the only possible users can PHI nodes
2361 // in the exit block of the loop nest or the outer loop header (reduction
2362 // PHIs, in that case, the incoming value must be defined in the inner loop
2363 // header). We can just substitute the user with the incoming value and remove
2364 // the PHI.
2365 for (PHINode &P : make_early_inc_range(InnerExit->phis())) {
2366 assert(P.getNumIncomingValues() == 1 &&
2367 "Only loops with a single exit are supported!");
2368
2369 Value *IncomingValue = P.getIncomingValueForBlock(InnerLatch);
2370 auto *IncI = dyn_cast<Instruction>(IncomingValue);
2371 if (!IncI) {
2372 // If the incoming value is not an instruction, it must be loop invariant.
2373 // In that case, we can just replace the PHI with the incoming value and
2374 // remove the PHI.
2375 assert(InnerLoop->isLoopInvariant(IncomingValue) &&
2376 "Expected non-instruction incoming value to be loop invariant");
2377 P.replaceAllUsesWith(IncomingValue);
2378 P.eraseFromParent();
2379 continue;
2380 }
2381
2382 // In case of multi-level nested loops, follow LCSSA to find the incoming
2383 // value defined from the innermost loop.
2384 auto *IncIInnerMost = dyn_cast<Instruction>(followLCSSA(IncI));
2385 // Skip phis when:
2386 // - they are not an instruction, e.g. incoming values are constants.
2387 // - Incomming values from the inner loop body, excluding the header and
2388 // latch.
2389 if (!IncIInnerMost || (IncIInnerMost->getParent() != InnerLatch &&
2390 IncIInnerMost->getParent() != InnerHeader))
2391 continue;
2392
2393 assert(all_of(P.users(),
2394 [OuterHeader, OuterExit, IncI, InnerHeader](User *U) {
2395 return (cast<PHINode>(U)->getParent() == OuterHeader &&
2396 IncI->getParent() == InnerHeader) ||
2397 cast<PHINode>(U)->getParent() == OuterExit;
2398 }) &&
2399 "Can only replace phis iff the uses are in the loop nest exit or "
2400 "the incoming value is defined in the inner header (it will "
2401 "dominate all loop blocks after interchanging)");
2402 P.replaceAllUsesWith(IncI);
2403 P.eraseFromParent();
2404 }
2405
2406 SmallVector<PHINode *, 8> LcssaInnerExit(
2407 llvm::make_pointer_range(InnerExit->phis()));
2408
2409 SmallVector<PHINode *, 8> LcssaInnerLatch(
2410 llvm::make_pointer_range(InnerLatch->phis()));
2411
2412 // Lcssa PHIs for values used outside the inner loop are in InnerExit.
2413 // If a PHI node has users outside of InnerExit, it has a use outside the
2414 // interchanged loop and we have to preserve it. We move these to
2415 // InnerLatch, which will become the new exit block for the innermost
2416 // loop after interchanging.
2417 for (PHINode *P : LcssaInnerExit)
2418 P->moveBefore(InnerLatch->getFirstNonPHIIt());
2419
2420 // If the inner loop latch contains LCSSA PHIs, those come from a child loop
2421 // and we have to move them to the new inner latch.
2422 for (PHINode *P : LcssaInnerLatch)
2423 P->moveBefore(InnerExit->getFirstNonPHIIt());
2424
2425 // Deal with LCSSA PHI nodes in the loop nest exit block. For PHIs that have
2426 // incoming values defined in the outer loop, we have to add a new PHI
2427 // in the inner loop latch, which became the exit block of the outer loop,
2428 // after interchanging.
2429 if (OuterExit) {
2430 for (PHINode &P : OuterExit->phis()) {
2431 if (P.getNumIncomingValues() != 1)
2432 continue;
2433 // Skip Phis with incoming values defined in the inner loop. Those should
2434 // already have been updated.
2435 auto I = dyn_cast<Instruction>(P.getIncomingValue(0));
2436 if (!I || LI->getLoopFor(I->getParent()) == InnerLoop)
2437 continue;
2438
2439 PHINode *NewPhi = dyn_cast<PHINode>(P.clone());
2440 NewPhi->setIncomingValue(0, P.getIncomingValue(0));
2441 NewPhi->setIncomingBlock(0, OuterLatch);
2442 // We might have incoming edges from other BBs, i.e., the original outer
2443 // header.
2444 for (auto *Pred : predecessors(InnerLatch)) {
2445 if (Pred == OuterLatch)
2446 continue;
2447 NewPhi->addIncoming(P.getIncomingValue(0), Pred);
2448 }
2449 NewPhi->insertBefore(InnerLatch->getFirstNonPHIIt());
2450 P.setIncomingValue(0, NewPhi);
2451 }
2452 }
2453
2454 // Now adjust the incoming blocks for the LCSSA PHIs.
2455 // For PHIs moved from Inner's exit block, we need to replace Inner's latch
2456 // with the new latch.
2457 InnerLatch->replacePhiUsesWith(InnerLatch, OuterLatch);
2458}
2459
2460/// This deals with a corner case when a LCSSA phi node appears in a non-exit
2461/// block: the outer loop latch block does not need to be exit block of the
2462/// inner loop. Consider a loop that was in LCSSA form, but then some
2463/// transformation like loop-unswitch comes along and creates an empty block,
2464/// where BB5 in this example is the outer loop latch block:
2465///
2466/// BB4:
2467/// br label %BB5
2468/// BB5:
2469/// %old.cond.lcssa = phi i16 [ %cond, %BB4 ]
2470/// br outer.header
2471///
2472/// Interchange then brings it in LCSSA form again resulting in this chain of
2473/// single-input phi nodes:
2474///
2475/// BB4:
2476/// %new.cond.lcssa = phi i16 [ %cond, %BB3 ]
2477/// br label %BB5
2478/// BB5:
2479/// %old.cond.lcssa = phi i16 [ %new.cond.lcssa, %BB4 ]
2480///
2481/// The problem is that interchange can reoder blocks BB4 and BB5 placing the
2482/// use before the def if we don't check this. The solution is to simplify
2483/// lcssa phi nodes (remove) if they appear in non-exit blocks.
2484///
2485static void simplifyLCSSAPhis(Loop *OuterLoop, Loop *InnerLoop) {
2486 BasicBlock *InnerLoopExit = InnerLoop->getExitBlock();
2487 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
2488
2489 // Do not modify lcssa phis where they actually belong, i.e. in exit blocks.
2490 if (OuterLoopLatch == InnerLoopExit)
2491 return;
2492
2493 // Collect and remove phis in non-exit blocks if they have 1 input.
2495 llvm::make_pointer_range(OuterLoopLatch->phis()));
2496 for (PHINode *Phi : Phis) {
2497 assert(Phi->getNumIncomingValues() == 1 && "Single input phi expected");
2498 LLVM_DEBUG(dbgs() << "Removing 1-input phi in non-exit block: " << *Phi
2499 << "\n");
2500 Phi->replaceAllUsesWith(Phi->getIncomingValue(0));
2501 Phi->eraseFromParent();
2502 }
2503}
2504
2505void LoopInterchangeTransform::adjustLoopBranches() {
2506 LLVM_DEBUG(dbgs() << "adjustLoopBranches called\n");
2507 std::vector<DominatorTree::UpdateType> DTUpdates;
2508
2509 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
2510 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
2511
2512 assert(OuterLoopPreHeader != OuterLoop->getHeader() &&
2513 InnerLoopPreHeader != InnerLoop->getHeader() && OuterLoopPreHeader &&
2514 InnerLoopPreHeader && "Guaranteed by loop-simplify form");
2515
2516 simplifyLCSSAPhis(OuterLoop, InnerLoop);
2517
2518 // Ensure that both preheaders do not contain PHI nodes and have single
2519 // predecessors. This allows us to move them easily. We use
2520 // InsertPreHeaderForLoop to create an 'extra' preheader, if the existing
2521 // preheaders do not satisfy those conditions.
2522 if (isa<PHINode>(OuterLoopPreHeader->begin()) ||
2523 !OuterLoopPreHeader->getUniquePredecessor())
2524 OuterLoopPreHeader =
2525 InsertPreheaderForLoop(OuterLoop, DT, LI, nullptr, true);
2526 if (InnerLoopPreHeader == OuterLoop->getHeader())
2527 InnerLoopPreHeader =
2528 InsertPreheaderForLoop(InnerLoop, DT, LI, nullptr, true);
2529
2530 // Adjust the loop preheader
2531 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
2532 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
2533 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
2534 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
2535 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor();
2536 BasicBlock *InnerLoopLatchPredecessor =
2537 InnerLoopLatch->getUniquePredecessor();
2538 BasicBlock *InnerLoopLatchSuccessor;
2539 BasicBlock *OuterLoopLatchSuccessor;
2540
2541 CondBrInst *OuterLoopLatchBI =
2542 dyn_cast<CondBrInst>(OuterLoopLatch->getTerminator());
2543 CondBrInst *InnerLoopLatchBI =
2544 dyn_cast<CondBrInst>(InnerLoopLatch->getTerminator());
2545 Instruction *OuterLoopHeaderBI = OuterLoopHeader->getTerminator();
2546 Instruction *InnerLoopHeaderBI = InnerLoopHeader->getTerminator();
2547
2548 assert(OuterLoopPredecessor && InnerLoopLatchPredecessor &&
2549 "Failed to find a unique predecessor");
2550 assert(OuterLoopLatchBI && InnerLoopLatchBI &&
2551 "Failed to find a conditional branch");
2552
2553 Instruction *InnerLoopLatchPredecessorBI =
2554 InnerLoopLatchPredecessor->getTerminator();
2555 Instruction *OuterLoopPredecessorBI = OuterLoopPredecessor->getTerminator();
2556
2557 BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor();
2558 assert(InnerLoopHeaderSuccessor &&
2559 "Failed to find a unique successor for the inner loop header");
2560
2561 // Adjust Loop Preheader and headers.
2562 // The branches in the outer loop predecessor and the outer loop header can
2563 // be unconditional branches or conditional branches with duplicates. Consider
2564 // this when updating the successors.
2565 updateSuccessor(OuterLoopPredecessorBI, OuterLoopPreHeader,
2566 InnerLoopPreHeader, DTUpdates, /*MustUpdateOnce=*/false);
2567 // The outer loop header might or might not branch to the outer latch.
2568 // We are guaranteed to branch to the inner loop preheader.
2569 if (llvm::is_contained(successors(OuterLoopHeaderBI), OuterLoopLatch)) {
2570 // In this case the outerLoopHeader should branch to the InnerLoopLatch.
2571 updateSuccessor(OuterLoopHeaderBI, OuterLoopLatch, InnerLoopLatch,
2572 DTUpdates,
2573 /*MustUpdateOnce=*/false);
2574 }
2575 updateSuccessor(OuterLoopHeaderBI, InnerLoopPreHeader,
2576 InnerLoopHeaderSuccessor, DTUpdates,
2577 /*MustUpdateOnce=*/false);
2578
2579 // Adjust reduction PHI's now that the incoming block has changed.
2580 InnerLoopHeaderSuccessor->replacePhiUsesWith(InnerLoopHeader,
2581 OuterLoopHeader);
2582
2583 updateSuccessor(InnerLoopHeaderBI, InnerLoopHeaderSuccessor,
2584 OuterLoopPreHeader, DTUpdates);
2585
2586 // -------------Adjust loop latches-----------
2587 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
2588 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
2589 else
2590 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
2591
2592 updateSuccessor(InnerLoopLatchPredecessorBI, InnerLoopLatch,
2593 InnerLoopLatchSuccessor, DTUpdates);
2594
2595 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader)
2596 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1);
2597 else
2598 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0);
2599
2600 updateSuccessor(InnerLoopLatchBI, InnerLoopLatchSuccessor,
2601 OuterLoopLatchSuccessor, DTUpdates);
2602 updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch,
2603 DTUpdates);
2604
2605 DT->applyUpdates(DTUpdates);
2606 restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader,
2607 OuterLoopPreHeader);
2608
2609 moveLCSSAPhis(InnerLoopLatchSuccessor, InnerLoopHeader, InnerLoopLatch,
2610 OuterLoopHeader, OuterLoopLatch, InnerLoop->getExitBlock(),
2611 InnerLoop, LI);
2612 // For PHIs in the exit block of the outer loop, outer's latch has been
2613 // replaced by Inners'.
2614 OuterLoopLatchSuccessor->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch);
2615
2616 auto &OuterInnerReductions = LIL.getOuterInnerReductions();
2617 // Now update the reduction PHIs in the inner and outer loop headers.
2618 SmallVector<PHINode *, 4> InnerLoopPHIs, OuterLoopPHIs;
2619 for (PHINode &PHI : InnerLoopHeader->phis())
2620 if (OuterInnerReductions.contains(&PHI))
2621 InnerLoopPHIs.push_back(&PHI);
2622
2623 for (PHINode &PHI : OuterLoopHeader->phis())
2624 if (OuterInnerReductions.contains(&PHI))
2625 OuterLoopPHIs.push_back(&PHI);
2626
2627 // Now move the remaining reduction PHIs from outer to inner loop header and
2628 // vice versa. The PHI nodes must be part of a reduction across the inner and
2629 // outer loop and all the remains to do is and updating the incoming blocks.
2630 for (PHINode *PHI : OuterLoopPHIs) {
2631 LLVM_DEBUG(dbgs() << "Outer loop reduction PHIs:\n"; PHI->dump(););
2632 PHI->moveBefore(InnerLoopHeader->getFirstNonPHIIt());
2633 assert(OuterInnerReductions.count(PHI) && "Expected a reduction PHI node");
2634 }
2635 for (PHINode *PHI : InnerLoopPHIs) {
2636 LLVM_DEBUG(dbgs() << "Inner loop reduction PHIs:\n"; PHI->dump(););
2637 PHI->moveBefore(OuterLoopHeader->getFirstNonPHIIt());
2638 assert(OuterInnerReductions.count(PHI) && "Expected a reduction PHI node");
2639 }
2640
2641 // Update the incoming blocks for moved PHI nodes.
2642 OuterLoopHeader->replacePhiUsesWith(InnerLoopPreHeader, OuterLoopPreHeader);
2643 OuterLoopHeader->replacePhiUsesWith(InnerLoopLatch, OuterLoopLatch);
2644 InnerLoopHeader->replacePhiUsesWith(OuterLoopPreHeader, InnerLoopPreHeader);
2645 InnerLoopHeader->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch);
2646
2647 // Swap the preheader contents so each definition sits in the preheader of the
2648 // loop it now belongs to. This runs before the LCSSA rebuild below so that
2649 // any definition referenced across the interchanged levels dominates its uses
2650 // when formLCSSAForInstructions runs.
2651 swapBBContents(OuterLoop->getLoopPreheader(), InnerLoop->getLoopPreheader());
2652
2653 // Values defined in the outer loop header could be used in the inner loop
2654 // latch. In that case, we need to create LCSSA phis for them, because after
2655 // interchanging they will be defined in the new inner loop and used in the
2656 // new outer loop.
2657 SmallVector<Instruction *, 4> MayNeedLCSSAPhis;
2658 for (Instruction &I :
2659 make_range(OuterLoopHeader->begin(), std::prev(OuterLoopHeader->end())))
2660 MayNeedLCSSAPhis.push_back(&I);
2661
2662#ifndef NDEBUG
2663 assert(!verifyFunction(*OuterLoopHeader->getParent(), &errs()) &&
2664 "LoopInterchange handed dominance-broken IR to LCSSA rebuild");
2665#endif
2666
2667 formLCSSAForInstructions(MayNeedLCSSAPhis, *DT, *LI, SE);
2668}
2669
2673 LPMUpdater &U) {
2674 Function &F = *LN.getParent();
2675 SmallVector<Loop *, 8> LoopList(LN.getLoops());
2676
2678
2679 // Ensure minimum depth of the loop nest to do the interchange.
2680 if (!hasSupportedLoopDepth(LoopList, ORE))
2681 return PreservedAnalyses::all();
2682 // Ensure computable loop nest.
2683 if (!isComputableLoopNest(&AR.SE, LoopList)) {
2684 LLVM_DEBUG(dbgs() << "Not valid loop candidate for interchange\n");
2685 return PreservedAnalyses::all();
2686 }
2687
2688 ORE.emit([&]() {
2689 return OptimizationRemarkAnalysis(DEBUG_TYPE, "Dependence",
2692 << "Computed dependence info, invoking the transform.";
2693 });
2694
2695 DependenceInfo DI(&F, &AR.AA, &AR.SE, &AR.LI);
2696 if (!LoopInterchange(&AR.SE, &AR.LI, &DI, &AR.DT, &AR, &ORE).run(LN))
2697 return PreservedAnalyses::all();
2698 U.markLoopNestChanged(true);
2700}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
Rewrite undef for PHI
ReachingDefInfo InstSet InstSet & Ignore
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
DXIL Resource Access
#define DEBUG_TYPE
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file defines the interface for the loop cache analysis.
SmallVector< Loop *, 4 > LoopVector
Definition LoopFuse.cpp:362
Loop::LoopBounds::Direction Direction
Definition LoopInfo.cpp:253
static cl::list< RuleTy > Profitabilities("loop-interchange-profitabilities", cl::MiscFlags::CommaSeparated, cl::Hidden, cl::desc("List of profitability heuristics to be used. They are applied in " "the given order"), cl::list_init< RuleTy >({RuleTy::PerInstrOrderCost, RuleTy::ForVectorization}), cl::values(clEnumValN(RuleTy::PerLoopCacheAnalysis, "cache", "Prioritize loop cache cost"), clEnumValN(RuleTy::PerInstrOrderCost, "instorder", "Prioritize the IVs order of each instruction"), clEnumValN(RuleTy::ForVectorization, "vectorize", "Prioritize vectorization"), clEnumValN(RuleTy::Ignore, "ignore", "Ignore profitability, force interchange (does not " "work with other options)")))
static cl::opt< int > LoopInterchangeCostThreshold("loop-interchange-threshold", cl::init(0), cl::Hidden, cl::desc("Interchange if you gain more than this number"))
static FreezeInst * findFreezeInInnerLatchCloneSet(Loop *InnerLoop, ArrayRef< PHINode * > InnerLoopInductions)
static cl::opt< unsigned int > MinLoopNestDepth("loop-interchange-min-loop-nest-depth", cl::init(2), cl::Hidden, cl::desc("Minimum depth of loop nest considered for the transform"))
static void updateSuccessor(Instruction *Term, BasicBlock *OldBB, BasicBlock *NewBB, std::vector< DominatorTree::UpdateType > &DTUpdates, bool MustUpdateOnce=true)
static cl::opt< bool > EnableReduction2Memory("loop-interchange-reduction-to-mem", cl::init(false), cl::Hidden, cl::desc("Support for the inner-loop reduction pattern."))
static bool areInnerLoopLatchPHIsSupported(Loop *InnerLoop, ArrayRef< PHINode * > InductionPHIs)
The transform partially clones the inner loop's latch block, but PHI nodes cannot be cloned this way.
static bool isComputableLoopNest(ScalarEvolution *SE, ArrayRef< Loop * > LoopList)
static bool areOuterLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop)
static FreezeInst * findFreezeInReNestedBlocks(Loop *OuterLoop, Loop *InnerLoop)
static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore)
Move all instructions except the terminator from FromBB right before InsertBefore.
static void simplifyLCSSAPhis(Loop *OuterLoop, Loop *InnerLoop)
This deals with a corner case when a LCSSA phi node appears in a non-exit block: the outer loop latch...
static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx, unsigned ToIndx)
static void moveLCSSAPhis(BasicBlock *InnerExit, BasicBlock *InnerHeader, BasicBlock *InnerLatch, BasicBlock *OuterHeader, BasicBlock *OuterLatch, BasicBlock *OuterExit, Loop *InnerLoop, LoopInfo *LI)
static void printDepMatrix(CharMatrix &DepMatrix)
static cl::opt< unsigned int > MaxMemInstrRatio("loop-interchange-max-mem-instr-ratio", cl::init(4), cl::Hidden, cl::desc("Maximum number of load/store instructions squared in relation to " "the total number of instructions. Higher value may lead to more " "interchanges at the cost of compile-time"))
static void swapBBContents(BasicBlock *BB1, BasicBlock *BB2)
Swap instructions between BB1 and BB2 but keep terminators intact.
static PHINode * findInnerReductionPhi(Loop *L, Value *V, SmallVectorImpl< Instruction * > &HasNoWrapInsts, SmallVectorImpl< Instruction * > &HasNoInfInsts)
static bool areInnerLoopExitPHIsSupported(Loop *OuterL, Loop *InnerL, SmallPtrSetImpl< PHINode * > &Reductions, PHINode *LcssaReduction)
We currently only support LCSSA PHI nodes in the inner loop exit if their users are either of the fol...
static cl::opt< unsigned int > MaxLoopNestDepth("loop-interchange-max-loop-nest-depth", cl::init(10), cl::Hidden, cl::desc("Maximum depth of loop nest considered for the transform"))
static bool hasSupportedLoopDepth(ArrayRef< Loop * > LoopList, OptimizationRemarkEmitter &ORE)
static bool inThisOrder(const Instruction *Src, const Instruction *Dst)
Return true if Src appears before Dst in the same basic block.
static bool canVectorize(const CharMatrix &DepMatrix, unsigned LoopId)
Return true if we can vectorize the loop specified by LoopId.
static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix, unsigned InnerLoopId, unsigned OuterLoopId)
#define DEBUG_TYPE
static Value * followLCSSA(Value *SV)
static void populateWorklist(Loop &L, LoopVector &LoopList)
static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level, Loop *L, DependenceInfo *DI, ScalarEvolution *SE, OptimizationRemarkEmitter *ORE)
static std::optional< bool > isLexicographicallyPositive(ArrayRef< char > DV, unsigned Begin, unsigned End)
static bool checkReductionKind(Loop *L, PHINode *PHI, SmallVectorImpl< Instruction * > &HasNoWrapInsts, SmallVectorImpl< Instruction * > &HasNoInfInsts)
static std::optional< const SCEV * > getAddRecCoefficient(ScalarEvolution &SE, const SCEV *S, const Loop *L)
If \S contains an affine addrec for L, return the step recurrence of it.
static bool noDuplicateRulesAndIgnore(ArrayRef< RuleTy > Rules)
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.
loop Loop Strength Reduction
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
#define P(N)
This file contains some templates that are useful if you are working with the STL at all.
static bool processLoop(Loop &L, const AArch64Subtarget &ST, DataLayout DL)
SmallVector< Value *, 8 > ValueVector
This file defines the SmallSet class.
This file defines the SmallVector class.
static bool isProfitable(const StableFunctionMap::StableFunctionEntries &SFS)
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:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
Definition BasicBlock.h:644
static LLVM_ABI std::unique_ptr< CacheCost > getCacheCost(Loop &Root, LoopStandardAnalysisResults &AR, DependenceInfo &DI, std::optional< unsigned > TRT=std::nullopt)
Create a CacheCost for the loop nest rooted by Root.
CacheCostTy getLoopCost(const Loop &L) const
Return the estimated cost of loop L if the given loop is part of the loop nest associated with this o...
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
iterator end()
Definition DenseMap.h:141
DependenceInfo - This class is the main dependence-analysis driver.
LLVM_ABI std::unique_ptr< Dependence > depends(Instruction *Src, Instruction *Dst, bool UnderRuntimeAssumptions=false)
depends - Tests for a dependence between the Src and Dst instructions.
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This class represents a freeze function that returns random concrete value if an operand is either a ...
static LLVM_ABI bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, ArrayRef< const SCEVPredicate * > NoWrapPreds={}, const SCEV *Expr=nullptr, SmallVectorImpl< Instruction * > *CastsToIgnore=nullptr)
Returns true if Phi is an induction in the loop L.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void moveAfter(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
void removeBlockFromLoop(BlockT *BB)
This removes the specified basic block from the current loop, updating the Blocks as appropriate.
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
BlockT * getHeader() const
iterator_range< block_iterator > blocks() const
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
void addBlockEntry(BlockT *BB)
This adds a basic block directly to the basic block list.
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
iterator begin() const
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
void changeTopLevelLoop(LoopT *OldLoop, LoopT *NewLoop)
Replace the specified loop in the top-level loops list with the indicated loop.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
void changeLoopFor(const BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
This class represents a loop nest and can be used to query its properties.
static const BasicBlock & skipEmptyBlockUntil(const BasicBlock *From, const BasicBlock *End, bool CheckUniquePred=false)
Recursivelly traverse all empty 'single successor' basic blocks of From (if there are any).
ArrayRef< Loop * > getLoops() const
Get the loops in the nest.
Function * getParent() const
Return the function to which the loop-nest belongs.
Loop & getOutermostLoop() const
Return the outermost loop in the loop nest.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:695
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:67
StringRef getName() const
Definition LoopInfo.h:415
Diagnostic information for optimization analysis remarks.
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
bool isComplete() const
If the PHI node is complete which means all of its parent's predecessors have incoming value in this ...
op_range incoming_values()
void setIncomingBlock(unsigned i, BasicBlock *BB)
void setIncomingValue(unsigned i, Value *V)
static unsigned getIncomingValueNumForOperand(unsigned i)
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Instruction * getExactFPMathInst() const
Returns 1st non-reassociative FP instruction in the PHI node's use-chain.
static LLVM_ABI bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr, ScalarEvolution *SE=nullptr)
Returns true if Phi is a reduction in TheLoop.
bool hasUsesOutsideReductionChain() const
Returns true if the reduction PHI has any uses outside the reduction chain.
LLVM_ABI SmallVector< Instruction *, 4 > getReductionOpChain(PHINode *Phi, Loop *L) const
Attempts to find a chain of operations from Phi to LoopExitInst that can be treated as a set of reduc...
RecurKind getRecurrenceKind() const
This node represents a polynomial recurrence on the trip count of the specified loop.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class represents an analyzed expression in the program.
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
The main scalar evolution driver.
LLVM_ABI const SCEV * getAbsExpr(const SCEV *Op, bool IsNSW)
LLVM_ABI 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...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI 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...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&...Args)
Emplace a new element for the specified key into the map if the key isn't already in the map.
Definition StringMap.h:370
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
Definition Value.cpp:163
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI User * getUniqueUndroppableUser()
Return true if there is exactly one unique user of this value that cannot be dropped (that user can h...
Definition Value.cpp:185
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
list_initializer< Ty > list_init(ArrayRef< Ty > Vals)
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI BasicBlock * InsertPreheaderForLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
InsertPreheaderForLoop - Once we discover that a loop doesn't have a preheader, this method is called...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
InstructionCost Cost
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
auto successors(const MachineBasicBlock *BB)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition LCSSA.cpp:469
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2173
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:365
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:2026
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:322
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ FMinimumNum
FP min with llvm.minimumnum semantics.
@ Or
Bitwise or logical OR of integers.
@ FMinimum
FP min with llvm.minimum semantics.
@ Mul
Product of integers.
@ AnyOf
AnyOf reduction with select(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ Xor
Bitwise or logical XOR of integers.
@ FMax
FP max implemented in terms of select(cmp()).
@ FMaximum
FP max with llvm.maximum semantics.
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
@ FMul
Product of floats.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ And
Bitwise or logical AND of integers.
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ FMin
FP min implemented in terms of select(cmp()).
@ Add
Sum of integers.
@ FAdd
Sum of floats.
@ FMaximumNum
FP max with llvm.maximumnum semantics.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2012
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool formLCSSAForInstructions(SmallVectorImpl< Instruction * > &Worklist, const DominatorTree &DT, const LoopInfo &LI, ScalarEvolution *SE, SmallVectorImpl< PHINode * > *PHIsToRemove=nullptr, SmallVectorImpl< PHINode * > *InsertedPHIs=nullptr)
Ensures LCSSA form for every instruction from the Worklist in the scope of innermost containing loop.
Definition LCSSA.cpp:328
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2166
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
LLVM_ABI PreservedAnalyses run(LoopNest &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...