1//===-- MVETPAndVPTOptimisationsPass.cpp ----------------------------------===//
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//
9/// \file This pass does a few optimisations related to Tail predicated loops
10/// and MVE VPT blocks before register allocation is performed. For VPT blocks
11/// the goal is to maximize the sizes of the blocks that will be created by the
12/// MVE VPT Block Insertion pass (which runs after register allocation). For
13/// tail predicated loops we transform the loop into something that will
14/// hopefully make the backend ARMLowOverheadLoops pass's job easier.
15///
16//===----------------------------------------------------------------------===//
17
18#include "ARM.h"
19#include "ARMSubtarget.h"
20#include "MVETailPredUtils.h"
21#include "Thumb2InstrInfo.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/CodeGen/MachineBasicBlock.h"
24#include "llvm/CodeGen/MachineDominators.h"
25#include "llvm/CodeGen/MachineFunction.h"
26#include "llvm/CodeGen/MachineFunctionPass.h"
27#include "llvm/CodeGen/MachineInstr.h"
28#include "llvm/CodeGen/MachineLoopInfo.h"
29#include "llvm/CodeGen/RegisterClassInfo.h"
30#include "llvm/InitializePasses.h"
31#include "llvm/Support/Debug.h"
32#include <cassert>
33
34using namespace llvm;
35
36#define DEBUG_TYPE "arm-mve-vpt-opts"
37
38static cl::opt<bool>
39MergeEndDec("arm-enable-merge-loopenddec", cl::Hidden,
40 cl::desc("Enable merging Loop End and Dec instructions."),
41 cl::init(Val: true));
42
43static cl::opt<bool>
44SetLRPredicate("arm-set-lr-predicate", cl::Hidden,
45 cl::desc("Enable setting lr as a predicate in tail predication regions."),
46 cl::init(Val: true));
47
48namespace {
49class MVETPAndVPTOptimisations : public MachineFunctionPass {
50public:
51 static char ID;
52 const Thumb2InstrInfo *TII;
53 MachineRegisterInfo *MRI;
54
55 MVETPAndVPTOptimisations() : MachineFunctionPass(ID) {}
56
57 bool runOnMachineFunction(MachineFunction &Fn) override;
58
59 void getAnalysisUsage(AnalysisUsage &AU) const override {
60 AU.addRequired<MachineLoopInfoWrapperPass>();
61 AU.addPreserved<MachineLoopInfoWrapperPass>();
62 AU.addRequired<MachineDominatorTreeWrapperPass>();
63 AU.addPreserved<MachineDominatorTreeWrapperPass>();
64 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
65 MachineFunctionPass::getAnalysisUsage(AU);
66 }
67
68 StringRef getPassName() const override {
69 return "ARM MVE TailPred and VPT Optimisation Pass";
70 }
71
72private:
73 bool LowerWhileLoopStart(MachineLoop *ML);
74 bool MergeLoopEnd(MachineLoop *ML);
75 bool ConvertTailPredLoop(MachineLoop *ML, MachineDominatorTree *DT);
76 MachineInstr &ReplaceRegisterUseWithVPNOT(MachineBasicBlock &MBB,
77 MachineInstr &Instr,
78 MachineOperand &User,
79 Register Target);
80 bool ReduceOldVCCRValueUses(MachineBasicBlock &MBB);
81 bool ReplaceVCMPsByVPNOTs(MachineBasicBlock &MBB);
82 bool ReplaceConstByVPNOTs(MachineBasicBlock &MBB, MachineDominatorTree *DT);
83 bool ConvertVPSEL(MachineBasicBlock &MBB);
84 bool HintDoLoopStartReg(MachineBasicBlock &MBB);
85 MachineInstr *CheckForLRUseInPredecessors(MachineBasicBlock *PreHeader,
86 MachineInstr *LoopStart);
87};
88
89char MVETPAndVPTOptimisations::ID = 0;
90
91} // end anonymous namespace
92
93INITIALIZE_PASS_BEGIN(MVETPAndVPTOptimisations, DEBUG_TYPE,
94 "ARM MVE TailPred and VPT Optimisations pass", false,
95 false)
96INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
97INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
98INITIALIZE_PASS_END(MVETPAndVPTOptimisations, DEBUG_TYPE,
99 "ARM MVE TailPred and VPT Optimisations pass", false, false)
100
101static MachineInstr *LookThroughCOPY(MachineInstr *MI,
102 MachineRegisterInfo *MRI) {
103 while (MI && MI->getOpcode() == TargetOpcode::COPY &&
104 MI->getOperand(i: 1).getReg().isVirtual())
105 MI = MRI->getVRegDef(Reg: MI->getOperand(i: 1).getReg());
106 return MI;
107}
108
109// Given a loop ML, this attempts to find the t2LoopEnd, t2LoopDec and
110// corresponding PHI that make up a low overhead loop. Only handles 'do' loops
111// at the moment, returning a t2DoLoopStart in LoopStart.
112static bool findLoopComponents(MachineLoop *ML, MachineRegisterInfo *MRI,
113 MachineInstr *&LoopStart, MachineInstr *&LoopPhi,
114 MachineInstr *&LoopDec, MachineInstr *&LoopEnd) {
115 MachineBasicBlock *Header = ML->getHeader();
116 MachineBasicBlock *Latch = ML->getLoopLatch();
117 if (!Header || !Latch) {
118 LLVM_DEBUG(dbgs() << " no Loop Latch or Header\n");
119 return false;
120 }
121
122 // Find the loop end from the terminators.
123 LoopEnd = nullptr;
124 for (auto &T : Latch->terminators()) {
125 if (T.getOpcode() == ARM::t2LoopEnd && T.getOperand(i: 1).getMBB() == Header) {
126 LoopEnd = &T;
127 break;
128 }
129 if (T.getOpcode() == ARM::t2LoopEndDec &&
130 T.getOperand(i: 2).getMBB() == Header) {
131 LoopEnd = &T;
132 break;
133 }
134 }
135 if (!LoopEnd) {
136 LLVM_DEBUG(dbgs() << " no LoopEnd\n");
137 return false;
138 }
139 LLVM_DEBUG(dbgs() << " found loop end: " << *LoopEnd);
140
141 // Find the dec from the use of the end. There may be copies between
142 // instructions. We expect the loop to loop like:
143 // $vs = t2DoLoopStart ...
144 // loop:
145 // $vp = phi [ $vs ], [ $vd ]
146 // ...
147 // $vd = t2LoopDec $vp
148 // ...
149 // t2LoopEnd $vd, loop
150 if (LoopEnd->getOpcode() == ARM::t2LoopEndDec)
151 LoopDec = LoopEnd;
152 else {
153 LoopDec =
154 LookThroughCOPY(MI: MRI->getVRegDef(Reg: LoopEnd->getOperand(i: 0).getReg()), MRI);
155 if (!LoopDec || LoopDec->getOpcode() != ARM::t2LoopDec) {
156 LLVM_DEBUG(dbgs() << " didn't find LoopDec where we expected!\n");
157 return false;
158 }
159 }
160 LLVM_DEBUG(dbgs() << " found loop dec: " << *LoopDec);
161
162 LoopPhi =
163 LookThroughCOPY(MI: MRI->getVRegDef(Reg: LoopDec->getOperand(i: 1).getReg()), MRI);
164 if (!LoopPhi || LoopPhi->getOpcode() != TargetOpcode::PHI ||
165 LoopPhi->getNumOperands() != 5 ||
166 (LoopPhi->getOperand(i: 2).getMBB() != Latch &&
167 LoopPhi->getOperand(i: 4).getMBB() != Latch)) {
168 LLVM_DEBUG(dbgs() << " didn't find PHI where we expected!\n");
169 return false;
170 }
171 LLVM_DEBUG(dbgs() << " found loop phi: " << *LoopPhi);
172
173 Register StartReg = LoopPhi->getOperand(i: 2).getMBB() == Latch
174 ? LoopPhi->getOperand(i: 3).getReg()
175 : LoopPhi->getOperand(i: 1).getReg();
176 LoopStart = LookThroughCOPY(MI: MRI->getVRegDef(Reg: StartReg), MRI);
177 if (!LoopStart || (LoopStart->getOpcode() != ARM::t2DoLoopStart &&
178 LoopStart->getOpcode() != ARM::t2WhileLoopSetup &&
179 LoopStart->getOpcode() != ARM::t2WhileLoopStartLR)) {
180 LLVM_DEBUG(dbgs() << " didn't find Start where we expected!\n");
181 return false;
182 }
183 LLVM_DEBUG(dbgs() << " found loop start: " << *LoopStart);
184
185 return true;
186}
187
188static void RevertWhileLoopSetup(MachineInstr *MI, const TargetInstrInfo *TII) {
189 MachineBasicBlock *MBB = MI->getParent();
190 assert(MI->getOpcode() == ARM::t2WhileLoopSetup &&
191 "Only expected a t2WhileLoopSetup in RevertWhileLoopStart!");
192
193 // Subs
194 MachineInstrBuilder MIB =
195 BuildMI(BB&: *MBB, I: MI, MIMD: MI->getDebugLoc(), MCID: TII->get(Opcode: ARM::t2SUBri));
196 MIB.add(MO: MI->getOperand(i: 0));
197 MIB.add(MO: MI->getOperand(i: 1));
198 MIB.addImm(Val: 0);
199 MIB.addImm(Val: ARMCC::AL);
200 MIB.addReg(RegNo: Register());
201 MIB.addReg(RegNo: ARM::CPSR, Flags: RegState::Define);
202
203 // Attempt to find a t2WhileLoopStart and revert to a t2Bcc.
204 for (MachineInstr &I : MBB->terminators()) {
205 if (I.getOpcode() == ARM::t2WhileLoopStart) {
206 MachineInstrBuilder MIB =
207 BuildMI(BB&: *MBB, I: &I, MIMD: I.getDebugLoc(), MCID: TII->get(Opcode: ARM::t2Bcc));
208 MIB.add(MO: MI->getOperand(i: 1)); // branch target
209 MIB.addImm(Val: ARMCC::EQ);
210 MIB.addReg(RegNo: ARM::CPSR);
211 I.eraseFromParent();
212 break;
213 }
214 }
215
216 MI->eraseFromParent();
217}
218
219// The Hardware Loop insertion and ISel Lowering produce the pseudos for the
220// start of a while loop:
221// %a:gprlr = t2WhileLoopSetup %Cnt
222// t2WhileLoopStart %a, %BB
223// We want to convert those to a single instruction which, like t2LoopEndDec and
224// t2DoLoopStartTP is both a terminator and produces a value:
225// %a:grplr: t2WhileLoopStartLR %Cnt, %BB
226//
227// Otherwise if we can't, we revert the loop. t2WhileLoopSetup and
228// t2WhileLoopStart are not valid past regalloc.
229bool MVETPAndVPTOptimisations::LowerWhileLoopStart(MachineLoop *ML) {
230 LLVM_DEBUG(dbgs() << "LowerWhileLoopStart on loop "
231 << ML->getHeader()->getName() << "\n");
232
233 MachineInstr *LoopEnd, *LoopPhi, *LoopStart, *LoopDec;
234 if (!findLoopComponents(ML, MRI, LoopStart, LoopPhi, LoopDec, LoopEnd))
235 return false;
236
237 if (LoopStart->getOpcode() != ARM::t2WhileLoopSetup)
238 return false;
239
240 Register LR = LoopStart->getOperand(i: 0).getReg();
241 auto WLSIt = find_if(Range: MRI->use_nodbg_instructions(Reg: LR), P: [](auto &MI) {
242 return MI.getOpcode() == ARM::t2WhileLoopStart;
243 });
244 if (!MergeEndDec || WLSIt == MRI->use_instr_nodbg_end()) {
245 RevertWhileLoopSetup(MI: LoopStart, TII);
246 RevertLoopDec(MI: LoopStart, TII);
247 RevertLoopEnd(MI: LoopStart, TII);
248 return true;
249 }
250
251 MachineInstrBuilder MI =
252 BuildMI(BB&: *WLSIt->getParent(), I&: *WLSIt, MIMD: WLSIt->getDebugLoc(),
253 MCID: TII->get(Opcode: ARM::t2WhileLoopStartLR), DestReg: LR)
254 .add(MO: LoopStart->getOperand(i: 1))
255 .add(MO: WLSIt->getOperand(i: 1))
256 .setOperandDead(3); // implicit-def $cpsr
257 (void)MI;
258 LLVM_DEBUG(dbgs() << "Lowered WhileLoopStart into: " << *MI.getInstr());
259
260 WLSIt->eraseFromParent();
261 LoopStart->eraseFromParent();
262 return true;
263}
264
265// Return true if this instruction is invalid in a low overhead loop, usually
266// because it clobbers LR.
267static bool IsInvalidTPInstruction(MachineInstr &MI) {
268 return MI.isCall() || isLoopStart(MI);
269}
270
271// Starting from PreHeader, search for invalid instructions back until the
272// LoopStart block is reached. If invalid instructions are found, the loop start
273// is reverted from a WhileLoopStart to a DoLoopStart on the same loop. Will
274// return the new DLS LoopStart if updated.
275MachineInstr *MVETPAndVPTOptimisations::CheckForLRUseInPredecessors(
276 MachineBasicBlock *PreHeader, MachineInstr *LoopStart) {
277 SmallVector<MachineBasicBlock *> Worklist;
278 SmallPtrSet<MachineBasicBlock *, 4> Visited;
279 Worklist.push_back(Elt: PreHeader);
280 Visited.insert(Ptr: LoopStart->getParent());
281
282 while (!Worklist.empty()) {
283 MachineBasicBlock *MBB = Worklist.pop_back_val();
284 if (Visited.count(Ptr: MBB))
285 continue;
286
287 for (MachineInstr &MI : *MBB) {
288 if (!IsInvalidTPInstruction(MI))
289 continue;
290
291 LLVM_DEBUG(dbgs() << "Found LR use in predecessors, reverting: " << MI);
292 Register DefReg = LoopStart->getOperand(i: 0).getReg();
293 Register SrcReg = LoopStart->getOperand(i: 1).getReg();
294
295 // Create a t2DoLoopStart at the end of the preheader.
296 MachineInstrBuilder MIB =
297 BuildMI(BB&: *PreHeader, I: PreHeader->getFirstTerminator(),
298 MIMD: LoopStart->getDebugLoc(), MCID: TII->get(Opcode: ARM::t2DoLoopStart));
299 MIB.add(MO: LoopStart->getOperand(i: 0));
300 MIB.add(MO: LoopStart->getOperand(i: 1));
301
302 // Revert the t2WhileLoopStartLR to a CMP and Br.
303 RevertWhileLoopStartLR(MI: LoopStart, TII, BrOpc: ARM::t2Bcc, UseCmp: true);
304 // If we looked through a COPY to find the WhileLoopStart, replace it's
305 // use with SrcReg.
306 for (MachineOperand &MO :
307 make_early_inc_range(Range: MRI->use_operands(Reg: DefReg))) {
308 if (MO.getParent()->getOpcode() == TargetOpcode::COPY)
309 MO.setReg(SrcReg);
310 }
311 return MIB;
312 }
313
314 Visited.insert(Ptr: MBB);
315 llvm::append_range(C&: Worklist, R: MBB->predecessors());
316 }
317 return LoopStart;
318}
319
320// This function converts loops with t2LoopEnd and t2LoopEnd instructions into
321// a single t2LoopEndDec instruction. To do that it needs to make sure that LR
322// will be valid to be used for the low overhead loop, which means nothing else
323// is using LR (especially calls) and there are no superfluous copies in the
324// loop. The t2LoopEndDec is a branching terminator that produces a value (the
325// decrement) around the loop edge, which means we need to be careful that they
326// will be valid to allocate without any spilling.
327bool MVETPAndVPTOptimisations::MergeLoopEnd(MachineLoop *ML) {
328 if (!MergeEndDec)
329 return false;
330
331 LLVM_DEBUG(dbgs() << "MergeLoopEnd on loop " << ML->getHeader()->getName()
332 << "\n");
333
334 MachineInstr *LoopEnd, *LoopPhi, *LoopStart, *LoopDec;
335 if (!findLoopComponents(ML, MRI, LoopStart, LoopPhi, LoopDec, LoopEnd))
336 return false;
337
338 // Check if there is an illegal instruction (a call) in the low overhead loop
339 // and if so revert it now before we get any further. While loops also need to
340 // check the preheaders, but can be reverted to a DLS loop if needed.
341 auto *PreHeader = ML->getLoopPreheader();
342 if (LoopStart->getOpcode() == ARM::t2WhileLoopStartLR && PreHeader)
343 LoopStart = CheckForLRUseInPredecessors(PreHeader, LoopStart);
344
345 for (MachineBasicBlock *MBB : ML->blocks()) {
346 for (MachineInstr &MI : *MBB) {
347 if (IsInvalidTPInstruction(MI)) {
348 LLVM_DEBUG(dbgs() << "Found LR use in loop, reverting: " << MI);
349 if (LoopStart->getOpcode() == ARM::t2DoLoopStart)
350 RevertDoLoopStart(MI: LoopStart, TII);
351 else
352 RevertWhileLoopStartLR(MI: LoopStart, TII);
353 RevertLoopDec(MI: LoopDec, TII);
354 RevertLoopEnd(MI: LoopEnd, TII);
355 return true;
356 }
357 }
358 }
359
360 // Remove any copies from the loop, to ensure the phi that remains is both
361 // simpler and contains no extra uses. Because t2LoopEndDec is a terminator
362 // that cannot spill, we need to be careful what remains in the loop.
363 Register PhiReg = LoopPhi->getOperand(i: 0).getReg();
364 Register DecReg = LoopDec->getOperand(i: 0).getReg();
365 Register StartReg = LoopStart->getOperand(i: 0).getReg();
366 // Ensure the uses are expected, and collect any copies we want to remove.
367 SmallVector<MachineInstr *, 4> Copies;
368 auto CheckUsers = [&Copies](Register BaseReg,
369 ArrayRef<MachineInstr *> ExpectedUsers,
370 MachineRegisterInfo *MRI) {
371 SmallVector<Register, 4> Worklist;
372 Worklist.push_back(Elt: BaseReg);
373 while (!Worklist.empty()) {
374 Register Reg = Worklist.pop_back_val();
375 for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) {
376 if (llvm::is_contained(Range&: ExpectedUsers, Element: &MI))
377 continue;
378 if (MI.getOpcode() != TargetOpcode::COPY ||
379 !MI.getOperand(i: 0).getReg().isVirtual()) {
380 LLVM_DEBUG(dbgs() << "Extra users of register found: " << MI);
381 return false;
382 }
383 Worklist.push_back(Elt: MI.getOperand(i: 0).getReg());
384 Copies.push_back(Elt: &MI);
385 }
386 }
387 return true;
388 };
389 if (!CheckUsers(PhiReg, {LoopDec}, MRI) ||
390 !CheckUsers(DecReg, {LoopPhi, LoopEnd}, MRI) ||
391 !CheckUsers(StartReg, {LoopPhi}, MRI)) {
392 // Don't leave a t2WhileLoopStartLR without the LoopDecEnd.
393 if (LoopStart->getOpcode() == ARM::t2WhileLoopStartLR) {
394 RevertWhileLoopStartLR(MI: LoopStart, TII);
395 RevertLoopDec(MI: LoopDec, TII);
396 RevertLoopEnd(MI: LoopEnd, TII);
397 return true;
398 }
399 return false;
400 }
401
402 MRI->constrainRegClass(Reg: StartReg, RC: &ARM::GPRlrRegClass);
403 MRI->constrainRegClass(Reg: PhiReg, RC: &ARM::GPRlrRegClass);
404 MRI->constrainRegClass(Reg: DecReg, RC: &ARM::GPRlrRegClass);
405
406 if (LoopPhi->getOperand(i: 2).getMBB() == ML->getLoopLatch()) {
407 LoopPhi->getOperand(i: 3).setReg(StartReg);
408 LoopPhi->getOperand(i: 1).setReg(DecReg);
409 } else {
410 LoopPhi->getOperand(i: 1).setReg(StartReg);
411 LoopPhi->getOperand(i: 3).setReg(DecReg);
412 }
413
414 SmallVector<MachineOperand, 4> Cond; // For analyzeBranch.
415 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
416 if (!TII->analyzeBranch(MBB&: *LoopEnd->getParent(), TBB, FBB, Cond) && !FBB) {
417 // If the LoopEnd falls through, need to insert a t2B to the fall-through
418 // block so that the non-analyzable t2LoopEndDec doesn't fall through.
419 MachineFunction::iterator MBBI = ++LoopEnd->getParent()->getIterator();
420 BuildMI(BB: LoopEnd->getParent(), MIMD: DebugLoc(), MCID: TII->get(Opcode: ARM::t2B))
421 .addMBB(MBB: &*MBBI)
422 .add(MOs: predOps(Pred: ARMCC::AL));
423 }
424
425 // Replace the loop dec and loop end as a single instruction.
426 MachineInstrBuilder MI =
427 BuildMI(BB&: *LoopEnd->getParent(), I&: *LoopEnd, MIMD: LoopEnd->getDebugLoc(),
428 MCID: TII->get(Opcode: ARM::t2LoopEndDec), DestReg: DecReg)
429 .addReg(RegNo: PhiReg)
430 .add(MO: LoopEnd->getOperand(i: 1))
431 .setOperandDead(3); // implicit-def $cpsr
432 (void)MI;
433 LLVM_DEBUG(dbgs() << "Merged LoopDec and End into: " << *MI.getInstr());
434
435 LoopDec->eraseFromParent();
436 LoopEnd->eraseFromParent();
437 for (auto *MI : Copies)
438 MI->eraseFromParent();
439 return true;
440}
441
442// Convert t2DoLoopStart to t2DoLoopStartTP if the loop contains VCTP
443// instructions. This keeps the VCTP count reg operand on the t2DoLoopStartTP
444// instruction, making the backend ARMLowOverheadLoops passes job of finding the
445// VCTP operand much simpler.
446bool MVETPAndVPTOptimisations::ConvertTailPredLoop(MachineLoop *ML,
447 MachineDominatorTree *DT) {
448 LLVM_DEBUG(dbgs() << "ConvertTailPredLoop on loop "
449 << ML->getHeader()->getName() << "\n");
450
451 // Find some loop components including the LoopEnd/Dec/Start, and any VCTP's
452 // in the loop.
453 MachineInstr *LoopEnd, *LoopPhi, *LoopStart, *LoopDec;
454 if (!findLoopComponents(ML, MRI, LoopStart, LoopPhi, LoopDec, LoopEnd))
455 return false;
456 if (LoopDec != LoopEnd || (LoopStart->getOpcode() != ARM::t2DoLoopStart &&
457 LoopStart->getOpcode() != ARM::t2WhileLoopStartLR))
458 return false;
459
460 SmallVector<MachineInstr *, 4> VCTPs;
461 SmallVector<MachineInstr *, 4> MVEInstrs;
462 for (MachineBasicBlock *BB : ML->blocks()) {
463 for (MachineInstr &MI : *BB)
464 if (isVCTP(MI: &MI))
465 VCTPs.push_back(Elt: &MI);
466 else if (findFirstVPTPredOperandIdx(MI) != -1)
467 MVEInstrs.push_back(Elt: &MI);
468 }
469
470 if (VCTPs.empty()) {
471 LLVM_DEBUG(dbgs() << " no VCTPs\n");
472 return false;
473 }
474
475 // Check all VCTPs are the same.
476 MachineInstr *FirstVCTP = *VCTPs.begin();
477 for (MachineInstr *VCTP : VCTPs) {
478 LLVM_DEBUG(dbgs() << " with VCTP " << *VCTP);
479 if (VCTP->getOpcode() != FirstVCTP->getOpcode() ||
480 VCTP->getOperand(i: 0).getReg() != FirstVCTP->getOperand(i: 0).getReg()) {
481 LLVM_DEBUG(dbgs() << " VCTP's are not identical\n");
482 return false;
483 }
484 }
485
486 // Check for the register being used can be setup before the loop. We expect
487 // this to be:
488 // $vx = ...
489 // loop:
490 // $vp = PHI [ $vx ], [ $vd ]
491 // ..
492 // $vpr = VCTP $vp
493 // ..
494 // $vd = t2SUBri $vp, #n
495 // ..
496 Register CountReg = FirstVCTP->getOperand(i: 1).getReg();
497 if (!CountReg.isVirtual()) {
498 LLVM_DEBUG(dbgs() << " cannot determine VCTP PHI\n");
499 return false;
500 }
501 MachineInstr *Phi = LookThroughCOPY(MI: MRI->getVRegDef(Reg: CountReg), MRI);
502 if (!Phi || Phi->getOpcode() != TargetOpcode::PHI ||
503 Phi->getNumOperands() != 5 ||
504 (Phi->getOperand(i: 2).getMBB() != ML->getLoopLatch() &&
505 Phi->getOperand(i: 4).getMBB() != ML->getLoopLatch())) {
506 LLVM_DEBUG(dbgs() << " cannot determine VCTP Count\n");
507 return false;
508 }
509 CountReg = Phi->getOperand(i: 2).getMBB() == ML->getLoopLatch()
510 ? Phi->getOperand(i: 3).getReg()
511 : Phi->getOperand(i: 1).getReg();
512
513 // Replace the t2DoLoopStart with the t2DoLoopStartTP, move it to the end of
514 // the preheader and add the new CountReg to it. We attempt to place it late
515 // in the preheader, but may need to move that earlier based on uses.
516 MachineBasicBlock *MBB = LoopStart->getParent();
517 MachineBasicBlock::iterator InsertPt = MBB->getFirstTerminator();
518 for (MachineInstr &Use :
519 MRI->use_instructions(Reg: LoopStart->getOperand(i: 0).getReg()))
520 if ((InsertPt != MBB->end() && !DT->dominates(A: &*InsertPt, B: &Use)) ||
521 !DT->dominates(A: ML->getHeader(), B: Use.getParent())) {
522 LLVM_DEBUG(dbgs() << " InsertPt could not be a terminator!\n");
523 return false;
524 }
525
526 unsigned NewOpc = LoopStart->getOpcode() == ARM::t2DoLoopStart
527 ? ARM::t2DoLoopStartTP
528 : ARM::t2WhileLoopStartTP;
529 MachineInstrBuilder MI =
530 BuildMI(BB&: *MBB, I: InsertPt, MIMD: LoopStart->getDebugLoc(), MCID: TII->get(Opcode: NewOpc))
531 .add(MO: LoopStart->getOperand(i: 0))
532 .add(MO: LoopStart->getOperand(i: 1))
533 .addReg(RegNo: CountReg);
534 if (NewOpc == ARM::t2WhileLoopStartTP)
535 MI.add(MO: LoopStart->getOperand(i: 2)).setOperandDead(4); // implicit-def $cpsr
536 LLVM_DEBUG(dbgs() << "Replacing " << *LoopStart << " with "
537 << *MI.getInstr());
538 MRI->constrainRegClass(Reg: CountReg, RC: &ARM::rGPRRegClass);
539 LoopStart->eraseFromParent();
540
541 if (SetLRPredicate) {
542 // Each instruction in the loop needs to be using LR as the predicate from
543 // the Phi as the predicate.
544 Register LR = LoopPhi->getOperand(i: 0).getReg();
545 for (MachineInstr *MI : MVEInstrs) {
546 int Idx = findFirstVPTPredOperandIdx(MI: *MI);
547 MI->getOperand(i: Idx + ARM::SUBOP_vpred_n_tp_reg).setReg(LR);
548 }
549 }
550
551 return true;
552}
553
554// Returns true if Opcode is any VCMP Opcode.
555static bool IsVCMP(unsigned Opcode) { return VCMPOpcodeToVPT(Opcode) != 0; }
556
557// Returns true if a VCMP with this Opcode can have its operands swapped.
558// There is 2 kind of VCMP that can't have their operands swapped: Float VCMPs,
559// and VCMPr instructions (since the r is always on the right).
560static bool CanHaveSwappedOperands(unsigned Opcode) {
561 switch (Opcode) {
562 default:
563 return true;
564 case ARM::MVE_VCMPf32:
565 case ARM::MVE_VCMPf16:
566 case ARM::MVE_VCMPf32r:
567 case ARM::MVE_VCMPf16r:
568 case ARM::MVE_VCMPi8r:
569 case ARM::MVE_VCMPi16r:
570 case ARM::MVE_VCMPi32r:
571 case ARM::MVE_VCMPu8r:
572 case ARM::MVE_VCMPu16r:
573 case ARM::MVE_VCMPu32r:
574 case ARM::MVE_VCMPs8r:
575 case ARM::MVE_VCMPs16r:
576 case ARM::MVE_VCMPs32r:
577 return false;
578 }
579}
580
581// Returns the CondCode of a VCMP Instruction.
582static ARMCC::CondCodes GetCondCode(MachineInstr &Instr) {
583 assert(IsVCMP(Instr.getOpcode()) && "Inst must be a VCMP");
584 return ARMCC::CondCodes(Instr.getOperand(i: 3).getImm());
585}
586
587// Returns true if Cond is equivalent to a VPNOT instruction on the result of
588// Prev. Cond and Prev must be VCMPs.
589static bool IsVPNOTEquivalent(MachineInstr &Cond, MachineInstr &Prev) {
590 assert(IsVCMP(Cond.getOpcode()) && IsVCMP(Prev.getOpcode()));
591
592 // Opcodes must match.
593 if (Cond.getOpcode() != Prev.getOpcode())
594 return false;
595
596 MachineOperand &CondOP1 = Cond.getOperand(i: 1), &CondOP2 = Cond.getOperand(i: 2);
597 MachineOperand &PrevOP1 = Prev.getOperand(i: 1), &PrevOP2 = Prev.getOperand(i: 2);
598
599 // If the VCMP has the opposite condition with the same operands, we can
600 // replace it with a VPNOT
601 ARMCC::CondCodes ExpectedCode = GetCondCode(Instr&: Cond);
602 ExpectedCode = ARMCC::getOppositeCondition(CC: ExpectedCode);
603 if (ExpectedCode == GetCondCode(Instr&: Prev))
604 if (CondOP1.isIdenticalTo(Other: PrevOP1) && CondOP2.isIdenticalTo(Other: PrevOP2))
605 return true;
606 // Check again with operands swapped if possible
607 if (!CanHaveSwappedOperands(Opcode: Cond.getOpcode()))
608 return false;
609 ExpectedCode = ARMCC::getSwappedCondition(CC: ExpectedCode);
610 return ExpectedCode == GetCondCode(Instr&: Prev) && CondOP1.isIdenticalTo(Other: PrevOP2) &&
611 CondOP2.isIdenticalTo(Other: PrevOP1);
612}
613
614// Returns true if Instr writes to VCCR.
615static bool IsWritingToVCCR(MachineInstr &Instr) {
616 if (Instr.getNumOperands() == 0)
617 return false;
618 MachineOperand &Dst = Instr.getOperand(i: 0);
619 if (!Dst.isReg())
620 return false;
621 Register DstReg = Dst.getReg();
622 if (!DstReg.isVirtual())
623 return false;
624 MachineRegisterInfo &RegInfo = Instr.getMF()->getRegInfo();
625 const TargetRegisterClass *RegClass = RegInfo.getRegClassOrNull(Reg: DstReg);
626 return RegClass && (RegClass->getID() == ARM::VCCRRegClassID);
627}
628
629// Transforms
630// <Instr that uses %A ('User' Operand)>
631// Into
632// %K = VPNOT %Target
633// <Instr that uses %K ('User' Operand)>
634// And returns the newly inserted VPNOT.
635// This optimization is done in the hopes of preventing spills/reloads of VPR by
636// reducing the number of VCCR values with overlapping lifetimes.
637MachineInstr &MVETPAndVPTOptimisations::ReplaceRegisterUseWithVPNOT(
638 MachineBasicBlock &MBB, MachineInstr &Instr, MachineOperand &User,
639 Register Target) {
640 Register NewResult = MRI->createVirtualRegister(RegClass: MRI->getRegClass(Reg: Target));
641
642 MachineInstrBuilder MIBuilder =
643 BuildMI(BB&: MBB, I: &Instr, MIMD: Instr.getDebugLoc(), MCID: TII->get(Opcode: ARM::MVE_VPNOT))
644 .addDef(RegNo: NewResult)
645 .addReg(RegNo: Target);
646 addUnpredicatedMveVpredNOp(MIB&: MIBuilder);
647
648 // Make the user use NewResult instead.
649 User.setReg(NewResult);
650
651 LLVM_DEBUG(dbgs() << " Inserting VPNOT (for spill prevention): ";
652 MIBuilder.getInstr()->dump());
653
654 return *MIBuilder.getInstr();
655}
656
657// Moves a VPNOT before its first user if an instruction that uses Reg is found
658// in-between the VPNOT and its user.
659// Returns true if there is at least one user of the VPNOT in the block.
660static bool MoveVPNOTBeforeFirstUser(MachineBasicBlock &MBB,
661 MachineBasicBlock::iterator Iter,
662 Register Reg) {
663 assert(Iter->getOpcode() == ARM::MVE_VPNOT && "Not a VPNOT!");
664 assert(getVPTInstrPredicate(*Iter) == ARMVCC::None &&
665 "The VPNOT cannot be predicated");
666
667 MachineInstr &VPNOT = *Iter;
668 Register VPNOTResult = VPNOT.getOperand(i: 0).getReg();
669
670 // Whether the VPNOT will need to be moved, and whether we found a user of the
671 // VPNOT.
672 bool MustMove = false, HasUser = false;
673 for (; Iter != MBB.end(); ++Iter) {
674 if (Iter->findRegisterUseOperandIdx(Reg, /*TRI=*/nullptr) != -1) {
675 MustMove = true;
676 continue;
677 }
678
679 if (Iter->findRegisterUseOperandIdx(Reg: VPNOTResult, /*TRI=*/nullptr) == -1)
680 continue;
681
682 HasUser = true;
683 if (!MustMove)
684 break;
685
686 // Move the VPNOT right before Iter
687 LLVM_DEBUG(dbgs() << "Moving: "; VPNOT.dump(); dbgs() << " Before: ";
688 Iter->dump());
689 MBB.splice(Where: Iter, Other: &MBB, From: VPNOT.getIterator());
690 break;
691 }
692 return HasUser;
693}
694
695// This optimisation attempts to reduce the number of overlapping lifetimes of
696// VCCR values by replacing uses of old VCCR values with VPNOTs. For example,
697// this replaces
698// %A:vccr = (something)
699// %B:vccr = VPNOT %A
700// %Foo = (some op that uses %B)
701// %Bar = (some op that uses %A)
702// With
703// %A:vccr = (something)
704// %B:vccr = VPNOT %A
705// %Foo = (some op that uses %B)
706// %TMP2:vccr = VPNOT %B
707// %Bar = (some op that uses %A)
708bool MVETPAndVPTOptimisations::ReduceOldVCCRValueUses(MachineBasicBlock &MBB) {
709 MachineBasicBlock::iterator Iter = MBB.begin(), End = MBB.end();
710 SmallVector<MachineInstr *, 4> DeadInstructions;
711 bool Modified = false;
712
713 while (Iter != End) {
714 Register VCCRValue, OppositeVCCRValue;
715 // The first loop looks for 2 unpredicated instructions:
716 // %A:vccr = (instr) ; A is stored in VCCRValue
717 // %B:vccr = VPNOT %A ; B is stored in OppositeVCCRValue
718 for (; Iter != End; ++Iter) {
719 // We're only interested in unpredicated instructions that write to VCCR.
720 if (!IsWritingToVCCR(Instr&: *Iter) ||
721 getVPTInstrPredicate(MI: *Iter) != ARMVCC::None)
722 continue;
723 Register Dst = Iter->getOperand(i: 0).getReg();
724
725 // If we already have a VCCRValue, and this is a VPNOT on VCCRValue, we've
726 // found what we were looking for.
727 if (VCCRValue && Iter->getOpcode() == ARM::MVE_VPNOT &&
728 Iter->findRegisterUseOperandIdx(Reg: VCCRValue, /*TRI=*/nullptr) != -1) {
729 // Move the VPNOT closer to its first user if needed, and ignore if it
730 // has no users.
731 if (!MoveVPNOTBeforeFirstUser(MBB, Iter, Reg: VCCRValue))
732 continue;
733
734 OppositeVCCRValue = Dst;
735 ++Iter;
736 break;
737 }
738
739 // Else, just set VCCRValue.
740 VCCRValue = Dst;
741 }
742
743 // If the first inner loop didn't find anything, stop here.
744 if (Iter == End)
745 break;
746
747 assert(VCCRValue && OppositeVCCRValue &&
748 "VCCRValue and OppositeVCCRValue shouldn't be empty if the loop "
749 "stopped before the end of the block!");
750 assert(VCCRValue != OppositeVCCRValue &&
751 "VCCRValue should not be equal to OppositeVCCRValue!");
752
753 // LastVPNOTResult always contains the same value as OppositeVCCRValue.
754 Register LastVPNOTResult = OppositeVCCRValue;
755
756 // This second loop tries to optimize the remaining instructions.
757 for (; Iter != End; ++Iter) {
758 bool IsInteresting = false;
759
760 if (MachineOperand *MO =
761 Iter->findRegisterUseOperand(Reg: VCCRValue, /*TRI=*/nullptr)) {
762 IsInteresting = true;
763
764 // - If the instruction is a VPNOT, it can be removed, and we can just
765 // replace its uses with LastVPNOTResult.
766 // - Else, insert a new VPNOT on LastVPNOTResult to recompute VCCRValue.
767 if (Iter->getOpcode() == ARM::MVE_VPNOT) {
768 Register Result = Iter->getOperand(i: 0).getReg();
769
770 MRI->replaceRegWith(FromReg: Result, ToReg: LastVPNOTResult);
771 DeadInstructions.push_back(Elt: &*Iter);
772 Modified = true;
773
774 LLVM_DEBUG(dbgs()
775 << "Replacing all uses of '" << printReg(Result)
776 << "' with '" << printReg(LastVPNOTResult) << "'\n");
777 } else {
778 MachineInstr &VPNOT =
779 ReplaceRegisterUseWithVPNOT(MBB, Instr&: *Iter, User&: *MO, Target: LastVPNOTResult);
780 Modified = true;
781
782 LastVPNOTResult = VPNOT.getOperand(i: 0).getReg();
783 std::swap(a&: VCCRValue, b&: OppositeVCCRValue);
784
785 LLVM_DEBUG(dbgs() << "Replacing use of '" << printReg(VCCRValue)
786 << "' with '" << printReg(LastVPNOTResult)
787 << "' in instr: " << *Iter);
788 }
789 } else {
790 // If the instr uses OppositeVCCRValue, make it use LastVPNOTResult
791 // instead as they contain the same value.
792 if (MachineOperand *MO = Iter->findRegisterUseOperand(
793 Reg: OppositeVCCRValue, /*TRI=*/nullptr)) {
794 IsInteresting = true;
795
796 // This is pointless if LastVPNOTResult == OppositeVCCRValue.
797 if (LastVPNOTResult != OppositeVCCRValue) {
798 LLVM_DEBUG(dbgs() << "Replacing usage of '"
799 << printReg(OppositeVCCRValue) << "' with '"
800 << printReg(LastVPNOTResult) << " for instr: ";
801 Iter->dump());
802 MO->setReg(LastVPNOTResult);
803 Modified = true;
804 }
805 }
806
807 // If this is an unpredicated VPNOT on
808 // LastVPNOTResult/OppositeVCCRValue, we can act like we inserted it.
809 if (Iter->getOpcode() == ARM::MVE_VPNOT &&
810 getVPTInstrPredicate(MI: *Iter) == ARMVCC::None) {
811 Register VPNOTOperand = Iter->getOperand(i: 1).getReg();
812 if (VPNOTOperand == LastVPNOTResult ||
813 VPNOTOperand == OppositeVCCRValue) {
814 IsInteresting = true;
815
816 std::swap(a&: VCCRValue, b&: OppositeVCCRValue);
817 LastVPNOTResult = Iter->getOperand(i: 0).getReg();
818 }
819 }
820 }
821
822 // If this instruction was not interesting, and it writes to VCCR, stop.
823 if (!IsInteresting && IsWritingToVCCR(Instr&: *Iter))
824 break;
825 }
826 }
827
828 for (MachineInstr *DeadInstruction : DeadInstructions)
829 DeadInstruction->eraseFromParent();
830
831 return Modified;
832}
833
834// This optimisation replaces VCMPs with VPNOTs when they are equivalent.
835bool MVETPAndVPTOptimisations::ReplaceVCMPsByVPNOTs(MachineBasicBlock &MBB) {
836 SmallVector<MachineInstr *, 4> DeadInstructions;
837
838 // The last VCMP that we have seen and that couldn't be replaced.
839 // This is reset when an instruction that writes to VCCR/VPR is found, or when
840 // a VCMP is replaced with a VPNOT.
841 // We'll only replace VCMPs with VPNOTs when this is not null, and when the
842 // current VCMP is the opposite of PrevVCMP.
843 MachineInstr *PrevVCMP = nullptr;
844
845 for (MachineInstr &Instr : MBB.instrs()) {
846 // Ignore predicated instructions.
847 if (getVPTInstrPredicate(MI: Instr) != ARMVCC::None)
848 continue;
849
850 // Only look at VCMPs
851 if (!IsVCMP(Opcode: Instr.getOpcode())) {
852 // If the instruction writes to VCCR, forget the previous VCMP.
853 if (IsWritingToVCCR(Instr))
854 PrevVCMP = nullptr;
855 continue;
856 }
857
858 if (!PrevVCMP || !IsVPNOTEquivalent(Cond&: Instr, Prev&: *PrevVCMP)) {
859 PrevVCMP = &Instr;
860 continue;
861 }
862
863 // The register containing the result of the VCMP that we're going to
864 // replace.
865 Register PrevVCMPResultReg = PrevVCMP->getOperand(i: 0).getReg();
866
867 // Build a VPNOT to replace the VCMP, reusing its operands.
868 MachineInstrBuilder MIBuilder =
869 BuildMI(BB&: MBB, I: &Instr, MIMD: Instr.getDebugLoc(), MCID: TII->get(Opcode: ARM::MVE_VPNOT))
870 .add(MO: Instr.getOperand(i: 0))
871 .addReg(RegNo: PrevVCMPResultReg);
872 addUnpredicatedMveVpredNOp(MIB&: MIBuilder);
873 LLVM_DEBUG(dbgs() << "Inserting VPNOT (to replace VCMP): ";
874 MIBuilder.getInstr()->dump(); dbgs() << " Removed VCMP: ";
875 Instr.dump());
876
877 // Finally, mark the old VCMP for removal and reset PrevVCMP.
878 DeadInstructions.push_back(Elt: &Instr);
879 PrevVCMP = nullptr;
880 }
881
882 for (MachineInstr *DeadInstruction : DeadInstructions)
883 DeadInstruction->eraseFromParent();
884
885 return !DeadInstructions.empty();
886}
887
888bool MVETPAndVPTOptimisations::ReplaceConstByVPNOTs(MachineBasicBlock &MBB,
889 MachineDominatorTree *DT) {
890 // Scan through the block, looking for instructions that use constants moves
891 // into VPR that are the negative of one another. These are expected to be
892 // COPY's to VCCRRegClass, from a t2MOVi or t2MOVi16. The last seen constant
893 // mask is kept it or and VPNOT's of it are added or reused as we scan through
894 // the function.
895 unsigned LastVPTImm = 0;
896 Register LastVPTReg = 0;
897 SmallPtrSet<MachineInstr *, 4> DeadInstructions;
898
899 for (MachineInstr &Instr : MBB.instrs()) {
900 // Look for predicated MVE instructions.
901 int PIdx = llvm::findFirstVPTPredOperandIdx(MI: Instr);
902 if (PIdx == -1)
903 continue;
904 Register VPR = Instr.getOperand(i: PIdx + 1).getReg();
905 if (!VPR.isVirtual())
906 continue;
907
908 // From that we are looking for an instruction like %11:vccr = COPY %9:rgpr.
909 MachineInstr *Copy = MRI->getVRegDef(Reg: VPR);
910 if (!Copy || Copy->getOpcode() != TargetOpcode::COPY ||
911 !Copy->getOperand(i: 1).getReg().isVirtual() ||
912 MRI->getRegClass(Reg: Copy->getOperand(i: 1).getReg()) == &ARM::VCCRRegClass) {
913 LastVPTReg = 0;
914 continue;
915 }
916 Register GPR = Copy->getOperand(i: 1).getReg();
917
918 // Find the Immediate used by the copy.
919 auto getImm = [&](Register GPR) -> unsigned {
920 MachineInstr *Def = MRI->getVRegDef(Reg: GPR);
921 if (Def && (Def->getOpcode() == ARM::t2MOVi ||
922 Def->getOpcode() == ARM::t2MOVi16))
923 return Def->getOperand(i: 1).getImm();
924 return -1U;
925 };
926 unsigned Imm = getImm(GPR);
927 if (Imm == -1U) {
928 LastVPTReg = 0;
929 continue;
930 }
931
932 unsigned NotImm = ~Imm & 0xffff;
933 if (LastVPTReg != 0 && LastVPTReg != VPR && LastVPTImm == Imm) {
934 Instr.getOperand(i: PIdx + 1).setReg(LastVPTReg);
935 if (MRI->use_nodbg_empty(RegNo: VPR)) {
936 DeadInstructions.insert(Ptr: Copy);
937 if (MRI->hasOneNonDBGUse(RegNo: GPR))
938 DeadInstructions.insert(Ptr: MRI->getVRegDef(Reg: GPR));
939 }
940 LLVM_DEBUG(dbgs() << "Reusing predicate: in " << Instr);
941 VPR = LastVPTReg;
942 } else if (LastVPTReg != 0 && LastVPTImm == NotImm) {
943 // We have found the not of a previous constant. Create a VPNot of the
944 // earlier predicate reg and use it instead of the copy.
945 Register NewVPR = MRI->createVirtualRegister(RegClass: &ARM::VCCRRegClass);
946 auto VPNot = BuildMI(BB&: MBB, I: &Instr, MIMD: Instr.getDebugLoc(),
947 MCID: TII->get(Opcode: ARM::MVE_VPNOT), DestReg: NewVPR)
948 .addReg(RegNo: LastVPTReg);
949 addUnpredicatedMveVpredNOp(MIB&: VPNot);
950
951 // Use the new register and check if the def is now dead.
952 Instr.getOperand(i: PIdx + 1).setReg(NewVPR);
953 if (MRI->use_nodbg_empty(RegNo: VPR)) {
954 DeadInstructions.insert(Ptr: Copy);
955 if (MRI->hasOneNonDBGUse(RegNo: GPR))
956 DeadInstructions.insert(Ptr: MRI->getVRegDef(Reg: GPR));
957 }
958 LLVM_DEBUG(dbgs() << "Adding VPNot: " << *VPNot << " to replace use at "
959 << Instr);
960 VPR = NewVPR;
961 }
962
963 LastVPTImm = Imm;
964 LastVPTReg = VPR;
965 }
966
967 for (MachineInstr *DI : DeadInstructions)
968 DI->eraseFromParent();
969
970 return !DeadInstructions.empty();
971}
972
973// Replace VPSEL with a predicated VMOV in blocks with a VCTP. This is a
974// somewhat blunt approximation to allow tail predicated with vpsel
975// instructions. We turn a vselect into a VPSEL in ISEL, but they have slightly
976// different semantics under tail predication. Until that is modelled we just
977// convert to a VMOVT (via a predicated VORR) instead.
978bool MVETPAndVPTOptimisations::ConvertVPSEL(MachineBasicBlock &MBB) {
979 bool HasVCTP = false;
980 SmallVector<MachineInstr *, 4> DeadInstructions;
981
982 for (MachineInstr &MI : MBB.instrs()) {
983 if (isVCTP(MI: &MI)) {
984 HasVCTP = true;
985 continue;
986 }
987
988 if (!HasVCTP || MI.getOpcode() != ARM::MVE_VPSEL)
989 continue;
990
991 MachineInstrBuilder MIBuilder =
992 BuildMI(BB&: MBB, I: &MI, MIMD: MI.getDebugLoc(), MCID: TII->get(Opcode: ARM::MVE_VORR))
993 .add(MO: MI.getOperand(i: 0))
994 .add(MO: MI.getOperand(i: 1))
995 .add(MO: MI.getOperand(i: 1))
996 .addImm(Val: ARMVCC::Then)
997 .add(MO: MI.getOperand(i: 4))
998 .add(MO: MI.getOperand(i: 5))
999 .add(MO: MI.getOperand(i: 2));
1000 // Silence unused variable warning in release builds.
1001 (void)MIBuilder;
1002 LLVM_DEBUG(dbgs() << "Replacing VPSEL: "; MI.dump();
1003 dbgs() << " with VMOVT: "; MIBuilder.getInstr()->dump());
1004 DeadInstructions.push_back(Elt: &MI);
1005 }
1006
1007 for (MachineInstr *DeadInstruction : DeadInstructions)
1008 DeadInstruction->eraseFromParent();
1009
1010 return !DeadInstructions.empty();
1011}
1012
1013// Add a registry allocation hint for t2DoLoopStart to hint it towards LR, as
1014// the instruction may be removable as a noop.
1015bool MVETPAndVPTOptimisations::HintDoLoopStartReg(MachineBasicBlock &MBB) {
1016 bool Changed = false;
1017 for (MachineInstr &MI : MBB.instrs()) {
1018 if (MI.getOpcode() != ARM::t2DoLoopStart)
1019 continue;
1020 Register R = MI.getOperand(i: 1).getReg();
1021 MachineFunction *MF = MI.getParent()->getParent();
1022 MF->getRegInfo().setRegAllocationHint(VReg: R, Type: ARMRI::RegLR, PrefReg: 0);
1023 Changed = true;
1024 }
1025 return Changed;
1026}
1027
1028bool MVETPAndVPTOptimisations::runOnMachineFunction(MachineFunction &Fn) {
1029 const ARMSubtarget &STI = Fn.getSubtarget<ARMSubtarget>();
1030
1031 if (!STI.isThumb2() || !STI.hasLOB())
1032 return false;
1033
1034 TII = static_cast<const Thumb2InstrInfo *>(STI.getInstrInfo());
1035 MRI = &Fn.getRegInfo();
1036 MachineLoopInfo *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
1037 MachineDominatorTree *DT =
1038 &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
1039
1040 LLVM_DEBUG(dbgs() << "********** ARM MVE VPT Optimisations **********\n"
1041 << "********** Function: " << Fn.getName() << '\n');
1042
1043 bool Modified = false;
1044 for (MachineLoop *ML : MLI->getLoopsInPreorder()) {
1045 Modified |= LowerWhileLoopStart(ML);
1046 Modified |= MergeLoopEnd(ML);
1047 Modified |= ConvertTailPredLoop(ML, DT);
1048 }
1049
1050 for (MachineBasicBlock &MBB : Fn) {
1051 Modified |= HintDoLoopStartReg(MBB);
1052 Modified |= ReplaceConstByVPNOTs(MBB, DT);
1053 Modified |= ReplaceVCMPsByVPNOTs(MBB);
1054 Modified |= ReduceOldVCCRValueUses(MBB);
1055 Modified |= ConvertVPSEL(MBB);
1056 }
1057
1058 LLVM_DEBUG(dbgs() << "**************************************\n");
1059 return Modified;
1060}
1061
1062/// createMVETPAndVPTOptimisationsPass
1063FunctionPass *llvm::createMVETPAndVPTOptimisationsPass() {
1064 return new MVETPAndVPTOptimisations();
1065}
1066