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