blob: fc27bfee73d13009a3ad938a35b1b2bbf6f7b4eb [file] [log] [blame]
Jiangning Liu1a486da2014-09-05 02:55:24 +00001//=- AArch64ConditionOptimizer.cpp - Remove useless comparisons for AArch64 -=//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass tries to make consecutive compares of values use same operands to
11// allow CSE pass to remove duplicated instructions. For this it analyzes
12// branches and adjusts comparisons with immediate values by converting:
13// * GE -> GT
14// * GT -> GE
15// * LT -> LE
16// * LE -> LT
17// and adjusting immediate values appropriately. It basically corrects two
18// immediate values towards each other to make them equal.
19//
20// Consider the following example in C:
21//
22// if ((a < 5 && ...) || (a > 5 && ...)) {
23// ~~~~~ ~~~~~
24// ^ ^
25// x y
26//
27// Here both "x" and "y" expressions compare "a" with "5". When "x" evaluates
28// to "false", "y" can just check flags set by the first comparison. As a
29// result of the canonicalization employed by
30// SelectionDAGBuilder::visitSwitchCase, DAGCombine, and other target-specific
31// code, assembly ends up in the form that is not CSE friendly:
32//
33// ...
34// cmp w8, #4
35// b.gt .LBB0_3
36// ...
37// .LBB0_3:
38// cmp w8, #6
39// b.lt .LBB0_6
40// ...
41//
42// Same assembly after the pass:
43//
44// ...
45// cmp w8, #5
46// b.ge .LBB0_3
47// ...
48// .LBB0_3:
49// cmp w8, #5 // <-- CSE pass removes this instruction
50// b.le .LBB0_6
51// ...
52//
53// Currently only SUBS and ADDS followed by b.?? are supported.
54//
55// TODO: maybe handle TBNZ/TBZ the same way as CMP when used instead for "a < 0"
56// TODO: handle other conditional instructions (e.g. CSET)
57// TODO: allow second branching to be anything if it doesn't require adjusting
58//
59//===----------------------------------------------------------------------===//
60
61#include "AArch64.h"
Tim Northovercf739b82015-07-29 16:39:56 +000062#include "MCTargetDesc/AArch64AddressingModes.h"
Jiangning Liu1a486da2014-09-05 02:55:24 +000063#include "llvm/ADT/DepthFirstIterator.h"
64#include "llvm/ADT/SmallVector.h"
65#include "llvm/ADT/Statistic.h"
Chad Rosier7bb413e2014-10-31 19:02:38 +000066#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Jiangning Liu1a486da2014-09-05 02:55:24 +000067#include "llvm/CodeGen/MachineDominators.h"
68#include "llvm/CodeGen/MachineFunction.h"
69#include "llvm/CodeGen/MachineFunctionPass.h"
70#include "llvm/CodeGen/MachineInstrBuilder.h"
Pete Cooper037b7002015-04-22 18:05:13 +000071#include "llvm/CodeGen/MachineRegisterInfo.h"
Jiangning Liu1a486da2014-09-05 02:55:24 +000072#include "llvm/CodeGen/Passes.h"
73#include "llvm/Support/CommandLine.h"
74#include "llvm/Support/Debug.h"
75#include "llvm/Support/raw_ostream.h"
76#include "llvm/Target/TargetInstrInfo.h"
77#include "llvm/Target/TargetSubtargetInfo.h"
78#include <cstdlib>
79#include <tuple>
80
81using namespace llvm;
82
83#define DEBUG_TYPE "aarch64-condopt"
84
85STATISTIC(NumConditionsAdjusted, "Number of conditions adjusted");
86
87namespace {
88class AArch64ConditionOptimizer : public MachineFunctionPass {
89 const TargetInstrInfo *TII;
90 MachineDominatorTree *DomTree;
Pete Cooper037b7002015-04-22 18:05:13 +000091 const MachineRegisterInfo *MRI;
Jiangning Liu1a486da2014-09-05 02:55:24 +000092
93public:
94 // Stores immediate, compare instruction opcode and branch condition (in this
95 // order) of adjusted comparison.
Matthias Braunfa3872e2015-05-18 20:27:55 +000096 typedef std::tuple<int, unsigned, AArch64CC::CondCode> CmpInfo;
Jiangning Liu1a486da2014-09-05 02:55:24 +000097
98 static char ID;
99 AArch64ConditionOptimizer() : MachineFunctionPass(ID) {}
100 void getAnalysisUsage(AnalysisUsage &AU) const override;
101 MachineInstr *findSuitableCompare(MachineBasicBlock *MBB);
102 CmpInfo adjustCmp(MachineInstr *CmpMI, AArch64CC::CondCode Cmp);
103 void modifyCmp(MachineInstr *CmpMI, const CmpInfo &Info);
104 bool adjustTo(MachineInstr *CmpMI, AArch64CC::CondCode Cmp, MachineInstr *To,
105 int ToImm);
106 bool runOnMachineFunction(MachineFunction &MF) override;
107 const char *getPassName() const override {
108 return "AArch64 Condition Optimizer";
109 }
110};
111} // end anonymous namespace
112
113char AArch64ConditionOptimizer::ID = 0;
114
115namespace llvm {
116void initializeAArch64ConditionOptimizerPass(PassRegistry &);
117}
118
119INITIALIZE_PASS_BEGIN(AArch64ConditionOptimizer, "aarch64-condopt",
120 "AArch64 CondOpt Pass", false, false)
121INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
122INITIALIZE_PASS_END(AArch64ConditionOptimizer, "aarch64-condopt",
123 "AArch64 CondOpt Pass", false, false)
124
125FunctionPass *llvm::createAArch64ConditionOptimizerPass() {
126 return new AArch64ConditionOptimizer();
127}
128
129void AArch64ConditionOptimizer::getAnalysisUsage(AnalysisUsage &AU) const {
130 AU.addRequired<MachineDominatorTree>();
131 AU.addPreserved<MachineDominatorTree>();
132 MachineFunctionPass::getAnalysisUsage(AU);
133}
134
135// Finds compare instruction that corresponds to supported types of branching.
136// Returns the instruction or nullptr on failures or detecting unsupported
137// instructions.
138MachineInstr *AArch64ConditionOptimizer::findSuitableCompare(
139 MachineBasicBlock *MBB) {
140 MachineBasicBlock::iterator I = MBB->getFirstTerminator();
Chad Rosier7bb413e2014-10-31 19:02:38 +0000141 if (I == MBB->end())
Jiangning Liu1a486da2014-09-05 02:55:24 +0000142 return nullptr;
Jiangning Liu1a486da2014-09-05 02:55:24 +0000143
Chad Rosier7bb413e2014-10-31 19:02:38 +0000144 if (I->getOpcode() != AArch64::Bcc)
145 return nullptr;
Jiangning Liu1a486da2014-09-05 02:55:24 +0000146
147 // Now find the instruction controlling the terminator.
148 for (MachineBasicBlock::iterator B = MBB->begin(); I != B;) {
149 --I;
150 assert(!I->isTerminator() && "Spurious terminator");
151 switch (I->getOpcode()) {
152 // cmp is an alias for subs with a dead destination register.
153 case AArch64::SUBSWri:
154 case AArch64::SUBSXri:
155 // cmn is an alias for adds with a dead destination register.
156 case AArch64::ADDSWri:
Tim Northovercf739b82015-07-29 16:39:56 +0000157 case AArch64::ADDSXri: {
158 unsigned ShiftAmt = AArch64_AM::getShiftValue(I->getOperand(3).getImm());
Tim Northover17ae83a2015-07-28 22:42:32 +0000159 if (!I->getOperand(2).isImm()) {
160 DEBUG(dbgs() << "Immediate of cmp is symbolic, " << *I << '\n');
161 return nullptr;
Tim Northovercf739b82015-07-29 16:39:56 +0000162 } else if (I->getOperand(2).getImm() << ShiftAmt >= 0xfff) {
Tim Northover17ae83a2015-07-28 22:42:32 +0000163 DEBUG(dbgs() << "Immediate of cmp may be out of range, " << *I << '\n');
164 return nullptr;
165 } else if (!MRI->use_empty(I->getOperand(0).getReg())) {
166 DEBUG(dbgs() << "Destination of cmp is not dead, " << *I << '\n');
167 return nullptr;
168 }
169 return I;
Tim Northovercf739b82015-07-29 16:39:56 +0000170 }
Chad Rosiera675e552014-10-31 15:17:36 +0000171 // Prevent false positive case like:
172 // cmp w19, #0
173 // cinc w0, w19, gt
174 // ...
175 // fcmp d8, #0.0
176 // b.gt .LBB0_5
177 case AArch64::FCMPDri:
178 case AArch64::FCMPSri:
179 case AArch64::FCMPESri:
180 case AArch64::FCMPEDri:
181
Jiangning Liu1a486da2014-09-05 02:55:24 +0000182 case AArch64::SUBSWrr:
183 case AArch64::SUBSXrr:
184 case AArch64::ADDSWrr:
185 case AArch64::ADDSXrr:
186 case AArch64::FCMPSrr:
187 case AArch64::FCMPDrr:
188 case AArch64::FCMPESrr:
189 case AArch64::FCMPEDrr:
190 // Skip comparison instructions without immediate operands.
191 return nullptr;
192 }
193 }
194 DEBUG(dbgs() << "Flags not defined in BB#" << MBB->getNumber() << '\n');
195 return nullptr;
196}
197
198// Changes opcode adds <-> subs considering register operand width.
199static int getComplementOpc(int Opc) {
200 switch (Opc) {
201 case AArch64::ADDSWri: return AArch64::SUBSWri;
202 case AArch64::ADDSXri: return AArch64::SUBSXri;
203 case AArch64::SUBSWri: return AArch64::ADDSWri;
204 case AArch64::SUBSXri: return AArch64::ADDSXri;
205 default:
206 llvm_unreachable("Unexpected opcode");
207 }
208}
209
210// Changes form of comparison inclusive <-> exclusive.
211static AArch64CC::CondCode getAdjustedCmp(AArch64CC::CondCode Cmp) {
212 switch (Cmp) {
213 case AArch64CC::GT: return AArch64CC::GE;
214 case AArch64CC::GE: return AArch64CC::GT;
215 case AArch64CC::LT: return AArch64CC::LE;
216 case AArch64CC::LE: return AArch64CC::LT;
217 default:
218 llvm_unreachable("Unexpected condition code");
219 }
220}
221
222// Transforms GT -> GE, GE -> GT, LT -> LE, LE -> LT by updating comparison
223// operator and condition code.
224AArch64ConditionOptimizer::CmpInfo AArch64ConditionOptimizer::adjustCmp(
225 MachineInstr *CmpMI, AArch64CC::CondCode Cmp) {
Matthias Braunfa3872e2015-05-18 20:27:55 +0000226 unsigned Opc = CmpMI->getOpcode();
Jiangning Liu1a486da2014-09-05 02:55:24 +0000227
228 // CMN (compare with negative immediate) is an alias to ADDS (as
229 // "operand - negative" == "operand + positive")
230 bool Negative = (Opc == AArch64::ADDSWri || Opc == AArch64::ADDSXri);
231
232 int Correction = (Cmp == AArch64CC::GT) ? 1 : -1;
233 // Negate Correction value for comparison with negative immediate (CMN).
234 if (Negative) {
235 Correction = -Correction;
236 }
237
238 const int OldImm = (int)CmpMI->getOperand(2).getImm();
239 const int NewImm = std::abs(OldImm + Correction);
240
241 // Handle +0 -> -1 and -0 -> +1 (CMN with 0 immediate) transitions by
242 // adjusting compare instruction opcode.
243 if (OldImm == 0 && ((Negative && Correction == 1) ||
244 (!Negative && Correction == -1))) {
245 Opc = getComplementOpc(Opc);
246 }
247
248 return CmpInfo(NewImm, Opc, getAdjustedCmp(Cmp));
249}
250
251// Applies changes to comparison instruction suggested by adjustCmp().
252void AArch64ConditionOptimizer::modifyCmp(MachineInstr *CmpMI,
253 const CmpInfo &Info) {
254 int Imm;
Matthias Braunfa3872e2015-05-18 20:27:55 +0000255 unsigned Opc;
Jiangning Liu1a486da2014-09-05 02:55:24 +0000256 AArch64CC::CondCode Cmp;
257 std::tie(Imm, Opc, Cmp) = Info;
258
259 MachineBasicBlock *const MBB = CmpMI->getParent();
260
261 // Change immediate in comparison instruction (ADDS or SUBS).
262 BuildMI(*MBB, CmpMI, CmpMI->getDebugLoc(), TII->get(Opc))
263 .addOperand(CmpMI->getOperand(0))
264 .addOperand(CmpMI->getOperand(1))
265 .addImm(Imm)
266 .addOperand(CmpMI->getOperand(3));
267 CmpMI->eraseFromParent();
268
269 // The fact that this comparison was picked ensures that it's related to the
270 // first terminator instruction.
271 MachineInstr *BrMI = MBB->getFirstTerminator();
272
273 // Change condition in branch instruction.
274 BuildMI(*MBB, BrMI, BrMI->getDebugLoc(), TII->get(AArch64::Bcc))
275 .addImm(Cmp)
276 .addOperand(BrMI->getOperand(1));
277 BrMI->eraseFromParent();
278
279 MBB->updateTerminator();
280
281 ++NumConditionsAdjusted;
282}
283
284// Parse a condition code returned by AnalyzeBranch, and compute the CondCode
285// corresponding to TBB.
286// Returns true if parsing was successful, otherwise false is returned.
287static bool parseCond(ArrayRef<MachineOperand> Cond, AArch64CC::CondCode &CC) {
288 // A normal br.cond simply has the condition code.
289 if (Cond[0].getImm() != -1) {
290 assert(Cond.size() == 1 && "Unknown Cond array format");
291 CC = (AArch64CC::CondCode)(int)Cond[0].getImm();
292 return true;
293 }
294 return false;
295}
296
297// Adjusts one cmp instruction to another one if result of adjustment will allow
298// CSE. Returns true if compare instruction was changed, otherwise false is
299// returned.
300bool AArch64ConditionOptimizer::adjustTo(MachineInstr *CmpMI,
301 AArch64CC::CondCode Cmp, MachineInstr *To, int ToImm)
302{
303 CmpInfo Info = adjustCmp(CmpMI, Cmp);
304 if (std::get<0>(Info) == ToImm && std::get<1>(Info) == To->getOpcode()) {
305 modifyCmp(CmpMI, Info);
306 return true;
307 }
308 return false;
309}
310
311bool AArch64ConditionOptimizer::runOnMachineFunction(MachineFunction &MF) {
312 DEBUG(dbgs() << "********** AArch64 Conditional Compares **********\n"
313 << "********** Function: " << MF.getName() << '\n');
Eric Christopher6c901622015-01-28 03:51:33 +0000314 TII = MF.getSubtarget().getInstrInfo();
Jiangning Liu1a486da2014-09-05 02:55:24 +0000315 DomTree = &getAnalysis<MachineDominatorTree>();
Pete Cooper037b7002015-04-22 18:05:13 +0000316 MRI = &MF.getRegInfo();
Jiangning Liu1a486da2014-09-05 02:55:24 +0000317
318 bool Changed = false;
319
320 // Visit blocks in dominator tree pre-order. The pre-order enables multiple
321 // cmp-conversions from the same head block.
322 // Note that updateDomTree() modifies the children of the DomTree node
323 // currently being visited. The df_iterator supports that; it doesn't look at
324 // child_begin() / child_end() until after a node has been visited.
325 for (MachineDomTreeNode *I : depth_first(DomTree)) {
326 MachineBasicBlock *HBB = I->getBlock();
327
328 SmallVector<MachineOperand, 4> HeadCond;
329 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
330 if (TII->AnalyzeBranch(*HBB, TBB, FBB, HeadCond)) {
331 continue;
332 }
333
334 // Equivalence check is to skip loops.
335 if (!TBB || TBB == HBB) {
336 continue;
337 }
338
339 SmallVector<MachineOperand, 4> TrueCond;
340 MachineBasicBlock *TBB_TBB = nullptr, *TBB_FBB = nullptr;
341 if (TII->AnalyzeBranch(*TBB, TBB_TBB, TBB_FBB, TrueCond)) {
342 continue;
343 }
344
345 MachineInstr *HeadCmpMI = findSuitableCompare(HBB);
346 if (!HeadCmpMI) {
347 continue;
348 }
349
350 MachineInstr *TrueCmpMI = findSuitableCompare(TBB);
351 if (!TrueCmpMI) {
352 continue;
353 }
354
355 AArch64CC::CondCode HeadCmp;
356 if (HeadCond.empty() || !parseCond(HeadCond, HeadCmp)) {
357 continue;
358 }
359
360 AArch64CC::CondCode TrueCmp;
361 if (TrueCond.empty() || !parseCond(TrueCond, TrueCmp)) {
362 continue;
363 }
364
365 const int HeadImm = (int)HeadCmpMI->getOperand(2).getImm();
366 const int TrueImm = (int)TrueCmpMI->getOperand(2).getImm();
367
368 DEBUG(dbgs() << "Head branch:\n");
369 DEBUG(dbgs() << "\tcondition: "
370 << AArch64CC::getCondCodeName(HeadCmp) << '\n');
371 DEBUG(dbgs() << "\timmediate: " << HeadImm << '\n');
372
373 DEBUG(dbgs() << "True branch:\n");
374 DEBUG(dbgs() << "\tcondition: "
375 << AArch64CC::getCondCodeName(TrueCmp) << '\n');
376 DEBUG(dbgs() << "\timmediate: " << TrueImm << '\n');
377
378 if (((HeadCmp == AArch64CC::GT && TrueCmp == AArch64CC::LT) ||
379 (HeadCmp == AArch64CC::LT && TrueCmp == AArch64CC::GT)) &&
380 std::abs(TrueImm - HeadImm) == 2) {
381 // This branch transforms machine instructions that correspond to
382 //
383 // 1) (a > {TrueImm} && ...) || (a < {HeadImm} && ...)
384 // 2) (a < {TrueImm} && ...) || (a > {HeadImm} && ...)
385 //
386 // into
387 //
388 // 1) (a >= {NewImm} && ...) || (a <= {NewImm} && ...)
389 // 2) (a <= {NewImm} && ...) || (a >= {NewImm} && ...)
390
391 CmpInfo HeadCmpInfo = adjustCmp(HeadCmpMI, HeadCmp);
392 CmpInfo TrueCmpInfo = adjustCmp(TrueCmpMI, TrueCmp);
393 if (std::get<0>(HeadCmpInfo) == std::get<0>(TrueCmpInfo) &&
394 std::get<1>(HeadCmpInfo) == std::get<1>(TrueCmpInfo)) {
395 modifyCmp(HeadCmpMI, HeadCmpInfo);
396 modifyCmp(TrueCmpMI, TrueCmpInfo);
397 Changed = true;
398 }
399 } else if (((HeadCmp == AArch64CC::GT && TrueCmp == AArch64CC::GT) ||
400 (HeadCmp == AArch64CC::LT && TrueCmp == AArch64CC::LT)) &&
401 std::abs(TrueImm - HeadImm) == 1) {
402 // This branch transforms machine instructions that correspond to
403 //
404 // 1) (a > {TrueImm} && ...) || (a > {HeadImm} && ...)
405 // 2) (a < {TrueImm} && ...) || (a < {HeadImm} && ...)
406 //
407 // into
408 //
409 // 1) (a <= {NewImm} && ...) || (a > {NewImm} && ...)
410 // 2) (a < {NewImm} && ...) || (a >= {NewImm} && ...)
411
412 // GT -> GE transformation increases immediate value, so picking the
413 // smaller one; LT -> LE decreases immediate value so invert the choice.
414 bool adjustHeadCond = (HeadImm < TrueImm);
415 if (HeadCmp == AArch64CC::LT) {
416 adjustHeadCond = !adjustHeadCond;
417 }
418
419 if (adjustHeadCond) {
420 Changed |= adjustTo(HeadCmpMI, HeadCmp, TrueCmpMI, TrueImm);
421 } else {
422 Changed |= adjustTo(TrueCmpMI, TrueCmp, HeadCmpMI, HeadImm);
423 }
424 }
425 // Other transformation cases almost never occur due to generation of < or >
426 // comparisons instead of <= and >=.
427 }
428
429 return Changed;
430}