xref: /llvm-project/llvm/lib/Target/ARM/ARMLowOverheadLoops.cpp (revision ff9ac33e1e02a7c637b8cdf081a7d88f40bf387f)
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;
179     MachineLoopInfo &MLI;
180     ReachingDefAnalysis &RDA;
181     const TargetRegisterInfo &TRI;
182     MachineFunction *MF = nullptr;
183     MachineInstr *InsertPt = nullptr;
184     MachineInstr *Start = nullptr;
185     MachineInstr *Dec = nullptr;
186     MachineInstr *End = nullptr;
187     MachineInstr *VCTP = nullptr;
188     VPTBlock *CurrentBlock = nullptr;
189     SetVector<MachineInstr*> CurrentPredicate;
190     SmallVector<VPTBlock, 4> VPTBlocks;
191     SmallPtrSet<MachineInstr*, 4> ToRemove;
192     bool Revert = false;
193     bool CannotTailPredicate = false;
194 
195     LowOverheadLoop(MachineLoop &ML, MachineLoopInfo &MLI,
196                     ReachingDefAnalysis &RDA, const TargetRegisterInfo &TRI)
197       : ML(ML), MLI(MLI), RDA(RDA), TRI(TRI) {
198       MF = ML.getHeader()->getParent();
199     }
200 
201     // If this is an MVE instruction, check that we know how to use tail
202     // predication with it. Record VPT blocks and return whether the
203     // instruction is valid for tail predication.
204     bool ValidateMVEInst(MachineInstr *MI);
205 
206     void AnalyseMVEInst(MachineInstr *MI) {
207       CannotTailPredicate = !ValidateMVEInst(MI);
208     }
209 
210     bool IsTailPredicationLegal() const {
211       // For now, let's keep things really simple and only support a single
212       // block for tail predication.
213       return !Revert && FoundAllComponents() && VCTP &&
214              !CannotTailPredicate && ML.getNumBlocks() == 1;
215     }
216 
217     // Check that the predication in the loop will be equivalent once we
218     // perform the conversion. Also ensure that we can provide the number
219     // of elements to the loop start instruction.
220     bool ValidateTailPredicate(MachineInstr *StartInsertPt);
221 
222     // Check that any values available outside of the loop will be the same
223     // after tail predication conversion.
224     bool ValidateLiveOuts() const;
225 
226     // Is it safe to define LR with DLS/WLS?
227     // LR can be defined if it is the operand to start, because it's the same
228     // value, or if it's going to be equivalent to the operand to Start.
229     MachineInstr *isSafeToDefineLR();
230 
231     // Check the branch targets are within range and we satisfy our
232     // restrictions.
233     void CheckLegality(ARMBasicBlockUtils *BBUtils);
234 
235     bool FoundAllComponents() const {
236       return Start && Dec && End;
237     }
238 
239     SmallVectorImpl<VPTBlock> &getVPTBlocks() { return VPTBlocks; }
240 
241     // Return the loop iteration count, or the number of elements if we're tail
242     // predicating.
243     MachineOperand &getCount() {
244       return IsTailPredicationLegal() ?
245         VCTP->getOperand(1) : Start->getOperand(0);
246     }
247 
248     unsigned getStartOpcode() const {
249       bool IsDo = Start->getOpcode() == ARM::t2DoLoopStart;
250       if (!IsTailPredicationLegal())
251         return IsDo ? ARM::t2DLS : ARM::t2WLS;
252 
253       return VCTPOpcodeToLSTP(VCTP->getOpcode(), IsDo);
254     }
255 
256     void dump() const {
257       if (Start) dbgs() << "ARM Loops: Found Loop Start: " << *Start;
258       if (Dec) dbgs() << "ARM Loops: Found Loop Dec: " << *Dec;
259       if (End) dbgs() << "ARM Loops: Found Loop End: " << *End;
260       if (VCTP) dbgs() << "ARM Loops: Found VCTP: " << *VCTP;
261       if (!FoundAllComponents())
262         dbgs() << "ARM Loops: Not a low-overhead loop.\n";
263       else if (!(Start && Dec && End))
264         dbgs() << "ARM Loops: Failed to find all loop components.\n";
265     }
266   };
267 
268   class ARMLowOverheadLoops : public MachineFunctionPass {
269     MachineFunction           *MF = nullptr;
270     MachineLoopInfo           *MLI = nullptr;
271     ReachingDefAnalysis       *RDA = nullptr;
272     const ARMBaseInstrInfo    *TII = nullptr;
273     MachineRegisterInfo       *MRI = nullptr;
274     const TargetRegisterInfo  *TRI = nullptr;
275     std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr;
276 
277   public:
278     static char ID;
279 
280     ARMLowOverheadLoops() : MachineFunctionPass(ID) { }
281 
282     void getAnalysisUsage(AnalysisUsage &AU) const override {
283       AU.setPreservesCFG();
284       AU.addRequired<MachineLoopInfo>();
285       AU.addRequired<ReachingDefAnalysis>();
286       MachineFunctionPass::getAnalysisUsage(AU);
287     }
288 
289     bool runOnMachineFunction(MachineFunction &MF) override;
290 
291     MachineFunctionProperties getRequiredProperties() const override {
292       return MachineFunctionProperties().set(
293           MachineFunctionProperties::Property::NoVRegs).set(
294           MachineFunctionProperties::Property::TracksLiveness);
295     }
296 
297     StringRef getPassName() const override {
298       return ARM_LOW_OVERHEAD_LOOPS_NAME;
299     }
300 
301   private:
302     bool ProcessLoop(MachineLoop *ML);
303 
304     bool RevertNonLoops();
305 
306     void RevertWhile(MachineInstr *MI) const;
307 
308     bool RevertLoopDec(MachineInstr *MI) const;
309 
310     void RevertLoopEnd(MachineInstr *MI, bool SkipCmp = false) const;
311 
312     void ConvertVPTBlocks(LowOverheadLoop &LoLoop);
313 
314     MachineInstr *ExpandLoopStart(LowOverheadLoop &LoLoop);
315 
316     void Expand(LowOverheadLoop &LoLoop);
317 
318     void IterationCountDCE(LowOverheadLoop &LoLoop);
319   };
320 }
321 
322 char ARMLowOverheadLoops::ID = 0;
323 
324 INITIALIZE_PASS(ARMLowOverheadLoops, DEBUG_TYPE, ARM_LOW_OVERHEAD_LOOPS_NAME,
325                 false, false)
326 
327 MachineInstr *LowOverheadLoop::isSafeToDefineLR() {
328   // We can define LR because LR already contains the same value.
329   if (Start->getOperand(0).getReg() == ARM::LR)
330     return Start;
331 
332   unsigned CountReg = Start->getOperand(0).getReg();
333   auto IsMoveLR = [&CountReg](MachineInstr *MI) {
334     return MI->getOpcode() == ARM::tMOVr &&
335            MI->getOperand(0).getReg() == ARM::LR &&
336            MI->getOperand(1).getReg() == CountReg &&
337            MI->getOperand(2).getImm() == ARMCC::AL;
338    };
339 
340   MachineBasicBlock *MBB = Start->getParent();
341 
342   // Find an insertion point:
343   // - Is there a (mov lr, Count) before Start? If so, and nothing else writes
344   //   to Count before Start, we can insert at that mov.
345   if (auto *LRDef = RDA.getUniqueReachingMIDef(Start, ARM::LR))
346     if (IsMoveLR(LRDef) && RDA.hasSameReachingDef(Start, LRDef, CountReg))
347       return LRDef;
348 
349   // - Is there a (mov lr, Count) after Start? If so, and nothing else writes
350   //   to Count after Start, we can insert at that mov.
351   if (auto *LRDef = RDA.getLocalLiveOutMIDef(MBB, ARM::LR))
352     if (IsMoveLR(LRDef) && RDA.hasSameReachingDef(Start, LRDef, CountReg))
353       return LRDef;
354 
355   // We've found no suitable LR def and Start doesn't use LR directly. Can we
356   // just define LR anyway?
357   return RDA.isSafeToDefRegAt(Start, ARM::LR) ? Start : nullptr;
358 }
359 
360 bool LowOverheadLoop::ValidateTailPredicate(MachineInstr *StartInsertPt) {
361   assert(VCTP && "VCTP instruction expected but is not set");
362   // All predication within the loop should be based on vctp. If the block
363   // isn't predicated on entry, check whether the vctp is within the block
364   // and that all other instructions are then predicated on it.
365   for (auto &Block : VPTBlocks) {
366     if (Block.IsPredicatedOn(VCTP))
367       continue;
368     if (!Block.HasNonUniformPredicate() || !isVCTP(Block.getDivergent()->MI)) {
369       LLVM_DEBUG(dbgs() << "ARM Loops: Found unsupported diverging predicate: "
370                  << *Block.getDivergent()->MI);
371       return false;
372     }
373     SmallVectorImpl<PredicatedMI> &Insts = Block.getInsts();
374     for (auto &PredMI : Insts) {
375       if (PredMI.Predicates.count(VCTP) || isVCTP(PredMI.MI))
376         continue;
377       LLVM_DEBUG(dbgs() << "ARM Loops: Can't convert: " << *PredMI.MI
378                  << " - which is predicated on:\n";
379                  for (auto *MI : PredMI.Predicates)
380                    dbgs() << "   - " << *MI);
381       return false;
382     }
383   }
384 
385   if (!ValidateLiveOuts())
386     return false;
387 
388   // For tail predication, we need to provide the number of elements, instead
389   // of the iteration count, to the loop start instruction. The number of
390   // elements is provided to the vctp instruction, so we need to check that
391   // we can use this register at InsertPt.
392   Register NumElements = VCTP->getOperand(1).getReg();
393 
394   // If the register is defined within loop, then we can't perform TP.
395   // TODO: Check whether this is just a mov of a register that would be
396   // available.
397   if (RDA.hasLocalDefBefore(VCTP, NumElements)) {
398     LLVM_DEBUG(dbgs() << "ARM Loops: VCTP operand is defined in the loop.\n");
399     return false;
400   }
401 
402   // The element count register maybe defined after InsertPt, in which case we
403   // need to try to move either InsertPt or the def so that the [w|d]lstp can
404   // use the value.
405   // TODO: On failing to move an instruction, check if the count is provided by
406   // a mov and whether we can use the mov operand directly.
407   MachineBasicBlock *InsertBB = StartInsertPt->getParent();
408   if (!RDA.isReachingDefLiveOut(StartInsertPt, NumElements)) {
409     if (auto *ElemDef = RDA.getLocalLiveOutMIDef(InsertBB, NumElements)) {
410       if (RDA.isSafeToMoveForwards(ElemDef, StartInsertPt)) {
411         ElemDef->removeFromParent();
412         InsertBB->insert(MachineBasicBlock::iterator(StartInsertPt), ElemDef);
413         LLVM_DEBUG(dbgs() << "ARM Loops: Moved element count def: "
414                    << *ElemDef);
415       } else if (RDA.isSafeToMoveBackwards(StartInsertPt, ElemDef)) {
416         StartInsertPt->removeFromParent();
417         InsertBB->insertAfter(MachineBasicBlock::iterator(ElemDef),
418                               StartInsertPt);
419         LLVM_DEBUG(dbgs() << "ARM Loops: Moved start past: " << *ElemDef);
420       } else {
421         LLVM_DEBUG(dbgs() << "ARM Loops: Unable to move element count to loop "
422                    << "start instruction.\n");
423         return false;
424       }
425     }
426   }
427 
428   // Especially in the case of while loops, InsertBB may not be the
429   // preheader, so we need to check that the register isn't redefined
430   // before entering the loop.
431   auto CannotProvideElements = [this](MachineBasicBlock *MBB,
432                                       Register NumElements) {
433     // NumElements is redefined in this block.
434     if (RDA.hasLocalDefBefore(&MBB->back(), NumElements))
435       return true;
436 
437     // Don't continue searching up through multiple predecessors.
438     if (MBB->pred_size() > 1)
439       return true;
440 
441     return false;
442   };
443 
444   // First, find the block that looks like the preheader.
445   MachineBasicBlock *MBB = MLI.findLoopPreheader(&ML, true);
446   if (!MBB) {
447     LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find preheader.\n");
448     return false;
449   }
450 
451   // Then search backwards for a def, until we get to InsertBB.
452   while (MBB != InsertBB) {
453     if (CannotProvideElements(MBB, NumElements)) {
454       LLVM_DEBUG(dbgs() << "ARM Loops: Unable to provide element count.\n");
455       return false;
456     }
457     MBB = *MBB->pred_begin();
458   }
459 
460   // Check that the value change of the element count is what we expect and
461   // that the predication will be equivalent. For this we need:
462   // NumElements = NumElements - VectorWidth. The sub will be a sub immediate
463   // and we can also allow register copies within the chain too.
464   auto IsValidSub = [](MachineInstr *MI, unsigned ExpectedVecWidth) {
465     unsigned ImmOpIdx = 0;
466     switch (MI->getOpcode()) {
467     default:
468       llvm_unreachable("unhandled sub opcode");
469     case ARM::tSUBi3:
470     case ARM::tSUBi8:
471       ImmOpIdx = 3;
472       break;
473     case ARM::t2SUBri:
474     case ARM::t2SUBri12:
475       ImmOpIdx = 2;
476       break;
477     }
478     return MI->getOperand(ImmOpIdx).getImm() == ExpectedVecWidth;
479   };
480 
481   MBB = VCTP->getParent();
482   if (auto *Def = RDA.getUniqueReachingMIDef(&MBB->back(), NumElements)) {
483     SmallPtrSet<MachineInstr*, 2> ElementChain;
484     SmallPtrSet<MachineInstr*, 2> Ignore = { VCTP };
485     unsigned ExpectedVectorWidth = getTailPredVectorWidth(VCTP->getOpcode());
486 
487     if (RDA.isSafeToRemove(Def, ElementChain, Ignore)) {
488       bool FoundSub = false;
489 
490       for (auto *MI : ElementChain) {
491         if (isMovRegOpcode(MI->getOpcode()))
492           continue;
493 
494         if (isSubImmOpcode(MI->getOpcode())) {
495           if (FoundSub || !IsValidSub(MI, ExpectedVectorWidth))
496             return false;
497           FoundSub = true;
498         } else
499           return false;
500       }
501 
502       LLVM_DEBUG(dbgs() << "ARM Loops: Will remove element count chain:\n";
503                  for (auto *MI : ElementChain)
504                    dbgs() << " - " << *MI);
505       ToRemove.insert(ElementChain.begin(), ElementChain.end());
506     }
507   }
508   return true;
509 }
510 
511 static bool isVectorPredicated(MachineInstr *MI) {
512   int PIdx = llvm::findFirstVPTPredOperandIdx(*MI);
513   return PIdx != -1 && MI->getOperand(PIdx + 1).getReg() == ARM::VPR;
514 }
515 
516 static bool isRegInClass(const MachineOperand &MO,
517                          const TargetRegisterClass *Class) {
518   return MO.isReg() && MO.getReg() && Class->contains(MO.getReg());
519 }
520 
521 bool LowOverheadLoop::ValidateLiveOuts() const {
522   // Collect Q-regs that are live in the exit blocks. We don't collect scalars
523   // because they won't be affected by lane predication.
524   const TargetRegisterClass *QPRs = TRI.getRegClass(ARM::MQPRRegClassID);
525   SmallSet<Register, 2> LiveOuts;
526   SmallVector<MachineBasicBlock *, 2> ExitBlocks;
527   ML.getExitBlocks(ExitBlocks);
528   for (auto *MBB : ExitBlocks)
529     for (const MachineBasicBlock::RegisterMaskPair &RegMask : MBB->liveins())
530       if (QPRs->contains(RegMask.PhysReg))
531         LiveOuts.insert(RegMask.PhysReg);
532 
533   // Collect the instructions in the loop body that define the live-out values.
534   SmallPtrSet<MachineInstr *, 2> LiveMIs;
535   assert(ML.getNumBlocks() == 1 && "Expected single block loop!");
536   MachineBasicBlock *MBB = ML.getHeader();
537   for (auto Reg : LiveOuts)
538     if (auto *MI = RDA.getLocalLiveOutMIDef(MBB, Reg))
539       LiveMIs.insert(MI);
540 
541   LLVM_DEBUG(dbgs() << "ARM Loops: Found loop live-outs:\n";
542              for (auto *MI : LiveMIs)
543                dbgs() << " - " << *MI);
544   // We've already validated that any VPT predication within the loop will be
545   // equivalent when we perform the predication transformation; so we know that
546   // any VPT predicated instruction is predicated upon VCTP. Any live-out
547   // instruction needs to be predicated, so check this here.
548   for (auto *MI : LiveMIs)
549     if (!isVectorPredicated(MI))
550       return false;
551 
552   // We want to find out if the tail-predicated version of this loop will
553   // produce the same values as the loop in its original form. For this to
554   // be true, the newly inserted implicit predication must not change the
555   // the (observable) results.
556   // We're doing this because many instructions in the loop will not be
557   // predicated and so the conversion from VPT predication to tail-predication
558   // can result in different values being produced; due to the tail-predication
559   // preventing many instructions from updating their falsely predicated
560   // lanes. This analysis assumes that all the instructions perform lane-wise
561   // operations and don't perform any exchanges.
562   // A masked load, whether through VPT or tail predication, will write zeros
563   // to any of the falsely predicated bytes. So, from the loads, we know that
564   // the false lanes are zeroed and here we're trying to track that those false
565   // lanes remain zero, or where they change, the differences are masked away
566   // by their user(s).
567   // All MVE loads and stores have to be predicated, so we know that any load
568   // operands, or stored results are equivalent already. Other explicitly
569   // predicated instructions will perform the same operation in the original
570   // loop and the tail-predicated form too. Because of this, we can insert
571   // loads, stores and other predicated instructions into our KnownFalseZeros
572   // set and build from there.
573   SetVector<MachineInstr *> UnknownFalseLanes;
574   SmallPtrSet<MachineInstr *, 4> KnownFalseZeros;
575   for (auto &MI : *MBB) {
576     const MCInstrDesc &MCID = MI.getDesc();
577     uint64_t Flags = MCID.TSFlags;
578     if ((Flags & ARMII::DomainMask) != ARMII::DomainMVE)
579       continue;
580 
581     if (isVectorPredicated(&MI)) {
582       KnownFalseZeros.insert(&MI);
583       continue;
584     }
585 
586     if (MI.getNumDefs() == 0)
587       continue;
588 
589     // Only evaluate instructions which produce a single value.
590     assert((MI.getNumDefs() == 1 && MI.defs().begin()->isReg()) &&
591            "Expected no more than one register def");
592 
593     Register DefReg = MI.defs().begin()->getReg();
594     for (auto &MO : MI.operands()) {
595       if (!isRegInClass(MO, QPRs) || !MO.isUse() || MO.getReg() != DefReg)
596         continue;
597 
598       // If this instruction overwrites one of its operands, and that register
599       // has known lanes, then this instruction also has known predicated false
600       // lanes.
601       if (auto *OpDef = RDA.getMIOperand(&MI, MO)) {
602         if (KnownFalseZeros.count(OpDef)) {
603           KnownFalseZeros.insert(&MI);
604           break;
605         }
606       }
607     }
608     if (!KnownFalseZeros.count(&MI))
609       UnknownFalseLanes.insert(&MI);
610   }
611 
612   auto HasKnownUsers = [this](MachineInstr *MI, const MachineOperand &MO,
613                               SmallPtrSetImpl<MachineInstr *> &Knowns) {
614     SmallPtrSet<MachineInstr *, 2> Uses;
615     RDA.getGlobalUses(MI, MO.getReg(), Uses);
616     for (auto *Use : Uses) {
617       if (Use != MI && !Knowns.count(Use))
618         return false;
619     }
620     return true;
621   };
622 
623   // Now for all the unknown values, see if they're only consumed by known
624   // instructions. Visit in reverse so that we can start at the values being
625   // stored and then we can work towards the leaves, hopefully adding more
626   // instructions to KnownFalseZeros.
627   for (auto *MI : reverse(UnknownFalseLanes)) {
628     for (auto &MO : MI->operands()) {
629       if (!isRegInClass(MO, QPRs) || !MO.isDef())
630         continue;
631       if (!HasKnownUsers(MI, MO, KnownFalseZeros)) {
632         LLVM_DEBUG(dbgs() << "ARM Loops: Found an unknown def of : "
633                           << TRI.getRegAsmName(MO.getReg()) << " at " << *MI);
634         return false;
635       }
636     }
637     // Any unknown false lanes have been masked away by the user(s).
638     KnownFalseZeros.insert(MI);
639   }
640   return true;
641 }
642 
643 void LowOverheadLoop::CheckLegality(ARMBasicBlockUtils *BBUtils) {
644   if (Revert)
645     return;
646 
647   if (!End->getOperand(1).isMBB())
648     report_fatal_error("Expected LoopEnd to target basic block");
649 
650   // TODO Maybe there's cases where the target doesn't have to be the header,
651   // but for now be safe and revert.
652   if (End->getOperand(1).getMBB() != ML.getHeader()) {
653     LLVM_DEBUG(dbgs() << "ARM Loops: LoopEnd is not targetting header.\n");
654     Revert = true;
655     return;
656   }
657 
658   // The WLS and LE instructions have 12-bits for the label offset. WLS
659   // requires a positive offset, while LE uses negative.
660   if (BBUtils->getOffsetOf(End) < BBUtils->getOffsetOf(ML.getHeader()) ||
661       !BBUtils->isBBInRange(End, ML.getHeader(), 4094)) {
662     LLVM_DEBUG(dbgs() << "ARM Loops: LE offset is out-of-range\n");
663     Revert = true;
664     return;
665   }
666 
667   if (Start->getOpcode() == ARM::t2WhileLoopStart &&
668       (BBUtils->getOffsetOf(Start) >
669        BBUtils->getOffsetOf(Start->getOperand(1).getMBB()) ||
670        !BBUtils->isBBInRange(Start, Start->getOperand(1).getMBB(), 4094))) {
671     LLVM_DEBUG(dbgs() << "ARM Loops: WLS offset is out-of-range!\n");
672     Revert = true;
673     return;
674   }
675 
676   InsertPt = Revert ? nullptr : isSafeToDefineLR();
677   if (!InsertPt) {
678     LLVM_DEBUG(dbgs() << "ARM Loops: Unable to find safe insertion point.\n");
679     Revert = true;
680     return;
681   } else
682     LLVM_DEBUG(dbgs() << "ARM Loops: Start insertion point: " << *InsertPt);
683 
684   if (!IsTailPredicationLegal()) {
685     LLVM_DEBUG(if (!VCTP)
686                  dbgs() << "ARM Loops: Didn't find a VCTP instruction.\n";
687                dbgs() << "ARM Loops: Tail-predication is not valid.\n");
688     return;
689   }
690 
691   assert(ML.getBlocks().size() == 1 &&
692          "Shouldn't be processing a loop with more than one block");
693   CannotTailPredicate = !ValidateTailPredicate(InsertPt);
694   LLVM_DEBUG(if (CannotTailPredicate)
695              dbgs() << "ARM Loops: Couldn't validate tail predicate.\n");
696 }
697 
698 bool LowOverheadLoop::ValidateMVEInst(MachineInstr* MI) {
699   if (CannotTailPredicate)
700     return false;
701 
702   // Only support a single vctp.
703   if (isVCTP(MI) && VCTP)
704     return false;
705 
706   // Start a new vpt block when we discover a vpt.
707   if (MI->getOpcode() == ARM::MVE_VPST) {
708     VPTBlocks.emplace_back(MI, CurrentPredicate);
709     CurrentBlock = &VPTBlocks.back();
710     return true;
711   } else if (isVCTP(MI))
712     VCTP = MI;
713   else if (MI->getOpcode() == ARM::MVE_VPSEL ||
714            MI->getOpcode() == ARM::MVE_VPNOT)
715     return false;
716 
717   // TODO: Allow VPSEL and VPNOT, we currently cannot because:
718   // 1) It will use the VPR as a predicate operand, but doesn't have to be
719   //    instead a VPT block, which means we can assert while building up
720   //    the VPT block because we don't find another VPST to being a new
721   //    one.
722   // 2) VPSEL still requires a VPR operand even after tail predicating,
723   //    which means we can't remove it unless there is another
724   //    instruction, such as vcmp, that can provide the VPR def.
725 
726   bool IsUse = false;
727   bool IsDef = false;
728   const MCInstrDesc &MCID = MI->getDesc();
729   for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
730     const MachineOperand &MO = MI->getOperand(i);
731     if (!MO.isReg() || MO.getReg() != ARM::VPR)
732       continue;
733 
734     if (MO.isDef()) {
735       CurrentPredicate.insert(MI);
736       IsDef = true;
737     } else if (ARM::isVpred(MCID.OpInfo[i].OperandType)) {
738       CurrentBlock->addInst(MI, CurrentPredicate);
739       IsUse = true;
740     } else {
741       LLVM_DEBUG(dbgs() << "ARM Loops: Found instruction using vpr: " << *MI);
742       return false;
743     }
744   }
745 
746   // If we find a vpr def that is not already predicated on the vctp, we've
747   // got disjoint predicates that may not be equivalent when we do the
748   // conversion.
749   if (IsDef && !IsUse && VCTP && !isVCTP(MI)) {
750     LLVM_DEBUG(dbgs() << "ARM Loops: Found disjoint vpr def: " << *MI);
751     return false;
752   }
753 
754   uint64_t Flags = MCID.TSFlags;
755   if ((Flags & ARMII::DomainMask) != ARMII::DomainMVE)
756     return true;
757 
758   // If we find an instruction that has been marked as not valid for tail
759   // predication, only allow the instruction if it's contained within a valid
760   // VPT block.
761   if ((Flags & ARMII::ValidForTailPredication) == 0 && !IsUse) {
762     LLVM_DEBUG(dbgs() << "ARM Loops: Can't tail predicate: " << *MI);
763     return false;
764   }
765 
766   // If the instruction is already explicitly predicated, then the conversion
767   // will be fine, but ensure that all memory operations are predicated.
768   return !IsUse && MI->mayLoadOrStore() ? false : true;
769 }
770 
771 bool ARMLowOverheadLoops::runOnMachineFunction(MachineFunction &mf) {
772   const ARMSubtarget &ST = static_cast<const ARMSubtarget&>(mf.getSubtarget());
773   if (!ST.hasLOB())
774     return false;
775 
776   MF = &mf;
777   LLVM_DEBUG(dbgs() << "ARM Loops on " << MF->getName() << " ------------- \n");
778 
779   MLI = &getAnalysis<MachineLoopInfo>();
780   RDA = &getAnalysis<ReachingDefAnalysis>();
781   MF->getProperties().set(MachineFunctionProperties::Property::TracksLiveness);
782   MRI = &MF->getRegInfo();
783   TII = static_cast<const ARMBaseInstrInfo*>(ST.getInstrInfo());
784   TRI = ST.getRegisterInfo();
785   BBUtils = std::unique_ptr<ARMBasicBlockUtils>(new ARMBasicBlockUtils(*MF));
786   BBUtils->computeAllBlockSizes();
787   BBUtils->adjustBBOffsetsAfter(&MF->front());
788 
789   bool Changed = false;
790   for (auto ML : *MLI) {
791     if (!ML->getParentLoop())
792       Changed |= ProcessLoop(ML);
793   }
794   Changed |= RevertNonLoops();
795   return Changed;
796 }
797 
798 bool ARMLowOverheadLoops::ProcessLoop(MachineLoop *ML) {
799 
800   bool Changed = false;
801 
802   // Process inner loops first.
803   for (auto I = ML->begin(), E = ML->end(); I != E; ++I)
804     Changed |= ProcessLoop(*I);
805 
806   LLVM_DEBUG(dbgs() << "ARM Loops: Processing loop containing:\n";
807              if (auto *Preheader = ML->getLoopPreheader())
808                dbgs() << " - " << Preheader->getName() << "\n";
809              else if (auto *Preheader = MLI->findLoopPreheader(ML))
810                dbgs() << " - " << Preheader->getName() << "\n";
811              else if (auto *Preheader = MLI->findLoopPreheader(ML, true))
812                dbgs() << " - " << Preheader->getName() << "\n";
813              for (auto *MBB : ML->getBlocks())
814                dbgs() << " - " << MBB->getName() << "\n";
815             );
816 
817   // Search the given block for a loop start instruction. If one isn't found,
818   // and there's only one predecessor block, search that one too.
819   std::function<MachineInstr*(MachineBasicBlock*)> SearchForStart =
820     [&SearchForStart](MachineBasicBlock *MBB) -> MachineInstr* {
821     for (auto &MI : *MBB) {
822       if (isLoopStart(MI))
823         return &MI;
824     }
825     if (MBB->pred_size() == 1)
826       return SearchForStart(*MBB->pred_begin());
827     return nullptr;
828   };
829 
830   LowOverheadLoop LoLoop(*ML, *MLI, *RDA, *TRI);
831   // Search the preheader for the start intrinsic.
832   // FIXME: I don't see why we shouldn't be supporting multiple predecessors
833   // with potentially multiple set.loop.iterations, so we need to enable this.
834   if (auto *Preheader = ML->getLoopPreheader())
835     LoLoop.Start = SearchForStart(Preheader);
836   else if (auto *Preheader = MLI->findLoopPreheader(ML, true))
837     LoLoop.Start = SearchForStart(Preheader);
838   else
839     return false;
840 
841   // Find the low-overhead loop components and decide whether or not to fall
842   // back to a normal loop. Also look for a vctp instructions and decide
843   // whether we can convert that predicate using tail predication.
844   for (auto *MBB : reverse(ML->getBlocks())) {
845     for (auto &MI : *MBB) {
846       if (MI.isDebugValue())
847         continue;
848       else if (MI.getOpcode() == ARM::t2LoopDec)
849         LoLoop.Dec = &MI;
850       else if (MI.getOpcode() == ARM::t2LoopEnd)
851         LoLoop.End = &MI;
852       else if (isLoopStart(MI))
853         LoLoop.Start = &MI;
854       else if (MI.getDesc().isCall()) {
855         // TODO: Though the call will require LE to execute again, does this
856         // mean we should revert? Always executing LE hopefully should be
857         // faster than performing a sub,cmp,br or even subs,br.
858         LoLoop.Revert = true;
859         LLVM_DEBUG(dbgs() << "ARM Loops: Found call.\n");
860       } else {
861         // Record VPR defs and build up their corresponding vpt blocks.
862         // Check we know how to tail predicate any mve instructions.
863         LoLoop.AnalyseMVEInst(&MI);
864       }
865     }
866   }
867 
868   LLVM_DEBUG(LoLoop.dump());
869   if (!LoLoop.FoundAllComponents()) {
870     LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find loop start, update, end\n");
871     return false;
872   }
873 
874   // Check that the only instruction using LoopDec is LoopEnd.
875   // TODO: Check for copy chains that really have no effect.
876   SmallPtrSet<MachineInstr*, 2> Uses;
877   RDA->getReachingLocalUses(LoLoop.Dec, ARM::LR, Uses);
878   if (Uses.size() > 1 || !Uses.count(LoLoop.End)) {
879     LLVM_DEBUG(dbgs() << "ARM Loops: Unable to remove LoopDec.\n");
880     LoLoop.Revert = true;
881   }
882   LoLoop.CheckLegality(BBUtils.get());
883   Expand(LoLoop);
884   return true;
885 }
886 
887 // WhileLoopStart holds the exit block, so produce a cmp lr, 0 and then a
888 // beq that branches to the exit branch.
889 // TODO: We could also try to generate a cbz if the value in LR is also in
890 // another low register.
891 void ARMLowOverheadLoops::RevertWhile(MachineInstr *MI) const {
892   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp: " << *MI);
893   MachineBasicBlock *MBB = MI->getParent();
894   MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
895                                     TII->get(ARM::t2CMPri));
896   MIB.add(MI->getOperand(0));
897   MIB.addImm(0);
898   MIB.addImm(ARMCC::AL);
899   MIB.addReg(ARM::NoRegister);
900 
901   MachineBasicBlock *DestBB = MI->getOperand(1).getMBB();
902   unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
903     ARM::tBcc : ARM::t2Bcc;
904 
905   MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc));
906   MIB.add(MI->getOperand(1));   // branch target
907   MIB.addImm(ARMCC::EQ);        // condition code
908   MIB.addReg(ARM::CPSR);
909   MI->eraseFromParent();
910 }
911 
912 bool ARMLowOverheadLoops::RevertLoopDec(MachineInstr *MI) const {
913   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to sub: " << *MI);
914   MachineBasicBlock *MBB = MI->getParent();
915   SmallPtrSet<MachineInstr*, 1> Ignore;
916   for (auto I = MachineBasicBlock::iterator(MI), E = MBB->end(); I != E; ++I) {
917     if (I->getOpcode() == ARM::t2LoopEnd) {
918       Ignore.insert(&*I);
919       break;
920     }
921   }
922 
923   // If nothing defines CPSR between LoopDec and LoopEnd, use a t2SUBS.
924   bool SetFlags = RDA->isSafeToDefRegAt(MI, ARM::CPSR, Ignore);
925 
926   MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
927                                     TII->get(ARM::t2SUBri));
928   MIB.addDef(ARM::LR);
929   MIB.add(MI->getOperand(1));
930   MIB.add(MI->getOperand(2));
931   MIB.addImm(ARMCC::AL);
932   MIB.addReg(0);
933 
934   if (SetFlags) {
935     MIB.addReg(ARM::CPSR);
936     MIB->getOperand(5).setIsDef(true);
937   } else
938     MIB.addReg(0);
939 
940   MI->eraseFromParent();
941   return SetFlags;
942 }
943 
944 // Generate a subs, or sub and cmp, and a branch instead of an LE.
945 void ARMLowOverheadLoops::RevertLoopEnd(MachineInstr *MI, bool SkipCmp) const {
946   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp, br: " << *MI);
947 
948   MachineBasicBlock *MBB = MI->getParent();
949   // Create cmp
950   if (!SkipCmp) {
951     MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
952                                       TII->get(ARM::t2CMPri));
953     MIB.addReg(ARM::LR);
954     MIB.addImm(0);
955     MIB.addImm(ARMCC::AL);
956     MIB.addReg(ARM::NoRegister);
957   }
958 
959   MachineBasicBlock *DestBB = MI->getOperand(1).getMBB();
960   unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
961     ARM::tBcc : ARM::t2Bcc;
962 
963   // Create bne
964   MachineInstrBuilder MIB =
965     BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc));
966   MIB.add(MI->getOperand(1));   // branch target
967   MIB.addImm(ARMCC::NE);        // condition code
968   MIB.addReg(ARM::CPSR);
969   MI->eraseFromParent();
970 }
971 
972 // Perform dead code elimation on the loop iteration count setup expression.
973 // If we are tail-predicating, the number of elements to be processed is the
974 // operand of the VCTP instruction in the vector body, see getCount(), which is
975 // register $r3 in this example:
976 //
977 //   $lr = big-itercount-expression
978 //   ..
979 //   t2DoLoopStart renamable $lr
980 //   vector.body:
981 //     ..
982 //     $vpr = MVE_VCTP32 renamable $r3
983 //     renamable $lr = t2LoopDec killed renamable $lr, 1
984 //     t2LoopEnd renamable $lr, %vector.body
985 //     tB %end
986 //
987 // What we would like achieve here is to replace the do-loop start pseudo
988 // instruction t2DoLoopStart with:
989 //
990 //    $lr = MVE_DLSTP_32 killed renamable $r3
991 //
992 // Thus, $r3 which defines the number of elements, is written to $lr,
993 // and then we want to delete the whole chain that used to define $lr,
994 // see the comment below how this chain could look like.
995 //
996 void ARMLowOverheadLoops::IterationCountDCE(LowOverheadLoop &LoLoop) {
997   if (!LoLoop.IsTailPredicationLegal())
998     return;
999 
1000   LLVM_DEBUG(dbgs() << "ARM Loops: Trying DCE on loop iteration count.\n");
1001 
1002   MachineInstr *Def = RDA->getMIOperand(LoLoop.Start, 0);
1003   if (!Def) {
1004     LLVM_DEBUG(dbgs() << "ARM Loops: Couldn't find iteration count.\n");
1005     return;
1006   }
1007 
1008   // Collect and remove the users of iteration count.
1009   SmallPtrSet<MachineInstr*, 4> Killed  = { LoLoop.Start, LoLoop.Dec,
1010                                             LoLoop.End, LoLoop.InsertPt };
1011   SmallPtrSet<MachineInstr*, 2> Remove;
1012   if (RDA->isSafeToRemove(Def, Remove, Killed))
1013     LoLoop.ToRemove.insert(Remove.begin(), Remove.end());
1014   else {
1015     LLVM_DEBUG(dbgs() << "ARM Loops: Unsafe to remove loop iteration count.\n");
1016     return;
1017   }
1018 
1019   // Collect the dead code and the MBBs in which they reside.
1020   RDA->collectKilledOperands(Def, Killed);
1021   SmallPtrSet<MachineBasicBlock*, 2> BasicBlocks;
1022   for (auto *MI : Killed)
1023     BasicBlocks.insert(MI->getParent());
1024 
1025   // Collect IT blocks in all affected basic blocks.
1026   std::map<MachineInstr *, SmallPtrSet<MachineInstr *, 2>> ITBlocks;
1027   for (auto *MBB : BasicBlocks) {
1028     for (auto &MI : *MBB) {
1029       if (MI.getOpcode() != ARM::t2IT)
1030         continue;
1031       RDA->getReachingLocalUses(&MI, ARM::ITSTATE, ITBlocks[&MI]);
1032     }
1033   }
1034 
1035   // If we're removing all of the instructions within an IT block, then
1036   // also remove the IT instruction.
1037   SmallPtrSet<MachineInstr*, 2> ModifiedITs;
1038   for (auto *MI : Killed) {
1039     if (MachineOperand *MO = MI->findRegisterUseOperand(ARM::ITSTATE)) {
1040       MachineInstr *IT = RDA->getMIOperand(MI, *MO);
1041       auto &CurrentBlock = ITBlocks[IT];
1042       CurrentBlock.erase(MI);
1043       if (CurrentBlock.empty())
1044         ModifiedITs.erase(IT);
1045       else
1046         ModifiedITs.insert(IT);
1047     }
1048   }
1049 
1050   // Delete the killed instructions only if we don't have any IT blocks that
1051   // need to be modified because we need to fixup the mask.
1052   // TODO: Handle cases where IT blocks are modified.
1053   if (ModifiedITs.empty()) {
1054     LLVM_DEBUG(dbgs() << "ARM Loops: Will remove iteration count:\n";
1055                for (auto *MI : Killed)
1056                  dbgs() << " - " << *MI);
1057     LoLoop.ToRemove.insert(Killed.begin(), Killed.end());
1058   } else
1059     LLVM_DEBUG(dbgs() << "ARM Loops: Would need to modify IT block(s).\n");
1060 }
1061 
1062 MachineInstr* ARMLowOverheadLoops::ExpandLoopStart(LowOverheadLoop &LoLoop) {
1063   LLVM_DEBUG(dbgs() << "ARM Loops: Expanding LoopStart.\n");
1064   // When using tail-predication, try to delete the dead code that was used to
1065   // calculate the number of loop iterations.
1066   IterationCountDCE(LoLoop);
1067 
1068   MachineInstr *InsertPt = LoLoop.InsertPt;
1069   MachineInstr *Start = LoLoop.Start;
1070   MachineBasicBlock *MBB = InsertPt->getParent();
1071   bool IsDo = Start->getOpcode() == ARM::t2DoLoopStart;
1072   unsigned Opc = LoLoop.getStartOpcode();
1073   MachineOperand &Count = LoLoop.getCount();
1074 
1075   MachineInstrBuilder MIB =
1076     BuildMI(*MBB, InsertPt, InsertPt->getDebugLoc(), TII->get(Opc));
1077 
1078   MIB.addDef(ARM::LR);
1079   MIB.add(Count);
1080   if (!IsDo)
1081     MIB.add(Start->getOperand(1));
1082 
1083   // If we're inserting at a mov lr, then remove it as it's redundant.
1084   if (InsertPt != Start)
1085     LoLoop.ToRemove.insert(InsertPt);
1086   LoLoop.ToRemove.insert(Start);
1087   LLVM_DEBUG(dbgs() << "ARM Loops: Inserted start: " << *MIB);
1088   return &*MIB;
1089 }
1090 
1091 void ARMLowOverheadLoops::ConvertVPTBlocks(LowOverheadLoop &LoLoop) {
1092   auto RemovePredicate = [](MachineInstr *MI) {
1093     LLVM_DEBUG(dbgs() << "ARM Loops: Removing predicate from: " << *MI);
1094     if (int PIdx = llvm::findFirstVPTPredOperandIdx(*MI)) {
1095       assert(MI->getOperand(PIdx).getImm() == ARMVCC::Then &&
1096              "Expected Then predicate!");
1097       MI->getOperand(PIdx).setImm(ARMVCC::None);
1098       MI->getOperand(PIdx+1).setReg(0);
1099     } else
1100       llvm_unreachable("trying to unpredicate a non-predicated instruction");
1101   };
1102 
1103   // There are a few scenarios which we have to fix up:
1104   // 1) A VPT block with is only predicated by the vctp and has no internal vpr
1105   //    defs.
1106   // 2) A VPT block which is only predicated by the vctp but has an internal
1107   //    vpr def.
1108   // 3) A VPT block which is predicated upon the vctp as well as another vpr
1109   //    def.
1110   // 4) A VPT block which is not predicated upon a vctp, but contains it and
1111   //    all instructions within the block are predicated upon in.
1112 
1113   for (auto &Block : LoLoop.getVPTBlocks()) {
1114     SmallVectorImpl<PredicatedMI> &Insts = Block.getInsts();
1115     if (Block.HasNonUniformPredicate()) {
1116       PredicatedMI *Divergent = Block.getDivergent();
1117       if (isVCTP(Divergent->MI)) {
1118         // The vctp will be removed, so the size of the vpt block needs to be
1119         // modified.
1120         uint64_t Size = getARMVPTBlockMask(Block.size() - 1);
1121         Block.getVPST()->getOperand(0).setImm(Size);
1122         LLVM_DEBUG(dbgs() << "ARM Loops: Modified VPT block mask.\n");
1123       } else if (Block.IsOnlyPredicatedOn(LoLoop.VCTP)) {
1124         // The VPT block has a non-uniform predicate but it's entry is guarded
1125         // only by a vctp, which means we:
1126         // - Need to remove the original vpst.
1127         // - Then need to unpredicate any following instructions, until
1128         //   we come across the divergent vpr def.
1129         // - Insert a new vpst to predicate the instruction(s) that following
1130         //   the divergent vpr def.
1131         // TODO: We could be producing more VPT blocks than necessary and could
1132         // fold the newly created one into a proceeding one.
1133         for (auto I = ++MachineBasicBlock::iterator(Block.getVPST()),
1134              E = ++MachineBasicBlock::iterator(Divergent->MI); I != E; ++I)
1135           RemovePredicate(&*I);
1136 
1137         unsigned Size = 0;
1138         auto E = MachineBasicBlock::reverse_iterator(Divergent->MI);
1139         auto I = MachineBasicBlock::reverse_iterator(Insts.back().MI);
1140         MachineInstr *InsertAt = nullptr;
1141         while (I != E) {
1142           InsertAt = &*I;
1143           ++Size;
1144           ++I;
1145         }
1146         MachineInstrBuilder MIB = BuildMI(*InsertAt->getParent(), InsertAt,
1147                                           InsertAt->getDebugLoc(),
1148                                           TII->get(ARM::MVE_VPST));
1149         MIB.addImm(getARMVPTBlockMask(Size));
1150         LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *Block.getVPST());
1151         LLVM_DEBUG(dbgs() << "ARM Loops: Created VPST: " << *MIB);
1152         LoLoop.ToRemove.insert(Block.getVPST());
1153       }
1154     } else if (Block.IsOnlyPredicatedOn(LoLoop.VCTP)) {
1155       // A vpt block which is only predicated upon vctp and has no internal vpr
1156       // defs:
1157       // - Remove vpst.
1158       // - Unpredicate the remaining instructions.
1159       LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *Block.getVPST());
1160       LoLoop.ToRemove.insert(Block.getVPST());
1161       for (auto &PredMI : Insts)
1162         RemovePredicate(PredMI.MI);
1163     }
1164   }
1165   LLVM_DEBUG(dbgs() << "ARM Loops: Removing VCTP: " << *LoLoop.VCTP);
1166   LoLoop.ToRemove.insert(LoLoop.VCTP);
1167 }
1168 
1169 void ARMLowOverheadLoops::Expand(LowOverheadLoop &LoLoop) {
1170 
1171   // Combine the LoopDec and LoopEnd instructions into LE(TP).
1172   auto ExpandLoopEnd = [this](LowOverheadLoop &LoLoop) {
1173     MachineInstr *End = LoLoop.End;
1174     MachineBasicBlock *MBB = End->getParent();
1175     unsigned Opc = LoLoop.IsTailPredicationLegal() ?
1176       ARM::MVE_LETP : ARM::t2LEUpdate;
1177     MachineInstrBuilder MIB = BuildMI(*MBB, End, End->getDebugLoc(),
1178                                       TII->get(Opc));
1179     MIB.addDef(ARM::LR);
1180     MIB.add(End->getOperand(0));
1181     MIB.add(End->getOperand(1));
1182     LLVM_DEBUG(dbgs() << "ARM Loops: Inserted LE: " << *MIB);
1183     LoLoop.ToRemove.insert(LoLoop.Dec);
1184     LoLoop.ToRemove.insert(End);
1185     return &*MIB;
1186   };
1187 
1188   // TODO: We should be able to automatically remove these branches before we
1189   // get here - probably by teaching analyzeBranch about the pseudo
1190   // instructions.
1191   // If there is an unconditional branch, after I, that just branches to the
1192   // next block, remove it.
1193   auto RemoveDeadBranch = [](MachineInstr *I) {
1194     MachineBasicBlock *BB = I->getParent();
1195     MachineInstr *Terminator = &BB->instr_back();
1196     if (Terminator->isUnconditionalBranch() && I != Terminator) {
1197       MachineBasicBlock *Succ = Terminator->getOperand(0).getMBB();
1198       if (BB->isLayoutSuccessor(Succ)) {
1199         LLVM_DEBUG(dbgs() << "ARM Loops: Removing branch: " << *Terminator);
1200         Terminator->eraseFromParent();
1201       }
1202     }
1203   };
1204 
1205   if (LoLoop.Revert) {
1206     if (LoLoop.Start->getOpcode() == ARM::t2WhileLoopStart)
1207       RevertWhile(LoLoop.Start);
1208     else
1209       LoLoop.Start->eraseFromParent();
1210     bool FlagsAlreadySet = RevertLoopDec(LoLoop.Dec);
1211     RevertLoopEnd(LoLoop.End, FlagsAlreadySet);
1212   } else {
1213     LoLoop.Start = ExpandLoopStart(LoLoop);
1214     RemoveDeadBranch(LoLoop.Start);
1215     LoLoop.End = ExpandLoopEnd(LoLoop);
1216     RemoveDeadBranch(LoLoop.End);
1217     if (LoLoop.IsTailPredicationLegal())
1218       ConvertVPTBlocks(LoLoop);
1219     for (auto *I : LoLoop.ToRemove) {
1220       LLVM_DEBUG(dbgs() << "ARM Loops: Erasing " << *I);
1221       I->eraseFromParent();
1222     }
1223   }
1224 
1225   PostOrderLoopTraversal DFS(LoLoop.ML, *MLI);
1226   DFS.ProcessLoop();
1227   const SmallVectorImpl<MachineBasicBlock*> &PostOrder = DFS.getOrder();
1228   for (auto *MBB : PostOrder) {
1229     recomputeLiveIns(*MBB);
1230     // FIXME: For some reason, the live-in print order is non-deterministic for
1231     // our tests and I can't out why... So just sort them.
1232     MBB->sortUniqueLiveIns();
1233   }
1234 
1235   for (auto *MBB : reverse(PostOrder))
1236     recomputeLivenessFlags(*MBB);
1237 
1238   // We've moved, removed and inserted new instructions, so update RDA.
1239   RDA->reset();
1240 }
1241 
1242 bool ARMLowOverheadLoops::RevertNonLoops() {
1243   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting any remaining pseudos...\n");
1244   bool Changed = false;
1245 
1246   for (auto &MBB : *MF) {
1247     SmallVector<MachineInstr*, 4> Starts;
1248     SmallVector<MachineInstr*, 4> Decs;
1249     SmallVector<MachineInstr*, 4> Ends;
1250 
1251     for (auto &I : MBB) {
1252       if (isLoopStart(I))
1253         Starts.push_back(&I);
1254       else if (I.getOpcode() == ARM::t2LoopDec)
1255         Decs.push_back(&I);
1256       else if (I.getOpcode() == ARM::t2LoopEnd)
1257         Ends.push_back(&I);
1258     }
1259 
1260     if (Starts.empty() && Decs.empty() && Ends.empty())
1261       continue;
1262 
1263     Changed = true;
1264 
1265     for (auto *Start : Starts) {
1266       if (Start->getOpcode() == ARM::t2WhileLoopStart)
1267         RevertWhile(Start);
1268       else
1269         Start->eraseFromParent();
1270     }
1271     for (auto *Dec : Decs)
1272       RevertLoopDec(Dec);
1273 
1274     for (auto *End : Ends)
1275       RevertLoopEnd(End);
1276   }
1277   return Changed;
1278 }
1279 
1280 FunctionPass *llvm::createARMLowOverheadLoopsPass() {
1281   return new ARMLowOverheadLoops();
1282 }
1283