1//===-- AArch64CondBrTuning.cpp --- Conditional branch tuning for AArch64 -===//
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/// This file contains a pass that transforms CBZ/CBNZ/TBZ/TBNZ instructions
10/// into a conditional branch (B.cond), when the NZCV flags can be set for
11/// "free". This is preferred on targets that have more flexibility when
12/// scheduling B.cond instructions as compared to CBZ/CBNZ/TBZ/TBNZ (assuming
13/// all other variables are equal). This can also reduce register pressure.
14///
15/// A few examples:
16///
17/// 1) add w8, w0, w1 -> cmn w0, w1 ; CMN is an alias of ADDS.
18/// cbz w8, .LBB_2 -> b.eq .LBB0_2
19///
20/// 2) add w8, w0, w1 -> adds w8, w0, w1 ; w8 has multiple uses.
21/// cbz w8, .LBB1_2 -> b.eq .LBB1_2
22///
23/// 3) sub w8, w0, w1 -> subs w8, w0, w1 ; w8 has multiple uses.
24/// tbz w8, #31, .LBB6_2 -> b.pl .LBB6_2
25///
26//===----------------------------------------------------------------------===//
27
28#include "AArch64.h"
29#include "AArch64Subtarget.h"
30#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFunctionPass.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
33#include "llvm/CodeGen/MachineRegisterInfo.h"
34#include "llvm/CodeGen/Passes.h"
35#include "llvm/CodeGen/TargetInstrInfo.h"
36#include "llvm/CodeGen/TargetRegisterInfo.h"
37#include "llvm/CodeGen/TargetSubtargetInfo.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/raw_ostream.h"
40
41using namespace llvm;
42
43#define DEBUG_TYPE "aarch64-cond-br-tuning"
44#define AARCH64_CONDBR_TUNING_NAME "AArch64 Conditional Branch Tuning"
45
46namespace {
47class AArch64CondBrTuning : public MachineFunctionPass {
48 const AArch64InstrInfo *TII;
49 const TargetRegisterInfo *TRI;
50
51 MachineRegisterInfo *MRI;
52
53public:
54 static char ID;
55 AArch64CondBrTuning() : MachineFunctionPass(ID) {}
56 void getAnalysisUsage(AnalysisUsage &AU) const override;
57 bool runOnMachineFunction(MachineFunction &MF) override;
58 StringRef getPassName() const override { return AARCH64_CONDBR_TUNING_NAME; }
59
60private:
61 MachineInstr *getOperandDef(const MachineOperand &MO);
62 MachineInstr *tryConvertToFlagSetting(MachineInstr &MI, bool IsFlagSetting,
63 bool Is64Bit);
64 MachineInstr *convertToCondBr(MachineInstr &MI);
65 bool tryToTuneBranch(MachineInstr &MI, MachineInstr &DefMI);
66};
67} // end anonymous namespace
68
69char AArch64CondBrTuning::ID = 0;
70
71INITIALIZE_PASS(AArch64CondBrTuning, "aarch64-cond-br-tuning",
72 AARCH64_CONDBR_TUNING_NAME, false, false)
73
74void AArch64CondBrTuning::getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.setPreservesCFG();
76 MachineFunctionPass::getAnalysisUsage(AU);
77}
78
79MachineInstr *AArch64CondBrTuning::getOperandDef(const MachineOperand &MO) {
80 if (!MO.getReg().isVirtual())
81 return nullptr;
82 return MRI->getUniqueVRegDef(Reg: MO.getReg());
83}
84
85MachineInstr *AArch64CondBrTuning::tryConvertToFlagSetting(MachineInstr &MI,
86 bool IsFlagSetting,
87 bool Is64Bit) {
88 // If the instruction has a frame index operand, we can't safely convert it
89 // to a flag-setting form, because it can be expanded later into multiple
90 // instructions, which don't all have flag-setting forms (e.g. ADDVL).
91 if (any_of(Range: MI.operands(), P: [](const MachineOperand &Op) { return Op.isFI(); }))
92 return nullptr;
93
94 // If this is already the flag setting version of the instruction (e.g., SUBS)
95 // just make sure the implicit-def of NZCV isn't marked dead.
96 if (IsFlagSetting) {
97 for (MachineOperand &MO : MI.implicit_operands())
98 if (MO.isReg() && MO.isDead() && MO.getReg() == AArch64::NZCV)
99 MO.setIsDead(false);
100 return &MI;
101 }
102 unsigned NewOpc = TII->convertToFlagSettingOpc(Opc: MI.getOpcode());
103 Register NewDestReg = MI.getOperand(i: 0).getReg();
104 if (MRI->hasOneNonDBGUse(RegNo: MI.getOperand(i: 0).getReg()))
105 NewDestReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
106
107 MachineInstrBuilder MIB = BuildMI(BB&: *MI.getParent(), I&: MI, MIMD: MI.getDebugLoc(),
108 MCID: TII->get(Opcode: NewOpc), DestReg: NewDestReg);
109
110 // If the MI has a debug instruction number, preserve that in the new Machine
111 // Instruction that is created.
112 if (MI.peekDebugInstrNum() != 0)
113 MIB->setDebugInstrNum(MI.peekDebugInstrNum());
114
115 for (const MachineOperand &MO : llvm::drop_begin(RangeOrContainer: MI.operands()))
116 MIB.add(MO);
117
118 return MIB;
119}
120
121MachineInstr *AArch64CondBrTuning::convertToCondBr(MachineInstr &MI) {
122 AArch64CC::CondCode CC;
123 MachineBasicBlock *TargetMBB = TII->getBranchDestBlock(MI);
124 switch (MI.getOpcode()) {
125 default:
126 llvm_unreachable("Unexpected opcode!");
127
128 case AArch64::CBZW:
129 case AArch64::CBZX:
130 CC = AArch64CC::EQ;
131 break;
132 case AArch64::CBNZW:
133 case AArch64::CBNZX:
134 CC = AArch64CC::NE;
135 break;
136 case AArch64::TBZW:
137 case AArch64::TBZX:
138 CC = AArch64CC::PL;
139 break;
140 case AArch64::TBNZW:
141 case AArch64::TBNZX:
142 CC = AArch64CC::MI;
143 break;
144 }
145 return BuildMI(BB&: *MI.getParent(), I&: MI, MIMD: MI.getDebugLoc(), MCID: TII->get(Opcode: AArch64::Bcc))
146 .addImm(Val: CC)
147 .addMBB(MBB: TargetMBB);
148}
149
150bool AArch64CondBrTuning::tryToTuneBranch(MachineInstr &MI,
151 MachineInstr &DefMI) {
152 // We don't want NZCV bits live across blocks.
153 if (MI.getParent() != DefMI.getParent())
154 return false;
155
156 bool IsFlagSetting = true;
157 unsigned MIOpc = MI.getOpcode();
158 MachineInstr *NewCmp = nullptr, *NewBr = nullptr;
159 switch (DefMI.getOpcode()) {
160 default:
161 return false;
162 case AArch64::ADDWri:
163 case AArch64::ADDWrr:
164 case AArch64::ADDWrs:
165 case AArch64::ADDWrx:
166 case AArch64::ANDWri:
167 case AArch64::ANDWrr:
168 case AArch64::ANDWrs:
169 case AArch64::BICWrr:
170 case AArch64::BICWrs:
171 case AArch64::SUBWri:
172 case AArch64::SUBWrr:
173 case AArch64::SUBWrs:
174 case AArch64::SUBWrx:
175 IsFlagSetting = false;
176 [[fallthrough]];
177 case AArch64::ADDSWri:
178 case AArch64::ADDSWrr:
179 case AArch64::ADDSWrs:
180 case AArch64::ADDSWrx:
181 case AArch64::ANDSWri:
182 case AArch64::ANDSWrr:
183 case AArch64::ANDSWrs:
184 case AArch64::BICSWrr:
185 case AArch64::BICSWrs:
186 case AArch64::SUBSWri:
187 case AArch64::SUBSWrr:
188 case AArch64::SUBSWrs:
189 case AArch64::SUBSWrx:
190 switch (MIOpc) {
191 default:
192 llvm_unreachable("Unexpected opcode!");
193
194 case AArch64::CBZW:
195 case AArch64::CBNZW:
196 case AArch64::TBZW:
197 case AArch64::TBNZW:
198 // Check to see if the TBZ/TBNZ is checking the sign bit.
199 if ((MIOpc == AArch64::TBZW || MIOpc == AArch64::TBNZW) &&
200 MI.getOperand(i: 1).getImm() != 31)
201 return false;
202
203 // There must not be any instruction between DefMI and MI that clobbers or
204 // reads NZCV.
205 if (isNZCVTouchedInInstructionRange(DefMI, UseMI: MI, TRI))
206 return false;
207
208 NewCmp = tryConvertToFlagSetting(MI&: DefMI, IsFlagSetting, /*Is64Bit=*/false);
209 if (!NewCmp)
210 return false;
211
212 LLVM_DEBUG(dbgs() << " Replacing instructions:\n ");
213 LLVM_DEBUG(DefMI.print(dbgs()));
214 LLVM_DEBUG(dbgs() << " ");
215 LLVM_DEBUG(MI.print(dbgs()));
216
217 NewBr = convertToCondBr(MI);
218 break;
219 }
220 break;
221
222 case AArch64::ADDXri:
223 case AArch64::ADDXrr:
224 case AArch64::ADDXrs:
225 case AArch64::ADDXrx:
226 case AArch64::ANDXri:
227 case AArch64::ANDXrr:
228 case AArch64::ANDXrs:
229 case AArch64::BICXrr:
230 case AArch64::BICXrs:
231 case AArch64::SUBXri:
232 case AArch64::SUBXrr:
233 case AArch64::SUBXrs:
234 case AArch64::SUBXrx:
235 IsFlagSetting = false;
236 [[fallthrough]];
237 case AArch64::ADDSXri:
238 case AArch64::ADDSXrr:
239 case AArch64::ADDSXrs:
240 case AArch64::ADDSXrx:
241 case AArch64::ANDSXri:
242 case AArch64::ANDSXrr:
243 case AArch64::ANDSXrs:
244 case AArch64::BICSXrr:
245 case AArch64::BICSXrs:
246 case AArch64::SUBSXri:
247 case AArch64::SUBSXrr:
248 case AArch64::SUBSXrs:
249 case AArch64::SUBSXrx:
250 switch (MIOpc) {
251 default:
252 llvm_unreachable("Unexpected opcode!");
253
254 case AArch64::CBZX:
255 case AArch64::CBNZX:
256 case AArch64::TBZX:
257 case AArch64::TBNZX: {
258 // Check to see if the TBZ/TBNZ is checking the sign bit.
259 if ((MIOpc == AArch64::TBZX || MIOpc == AArch64::TBNZX) &&
260 MI.getOperand(i: 1).getImm() != 63)
261 return false;
262 // There must not be any instruction between DefMI and MI that clobbers or
263 // reads NZCV.
264 if (isNZCVTouchedInInstructionRange(DefMI, UseMI: MI, TRI))
265 return false;
266
267 NewCmp = tryConvertToFlagSetting(MI&: DefMI, IsFlagSetting, /*Is64Bit=*/true);
268 if (!NewCmp)
269 return false;
270
271 LLVM_DEBUG(dbgs() << " Replacing instructions:\n ");
272 LLVM_DEBUG(DefMI.print(dbgs()));
273 LLVM_DEBUG(dbgs() << " ");
274 LLVM_DEBUG(MI.print(dbgs()));
275
276 NewBr = convertToCondBr(MI);
277 break;
278 }
279 }
280 break;
281 }
282 (void)NewCmp; (void)NewBr;
283 assert(NewCmp && NewBr && "Expected new instructions.");
284
285 LLVM_DEBUG(dbgs() << " with instruction:\n ");
286 LLVM_DEBUG(NewCmp->print(dbgs()));
287 LLVM_DEBUG(dbgs() << " ");
288 LLVM_DEBUG(NewBr->print(dbgs()));
289
290 // If this was a flag setting version of the instruction, we use the original
291 // instruction by just clearing the dead marked on the implicit-def of NCZV.
292 // Therefore, we should not erase this instruction.
293 if (!IsFlagSetting)
294 DefMI.eraseFromParent();
295 MI.eraseFromParent();
296 return true;
297}
298
299bool AArch64CondBrTuning::runOnMachineFunction(MachineFunction &MF) {
300 if (skipFunction(F: MF.getFunction()))
301 return false;
302
303 LLVM_DEBUG(
304 dbgs() << "********** AArch64 Conditional Branch Tuning **********\n"
305 << "********** Function: " << MF.getName() << '\n');
306
307 TII = static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
308 TRI = MF.getSubtarget().getRegisterInfo();
309 MRI = &MF.getRegInfo();
310
311 bool Changed = false;
312 for (MachineBasicBlock &MBB : MF) {
313 bool LocalChange = false;
314 for (MachineInstr &MI : MBB.terminators()) {
315 switch (MI.getOpcode()) {
316 default:
317 break;
318 case AArch64::CBZW:
319 case AArch64::CBZX:
320 case AArch64::CBNZW:
321 case AArch64::CBNZX:
322 case AArch64::TBZW:
323 case AArch64::TBZX:
324 case AArch64::TBNZW:
325 case AArch64::TBNZX:
326 MachineInstr *DefMI = getOperandDef(MO: MI.getOperand(i: 0));
327 LocalChange = (DefMI && tryToTuneBranch(MI, DefMI&: *DefMI));
328 break;
329 }
330 // If the optimization was successful, we can't optimize any other
331 // branches because doing so would clobber the NZCV flags.
332 if (LocalChange) {
333 Changed = true;
334 break;
335 }
336 }
337 }
338 return Changed;
339}
340
341FunctionPass *llvm::createAArch64CondBrTuning() {
342 return new AArch64CondBrTuning();
343}
344