X86CmovConversion.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. //====- X86CmovConversion.cpp - Convert Cmov to Branch --------------------===//
  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. //
  9. /// \file
  10. /// This file implements a pass that converts X86 cmov instructions into
  11. /// branches when profitable. This pass is conservative. It transforms if and
  12. /// only if it can guarantee a gain with high confidence.
  13. ///
  14. /// Thus, the optimization applies under the following conditions:
  15. /// 1. Consider as candidates only CMOVs in innermost loops (assume that
  16. /// most hotspots are represented by these loops).
  17. /// 2. Given a group of CMOV instructions that are using the same EFLAGS def
  18. /// instruction:
  19. /// a. Consider them as candidates only if all have the same code condition
  20. /// or the opposite one to prevent generating more than one conditional
  21. /// jump per EFLAGS def instruction.
  22. /// b. Consider them as candidates only if all are profitable to be
  23. /// converted (assume that one bad conversion may cause a degradation).
  24. /// 3. Apply conversion only for loops that are found profitable and only for
  25. /// CMOV candidates that were found profitable.
  26. /// a. A loop is considered profitable only if conversion will reduce its
  27. /// depth cost by some threshold.
  28. /// b. CMOV is considered profitable if the cost of its condition is higher
  29. /// than the average cost of its true-value and false-value by 25% of
  30. /// branch-misprediction-penalty. This assures no degradation even with
  31. /// 25% branch misprediction.
  32. ///
  33. /// Note: This pass is assumed to run on SSA machine code.
  34. //
  35. //===----------------------------------------------------------------------===//
  36. //
  37. // External interfaces:
  38. // FunctionPass *llvm::createX86CmovConverterPass();
  39. // bool X86CmovConverterPass::runOnMachineFunction(MachineFunction &MF);
  40. //
  41. //===----------------------------------------------------------------------===//
  42. #include "X86.h"
  43. #include "X86InstrInfo.h"
  44. #include "llvm/ADT/ArrayRef.h"
  45. #include "llvm/ADT/DenseMap.h"
  46. #include "llvm/ADT/STLExtras.h"
  47. #include "llvm/ADT/SmallPtrSet.h"
  48. #include "llvm/ADT/SmallVector.h"
  49. #include "llvm/ADT/Statistic.h"
  50. #include "llvm/CodeGen/MachineBasicBlock.h"
  51. #include "llvm/CodeGen/MachineFunction.h"
  52. #include "llvm/CodeGen/MachineFunctionPass.h"
  53. #include "llvm/CodeGen/MachineInstr.h"
  54. #include "llvm/CodeGen/MachineInstrBuilder.h"
  55. #include "llvm/CodeGen/MachineLoopInfo.h"
  56. #include "llvm/CodeGen/MachineOperand.h"
  57. #include "llvm/CodeGen/MachineRegisterInfo.h"
  58. #include "llvm/CodeGen/TargetInstrInfo.h"
  59. #include "llvm/CodeGen/TargetRegisterInfo.h"
  60. #include "llvm/CodeGen/TargetSchedule.h"
  61. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  62. #include "llvm/IR/DebugLoc.h"
  63. #include "llvm/InitializePasses.h"
  64. #include "llvm/MC/MCSchedule.h"
  65. #include "llvm/Pass.h"
  66. #include "llvm/Support/CommandLine.h"
  67. #include "llvm/Support/Debug.h"
  68. #include "llvm/Support/raw_ostream.h"
  69. #include <algorithm>
  70. #include <cassert>
  71. #include <iterator>
  72. #include <utility>
  73. using namespace llvm;
  74. #define DEBUG_TYPE "x86-cmov-conversion"
  75. STATISTIC(NumOfSkippedCmovGroups, "Number of unsupported CMOV-groups");
  76. STATISTIC(NumOfCmovGroupCandidate, "Number of CMOV-group candidates");
  77. STATISTIC(NumOfLoopCandidate, "Number of CMOV-conversion profitable loops");
  78. STATISTIC(NumOfOptimizedCmovGroups, "Number of optimized CMOV-groups");
  79. // This internal switch can be used to turn off the cmov/branch optimization.
  80. static cl::opt<bool>
  81. EnableCmovConverter("x86-cmov-converter",
  82. cl::desc("Enable the X86 cmov-to-branch optimization."),
  83. cl::init(true), cl::Hidden);
  84. static cl::opt<unsigned>
  85. GainCycleThreshold("x86-cmov-converter-threshold",
  86. cl::desc("Minimum gain per loop (in cycles) threshold."),
  87. cl::init(4), cl::Hidden);
  88. static cl::opt<bool> ForceMemOperand(
  89. "x86-cmov-converter-force-mem-operand",
  90. cl::desc("Convert cmovs to branches whenever they have memory operands."),
  91. cl::init(true), cl::Hidden);
  92. namespace {
  93. /// Converts X86 cmov instructions into branches when profitable.
  94. class X86CmovConverterPass : public MachineFunctionPass {
  95. public:
  96. X86CmovConverterPass() : MachineFunctionPass(ID) { }
  97. StringRef getPassName() const override { return "X86 cmov Conversion"; }
  98. bool runOnMachineFunction(MachineFunction &MF) override;
  99. void getAnalysisUsage(AnalysisUsage &AU) const override;
  100. /// Pass identification, replacement for typeid.
  101. static char ID;
  102. private:
  103. MachineRegisterInfo *MRI = nullptr;
  104. const TargetInstrInfo *TII = nullptr;
  105. const TargetRegisterInfo *TRI = nullptr;
  106. MachineLoopInfo *MLI = nullptr;
  107. TargetSchedModel TSchedModel;
  108. /// List of consecutive CMOV instructions.
  109. using CmovGroup = SmallVector<MachineInstr *, 2>;
  110. using CmovGroups = SmallVector<CmovGroup, 2>;
  111. /// Collect all CMOV-group-candidates in \p CurrLoop and update \p
  112. /// CmovInstGroups accordingly.
  113. ///
  114. /// \param Blocks List of blocks to process.
  115. /// \param CmovInstGroups List of consecutive CMOV instructions in CurrLoop.
  116. /// \returns true iff it found any CMOV-group-candidate.
  117. bool collectCmovCandidates(ArrayRef<MachineBasicBlock *> Blocks,
  118. CmovGroups &CmovInstGroups,
  119. bool IncludeLoads = false);
  120. /// Check if it is profitable to transform each CMOV-group-candidates into
  121. /// branch. Remove all groups that are not profitable from \p CmovInstGroups.
  122. ///
  123. /// \param Blocks List of blocks to process.
  124. /// \param CmovInstGroups List of consecutive CMOV instructions in CurrLoop.
  125. /// \returns true iff any CMOV-group-candidate remain.
  126. bool checkForProfitableCmovCandidates(ArrayRef<MachineBasicBlock *> Blocks,
  127. CmovGroups &CmovInstGroups);
  128. /// Convert the given list of consecutive CMOV instructions into a branch.
  129. ///
  130. /// \param Group Consecutive CMOV instructions to be converted into branch.
  131. void convertCmovInstsToBranches(SmallVectorImpl<MachineInstr *> &Group) const;
  132. };
  133. } // end anonymous namespace
  134. char X86CmovConverterPass::ID = 0;
  135. void X86CmovConverterPass::getAnalysisUsage(AnalysisUsage &AU) const {
  136. MachineFunctionPass::getAnalysisUsage(AU);
  137. AU.addRequired<MachineLoopInfo>();
  138. }
  139. bool X86CmovConverterPass::runOnMachineFunction(MachineFunction &MF) {
  140. if (skipFunction(MF.getFunction()))
  141. return false;
  142. if (!EnableCmovConverter)
  143. return false;
  144. LLVM_DEBUG(dbgs() << "********** " << getPassName() << " : " << MF.getName()
  145. << "**********\n");
  146. bool Changed = false;
  147. MLI = &getAnalysis<MachineLoopInfo>();
  148. const TargetSubtargetInfo &STI = MF.getSubtarget();
  149. MRI = &MF.getRegInfo();
  150. TII = STI.getInstrInfo();
  151. TRI = STI.getRegisterInfo();
  152. TSchedModel.init(&STI);
  153. // Before we handle the more subtle cases of register-register CMOVs inside
  154. // of potentially hot loops, we want to quickly remove all CMOVs with
  155. // a memory operand. The CMOV will risk a stall waiting for the load to
  156. // complete that speculative execution behind a branch is better suited to
  157. // handle on modern x86 chips.
  158. if (ForceMemOperand) {
  159. CmovGroups AllCmovGroups;
  160. SmallVector<MachineBasicBlock *, 4> Blocks;
  161. for (auto &MBB : MF)
  162. Blocks.push_back(&MBB);
  163. if (collectCmovCandidates(Blocks, AllCmovGroups, /*IncludeLoads*/ true)) {
  164. for (auto &Group : AllCmovGroups) {
  165. // Skip any group that doesn't do at least one memory operand cmov.
  166. if (llvm::none_of(Group, [&](MachineInstr *I) { return I->mayLoad(); }))
  167. continue;
  168. // For CMOV groups which we can rewrite and which contain a memory load,
  169. // always rewrite them. On x86, a CMOV will dramatically amplify any
  170. // memory latency by blocking speculative execution.
  171. Changed = true;
  172. convertCmovInstsToBranches(Group);
  173. }
  174. }
  175. }
  176. //===--------------------------------------------------------------------===//
  177. // Register-operand Conversion Algorithm
  178. // ---------
  179. // For each inner most loop
  180. // collectCmovCandidates() {
  181. // Find all CMOV-group-candidates.
  182. // }
  183. //
  184. // checkForProfitableCmovCandidates() {
  185. // * Calculate both loop-depth and optimized-loop-depth.
  186. // * Use these depth to check for loop transformation profitability.
  187. // * Check for CMOV-group-candidate transformation profitability.
  188. // }
  189. //
  190. // For each profitable CMOV-group-candidate
  191. // convertCmovInstsToBranches() {
  192. // * Create FalseBB, SinkBB, Conditional branch to SinkBB.
  193. // * Replace each CMOV instruction with a PHI instruction in SinkBB.
  194. // }
  195. //
  196. // Note: For more details, see each function description.
  197. //===--------------------------------------------------------------------===//
  198. // Build up the loops in pre-order.
  199. SmallVector<MachineLoop *, 4> Loops(MLI->begin(), MLI->end());
  200. // Note that we need to check size on each iteration as we accumulate child
  201. // loops.
  202. for (int i = 0; i < (int)Loops.size(); ++i)
  203. for (MachineLoop *Child : Loops[i]->getSubLoops())
  204. Loops.push_back(Child);
  205. for (MachineLoop *CurrLoop : Loops) {
  206. // Optimize only inner most loops.
  207. if (!CurrLoop->getSubLoops().empty())
  208. continue;
  209. // List of consecutive CMOV instructions to be processed.
  210. CmovGroups CmovInstGroups;
  211. if (!collectCmovCandidates(CurrLoop->getBlocks(), CmovInstGroups))
  212. continue;
  213. if (!checkForProfitableCmovCandidates(CurrLoop->getBlocks(),
  214. CmovInstGroups))
  215. continue;
  216. Changed = true;
  217. for (auto &Group : CmovInstGroups)
  218. convertCmovInstsToBranches(Group);
  219. }
  220. return Changed;
  221. }
  222. bool X86CmovConverterPass::collectCmovCandidates(
  223. ArrayRef<MachineBasicBlock *> Blocks, CmovGroups &CmovInstGroups,
  224. bool IncludeLoads) {
  225. //===--------------------------------------------------------------------===//
  226. // Collect all CMOV-group-candidates and add them into CmovInstGroups.
  227. //
  228. // CMOV-group:
  229. // CMOV instructions, in same MBB, that uses same EFLAGS def instruction.
  230. //
  231. // CMOV-group-candidate:
  232. // CMOV-group where all the CMOV instructions are
  233. // 1. consecutive.
  234. // 2. have same condition code or opposite one.
  235. // 3. have only operand registers (X86::CMOVrr).
  236. //===--------------------------------------------------------------------===//
  237. // List of possible improvement (TODO's):
  238. // --------------------------------------
  239. // TODO: Add support for X86::CMOVrm instructions.
  240. // TODO: Add support for X86::SETcc instructions.
  241. // TODO: Add support for CMOV-groups with non consecutive CMOV instructions.
  242. //===--------------------------------------------------------------------===//
  243. // Current processed CMOV-Group.
  244. CmovGroup Group;
  245. for (auto *MBB : Blocks) {
  246. Group.clear();
  247. // Condition code of first CMOV instruction current processed range and its
  248. // opposite condition code.
  249. X86::CondCode FirstCC = X86::COND_INVALID, FirstOppCC = X86::COND_INVALID,
  250. MemOpCC = X86::COND_INVALID;
  251. // Indicator of a non CMOVrr instruction in the current processed range.
  252. bool FoundNonCMOVInst = false;
  253. // Indicator for current processed CMOV-group if it should be skipped.
  254. bool SkipGroup = false;
  255. for (auto &I : *MBB) {
  256. // Skip debug instructions.
  257. if (I.isDebugInstr())
  258. continue;
  259. X86::CondCode CC = X86::getCondFromCMov(I);
  260. // Check if we found a X86::CMOVrr instruction.
  261. if (CC != X86::COND_INVALID && (IncludeLoads || !I.mayLoad())) {
  262. if (Group.empty()) {
  263. // We found first CMOV in the range, reset flags.
  264. FirstCC = CC;
  265. FirstOppCC = X86::GetOppositeBranchCondition(CC);
  266. // Clear out the prior group's memory operand CC.
  267. MemOpCC = X86::COND_INVALID;
  268. FoundNonCMOVInst = false;
  269. SkipGroup = false;
  270. }
  271. Group.push_back(&I);
  272. // Check if it is a non-consecutive CMOV instruction or it has different
  273. // condition code than FirstCC or FirstOppCC.
  274. if (FoundNonCMOVInst || (CC != FirstCC && CC != FirstOppCC))
  275. // Mark the SKipGroup indicator to skip current processed CMOV-Group.
  276. SkipGroup = true;
  277. if (I.mayLoad()) {
  278. if (MemOpCC == X86::COND_INVALID)
  279. // The first memory operand CMOV.
  280. MemOpCC = CC;
  281. else if (CC != MemOpCC)
  282. // Can't handle mixed conditions with memory operands.
  283. SkipGroup = true;
  284. }
  285. // Check if we were relying on zero-extending behavior of the CMOV.
  286. if (!SkipGroup &&
  287. llvm::any_of(
  288. MRI->use_nodbg_instructions(I.defs().begin()->getReg()),
  289. [&](MachineInstr &UseI) {
  290. return UseI.getOpcode() == X86::SUBREG_TO_REG;
  291. }))
  292. // FIXME: We should model the cost of using an explicit MOV to handle
  293. // the zero-extension rather than just refusing to handle this.
  294. SkipGroup = true;
  295. continue;
  296. }
  297. // If Group is empty, keep looking for first CMOV in the range.
  298. if (Group.empty())
  299. continue;
  300. // We found a non X86::CMOVrr instruction.
  301. FoundNonCMOVInst = true;
  302. // Check if this instruction define EFLAGS, to determine end of processed
  303. // range, as there would be no more instructions using current EFLAGS def.
  304. if (I.definesRegister(X86::EFLAGS)) {
  305. // Check if current processed CMOV-group should not be skipped and add
  306. // it as a CMOV-group-candidate.
  307. if (!SkipGroup)
  308. CmovInstGroups.push_back(Group);
  309. else
  310. ++NumOfSkippedCmovGroups;
  311. Group.clear();
  312. }
  313. }
  314. // End of basic block is considered end of range, check if current processed
  315. // CMOV-group should not be skipped and add it as a CMOV-group-candidate.
  316. if (Group.empty())
  317. continue;
  318. if (!SkipGroup)
  319. CmovInstGroups.push_back(Group);
  320. else
  321. ++NumOfSkippedCmovGroups;
  322. }
  323. NumOfCmovGroupCandidate += CmovInstGroups.size();
  324. return !CmovInstGroups.empty();
  325. }
  326. /// \returns Depth of CMOV instruction as if it was converted into branch.
  327. /// \param TrueOpDepth depth cost of CMOV true value operand.
  328. /// \param FalseOpDepth depth cost of CMOV false value operand.
  329. static unsigned getDepthOfOptCmov(unsigned TrueOpDepth, unsigned FalseOpDepth) {
  330. // The depth of the result after branch conversion is
  331. // TrueOpDepth * TrueOpProbability + FalseOpDepth * FalseOpProbability.
  332. // As we have no info about branch weight, we assume 75% for one and 25% for
  333. // the other, and pick the result with the largest resulting depth.
  334. return std::max(
  335. divideCeil(TrueOpDepth * 3 + FalseOpDepth, 4),
  336. divideCeil(FalseOpDepth * 3 + TrueOpDepth, 4));
  337. }
  338. bool X86CmovConverterPass::checkForProfitableCmovCandidates(
  339. ArrayRef<MachineBasicBlock *> Blocks, CmovGroups &CmovInstGroups) {
  340. struct DepthInfo {
  341. /// Depth of original loop.
  342. unsigned Depth;
  343. /// Depth of optimized loop.
  344. unsigned OptDepth;
  345. };
  346. /// Number of loop iterations to calculate depth for ?!
  347. static const unsigned LoopIterations = 2;
  348. DenseMap<MachineInstr *, DepthInfo> DepthMap;
  349. DepthInfo LoopDepth[LoopIterations] = {{0, 0}, {0, 0}};
  350. enum { PhyRegType = 0, VirRegType = 1, RegTypeNum = 2 };
  351. /// For each register type maps the register to its last def instruction.
  352. DenseMap<unsigned, MachineInstr *> RegDefMaps[RegTypeNum];
  353. /// Maps register operand to its def instruction, which can be nullptr if it
  354. /// is unknown (e.g., operand is defined outside the loop).
  355. DenseMap<MachineOperand *, MachineInstr *> OperandToDefMap;
  356. // Set depth of unknown instruction (i.e., nullptr) to zero.
  357. DepthMap[nullptr] = {0, 0};
  358. SmallPtrSet<MachineInstr *, 4> CmovInstructions;
  359. for (auto &Group : CmovInstGroups)
  360. CmovInstructions.insert(Group.begin(), Group.end());
  361. //===--------------------------------------------------------------------===//
  362. // Step 1: Calculate instruction depth and loop depth.
  363. // Optimized-Loop:
  364. // loop with CMOV-group-candidates converted into branches.
  365. //
  366. // Instruction-Depth:
  367. // instruction latency + max operand depth.
  368. // * For CMOV instruction in optimized loop the depth is calculated as:
  369. // CMOV latency + getDepthOfOptCmov(True-Op-Depth, False-Op-depth)
  370. // TODO: Find a better way to estimate the latency of the branch instruction
  371. // rather than using the CMOV latency.
  372. //
  373. // Loop-Depth:
  374. // max instruction depth of all instructions in the loop.
  375. // Note: instruction with max depth represents the critical-path in the loop.
  376. //
  377. // Loop-Depth[i]:
  378. // Loop-Depth calculated for first `i` iterations.
  379. // Note: it is enough to calculate depth for up to two iterations.
  380. //
  381. // Depth-Diff[i]:
  382. // Number of cycles saved in first 'i` iterations by optimizing the loop.
  383. //===--------------------------------------------------------------------===//
  384. for (unsigned I = 0; I < LoopIterations; ++I) {
  385. DepthInfo &MaxDepth = LoopDepth[I];
  386. for (auto *MBB : Blocks) {
  387. // Clear physical registers Def map.
  388. RegDefMaps[PhyRegType].clear();
  389. for (MachineInstr &MI : *MBB) {
  390. // Skip debug instructions.
  391. if (MI.isDebugInstr())
  392. continue;
  393. unsigned MIDepth = 0;
  394. unsigned MIDepthOpt = 0;
  395. bool IsCMOV = CmovInstructions.count(&MI);
  396. for (auto &MO : MI.uses()) {
  397. // Checks for "isUse()" as "uses()" returns also implicit definitions.
  398. if (!MO.isReg() || !MO.isUse())
  399. continue;
  400. Register Reg = MO.getReg();
  401. auto &RDM = RegDefMaps[Reg.isVirtual()];
  402. if (MachineInstr *DefMI = RDM.lookup(Reg)) {
  403. OperandToDefMap[&MO] = DefMI;
  404. DepthInfo Info = DepthMap.lookup(DefMI);
  405. MIDepth = std::max(MIDepth, Info.Depth);
  406. if (!IsCMOV)
  407. MIDepthOpt = std::max(MIDepthOpt, Info.OptDepth);
  408. }
  409. }
  410. if (IsCMOV)
  411. MIDepthOpt = getDepthOfOptCmov(
  412. DepthMap[OperandToDefMap.lookup(&MI.getOperand(1))].OptDepth,
  413. DepthMap[OperandToDefMap.lookup(&MI.getOperand(2))].OptDepth);
  414. // Iterates over all operands to handle implicit definitions as well.
  415. for (auto &MO : MI.operands()) {
  416. if (!MO.isReg() || !MO.isDef())
  417. continue;
  418. Register Reg = MO.getReg();
  419. RegDefMaps[Reg.isVirtual()][Reg] = &MI;
  420. }
  421. unsigned Latency = TSchedModel.computeInstrLatency(&MI);
  422. DepthMap[&MI] = {MIDepth += Latency, MIDepthOpt += Latency};
  423. MaxDepth.Depth = std::max(MaxDepth.Depth, MIDepth);
  424. MaxDepth.OptDepth = std::max(MaxDepth.OptDepth, MIDepthOpt);
  425. }
  426. }
  427. }
  428. unsigned Diff[LoopIterations] = {LoopDepth[0].Depth - LoopDepth[0].OptDepth,
  429. LoopDepth[1].Depth - LoopDepth[1].OptDepth};
  430. //===--------------------------------------------------------------------===//
  431. // Step 2: Check if Loop worth to be optimized.
  432. // Worth-Optimize-Loop:
  433. // case 1: Diff[1] == Diff[0]
  434. // Critical-path is iteration independent - there is no dependency
  435. // of critical-path instructions on critical-path instructions of
  436. // previous iteration.
  437. // Thus, it is enough to check gain percent of 1st iteration -
  438. // To be conservative, the optimized loop need to have a depth of
  439. // 12.5% cycles less than original loop, per iteration.
  440. //
  441. // case 2: Diff[1] > Diff[0]
  442. // Critical-path is iteration dependent - there is dependency of
  443. // critical-path instructions on critical-path instructions of
  444. // previous iteration.
  445. // Thus, check the gain percent of the 2nd iteration (similar to the
  446. // previous case), but it is also required to check the gradient of
  447. // the gain - the change in Depth-Diff compared to the change in
  448. // Loop-Depth between 1st and 2nd iterations.
  449. // To be conservative, the gradient need to be at least 50%.
  450. //
  451. // In addition, In order not to optimize loops with very small gain, the
  452. // gain (in cycles) after 2nd iteration should not be less than a given
  453. // threshold. Thus, the check (Diff[1] >= GainCycleThreshold) must apply.
  454. //
  455. // If loop is not worth optimizing, remove all CMOV-group-candidates.
  456. //===--------------------------------------------------------------------===//
  457. if (Diff[1] < GainCycleThreshold)
  458. return false;
  459. bool WorthOptLoop = false;
  460. if (Diff[1] == Diff[0])
  461. WorthOptLoop = Diff[0] * 8 >= LoopDepth[0].Depth;
  462. else if (Diff[1] > Diff[0])
  463. WorthOptLoop =
  464. (Diff[1] - Diff[0]) * 2 >= (LoopDepth[1].Depth - LoopDepth[0].Depth) &&
  465. (Diff[1] * 8 >= LoopDepth[1].Depth);
  466. if (!WorthOptLoop)
  467. return false;
  468. ++NumOfLoopCandidate;
  469. //===--------------------------------------------------------------------===//
  470. // Step 3: Check for each CMOV-group-candidate if it worth to be optimized.
  471. // Worth-Optimize-Group:
  472. // Iff it worths to optimize all CMOV instructions in the group.
  473. //
  474. // Worth-Optimize-CMOV:
  475. // Predicted branch is faster than CMOV by the difference between depth of
  476. // condition operand and depth of taken (predicted) value operand.
  477. // To be conservative, the gain of such CMOV transformation should cover at
  478. // at least 25% of branch-misprediction-penalty.
  479. //===--------------------------------------------------------------------===//
  480. unsigned MispredictPenalty = TSchedModel.getMCSchedModel()->MispredictPenalty;
  481. CmovGroups TempGroups;
  482. std::swap(TempGroups, CmovInstGroups);
  483. for (auto &Group : TempGroups) {
  484. bool WorthOpGroup = true;
  485. for (auto *MI : Group) {
  486. // Avoid CMOV instruction which value is used as a pointer to load from.
  487. // This is another conservative check to avoid converting CMOV instruction
  488. // used with tree-search like algorithm, where the branch is unpredicted.
  489. auto UIs = MRI->use_instructions(MI->defs().begin()->getReg());
  490. if (!UIs.empty() && ++UIs.begin() == UIs.end()) {
  491. unsigned Op = UIs.begin()->getOpcode();
  492. if (Op == X86::MOV64rm || Op == X86::MOV32rm) {
  493. WorthOpGroup = false;
  494. break;
  495. }
  496. }
  497. unsigned CondCost =
  498. DepthMap[OperandToDefMap.lookup(&MI->getOperand(4))].Depth;
  499. unsigned ValCost = getDepthOfOptCmov(
  500. DepthMap[OperandToDefMap.lookup(&MI->getOperand(1))].Depth,
  501. DepthMap[OperandToDefMap.lookup(&MI->getOperand(2))].Depth);
  502. if (ValCost > CondCost || (CondCost - ValCost) * 4 < MispredictPenalty) {
  503. WorthOpGroup = false;
  504. break;
  505. }
  506. }
  507. if (WorthOpGroup)
  508. CmovInstGroups.push_back(Group);
  509. }
  510. return !CmovInstGroups.empty();
  511. }
  512. static bool checkEFLAGSLive(MachineInstr *MI) {
  513. if (MI->killsRegister(X86::EFLAGS))
  514. return false;
  515. // The EFLAGS operand of MI might be missing a kill marker.
  516. // Figure out whether EFLAGS operand should LIVE after MI instruction.
  517. MachineBasicBlock *BB = MI->getParent();
  518. MachineBasicBlock::iterator ItrMI = MI;
  519. // Scan forward through BB for a use/def of EFLAGS.
  520. for (auto I = std::next(ItrMI), E = BB->end(); I != E; ++I) {
  521. if (I->readsRegister(X86::EFLAGS))
  522. return true;
  523. if (I->definesRegister(X86::EFLAGS))
  524. return false;
  525. }
  526. // We hit the end of the block, check whether EFLAGS is live into a successor.
  527. for (MachineBasicBlock *Succ : BB->successors())
  528. if (Succ->isLiveIn(X86::EFLAGS))
  529. return true;
  530. return false;
  531. }
  532. /// Given /p First CMOV instruction and /p Last CMOV instruction representing a
  533. /// group of CMOV instructions, which may contain debug instructions in between,
  534. /// move all debug instructions to after the last CMOV instruction, making the
  535. /// CMOV group consecutive.
  536. static void packCmovGroup(MachineInstr *First, MachineInstr *Last) {
  537. assert(X86::getCondFromCMov(*Last) != X86::COND_INVALID &&
  538. "Last instruction in a CMOV group must be a CMOV instruction");
  539. SmallVector<MachineInstr *, 2> DBGInstructions;
  540. for (auto I = First->getIterator(), E = Last->getIterator(); I != E; I++) {
  541. if (I->isDebugInstr())
  542. DBGInstructions.push_back(&*I);
  543. }
  544. // Splice the debug instruction after the cmov group.
  545. MachineBasicBlock *MBB = First->getParent();
  546. for (auto *MI : DBGInstructions)
  547. MBB->insertAfter(Last, MI->removeFromParent());
  548. }
  549. void X86CmovConverterPass::convertCmovInstsToBranches(
  550. SmallVectorImpl<MachineInstr *> &Group) const {
  551. assert(!Group.empty() && "No CMOV instructions to convert");
  552. ++NumOfOptimizedCmovGroups;
  553. // If the CMOV group is not packed, e.g., there are debug instructions between
  554. // first CMOV and last CMOV, then pack the group and make the CMOV instruction
  555. // consecutive by moving the debug instructions to after the last CMOV.
  556. packCmovGroup(Group.front(), Group.back());
  557. // To convert a CMOVcc instruction, we actually have to insert the diamond
  558. // control-flow pattern. The incoming instruction knows the destination vreg
  559. // to set, the condition code register to branch on, the true/false values to
  560. // select between, and a branch opcode to use.
  561. // Before
  562. // -----
  563. // MBB:
  564. // cond = cmp ...
  565. // v1 = CMOVge t1, f1, cond
  566. // v2 = CMOVlt t2, f2, cond
  567. // v3 = CMOVge v1, f3, cond
  568. //
  569. // After
  570. // -----
  571. // MBB:
  572. // cond = cmp ...
  573. // jge %SinkMBB
  574. //
  575. // FalseMBB:
  576. // jmp %SinkMBB
  577. //
  578. // SinkMBB:
  579. // %v1 = phi[%f1, %FalseMBB], [%t1, %MBB]
  580. // %v2 = phi[%t2, %FalseMBB], [%f2, %MBB] ; For CMOV with OppCC switch
  581. // ; true-value with false-value
  582. // %v3 = phi[%f3, %FalseMBB], [%t1, %MBB] ; Phi instruction cannot use
  583. // ; previous Phi instruction result
  584. MachineInstr &MI = *Group.front();
  585. MachineInstr *LastCMOV = Group.back();
  586. DebugLoc DL = MI.getDebugLoc();
  587. X86::CondCode CC = X86::CondCode(X86::getCondFromCMov(MI));
  588. X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
  589. // Potentially swap the condition codes so that any memory operand to a CMOV
  590. // is in the *false* position instead of the *true* position. We can invert
  591. // any non-memory operand CMOV instructions to cope with this and we ensure
  592. // memory operand CMOVs are only included with a single condition code.
  593. if (llvm::any_of(Group, [&](MachineInstr *I) {
  594. return I->mayLoad() && X86::getCondFromCMov(*I) == CC;
  595. }))
  596. std::swap(CC, OppCC);
  597. MachineBasicBlock *MBB = MI.getParent();
  598. MachineFunction::iterator It = ++MBB->getIterator();
  599. MachineFunction *F = MBB->getParent();
  600. const BasicBlock *BB = MBB->getBasicBlock();
  601. MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(BB);
  602. MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(BB);
  603. F->insert(It, FalseMBB);
  604. F->insert(It, SinkMBB);
  605. // If the EFLAGS register isn't dead in the terminator, then claim that it's
  606. // live into the sink and copy blocks.
  607. if (checkEFLAGSLive(LastCMOV)) {
  608. FalseMBB->addLiveIn(X86::EFLAGS);
  609. SinkMBB->addLiveIn(X86::EFLAGS);
  610. }
  611. // Transfer the remainder of BB and its successor edges to SinkMBB.
  612. SinkMBB->splice(SinkMBB->begin(), MBB,
  613. std::next(MachineBasicBlock::iterator(LastCMOV)), MBB->end());
  614. SinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
  615. // Add the false and sink blocks as its successors.
  616. MBB->addSuccessor(FalseMBB);
  617. MBB->addSuccessor(SinkMBB);
  618. // Create the conditional branch instruction.
  619. BuildMI(MBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(CC);
  620. // Add the sink block to the false block successors.
  621. FalseMBB->addSuccessor(SinkMBB);
  622. MachineInstrBuilder MIB;
  623. MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
  624. MachineBasicBlock::iterator MIItEnd =
  625. std::next(MachineBasicBlock::iterator(LastCMOV));
  626. MachineBasicBlock::iterator FalseInsertionPoint = FalseMBB->begin();
  627. MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
  628. // First we need to insert an explicit load on the false path for any memory
  629. // operand. We also need to potentially do register rewriting here, but it is
  630. // simpler as the memory operands are always on the false path so we can
  631. // simply take that input, whatever it is.
  632. DenseMap<unsigned, unsigned> FalseBBRegRewriteTable;
  633. for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd;) {
  634. auto &MI = *MIIt++;
  635. // Skip any CMOVs in this group which don't load from memory.
  636. if (!MI.mayLoad()) {
  637. // Remember the false-side register input.
  638. Register FalseReg =
  639. MI.getOperand(X86::getCondFromCMov(MI) == CC ? 1 : 2).getReg();
  640. // Walk back through any intermediate cmovs referenced.
  641. while (true) {
  642. auto FRIt = FalseBBRegRewriteTable.find(FalseReg);
  643. if (FRIt == FalseBBRegRewriteTable.end())
  644. break;
  645. FalseReg = FRIt->second;
  646. }
  647. FalseBBRegRewriteTable[MI.getOperand(0).getReg()] = FalseReg;
  648. continue;
  649. }
  650. // The condition must be the *opposite* of the one we've decided to branch
  651. // on as the branch will go *around* the load and the load should happen
  652. // when the CMOV condition is false.
  653. assert(X86::getCondFromCMov(MI) == OppCC &&
  654. "Can only handle memory-operand cmov instructions with a condition "
  655. "opposite to the selected branch direction.");
  656. // The goal is to rewrite the cmov from:
  657. //
  658. // MBB:
  659. // %A = CMOVcc %B (tied), (mem)
  660. //
  661. // to
  662. //
  663. // MBB:
  664. // %A = CMOVcc %B (tied), %C
  665. // FalseMBB:
  666. // %C = MOV (mem)
  667. //
  668. // Which will allow the next loop to rewrite the CMOV in terms of a PHI:
  669. //
  670. // MBB:
  671. // JMP!cc SinkMBB
  672. // FalseMBB:
  673. // %C = MOV (mem)
  674. // SinkMBB:
  675. // %A = PHI [ %C, FalseMBB ], [ %B, MBB]
  676. // Get a fresh register to use as the destination of the MOV.
  677. const TargetRegisterClass *RC = MRI->getRegClass(MI.getOperand(0).getReg());
  678. Register TmpReg = MRI->createVirtualRegister(RC);
  679. SmallVector<MachineInstr *, 4> NewMIs;
  680. bool Unfolded = TII->unfoldMemoryOperand(*MBB->getParent(), MI, TmpReg,
  681. /*UnfoldLoad*/ true,
  682. /*UnfoldStore*/ false, NewMIs);
  683. (void)Unfolded;
  684. assert(Unfolded && "Should never fail to unfold a loading cmov!");
  685. // Move the new CMOV to just before the old one and reset any impacted
  686. // iterator.
  687. auto *NewCMOV = NewMIs.pop_back_val();
  688. assert(X86::getCondFromCMov(*NewCMOV) == OppCC &&
  689. "Last new instruction isn't the expected CMOV!");
  690. LLVM_DEBUG(dbgs() << "\tRewritten cmov: "; NewCMOV->dump());
  691. MBB->insert(MachineBasicBlock::iterator(MI), NewCMOV);
  692. if (&*MIItBegin == &MI)
  693. MIItBegin = MachineBasicBlock::iterator(NewCMOV);
  694. // Sink whatever instructions were needed to produce the unfolded operand
  695. // into the false block.
  696. for (auto *NewMI : NewMIs) {
  697. LLVM_DEBUG(dbgs() << "\tRewritten load instr: "; NewMI->dump());
  698. FalseMBB->insert(FalseInsertionPoint, NewMI);
  699. // Re-map any operands that are from other cmovs to the inputs for this block.
  700. for (auto &MOp : NewMI->uses()) {
  701. if (!MOp.isReg())
  702. continue;
  703. auto It = FalseBBRegRewriteTable.find(MOp.getReg());
  704. if (It == FalseBBRegRewriteTable.end())
  705. continue;
  706. MOp.setReg(It->second);
  707. // This might have been a kill when it referenced the cmov result, but
  708. // it won't necessarily be once rewritten.
  709. // FIXME: We could potentially improve this by tracking whether the
  710. // operand to the cmov was also a kill, and then skipping the PHI node
  711. // construction below.
  712. MOp.setIsKill(false);
  713. }
  714. }
  715. MBB->erase(&MI);
  716. // Add this PHI to the rewrite table.
  717. FalseBBRegRewriteTable[NewCMOV->getOperand(0).getReg()] = TmpReg;
  718. }
  719. // As we are creating the PHIs, we have to be careful if there is more than
  720. // one. Later CMOVs may reference the results of earlier CMOVs, but later
  721. // PHIs have to reference the individual true/false inputs from earlier PHIs.
  722. // That also means that PHI construction must work forward from earlier to
  723. // later, and that the code must maintain a mapping from earlier PHI's
  724. // destination registers, and the registers that went into the PHI.
  725. DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
  726. for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
  727. Register DestReg = MIIt->getOperand(0).getReg();
  728. Register Op1Reg = MIIt->getOperand(1).getReg();
  729. Register Op2Reg = MIIt->getOperand(2).getReg();
  730. // If this CMOV we are processing is the opposite condition from the jump we
  731. // generated, then we have to swap the operands for the PHI that is going to
  732. // be generated.
  733. if (X86::getCondFromCMov(*MIIt) == OppCC)
  734. std::swap(Op1Reg, Op2Reg);
  735. auto Op1Itr = RegRewriteTable.find(Op1Reg);
  736. if (Op1Itr != RegRewriteTable.end())
  737. Op1Reg = Op1Itr->second.first;
  738. auto Op2Itr = RegRewriteTable.find(Op2Reg);
  739. if (Op2Itr != RegRewriteTable.end())
  740. Op2Reg = Op2Itr->second.second;
  741. // SinkMBB:
  742. // %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, MBB ]
  743. // ...
  744. MIB = BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(X86::PHI), DestReg)
  745. .addReg(Op1Reg)
  746. .addMBB(FalseMBB)
  747. .addReg(Op2Reg)
  748. .addMBB(MBB);
  749. (void)MIB;
  750. LLVM_DEBUG(dbgs() << "\tFrom: "; MIIt->dump());
  751. LLVM_DEBUG(dbgs() << "\tTo: "; MIB->dump());
  752. // Add this PHI to the rewrite table.
  753. RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
  754. }
  755. // Now remove the CMOV(s).
  756. MBB->erase(MIItBegin, MIItEnd);
  757. // Add new basic blocks to MachineLoopInfo.
  758. if (MachineLoop *L = MLI->getLoopFor(MBB)) {
  759. L->addBasicBlockToLoop(FalseMBB, MLI->getBase());
  760. L->addBasicBlockToLoop(SinkMBB, MLI->getBase());
  761. }
  762. }
  763. INITIALIZE_PASS_BEGIN(X86CmovConverterPass, DEBUG_TYPE, "X86 cmov Conversion",
  764. false, false)
  765. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  766. INITIALIZE_PASS_END(X86CmovConverterPass, DEBUG_TYPE, "X86 cmov Conversion",
  767. false, false)
  768. FunctionPass *llvm::createX86CmovConverterPass() {
  769. return new X86CmovConverterPass();
  770. }