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