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