AArch64: be careful of large immediates when optimising cmps.
[oota-llvm.git] / lib / Target / AArch64 / AArch64ConditionOptimizer.cpp
1 //=- 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"
62 #include "llvm/ADT/DepthFirstIterator.h"
63 #include "llvm/ADT/SmallVector.h"
64 #include "llvm/ADT/Statistic.h"
65 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
66 #include "llvm/CodeGen/MachineDominators.h"
67 #include "llvm/CodeGen/MachineFunction.h"
68 #include "llvm/CodeGen/MachineFunctionPass.h"
69 #include "llvm/CodeGen/MachineInstrBuilder.h"
70 #include "llvm/CodeGen/MachineRegisterInfo.h"
71 #include "llvm/CodeGen/Passes.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/raw_ostream.h"
75 #include "llvm/Target/TargetInstrInfo.h"
76 #include "llvm/Target/TargetSubtargetInfo.h"
77 #include <cstdlib>
78 #include <tuple>
79
80 using namespace llvm;
81
82 #define DEBUG_TYPE "aarch64-condopt"
83
84 STATISTIC(NumConditionsAdjusted, "Number of conditions adjusted");
85
86 namespace {
87 class AArch64ConditionOptimizer : public MachineFunctionPass {
88   const TargetInstrInfo *TII;
89   MachineDominatorTree *DomTree;
90   const MachineRegisterInfo *MRI;
91
92 public:
93   // Stores immediate, compare instruction opcode and branch condition (in this
94   // order) of adjusted comparison.
95   typedef std::tuple<int, unsigned, AArch64CC::CondCode> CmpInfo;
96
97   static char ID;
98   AArch64ConditionOptimizer() : MachineFunctionPass(ID) {}
99   void getAnalysisUsage(AnalysisUsage &AU) const override;
100   MachineInstr *findSuitableCompare(MachineBasicBlock *MBB);
101   CmpInfo adjustCmp(MachineInstr *CmpMI, AArch64CC::CondCode Cmp);
102   void modifyCmp(MachineInstr *CmpMI, const CmpInfo &Info);
103   bool adjustTo(MachineInstr *CmpMI, AArch64CC::CondCode Cmp, MachineInstr *To,
104                 int ToImm);
105   bool runOnMachineFunction(MachineFunction &MF) override;
106   const char *getPassName() const override {
107     return "AArch64 Condition Optimizer";
108   }
109 };
110 } // end anonymous namespace
111
112 char AArch64ConditionOptimizer::ID = 0;
113
114 namespace llvm {
115 void initializeAArch64ConditionOptimizerPass(PassRegistry &);
116 }
117
118 INITIALIZE_PASS_BEGIN(AArch64ConditionOptimizer, "aarch64-condopt",
119                       "AArch64 CondOpt Pass", false, false)
120 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
121 INITIALIZE_PASS_END(AArch64ConditionOptimizer, "aarch64-condopt",
122                     "AArch64 CondOpt Pass", false, false)
123
124 FunctionPass *llvm::createAArch64ConditionOptimizerPass() {
125   return new AArch64ConditionOptimizer();
126 }
127
128 void AArch64ConditionOptimizer::getAnalysisUsage(AnalysisUsage &AU) const {
129   AU.addRequired<MachineDominatorTree>();
130   AU.addPreserved<MachineDominatorTree>();
131   MachineFunctionPass::getAnalysisUsage(AU);
132 }
133
134 // Finds compare instruction that corresponds to supported types of branching.
135 // Returns the instruction or nullptr on failures or detecting unsupported
136 // instructions.
137 MachineInstr *AArch64ConditionOptimizer::findSuitableCompare(
138     MachineBasicBlock *MBB) {
139   MachineBasicBlock::iterator I = MBB->getFirstTerminator();
140   if (I == MBB->end())
141     return nullptr;
142
143   if (I->getOpcode() != AArch64::Bcc)
144     return nullptr;
145
146   // Now find the instruction controlling the terminator.
147   for (MachineBasicBlock::iterator B = MBB->begin(); I != B;) {
148     --I;
149     assert(!I->isTerminator() && "Spurious terminator");
150     switch (I->getOpcode()) {
151     // cmp is an alias for subs with a dead destination register.
152     case AArch64::SUBSWri:
153     case AArch64::SUBSXri:
154     // cmn is an alias for adds with a dead destination register.
155     case AArch64::ADDSWri:
156     case AArch64::ADDSXri:
157       if (!I->getOperand(2).isImm()) {
158         DEBUG(dbgs() << "Immediate of cmp is symbolic, " << *I << '\n');
159         return nullptr;
160       } else if (I->getOperand(2).getImm() << I->getOperand(3).getImm() >=
161                  0xfff) {
162         DEBUG(dbgs() << "Immediate of cmp may be out of range, " << *I << '\n');
163         return nullptr;
164       } else if (!MRI->use_empty(I->getOperand(0).getReg())) {
165         DEBUG(dbgs() << "Destination of cmp is not dead, " << *I << '\n');
166         return nullptr;
167       }
168       return I;
169
170     // Prevent false positive case like:
171     // cmp      w19, #0
172     // cinc     w0, w19, gt
173     // ...
174     // fcmp     d8, #0.0
175     // b.gt     .LBB0_5
176     case AArch64::FCMPDri:
177     case AArch64::FCMPSri:
178     case AArch64::FCMPESri:
179     case AArch64::FCMPEDri:
180
181     case AArch64::SUBSWrr:
182     case AArch64::SUBSXrr:
183     case AArch64::ADDSWrr:
184     case AArch64::ADDSXrr:
185     case AArch64::FCMPSrr:
186     case AArch64::FCMPDrr:
187     case AArch64::FCMPESrr:
188     case AArch64::FCMPEDrr:
189       // Skip comparison instructions without immediate operands.
190       return nullptr;
191     }
192   }
193   DEBUG(dbgs() << "Flags not defined in BB#" << MBB->getNumber() << '\n');
194   return nullptr;
195 }
196
197 // Changes opcode adds <-> subs considering register operand width.
198 static int getComplementOpc(int Opc) {
199   switch (Opc) {
200   case AArch64::ADDSWri: return AArch64::SUBSWri;
201   case AArch64::ADDSXri: return AArch64::SUBSXri;
202   case AArch64::SUBSWri: return AArch64::ADDSWri;
203   case AArch64::SUBSXri: return AArch64::ADDSXri;
204   default:
205     llvm_unreachable("Unexpected opcode");
206   }
207 }
208
209 // Changes form of comparison inclusive <-> exclusive.
210 static AArch64CC::CondCode getAdjustedCmp(AArch64CC::CondCode Cmp) {
211   switch (Cmp) {
212   case AArch64CC::GT: return AArch64CC::GE;
213   case AArch64CC::GE: return AArch64CC::GT;
214   case AArch64CC::LT: return AArch64CC::LE;
215   case AArch64CC::LE: return AArch64CC::LT;
216   default:
217     llvm_unreachable("Unexpected condition code");
218   }
219 }
220
221 // Transforms GT -> GE, GE -> GT, LT -> LE, LE -> LT by updating comparison
222 // operator and condition code.
223 AArch64ConditionOptimizer::CmpInfo AArch64ConditionOptimizer::adjustCmp(
224     MachineInstr *CmpMI, AArch64CC::CondCode Cmp) {
225   unsigned Opc = CmpMI->getOpcode();
226
227   // CMN (compare with negative immediate) is an alias to ADDS (as
228   // "operand - negative" == "operand + positive")
229   bool Negative = (Opc == AArch64::ADDSWri || Opc == AArch64::ADDSXri);
230
231   int Correction = (Cmp == AArch64CC::GT) ? 1 : -1;
232   // Negate Correction value for comparison with negative immediate (CMN).
233   if (Negative) {
234     Correction = -Correction;
235   }
236
237   const int OldImm = (int)CmpMI->getOperand(2).getImm();
238   const int NewImm = std::abs(OldImm + Correction);
239
240   // Handle +0 -> -1 and -0 -> +1 (CMN with 0 immediate) transitions by
241   // adjusting compare instruction opcode.
242   if (OldImm == 0 && ((Negative && Correction == 1) ||
243                       (!Negative && Correction == -1))) {
244     Opc = getComplementOpc(Opc);
245   }
246
247   return CmpInfo(NewImm, Opc, getAdjustedCmp(Cmp));
248 }
249
250 // Applies changes to comparison instruction suggested by adjustCmp().
251 void AArch64ConditionOptimizer::modifyCmp(MachineInstr *CmpMI,
252     const CmpInfo &Info) {
253   int Imm;
254   unsigned Opc;
255   AArch64CC::CondCode Cmp;
256   std::tie(Imm, Opc, Cmp) = Info;
257
258   MachineBasicBlock *const MBB = CmpMI->getParent();
259
260   // Change immediate in comparison instruction (ADDS or SUBS).
261   BuildMI(*MBB, CmpMI, CmpMI->getDebugLoc(), TII->get(Opc))
262       .addOperand(CmpMI->getOperand(0))
263       .addOperand(CmpMI->getOperand(1))
264       .addImm(Imm)
265       .addOperand(CmpMI->getOperand(3));
266   CmpMI->eraseFromParent();
267
268   // The fact that this comparison was picked ensures that it's related to the
269   // first terminator instruction.
270   MachineInstr *BrMI = MBB->getFirstTerminator();
271
272   // Change condition in branch instruction.
273   BuildMI(*MBB, BrMI, BrMI->getDebugLoc(), TII->get(AArch64::Bcc))
274       .addImm(Cmp)
275       .addOperand(BrMI->getOperand(1));
276   BrMI->eraseFromParent();
277
278   MBB->updateTerminator();
279
280   ++NumConditionsAdjusted;
281 }
282
283 // Parse a condition code returned by AnalyzeBranch, and compute the CondCode
284 // corresponding to TBB.
285 // Returns true if parsing was successful, otherwise false is returned.
286 static bool parseCond(ArrayRef<MachineOperand> Cond, AArch64CC::CondCode &CC) {
287   // A normal br.cond simply has the condition code.
288   if (Cond[0].getImm() != -1) {
289     assert(Cond.size() == 1 && "Unknown Cond array format");
290     CC = (AArch64CC::CondCode)(int)Cond[0].getImm();
291     return true;
292   }
293   return false;
294 }
295
296 // Adjusts one cmp instruction to another one if result of adjustment will allow
297 // CSE.  Returns true if compare instruction was changed, otherwise false is
298 // returned.
299 bool AArch64ConditionOptimizer::adjustTo(MachineInstr *CmpMI,
300   AArch64CC::CondCode Cmp, MachineInstr *To, int ToImm)
301 {
302   CmpInfo Info = adjustCmp(CmpMI, Cmp);
303   if (std::get<0>(Info) == ToImm && std::get<1>(Info) == To->getOpcode()) {
304     modifyCmp(CmpMI, Info);
305     return true;
306   }
307   return false;
308 }
309
310 bool AArch64ConditionOptimizer::runOnMachineFunction(MachineFunction &MF) {
311   DEBUG(dbgs() << "********** AArch64 Conditional Compares **********\n"
312                << "********** Function: " << MF.getName() << '\n');
313   TII = MF.getSubtarget().getInstrInfo();
314   DomTree = &getAnalysis<MachineDominatorTree>();
315   MRI = &MF.getRegInfo();
316
317   bool Changed = false;
318
319   // Visit blocks in dominator tree pre-order. The pre-order enables multiple
320   // cmp-conversions from the same head block.
321   // Note that updateDomTree() modifies the children of the DomTree node
322   // currently being visited. The df_iterator supports that; it doesn't look at
323   // child_begin() / child_end() until after a node has been visited.
324   for (MachineDomTreeNode *I : depth_first(DomTree)) {
325     MachineBasicBlock *HBB = I->getBlock();
326
327     SmallVector<MachineOperand, 4> HeadCond;
328     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
329     if (TII->AnalyzeBranch(*HBB, TBB, FBB, HeadCond)) {
330       continue;
331     }
332
333     // Equivalence check is to skip loops.
334     if (!TBB || TBB == HBB) {
335       continue;
336     }
337
338     SmallVector<MachineOperand, 4> TrueCond;
339     MachineBasicBlock *TBB_TBB = nullptr, *TBB_FBB = nullptr;
340     if (TII->AnalyzeBranch(*TBB, TBB_TBB, TBB_FBB, TrueCond)) {
341       continue;
342     }
343
344     MachineInstr *HeadCmpMI = findSuitableCompare(HBB);
345     if (!HeadCmpMI) {
346       continue;
347     }
348
349     MachineInstr *TrueCmpMI = findSuitableCompare(TBB);
350     if (!TrueCmpMI) {
351       continue;
352     }
353
354     AArch64CC::CondCode HeadCmp;
355     if (HeadCond.empty() || !parseCond(HeadCond, HeadCmp)) {
356       continue;
357     }
358
359     AArch64CC::CondCode TrueCmp;
360     if (TrueCond.empty() || !parseCond(TrueCond, TrueCmp)) {
361       continue;
362     }
363
364     const int HeadImm = (int)HeadCmpMI->getOperand(2).getImm();
365     const int TrueImm = (int)TrueCmpMI->getOperand(2).getImm();
366
367     DEBUG(dbgs() << "Head branch:\n");
368     DEBUG(dbgs() << "\tcondition: "
369           << AArch64CC::getCondCodeName(HeadCmp) << '\n');
370     DEBUG(dbgs() << "\timmediate: " << HeadImm << '\n');
371
372     DEBUG(dbgs() << "True branch:\n");
373     DEBUG(dbgs() << "\tcondition: "
374           << AArch64CC::getCondCodeName(TrueCmp) << '\n');
375     DEBUG(dbgs() << "\timmediate: " << TrueImm << '\n');
376
377     if (((HeadCmp == AArch64CC::GT && TrueCmp == AArch64CC::LT) ||
378          (HeadCmp == AArch64CC::LT && TrueCmp == AArch64CC::GT)) &&
379         std::abs(TrueImm - HeadImm) == 2) {
380       // This branch transforms machine instructions that correspond to
381       //
382       // 1) (a > {TrueImm} && ...) || (a < {HeadImm} && ...)
383       // 2) (a < {TrueImm} && ...) || (a > {HeadImm} && ...)
384       //
385       // into
386       //
387       // 1) (a >= {NewImm} && ...) || (a <= {NewImm} && ...)
388       // 2) (a <= {NewImm} && ...) || (a >= {NewImm} && ...)
389
390       CmpInfo HeadCmpInfo = adjustCmp(HeadCmpMI, HeadCmp);
391       CmpInfo TrueCmpInfo = adjustCmp(TrueCmpMI, TrueCmp);
392       if (std::get<0>(HeadCmpInfo) == std::get<0>(TrueCmpInfo) &&
393           std::get<1>(HeadCmpInfo) == std::get<1>(TrueCmpInfo)) {
394         modifyCmp(HeadCmpMI, HeadCmpInfo);
395         modifyCmp(TrueCmpMI, TrueCmpInfo);
396         Changed = true;
397       }
398     } else if (((HeadCmp == AArch64CC::GT && TrueCmp == AArch64CC::GT) ||
399                 (HeadCmp == AArch64CC::LT && TrueCmp == AArch64CC::LT)) &&
400                 std::abs(TrueImm - HeadImm) == 1) {
401       // This branch transforms machine instructions that correspond to
402       //
403       // 1) (a > {TrueImm} && ...) || (a > {HeadImm} && ...)
404       // 2) (a < {TrueImm} && ...) || (a < {HeadImm} && ...)
405       //
406       // into
407       //
408       // 1) (a <= {NewImm} && ...) || (a >  {NewImm} && ...)
409       // 2) (a <  {NewImm} && ...) || (a >= {NewImm} && ...)
410
411       // GT -> GE transformation increases immediate value, so picking the
412       // smaller one; LT -> LE decreases immediate value so invert the choice.
413       bool adjustHeadCond = (HeadImm < TrueImm);
414       if (HeadCmp == AArch64CC::LT) {
415           adjustHeadCond = !adjustHeadCond;
416       }
417
418       if (adjustHeadCond) {
419         Changed |= adjustTo(HeadCmpMI, HeadCmp, TrueCmpMI, TrueImm);
420       } else {
421         Changed |= adjustTo(TrueCmpMI, TrueCmp, HeadCmpMI, HeadImm);
422       }
423     }
424     // Other transformation cases almost never occur due to generation of < or >
425     // comparisons instead of <= and >=.
426   }
427
428   return Changed;
429 }