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