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