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