xref: /llvm-project/llvm/lib/Target/ARM/ARMLowOverheadLoops.cpp (revision b4fa884a73c5c883723738f67ad1810a6d48cc2d)
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   for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
977     const MachineOperand &MO = MI->getOperand(i);
978     if (!MO.isReg() || !MO.isUse() || MO.getReg() != ARM::VPR)
979       continue;
980 
981     if (ARM::isVpred(MCID.OpInfo[i].OperandType)) {
982       VPTState::addInst(MI);
983       IsUse = true;
984     } else if (MI->getOpcode() != ARM::MVE_VPST) {
985       LLVM_DEBUG(dbgs() << "ARM Loops: Found instruction using vpr: " << *MI);
986       return false;
987     }
988   }
989 
990   // If we find an instruction that has been marked as not valid for tail
991   // predication, only allow the instruction if it's contained within a valid
992   // VPT block.
993   bool RequiresExplicitPredication =
994     (MCID.TSFlags & ARMII::ValidForTailPredication) == 0;
995   if (isDomainMVE(MI) && RequiresExplicitPredication) {
996     LLVM_DEBUG(if (!IsUse)
997                dbgs() << "ARM Loops: Can't tail predicate: " << *MI);
998     return IsUse;
999   }
1000 
1001   // If the instruction is already explicitly predicated, then the conversion
1002   // will be fine, but ensure that all store operations are predicated.
1003   if (MI->mayStore())
1004     return IsUse;
1005 
1006   // If this instruction defines the VPR, update the predicate for the
1007   // proceeding instructions.
1008   if (isVectorPredicate(MI)) {
1009     // Clear the existing predicate when we're not in VPT Active state,
1010     // otherwise we add to it.
1011     if (!isVectorPredicated(MI))
1012       VPTState::resetPredicate(MI);
1013     else
1014       VPTState::addPredicate(MI);
1015   }
1016 
1017   // Finally once the predicate has been modified, we can start a new VPT
1018   // block if necessary.
1019   if (isVPTOpcode(MI->getOpcode()))
1020     VPTState::CreateVPTBlock(MI);
1021 
1022   return true;
1023 }
1024 
1025 bool ARMLowOverheadLoops::runOnMachineFunction(MachineFunction &mf) {
1026   const ARMSubtarget &ST = static_cast<const ARMSubtarget&>(mf.getSubtarget());
1027   if (!ST.hasLOB())
1028     return false;
1029 
1030   MF = &mf;
1031   LLVM_DEBUG(dbgs() << "ARM Loops on " << MF->getName() << " ------------- \n");
1032 
1033   MLI = &getAnalysis<MachineLoopInfo>();
1034   RDA = &getAnalysis<ReachingDefAnalysis>();
1035   MF->getProperties().set(MachineFunctionProperties::Property::TracksLiveness);
1036   MRI = &MF->getRegInfo();
1037   TII = static_cast<const ARMBaseInstrInfo*>(ST.getInstrInfo());
1038   TRI = ST.getRegisterInfo();
1039   BBUtils = std::unique_ptr<ARMBasicBlockUtils>(new ARMBasicBlockUtils(*MF));
1040   BBUtils->computeAllBlockSizes();
1041   BBUtils->adjustBBOffsetsAfter(&MF->front());
1042 
1043   bool Changed = false;
1044   for (auto ML : *MLI) {
1045     if (!ML->getParentLoop())
1046       Changed |= ProcessLoop(ML);
1047   }
1048   Changed |= RevertNonLoops();
1049   return Changed;
1050 }
1051 
1052 bool ARMLowOverheadLoops::ProcessLoop(MachineLoop *ML) {
1053 
1054   bool Changed = false;
1055 
1056   // Process inner loops first.
1057   for (auto I = ML->begin(), E = ML->end(); I != E; ++I)
1058     Changed |= ProcessLoop(*I);
1059 
1060   LLVM_DEBUG(dbgs() << "ARM Loops: Processing loop containing:\n";
1061              if (auto *Preheader = ML->getLoopPreheader())
1062                dbgs() << " - " << Preheader->getName() << "\n";
1063              else if (auto *Preheader = MLI->findLoopPreheader(ML))
1064                dbgs() << " - " << Preheader->getName() << "\n";
1065              else if (auto *Preheader = MLI->findLoopPreheader(ML, true))
1066                dbgs() << " - " << Preheader->getName() << "\n";
1067              for (auto *MBB : ML->getBlocks())
1068                dbgs() << " - " << MBB->getName() << "\n";
1069             );
1070 
1071   // Search the given block for a loop start instruction. If one isn't found,
1072   // and there's only one predecessor block, search that one too.
1073   std::function<MachineInstr*(MachineBasicBlock*)> SearchForStart =
1074     [&SearchForStart](MachineBasicBlock *MBB) -> MachineInstr* {
1075     for (auto &MI : *MBB) {
1076       if (isLoopStart(MI))
1077         return &MI;
1078     }
1079     if (MBB->pred_size() == 1)
1080       return SearchForStart(*MBB->pred_begin());
1081     return nullptr;
1082   };
1083 
1084   LowOverheadLoop LoLoop(*ML, *MLI, *RDA, *TRI, *TII);
1085   // Search the preheader for the start intrinsic.
1086   // FIXME: I don't see why we shouldn't be supporting multiple predecessors
1087   // with potentially multiple set.loop.iterations, so we need to enable this.
1088   if (LoLoop.Preheader)
1089     LoLoop.Start = SearchForStart(LoLoop.Preheader);
1090   else
1091     return false;
1092 
1093   // Find the low-overhead loop components and decide whether or not to fall
1094   // back to a normal loop. Also look for a vctp instructions and decide
1095   // whether we can convert that predicate using tail predication.
1096   for (auto *MBB : reverse(ML->getBlocks())) {
1097     for (auto &MI : *MBB) {
1098       if (MI.isDebugValue())
1099         continue;
1100       else if (MI.getOpcode() == ARM::t2LoopDec)
1101         LoLoop.Dec = &MI;
1102       else if (MI.getOpcode() == ARM::t2LoopEnd)
1103         LoLoop.End = &MI;
1104       else if (isLoopStart(MI))
1105         LoLoop.Start = &MI;
1106       else if (MI.getDesc().isCall()) {
1107         // TODO: Though the call will require LE to execute again, does this
1108         // mean we should revert? Always executing LE hopefully should be
1109         // faster than performing a sub,cmp,br or even subs,br.
1110         LoLoop.Revert = true;
1111         LLVM_DEBUG(dbgs() << "ARM Loops: Found call.\n");
1112       } else {
1113         // Record VPR defs and build up their corresponding vpt blocks.
1114         // Check we know how to tail predicate any mve instructions.
1115         LoLoop.AnalyseMVEInst(&MI);
1116       }
1117     }
1118   }
1119 
1120   LLVM_DEBUG(LoLoop.dump());
1121   if (!LoLoop.FoundAllComponents()) {
1122     LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find loop start, update, end\n");
1123     return false;
1124   }
1125 
1126   // Check that the only instruction using LoopDec is LoopEnd.
1127   // TODO: Check for copy chains that really have no effect.
1128   SmallPtrSet<MachineInstr*, 2> Uses;
1129   RDA->getReachingLocalUses(LoLoop.Dec, ARM::LR, Uses);
1130   if (Uses.size() > 1 || !Uses.count(LoLoop.End)) {
1131     LLVM_DEBUG(dbgs() << "ARM Loops: Unable to remove LoopDec.\n");
1132     LoLoop.Revert = true;
1133   }
1134   LoLoop.CheckLegality(BBUtils.get());
1135   Expand(LoLoop);
1136   return true;
1137 }
1138 
1139 // WhileLoopStart holds the exit block, so produce a cmp lr, 0 and then a
1140 // beq that branches to the exit branch.
1141 // TODO: We could also try to generate a cbz if the value in LR is also in
1142 // another low register.
1143 void ARMLowOverheadLoops::RevertWhile(MachineInstr *MI) const {
1144   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp: " << *MI);
1145   MachineBasicBlock *MBB = MI->getParent();
1146   MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
1147                                     TII->get(ARM::t2CMPri));
1148   MIB.add(MI->getOperand(0));
1149   MIB.addImm(0);
1150   MIB.addImm(ARMCC::AL);
1151   MIB.addReg(ARM::NoRegister);
1152 
1153   MachineBasicBlock *DestBB = MI->getOperand(1).getMBB();
1154   unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
1155     ARM::tBcc : ARM::t2Bcc;
1156 
1157   MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc));
1158   MIB.add(MI->getOperand(1));   // branch target
1159   MIB.addImm(ARMCC::EQ);        // condition code
1160   MIB.addReg(ARM::CPSR);
1161   MI->eraseFromParent();
1162 }
1163 
1164 bool ARMLowOverheadLoops::RevertLoopDec(MachineInstr *MI) const {
1165   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to sub: " << *MI);
1166   MachineBasicBlock *MBB = MI->getParent();
1167   SmallPtrSet<MachineInstr*, 1> Ignore;
1168   for (auto I = MachineBasicBlock::iterator(MI), E = MBB->end(); I != E; ++I) {
1169     if (I->getOpcode() == ARM::t2LoopEnd) {
1170       Ignore.insert(&*I);
1171       break;
1172     }
1173   }
1174 
1175   // If nothing defines CPSR between LoopDec and LoopEnd, use a t2SUBS.
1176   bool SetFlags = RDA->isSafeToDefRegAt(MI, ARM::CPSR, Ignore);
1177 
1178   MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
1179                                     TII->get(ARM::t2SUBri));
1180   MIB.addDef(ARM::LR);
1181   MIB.add(MI->getOperand(1));
1182   MIB.add(MI->getOperand(2));
1183   MIB.addImm(ARMCC::AL);
1184   MIB.addReg(0);
1185 
1186   if (SetFlags) {
1187     MIB.addReg(ARM::CPSR);
1188     MIB->getOperand(5).setIsDef(true);
1189   } else
1190     MIB.addReg(0);
1191 
1192   MI->eraseFromParent();
1193   return SetFlags;
1194 }
1195 
1196 // Generate a subs, or sub and cmp, and a branch instead of an LE.
1197 void ARMLowOverheadLoops::RevertLoopEnd(MachineInstr *MI, bool SkipCmp) const {
1198   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp, br: " << *MI);
1199 
1200   MachineBasicBlock *MBB = MI->getParent();
1201   // Create cmp
1202   if (!SkipCmp) {
1203     MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
1204                                       TII->get(ARM::t2CMPri));
1205     MIB.addReg(ARM::LR);
1206     MIB.addImm(0);
1207     MIB.addImm(ARMCC::AL);
1208     MIB.addReg(ARM::NoRegister);
1209   }
1210 
1211   MachineBasicBlock *DestBB = MI->getOperand(1).getMBB();
1212   unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
1213     ARM::tBcc : ARM::t2Bcc;
1214 
1215   // Create bne
1216   MachineInstrBuilder MIB =
1217     BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc));
1218   MIB.add(MI->getOperand(1));   // branch target
1219   MIB.addImm(ARMCC::NE);        // condition code
1220   MIB.addReg(ARM::CPSR);
1221   MI->eraseFromParent();
1222 }
1223 
1224 // Perform dead code elimation on the loop iteration count setup expression.
1225 // If we are tail-predicating, the number of elements to be processed is the
1226 // operand of the VCTP instruction in the vector body, see getCount(), which is
1227 // register $r3 in this example:
1228 //
1229 //   $lr = big-itercount-expression
1230 //   ..
1231 //   t2DoLoopStart renamable $lr
1232 //   vector.body:
1233 //     ..
1234 //     $vpr = MVE_VCTP32 renamable $r3
1235 //     renamable $lr = t2LoopDec killed renamable $lr, 1
1236 //     t2LoopEnd renamable $lr, %vector.body
1237 //     tB %end
1238 //
1239 // What we would like achieve here is to replace the do-loop start pseudo
1240 // instruction t2DoLoopStart with:
1241 //
1242 //    $lr = MVE_DLSTP_32 killed renamable $r3
1243 //
1244 // Thus, $r3 which defines the number of elements, is written to $lr,
1245 // and then we want to delete the whole chain that used to define $lr,
1246 // see the comment below how this chain could look like.
1247 //
1248 void ARMLowOverheadLoops::IterationCountDCE(LowOverheadLoop &LoLoop) {
1249   if (!LoLoop.IsTailPredicationLegal())
1250     return;
1251 
1252   LLVM_DEBUG(dbgs() << "ARM Loops: Trying DCE on loop iteration count.\n");
1253 
1254   MachineInstr *Def = RDA->getMIOperand(LoLoop.Start, 0);
1255   if (!Def) {
1256     LLVM_DEBUG(dbgs() << "ARM Loops: Couldn't find iteration count.\n");
1257     return;
1258   }
1259 
1260   // Collect and remove the users of iteration count.
1261   SmallPtrSet<MachineInstr*, 4> Killed  = { LoLoop.Start, LoLoop.Dec,
1262                                             LoLoop.End, LoLoop.InsertPt };
1263   SmallPtrSet<MachineInstr*, 2> Remove;
1264   if (RDA->isSafeToRemove(Def, Remove, Killed))
1265     LoLoop.ToRemove.insert(Remove.begin(), Remove.end());
1266   else {
1267     LLVM_DEBUG(dbgs() << "ARM Loops: Unsafe to remove loop iteration count.\n");
1268     return;
1269   }
1270 
1271   // Collect the dead code and the MBBs in which they reside.
1272   RDA->collectKilledOperands(Def, Killed);
1273   SmallPtrSet<MachineBasicBlock*, 2> BasicBlocks;
1274   for (auto *MI : Killed)
1275     BasicBlocks.insert(MI->getParent());
1276 
1277   // Collect IT blocks in all affected basic blocks.
1278   std::map<MachineInstr *, SmallPtrSet<MachineInstr *, 2>> ITBlocks;
1279   for (auto *MBB : BasicBlocks) {
1280     for (auto &MI : *MBB) {
1281       if (MI.getOpcode() != ARM::t2IT)
1282         continue;
1283       RDA->getReachingLocalUses(&MI, ARM::ITSTATE, ITBlocks[&MI]);
1284     }
1285   }
1286 
1287   // If we're removing all of the instructions within an IT block, then
1288   // also remove the IT instruction.
1289   SmallPtrSet<MachineInstr*, 2> ModifiedITs;
1290   for (auto *MI : Killed) {
1291     if (MachineOperand *MO = MI->findRegisterUseOperand(ARM::ITSTATE)) {
1292       MachineInstr *IT = RDA->getMIOperand(MI, *MO);
1293       auto &CurrentBlock = ITBlocks[IT];
1294       CurrentBlock.erase(MI);
1295       if (CurrentBlock.empty())
1296         ModifiedITs.erase(IT);
1297       else
1298         ModifiedITs.insert(IT);
1299     }
1300   }
1301 
1302   // Delete the killed instructions only if we don't have any IT blocks that
1303   // need to be modified because we need to fixup the mask.
1304   // TODO: Handle cases where IT blocks are modified.
1305   if (ModifiedITs.empty()) {
1306     LLVM_DEBUG(dbgs() << "ARM Loops: Will remove iteration count:\n";
1307                for (auto *MI : Killed)
1308                  dbgs() << " - " << *MI);
1309     LoLoop.ToRemove.insert(Killed.begin(), Killed.end());
1310   } else
1311     LLVM_DEBUG(dbgs() << "ARM Loops: Would need to modify IT block(s).\n");
1312 }
1313 
1314 MachineInstr* ARMLowOverheadLoops::ExpandLoopStart(LowOverheadLoop &LoLoop) {
1315   LLVM_DEBUG(dbgs() << "ARM Loops: Expanding LoopStart.\n");
1316   // When using tail-predication, try to delete the dead code that was used to
1317   // calculate the number of loop iterations.
1318   IterationCountDCE(LoLoop);
1319 
1320   MachineInstr *InsertPt = LoLoop.InsertPt;
1321   MachineInstr *Start = LoLoop.Start;
1322   MachineBasicBlock *MBB = InsertPt->getParent();
1323   bool IsDo = Start->getOpcode() == ARM::t2DoLoopStart;
1324   unsigned Opc = LoLoop.getStartOpcode();
1325   MachineOperand &Count = LoLoop.getLoopStartOperand();
1326 
1327   MachineInstrBuilder MIB =
1328     BuildMI(*MBB, InsertPt, InsertPt->getDebugLoc(), TII->get(Opc));
1329 
1330   MIB.addDef(ARM::LR);
1331   MIB.add(Count);
1332   if (!IsDo)
1333     MIB.add(Start->getOperand(1));
1334 
1335   // If we're inserting at a mov lr, then remove it as it's redundant.
1336   if (InsertPt != Start)
1337     LoLoop.ToRemove.insert(InsertPt);
1338   LoLoop.ToRemove.insert(Start);
1339   LLVM_DEBUG(dbgs() << "ARM Loops: Inserted start: " << *MIB);
1340   return &*MIB;
1341 }
1342 
1343 void ARMLowOverheadLoops::ConvertVPTBlocks(LowOverheadLoop &LoLoop) {
1344   auto RemovePredicate = [](MachineInstr *MI) {
1345     LLVM_DEBUG(dbgs() << "ARM Loops: Removing predicate from: " << *MI);
1346     if (int PIdx = llvm::findFirstVPTPredOperandIdx(*MI)) {
1347       assert(MI->getOperand(PIdx).getImm() == ARMVCC::Then &&
1348              "Expected Then predicate!");
1349       MI->getOperand(PIdx).setImm(ARMVCC::None);
1350       MI->getOperand(PIdx+1).setReg(0);
1351     } else
1352       llvm_unreachable("trying to unpredicate a non-predicated instruction");
1353   };
1354 
1355   for (auto &Block : LoLoop.getVPTBlocks()) {
1356     SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
1357 
1358     if (VPTState::isEntryPredicatedOnVCTP(Block, /*exclusive*/true)) {
1359       if (VPTState::hasUniformPredicate(Block)) {
1360         // A vpt block starting with VPST, is only predicated upon vctp and has no
1361         // internal vpr defs:
1362         // - Remove vpst.
1363         // - Unpredicate the remaining instructions.
1364         LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *Insts.front());
1365         LoLoop.ToRemove.insert(Insts.front());
1366         for (unsigned i = 1; i < Insts.size(); ++i)
1367           RemovePredicate(Insts[i]);
1368       } else {
1369         // The VPT block has a non-uniform predicate but it uses a vpst and its
1370         // entry is guarded only by a vctp, which means we:
1371         // - Need to remove the original vpst.
1372         // - Then need to unpredicate any following instructions, until
1373         //   we come across the divergent vpr def.
1374         // - Insert a new vpst to predicate the instruction(s) that following
1375         //   the divergent vpr def.
1376         // TODO: We could be producing more VPT blocks than necessary and could
1377         // fold the newly created one into a proceeding one.
1378         MachineInstr *Divergent = VPTState::getDivergent(Block);
1379         for (auto I = ++MachineBasicBlock::iterator(Insts.front()),
1380              E = ++MachineBasicBlock::iterator(Divergent); I != E; ++I)
1381           RemovePredicate(&*I);
1382 
1383         // Check if the instruction defining vpr is a vcmp so it can be combined
1384         // with the VPST This should be the divergent instruction
1385         MachineInstr *VCMP = VCMPOpcodeToVPT(Divergent->getOpcode()) != 0
1386           ? Divergent
1387           : nullptr;
1388 
1389         unsigned Size = 0;
1390         auto E = MachineBasicBlock::reverse_iterator(Divergent);
1391         auto I = MachineBasicBlock::reverse_iterator(Insts.back());
1392         MachineInstr *InsertAt = nullptr;
1393         while (I != E) {
1394           InsertAt = &*I;
1395           ++Size;
1396           ++I;
1397         }
1398 
1399         MachineInstrBuilder MIB;
1400         if (VCMP) {
1401           // Combine the VPST and VCMP into a VPT
1402           MIB =
1403               BuildMI(*InsertAt->getParent(), InsertAt, InsertAt->getDebugLoc(),
1404                       TII->get(VCMPOpcodeToVPT(VCMP->getOpcode())));
1405           MIB.addImm(ARMVCC::Then);
1406           // Register one
1407           MIB.add(VCMP->getOperand(1));
1408           // Register two
1409           MIB.add(VCMP->getOperand(2));
1410           // The comparison code, e.g. ge, eq, lt
1411           MIB.add(VCMP->getOperand(3));
1412           LLVM_DEBUG(dbgs()
1413                      << "ARM Loops: Combining with VCMP to VPT: " << *MIB);
1414           LoLoop.ToRemove.insert(VCMP);
1415         } else {
1416           // Create a VPST (with a null mask for now, we'll recompute it later)
1417           // or a VPT in case there was a VCMP right before it
1418           MIB = BuildMI(*InsertAt->getParent(), InsertAt,
1419                         InsertAt->getDebugLoc(), TII->get(ARM::MVE_VPST));
1420           MIB.addImm(0);
1421           LLVM_DEBUG(dbgs() << "ARM Loops: Created VPST: " << *MIB);
1422         }
1423         LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *Insts.front());
1424         LoLoop.ToRemove.insert(Insts.front());
1425         LoLoop.BlockMasksToRecompute.insert(MIB.getInstr());
1426       }
1427     } else if (Block.containsVCTP()) {
1428       // The vctp will be removed, so the block mask of the vp(s)t will need
1429       // to be recomputed.
1430       LoLoop.BlockMasksToRecompute.insert(Insts.front());
1431     }
1432   }
1433 
1434   LoLoop.ToRemove.insert(LoLoop.VCTPs.begin(), LoLoop.VCTPs.end());
1435 }
1436 
1437 void ARMLowOverheadLoops::Expand(LowOverheadLoop &LoLoop) {
1438 
1439   // Combine the LoopDec and LoopEnd instructions into LE(TP).
1440   auto ExpandLoopEnd = [this](LowOverheadLoop &LoLoop) {
1441     MachineInstr *End = LoLoop.End;
1442     MachineBasicBlock *MBB = End->getParent();
1443     unsigned Opc = LoLoop.IsTailPredicationLegal() ?
1444       ARM::MVE_LETP : ARM::t2LEUpdate;
1445     MachineInstrBuilder MIB = BuildMI(*MBB, End, End->getDebugLoc(),
1446                                       TII->get(Opc));
1447     MIB.addDef(ARM::LR);
1448     MIB.add(End->getOperand(0));
1449     MIB.add(End->getOperand(1));
1450     LLVM_DEBUG(dbgs() << "ARM Loops: Inserted LE: " << *MIB);
1451     LoLoop.ToRemove.insert(LoLoop.Dec);
1452     LoLoop.ToRemove.insert(End);
1453     return &*MIB;
1454   };
1455 
1456   // TODO: We should be able to automatically remove these branches before we
1457   // get here - probably by teaching analyzeBranch about the pseudo
1458   // instructions.
1459   // If there is an unconditional branch, after I, that just branches to the
1460   // next block, remove it.
1461   auto RemoveDeadBranch = [](MachineInstr *I) {
1462     MachineBasicBlock *BB = I->getParent();
1463     MachineInstr *Terminator = &BB->instr_back();
1464     if (Terminator->isUnconditionalBranch() && I != Terminator) {
1465       MachineBasicBlock *Succ = Terminator->getOperand(0).getMBB();
1466       if (BB->isLayoutSuccessor(Succ)) {
1467         LLVM_DEBUG(dbgs() << "ARM Loops: Removing branch: " << *Terminator);
1468         Terminator->eraseFromParent();
1469       }
1470     }
1471   };
1472 
1473   if (LoLoop.Revert) {
1474     if (LoLoop.Start->getOpcode() == ARM::t2WhileLoopStart)
1475       RevertWhile(LoLoop.Start);
1476     else
1477       LoLoop.Start->eraseFromParent();
1478     bool FlagsAlreadySet = RevertLoopDec(LoLoop.Dec);
1479     RevertLoopEnd(LoLoop.End, FlagsAlreadySet);
1480   } else {
1481     LoLoop.Start = ExpandLoopStart(LoLoop);
1482     RemoveDeadBranch(LoLoop.Start);
1483     LoLoop.End = ExpandLoopEnd(LoLoop);
1484     RemoveDeadBranch(LoLoop.End);
1485     if (LoLoop.IsTailPredicationLegal())
1486       ConvertVPTBlocks(LoLoop);
1487     for (auto *I : LoLoop.ToRemove) {
1488       LLVM_DEBUG(dbgs() << "ARM Loops: Erasing " << *I);
1489       I->eraseFromParent();
1490     }
1491     for (auto *I : LoLoop.BlockMasksToRecompute) {
1492       LLVM_DEBUG(dbgs() << "ARM Loops: Recomputing VPT/VPST Block Mask: " << *I);
1493       recomputeVPTBlockMask(*I);
1494       LLVM_DEBUG(dbgs() << "           ... done: " << *I);
1495     }
1496   }
1497 
1498   PostOrderLoopTraversal DFS(LoLoop.ML, *MLI);
1499   DFS.ProcessLoop();
1500   const SmallVectorImpl<MachineBasicBlock*> &PostOrder = DFS.getOrder();
1501   for (auto *MBB : PostOrder) {
1502     recomputeLiveIns(*MBB);
1503     // FIXME: For some reason, the live-in print order is non-deterministic for
1504     // our tests and I can't out why... So just sort them.
1505     MBB->sortUniqueLiveIns();
1506   }
1507 
1508   for (auto *MBB : reverse(PostOrder))
1509     recomputeLivenessFlags(*MBB);
1510 
1511   // We've moved, removed and inserted new instructions, so update RDA.
1512   RDA->reset();
1513 }
1514 
1515 bool ARMLowOverheadLoops::RevertNonLoops() {
1516   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting any remaining pseudos...\n");
1517   bool Changed = false;
1518 
1519   for (auto &MBB : *MF) {
1520     SmallVector<MachineInstr*, 4> Starts;
1521     SmallVector<MachineInstr*, 4> Decs;
1522     SmallVector<MachineInstr*, 4> Ends;
1523 
1524     for (auto &I : MBB) {
1525       if (isLoopStart(I))
1526         Starts.push_back(&I);
1527       else if (I.getOpcode() == ARM::t2LoopDec)
1528         Decs.push_back(&I);
1529       else if (I.getOpcode() == ARM::t2LoopEnd)
1530         Ends.push_back(&I);
1531     }
1532 
1533     if (Starts.empty() && Decs.empty() && Ends.empty())
1534       continue;
1535 
1536     Changed = true;
1537 
1538     for (auto *Start : Starts) {
1539       if (Start->getOpcode() == ARM::t2WhileLoopStart)
1540         RevertWhile(Start);
1541       else
1542         Start->eraseFromParent();
1543     }
1544     for (auto *Dec : Decs)
1545       RevertLoopDec(Dec);
1546 
1547     for (auto *End : Ends)
1548       RevertLoopEnd(End);
1549   }
1550   return Changed;
1551 }
1552 
1553 FunctionPass *llvm::createARMLowOverheadLoopsPass() {
1554   return new ARMLowOverheadLoops();
1555 }
1556