LLVM API Documentation

AArch64ConditionOptimizer.cpp
Go to the documentation of this file.
00001 //=- AArch64ConditionOptimizer.cpp - Remove useless comparisons for AArch64 -=//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass tries to make consecutive compares of values use same operands to
00011 // allow CSE pass to remove duplicated instructions.  For this it analyzes
00012 // branches and adjusts comparisons with immediate values by converting:
00013 //  * GE -> GT
00014 //  * GT -> GE
00015 //  * LT -> LE
00016 //  * LE -> LT
00017 // and adjusting immediate values appropriately.  It basically corrects two
00018 // immediate values towards each other to make them equal.
00019 //
00020 // Consider the following example in C:
00021 //
00022 //   if ((a < 5 && ...) || (a > 5 && ...)) {
00023 //        ~~~~~             ~~~~~
00024 //          ^                 ^
00025 //          x                 y
00026 //
00027 // Here both "x" and "y" expressions compare "a" with "5".  When "x" evaluates
00028 // to "false", "y" can just check flags set by the first comparison.  As a
00029 // result of the canonicalization employed by
00030 // SelectionDAGBuilder::visitSwitchCase, DAGCombine, and other target-specific
00031 // code, assembly ends up in the form that is not CSE friendly:
00032 //
00033 //     ...
00034 //     cmp      w8, #4
00035 //     b.gt     .LBB0_3
00036 //     ...
00037 //   .LBB0_3:
00038 //     cmp      w8, #6
00039 //     b.lt     .LBB0_6
00040 //     ...
00041 //
00042 // Same assembly after the pass:
00043 //
00044 //     ...
00045 //     cmp      w8, #5
00046 //     b.ge     .LBB0_3
00047 //     ...
00048 //   .LBB0_3:
00049 //     cmp      w8, #5     // <-- CSE pass removes this instruction
00050 //     b.le     .LBB0_6
00051 //     ...
00052 //
00053 // Currently only SUBS and ADDS followed by b.?? are supported.
00054 //
00055 // TODO: maybe handle TBNZ/TBZ the same way as CMP when used instead for "a < 0"
00056 // TODO: handle other conditional instructions (e.g. CSET)
00057 // TODO: allow second branching to be anything if it doesn't require adjusting
00058 //
00059 //===----------------------------------------------------------------------===//
00060 
00061 #include "AArch64.h"
00062 #include "llvm/ADT/DepthFirstIterator.h"
00063 #include "llvm/ADT/SmallVector.h"
00064 #include "llvm/ADT/Statistic.h"
00065 #include "llvm/CodeGen/MachineDominators.h"
00066 #include "llvm/CodeGen/MachineFunction.h"
00067 #include "llvm/CodeGen/MachineFunctionPass.h"
00068 #include "llvm/CodeGen/MachineInstrBuilder.h"
00069 #include "llvm/CodeGen/Passes.h"
00070 #include "llvm/Support/CommandLine.h"
00071 #include "llvm/Support/Debug.h"
00072 #include "llvm/Support/raw_ostream.h"
00073 #include "llvm/Target/TargetInstrInfo.h"
00074 #include "llvm/Target/TargetSubtargetInfo.h"
00075 #include <cstdlib>
00076 #include <tuple>
00077 
00078 using namespace llvm;
00079 
00080 #define DEBUG_TYPE "aarch64-condopt"
00081 
00082 STATISTIC(NumConditionsAdjusted, "Number of conditions adjusted");
00083 
00084 namespace {
00085 class AArch64ConditionOptimizer : public MachineFunctionPass {
00086   const TargetInstrInfo *TII;
00087   MachineDominatorTree *DomTree;
00088 
00089 public:
00090   // Stores immediate, compare instruction opcode and branch condition (in this
00091   // order) of adjusted comparison.
00092   typedef std::tuple<int, int, AArch64CC::CondCode> CmpInfo;
00093 
00094   static char ID;
00095   AArch64ConditionOptimizer() : MachineFunctionPass(ID) {}
00096   void getAnalysisUsage(AnalysisUsage &AU) const override;
00097   MachineInstr *findSuitableCompare(MachineBasicBlock *MBB);
00098   CmpInfo adjustCmp(MachineInstr *CmpMI, AArch64CC::CondCode Cmp);
00099   void modifyCmp(MachineInstr *CmpMI, const CmpInfo &Info);
00100   bool adjustTo(MachineInstr *CmpMI, AArch64CC::CondCode Cmp, MachineInstr *To,
00101                 int ToImm);
00102   bool runOnMachineFunction(MachineFunction &MF) override;
00103   const char *getPassName() const override {
00104     return "AArch64 Condition Optimizer";
00105   }
00106 };
00107 } // end anonymous namespace
00108 
00109 char AArch64ConditionOptimizer::ID = 0;
00110 
00111 namespace llvm {
00112 void initializeAArch64ConditionOptimizerPass(PassRegistry &);
00113 }
00114 
00115 INITIALIZE_PASS_BEGIN(AArch64ConditionOptimizer, "aarch64-condopt",
00116                       "AArch64 CondOpt Pass", false, false)
00117 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
00118 INITIALIZE_PASS_END(AArch64ConditionOptimizer, "aarch64-condopt",
00119                     "AArch64 CondOpt Pass", false, false)
00120 
00121 FunctionPass *llvm::createAArch64ConditionOptimizerPass() {
00122   return new AArch64ConditionOptimizer();
00123 }
00124 
00125 void AArch64ConditionOptimizer::getAnalysisUsage(AnalysisUsage &AU) const {
00126   AU.addRequired<MachineDominatorTree>();
00127   AU.addPreserved<MachineDominatorTree>();
00128   MachineFunctionPass::getAnalysisUsage(AU);
00129 }
00130 
00131 // Finds compare instruction that corresponds to supported types of branching.
00132 // Returns the instruction or nullptr on failures or detecting unsupported
00133 // instructions.
00134 MachineInstr *AArch64ConditionOptimizer::findSuitableCompare(
00135     MachineBasicBlock *MBB) {
00136   MachineBasicBlock::iterator I = MBB->getFirstTerminator();
00137   if (I == MBB->end()) {
00138     return nullptr;
00139   }
00140 
00141   if (I->getOpcode() != AArch64::Bcc) {
00142       return nullptr;
00143   }
00144 
00145   // Now find the instruction controlling the terminator.
00146   for (MachineBasicBlock::iterator B = MBB->begin(); I != B;) {
00147     --I;
00148     assert(!I->isTerminator() && "Spurious terminator");
00149     switch (I->getOpcode()) {
00150     // cmp is an alias for subs with a dead destination register.
00151     case AArch64::SUBSWri:
00152     case AArch64::SUBSXri:
00153     // cmn is an alias for adds with a dead destination register.
00154     case AArch64::ADDSWri:
00155     case AArch64::ADDSXri:
00156       return I;
00157 
00158     case AArch64::SUBSWrr:
00159     case AArch64::SUBSXrr:
00160     case AArch64::ADDSWrr:
00161     case AArch64::ADDSXrr:
00162     case AArch64::FCMPSrr:
00163     case AArch64::FCMPDrr:
00164     case AArch64::FCMPESrr:
00165     case AArch64::FCMPEDrr:
00166       // Skip comparison instructions without immediate operands.
00167       return nullptr;
00168     }
00169   }
00170   DEBUG(dbgs() << "Flags not defined in BB#" << MBB->getNumber() << '\n');
00171   return nullptr;
00172 }
00173 
00174 // Changes opcode adds <-> subs considering register operand width.
00175 static int getComplementOpc(int Opc) {
00176   switch (Opc) {
00177   case AArch64::ADDSWri: return AArch64::SUBSWri;
00178   case AArch64::ADDSXri: return AArch64::SUBSXri;
00179   case AArch64::SUBSWri: return AArch64::ADDSWri;
00180   case AArch64::SUBSXri: return AArch64::ADDSXri;
00181   default:
00182     llvm_unreachable("Unexpected opcode");
00183   }
00184 }
00185 
00186 // Changes form of comparison inclusive <-> exclusive.
00187 static AArch64CC::CondCode getAdjustedCmp(AArch64CC::CondCode Cmp) {
00188   switch (Cmp) {
00189   case AArch64CC::GT: return AArch64CC::GE;
00190   case AArch64CC::GE: return AArch64CC::GT;
00191   case AArch64CC::LT: return AArch64CC::LE;
00192   case AArch64CC::LE: return AArch64CC::LT;
00193   default:
00194     llvm_unreachable("Unexpected condition code");
00195   }
00196 }
00197 
00198 // Transforms GT -> GE, GE -> GT, LT -> LE, LE -> LT by updating comparison
00199 // operator and condition code.
00200 AArch64ConditionOptimizer::CmpInfo AArch64ConditionOptimizer::adjustCmp(
00201     MachineInstr *CmpMI, AArch64CC::CondCode Cmp) {
00202   int Opc = CmpMI->getOpcode();
00203 
00204   // CMN (compare with negative immediate) is an alias to ADDS (as
00205   // "operand - negative" == "operand + positive")
00206   bool Negative = (Opc == AArch64::ADDSWri || Opc == AArch64::ADDSXri);
00207 
00208   int Correction = (Cmp == AArch64CC::GT) ? 1 : -1;
00209   // Negate Correction value for comparison with negative immediate (CMN).
00210   if (Negative) {
00211     Correction = -Correction;
00212   }
00213 
00214   const int OldImm = (int)CmpMI->getOperand(2).getImm();
00215   const int NewImm = std::abs(OldImm + Correction);
00216 
00217   // Handle +0 -> -1 and -0 -> +1 (CMN with 0 immediate) transitions by
00218   // adjusting compare instruction opcode.
00219   if (OldImm == 0 && ((Negative && Correction == 1) ||
00220                       (!Negative && Correction == -1))) {
00221     Opc = getComplementOpc(Opc);
00222   }
00223 
00224   return CmpInfo(NewImm, Opc, getAdjustedCmp(Cmp));
00225 }
00226 
00227 // Applies changes to comparison instruction suggested by adjustCmp().
00228 void AArch64ConditionOptimizer::modifyCmp(MachineInstr *CmpMI,
00229     const CmpInfo &Info) {
00230   int Imm;
00231   int Opc;
00232   AArch64CC::CondCode Cmp;
00233   std::tie(Imm, Opc, Cmp) = Info;
00234 
00235   MachineBasicBlock *const MBB = CmpMI->getParent();
00236 
00237   // Change immediate in comparison instruction (ADDS or SUBS).
00238   BuildMI(*MBB, CmpMI, CmpMI->getDebugLoc(), TII->get(Opc))
00239       .addOperand(CmpMI->getOperand(0))
00240       .addOperand(CmpMI->getOperand(1))
00241       .addImm(Imm)
00242       .addOperand(CmpMI->getOperand(3));
00243   CmpMI->eraseFromParent();
00244 
00245   // The fact that this comparison was picked ensures that it's related to the
00246   // first terminator instruction.
00247   MachineInstr *BrMI = MBB->getFirstTerminator();
00248 
00249   // Change condition in branch instruction.
00250   BuildMI(*MBB, BrMI, BrMI->getDebugLoc(), TII->get(AArch64::Bcc))
00251       .addImm(Cmp)
00252       .addOperand(BrMI->getOperand(1));
00253   BrMI->eraseFromParent();
00254 
00255   MBB->updateTerminator();
00256 
00257   ++NumConditionsAdjusted;
00258 }
00259 
00260 // Parse a condition code returned by AnalyzeBranch, and compute the CondCode
00261 // corresponding to TBB.
00262 // Returns true if parsing was successful, otherwise false is returned.
00263 static bool parseCond(ArrayRef<MachineOperand> Cond, AArch64CC::CondCode &CC) {
00264   // A normal br.cond simply has the condition code.
00265   if (Cond[0].getImm() != -1) {
00266     assert(Cond.size() == 1 && "Unknown Cond array format");
00267     CC = (AArch64CC::CondCode)(int)Cond[0].getImm();
00268     return true;
00269   }
00270   return false;
00271 }
00272 
00273 // Adjusts one cmp instruction to another one if result of adjustment will allow
00274 // CSE.  Returns true if compare instruction was changed, otherwise false is
00275 // returned.
00276 bool AArch64ConditionOptimizer::adjustTo(MachineInstr *CmpMI,
00277   AArch64CC::CondCode Cmp, MachineInstr *To, int ToImm)
00278 {
00279   CmpInfo Info = adjustCmp(CmpMI, Cmp);
00280   if (std::get<0>(Info) == ToImm && std::get<1>(Info) == To->getOpcode()) {
00281     modifyCmp(CmpMI, Info);
00282     return true;
00283   }
00284   return false;
00285 }
00286 
00287 bool AArch64ConditionOptimizer::runOnMachineFunction(MachineFunction &MF) {
00288   DEBUG(dbgs() << "********** AArch64 Conditional Compares **********\n"
00289                << "********** Function: " << MF.getName() << '\n');
00290   TII = MF.getTarget().getSubtargetImpl()->getInstrInfo();
00291   DomTree = &getAnalysis<MachineDominatorTree>();
00292 
00293   bool Changed = false;
00294 
00295   // Visit blocks in dominator tree pre-order. The pre-order enables multiple
00296   // cmp-conversions from the same head block.
00297   // Note that updateDomTree() modifies the children of the DomTree node
00298   // currently being visited. The df_iterator supports that; it doesn't look at
00299   // child_begin() / child_end() until after a node has been visited.
00300   for (MachineDomTreeNode *I : depth_first(DomTree)) {
00301     MachineBasicBlock *HBB = I->getBlock();
00302 
00303     SmallVector<MachineOperand, 4> HeadCond;
00304     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
00305     if (TII->AnalyzeBranch(*HBB, TBB, FBB, HeadCond)) {
00306       continue;
00307     }
00308 
00309     // Equivalence check is to skip loops.
00310     if (!TBB || TBB == HBB) {
00311       continue;
00312     }
00313 
00314     SmallVector<MachineOperand, 4> TrueCond;
00315     MachineBasicBlock *TBB_TBB = nullptr, *TBB_FBB = nullptr;
00316     if (TII->AnalyzeBranch(*TBB, TBB_TBB, TBB_FBB, TrueCond)) {
00317       continue;
00318     }
00319 
00320     MachineInstr *HeadCmpMI = findSuitableCompare(HBB);
00321     if (!HeadCmpMI) {
00322       continue;
00323     }
00324 
00325     MachineInstr *TrueCmpMI = findSuitableCompare(TBB);
00326     if (!TrueCmpMI) {
00327       continue;
00328     }
00329 
00330     AArch64CC::CondCode HeadCmp;
00331     if (HeadCond.empty() || !parseCond(HeadCond, HeadCmp)) {
00332       continue;
00333     }
00334 
00335     AArch64CC::CondCode TrueCmp;
00336     if (TrueCond.empty() || !parseCond(TrueCond, TrueCmp)) {
00337       continue;
00338     }
00339 
00340     const int HeadImm = (int)HeadCmpMI->getOperand(2).getImm();
00341     const int TrueImm = (int)TrueCmpMI->getOperand(2).getImm();
00342 
00343     DEBUG(dbgs() << "Head branch:\n");
00344     DEBUG(dbgs() << "\tcondition: "
00345           << AArch64CC::getCondCodeName(HeadCmp) << '\n');
00346     DEBUG(dbgs() << "\timmediate: " << HeadImm << '\n');
00347 
00348     DEBUG(dbgs() << "True branch:\n");
00349     DEBUG(dbgs() << "\tcondition: "
00350           << AArch64CC::getCondCodeName(TrueCmp) << '\n');
00351     DEBUG(dbgs() << "\timmediate: " << TrueImm << '\n');
00352 
00353     if (((HeadCmp == AArch64CC::GT && TrueCmp == AArch64CC::LT) ||
00354          (HeadCmp == AArch64CC::LT && TrueCmp == AArch64CC::GT)) &&
00355         std::abs(TrueImm - HeadImm) == 2) {
00356       // This branch transforms machine instructions that correspond to
00357       //
00358       // 1) (a > {TrueImm} && ...) || (a < {HeadImm} && ...)
00359       // 2) (a < {TrueImm} && ...) || (a > {HeadImm} && ...)
00360       //
00361       // into
00362       //
00363       // 1) (a >= {NewImm} && ...) || (a <= {NewImm} && ...)
00364       // 2) (a <= {NewImm} && ...) || (a >= {NewImm} && ...)
00365 
00366       CmpInfo HeadCmpInfo = adjustCmp(HeadCmpMI, HeadCmp);
00367       CmpInfo TrueCmpInfo = adjustCmp(TrueCmpMI, TrueCmp);
00368       if (std::get<0>(HeadCmpInfo) == std::get<0>(TrueCmpInfo) &&
00369           std::get<1>(HeadCmpInfo) == std::get<1>(TrueCmpInfo)) {
00370         modifyCmp(HeadCmpMI, HeadCmpInfo);
00371         modifyCmp(TrueCmpMI, TrueCmpInfo);
00372         Changed = true;
00373       }
00374     } else if (((HeadCmp == AArch64CC::GT && TrueCmp == AArch64CC::GT) ||
00375                 (HeadCmp == AArch64CC::LT && TrueCmp == AArch64CC::LT)) &&
00376                 std::abs(TrueImm - HeadImm) == 1) {
00377       // This branch transforms machine instructions that correspond to
00378       //
00379       // 1) (a > {TrueImm} && ...) || (a > {HeadImm} && ...)
00380       // 2) (a < {TrueImm} && ...) || (a < {HeadImm} && ...)
00381       //
00382       // into
00383       //
00384       // 1) (a <= {NewImm} && ...) || (a >  {NewImm} && ...)
00385       // 2) (a <  {NewImm} && ...) || (a >= {NewImm} && ...)
00386 
00387       // GT -> GE transformation increases immediate value, so picking the
00388       // smaller one; LT -> LE decreases immediate value so invert the choice.
00389       bool adjustHeadCond = (HeadImm < TrueImm);
00390       if (HeadCmp == AArch64CC::LT) {
00391           adjustHeadCond = !adjustHeadCond;
00392       }
00393 
00394       if (adjustHeadCond) {
00395         Changed |= adjustTo(HeadCmpMI, HeadCmp, TrueCmpMI, TrueImm);
00396       } else {
00397         Changed |= adjustTo(TrueCmpMI, TrueCmp, HeadCmpMI, HeadImm);
00398       }
00399     }
00400     // Other transformation cases almost never occur due to generation of < or >
00401     // comparisons instead of <= and >=.
00402   }
00403 
00404   return Changed;
00405 }