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