xref: /llvm-project/llvm/lib/Target/ARM/ARMLowOverheadLoops.cpp (revision 42350cd893a9cf6c199b17441dc2ba526c7cca71)
1 //===-- ARMLowOverheadLoops.cpp - CodeGen Low-overhead Loops ---*- C++ -*-===//
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 /// \file
9 /// Finalize v8.1-m low-overhead loops by converting the associated pseudo
10 /// instructions into machine operations.
11 /// The expectation is that the loop contains three pseudo instructions:
12 /// - t2*LoopStart - placed in the preheader or pre-preheader. The do-loop
13 ///   form should be in the preheader, whereas the while form should be in the
14 ///   preheaders only predecessor.
15 /// - t2LoopDec - placed within in the loop body.
16 /// - t2LoopEnd - the loop latch terminator.
17 ///
18 /// In addition to this, we also look for the presence of the VCTP instruction,
19 /// which determines whether we can generated the tail-predicated low-overhead
20 /// loop form.
21 ///
22 /// Assumptions and Dependencies:
23 /// Low-overhead loops are constructed and executed using a setup instruction:
24 /// DLS, WLS, DLSTP or WLSTP and an instruction that loops back: LE or LETP.
25 /// WLS(TP) and LE(TP) are branching instructions with a (large) limited range
26 /// but fixed polarity: WLS can only branch forwards and LE can only branch
27 /// backwards. These restrictions mean that this pass is dependent upon block
28 /// layout and block sizes, which is why it's the last pass to run. The same is
29 /// true for ConstantIslands, but this pass does not increase the size of the
30 /// basic blocks, nor does it change the CFG. Instructions are mainly removed
31 /// during the transform and pseudo instructions are replaced by real ones. In
32 /// some cases, when we have to revert to a 'normal' loop, we have to introduce
33 /// multiple instructions for a single pseudo (see RevertWhile and
34 /// RevertLoopEnd). To handle this situation, t2WhileLoopStart and t2LoopEnd
35 /// are defined to be as large as this maximum sequence of replacement
36 /// instructions.
37 ///
38 //===----------------------------------------------------------------------===//
39 
40 #include "ARM.h"
41 #include "ARMBaseInstrInfo.h"
42 #include "ARMBaseRegisterInfo.h"
43 #include "ARMBasicBlockInfo.h"
44 #include "ARMSubtarget.h"
45 #include "Thumb2InstrInfo.h"
46 #include "llvm/ADT/SetOperations.h"
47 #include "llvm/ADT/SmallSet.h"
48 #include "llvm/CodeGen/LivePhysRegs.h"
49 #include "llvm/CodeGen/MachineFunctionPass.h"
50 #include "llvm/CodeGen/MachineLoopInfo.h"
51 #include "llvm/CodeGen/MachineLoopUtils.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/Passes.h"
54 #include "llvm/CodeGen/ReachingDefAnalysis.h"
55 #include "llvm/MC/MCInstrDesc.h"
56 
57 using namespace llvm;
58 
59 #define DEBUG_TYPE "arm-low-overhead-loops"
60 #define ARM_LOW_OVERHEAD_LOOPS_NAME "ARM Low Overhead Loops pass"
61 
62 namespace {
63 
64   class PostOrderLoopTraversal {
65     MachineLoop &ML;
66     MachineLoopInfo &MLI;
67     SmallPtrSet<MachineBasicBlock*, 4> Visited;
68     SmallVector<MachineBasicBlock*, 4> Order;
69 
70   public:
71     PostOrderLoopTraversal(MachineLoop &ML, MachineLoopInfo &MLI)
72       : ML(ML), MLI(MLI) { }
73 
74     const SmallVectorImpl<MachineBasicBlock*> &getOrder() const {
75       return Order;
76     }
77 
78     // Visit all the blocks within the loop, as well as exit blocks and any
79     // blocks properly dominating the header.
80     void ProcessLoop() {
81       std::function<void(MachineBasicBlock*)> Search = [this, &Search]
82         (MachineBasicBlock *MBB) -> void {
83         if (Visited.count(MBB))
84           return;
85 
86         Visited.insert(MBB);
87         for (auto *Succ : MBB->successors()) {
88           if (!ML.contains(Succ))
89             continue;
90           Search(Succ);
91         }
92         Order.push_back(MBB);
93       };
94 
95       // Insert exit blocks.
96       SmallVector<MachineBasicBlock*, 2> ExitBlocks;
97       ML.getExitBlocks(ExitBlocks);
98       for (auto *MBB : ExitBlocks)
99         Order.push_back(MBB);
100 
101       // Then add the loop body.
102       Search(ML.getHeader());
103 
104       // Then try the preheader and its predecessors.
105       std::function<void(MachineBasicBlock*)> GetPredecessor =
106         [this, &GetPredecessor] (MachineBasicBlock *MBB) -> void {
107         Order.push_back(MBB);
108         if (MBB->pred_size() == 1)
109           GetPredecessor(*MBB->pred_begin());
110       };
111 
112       if (auto *Preheader = ML.getLoopPreheader())
113         GetPredecessor(Preheader);
114       else if (auto *Preheader = MLI.findLoopPreheader(&ML, true))
115         GetPredecessor(Preheader);
116     }
117   };
118 
119   struct PredicatedMI {
120     MachineInstr *MI = nullptr;
121     SetVector<MachineInstr*> Predicates;
122 
123   public:
124     PredicatedMI(MachineInstr *I, SetVector<MachineInstr*> &Preds) :
125       MI(I) { Predicates.insert(Preds.begin(), Preds.end()); }
126   };
127 
128   // Represent a VPT block, a list of instructions that begins with a VPST and
129   // has a maximum of four proceeding instructions. All instructions within the
130   // block are predicated upon the vpr and we allow instructions to define the
131   // vpr within in the block too.
132   class VPTBlock {
133     std::unique_ptr<PredicatedMI> VPST;
134     PredicatedMI *Divergent = nullptr;
135     SmallVector<PredicatedMI, 4> Insts;
136 
137   public:
138     VPTBlock(MachineInstr *MI, SetVector<MachineInstr*> &Preds) {
139       VPST = std::make_unique<PredicatedMI>(MI, Preds);
140     }
141 
142     void addInst(MachineInstr *MI, SetVector<MachineInstr*> &Preds) {
143       LLVM_DEBUG(dbgs() << "ARM Loops: Adding predicated MI: " << *MI);
144       if (!Divergent && !set_difference(Preds, VPST->Predicates).empty()) {
145         Divergent = &Insts.back();
146         LLVM_DEBUG(dbgs() << " - has divergent predicate: " << *Divergent->MI);
147       }
148       Insts.emplace_back(MI, Preds);
149       assert(Insts.size() <= 4 && "Too many instructions in VPT block!");
150     }
151 
152     // Have we found an instruction within the block which defines the vpr? If
153     // so, not all the instructions in the block will have the same predicate.
154     bool HasNonUniformPredicate() const {
155       return Divergent != nullptr;
156     }
157 
158     // Is the given instruction part of the predicate set controlling the entry
159     // to the block.
160     bool IsPredicatedOn(MachineInstr *MI) const {
161       return VPST->Predicates.count(MI);
162     }
163 
164     // Is the given instruction the only predicate which controls the entry to
165     // the block.
166     bool IsOnlyPredicatedOn(MachineInstr *MI) const {
167       return IsPredicatedOn(MI) && VPST->Predicates.size() == 1;
168     }
169 
170     unsigned size() const { return Insts.size(); }
171     SmallVectorImpl<PredicatedMI> &getInsts() { return Insts; }
172     MachineInstr *getVPST() const { return VPST->MI; }
173     PredicatedMI *getDivergent() const { return Divergent; }
174   };
175 
176   struct LowOverheadLoop {
177 
178     MachineLoop *ML = nullptr;
179     MachineFunction *MF = nullptr;
180     MachineInstr *InsertPt = nullptr;
181     MachineInstr *Start = nullptr;
182     MachineInstr *Dec = nullptr;
183     MachineInstr *End = nullptr;
184     MachineInstr *VCTP = nullptr;
185     VPTBlock *CurrentBlock = nullptr;
186     SetVector<MachineInstr*> CurrentPredicate;
187     SmallVector<VPTBlock, 4> VPTBlocks;
188     SmallPtrSet<MachineInstr*, 4> ToRemove;
189     bool Revert = false;
190     bool CannotTailPredicate = false;
191 
192     LowOverheadLoop(MachineLoop *ML) : ML(ML) {
193       MF = ML->getHeader()->getParent();
194     }
195 
196     // If this is an MVE instruction, check that we know how to use tail
197     // predication with it. Record VPT blocks and return whether the
198     // instruction is valid for tail predication.
199     bool ValidateMVEInst(MachineInstr *MI);
200 
201     void AnalyseMVEInst(MachineInstr *MI) {
202       CannotTailPredicate = !ValidateMVEInst(MI);
203     }
204 
205     bool IsTailPredicationLegal() const {
206       // For now, let's keep things really simple and only support a single
207       // block for tail predication.
208       return !Revert && FoundAllComponents() && VCTP &&
209              !CannotTailPredicate && ML->getNumBlocks() == 1;
210     }
211 
212     bool ValidateTailPredicate(MachineInstr *StartInsertPt,
213                                ReachingDefAnalysis *RDA,
214                                MachineLoopInfo *MLI);
215 
216     // Is it safe to define LR with DLS/WLS?
217     // LR can be defined if it is the operand to start, because it's the same
218     // value, or if it's going to be equivalent to the operand to Start.
219     MachineInstr *IsSafeToDefineLR(ReachingDefAnalysis *RDA);
220 
221     // Check the branch targets are within range and we satisfy our
222     // restrictions.
223     void CheckLegality(ARMBasicBlockUtils *BBUtils, ReachingDefAnalysis *RDA,
224                        MachineLoopInfo *MLI);
225 
226     bool FoundAllComponents() const {
227       return Start && Dec && End;
228     }
229 
230     SmallVectorImpl<VPTBlock> &getVPTBlocks() { return VPTBlocks; }
231 
232     // Return the loop iteration count, or the number of elements if we're tail
233     // predicating.
234     MachineOperand &getCount() {
235       return IsTailPredicationLegal() ?
236         VCTP->getOperand(1) : Start->getOperand(0);
237     }
238 
239     unsigned getStartOpcode() const {
240       bool IsDo = Start->getOpcode() == ARM::t2DoLoopStart;
241       if (!IsTailPredicationLegal())
242         return IsDo ? ARM::t2DLS : ARM::t2WLS;
243 
244       return VCTPOpcodeToLSTP(VCTP->getOpcode(), IsDo);
245     }
246 
247     void dump() const {
248       if (Start) dbgs() << "ARM Loops: Found Loop Start: " << *Start;
249       if (Dec) dbgs() << "ARM Loops: Found Loop Dec: " << *Dec;
250       if (End) dbgs() << "ARM Loops: Found Loop End: " << *End;
251       if (VCTP) dbgs() << "ARM Loops: Found VCTP: " << *VCTP;
252       if (!FoundAllComponents())
253         dbgs() << "ARM Loops: Not a low-overhead loop.\n";
254       else if (!(Start && Dec && End))
255         dbgs() << "ARM Loops: Failed to find all loop components.\n";
256     }
257   };
258 
259   class ARMLowOverheadLoops : public MachineFunctionPass {
260     MachineFunction           *MF = nullptr;
261     MachineLoopInfo           *MLI = nullptr;
262     ReachingDefAnalysis       *RDA = nullptr;
263     const ARMBaseInstrInfo    *TII = nullptr;
264     MachineRegisterInfo       *MRI = nullptr;
265     const TargetRegisterInfo  *TRI = nullptr;
266     std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr;
267 
268   public:
269     static char ID;
270 
271     ARMLowOverheadLoops() : MachineFunctionPass(ID) { }
272 
273     void getAnalysisUsage(AnalysisUsage &AU) const override {
274       AU.setPreservesCFG();
275       AU.addRequired<MachineLoopInfo>();
276       AU.addRequired<ReachingDefAnalysis>();
277       MachineFunctionPass::getAnalysisUsage(AU);
278     }
279 
280     bool runOnMachineFunction(MachineFunction &MF) override;
281 
282     MachineFunctionProperties getRequiredProperties() const override {
283       return MachineFunctionProperties().set(
284           MachineFunctionProperties::Property::NoVRegs).set(
285           MachineFunctionProperties::Property::TracksLiveness);
286     }
287 
288     StringRef getPassName() const override {
289       return ARM_LOW_OVERHEAD_LOOPS_NAME;
290     }
291 
292   private:
293     bool ProcessLoop(MachineLoop *ML);
294 
295     bool RevertNonLoops();
296 
297     void RevertWhile(MachineInstr *MI) const;
298 
299     bool RevertLoopDec(MachineInstr *MI, bool AllowFlags = false) const;
300 
301     void RevertLoopEnd(MachineInstr *MI, bool SkipCmp = false) const;
302 
303     void ConvertVPTBlocks(LowOverheadLoop &LoLoop);
304 
305     MachineInstr *ExpandLoopStart(LowOverheadLoop &LoLoop);
306 
307     void Expand(LowOverheadLoop &LoLoop);
308 
309   };
310 }
311 
312 char ARMLowOverheadLoops::ID = 0;
313 
314 INITIALIZE_PASS(ARMLowOverheadLoops, DEBUG_TYPE, ARM_LOW_OVERHEAD_LOOPS_NAME,
315                 false, false)
316 
317 MachineInstr *LowOverheadLoop::IsSafeToDefineLR(ReachingDefAnalysis *RDA) {
318   // We can define LR because LR already contains the same value.
319   if (Start->getOperand(0).getReg() == ARM::LR)
320     return Start;
321 
322   unsigned CountReg = Start->getOperand(0).getReg();
323   auto IsMoveLR = [&CountReg](MachineInstr *MI) {
324     return MI->getOpcode() == ARM::tMOVr &&
325            MI->getOperand(0).getReg() == ARM::LR &&
326            MI->getOperand(1).getReg() == CountReg &&
327            MI->getOperand(2).getImm() == ARMCC::AL;
328    };
329 
330   MachineBasicBlock *MBB = Start->getParent();
331 
332   // Find an insertion point:
333   // - Is there a (mov lr, Count) before Start? If so, and nothing else writes
334   //   to Count before Start, we can insert at that mov.
335   if (auto *LRDef = RDA->getReachingMIDef(Start, ARM::LR))
336     if (IsMoveLR(LRDef) && RDA->hasSameReachingDef(Start, LRDef, CountReg))
337       return LRDef;
338 
339   // - Is there a (mov lr, Count) after Start? If so, and nothing else writes
340   //   to Count after Start, we can insert at that mov.
341   if (auto *LRDef = RDA->getLocalLiveOutMIDef(MBB, ARM::LR))
342     if (IsMoveLR(LRDef) && RDA->hasSameReachingDef(Start, LRDef, CountReg))
343       return LRDef;
344 
345   // We've found no suitable LR def and Start doesn't use LR directly. Can we
346   // just define LR anyway?
347   if (!RDA->isRegUsedAfter(Start, ARM::LR))
348     return Start;
349 
350   return nullptr;
351 }
352 
353 // Can we safely move 'From' to just before 'To'? To satisfy this, 'From' must
354 // not define a register that is used by any instructions, after and including,
355 // 'To'. These instructions also must not redefine any of Froms operands.
356 template<typename Iterator>
357 static bool IsSafeToMove(MachineInstr *From, MachineInstr *To, ReachingDefAnalysis *RDA) {
358   SmallSet<int, 2> Defs;
359   // First check that From would compute the same value if moved.
360   for (auto &MO : From->operands()) {
361     if (!MO.isReg() || MO.isUndef() || !MO.getReg())
362       continue;
363     if (MO.isDef())
364       Defs.insert(MO.getReg());
365     else if (!RDA->hasSameReachingDef(From, To, MO.getReg()))
366       return false;
367   }
368 
369   // Now walk checking that the rest of the instructions will compute the same
370   // value.
371   for (auto I = ++Iterator(From), E = Iterator(To); I != E; ++I) {
372     for (auto &MO : I->operands())
373       if (MO.isReg() && MO.getReg() && MO.isUse() && Defs.count(MO.getReg()))
374         return false;
375   }
376   return true;
377 }
378 
379 static bool IsSafeToRemove(MachineInstr *MI, ReachingDefAnalysis *RDA,
380                            SmallPtrSetImpl<MachineInstr*> &Visited,
381                            SmallPtrSetImpl<MachineInstr*> &ToRemove,
382                            SmallPtrSetImpl<MachineInstr*> &Ignore) {
383   if (Visited.count(MI) || Ignore.count(MI))
384     return true;
385   else if (MI->mayLoadOrStore() || MI->hasUnmodeledSideEffects() ||
386            MI->isBranch() || MI->isTerminator() || MI->isReturn()) {
387     // Unless told to ignore the instruction, don't remove anything which has
388     // side effects.
389     LLVM_DEBUG(dbgs() << "ARM Loops: Has side effects: " << *MI);
390     return false;
391   }
392 
393   Visited.insert(MI);
394   for (auto &MO : MI->operands()) {
395     if (!MO.isReg() || MO.isUse() || MO.getReg() == 0)
396       continue;
397 
398     SmallPtrSet<MachineInstr*, 4> Uses;
399     RDA->getGlobalUses(MI, MO.getReg(), Uses);
400 
401     for (auto I : Uses) {
402       if (Ignore.count(I) || ToRemove.count(I))
403         continue;
404       if (!IsSafeToRemove(I, RDA, Visited, ToRemove, Ignore)) {
405         LLVM_DEBUG(dbgs() << "ARM Loops: Unable to remove " << *I);
406         return false;
407       }
408     }
409   }
410   ToRemove.insert(MI);
411   LLVM_DEBUG(dbgs() << "ARM Loops: Can remove: " << *MI);
412   return true;
413 }
414 
415 bool LowOverheadLoop::ValidateTailPredicate(MachineInstr *StartInsertPt,
416                                             ReachingDefAnalysis *RDA,
417                                             MachineLoopInfo *MLI) {
418   assert(VCTP && "VCTP instruction expected but is not set");
419   // All predication within the loop should be based on vctp. If the block
420   // isn't predicated on entry, check whether the vctp is within the block
421   // and that all other instructions are then predicated on it.
422   for (auto &Block : VPTBlocks) {
423     if (Block.IsPredicatedOn(VCTP))
424       continue;
425     if (!Block.HasNonUniformPredicate() || !isVCTP(Block.getDivergent()->MI)) {
426       LLVM_DEBUG(dbgs() << "ARM Loops: Found unsupported diverging predicate: "
427                  << *Block.getDivergent()->MI);
428       return false;
429     }
430     SmallVectorImpl<PredicatedMI> &Insts = Block.getInsts();
431     for (auto &PredMI : Insts) {
432       if (PredMI.Predicates.count(VCTP) || isVCTP(PredMI.MI))
433         continue;
434       LLVM_DEBUG(dbgs() << "ARM Loops: Can't convert: " << *PredMI.MI
435                  << " - which is predicated on:\n";
436                  for (auto *MI : PredMI.Predicates)
437                    dbgs() << "   - " << *MI);
438       return false;
439     }
440   }
441 
442   // For tail predication, we need to provide the number of elements, instead
443   // of the iteration count, to the loop start instruction. The number of
444   // elements is provided to the vctp instruction, so we need to check that
445   // we can use this register at InsertPt.
446   Register NumElements = VCTP->getOperand(1).getReg();
447 
448   // If the register is defined within loop, then we can't perform TP.
449   // TODO: Check whether this is just a mov of a register that would be
450   // available.
451   if (RDA->getReachingDef(VCTP, NumElements) >= 0) {
452     LLVM_DEBUG(dbgs() << "ARM Loops: VCTP operand is defined in the loop.\n");
453     return false;
454   }
455 
456   // The element count register maybe defined after InsertPt, in which case we
457   // need to try to move either InsertPt or the def so that the [w|d]lstp can
458   // use the value.
459   MachineBasicBlock *InsertBB = StartInsertPt->getParent();
460   if (!RDA->isReachingDefLiveOut(StartInsertPt, NumElements)) {
461     if (auto *ElemDef = RDA->getLocalLiveOutMIDef(InsertBB, NumElements)) {
462       if (IsSafeToMove<MachineBasicBlock::reverse_iterator>(
463           ElemDef, StartInsertPt, RDA)) {
464         ElemDef->removeFromParent();
465         InsertBB->insert(MachineBasicBlock::iterator(StartInsertPt), ElemDef);
466         LLVM_DEBUG(dbgs() << "ARM Loops: Moved element count def: "
467                    << *ElemDef);
468       } else if (IsSafeToMove<MachineBasicBlock::iterator>(
469           StartInsertPt, ElemDef, RDA)) {
470         StartInsertPt->removeFromParent();
471         InsertBB->insertAfter(MachineBasicBlock::iterator(ElemDef),
472                               StartInsertPt);
473         LLVM_DEBUG(dbgs() << "ARM Loops: Moved start past: " << *ElemDef);
474       } else {
475         LLVM_DEBUG(dbgs() << "ARM Loops: Unable to move element count to loop "
476                    << "start instruction.\n");
477         return false;
478       }
479     }
480   }
481 
482   // Especially in the case of while loops, InsertBB may not be the
483   // preheader, so we need to check that the register isn't redefined
484   // before entering the loop.
485   auto CannotProvideElements = [&RDA](MachineBasicBlock *MBB,
486                                       Register NumElements) {
487     // NumElements is redefined in this block.
488     if (RDA->getReachingDef(&MBB->back(), NumElements) >= 0)
489       return true;
490 
491     // Don't continue searching up through multiple predecessors.
492     if (MBB->pred_size() > 1)
493       return true;
494 
495     return false;
496   };
497 
498   // First, find the block that looks like the preheader.
499   MachineBasicBlock *MBB = MLI->findLoopPreheader(ML, true);
500   if (!MBB) {
501     LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find preheader.\n");
502     return false;
503   }
504 
505   // Then search backwards for a def, until we get to InsertBB.
506   while (MBB != InsertBB) {
507     if (CannotProvideElements(MBB, NumElements)) {
508       LLVM_DEBUG(dbgs() << "ARM Loops: Unable to provide element count.\n");
509       return false;
510     }
511     MBB = *MBB->pred_begin();
512   }
513 
514   // Check that the value change of the element count is what we expect and
515   // that the predication will be equivalent. For this we need:
516   // NumElements = NumElements - VectorWidth. The sub will be a sub immediate
517   // and we can also allow register copies within the chain too.
518   auto IsValidSub = [](MachineInstr *MI, unsigned ExpectedVecWidth) {
519     unsigned ImmOpIdx = 0;
520     switch (MI->getOpcode()) {
521     default:
522       llvm_unreachable("unhandled sub opcode");
523     case ARM::tSUBi3:
524     case ARM::tSUBi8:
525       ImmOpIdx = 3;
526       break;
527     case ARM::t2SUBri:
528     case ARM::t2SUBri12:
529       ImmOpIdx = 2;
530       break;
531     }
532     return MI->getOperand(ImmOpIdx).getImm() == ExpectedVecWidth;
533   };
534 
535   MBB = VCTP->getParent();
536   if (MachineInstr *Def = RDA->getReachingMIDef(&MBB->back(), NumElements)) {
537     SmallPtrSet<MachineInstr*, 2> Visited;
538     SmallPtrSet<MachineInstr*, 2> ElementChain;
539     SmallPtrSet<MachineInstr*, 2> Ignore = { VCTP };
540     unsigned ExpectedVectorWidth = getTailPredVectorWidth(VCTP->getOpcode());
541 
542     if (IsSafeToRemove(Def, RDA, Visited, ElementChain, Ignore)) {
543       bool FoundSub = false;
544 
545       for (auto *MI : ElementChain) {
546         if (isMovRegOpcode(MI->getOpcode()))
547           continue;
548 
549         if (isSubImmOpcode(MI->getOpcode())) {
550           if (FoundSub || !IsValidSub(MI, ExpectedVectorWidth))
551             return false;
552           FoundSub = true;
553         } else
554           return false;
555       }
556 
557       LLVM_DEBUG(dbgs() << "ARM Loops: Will remove element count chain:\n";
558                  for (auto *MI : ElementChain)
559                    dbgs() << " - " << *MI);
560       ToRemove.insert(ElementChain.begin(), ElementChain.end());
561     }
562   }
563   return true;
564 }
565 
566 void LowOverheadLoop::CheckLegality(ARMBasicBlockUtils *BBUtils,
567                                     ReachingDefAnalysis *RDA,
568                                     MachineLoopInfo *MLI) {
569   if (Revert)
570     return;
571 
572   if (!End->getOperand(1).isMBB())
573     report_fatal_error("Expected LoopEnd to target basic block");
574 
575   // TODO Maybe there's cases where the target doesn't have to be the header,
576   // but for now be safe and revert.
577   if (End->getOperand(1).getMBB() != ML->getHeader()) {
578     LLVM_DEBUG(dbgs() << "ARM Loops: LoopEnd is not targetting header.\n");
579     Revert = true;
580     return;
581   }
582 
583   // The WLS and LE instructions have 12-bits for the label offset. WLS
584   // requires a positive offset, while LE uses negative.
585   if (BBUtils->getOffsetOf(End) < BBUtils->getOffsetOf(ML->getHeader()) ||
586       !BBUtils->isBBInRange(End, ML->getHeader(), 4094)) {
587     LLVM_DEBUG(dbgs() << "ARM Loops: LE offset is out-of-range\n");
588     Revert = true;
589     return;
590   }
591 
592   if (Start->getOpcode() == ARM::t2WhileLoopStart &&
593       (BBUtils->getOffsetOf(Start) >
594        BBUtils->getOffsetOf(Start->getOperand(1).getMBB()) ||
595        !BBUtils->isBBInRange(Start, Start->getOperand(1).getMBB(), 4094))) {
596     LLVM_DEBUG(dbgs() << "ARM Loops: WLS offset is out-of-range!\n");
597     Revert = true;
598     return;
599   }
600 
601   InsertPt = Revert ? nullptr : IsSafeToDefineLR(RDA);
602   if (!InsertPt) {
603     LLVM_DEBUG(dbgs() << "ARM Loops: Unable to find safe insertion point.\n");
604     Revert = true;
605     return;
606   } else
607     LLVM_DEBUG(dbgs() << "ARM Loops: Start insertion point: " << *InsertPt);
608 
609   if (!IsTailPredicationLegal()) {
610     LLVM_DEBUG(if (!VCTP)
611                  dbgs() << "ARM Loops: Didn't find a VCTP instruction.\n";
612                dbgs() << "ARM Loops: Tail-predication is not valid.\n");
613     return;
614   }
615 
616   assert(ML->getBlocks().size() == 1 &&
617          "Shouldn't be processing a loop with more than one block");
618   CannotTailPredicate = !ValidateTailPredicate(InsertPt, RDA, MLI);
619   LLVM_DEBUG(if (CannotTailPredicate)
620              dbgs() << "ARM Loops: Couldn't validate tail predicate.\n");
621 }
622 
623 bool LowOverheadLoop::ValidateMVEInst(MachineInstr* MI) {
624   if (CannotTailPredicate)
625     return false;
626 
627   // Only support a single vctp.
628   if (isVCTP(MI) && VCTP)
629     return false;
630 
631   // Start a new vpt block when we discover a vpt.
632   if (MI->getOpcode() == ARM::MVE_VPST) {
633     VPTBlocks.emplace_back(MI, CurrentPredicate);
634     CurrentBlock = &VPTBlocks.back();
635     return true;
636   } else if (isVCTP(MI))
637     VCTP = MI;
638   else if (MI->getOpcode() == ARM::MVE_VPSEL ||
639            MI->getOpcode() == ARM::MVE_VPNOT)
640     return false;
641 
642   // TODO: Allow VPSEL and VPNOT, we currently cannot because:
643   // 1) It will use the VPR as a predicate operand, but doesn't have to be
644   //    instead a VPT block, which means we can assert while building up
645   //    the VPT block because we don't find another VPST to being a new
646   //    one.
647   // 2) VPSEL still requires a VPR operand even after tail predicating,
648   //    which means we can't remove it unless there is another
649   //    instruction, such as vcmp, that can provide the VPR def.
650 
651   bool IsUse = false;
652   bool IsDef = false;
653   const MCInstrDesc &MCID = MI->getDesc();
654   for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
655     const MachineOperand &MO = MI->getOperand(i);
656     if (!MO.isReg() || MO.getReg() != ARM::VPR)
657       continue;
658 
659     if (MO.isDef()) {
660       CurrentPredicate.insert(MI);
661       IsDef = true;
662     } else if (ARM::isVpred(MCID.OpInfo[i].OperandType)) {
663       CurrentBlock->addInst(MI, CurrentPredicate);
664       IsUse = true;
665     } else {
666       LLVM_DEBUG(dbgs() << "ARM Loops: Found instruction using vpr: " << *MI);
667       return false;
668     }
669   }
670 
671   // If we find a vpr def that is not already predicated on the vctp, we've
672   // got disjoint predicates that may not be equivalent when we do the
673   // conversion.
674   if (IsDef && !IsUse && VCTP && !isVCTP(MI)) {
675     LLVM_DEBUG(dbgs() << "ARM Loops: Found disjoint vpr def: " << *MI);
676     return false;
677   }
678 
679   uint64_t Flags = MCID.TSFlags;
680   if ((Flags & ARMII::DomainMask) != ARMII::DomainMVE)
681     return true;
682 
683   // If we find an instruction that has been marked as not valid for tail
684   // predication, only allow the instruction if it's contained within a valid
685   // VPT block.
686   if ((Flags & ARMII::ValidForTailPredication) == 0 && !IsUse) {
687     LLVM_DEBUG(dbgs() << "ARM Loops: Can't tail predicate: " << *MI);
688     return false;
689   }
690 
691   return true;
692 }
693 
694 bool ARMLowOverheadLoops::runOnMachineFunction(MachineFunction &mf) {
695   const ARMSubtarget &ST = static_cast<const ARMSubtarget&>(mf.getSubtarget());
696   if (!ST.hasLOB())
697     return false;
698 
699   MF = &mf;
700   LLVM_DEBUG(dbgs() << "ARM Loops on " << MF->getName() << " ------------- \n");
701 
702   MLI = &getAnalysis<MachineLoopInfo>();
703   RDA = &getAnalysis<ReachingDefAnalysis>();
704   MF->getProperties().set(MachineFunctionProperties::Property::TracksLiveness);
705   MRI = &MF->getRegInfo();
706   TII = static_cast<const ARMBaseInstrInfo*>(ST.getInstrInfo());
707   TRI = ST.getRegisterInfo();
708   BBUtils = std::unique_ptr<ARMBasicBlockUtils>(new ARMBasicBlockUtils(*MF));
709   BBUtils->computeAllBlockSizes();
710   BBUtils->adjustBBOffsetsAfter(&MF->front());
711 
712   bool Changed = false;
713   for (auto ML : *MLI) {
714     if (!ML->getParentLoop())
715       Changed |= ProcessLoop(ML);
716   }
717   Changed |= RevertNonLoops();
718   return Changed;
719 }
720 
721 bool ARMLowOverheadLoops::ProcessLoop(MachineLoop *ML) {
722 
723   bool Changed = false;
724 
725   // Process inner loops first.
726   for (auto I = ML->begin(), E = ML->end(); I != E; ++I)
727     Changed |= ProcessLoop(*I);
728 
729   LLVM_DEBUG(dbgs() << "ARM Loops: Processing loop containing:\n";
730              if (auto *Preheader = ML->getLoopPreheader())
731                dbgs() << " - " << Preheader->getName() << "\n";
732              else if (auto *Preheader = MLI->findLoopPreheader(ML))
733                dbgs() << " - " << Preheader->getName() << "\n";
734              else if (auto *Preheader = MLI->findLoopPreheader(ML, true))
735                dbgs() << " - " << Preheader->getName() << "\n";
736              for (auto *MBB : ML->getBlocks())
737                dbgs() << " - " << MBB->getName() << "\n";
738             );
739 
740   // Search the given block for a loop start instruction. If one isn't found,
741   // and there's only one predecessor block, search that one too.
742   std::function<MachineInstr*(MachineBasicBlock*)> SearchForStart =
743     [&SearchForStart](MachineBasicBlock *MBB) -> MachineInstr* {
744     for (auto &MI : *MBB) {
745       if (isLoopStart(MI))
746         return &MI;
747     }
748     if (MBB->pred_size() == 1)
749       return SearchForStart(*MBB->pred_begin());
750     return nullptr;
751   };
752 
753   LowOverheadLoop LoLoop(ML);
754   // Search the preheader for the start intrinsic.
755   // FIXME: I don't see why we shouldn't be supporting multiple predecessors
756   // with potentially multiple set.loop.iterations, so we need to enable this.
757   if (auto *Preheader = ML->getLoopPreheader())
758     LoLoop.Start = SearchForStart(Preheader);
759   else if (auto *Preheader = MLI->findLoopPreheader(ML, true))
760     LoLoop.Start = SearchForStart(Preheader);
761   else
762     return false;
763 
764   // Find the low-overhead loop components and decide whether or not to fall
765   // back to a normal loop. Also look for a vctp instructions and decide
766   // whether we can convert that predicate using tail predication.
767   for (auto *MBB : reverse(ML->getBlocks())) {
768     for (auto &MI : *MBB) {
769       if (MI.getOpcode() == ARM::t2LoopDec)
770         LoLoop.Dec = &MI;
771       else if (MI.getOpcode() == ARM::t2LoopEnd)
772         LoLoop.End = &MI;
773       else if (isLoopStart(MI))
774         LoLoop.Start = &MI;
775       else if (MI.getDesc().isCall()) {
776         // TODO: Though the call will require LE to execute again, does this
777         // mean we should revert? Always executing LE hopefully should be
778         // faster than performing a sub,cmp,br or even subs,br.
779         LoLoop.Revert = true;
780         LLVM_DEBUG(dbgs() << "ARM Loops: Found call.\n");
781       } else {
782         // Record VPR defs and build up their corresponding vpt blocks.
783         // Check we know how to tail predicate any mve instructions.
784         LoLoop.AnalyseMVEInst(&MI);
785       }
786     }
787   }
788 
789   LLVM_DEBUG(LoLoop.dump());
790   if (!LoLoop.FoundAllComponents()) {
791     LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find loop start, update, end\n");
792     return false;
793   }
794 
795   SmallPtrSet<MachineInstr*, 2> Visited;
796   SmallPtrSet<MachineInstr*, 2> Ignore = { LoLoop.End };
797   SmallPtrSet<MachineInstr*, 4> Remove;
798   if (!IsSafeToRemove(LoLoop.Dec, RDA, Visited, Remove, Ignore)) {
799     LLVM_DEBUG(dbgs() << "ARM Loops: Unable to remove loop count chain.\n");
800     LoLoop.Revert = true;
801   } else {
802     LLVM_DEBUG(dbgs() << "ARM Loops: Will need to remove:\n";
803                for (auto *I : Remove)
804                  dbgs() << " - " << *I);
805     LoLoop.ToRemove.insert(Remove.begin(), Remove.end());
806   }
807 
808   LoLoop.CheckLegality(BBUtils.get(), RDA, MLI);
809   Expand(LoLoop);
810   return true;
811 }
812 
813 // WhileLoopStart holds the exit block, so produce a cmp lr, 0 and then a
814 // beq that branches to the exit branch.
815 // TODO: We could also try to generate a cbz if the value in LR is also in
816 // another low register.
817 void ARMLowOverheadLoops::RevertWhile(MachineInstr *MI) const {
818   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp: " << *MI);
819   MachineBasicBlock *MBB = MI->getParent();
820   MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
821                                     TII->get(ARM::t2CMPri));
822   MIB.add(MI->getOperand(0));
823   MIB.addImm(0);
824   MIB.addImm(ARMCC::AL);
825   MIB.addReg(ARM::NoRegister);
826 
827   MachineBasicBlock *DestBB = MI->getOperand(1).getMBB();
828   unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
829     ARM::tBcc : ARM::t2Bcc;
830 
831   MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc));
832   MIB.add(MI->getOperand(1));   // branch target
833   MIB.addImm(ARMCC::EQ);        // condition code
834   MIB.addReg(ARM::CPSR);
835   MI->eraseFromParent();
836 }
837 
838 bool ARMLowOverheadLoops::RevertLoopDec(MachineInstr *MI,
839                                         bool SetFlags) const {
840   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to sub: " << *MI);
841   MachineBasicBlock *MBB = MI->getParent();
842 
843   // If nothing defines CPSR between LoopDec and LoopEnd, use a t2SUBS.
844   if (SetFlags &&
845       (RDA->isRegUsedAfter(MI, ARM::CPSR) ||
846        !RDA->hasSameReachingDef(MI, &MBB->back(), ARM::CPSR)))
847       SetFlags = false;
848 
849   MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
850                                     TII->get(ARM::t2SUBri));
851   MIB.addDef(ARM::LR);
852   MIB.add(MI->getOperand(1));
853   MIB.add(MI->getOperand(2));
854   MIB.addImm(ARMCC::AL);
855   MIB.addReg(0);
856 
857   if (SetFlags) {
858     MIB.addReg(ARM::CPSR);
859     MIB->getOperand(5).setIsDef(true);
860   } else
861     MIB.addReg(0);
862 
863   MI->eraseFromParent();
864   return SetFlags;
865 }
866 
867 // Generate a subs, or sub and cmp, and a branch instead of an LE.
868 void ARMLowOverheadLoops::RevertLoopEnd(MachineInstr *MI, bool SkipCmp) const {
869   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp, br: " << *MI);
870 
871   MachineBasicBlock *MBB = MI->getParent();
872   // Create cmp
873   if (!SkipCmp) {
874     MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
875                                       TII->get(ARM::t2CMPri));
876     MIB.addReg(ARM::LR);
877     MIB.addImm(0);
878     MIB.addImm(ARMCC::AL);
879     MIB.addReg(ARM::NoRegister);
880   }
881 
882   MachineBasicBlock *DestBB = MI->getOperand(1).getMBB();
883   unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
884     ARM::tBcc : ARM::t2Bcc;
885 
886   // Create bne
887   MachineInstrBuilder MIB =
888     BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc));
889   MIB.add(MI->getOperand(1));   // branch target
890   MIB.addImm(ARMCC::NE);        // condition code
891   MIB.addReg(ARM::CPSR);
892   MI->eraseFromParent();
893 }
894 
895 MachineInstr* ARMLowOverheadLoops::ExpandLoopStart(LowOverheadLoop &LoLoop) {
896   LLVM_DEBUG(dbgs() << "ARM Loops: Expanding LoopStart.\n");
897   // When using tail-predication, try to delete the dead code that was used to
898   // calculate the number of loop iterations.
899   if (LoLoop.IsTailPredicationLegal()) {
900     SmallVector<MachineInstr*, 4> Killed;
901     SmallVector<MachineInstr*, 4> Dead;
902     if (auto *Def = RDA->getReachingMIDef(LoLoop.Start,
903                                       LoLoop.Start->getOperand(0).getReg())) {
904       SmallPtrSet<MachineInstr*, 4> Visited;
905       SmallPtrSet<MachineInstr*, 4> Remove;
906       SmallPtrSet<MachineInstr*, 4> Ignore = { LoLoop.Start, LoLoop.Dec,
907                                                LoLoop.End, LoLoop.VCTP,
908                                                LoLoop.InsertPt };
909       SmallVector<MachineInstr*, 4> Chain = { Def };
910       while (!Chain.empty()) {
911         MachineInstr *MI = Chain.back();
912         Chain.pop_back();
913         if (IsSafeToRemove(MI, RDA, Visited, Remove, Ignore)) {
914           for (auto &MO : MI->operands()) {
915             if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0)
916               continue;
917             if (auto *Op = RDA->getReachingMIDef(MI, MO.getReg()))
918               Chain.push_back(Op);
919           }
920           Ignore.insert(MI);
921         }
922       }
923       LoLoop.ToRemove.insert(Remove.begin(), Remove.end());
924     }
925   }
926 
927   MachineInstr *InsertPt = LoLoop.InsertPt;
928   MachineInstr *Start = LoLoop.Start;
929   MachineBasicBlock *MBB = InsertPt->getParent();
930   bool IsDo = Start->getOpcode() == ARM::t2DoLoopStart;
931   unsigned Opc = LoLoop.getStartOpcode();
932   MachineOperand &Count = LoLoop.getCount();
933 
934   MachineInstrBuilder MIB =
935     BuildMI(*MBB, InsertPt, InsertPt->getDebugLoc(), TII->get(Opc));
936 
937   MIB.addDef(ARM::LR);
938   MIB.add(Count);
939   if (!IsDo)
940     MIB.add(Start->getOperand(1));
941 
942   // If we're inserting at a mov lr, then remove it as it's redundant.
943   if (InsertPt != Start)
944     LoLoop.ToRemove.insert(InsertPt);
945   LoLoop.ToRemove.insert(Start);
946   LLVM_DEBUG(dbgs() << "ARM Loops: Inserted start: " << *MIB);
947   return &*MIB;
948 }
949 
950 void ARMLowOverheadLoops::ConvertVPTBlocks(LowOverheadLoop &LoLoop) {
951   auto RemovePredicate = [](MachineInstr *MI) {
952     LLVM_DEBUG(dbgs() << "ARM Loops: Removing predicate from: " << *MI);
953     if (int PIdx = llvm::findFirstVPTPredOperandIdx(*MI)) {
954       assert(MI->getOperand(PIdx).getImm() == ARMVCC::Then &&
955              "Expected Then predicate!");
956       MI->getOperand(PIdx).setImm(ARMVCC::None);
957       MI->getOperand(PIdx+1).setReg(0);
958     } else
959       llvm_unreachable("trying to unpredicate a non-predicated instruction");
960   };
961 
962   // There are a few scenarios which we have to fix up:
963   // 1) A VPT block with is only predicated by the vctp and has no internal vpr
964   //    defs.
965   // 2) A VPT block which is only predicated by the vctp but has an internal
966   //    vpr def.
967   // 3) A VPT block which is predicated upon the vctp as well as another vpr
968   //    def.
969   // 4) A VPT block which is not predicated upon a vctp, but contains it and
970   //    all instructions within the block are predicated upon in.
971 
972   for (auto &Block : LoLoop.getVPTBlocks()) {
973     SmallVectorImpl<PredicatedMI> &Insts = Block.getInsts();
974     if (Block.HasNonUniformPredicate()) {
975       PredicatedMI *Divergent = Block.getDivergent();
976       if (isVCTP(Divergent->MI)) {
977         // The vctp will be removed, so the size of the vpt block needs to be
978         // modified.
979         uint64_t Size = getARMVPTBlockMask(Block.size() - 1);
980         Block.getVPST()->getOperand(0).setImm(Size);
981         LLVM_DEBUG(dbgs() << "ARM Loops: Modified VPT block mask.\n");
982       } else if (Block.IsOnlyPredicatedOn(LoLoop.VCTP)) {
983         // The VPT block has a non-uniform predicate but it's entry is guarded
984         // only by a vctp, which means we:
985         // - Need to remove the original vpst.
986         // - Then need to unpredicate any following instructions, until
987         //   we come across the divergent vpr def.
988         // - Insert a new vpst to predicate the instruction(s) that following
989         //   the divergent vpr def.
990         // TODO: We could be producing more VPT blocks than necessary and could
991         // fold the newly created one into a proceeding one.
992         for (auto I = ++MachineBasicBlock::iterator(Block.getVPST()),
993              E = ++MachineBasicBlock::iterator(Divergent->MI); I != E; ++I)
994           RemovePredicate(&*I);
995 
996         unsigned Size = 0;
997         auto E = MachineBasicBlock::reverse_iterator(Divergent->MI);
998         auto I = MachineBasicBlock::reverse_iterator(Insts.back().MI);
999         MachineInstr *InsertAt = nullptr;
1000         while (I != E) {
1001           InsertAt = &*I;
1002           ++Size;
1003           ++I;
1004         }
1005         MachineInstrBuilder MIB = BuildMI(*InsertAt->getParent(), InsertAt,
1006                                           InsertAt->getDebugLoc(),
1007                                           TII->get(ARM::MVE_VPST));
1008         MIB.addImm(getARMVPTBlockMask(Size));
1009         LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *Block.getVPST());
1010         LLVM_DEBUG(dbgs() << "ARM Loops: Created VPST: " << *MIB);
1011         LoLoop.ToRemove.insert(Block.getVPST());
1012       }
1013     } else if (Block.IsOnlyPredicatedOn(LoLoop.VCTP)) {
1014       // A vpt block which is only predicated upon vctp and has no internal vpr
1015       // defs:
1016       // - Remove vpst.
1017       // - Unpredicate the remaining instructions.
1018       LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *Block.getVPST());
1019       LoLoop.ToRemove.insert(Block.getVPST());
1020       for (auto &PredMI : Insts)
1021         RemovePredicate(PredMI.MI);
1022     }
1023   }
1024   LLVM_DEBUG(dbgs() << "ARM Loops: Removing VCTP: " << *LoLoop.VCTP);
1025   LoLoop.ToRemove.insert(LoLoop.VCTP);
1026 }
1027 
1028 void ARMLowOverheadLoops::Expand(LowOverheadLoop &LoLoop) {
1029 
1030   // Combine the LoopDec and LoopEnd instructions into LE(TP).
1031   auto ExpandLoopEnd = [this](LowOverheadLoop &LoLoop) {
1032     MachineInstr *End = LoLoop.End;
1033     MachineBasicBlock *MBB = End->getParent();
1034     unsigned Opc = LoLoop.IsTailPredicationLegal() ?
1035       ARM::MVE_LETP : ARM::t2LEUpdate;
1036     MachineInstrBuilder MIB = BuildMI(*MBB, End, End->getDebugLoc(),
1037                                       TII->get(Opc));
1038     MIB.addDef(ARM::LR);
1039     MIB.add(End->getOperand(0));
1040     MIB.add(End->getOperand(1));
1041     LLVM_DEBUG(dbgs() << "ARM Loops: Inserted LE: " << *MIB);
1042     End->eraseFromParent();
1043     return &*MIB;
1044   };
1045 
1046   // TODO: We should be able to automatically remove these branches before we
1047   // get here - probably by teaching analyzeBranch about the pseudo
1048   // instructions.
1049   // If there is an unconditional branch, after I, that just branches to the
1050   // next block, remove it.
1051   auto RemoveDeadBranch = [](MachineInstr *I) {
1052     MachineBasicBlock *BB = I->getParent();
1053     MachineInstr *Terminator = &BB->instr_back();
1054     if (Terminator->isUnconditionalBranch() && I != Terminator) {
1055       MachineBasicBlock *Succ = Terminator->getOperand(0).getMBB();
1056       if (BB->isLayoutSuccessor(Succ)) {
1057         LLVM_DEBUG(dbgs() << "ARM Loops: Removing branch: " << *Terminator);
1058         Terminator->eraseFromParent();
1059       }
1060     }
1061   };
1062 
1063   if (LoLoop.Revert) {
1064     if (LoLoop.Start->getOpcode() == ARM::t2WhileLoopStart)
1065       RevertWhile(LoLoop.Start);
1066     else
1067       LoLoop.Start->eraseFromParent();
1068     bool FlagsAlreadySet = RevertLoopDec(LoLoop.Dec, true);
1069     RevertLoopEnd(LoLoop.End, FlagsAlreadySet);
1070   } else {
1071     LoLoop.Start = ExpandLoopStart(LoLoop);
1072     RemoveDeadBranch(LoLoop.Start);
1073     LoLoop.End = ExpandLoopEnd(LoLoop);
1074     RemoveDeadBranch(LoLoop.End);
1075     if (LoLoop.IsTailPredicationLegal())
1076       ConvertVPTBlocks(LoLoop);
1077     for (auto *I : LoLoop.ToRemove) {
1078       LLVM_DEBUG(dbgs() << "ARM Loops: Erasing " << *I);
1079       I->eraseFromParent();
1080     }
1081   }
1082 
1083   PostOrderLoopTraversal DFS(*LoLoop.ML, *MLI);
1084   DFS.ProcessLoop();
1085   const SmallVectorImpl<MachineBasicBlock*> &PostOrder = DFS.getOrder();
1086   for (auto *MBB : PostOrder) {
1087     recomputeLiveIns(*MBB);
1088     // FIXME: For some reason, the live-in print order is non-deterministic for
1089     // our tests and I can't out why... So just sort them.
1090     MBB->sortUniqueLiveIns();
1091   }
1092 
1093   for (auto *MBB : reverse(PostOrder))
1094     recomputeLivenessFlags(*MBB);
1095 }
1096 
1097 bool ARMLowOverheadLoops::RevertNonLoops() {
1098   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting any remaining pseudos...\n");
1099   bool Changed = false;
1100 
1101   for (auto &MBB : *MF) {
1102     SmallVector<MachineInstr*, 4> Starts;
1103     SmallVector<MachineInstr*, 4> Decs;
1104     SmallVector<MachineInstr*, 4> Ends;
1105 
1106     for (auto &I : MBB) {
1107       if (isLoopStart(I))
1108         Starts.push_back(&I);
1109       else if (I.getOpcode() == ARM::t2LoopDec)
1110         Decs.push_back(&I);
1111       else if (I.getOpcode() == ARM::t2LoopEnd)
1112         Ends.push_back(&I);
1113     }
1114 
1115     if (Starts.empty() && Decs.empty() && Ends.empty())
1116       continue;
1117 
1118     Changed = true;
1119 
1120     for (auto *Start : Starts) {
1121       if (Start->getOpcode() == ARM::t2WhileLoopStart)
1122         RevertWhile(Start);
1123       else
1124         Start->eraseFromParent();
1125     }
1126     for (auto *Dec : Decs)
1127       RevertLoopDec(Dec);
1128 
1129     for (auto *End : Ends)
1130       RevertLoopEnd(End);
1131   }
1132   return Changed;
1133 }
1134 
1135 FunctionPass *llvm::createARMLowOverheadLoopsPass() {
1136   return new ARMLowOverheadLoops();
1137 }
1138