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