LLVM 24.0.0git
AArch64CondBrTuning.cpp
Go to the documentation of this file.
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"
34#include "llvm/CodeGen/Passes.h"
39#include "llvm/Support/Debug.h"
41
42using namespace llvm;
43
44#define DEBUG_TYPE "aarch64-cond-br-tuning"
45#define AARCH64_CONDBR_TUNING_NAME "AArch64 Conditional Branch Tuning"
46
47namespace {
48class AArch64CondBrTuning : public MachineFunctionPass {
49 const AArch64InstrInfo *TII;
51
53
54public:
55 static char ID;
56 AArch64CondBrTuning() : MachineFunctionPass(ID) {}
57 void getAnalysisUsage(AnalysisUsage &AU) const override;
58 bool runOnMachineFunction(MachineFunction &MF) override;
59 StringRef getPassName() const override { return AARCH64_CONDBR_TUNING_NAME; }
60
61private:
62 MachineInstr *getOperandDef(const MachineOperand &MO);
63 MachineInstr *convertToFlagSetting(MachineInstr &MI, bool IsFlagSetting,
64 bool Is64Bit);
65 MachineInstr *convertToCondBr(MachineInstr &MI);
66 bool tryToTuneBranch(MachineInstr &MI, MachineInstr &DefMI);
67};
68} // end anonymous namespace
69
70char AArch64CondBrTuning::ID = 0;
71
72INITIALIZE_PASS(AArch64CondBrTuning, "aarch64-cond-br-tuning",
73 AARCH64_CONDBR_TUNING_NAME, false, false)
74
75void AArch64CondBrTuning::getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.setPreservesCFG();
78}
79
80MachineInstr *AArch64CondBrTuning::getOperandDef(const MachineOperand &MO) {
81 if (!MO.getReg().isVirtual())
82 return nullptr;
83 return MRI->getUniqueVRegDef(MO.getReg());
84}
85
86MachineInstr *AArch64CondBrTuning::convertToFlagSetting(MachineInstr &MI,
87 bool IsFlagSetting,
88 bool Is64Bit) {
89 // If this is already the flag setting version of the instruction (e.g., SUBS)
90 // just make sure the implicit-def of NZCV isn't marked dead.
91 if (IsFlagSetting) {
92 for (MachineOperand &MO : MI.implicit_operands())
93 if (MO.isReg() && MO.isDead() && MO.getReg() == AArch64::NZCV)
94 MO.setIsDead(false);
95 return &MI;
96 }
97 unsigned NewOpc = TII->convertToFlagSettingOpc(MI.getOpcode());
98 Register NewDestReg = MI.getOperand(0).getReg();
99 if (MRI->hasOneNonDBGUse(MI.getOperand(0).getReg()))
100 NewDestReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
101
102 MachineInstrBuilder MIB = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
103 TII->get(NewOpc), NewDestReg);
104
105 // If the MI has a debug instruction number, preserve that in the new Machine
106 // Instruction that is created.
107 if (MI.peekDebugInstrNum() != 0)
108 MIB->setDebugInstrNum(MI.peekDebugInstrNum());
109
110 for (const MachineOperand &MO : llvm::drop_begin(MI.operands()))
111 MIB.add(MO);
112
113 return MIB;
114}
115
116MachineInstr *AArch64CondBrTuning::convertToCondBr(MachineInstr &MI) {
118 MachineBasicBlock *TargetMBB = TII->getBranchDestBlock(MI);
119 switch (MI.getOpcode()) {
120 default:
121 llvm_unreachable("Unexpected opcode!");
122
123 case AArch64::CBZW:
124 case AArch64::CBZX:
125 CC = AArch64CC::EQ;
126 break;
127 case AArch64::CBNZW:
128 case AArch64::CBNZX:
129 CC = AArch64CC::NE;
130 break;
131 case AArch64::TBZW:
132 case AArch64::TBZX:
133 CC = AArch64CC::PL;
134 break;
135 case AArch64::TBNZW:
136 case AArch64::TBNZX:
137 CC = AArch64CC::MI;
138 break;
139 }
140 return BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII->get(AArch64::Bcc))
141 .addImm(CC)
142 .addMBB(TargetMBB);
143}
144
145bool AArch64CondBrTuning::tryToTuneBranch(MachineInstr &MI,
146 MachineInstr &DefMI) {
147 // We don't want NZCV bits live across blocks.
148 if (MI.getParent() != DefMI.getParent())
149 return false;
150
151 bool IsFlagSetting = true;
152 unsigned MIOpc = MI.getOpcode();
153 MachineInstr *NewCmp = nullptr, *NewBr = nullptr;
154 switch (DefMI.getOpcode()) {
155 default:
156 return false;
157 case AArch64::ADDWri:
158 case AArch64::ADDWrr:
159 case AArch64::ADDWrs:
160 case AArch64::ADDWrx:
161 case AArch64::ANDWri:
162 case AArch64::ANDWrr:
163 case AArch64::ANDWrs:
164 case AArch64::BICWrr:
165 case AArch64::BICWrs:
166 case AArch64::SUBWri:
167 case AArch64::SUBWrr:
168 case AArch64::SUBWrs:
169 case AArch64::SUBWrx:
170 IsFlagSetting = false;
171 [[fallthrough]];
172 case AArch64::ADDSWri:
173 case AArch64::ADDSWrr:
174 case AArch64::ADDSWrs:
175 case AArch64::ADDSWrx:
176 case AArch64::ANDSWri:
177 case AArch64::ANDSWrr:
178 case AArch64::ANDSWrs:
179 case AArch64::BICSWrr:
180 case AArch64::BICSWrs:
181 case AArch64::SUBSWri:
182 case AArch64::SUBSWrr:
183 case AArch64::SUBSWrs:
184 case AArch64::SUBSWrx:
185 switch (MIOpc) {
186 default:
187 llvm_unreachable("Unexpected opcode!");
188
189 case AArch64::CBZW:
190 case AArch64::CBNZW:
191 case AArch64::TBZW:
192 case AArch64::TBNZW:
193 // Check to see if the TBZ/TBNZ is checking the sign bit.
194 if ((MIOpc == AArch64::TBZW || MIOpc == AArch64::TBNZW) &&
195 MI.getOperand(1).getImm() != 31)
196 return false;
197
198 // There must not be any instruction between DefMI and MI that clobbers or
199 // reads NZCV.
201 return false;
202 LLVM_DEBUG(dbgs() << " Replacing instructions:\n ");
203 LLVM_DEBUG(DefMI.print(dbgs()));
204 LLVM_DEBUG(dbgs() << " ");
206
207 NewCmp = convertToFlagSetting(DefMI, IsFlagSetting, /*Is64Bit=*/false);
208 NewBr = convertToCondBr(MI);
209 break;
210 }
211 break;
212
213 case AArch64::ADDXri:
214 case AArch64::ADDXrr:
215 case AArch64::ADDXrs:
216 case AArch64::ADDXrx:
217 case AArch64::ANDXri:
218 case AArch64::ANDXrr:
219 case AArch64::ANDXrs:
220 case AArch64::BICXrr:
221 case AArch64::BICXrs:
222 case AArch64::SUBXri:
223 case AArch64::SUBXrr:
224 case AArch64::SUBXrs:
225 case AArch64::SUBXrx:
226 IsFlagSetting = false;
227 [[fallthrough]];
228 case AArch64::ADDSXri:
229 case AArch64::ADDSXrr:
230 case AArch64::ADDSXrs:
231 case AArch64::ADDSXrx:
232 case AArch64::ANDSXri:
233 case AArch64::ANDSXrr:
234 case AArch64::ANDSXrs:
235 case AArch64::BICSXrr:
236 case AArch64::BICSXrs:
237 case AArch64::SUBSXri:
238 case AArch64::SUBSXrr:
239 case AArch64::SUBSXrs:
240 case AArch64::SUBSXrx:
241 switch (MIOpc) {
242 default:
243 llvm_unreachable("Unexpected opcode!");
244
245 case AArch64::CBZX:
246 case AArch64::CBNZX:
247 case AArch64::TBZX:
248 case AArch64::TBNZX: {
249 // Check to see if the TBZ/TBNZ is checking the sign bit.
250 if ((MIOpc == AArch64::TBZX || MIOpc == AArch64::TBNZX) &&
251 MI.getOperand(1).getImm() != 63)
252 return false;
253 // There must not be any instruction between DefMI and MI that clobbers or
254 // reads NZCV.
256 return false;
257 LLVM_DEBUG(dbgs() << " Replacing instructions:\n ");
258 LLVM_DEBUG(DefMI.print(dbgs()));
259 LLVM_DEBUG(dbgs() << " ");
261
262 NewCmp = convertToFlagSetting(DefMI, IsFlagSetting, /*Is64Bit=*/true);
263 NewBr = convertToCondBr(MI);
264 break;
265 }
266 }
267 break;
268 }
269 (void)NewCmp; (void)NewBr;
270 assert(NewCmp && NewBr && "Expected new instructions.");
271
272 LLVM_DEBUG(dbgs() << " with instruction:\n ");
273 LLVM_DEBUG(NewCmp->print(dbgs()));
274 LLVM_DEBUG(dbgs() << " ");
275 LLVM_DEBUG(NewBr->print(dbgs()));
276
277 // If this was a flag setting version of the instruction, we use the original
278 // instruction by just clearing the dead marked on the implicit-def of NCZV.
279 // Therefore, we should not erase this instruction.
280 if (!IsFlagSetting)
281 DefMI.eraseFromParent();
282 MI.eraseFromParent();
283 return true;
284}
285
286bool AArch64CondBrTuning::runOnMachineFunction(MachineFunction &MF) {
287 if (skipFunction(MF.getFunction()))
288 return false;
289
291 dbgs() << "********** AArch64 Conditional Branch Tuning **********\n"
292 << "********** Function: " << MF.getName() << '\n');
293
294 TII = static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
296 MRI = &MF.getRegInfo();
297
298 bool Changed = false;
299 for (MachineBasicBlock &MBB : MF) {
300 bool LocalChange = false;
301 for (MachineInstr &MI : MBB.terminators()) {
302 switch (MI.getOpcode()) {
303 default:
304 break;
305 case AArch64::CBZW:
306 case AArch64::CBZX:
307 case AArch64::CBNZW:
308 case AArch64::CBNZX:
309 case AArch64::TBZW:
310 case AArch64::TBZX:
311 case AArch64::TBNZW:
312 case AArch64::TBNZX:
313 MachineInstr *DefMI = getOperandDef(MI.getOperand(0));
314 LocalChange = (DefMI && tryToTuneBranch(MI, *DefMI));
315 break;
316 }
317 // If the optimization was successful, we can't optimize any other
318 // branches because doing so would clobber the NZCV flags.
319 if (LocalChange) {
320 Changed = true;
321 break;
322 }
323 }
324 }
325 return Changed;
326}
327
329 return new AArch64CondBrTuning();
330}
#define AARCH64_CONDBR_TUNING_NAME
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
iterator_range< iterator > terminators()
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.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
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
Representation of each machine instruction.
void setDebugInstrNum(unsigned Num)
Set instruction number of this MachineInstr.
LLVM_ABI void print(raw_ostream &OS, bool IsStandalone=true, bool SkipOpers=false, bool SkipDebugLoc=false, bool AddNewLine=true, const TargetInstrInfo *TII=nullptr) const
Print this MI to OS.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setIsDead(bool Val=true)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
LLVM_ABI MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
virtual void print(raw_ostream &OS, const Module *M) const
print - Print out the internal state of the pass.
Definition Pass.cpp:140
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
FunctionPass * createAArch64CondBrTuning()
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isNZCVTouchedInInstructionRange(const MachineInstr &DefMI, const MachineInstr &UseMI, const TargetRegisterInfo *TRI)
Return true if there is an instruction /after/ DefMI and before UseMI which either reads or clobbers ...