xref: /llvm-project/llvm/lib/Target/ARM/ARMLowOverheadLoops.cpp (revision da2e4728c71f9f8569246fb881c21811f8182c75)
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 /// A note on VPR.P0 (the lane mask):
39 /// VPT, VCMP, VPNOT and VCTP won't overwrite VPR.P0 when they update it in a
40 /// "VPT Active" context (which includes low-overhead loops and vpt blocks).
41 /// They will simply "and" the result of their calculation with the current
42 /// value of VPR.P0. You can think of it like this:
43 /// \verbatim
44 /// if VPT active:    ; Between a DLSTP/LETP, or for predicated instrs
45 ///   VPR.P0 &= Value
46 /// else
47 ///   VPR.P0 = Value
48 /// \endverbatim
49 /// When we're inside the low-overhead loop (between DLSTP and LETP), we always
50 /// fall in the "VPT active" case, so we can consider that all VPR writes by
51 /// one of those instruction is actually a "and".
52 //===----------------------------------------------------------------------===//
53 
54 #include "ARM.h"
55 #include "ARMBaseInstrInfo.h"
56 #include "ARMBaseRegisterInfo.h"
57 #include "ARMBasicBlockInfo.h"
58 #include "ARMSubtarget.h"
59 #include "Thumb2InstrInfo.h"
60 #include "llvm/ADT/SetOperations.h"
61 #include "llvm/ADT/SmallSet.h"
62 #include "llvm/CodeGen/LivePhysRegs.h"
63 #include "llvm/CodeGen/MachineFunctionPass.h"
64 #include "llvm/CodeGen/MachineLoopInfo.h"
65 #include "llvm/CodeGen/MachineLoopUtils.h"
66 #include "llvm/CodeGen/MachineRegisterInfo.h"
67 #include "llvm/CodeGen/Passes.h"
68 #include "llvm/CodeGen/ReachingDefAnalysis.h"
69 #include "llvm/MC/MCInstrDesc.h"
70 
71 using namespace llvm;
72 
73 #define DEBUG_TYPE "arm-low-overhead-loops"
74 #define ARM_LOW_OVERHEAD_LOOPS_NAME "ARM Low Overhead Loops pass"
75 
76 static cl::opt<bool>
77 DisableTailPredication("arm-loloops-disable-tailpred", cl::Hidden,
78     cl::desc("Disable tail-predication in the ARM LowOverheadLoop pass"),
79     cl::init(false));
80 
81 static bool isVectorPredicated(MachineInstr *MI) {
82   int PIdx = llvm::findFirstVPTPredOperandIdx(*MI);
83   return PIdx != -1 && MI->getOperand(PIdx + 1).getReg() == ARM::VPR;
84 }
85 
86 static bool isVectorPredicate(MachineInstr *MI) {
87   return MI->findRegisterDefOperandIdx(ARM::VPR) != -1;
88 }
89 
90 static bool hasVPRUse(MachineInstr &MI) {
91   return MI.findRegisterUseOperandIdx(ARM::VPR) != -1;
92 }
93 
94 static bool isDomainMVE(MachineInstr *MI) {
95   uint64_t Domain = MI->getDesc().TSFlags & ARMII::DomainMask;
96   return Domain == ARMII::DomainMVE;
97 }
98 
99 static bool shouldInspect(MachineInstr &MI) {
100   return isDomainMVE(&MI) || isVectorPredicate(&MI) || hasVPRUse(MI);
101 }
102 
103 static bool isDo(MachineInstr *MI) {
104   return MI->getOpcode() != ARM::t2WhileLoopStart;
105 }
106 
107 namespace {
108 
109   using InstSet = SmallPtrSetImpl<MachineInstr *>;
110 
111   class PostOrderLoopTraversal {
112     MachineLoop &ML;
113     MachineLoopInfo &MLI;
114     SmallPtrSet<MachineBasicBlock*, 4> Visited;
115     SmallVector<MachineBasicBlock*, 4> Order;
116 
117   public:
118     PostOrderLoopTraversal(MachineLoop &ML, MachineLoopInfo &MLI)
119       : ML(ML), MLI(MLI) { }
120 
121     const SmallVectorImpl<MachineBasicBlock*> &getOrder() const {
122       return Order;
123     }
124 
125     // Visit all the blocks within the loop, as well as exit blocks and any
126     // blocks properly dominating the header.
127     void ProcessLoop() {
128       std::function<void(MachineBasicBlock*)> Search = [this, &Search]
129         (MachineBasicBlock *MBB) -> void {
130         if (Visited.count(MBB))
131           return;
132 
133         Visited.insert(MBB);
134         for (auto *Succ : MBB->successors()) {
135           if (!ML.contains(Succ))
136             continue;
137           Search(Succ);
138         }
139         Order.push_back(MBB);
140       };
141 
142       // Insert exit blocks.
143       SmallVector<MachineBasicBlock*, 2> ExitBlocks;
144       ML.getExitBlocks(ExitBlocks);
145       for (auto *MBB : ExitBlocks)
146         Order.push_back(MBB);
147 
148       // Then add the loop body.
149       Search(ML.getHeader());
150 
151       // Then try the preheader and its predecessors.
152       std::function<void(MachineBasicBlock*)> GetPredecessor =
153         [this, &GetPredecessor] (MachineBasicBlock *MBB) -> void {
154         Order.push_back(MBB);
155         if (MBB->pred_size() == 1)
156           GetPredecessor(*MBB->pred_begin());
157       };
158 
159       if (auto *Preheader = ML.getLoopPreheader())
160         GetPredecessor(Preheader);
161       else if (auto *Preheader = MLI.findLoopPreheader(&ML, true))
162         GetPredecessor(Preheader);
163     }
164   };
165 
166   struct PredicatedMI {
167     MachineInstr *MI = nullptr;
168     SetVector<MachineInstr*> Predicates;
169 
170   public:
171     PredicatedMI(MachineInstr *I, SetVector<MachineInstr *> &Preds) : MI(I) {
172       assert(I && "Instruction must not be null!");
173       Predicates.insert(Preds.begin(), Preds.end());
174     }
175   };
176 
177   // Represent the current state of the VPR and hold all instances which
178   // represent a VPT block, which is a list of instructions that begins with a
179   // VPT/VPST and has a maximum of four proceeding instructions. All
180   // instructions within the block are predicated upon the vpr and we allow
181   // instructions to define the vpr within in the block too.
182   class VPTState {
183     friend struct LowOverheadLoop;
184 
185     SmallVector<MachineInstr *, 4> Insts;
186 
187     static SmallVector<VPTState, 4> Blocks;
188     static SetVector<MachineInstr *> CurrentPredicates;
189     static std::map<MachineInstr *,
190       std::unique_ptr<PredicatedMI>> PredicatedInsts;
191 
192     static void CreateVPTBlock(MachineInstr *MI) {
193       assert((CurrentPredicates.size() || MI->getParent()->isLiveIn(ARM::VPR))
194              && "Can't begin VPT without predicate");
195       Blocks.emplace_back(MI);
196       // The execution of MI is predicated upon the current set of instructions
197       // that are AND'ed together to form the VPR predicate value. In the case
198       // that MI is a VPT, CurrentPredicates will also just be MI.
199       PredicatedInsts.emplace(
200         MI, std::make_unique<PredicatedMI>(MI, CurrentPredicates));
201     }
202 
203     static void reset() {
204       Blocks.clear();
205       PredicatedInsts.clear();
206       CurrentPredicates.clear();
207     }
208 
209     static void addInst(MachineInstr *MI) {
210       Blocks.back().insert(MI);
211       PredicatedInsts.emplace(
212         MI, std::make_unique<PredicatedMI>(MI, CurrentPredicates));
213     }
214 
215     static void addPredicate(MachineInstr *MI) {
216       LLVM_DEBUG(dbgs() << "ARM Loops: Adding VPT Predicate: " << *MI);
217       CurrentPredicates.insert(MI);
218     }
219 
220     static void resetPredicate(MachineInstr *MI) {
221       LLVM_DEBUG(dbgs() << "ARM Loops: Resetting VPT Predicate: " << *MI);
222       CurrentPredicates.clear();
223       CurrentPredicates.insert(MI);
224     }
225 
226   public:
227     // Have we found an instruction within the block which defines the vpr? If
228     // so, not all the instructions in the block will have the same predicate.
229     static bool hasUniformPredicate(VPTState &Block) {
230       return getDivergent(Block) == nullptr;
231     }
232 
233     // If it exists, return the first internal instruction which modifies the
234     // VPR.
235     static MachineInstr *getDivergent(VPTState &Block) {
236       SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
237       for (unsigned i = 1; i < Insts.size(); ++i) {
238         MachineInstr *Next = Insts[i];
239         if (isVectorPredicate(Next))
240           return Next; // Found an instruction altering the vpr.
241       }
242       return nullptr;
243     }
244 
245     // Return whether the given instruction is predicated upon a VCTP.
246     static bool isPredicatedOnVCTP(MachineInstr *MI, bool Exclusive = false) {
247       SetVector<MachineInstr *> &Predicates = PredicatedInsts[MI]->Predicates;
248       if (Exclusive && Predicates.size() != 1)
249         return false;
250       for (auto *PredMI : Predicates)
251         if (isVCTP(PredMI))
252           return true;
253       return false;
254     }
255 
256     // Is the VPST, controlling the block entry, predicated upon a VCTP.
257     static bool isEntryPredicatedOnVCTP(VPTState &Block,
258                                         bool Exclusive = false) {
259       SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
260       return isPredicatedOnVCTP(Insts.front(), Exclusive);
261     }
262 
263     // If this block begins with a VPT, we can check whether it's using
264     // at least one predicated input(s), as well as possible loop invariant
265     // which would result in it being implicitly predicated.
266     static bool hasImplicitlyValidVPT(VPTState &Block,
267                                       ReachingDefAnalysis &RDA) {
268       SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
269       MachineInstr *VPT = Insts.front();
270       assert(isVPTOpcode(VPT->getOpcode()) &&
271              "Expected VPT block to begin with VPT/VPST");
272 
273       if (VPT->getOpcode() == ARM::MVE_VPST)
274         return false;
275 
276       auto IsOperandPredicated = [&](MachineInstr *MI, unsigned Idx) {
277         MachineInstr *Op = RDA.getMIOperand(MI, MI->getOperand(Idx));
278         return Op && PredicatedInsts.count(Op) && isPredicatedOnVCTP(Op);
279       };
280 
281       auto IsOperandInvariant = [&](MachineInstr *MI, unsigned Idx) {
282         MachineOperand &MO = MI->getOperand(Idx);
283         if (!MO.isReg() || !MO.getReg())
284           return true;
285 
286         SmallPtrSet<MachineInstr *, 2> Defs;
287         RDA.getGlobalReachingDefs(MI, MO.getReg(), Defs);
288         if (Defs.empty())
289           return true;
290 
291         for (auto *Def : Defs)
292           if (Def->getParent() == VPT->getParent())
293             return false;
294         return true;
295       };
296 
297       // Check that at least one of the operands is directly predicated on a
298       // vctp and allow an invariant value too.
299       return (IsOperandPredicated(VPT, 1) || IsOperandPredicated(VPT, 2)) &&
300              (IsOperandPredicated(VPT, 1) || IsOperandInvariant(VPT, 1)) &&
301              (IsOperandPredicated(VPT, 2) || IsOperandInvariant(VPT, 2));
302     }
303 
304     static bool isValid(ReachingDefAnalysis &RDA) {
305       // All predication within the loop should be based on vctp. If the block
306       // isn't predicated on entry, check whether the vctp is within the block
307       // and that all other instructions are then predicated on it.
308       for (auto &Block : Blocks) {
309         if (isEntryPredicatedOnVCTP(Block, false) ||
310             hasImplicitlyValidVPT(Block, RDA))
311           continue;
312 
313         SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
314         for (auto *MI : Insts) {
315           // Check that any internal VCTPs are 'Then' predicated.
316           if (isVCTP(MI) && getVPTInstrPredicate(*MI) != ARMVCC::Then)
317             return false;
318           // Skip other instructions that build up the predicate.
319           if (MI->getOpcode() == ARM::MVE_VPST || isVectorPredicate(MI))
320             continue;
321           // Check that any other instructions are predicated upon a vctp.
322           // TODO: We could infer when VPTs are implicitly predicated on the
323           // vctp (when the operands are predicated).
324           if (!isPredicatedOnVCTP(MI)) {
325             LLVM_DEBUG(dbgs() << "ARM Loops: Can't convert: " << *MI);
326             return false;
327           }
328         }
329       }
330       return true;
331     }
332 
333     VPTState(MachineInstr *MI) { Insts.push_back(MI); }
334 
335     void insert(MachineInstr *MI) {
336       Insts.push_back(MI);
337       // VPT/VPST + 4 predicated instructions.
338       assert(Insts.size() <= 5 && "Too many instructions in VPT block!");
339     }
340 
341     bool containsVCTP() const {
342       for (auto *MI : Insts)
343         if (isVCTP(MI))
344           return true;
345       return false;
346     }
347 
348     unsigned size() const { return Insts.size(); }
349     SmallVectorImpl<MachineInstr *> &getInsts() { return Insts; }
350   };
351 
352   struct LowOverheadLoop {
353 
354     MachineLoop &ML;
355     MachineBasicBlock *Preheader = nullptr;
356     MachineLoopInfo &MLI;
357     ReachingDefAnalysis &RDA;
358     const TargetRegisterInfo &TRI;
359     const ARMBaseInstrInfo &TII;
360     MachineFunction *MF = nullptr;
361     MachineBasicBlock::iterator StartInsertPt;
362     MachineBasicBlock *StartInsertBB = nullptr;
363     MachineInstr *Start = nullptr;
364     MachineInstr *Dec = nullptr;
365     MachineInstr *End = nullptr;
366     MachineOperand TPNumElements;
367     SmallVector<MachineInstr*, 4> VCTPs;
368     SmallPtrSet<MachineInstr*, 4> ToRemove;
369     SmallPtrSet<MachineInstr*, 4> BlockMasksToRecompute;
370     bool Revert = false;
371     bool CannotTailPredicate = false;
372 
373     LowOverheadLoop(MachineLoop &ML, MachineLoopInfo &MLI,
374                     ReachingDefAnalysis &RDA, const TargetRegisterInfo &TRI,
375                     const ARMBaseInstrInfo &TII)
376         : ML(ML), MLI(MLI), RDA(RDA), TRI(TRI), TII(TII),
377           TPNumElements(MachineOperand::CreateImm(0)) {
378       MF = ML.getHeader()->getParent();
379       if (auto *MBB = ML.getLoopPreheader())
380         Preheader = MBB;
381       else if (auto *MBB = MLI.findLoopPreheader(&ML, true))
382         Preheader = MBB;
383       VPTState::reset();
384     }
385 
386     // If this is an MVE instruction, check that we know how to use tail
387     // predication with it. Record VPT blocks and return whether the
388     // instruction is valid for tail predication.
389     bool ValidateMVEInst(MachineInstr *MI);
390 
391     void AnalyseMVEInst(MachineInstr *MI) {
392       CannotTailPredicate = !ValidateMVEInst(MI);
393     }
394 
395     bool IsTailPredicationLegal() const {
396       // For now, let's keep things really simple and only support a single
397       // block for tail predication.
398       return !Revert && FoundAllComponents() && !VCTPs.empty() &&
399              !CannotTailPredicate && ML.getNumBlocks() == 1;
400     }
401 
402     // Given that MI is a VCTP, check that is equivalent to any other VCTPs
403     // found.
404     bool AddVCTP(MachineInstr *MI);
405 
406     // Check that the predication in the loop will be equivalent once we
407     // perform the conversion. Also ensure that we can provide the number
408     // of elements to the loop start instruction.
409     bool ValidateTailPredicate();
410 
411     // Check that any values available outside of the loop will be the same
412     // after tail predication conversion.
413     bool ValidateLiveOuts();
414 
415     // Is it safe to define LR with DLS/WLS?
416     // LR can be defined if it is the operand to start, because it's the same
417     // value, or if it's going to be equivalent to the operand to Start.
418     MachineInstr *isSafeToDefineLR();
419 
420     // Check the branch targets are within range and we satisfy our
421     // restrictions.
422     void Validate(ARMBasicBlockUtils *BBUtils);
423 
424     bool FoundAllComponents() const {
425       return Start && Dec && End;
426     }
427 
428     SmallVectorImpl<VPTState> &getVPTBlocks() {
429       return VPTState::Blocks;
430     }
431 
432     // Return the operand for the loop start instruction. This will be the loop
433     // iteration count, or the number of elements if we're tail predicating.
434     MachineOperand &getLoopStartOperand() {
435       if (IsTailPredicationLegal())
436         return TPNumElements;
437       return isDo(Start) ? Start->getOperand(1) : Start->getOperand(0);
438     }
439 
440     unsigned getStartOpcode() const {
441       bool IsDo = isDo(Start);
442       if (!IsTailPredicationLegal())
443         return IsDo ? ARM::t2DLS : ARM::t2WLS;
444 
445       return VCTPOpcodeToLSTP(VCTPs.back()->getOpcode(), IsDo);
446     }
447 
448     void dump() const {
449       if (Start) dbgs() << "ARM Loops: Found Loop Start: " << *Start;
450       if (Dec) dbgs() << "ARM Loops: Found Loop Dec: " << *Dec;
451       if (End) dbgs() << "ARM Loops: Found Loop End: " << *End;
452       if (!VCTPs.empty()) {
453         dbgs() << "ARM Loops: Found VCTP(s):\n";
454         for (auto *MI : VCTPs)
455           dbgs() << " - " << *MI;
456       }
457       if (!FoundAllComponents())
458         dbgs() << "ARM Loops: Not a low-overhead loop.\n";
459       else if (!(Start && Dec && End))
460         dbgs() << "ARM Loops: Failed to find all loop components.\n";
461     }
462   };
463 
464   class ARMLowOverheadLoops : public MachineFunctionPass {
465     MachineFunction           *MF = nullptr;
466     MachineLoopInfo           *MLI = nullptr;
467     ReachingDefAnalysis       *RDA = nullptr;
468     const ARMBaseInstrInfo    *TII = nullptr;
469     MachineRegisterInfo       *MRI = nullptr;
470     const TargetRegisterInfo  *TRI = nullptr;
471     std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr;
472 
473   public:
474     static char ID;
475 
476     ARMLowOverheadLoops() : MachineFunctionPass(ID) { }
477 
478     void getAnalysisUsage(AnalysisUsage &AU) const override {
479       AU.setPreservesCFG();
480       AU.addRequired<MachineLoopInfo>();
481       AU.addRequired<ReachingDefAnalysis>();
482       MachineFunctionPass::getAnalysisUsage(AU);
483     }
484 
485     bool runOnMachineFunction(MachineFunction &MF) override;
486 
487     MachineFunctionProperties getRequiredProperties() const override {
488       return MachineFunctionProperties().set(
489           MachineFunctionProperties::Property::NoVRegs).set(
490           MachineFunctionProperties::Property::TracksLiveness);
491     }
492 
493     StringRef getPassName() const override {
494       return ARM_LOW_OVERHEAD_LOOPS_NAME;
495     }
496 
497   private:
498     bool ProcessLoop(MachineLoop *ML);
499 
500     bool RevertNonLoops();
501 
502     void RevertWhile(MachineInstr *MI) const;
503     void RevertDo(MachineInstr *MI) const;
504 
505     bool RevertLoopDec(MachineInstr *MI) const;
506 
507     void RevertLoopEnd(MachineInstr *MI, bool SkipCmp = false) const;
508 
509     void ConvertVPTBlocks(LowOverheadLoop &LoLoop);
510 
511     MachineInstr *ExpandLoopStart(LowOverheadLoop &LoLoop);
512 
513     void Expand(LowOverheadLoop &LoLoop);
514 
515     void IterationCountDCE(LowOverheadLoop &LoLoop);
516   };
517 }
518 
519 char ARMLowOverheadLoops::ID = 0;
520 
521 SmallVector<VPTState, 4> VPTState::Blocks;
522 SetVector<MachineInstr *> VPTState::CurrentPredicates;
523 std::map<MachineInstr *,
524          std::unique_ptr<PredicatedMI>> VPTState::PredicatedInsts;
525 
526 INITIALIZE_PASS(ARMLowOverheadLoops, DEBUG_TYPE, ARM_LOW_OVERHEAD_LOOPS_NAME,
527                 false, false)
528 
529 static bool TryRemove(MachineInstr *MI, ReachingDefAnalysis &RDA,
530                       InstSet &ToRemove, InstSet &Ignore) {
531 
532   // Check that we can remove all of Killed without having to modify any IT
533   // blocks.
534   auto WontCorruptITs = [](InstSet &Killed, ReachingDefAnalysis &RDA) {
535     // Collect the dead code and the MBBs in which they reside.
536     SmallPtrSet<MachineBasicBlock*, 2> BasicBlocks;
537     for (auto *Dead : Killed)
538       BasicBlocks.insert(Dead->getParent());
539 
540     // Collect IT blocks in all affected basic blocks.
541     std::map<MachineInstr *, SmallPtrSet<MachineInstr *, 2>> ITBlocks;
542     for (auto *MBB : BasicBlocks) {
543       for (auto &IT : *MBB) {
544         if (IT.getOpcode() != ARM::t2IT)
545           continue;
546         RDA.getReachingLocalUses(&IT, MCRegister::from(ARM::ITSTATE),
547                                  ITBlocks[&IT]);
548       }
549     }
550 
551     // If we're removing all of the instructions within an IT block, then
552     // also remove the IT instruction.
553     SmallPtrSet<MachineInstr *, 2> ModifiedITs;
554     SmallPtrSet<MachineInstr *, 2> RemoveITs;
555     for (auto *Dead : Killed) {
556       if (MachineOperand *MO = Dead->findRegisterUseOperand(ARM::ITSTATE)) {
557         MachineInstr *IT = RDA.getMIOperand(Dead, *MO);
558         RemoveITs.insert(IT);
559         auto &CurrentBlock = ITBlocks[IT];
560         CurrentBlock.erase(Dead);
561         if (CurrentBlock.empty())
562           ModifiedITs.erase(IT);
563         else
564           ModifiedITs.insert(IT);
565       }
566     }
567     if (!ModifiedITs.empty())
568       return false;
569     Killed.insert(RemoveITs.begin(), RemoveITs.end());
570     return true;
571   };
572 
573   SmallPtrSet<MachineInstr *, 2> Uses;
574   if (!RDA.isSafeToRemove(MI, Uses, Ignore))
575     return false;
576 
577   if (WontCorruptITs(Uses, RDA)) {
578     ToRemove.insert(Uses.begin(), Uses.end());
579     LLVM_DEBUG(dbgs() << "ARM Loops: Able to remove: " << *MI
580                << " - can also remove:\n";
581                for (auto *Use : Uses)
582                  dbgs() << "   - " << *Use);
583 
584     SmallPtrSet<MachineInstr*, 4> Killed;
585     RDA.collectKilledOperands(MI, Killed);
586     if (WontCorruptITs(Killed, RDA)) {
587       ToRemove.insert(Killed.begin(), Killed.end());
588       LLVM_DEBUG(for (auto *Dead : Killed)
589                    dbgs() << "   - " << *Dead);
590     }
591     return true;
592   }
593   return false;
594 }
595 
596 bool LowOverheadLoop::ValidateTailPredicate() {
597   if (!IsTailPredicationLegal()) {
598     LLVM_DEBUG(if (VCTPs.empty())
599                  dbgs() << "ARM Loops: Didn't find a VCTP instruction.\n";
600                dbgs() << "ARM Loops: Tail-predication is not valid.\n");
601     return false;
602   }
603 
604   assert(!VCTPs.empty() && "VCTP instruction expected but is not set");
605   assert(ML.getBlocks().size() == 1 &&
606          "Shouldn't be processing a loop with more than one block");
607 
608   if (DisableTailPredication) {
609     LLVM_DEBUG(dbgs() << "ARM Loops: tail-predication is disabled\n");
610     return false;
611   }
612 
613   if (!VPTState::isValid(RDA)) {
614     LLVM_DEBUG(dbgs() << "ARM Loops: Invalid VPT state.\n");
615     return false;
616   }
617 
618   if (!ValidateLiveOuts()) {
619     LLVM_DEBUG(dbgs() << "ARM Loops: Invalid live outs.\n");
620     return false;
621   }
622 
623   // Check that creating a [W|D]LSTP, which will define LR with an element
624   // count instead of iteration count, won't affect any other instructions
625   // than the LoopStart and LoopDec.
626   // TODO: We should try to insert the [W|D]LSTP after any of the other uses.
627   Register StartReg = isDo(Start) ? Start->getOperand(1).getReg()
628                                   : Start->getOperand(0).getReg();
629   if (StartInsertPt == Start && StartReg == ARM::LR) {
630     if (auto *IterCount = RDA.getMIOperand(Start, isDo(Start) ? 1 : 0)) {
631       SmallPtrSet<MachineInstr *, 2> Uses;
632       RDA.getGlobalUses(IterCount, MCRegister::from(ARM::LR), Uses);
633       for (auto *Use : Uses) {
634         if (Use != Start && Use != Dec) {
635           LLVM_DEBUG(dbgs() << " ARM Loops: Found LR use: " << *Use);
636           return false;
637         }
638       }
639     }
640   }
641 
642   // For tail predication, we need to provide the number of elements, instead
643   // of the iteration count, to the loop start instruction. The number of
644   // elements is provided to the vctp instruction, so we need to check that
645   // we can use this register at InsertPt.
646   MachineInstr *VCTP = VCTPs.back();
647   if (Start->getOpcode() == ARM::t2DoLoopStartTP) {
648     TPNumElements = Start->getOperand(2);
649     StartInsertPt = Start;
650     StartInsertBB = Start->getParent();
651   } else {
652     TPNumElements = VCTP->getOperand(1);
653     MCRegister NumElements = TPNumElements.getReg().asMCReg();
654 
655     // If the register is defined within loop, then we can't perform TP.
656     // TODO: Check whether this is just a mov of a register that would be
657     // available.
658     if (RDA.hasLocalDefBefore(VCTP, NumElements)) {
659       LLVM_DEBUG(dbgs() << "ARM Loops: VCTP operand is defined in the loop.\n");
660       return false;
661     }
662 
663     // The element count register maybe defined after InsertPt, in which case we
664     // need to try to move either InsertPt or the def so that the [w|d]lstp can
665     // use the value.
666 
667     if (StartInsertPt != StartInsertBB->end() &&
668         !RDA.isReachingDefLiveOut(&*StartInsertPt, NumElements)) {
669       if (auto *ElemDef =
670               RDA.getLocalLiveOutMIDef(StartInsertBB, NumElements)) {
671         if (RDA.isSafeToMoveForwards(ElemDef, &*StartInsertPt)) {
672           ElemDef->removeFromParent();
673           StartInsertBB->insert(StartInsertPt, ElemDef);
674           LLVM_DEBUG(dbgs()
675                      << "ARM Loops: Moved element count def: " << *ElemDef);
676         } else if (RDA.isSafeToMoveBackwards(&*StartInsertPt, ElemDef)) {
677           StartInsertPt->removeFromParent();
678           StartInsertBB->insertAfter(MachineBasicBlock::iterator(ElemDef),
679                                      &*StartInsertPt);
680           LLVM_DEBUG(dbgs() << "ARM Loops: Moved start past: " << *ElemDef);
681         } else {
682           // If we fail to move an instruction and the element count is provided
683           // by a mov, use the mov operand if it will have the same value at the
684           // insertion point
685           MachineOperand Operand = ElemDef->getOperand(1);
686           if (isMovRegOpcode(ElemDef->getOpcode()) &&
687               RDA.getUniqueReachingMIDef(ElemDef, Operand.getReg().asMCReg()) ==
688                   RDA.getUniqueReachingMIDef(&*StartInsertPt,
689                                              Operand.getReg().asMCReg())) {
690             TPNumElements = Operand;
691             NumElements = TPNumElements.getReg();
692           } else {
693             LLVM_DEBUG(dbgs()
694                        << "ARM Loops: Unable to move element count to loop "
695                        << "start instruction.\n");
696             return false;
697           }
698         }
699       }
700     }
701 
702     // Especially in the case of while loops, InsertBB may not be the
703     // preheader, so we need to check that the register isn't redefined
704     // before entering the loop.
705     auto CannotProvideElements = [this](MachineBasicBlock *MBB,
706                                         MCRegister NumElements) {
707       if (MBB->empty())
708         return false;
709       // NumElements is redefined in this block.
710       if (RDA.hasLocalDefBefore(&MBB->back(), NumElements))
711         return true;
712 
713       // Don't continue searching up through multiple predecessors.
714       if (MBB->pred_size() > 1)
715         return true;
716 
717       return false;
718     };
719 
720     // Search backwards for a def, until we get to InsertBB.
721     MachineBasicBlock *MBB = Preheader;
722     while (MBB && MBB != StartInsertBB) {
723       if (CannotProvideElements(MBB, NumElements)) {
724         LLVM_DEBUG(dbgs() << "ARM Loops: Unable to provide element count.\n");
725         return false;
726       }
727       MBB = *MBB->pred_begin();
728     }
729   }
730 
731   // Could inserting the [W|D]LSTP cause some unintended affects? In a perfect
732   // world the [w|d]lstp instruction would be last instruction in the preheader
733   // and so it would only affect instructions within the loop body. But due to
734   // scheduling, and/or the logic in this pass (above), the insertion point can
735   // be moved earlier. So if the Loop Start isn't the last instruction in the
736   // preheader, and if the initial element count is smaller than the vector
737   // width, the Loop Start instruction will immediately generate one or more
738   // false lane mask which can, incorrectly, affect the proceeding MVE
739   // instructions in the preheader.
740   if (std::any_of(StartInsertPt, StartInsertBB->end(), shouldInspect)) {
741     LLVM_DEBUG(dbgs() << "ARM Loops: Instruction blocks [W|D]LSTP\n");
742     return false;
743   }
744 
745   // Check that the value change of the element count is what we expect and
746   // that the predication will be equivalent. For this we need:
747   // NumElements = NumElements - VectorWidth. The sub will be a sub immediate
748   // and we can also allow register copies within the chain too.
749   auto IsValidSub = [](MachineInstr *MI, int ExpectedVecWidth) {
750     return -getAddSubImmediate(*MI) == ExpectedVecWidth;
751   };
752 
753   MachineBasicBlock *MBB = VCTP->getParent();
754   // Remove modifications to the element count since they have no purpose in a
755   // tail predicated loop. Explicitly refer to the vctp operand no matter which
756   // register NumElements has been assigned to, since that is what the
757   // modifications will be using
758   if (auto *Def = RDA.getUniqueReachingMIDef(
759           &MBB->back(), VCTP->getOperand(1).getReg().asMCReg())) {
760     SmallPtrSet<MachineInstr*, 2> ElementChain;
761     SmallPtrSet<MachineInstr*, 2> Ignore;
762     unsigned ExpectedVectorWidth = getTailPredVectorWidth(VCTP->getOpcode());
763 
764     Ignore.insert(VCTPs.begin(), VCTPs.end());
765 
766     if (TryRemove(Def, RDA, ElementChain, Ignore)) {
767       bool FoundSub = false;
768 
769       for (auto *MI : ElementChain) {
770         if (isMovRegOpcode(MI->getOpcode()))
771           continue;
772 
773         if (isSubImmOpcode(MI->getOpcode())) {
774           if (FoundSub || !IsValidSub(MI, ExpectedVectorWidth)) {
775             LLVM_DEBUG(dbgs() << "ARM Loops: Unexpected instruction in element"
776                        " count: " << *MI);
777             return false;
778           }
779           FoundSub = true;
780         } else {
781           LLVM_DEBUG(dbgs() << "ARM Loops: Unexpected instruction in element"
782                      " count: " << *MI);
783           return false;
784         }
785       }
786       ToRemove.insert(ElementChain.begin(), ElementChain.end());
787     }
788   }
789   return true;
790 }
791 
792 static bool isRegInClass(const MachineOperand &MO,
793                          const TargetRegisterClass *Class) {
794   return MO.isReg() && MO.getReg() && Class->contains(MO.getReg());
795 }
796 
797 // MVE 'narrowing' operate on half a lane, reading from half and writing
798 // to half, which are referred to has the top and bottom half. The other
799 // half retains its previous value.
800 static bool retainsPreviousHalfElement(const MachineInstr &MI) {
801   const MCInstrDesc &MCID = MI.getDesc();
802   uint64_t Flags = MCID.TSFlags;
803   return (Flags & ARMII::RetainsPreviousHalfElement) != 0;
804 }
805 
806 // Some MVE instructions read from the top/bottom halves of their operand(s)
807 // and generate a vector result with result elements that are double the
808 // width of the input.
809 static bool producesDoubleWidthResult(const MachineInstr &MI) {
810   const MCInstrDesc &MCID = MI.getDesc();
811   uint64_t Flags = MCID.TSFlags;
812   return (Flags & ARMII::DoubleWidthResult) != 0;
813 }
814 
815 static bool isHorizontalReduction(const MachineInstr &MI) {
816   const MCInstrDesc &MCID = MI.getDesc();
817   uint64_t Flags = MCID.TSFlags;
818   return (Flags & ARMII::HorizontalReduction) != 0;
819 }
820 
821 // Can this instruction generate a non-zero result when given only zeroed
822 // operands? This allows us to know that, given operands with false bytes
823 // zeroed by masked loads, that the result will also contain zeros in those
824 // bytes.
825 static bool canGenerateNonZeros(const MachineInstr &MI) {
826 
827   // Check for instructions which can write into a larger element size,
828   // possibly writing into a previous zero'd lane.
829   if (producesDoubleWidthResult(MI))
830     return true;
831 
832   switch (MI.getOpcode()) {
833   default:
834     break;
835   // FIXME: VNEG FP and -0? I think we'll need to handle this once we allow
836   // fp16 -> fp32 vector conversions.
837   // Instructions that perform a NOT will generate 1s from 0s.
838   case ARM::MVE_VMVN:
839   case ARM::MVE_VORN:
840   // Count leading zeros will do just that!
841   case ARM::MVE_VCLZs8:
842   case ARM::MVE_VCLZs16:
843   case ARM::MVE_VCLZs32:
844     return true;
845   }
846   return false;
847 }
848 
849 // Look at its register uses to see if it only can only receive zeros
850 // into its false lanes which would then produce zeros. Also check that
851 // the output register is also defined by an FalseLanesZero instruction
852 // so that if tail-predication happens, the lanes that aren't updated will
853 // still be zeros.
854 static bool producesFalseLanesZero(MachineInstr &MI,
855                                    const TargetRegisterClass *QPRs,
856                                    const ReachingDefAnalysis &RDA,
857                                    InstSet &FalseLanesZero) {
858   if (canGenerateNonZeros(MI))
859     return false;
860 
861   bool isPredicated = isVectorPredicated(&MI);
862   // Predicated loads will write zeros to the falsely predicated bytes of the
863   // destination register.
864   if (MI.mayLoad())
865     return isPredicated;
866 
867   auto IsZeroInit = [](MachineInstr *Def) {
868     return !isVectorPredicated(Def) &&
869            Def->getOpcode() == ARM::MVE_VMOVimmi32 &&
870            Def->getOperand(1).getImm() == 0;
871   };
872 
873   bool AllowScalars = isHorizontalReduction(MI);
874   for (auto &MO : MI.operands()) {
875     if (!MO.isReg() || !MO.getReg())
876       continue;
877     if (!isRegInClass(MO, QPRs) && AllowScalars)
878       continue;
879 
880     // Check that this instruction will produce zeros in its false lanes:
881     // - If it only consumes false lanes zero or constant 0 (vmov #0)
882     // - If it's predicated, it only matters that it's def register already has
883     //   false lane zeros, so we can ignore the uses.
884     SmallPtrSet<MachineInstr *, 2> Defs;
885     RDA.getGlobalReachingDefs(&MI, MO.getReg(), Defs);
886     for (auto *Def : Defs) {
887       if (Def == &MI || FalseLanesZero.count(Def) || IsZeroInit(Def))
888         continue;
889       if (MO.isUse() && isPredicated)
890         continue;
891       return false;
892     }
893   }
894   LLVM_DEBUG(dbgs() << "ARM Loops: Always False Zeros: " << MI);
895   return true;
896 }
897 
898 bool LowOverheadLoop::ValidateLiveOuts() {
899   // We want to find out if the tail-predicated version of this loop will
900   // produce the same values as the loop in its original form. For this to
901   // be true, the newly inserted implicit predication must not change the
902   // the (observable) results.
903   // We're doing this because many instructions in the loop will not be
904   // predicated and so the conversion from VPT predication to tail-predication
905   // can result in different values being produced; due to the tail-predication
906   // preventing many instructions from updating their falsely predicated
907   // lanes. This analysis assumes that all the instructions perform lane-wise
908   // operations and don't perform any exchanges.
909   // A masked load, whether through VPT or tail predication, will write zeros
910   // to any of the falsely predicated bytes. So, from the loads, we know that
911   // the false lanes are zeroed and here we're trying to track that those false
912   // lanes remain zero, or where they change, the differences are masked away
913   // by their user(s).
914   // All MVE stores have to be predicated, so we know that any predicate load
915   // operands, or stored results are equivalent already. Other explicitly
916   // predicated instructions will perform the same operation in the original
917   // loop and the tail-predicated form too. Because of this, we can insert
918   // loads, stores and other predicated instructions into our Predicated
919   // set and build from there.
920   const TargetRegisterClass *QPRs = TRI.getRegClass(ARM::MQPRRegClassID);
921   SetVector<MachineInstr *> FalseLanesUnknown;
922   SmallPtrSet<MachineInstr *, 4> FalseLanesZero;
923   SmallPtrSet<MachineInstr *, 4> Predicated;
924   MachineBasicBlock *Header = ML.getHeader();
925 
926   for (auto &MI : *Header) {
927     if (!shouldInspect(MI))
928       continue;
929 
930     if (isVCTP(&MI) || isVPTOpcode(MI.getOpcode()))
931       continue;
932 
933     bool isPredicated = isVectorPredicated(&MI);
934     bool retainsOrReduces =
935       retainsPreviousHalfElement(MI) || isHorizontalReduction(MI);
936 
937     if (isPredicated)
938       Predicated.insert(&MI);
939     if (producesFalseLanesZero(MI, QPRs, RDA, FalseLanesZero))
940       FalseLanesZero.insert(&MI);
941     else if (MI.getNumDefs() == 0)
942       continue;
943     else if (!isPredicated && retainsOrReduces)
944       return false;
945     else if (!isPredicated)
946       FalseLanesUnknown.insert(&MI);
947   }
948 
949   auto HasPredicatedUsers = [this](MachineInstr *MI, const MachineOperand &MO,
950                               SmallPtrSetImpl<MachineInstr *> &Predicated) {
951     SmallPtrSet<MachineInstr *, 2> Uses;
952     RDA.getGlobalUses(MI, MO.getReg().asMCReg(), Uses);
953     for (auto *Use : Uses) {
954       if (Use != MI && !Predicated.count(Use))
955         return false;
956     }
957     return true;
958   };
959 
960   // Visit the unknowns in reverse so that we can start at the values being
961   // stored and then we can work towards the leaves, hopefully adding more
962   // instructions to Predicated. Successfully terminating the loop means that
963   // all the unknown values have to found to be masked by predicated user(s).
964   // For any unpredicated values, we store them in NonPredicated so that we
965   // can later check whether these form a reduction.
966   SmallPtrSet<MachineInstr*, 2> NonPredicated;
967   for (auto *MI : reverse(FalseLanesUnknown)) {
968     for (auto &MO : MI->operands()) {
969       if (!isRegInClass(MO, QPRs) || !MO.isDef())
970         continue;
971       if (!HasPredicatedUsers(MI, MO, Predicated)) {
972         LLVM_DEBUG(dbgs() << "ARM Loops: Found an unknown def of : "
973                           << TRI.getRegAsmName(MO.getReg()) << " at " << *MI);
974         NonPredicated.insert(MI);
975         break;
976       }
977     }
978     // Any unknown false lanes have been masked away by the user(s).
979     if (!NonPredicated.contains(MI))
980       Predicated.insert(MI);
981   }
982 
983   SmallPtrSet<MachineInstr *, 2> LiveOutMIs;
984   SmallVector<MachineBasicBlock *, 2> ExitBlocks;
985   ML.getExitBlocks(ExitBlocks);
986   assert(ML.getNumBlocks() == 1 && "Expected single block loop!");
987   assert(ExitBlocks.size() == 1 && "Expected a single exit block");
988   MachineBasicBlock *ExitBB = ExitBlocks.front();
989   for (const MachineBasicBlock::RegisterMaskPair &RegMask : ExitBB->liveins()) {
990     // TODO: Instead of blocking predication, we could move the vctp to the exit
991     // block and calculate it's operand there in or the preheader.
992     if (RegMask.PhysReg == ARM::VPR)
993       return false;
994     // Check Q-regs that are live in the exit blocks. We don't collect scalars
995     // because they won't be affected by lane predication.
996     if (QPRs->contains(RegMask.PhysReg))
997       if (auto *MI = RDA.getLocalLiveOutMIDef(Header, RegMask.PhysReg))
998         LiveOutMIs.insert(MI);
999   }
1000 
1001   // We've already validated that any VPT predication within the loop will be
1002   // equivalent when we perform the predication transformation; so we know that
1003   // any VPT predicated instruction is predicated upon VCTP. Any live-out
1004   // instruction needs to be predicated, so check this here. The instructions
1005   // in NonPredicated have been found to be a reduction that we can ensure its
1006   // legality.
1007   for (auto *MI : LiveOutMIs) {
1008     if (NonPredicated.count(MI) && FalseLanesUnknown.contains(MI)) {
1009       LLVM_DEBUG(dbgs() << "ARM Loops: Unable to handle live out: " << *MI);
1010       return false;
1011     }
1012   }
1013 
1014   return true;
1015 }
1016 
1017 void LowOverheadLoop::Validate(ARMBasicBlockUtils *BBUtils) {
1018   if (Revert)
1019     return;
1020 
1021   // Check branch target ranges: WLS[TP] can only branch forwards and LE[TP]
1022   // can only jump back.
1023   auto ValidateRanges = [](MachineInstr *Start, MachineInstr *End,
1024                            ARMBasicBlockUtils *BBUtils, MachineLoop &ML) {
1025     assert(End->getOperand(1).isMBB() &&
1026            "Expected LoopEnd to target basic block!");
1027 
1028     // TODO Maybe there's cases where the target doesn't have to be the header,
1029     // but for now be safe and revert.
1030     if (End->getOperand(1).getMBB() != ML.getHeader()) {
1031       LLVM_DEBUG(dbgs() << "ARM Loops: LoopEnd is not targeting header.\n");
1032       return false;
1033     }
1034 
1035     // The WLS and LE instructions have 12-bits for the label offset. WLS
1036     // requires a positive offset, while LE uses negative.
1037     if (BBUtils->getOffsetOf(End) < BBUtils->getOffsetOf(ML.getHeader()) ||
1038         !BBUtils->isBBInRange(End, ML.getHeader(), 4094)) {
1039       LLVM_DEBUG(dbgs() << "ARM Loops: LE offset is out-of-range\n");
1040       return false;
1041     }
1042 
1043     if (Start->getOpcode() == ARM::t2WhileLoopStart &&
1044         (BBUtils->getOffsetOf(Start) >
1045          BBUtils->getOffsetOf(Start->getOperand(1).getMBB()) ||
1046          !BBUtils->isBBInRange(Start, Start->getOperand(1).getMBB(), 4094))) {
1047       LLVM_DEBUG(dbgs() << "ARM Loops: WLS offset is out-of-range!\n");
1048       return false;
1049     }
1050     return true;
1051   };
1052 
1053   // Find a suitable position to insert the loop start instruction. It needs to
1054   // be able to safely define LR.
1055   auto FindStartInsertionPoint = [](MachineInstr *Start, MachineInstr *Dec,
1056                                     MachineBasicBlock::iterator &InsertPt,
1057                                     MachineBasicBlock *&InsertBB,
1058                                     ReachingDefAnalysis &RDA,
1059                                     InstSet &ToRemove) {
1060     // For a t2DoLoopStart it is always valid to use the start insertion point.
1061     // For WLS we can define LR if LR already contains the same value.
1062     if (isDo(Start) || Start->getOperand(0).getReg() == ARM::LR) {
1063       InsertPt = MachineBasicBlock::iterator(Start);
1064       InsertBB = Start->getParent();
1065       return true;
1066     }
1067 
1068     // We've found no suitable LR def and Start doesn't use LR directly. Can we
1069     // just define LR anyway?
1070     if (!RDA.isSafeToDefRegAt(Start, MCRegister::from(ARM::LR)))
1071       return false;
1072 
1073     InsertPt = MachineBasicBlock::iterator(Start);
1074     InsertBB = Start->getParent();
1075     return true;
1076   };
1077 
1078   if (!FindStartInsertionPoint(Start, Dec, StartInsertPt, StartInsertBB, RDA,
1079                                ToRemove)) {
1080     LLVM_DEBUG(dbgs() << "ARM Loops: Unable to find safe insertion point.\n");
1081     Revert = true;
1082     return;
1083   }
1084   LLVM_DEBUG(if (StartInsertPt == StartInsertBB->end())
1085                dbgs() << "ARM Loops: Will insert LoopStart at end of block\n";
1086              else
1087                dbgs() << "ARM Loops: Will insert LoopStart at "
1088                       << *StartInsertPt
1089             );
1090 
1091   Revert = !ValidateRanges(Start, End, BBUtils, ML);
1092   CannotTailPredicate = !ValidateTailPredicate();
1093 }
1094 
1095 bool LowOverheadLoop::AddVCTP(MachineInstr *MI) {
1096   LLVM_DEBUG(dbgs() << "ARM Loops: Adding VCTP: " << *MI);
1097   if (VCTPs.empty()) {
1098     VCTPs.push_back(MI);
1099     return true;
1100   }
1101 
1102   // If we find another VCTP, check whether it uses the same value as the main VCTP.
1103   // If it does, store it in the VCTPs set, else refuse it.
1104   MachineInstr *Prev = VCTPs.back();
1105   if (!Prev->getOperand(1).isIdenticalTo(MI->getOperand(1)) ||
1106       !RDA.hasSameReachingDef(Prev, MI, MI->getOperand(1).getReg().asMCReg())) {
1107     LLVM_DEBUG(dbgs() << "ARM Loops: Found VCTP with a different reaching "
1108                          "definition from the main VCTP");
1109     return false;
1110   }
1111   VCTPs.push_back(MI);
1112   return true;
1113 }
1114 
1115 bool LowOverheadLoop::ValidateMVEInst(MachineInstr* MI) {
1116   if (CannotTailPredicate)
1117     return false;
1118 
1119   if (!shouldInspect(*MI))
1120     return true;
1121 
1122   if (MI->getOpcode() == ARM::MVE_VPSEL ||
1123       MI->getOpcode() == ARM::MVE_VPNOT) {
1124     // TODO: Allow VPSEL and VPNOT, we currently cannot because:
1125     // 1) It will use the VPR as a predicate operand, but doesn't have to be
1126     //    instead a VPT block, which means we can assert while building up
1127     //    the VPT block because we don't find another VPT or VPST to being a new
1128     //    one.
1129     // 2) VPSEL still requires a VPR operand even after tail predicating,
1130     //    which means we can't remove it unless there is another
1131     //    instruction, such as vcmp, that can provide the VPR def.
1132     return false;
1133   }
1134 
1135   // Record all VCTPs and check that they're equivalent to one another.
1136   if (isVCTP(MI) && !AddVCTP(MI))
1137     return false;
1138 
1139   // Inspect uses first so that any instructions that alter the VPR don't
1140   // alter the predicate upon themselves.
1141   const MCInstrDesc &MCID = MI->getDesc();
1142   bool IsUse = false;
1143   unsigned LastOpIdx = MI->getNumOperands() - 1;
1144   for (auto &Op : enumerate(reverse(MCID.operands()))) {
1145     const MachineOperand &MO = MI->getOperand(LastOpIdx - Op.index());
1146     if (!MO.isReg() || !MO.isUse() || MO.getReg() != ARM::VPR)
1147       continue;
1148 
1149     if (ARM::isVpred(Op.value().OperandType)) {
1150       VPTState::addInst(MI);
1151       IsUse = true;
1152     } else if (MI->getOpcode() != ARM::MVE_VPST) {
1153       LLVM_DEBUG(dbgs() << "ARM Loops: Found instruction using vpr: " << *MI);
1154       return false;
1155     }
1156   }
1157 
1158   // If we find an instruction that has been marked as not valid for tail
1159   // predication, only allow the instruction if it's contained within a valid
1160   // VPT block.
1161   bool RequiresExplicitPredication =
1162     (MCID.TSFlags & ARMII::ValidForTailPredication) == 0;
1163   if (isDomainMVE(MI) && RequiresExplicitPredication) {
1164     LLVM_DEBUG(if (!IsUse)
1165                dbgs() << "ARM Loops: Can't tail predicate: " << *MI);
1166     return IsUse;
1167   }
1168 
1169   // If the instruction is already explicitly predicated, then the conversion
1170   // will be fine, but ensure that all store operations are predicated.
1171   if (MI->mayStore())
1172     return IsUse;
1173 
1174   // If this instruction defines the VPR, update the predicate for the
1175   // proceeding instructions.
1176   if (isVectorPredicate(MI)) {
1177     // Clear the existing predicate when we're not in VPT Active state,
1178     // otherwise we add to it.
1179     if (!isVectorPredicated(MI))
1180       VPTState::resetPredicate(MI);
1181     else
1182       VPTState::addPredicate(MI);
1183   }
1184 
1185   // Finally once the predicate has been modified, we can start a new VPT
1186   // block if necessary.
1187   if (isVPTOpcode(MI->getOpcode()))
1188     VPTState::CreateVPTBlock(MI);
1189 
1190   return true;
1191 }
1192 
1193 bool ARMLowOverheadLoops::runOnMachineFunction(MachineFunction &mf) {
1194   const ARMSubtarget &ST = static_cast<const ARMSubtarget&>(mf.getSubtarget());
1195   if (!ST.hasLOB())
1196     return false;
1197 
1198   MF = &mf;
1199   LLVM_DEBUG(dbgs() << "ARM Loops on " << MF->getName() << " ------------- \n");
1200 
1201   MLI = &getAnalysis<MachineLoopInfo>();
1202   RDA = &getAnalysis<ReachingDefAnalysis>();
1203   MF->getProperties().set(MachineFunctionProperties::Property::TracksLiveness);
1204   MRI = &MF->getRegInfo();
1205   TII = static_cast<const ARMBaseInstrInfo*>(ST.getInstrInfo());
1206   TRI = ST.getRegisterInfo();
1207   BBUtils = std::unique_ptr<ARMBasicBlockUtils>(new ARMBasicBlockUtils(*MF));
1208   BBUtils->computeAllBlockSizes();
1209   BBUtils->adjustBBOffsetsAfter(&MF->front());
1210 
1211   bool Changed = false;
1212   for (auto ML : *MLI) {
1213     if (ML->isOutermost())
1214       Changed |= ProcessLoop(ML);
1215   }
1216   Changed |= RevertNonLoops();
1217   return Changed;
1218 }
1219 
1220 bool ARMLowOverheadLoops::ProcessLoop(MachineLoop *ML) {
1221 
1222   bool Changed = false;
1223 
1224   // Process inner loops first.
1225   for (auto I = ML->begin(), E = ML->end(); I != E; ++I)
1226     Changed |= ProcessLoop(*I);
1227 
1228   LLVM_DEBUG(dbgs() << "ARM Loops: Processing loop containing:\n";
1229              if (auto *Preheader = ML->getLoopPreheader())
1230                dbgs() << " - " << Preheader->getName() << "\n";
1231              else if (auto *Preheader = MLI->findLoopPreheader(ML))
1232                dbgs() << " - " << Preheader->getName() << "\n";
1233              else if (auto *Preheader = MLI->findLoopPreheader(ML, true))
1234                dbgs() << " - " << Preheader->getName() << "\n";
1235              for (auto *MBB : ML->getBlocks())
1236                dbgs() << " - " << MBB->getName() << "\n";
1237             );
1238 
1239   // Search the given block for a loop start instruction. If one isn't found,
1240   // and there's only one predecessor block, search that one too.
1241   std::function<MachineInstr*(MachineBasicBlock*)> SearchForStart =
1242     [&SearchForStart](MachineBasicBlock *MBB) -> MachineInstr* {
1243     for (auto &MI : *MBB) {
1244       if (isLoopStart(MI))
1245         return &MI;
1246     }
1247     if (MBB->pred_size() == 1)
1248       return SearchForStart(*MBB->pred_begin());
1249     return nullptr;
1250   };
1251 
1252   LowOverheadLoop LoLoop(*ML, *MLI, *RDA, *TRI, *TII);
1253   // Search the preheader for the start intrinsic.
1254   // FIXME: I don't see why we shouldn't be supporting multiple predecessors
1255   // with potentially multiple set.loop.iterations, so we need to enable this.
1256   if (LoLoop.Preheader)
1257     LoLoop.Start = SearchForStart(LoLoop.Preheader);
1258   else
1259     return false;
1260 
1261   // Find the low-overhead loop components and decide whether or not to fall
1262   // back to a normal loop. Also look for a vctp instructions and decide
1263   // whether we can convert that predicate using tail predication.
1264   for (auto *MBB : reverse(ML->getBlocks())) {
1265     for (auto &MI : *MBB) {
1266       if (MI.isDebugValue())
1267         continue;
1268       else if (MI.getOpcode() == ARM::t2LoopDec)
1269         LoLoop.Dec = &MI;
1270       else if (MI.getOpcode() == ARM::t2LoopEnd)
1271         LoLoop.End = &MI;
1272       else if (isLoopStart(MI))
1273         LoLoop.Start = &MI;
1274       else if (MI.getDesc().isCall()) {
1275         // TODO: Though the call will require LE to execute again, does this
1276         // mean we should revert? Always executing LE hopefully should be
1277         // faster than performing a sub,cmp,br or even subs,br.
1278         LoLoop.Revert = true;
1279         LLVM_DEBUG(dbgs() << "ARM Loops: Found call.\n");
1280       } else {
1281         // Record VPR defs and build up their corresponding vpt blocks.
1282         // Check we know how to tail predicate any mve instructions.
1283         LoLoop.AnalyseMVEInst(&MI);
1284       }
1285     }
1286   }
1287 
1288   LLVM_DEBUG(LoLoop.dump());
1289   if (!LoLoop.FoundAllComponents()) {
1290     LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find loop start, update, end\n");
1291     return false;
1292   }
1293 
1294   // Check that the only instruction using LoopDec is LoopEnd.
1295   // TODO: Check for copy chains that really have no effect.
1296   SmallPtrSet<MachineInstr*, 2> Uses;
1297   RDA->getReachingLocalUses(LoLoop.Dec, MCRegister::from(ARM::LR), Uses);
1298   if (Uses.size() > 1 || !Uses.count(LoLoop.End)) {
1299     LLVM_DEBUG(dbgs() << "ARM Loops: Unable to remove LoopDec.\n");
1300     LoLoop.Revert = true;
1301   }
1302   LoLoop.Validate(BBUtils.get());
1303   Expand(LoLoop);
1304   return true;
1305 }
1306 
1307 // WhileLoopStart holds the exit block, so produce a cmp lr, 0 and then a
1308 // beq that branches to the exit branch.
1309 // TODO: We could also try to generate a cbz if the value in LR is also in
1310 // another low register.
1311 void ARMLowOverheadLoops::RevertWhile(MachineInstr *MI) const {
1312   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp: " << *MI);
1313   MachineBasicBlock *MBB = MI->getParent();
1314   MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
1315                                     TII->get(ARM::t2CMPri));
1316   MIB.add(MI->getOperand(0));
1317   MIB.addImm(0);
1318   MIB.addImm(ARMCC::AL);
1319   MIB.addReg(ARM::NoRegister);
1320 
1321   MachineBasicBlock *DestBB = MI->getOperand(1).getMBB();
1322   unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
1323     ARM::tBcc : ARM::t2Bcc;
1324 
1325   MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc));
1326   MIB.add(MI->getOperand(1));   // branch target
1327   MIB.addImm(ARMCC::EQ);        // condition code
1328   MIB.addReg(ARM::CPSR);
1329   MI->eraseFromParent();
1330 }
1331 
1332 void ARMLowOverheadLoops::RevertDo(MachineInstr *MI) const {
1333   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to mov: " << *MI);
1334   MachineBasicBlock *MBB = MI->getParent();
1335   BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(ARM::tMOVr))
1336       .add(MI->getOperand(0))
1337       .add(MI->getOperand(1))
1338       .add(predOps(ARMCC::AL));
1339   MI->eraseFromParent();
1340 }
1341 
1342 bool ARMLowOverheadLoops::RevertLoopDec(MachineInstr *MI) const {
1343   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to sub: " << *MI);
1344   MachineBasicBlock *MBB = MI->getParent();
1345   SmallPtrSet<MachineInstr*, 1> Ignore;
1346   for (auto I = MachineBasicBlock::iterator(MI), E = MBB->end(); I != E; ++I) {
1347     if (I->getOpcode() == ARM::t2LoopEnd) {
1348       Ignore.insert(&*I);
1349       break;
1350     }
1351   }
1352 
1353   // If nothing defines CPSR between LoopDec and LoopEnd, use a t2SUBS.
1354   bool SetFlags =
1355       RDA->isSafeToDefRegAt(MI, MCRegister::from(ARM::CPSR), Ignore);
1356 
1357   MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
1358                                     TII->get(ARM::t2SUBri));
1359   MIB.addDef(ARM::LR);
1360   MIB.add(MI->getOperand(1));
1361   MIB.add(MI->getOperand(2));
1362   MIB.addImm(ARMCC::AL);
1363   MIB.addReg(0);
1364 
1365   if (SetFlags) {
1366     MIB.addReg(ARM::CPSR);
1367     MIB->getOperand(5).setIsDef(true);
1368   } else
1369     MIB.addReg(0);
1370 
1371   MI->eraseFromParent();
1372   return SetFlags;
1373 }
1374 
1375 // Generate a subs, or sub and cmp, and a branch instead of an LE.
1376 void ARMLowOverheadLoops::RevertLoopEnd(MachineInstr *MI, bool SkipCmp) const {
1377   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp, br: " << *MI);
1378 
1379   MachineBasicBlock *MBB = MI->getParent();
1380   // Create cmp
1381   if (!SkipCmp) {
1382     MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
1383                                       TII->get(ARM::t2CMPri));
1384     MIB.addReg(ARM::LR);
1385     MIB.addImm(0);
1386     MIB.addImm(ARMCC::AL);
1387     MIB.addReg(ARM::NoRegister);
1388   }
1389 
1390   MachineBasicBlock *DestBB = MI->getOperand(1).getMBB();
1391   unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
1392     ARM::tBcc : ARM::t2Bcc;
1393 
1394   // Create bne
1395   MachineInstrBuilder MIB =
1396     BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc));
1397   MIB.add(MI->getOperand(1));   // branch target
1398   MIB.addImm(ARMCC::NE);        // condition code
1399   MIB.addReg(ARM::CPSR);
1400   MI->eraseFromParent();
1401 }
1402 
1403 // Perform dead code elimation on the loop iteration count setup expression.
1404 // If we are tail-predicating, the number of elements to be processed is the
1405 // operand of the VCTP instruction in the vector body, see getCount(), which is
1406 // register $r3 in this example:
1407 //
1408 //   $lr = big-itercount-expression
1409 //   ..
1410 //   $lr = t2DoLoopStart renamable $lr
1411 //   vector.body:
1412 //     ..
1413 //     $vpr = MVE_VCTP32 renamable $r3
1414 //     renamable $lr = t2LoopDec killed renamable $lr, 1
1415 //     t2LoopEnd renamable $lr, %vector.body
1416 //     tB %end
1417 //
1418 // What we would like achieve here is to replace the do-loop start pseudo
1419 // instruction t2DoLoopStart with:
1420 //
1421 //    $lr = MVE_DLSTP_32 killed renamable $r3
1422 //
1423 // Thus, $r3 which defines the number of elements, is written to $lr,
1424 // and then we want to delete the whole chain that used to define $lr,
1425 // see the comment below how this chain could look like.
1426 //
1427 void ARMLowOverheadLoops::IterationCountDCE(LowOverheadLoop &LoLoop) {
1428   if (!LoLoop.IsTailPredicationLegal())
1429     return;
1430 
1431   LLVM_DEBUG(dbgs() << "ARM Loops: Trying DCE on loop iteration count.\n");
1432 
1433   MachineInstr *Def =
1434       RDA->getMIOperand(LoLoop.Start, isDo(LoLoop.Start) ? 1 : 0);
1435   if (!Def) {
1436     LLVM_DEBUG(dbgs() << "ARM Loops: Couldn't find iteration count.\n");
1437     return;
1438   }
1439 
1440   // Collect and remove the users of iteration count.
1441   SmallPtrSet<MachineInstr*, 4> Killed  = { LoLoop.Start, LoLoop.Dec,
1442                                             LoLoop.End };
1443   if (!TryRemove(Def, *RDA, LoLoop.ToRemove, Killed))
1444     LLVM_DEBUG(dbgs() << "ARM Loops: Unsafe to remove loop iteration count.\n");
1445 }
1446 
1447 MachineInstr* ARMLowOverheadLoops::ExpandLoopStart(LowOverheadLoop &LoLoop) {
1448   LLVM_DEBUG(dbgs() << "ARM Loops: Expanding LoopStart.\n");
1449   // When using tail-predication, try to delete the dead code that was used to
1450   // calculate the number of loop iterations.
1451   IterationCountDCE(LoLoop);
1452 
1453   MachineBasicBlock::iterator InsertPt = LoLoop.StartInsertPt;
1454   MachineInstr *Start = LoLoop.Start;
1455   MachineBasicBlock *MBB = LoLoop.StartInsertBB;
1456   unsigned Opc = LoLoop.getStartOpcode();
1457   MachineOperand &Count = LoLoop.getLoopStartOperand();
1458 
1459   MachineInstrBuilder MIB =
1460     BuildMI(*MBB, InsertPt, Start->getDebugLoc(), TII->get(Opc));
1461 
1462   MIB.addDef(ARM::LR);
1463   MIB.add(Count);
1464   if (!isDo(Start))
1465     MIB.add(Start->getOperand(1));
1466 
1467   LoLoop.ToRemove.insert(Start);
1468   LLVM_DEBUG(dbgs() << "ARM Loops: Inserted start: " << *MIB);
1469   return &*MIB;
1470 }
1471 
1472 void ARMLowOverheadLoops::ConvertVPTBlocks(LowOverheadLoop &LoLoop) {
1473   auto RemovePredicate = [](MachineInstr *MI) {
1474     LLVM_DEBUG(dbgs() << "ARM Loops: Removing predicate from: " << *MI);
1475     if (int PIdx = llvm::findFirstVPTPredOperandIdx(*MI)) {
1476       assert(MI->getOperand(PIdx).getImm() == ARMVCC::Then &&
1477              "Expected Then predicate!");
1478       MI->getOperand(PIdx).setImm(ARMVCC::None);
1479       MI->getOperand(PIdx+1).setReg(0);
1480     } else
1481       llvm_unreachable("trying to unpredicate a non-predicated instruction");
1482   };
1483 
1484   for (auto &Block : LoLoop.getVPTBlocks()) {
1485     SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
1486 
1487     auto ReplaceVCMPWithVPT = [&](MachineInstr *&TheVCMP, MachineInstr *At) {
1488       assert(TheVCMP && "Replacing a removed or non-existent VCMP");
1489       // Replace the VCMP with a VPT
1490       MachineInstrBuilder MIB =
1491           BuildMI(*At->getParent(), At, At->getDebugLoc(),
1492                   TII->get(VCMPOpcodeToVPT(TheVCMP->getOpcode())));
1493       MIB.addImm(ARMVCC::Then);
1494       // Register one
1495       MIB.add(TheVCMP->getOperand(1));
1496       // Register two
1497       MIB.add(TheVCMP->getOperand(2));
1498       // The comparison code, e.g. ge, eq, lt
1499       MIB.add(TheVCMP->getOperand(3));
1500       LLVM_DEBUG(dbgs() << "ARM Loops: Combining with VCMP to VPT: " << *MIB);
1501       LoLoop.BlockMasksToRecompute.insert(MIB.getInstr());
1502       LoLoop.ToRemove.insert(TheVCMP);
1503       TheVCMP = nullptr;
1504     };
1505 
1506     if (VPTState::isEntryPredicatedOnVCTP(Block, /*exclusive*/ true)) {
1507       MachineInstr *VPST = Insts.front();
1508       if (VPTState::hasUniformPredicate(Block)) {
1509         // A vpt block starting with VPST, is only predicated upon vctp and has no
1510         // internal vpr defs:
1511         // - Remove vpst.
1512         // - Unpredicate the remaining instructions.
1513         LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST);
1514         for (unsigned i = 1; i < Insts.size(); ++i)
1515           RemovePredicate(Insts[i]);
1516       } else {
1517         // The VPT block has a non-uniform predicate but it uses a vpst and its
1518         // entry is guarded only by a vctp, which means we:
1519         // - Need to remove the original vpst.
1520         // - Then need to unpredicate any following instructions, until
1521         //   we come across the divergent vpr def.
1522         // - Insert a new vpst to predicate the instruction(s) that following
1523         //   the divergent vpr def.
1524         MachineInstr *Divergent = VPTState::getDivergent(Block);
1525         auto DivergentNext = ++MachineBasicBlock::iterator(Divergent);
1526         bool DivergentNextIsPredicated =
1527             getVPTInstrPredicate(*DivergentNext) != ARMVCC::None;
1528 
1529         for (auto I = ++MachineBasicBlock::iterator(VPST), E = DivergentNext;
1530              I != E; ++I)
1531           RemovePredicate(&*I);
1532 
1533         // Check if the instruction defining vpr is a vcmp so it can be combined
1534         // with the VPST This should be the divergent instruction
1535         MachineInstr *VCMP =
1536             VCMPOpcodeToVPT(Divergent->getOpcode()) != 0 ? Divergent : nullptr;
1537 
1538         if (DivergentNextIsPredicated) {
1539           // Insert a VPST at the divergent only if the next instruction
1540           // would actually use it. A VCMP following a VPST can be
1541           // merged into a VPT so do that instead if the VCMP exists.
1542           if (!VCMP) {
1543             // Create a VPST (with a null mask for now, we'll recompute it
1544             // later)
1545             MachineInstrBuilder MIB =
1546                 BuildMI(*Divergent->getParent(), Divergent,
1547                         Divergent->getDebugLoc(), TII->get(ARM::MVE_VPST));
1548             MIB.addImm(0);
1549             LLVM_DEBUG(dbgs() << "ARM Loops: Created VPST: " << *MIB);
1550             LoLoop.BlockMasksToRecompute.insert(MIB.getInstr());
1551           } else {
1552             // No RDA checks are necessary here since the VPST would have been
1553             // directly after the VCMP
1554             ReplaceVCMPWithVPT(VCMP, VCMP);
1555           }
1556         }
1557       }
1558       LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST);
1559       LoLoop.ToRemove.insert(VPST);
1560     } else if (Block.containsVCTP()) {
1561       // The vctp will be removed, so the block mask of the vp(s)t will need
1562       // to be recomputed.
1563       LoLoop.BlockMasksToRecompute.insert(Insts.front());
1564     } else if (Insts.front()->getOpcode() == ARM::MVE_VPST) {
1565       // If this block starts with a VPST then attempt to merge it with the
1566       // preceeding un-merged VCMP into a VPT. This VCMP comes from a VPT
1567       // block that no longer exists
1568       MachineInstr *VPST = Insts.front();
1569       auto Next = ++MachineBasicBlock::iterator(VPST);
1570       assert(getVPTInstrPredicate(*Next) != ARMVCC::None &&
1571              "The instruction after a VPST must be predicated");
1572 
1573       MachineInstr *VprDef = RDA->getUniqueReachingMIDef(VPST, ARM::VPR);
1574       if (VprDef && VCMPOpcodeToVPT(VprDef->getOpcode()) &&
1575           !LoLoop.ToRemove.contains(VprDef)) {
1576         MachineInstr *VCMP = VprDef;
1577         // The VCMP and VPST can only be merged if the VCMP's operands will have
1578         // the same values at the VPST
1579         if (RDA->hasSameReachingDef(VCMP, VPST, VCMP->getOperand(1).getReg()) &&
1580             RDA->hasSameReachingDef(VCMP, VPST, VCMP->getOperand(2).getReg())) {
1581           bool IntermediateInstrsUseVPR =
1582               std::any_of(++MachineBasicBlock::iterator(VCMP),
1583                           MachineBasicBlock::iterator(VPST), hasVPRUse);
1584           // If the instruction after the VCMP is predicated then a different
1585           // code path is expected to have merged the VCMP and VPST already.
1586           // This assertion protects against changes to that behaviour
1587           assert(!IntermediateInstrsUseVPR &&
1588                  "Instructions between the VCMP and VPST are not expected to "
1589                  "be predicated");
1590           ReplaceVCMPWithVPT(VCMP, VPST);
1591           LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST);
1592           LoLoop.ToRemove.insert(VPST);
1593         }
1594       }
1595     }
1596   }
1597 
1598   LoLoop.ToRemove.insert(LoLoop.VCTPs.begin(), LoLoop.VCTPs.end());
1599 }
1600 
1601 void ARMLowOverheadLoops::Expand(LowOverheadLoop &LoLoop) {
1602 
1603   // Combine the LoopDec and LoopEnd instructions into LE(TP).
1604   auto ExpandLoopEnd = [this](LowOverheadLoop &LoLoop) {
1605     MachineInstr *End = LoLoop.End;
1606     MachineBasicBlock *MBB = End->getParent();
1607     unsigned Opc = LoLoop.IsTailPredicationLegal() ?
1608       ARM::MVE_LETP : ARM::t2LEUpdate;
1609     MachineInstrBuilder MIB = BuildMI(*MBB, End, End->getDebugLoc(),
1610                                       TII->get(Opc));
1611     MIB.addDef(ARM::LR);
1612     MIB.add(End->getOperand(0));
1613     MIB.add(End->getOperand(1));
1614     LLVM_DEBUG(dbgs() << "ARM Loops: Inserted LE: " << *MIB);
1615     LoLoop.ToRemove.insert(LoLoop.Dec);
1616     LoLoop.ToRemove.insert(End);
1617     return &*MIB;
1618   };
1619 
1620   // TODO: We should be able to automatically remove these branches before we
1621   // get here - probably by teaching analyzeBranch about the pseudo
1622   // instructions.
1623   // If there is an unconditional branch, after I, that just branches to the
1624   // next block, remove it.
1625   auto RemoveDeadBranch = [](MachineInstr *I) {
1626     MachineBasicBlock *BB = I->getParent();
1627     MachineInstr *Terminator = &BB->instr_back();
1628     if (Terminator->isUnconditionalBranch() && I != Terminator) {
1629       MachineBasicBlock *Succ = Terminator->getOperand(0).getMBB();
1630       if (BB->isLayoutSuccessor(Succ)) {
1631         LLVM_DEBUG(dbgs() << "ARM Loops: Removing branch: " << *Terminator);
1632         Terminator->eraseFromParent();
1633       }
1634     }
1635   };
1636 
1637   if (LoLoop.Revert) {
1638     if (LoLoop.Start->getOpcode() == ARM::t2WhileLoopStart)
1639       RevertWhile(LoLoop.Start);
1640     else
1641       RevertDo(LoLoop.Start);
1642     bool FlagsAlreadySet = RevertLoopDec(LoLoop.Dec);
1643     RevertLoopEnd(LoLoop.End, FlagsAlreadySet);
1644   } else {
1645     LoLoop.Start = ExpandLoopStart(LoLoop);
1646     RemoveDeadBranch(LoLoop.Start);
1647     LoLoop.End = ExpandLoopEnd(LoLoop);
1648     RemoveDeadBranch(LoLoop.End);
1649     if (LoLoop.IsTailPredicationLegal())
1650       ConvertVPTBlocks(LoLoop);
1651     for (auto *I : LoLoop.ToRemove) {
1652       LLVM_DEBUG(dbgs() << "ARM Loops: Erasing " << *I);
1653       I->eraseFromParent();
1654     }
1655     for (auto *I : LoLoop.BlockMasksToRecompute) {
1656       LLVM_DEBUG(dbgs() << "ARM Loops: Recomputing VPT/VPST Block Mask: " << *I);
1657       recomputeVPTBlockMask(*I);
1658       LLVM_DEBUG(dbgs() << "           ... done: " << *I);
1659     }
1660   }
1661 
1662   PostOrderLoopTraversal DFS(LoLoop.ML, *MLI);
1663   DFS.ProcessLoop();
1664   const SmallVectorImpl<MachineBasicBlock*> &PostOrder = DFS.getOrder();
1665   for (auto *MBB : PostOrder) {
1666     recomputeLiveIns(*MBB);
1667     // FIXME: For some reason, the live-in print order is non-deterministic for
1668     // our tests and I can't out why... So just sort them.
1669     MBB->sortUniqueLiveIns();
1670   }
1671 
1672   for (auto *MBB : reverse(PostOrder))
1673     recomputeLivenessFlags(*MBB);
1674 
1675   // We've moved, removed and inserted new instructions, so update RDA.
1676   RDA->reset();
1677 }
1678 
1679 bool ARMLowOverheadLoops::RevertNonLoops() {
1680   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting any remaining pseudos...\n");
1681   bool Changed = false;
1682 
1683   for (auto &MBB : *MF) {
1684     SmallVector<MachineInstr*, 4> Starts;
1685     SmallVector<MachineInstr*, 4> Decs;
1686     SmallVector<MachineInstr*, 4> Ends;
1687 
1688     for (auto &I : MBB) {
1689       if (isLoopStart(I))
1690         Starts.push_back(&I);
1691       else if (I.getOpcode() == ARM::t2LoopDec)
1692         Decs.push_back(&I);
1693       else if (I.getOpcode() == ARM::t2LoopEnd)
1694         Ends.push_back(&I);
1695     }
1696 
1697     if (Starts.empty() && Decs.empty() && Ends.empty())
1698       continue;
1699 
1700     Changed = true;
1701 
1702     for (auto *Start : Starts) {
1703       if (Start->getOpcode() == ARM::t2WhileLoopStart)
1704         RevertWhile(Start);
1705       else
1706         RevertDo(Start);
1707     }
1708     for (auto *Dec : Decs)
1709       RevertLoopDec(Dec);
1710 
1711     for (auto *End : Ends)
1712       RevertLoopEnd(End);
1713   }
1714   return Changed;
1715 }
1716 
1717 FunctionPass *llvm::createARMLowOverheadLoopsPass() {
1718   return new ARMLowOverheadLoops();
1719 }
1720