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