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