LLVM  5.0.0
X86CmovConversion.cpp
Go to the documentation of this file.
1 //====-- X86CmovConversion.cpp - Convert Cmov to Branch -------------------===//
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 /// \file
10 /// This file implements a pass that converts X86 cmov instructions into branch
11 /// when profitable. This pass is conservative, i.e., it applies transformation
12 /// if and only if it can gaurantee a gain with high confidence.
13 ///
14 /// Thus, the optimization applies under the following conditions:
15 /// 1. Consider as a candidate only CMOV in most inner loop, assuming that
16 /// most hotspots are represented by these loops.
17 /// 2. Given a group of CMOV instructions, that are using same EFLAGS def
18 /// instruction:
19 /// a. Consider them as candidates only if all have same code condition or
20 /// opposite one, to prevent generating more than one conditional jump
21 /// per EFLAGS def instruction.
22 /// b. Consider them as candidates only if all are profitable to be
23 /// converted, assuming that one bad conversion may casue a degradation.
24 /// 3. Apply conversion only for loop that are found profitable and only for
25 /// CMOV candidates that were found profitable.
26 /// a. Loop is considered profitable only if conversion will reduce its
27 /// depth cost by some thrishold.
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 to assure no degredassion even
31 /// with 25% branch misprediction.
32 ///
33 /// Note: This pass is assumed to run on SSA machine code.
34 //===----------------------------------------------------------------------===//
35 //
36 // External interfaces:
37 // FunctionPass *llvm::createX86CmovConverterPass();
38 // bool X86CmovConverterPass::runOnMachineFunction(MachineFunction &MF);
39 //
40 
41 #include "X86.h"
42 #include "X86InstrInfo.h"
43 #include "X86Subtarget.h"
44 #include "llvm/ADT/Statistic.h"
49 #include "llvm/CodeGen/Passes.h"
51 #include "llvm/IR/InstIterator.h"
52 #include "llvm/Support/Debug.h"
54 using namespace llvm;
55 
56 #define DEBUG_TYPE "x86-cmov-converter"
57 
58 STATISTIC(NumOfSkippedCmovGroups, "Number of unsupported CMOV-groups");
59 STATISTIC(NumOfCmovGroupCandidate, "Number of CMOV-group candidates");
60 STATISTIC(NumOfLoopCandidate, "Number of CMOV-conversion profitable loops");
61 STATISTIC(NumOfOptimizedCmovGroups, "Number of optimized CMOV-groups");
62 
63 namespace {
64 // This internal switch can be used to turn off the cmov/branch optimization.
65 static cl::opt<bool>
66  EnableCmovConverter("x86-cmov-converter",
67  cl::desc("Enable the X86 cmov-to-branch optimization."),
68  cl::init(true), cl::Hidden);
69 
70 /// Converts X86 cmov instructions into branches when profitable.
71 class X86CmovConverterPass : public MachineFunctionPass {
72 public:
73  X86CmovConverterPass() : MachineFunctionPass(ID) {}
74  ~X86CmovConverterPass() {}
75 
76  StringRef getPassName() const override { return "X86 cmov Conversion"; }
77  bool runOnMachineFunction(MachineFunction &MF) override;
78  void getAnalysisUsage(AnalysisUsage &AU) const override;
79 
80 private:
81  /// Pass identification, replacement for typeid.
82  static char ID;
83 
84  const MachineRegisterInfo *MRI;
85  const TargetInstrInfo *TII;
86  TargetSchedModel TSchedModel;
87 
88  /// List of consecutive CMOV instructions.
89  typedef SmallVector<MachineInstr *, 2> CmovGroup;
90  typedef SmallVector<CmovGroup, 2> CmovGroups;
91 
92  /// Collect all CMOV-group-candidates in \p CurrLoop and update \p
93  /// CmovInstGroups accordingly.
94  ///
95  /// \param CurrLoop Loop being processed.
96  /// \param CmovInstGroups List of consecutive CMOV instructions in CurrLoop.
97  /// \returns true iff it found any CMOV-group-candidate.
98  bool collectCmovCandidates(MachineLoop *CurrLoop, CmovGroups &CmovInstGroups);
99 
100  /// Check if it is profitable to transform each CMOV-group-candidates into
101  /// branch. Remove all groups that are not profitable from \p CmovInstGroups.
102  ///
103  /// \param CurrLoop Loop being processed.
104  /// \param CmovInstGroups List of consecutive CMOV instructions in CurrLoop.
105  /// \returns true iff any CMOV-group-candidate remain.
106  bool checkForProfitableCmovCandidates(MachineLoop *CurrLoop,
107  CmovGroups &CmovInstGroups);
108 
109  /// Convert the given list of consecutive CMOV instructions into a branch.
110  ///
111  /// \param Group Consecutive CMOV instructions to be converted into branch.
112  void convertCmovInstsToBranches(SmallVectorImpl<MachineInstr *> &Group) const;
113 };
114 
115 char X86CmovConverterPass::ID = 0;
116 
117 void X86CmovConverterPass::getAnalysisUsage(AnalysisUsage &AU) const {
120 }
121 
122 bool X86CmovConverterPass::runOnMachineFunction(MachineFunction &MF) {
123  if (skipFunction(*MF.getFunction()))
124  return false;
125  if (!EnableCmovConverter)
126  return false;
127 
128  DEBUG(dbgs() << "********** " << getPassName() << " : " << MF.getName()
129  << "**********\n");
130 
131  bool Changed = false;
132  MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
133  const TargetSubtargetInfo &STI = MF.getSubtarget();
134  MRI = &MF.getRegInfo();
135  TII = STI.getInstrInfo();
136  TSchedModel.init(STI.getSchedModel(), &STI, TII);
137 
138  //===--------------------------------------------------------------------===//
139  // Algorithm
140  // ---------
141  // For each inner most loop
142  // collectCmovCandidates() {
143  // Find all CMOV-group-candidates.
144  // }
145  //
146  // checkForProfitableCmovCandidates() {
147  // * Calculate both loop-depth and optimized-loop-depth.
148  // * Use these depth to check for loop transformation profitability.
149  // * Check for CMOV-group-candidate transformation profitability.
150  // }
151  //
152  // For each profitable CMOV-group-candidate
153  // convertCmovInstsToBranches() {
154  // * Create FalseBB, SinkBB, Conditional branch to SinkBB.
155  // * Replace each CMOV instruction with a PHI instruction in SinkBB.
156  // }
157  //
158  // Note: For more details, see each function description.
159  //===--------------------------------------------------------------------===//
160  for (MachineBasicBlock &MBB : MF) {
161  MachineLoop *CurrLoop = MLI.getLoopFor(&MBB);
162 
163  // Optimize only inner most loops.
164  if (!CurrLoop || CurrLoop->getHeader() != &MBB ||
165  !CurrLoop->getSubLoops().empty())
166  continue;
167 
168  // List of consecutive CMOV instructions to be processed.
169  CmovGroups CmovInstGroups;
170 
171  if (!collectCmovCandidates(CurrLoop, CmovInstGroups))
172  continue;
173 
174  if (!checkForProfitableCmovCandidates(CurrLoop, CmovInstGroups))
175  continue;
176 
177  Changed = true;
178  for (auto &Group : CmovInstGroups)
179  convertCmovInstsToBranches(Group);
180  }
181  return Changed;
182 }
183 
184 bool X86CmovConverterPass::collectCmovCandidates(MachineLoop *CurrLoop,
185  CmovGroups &CmovInstGroups) {
186  //===--------------------------------------------------------------------===//
187  // Collect all CMOV-group-candidates and add them into CmovInstGroups.
188  //
189  // CMOV-group:
190  // CMOV instructions, in same MBB, that uses same EFLAGS def instruction.
191  //
192  // CMOV-group-candidate:
193  // CMOV-group where all the CMOV instructions are
194  // 1. consecutive.
195  // 2. have same condition code or opposite one.
196  // 3. have only operand registers (X86::CMOVrr).
197  //===--------------------------------------------------------------------===//
198  // List of possible improvement (TODO's):
199  // --------------------------------------
200  // TODO: Add support for X86::CMOVrm instructions.
201  // TODO: Add support for X86::SETcc instructions.
202  // TODO: Add support for CMOV-groups with non consecutive CMOV instructions.
203  //===--------------------------------------------------------------------===//
204 
205  // Current processed CMOV-Group.
206  CmovGroup Group;
207  for (auto *MBB : CurrLoop->getBlocks()) {
208  Group.clear();
209  // Condition code of first CMOV instruction current processed range and its
210  // opposite condition code.
211  X86::CondCode FirstCC, FirstOppCC;
212  // Indicator of a non CMOVrr instruction in the current processed range.
213  bool FoundNonCMOVInst = false;
214  // Indicator for current processed CMOV-group if it should be skipped.
215  bool SkipGroup = false;
216 
217  for (auto &I : *MBB) {
218  X86::CondCode CC = X86::getCondFromCMovOpc(I.getOpcode());
219  // Check if we found a X86::CMOVrr instruction.
220  if (CC != X86::COND_INVALID && !I.mayLoad()) {
221  if (Group.empty()) {
222  // We found first CMOV in the range, reset flags.
223  FirstCC = CC;
224  FirstOppCC = X86::GetOppositeBranchCondition(CC);
225  FoundNonCMOVInst = false;
226  SkipGroup = false;
227  }
228  Group.push_back(&I);
229  // Check if it is a non-consecutive CMOV instruction or it has different
230  // condition code than FirstCC or FirstOppCC.
231  if (FoundNonCMOVInst || (CC != FirstCC && CC != FirstOppCC))
232  // Mark the SKipGroup indicator to skip current processed CMOV-Group.
233  SkipGroup = true;
234  continue;
235  }
236  // If Group is empty, keep looking for first CMOV in the range.
237  if (Group.empty())
238  continue;
239 
240  // We found a non X86::CMOVrr instruction.
241  FoundNonCMOVInst = true;
242  // Check if this instruction define EFLAGS, to determine end of processed
243  // range, as there would be no more instructions using current EFLAGS def.
244  if (I.definesRegister(X86::EFLAGS)) {
245  // Check if current processed CMOV-group should not be skipped and add
246  // it as a CMOV-group-candidate.
247  if (!SkipGroup)
248  CmovInstGroups.push_back(Group);
249  else
250  ++NumOfSkippedCmovGroups;
251  Group.clear();
252  }
253  }
254  // End of basic block is considered end of range, check if current processed
255  // CMOV-group should not be skipped and add it as a CMOV-group-candidate.
256  if (Group.empty())
257  continue;
258  if (!SkipGroup)
259  CmovInstGroups.push_back(Group);
260  else
261  ++NumOfSkippedCmovGroups;
262  }
263 
264  NumOfCmovGroupCandidate += CmovInstGroups.size();
265  return !CmovInstGroups.empty();
266 }
267 
268 /// \returns Depth of CMOV instruction as if it was converted into branch.
269 /// \param TrueOpDepth depth cost of CMOV true value operand.
270 /// \param FalseOpDepth depth cost of CMOV false value operand.
271 static unsigned getDepthOfOptCmov(unsigned TrueOpDepth, unsigned FalseOpDepth) {
272  //===--------------------------------------------------------------------===//
273  // With no info about branch weight, we assume 50% for each value operand.
274  // Thus, depth of optimized CMOV instruction is the rounded up average of
275  // its True-Operand-Value-Depth and False-Operand-Value-Depth.
276  //===--------------------------------------------------------------------===//
277  return (TrueOpDepth + FalseOpDepth + 1) / 2;
278 }
279 
280 bool X86CmovConverterPass::checkForProfitableCmovCandidates(
281  MachineLoop *CurrLoop, CmovGroups &CmovInstGroups) {
282  struct DepthInfo {
283  /// Depth of original loop.
284  unsigned Depth;
285  /// Depth of optimized loop.
286  unsigned OptDepth;
287  };
288  /// Number of loop iterations to calculate depth for ?!
289  static const unsigned LoopIterations = 2;
291  DepthInfo LoopDepth[LoopIterations] = {{0, 0}, {0, 0}};
292  enum { PhyRegType = 0, VirRegType = 1, RegTypeNum = 2 };
293  /// For each register type maps the register to its last def instruction.
294  DenseMap<unsigned, MachineInstr *> RegDefMaps[RegTypeNum];
295  /// Maps register operand to its def instruction, which can be nullptr if it
296  /// is unknown (e.g., operand is defined outside the loop).
298 
299  // Set depth of unknown instruction (i.e., nullptr) to zero.
300  DepthMap[nullptr] = {0, 0};
301 
302  SmallPtrSet<MachineInstr *, 4> CmovInstructions;
303  for (auto &Group : CmovInstGroups)
304  CmovInstructions.insert(Group.begin(), Group.end());
305 
306  //===--------------------------------------------------------------------===//
307  // Step 1: Calculate instruction depth and loop depth.
308  // Optimized-Loop:
309  // loop with CMOV-group-candidates converted into branches.
310  //
311  // Instruction-Depth:
312  // instruction latency + max operand depth.
313  // * For CMOV instruction in optimized loop the depth is calculated as:
314  // CMOV latency + getDepthOfOptCmov(True-Op-Depth, False-Op-depth)
315  // TODO: Find a better way to estimate the latency of the branch instruction
316  // rather than using the CMOV latency.
317  //
318  // Loop-Depth:
319  // max instruction depth of all instructions in the loop.
320  // Note: instruction with max depth represents the critical-path in the loop.
321  //
322  // Loop-Depth[i]:
323  // Loop-Depth calculated for first `i` iterations.
324  // Note: it is enough to calculate depth for up to two iterations.
325  //
326  // Depth-Diff[i]:
327  // Number of cycles saved in first 'i` iterations by optimizing the loop.
328  //===--------------------------------------------------------------------===//
329  for (unsigned I = 0; I < LoopIterations; ++I) {
330  DepthInfo &MaxDepth = LoopDepth[I];
331  for (auto *MBB : CurrLoop->getBlocks()) {
332  // Clear physical registers Def map.
333  RegDefMaps[PhyRegType].clear();
334  for (MachineInstr &MI : *MBB) {
335  unsigned MIDepth = 0;
336  unsigned MIDepthOpt = 0;
337  bool IsCMOV = CmovInstructions.count(&MI);
338  for (auto &MO : MI.uses()) {
339  // Checks for "isUse()" as "uses()" returns also implicit definitions.
340  if (!MO.isReg() || !MO.isUse())
341  continue;
342  unsigned Reg = MO.getReg();
343  auto &RDM = RegDefMaps[TargetRegisterInfo::isVirtualRegister(Reg)];
344  if (MachineInstr *DefMI = RDM.lookup(Reg)) {
345  OperandToDefMap[&MO] = DefMI;
346  DepthInfo Info = DepthMap.lookup(DefMI);
347  MIDepth = std::max(MIDepth, Info.Depth);
348  if (!IsCMOV)
349  MIDepthOpt = std::max(MIDepthOpt, Info.OptDepth);
350  }
351  }
352 
353  if (IsCMOV)
354  MIDepthOpt = getDepthOfOptCmov(
355  DepthMap[OperandToDefMap.lookup(&MI.getOperand(1))].OptDepth,
356  DepthMap[OperandToDefMap.lookup(&MI.getOperand(2))].OptDepth);
357 
358  // Iterates over all operands to handle implicit definitions as well.
359  for (auto &MO : MI.operands()) {
360  if (!MO.isReg() || !MO.isDef())
361  continue;
362  unsigned Reg = MO.getReg();
363  RegDefMaps[TargetRegisterInfo::isVirtualRegister(Reg)][Reg] = &MI;
364  }
365 
366  unsigned Latency = TSchedModel.computeInstrLatency(&MI);
367  DepthMap[&MI] = {MIDepth += Latency, MIDepthOpt += Latency};
368  MaxDepth.Depth = std::max(MaxDepth.Depth, MIDepth);
369  MaxDepth.OptDepth = std::max(MaxDepth.OptDepth, MIDepthOpt);
370  }
371  }
372  }
373 
374  unsigned Diff[LoopIterations] = {LoopDepth[0].Depth - LoopDepth[0].OptDepth,
375  LoopDepth[1].Depth - LoopDepth[1].OptDepth};
376 
377  //===--------------------------------------------------------------------===//
378  // Step 2: Check if Loop worth to be optimized.
379  // Worth-Optimize-Loop:
380  // case 1: Diff[1] == Diff[0]
381  // Critical-path is iteration independent - there is no dependency
382  // of critical-path instructions on critical-path instructions of
383  // previous iteration.
384  // Thus, it is enough to check gain percent of 1st iteration -
385  // To be conservative, the optimized loop need to have a depth of
386  // 12.5% cycles less than original loop, per iteration.
387  //
388  // case 2: Diff[1] > Diff[0]
389  // Critical-path is iteration dependent - there is dependency of
390  // critical-path instructions on critical-path instructions of
391  // previous iteration.
392  // Thus, it is required to check the gradient of the gain - the
393  // change in Depth-Diff compared to the change in Loop-Depth between
394  // 1st and 2nd iterations.
395  // To be conservative, the gradient need to be at least 50%.
396  //
397  // If loop is not worth optimizing, remove all CMOV-group-candidates.
398  //===--------------------------------------------------------------------===//
399  bool WorthOptLoop = false;
400  if (Diff[1] == Diff[0])
401  WorthOptLoop = Diff[0] * 8 >= LoopDepth[0].Depth;
402  else if (Diff[1] > Diff[0])
403  WorthOptLoop =
404  (Diff[1] - Diff[0]) * 2 >= (LoopDepth[1].Depth - LoopDepth[0].Depth);
405 
406  if (!WorthOptLoop)
407  return false;
408 
409  ++NumOfLoopCandidate;
410 
411  //===--------------------------------------------------------------------===//
412  // Step 3: Check for each CMOV-group-candidate if it worth to be optimized.
413  // Worth-Optimize-Group:
414  // Iff it worths to optimize all CMOV instructions in the group.
415  //
416  // Worth-Optimize-CMOV:
417  // Predicted branch is faster than CMOV by the difference between depth of
418  // condition operand and depth of taken (predicted) value operand.
419  // To be conservative, the gain of such CMOV transformation should cover at
420  // at least 25% of branch-misprediction-penalty.
421  //===--------------------------------------------------------------------===//
422  unsigned MispredictPenalty = TSchedModel.getMCSchedModel()->MispredictPenalty;
423  CmovGroups TempGroups;
424  std::swap(TempGroups, CmovInstGroups);
425  for (auto &Group : TempGroups) {
426  bool WorthOpGroup = true;
427  for (auto *MI : Group) {
428  // Avoid CMOV instruction which value is used as a pointer to load from.
429  // This is another conservative check to avoid converting CMOV instruction
430  // used with tree-search like algorithm, where the branch is unpredicted.
431  auto UIs = MRI->use_instructions(MI->defs().begin()->getReg());
432  if (UIs.begin() != UIs.end() && ++UIs.begin() == UIs.end()) {
433  unsigned Op = UIs.begin()->getOpcode();
434  if (Op == X86::MOV64rm || Op == X86::MOV32rm) {
435  WorthOpGroup = false;
436  break;
437  }
438  }
439 
440  unsigned CondCost =
441  DepthMap[OperandToDefMap.lookup(&MI->getOperand(3))].Depth;
442  unsigned ValCost = getDepthOfOptCmov(
443  DepthMap[OperandToDefMap.lookup(&MI->getOperand(1))].Depth,
444  DepthMap[OperandToDefMap.lookup(&MI->getOperand(2))].Depth);
445  if (ValCost > CondCost || (CondCost - ValCost) * 4 < MispredictPenalty) {
446  WorthOpGroup = false;
447  break;
448  }
449  }
450 
451  if (WorthOpGroup)
452  CmovInstGroups.push_back(Group);
453  }
454 
455  return !CmovInstGroups.empty();
456 }
457 
458 static bool checkEFLAGSLive(MachineInstr *MI) {
459  if (MI->killsRegister(X86::EFLAGS))
460  return false;
461 
462  // The EFLAGS operand of MI might be missing a kill marker.
463  // Figure out whether EFLAGS operand should LIVE after MI instruction.
464  MachineBasicBlock *BB = MI->getParent();
466 
467  // Scan forward through BB for a use/def of EFLAGS.
468  for (auto I = std::next(ItrMI), E = BB->end(); I != E; ++I) {
469  if (I->readsRegister(X86::EFLAGS))
470  return true;
471  if (I->definesRegister(X86::EFLAGS))
472  return false;
473  }
474 
475  // We hit the end of the block, check whether EFLAGS is live into a successor.
476  for (auto I = BB->succ_begin(), E = BB->succ_end(); I != E; ++I) {
477  if ((*I)->isLiveIn(X86::EFLAGS))
478  return true;
479  }
480 
481  return false;
482 }
483 
484 void X86CmovConverterPass::convertCmovInstsToBranches(
485  SmallVectorImpl<MachineInstr *> &Group) const {
486  assert(!Group.empty() && "No CMOV instructions to convert");
487  ++NumOfOptimizedCmovGroups;
488 
489  // To convert a CMOVcc instruction, we actually have to insert the diamond
490  // control-flow pattern. The incoming instruction knows the destination vreg
491  // to set, the condition code register to branch on, the true/false values to
492  // select between, and a branch opcode to use.
493 
494  // Before
495  // -----
496  // MBB:
497  // cond = cmp ...
498  // v1 = CMOVge t1, f1, cond
499  // v2 = CMOVlt t2, f2, cond
500  // v3 = CMOVge v1, f3, cond
501  //
502  // After
503  // -----
504  // MBB:
505  // cond = cmp ...
506  // jge %SinkMBB
507  //
508  // FalseMBB:
509  // jmp %SinkMBB
510  //
511  // SinkMBB:
512  // %v1 = phi[%f1, %FalseMBB], [%t1, %MBB]
513  // %v2 = phi[%t2, %FalseMBB], [%f2, %MBB] ; For CMOV with OppCC switch
514  // ; true-value with false-value
515  // %v3 = phi[%f3, %FalseMBB], [%t1, %MBB] ; Phi instruction cannot use
516  // ; previous Phi instruction result
517 
518  MachineInstr &MI = *Group.front();
519  MachineInstr *LastCMOV = Group.back();
520  DebugLoc DL = MI.getDebugLoc();
523  MachineBasicBlock *MBB = MI.getParent();
525  MachineFunction *F = MBB->getParent();
526  const BasicBlock *BB = MBB->getBasicBlock();
527 
528  MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(BB);
529  MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(BB);
530  F->insert(It, FalseMBB);
531  F->insert(It, SinkMBB);
532 
533  // If the EFLAGS register isn't dead in the terminator, then claim that it's
534  // live into the sink and copy blocks.
535  if (checkEFLAGSLive(LastCMOV)) {
536  FalseMBB->addLiveIn(X86::EFLAGS);
537  SinkMBB->addLiveIn(X86::EFLAGS);
538  }
539 
540  // Transfer the remainder of BB and its successor edges to SinkMBB.
541  SinkMBB->splice(SinkMBB->begin(), MBB,
542  std::next(MachineBasicBlock::iterator(LastCMOV)), MBB->end());
543  SinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
544 
545  // Add the false and sink blocks as its successors.
546  MBB->addSuccessor(FalseMBB);
547  MBB->addSuccessor(SinkMBB);
548 
549  // Create the conditional branch instruction.
550  BuildMI(MBB, DL, TII->get(X86::GetCondBranchFromCond(CC))).addMBB(SinkMBB);
551 
552  // Add the sink block to the false block successors.
553  FalseMBB->addSuccessor(SinkMBB);
554 
558  std::next(MachineBasicBlock::iterator(LastCMOV));
559  MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
560  // As we are creating the PHIs, we have to be careful if there is more than
561  // one. Later CMOVs may reference the results of earlier CMOVs, but later
562  // PHIs have to reference the individual true/false inputs from earlier PHIs.
563  // That also means that PHI construction must work forward from earlier to
564  // later, and that the code must maintain a mapping from earlier PHI's
565  // destination registers, and the registers that went into the PHI.
567 
568  for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
569  unsigned DestReg = MIIt->getOperand(0).getReg();
570  unsigned Op1Reg = MIIt->getOperand(1).getReg();
571  unsigned Op2Reg = MIIt->getOperand(2).getReg();
572 
573  // If this CMOV we are processing is the opposite condition from the jump we
574  // generated, then we have to swap the operands for the PHI that is going to
575  // be generated.
576  if (X86::getCondFromCMovOpc(MIIt->getOpcode()) == OppCC)
577  std::swap(Op1Reg, Op2Reg);
578 
579  auto Op1Itr = RegRewriteTable.find(Op1Reg);
580  if (Op1Itr != RegRewriteTable.end())
581  Op1Reg = Op1Itr->second.first;
582 
583  auto Op2Itr = RegRewriteTable.find(Op2Reg);
584  if (Op2Itr != RegRewriteTable.end())
585  Op2Reg = Op2Itr->second.second;
586 
587  // SinkMBB:
588  // %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, MBB ]
589  // ...
590  MIB = BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(X86::PHI), DestReg)
591  .addReg(Op1Reg)
592  .addMBB(FalseMBB)
593  .addReg(Op2Reg)
594  .addMBB(MBB);
595  (void)MIB;
596  DEBUG(dbgs() << "\tFrom: "; MIIt->dump());
597  DEBUG(dbgs() << "\tTo: "; MIB->dump());
598 
599  // Add this PHI to the rewrite table.
600  RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
601  }
602 
603  // Now remove the CMOV(s).
604  MBB->erase(MIItBegin, MIItEnd);
605 }
606 
607 } // End anonymous namespace.
608 
610  return new X86CmovConverterPass();
611 }
unsigned GetCondBranchFromCond(CondCode CC)
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:166
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
STATISTIC(NumFunctions,"Total number of functions")
CondCode getCondFromCMovOpc(unsigned Opc)
Return condition code of a CMov opcode.
DataLayout DL
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
A debug info location.
Definition: DebugLoc.h:34
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
const std::vector< BlockT * > & getBlocks() const
Get a list of the basic blocks which make up this loop.
Definition: LoopInfo.h:140
BlockT * getHeader() const
Definition: LoopInfo.h:103
AnalysisUsage & addRequired()
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Provide an instruction scheduling machine model to CodeGen passes.
const HexagonInstrInfo * TII
FunctionPass * createX86CmovConverterPass()
This pass converts X86 cmov instructions into branch when profitable.
Reg
All possible values of the reg field in the ModR/M byte.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
#define F(x, y, z)
Definition: MD5.cpp:55
void dump() const
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *bb=nullptr)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:279
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:139
TargetInstrInfo - Interface to description of machine instruction set.
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:401
MachineInstrBundleIterator< MachineInstr > iterator
void addLiveIn(MCPhysReg PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
unsigned const MachineRegisterInfo * MRI
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:372
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
self_iterator getIterator()
Definition: ilist_node.h:82
const unsigned MaxDepth
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:423
#define E
Definition: LargeTest.cpp:27
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
CondCode GetOppositeBranchCondition(CondCode CC)
GetOppositeBranchCondition - Return the inverse of the specified cond, e.g.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:383
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:923
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:257
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
TargetSubtargetInfo - Generic base class for all target subtargets.
Representation of each machine instruction.
Definition: MachineInstr.h:59
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
#define I(x, y, z)
Definition: MD5.cpp:58
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void insert(iterator MBBI, MachineBasicBlock *MBB)
bool killsRegister(unsigned Reg, const TargetRegisterInfo *TRI=nullptr) const
Return true if the MachineInstr kills the specified register.
Definition: MachineInstr.h:913
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned char TargetFlags=0) const
#define DEBUG(X)
Definition: Debug.h:118
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
Definition: LoopInfo.h:128
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.