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