LLVM 24.0.0git
X86CmovConversion.cpp
Go to the documentation of this file.
1//====- X86CmovConversion.cpp - Convert Cmov to Branch --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// This file implements a pass that converts X86 cmov instructions into
11/// branches when profitable. This pass is conservative. It transforms if and
12/// only if it can guarantee a gain with high confidence.
13///
14/// Thus, the optimization applies under the following conditions:
15/// 1. Consider as candidates only CMOVs in innermost loops (assume that
16/// most hotspots are represented by these loops).
17/// 2. Given a group of CMOV instructions that are using the same EFLAGS def
18/// instruction:
19/// a. Consider them as candidates only if all have the same code condition
20/// or the opposite one to prevent generating more than one conditional
21/// jump per EFLAGS def instruction.
22/// b. Consider them as candidates only if all are profitable to be
23/// converted (assume that one bad conversion may cause a degradation).
24/// 3. Apply conversion only for loops that are found profitable and only for
25/// CMOV candidates that were found profitable.
26/// a. A loop is considered profitable only if conversion will reduce its
27/// depth cost by some threshold.
28/// b. CMOV is considered profitable if the cost of its condition is higher
29/// than the average cost of its true-value and false-value by 25% of
30/// branch-misprediction-penalty. This assures no degradation even with
31/// 25% branch misprediction.
32///
33/// Note: This pass is assumed to run on SSA machine code.
34//
35//===----------------------------------------------------------------------===//
36//
37// External interfaces:
38// FunctionPass *llvm::createX86CmovConverterPass();
39// bool X86CmovConverterPass::runOnMachineFunction(MachineFunction &MF);
40//
41//===----------------------------------------------------------------------===//
42
43#include "X86.h"
44#include "X86InstrInfo.h"
45#include "X86Subtarget.h"
46#include "llvm/ADT/ArrayRef.h"
47#include "llvm/ADT/DenseMap.h"
48#include "llvm/ADT/STLExtras.h"
51#include "llvm/ADT/Statistic.h"
65#include "llvm/IR/DebugLoc.h"
67#include "llvm/MC/MCSchedule.h"
68#include "llvm/Pass.h"
69#include "llvm/Support/Debug.h"
72#include <algorithm>
73#include <cassert>
74#include <iterator>
75#include <utility>
76
77using namespace llvm;
78
79#define DEBUG_TYPE "x86-cmov-conversion"
80
81STATISTIC(NumOfSkippedCmovGroups, "Number of unsupported CMOV-groups");
82STATISTIC(NumOfCmovGroupCandidate, "Number of CMOV-group candidates");
83STATISTIC(NumOfLoopCandidate, "Number of CMOV-conversion profitable loops");
84STATISTIC(NumOfOptimizedCmovGroups, "Number of optimized CMOV-groups");
85
86namespace {
87
88/// Converts X86 cmov instructions into branches when profitable.
89class X86CmovConversionImpl {
90public:
91 X86CmovConversionImpl(MachineLoopInfo *MLI) : MLI(MLI) {}
92
93 bool runOnMachineFunction(MachineFunction &MF);
94
95private:
96 MachineRegisterInfo *MRI = nullptr;
97 const TargetInstrInfo *TII = nullptr;
98 const X86Subtarget *STI = nullptr;
99 MachineLoopInfo *MLI = nullptr;
100 TargetSchedModel TSchedModel;
101
102 /// List of consecutive CMOV instructions.
103 using CmovGroup = SmallVector<MachineInstr *, 2>;
104 using CmovGroups = SmallVector<CmovGroup, 2>;
105
106 /// Unfold the load of each NDD CMOV left with a non-RIP-relative memory
107 /// operand. Return true if any CMOV was unfolded.
108 bool unfoldNDDMemCmovs(MachineFunction &MF);
109
110 /// Collect all CMOV-group-candidates in \p CurrLoop and update \p
111 /// CmovInstGroups accordingly.
112 ///
113 /// \param Blocks List of blocks to process.
114 /// \param CmovInstGroups List of consecutive CMOV instructions in CurrLoop.
115 /// \returns true iff it found any CMOV-group-candidate.
116 bool collectCmovCandidates(ArrayRef<MachineBasicBlock *> Blocks,
117 CmovGroups &CmovInstGroups,
118 bool IncludeLoads = false);
119
120 /// Check if it is profitable to transform each CMOV-group-candidates into
121 /// branch. Remove all groups that are not profitable from \p CmovInstGroups.
122 ///
123 /// \param Blocks List of blocks to process.
124 /// \param CmovInstGroups List of consecutive CMOV instructions in CurrLoop.
125 /// \returns true iff any CMOV-group-candidate remain.
126 bool checkForProfitableCmovCandidates(ArrayRef<MachineBasicBlock *> Blocks,
127 CmovGroups &CmovInstGroups);
128
129 /// Convert the given list of consecutive CMOV instructions into a branch.
130 ///
131 /// \param Group Consecutive CMOV instructions to be converted into branch.
132 void convertCmovInstsToBranches(SmallVectorImpl<MachineInstr *> &Group) const;
133};
134
135class X86CmovConversionLegacy : public MachineFunctionPass {
136public:
137 X86CmovConversionLegacy() : MachineFunctionPass(ID) {}
138
139 StringRef getPassName() const override { return "X86 cmov Conversion"; }
140 bool runOnMachineFunction(MachineFunction &MF) override;
141 void getAnalysisUsage(AnalysisUsage &AU) const override;
142
143 /// Pass identification, replacement for typeid.
144 static char ID;
145};
146
147} // end anonymous namespace
148
149char X86CmovConversionLegacy::ID = 0;
150
151void X86CmovConversionLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
153 AU.addRequired<MachineLoopInfoWrapperPass>();
154 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
155}
156
157bool X86CmovConversionImpl::runOnMachineFunction(MachineFunction &MF) {
158 STI = &MF.getSubtarget<X86Subtarget>();
159 const X86Options &CLOpts = STI->getCLOpts();
160 // Keep the early exits in sync with X86::foldNDDCmovLoads().
161 if (!CLOpts.cmov_converter)
162 return false;
163
164 // If the SelectOptimize pass is enabled, cmovs have already been optimized.
166 return false;
167
168 LLVM_DEBUG(dbgs() << "********** " << DEBUG_TYPE << " : " << MF.getName()
169 << "**********\n");
170
171 bool Changed = false;
172 MRI = &MF.getRegInfo();
173 TII = STI->getInstrInfo();
174 TSchedModel.init(STI);
175
176 // Before we handle the more subtle cases of register-register CMOVs inside
177 // of potentially hot loops, we want to quickly remove all CMOVs
178 // (cmov_converter_force_all) or the ones with a memory operand
179 // (cmov_converter_force_mem_operand). The latter CMOV will risk a stall
180 // waiting for the load to complete that speculative execution behind a branch
181 // is better suited to handle on modern x86 chips.
182 if (CLOpts.cmov_converter_force_mem_operand ||
183 CLOpts.cmov_converter_force_all) {
184 CmovGroups AllCmovGroups;
185 SmallVector<MachineBasicBlock *, 4> Blocks(llvm::make_pointer_range(MF));
186 if (collectCmovCandidates(Blocks, AllCmovGroups, /*IncludeLoads*/ true)) {
187 for (auto &Group : AllCmovGroups) {
188 // Skip any group that doesn't do at least one memory operand cmov.
189 if (CLOpts.cmov_converter_force_mem_operand &&
190 !CLOpts.cmov_converter_force_all &&
191 llvm::none_of(Group, [&](MachineInstr *I) { return I->mayLoad(); }))
192 continue;
193
194 // For CMOV groups which we can rewrite and which contain a memory load,
195 // always rewrite them. On x86, a CMOV will dramatically amplify any
196 // memory latency by blocking speculative execution.
197 Changed = true;
198 convertCmovInstsToBranches(Group);
199 }
200 }
201 // ISel folded non-RIP-relative loads into NDD CMOVs only for this
202 // conversion, so unfold them where the CMOV is kept.
203 if (X86::foldNDDCmovLoads(*STI, MF.getTarget()))
204 Changed |= unfoldNDDMemCmovs(MF);
205 // Early return as cmov_converter_force_all converts all CmovGroups.
206 if (CLOpts.cmov_converter_force_all)
207 return Changed;
208 }
209
210 //===--------------------------------------------------------------------===//
211 // Register-operand Conversion Algorithm
212 // ---------
213 // For each innermost loop
214 // collectCmovCandidates() {
215 // Find all CMOV-group-candidates.
216 // }
217 //
218 // checkForProfitableCmovCandidates() {
219 // * Calculate both loop-depth and optimized-loop-depth.
220 // * Use these depth to check for loop transformation profitability.
221 // * Check for CMOV-group-candidate transformation profitability.
222 // }
223 //
224 // For each profitable CMOV-group-candidate
225 // convertCmovInstsToBranches() {
226 // * Create FalseBB, SinkBB, Conditional branch to SinkBB.
227 // * Replace each CMOV instruction with a PHI instruction in SinkBB.
228 // }
229 //
230 // Note: For more details, see each function description.
231 //===--------------------------------------------------------------------===//
232
233 // Build up the loops in pre-order.
235 // Note that we need to check size on each iteration as we accumulate child
236 // loops.
237 for (int i = 0; i < (int)Loops.size(); ++i)
238 llvm::append_range(Loops, Loops[i]->getSubLoops());
239
240 for (MachineLoop *CurrLoop : Loops) {
241 // Optimize only innermost loops.
242 if (!CurrLoop->getSubLoops().empty())
243 continue;
244
245 // List of consecutive CMOV instructions to be processed.
246 CmovGroups CmovInstGroups;
247
248 if (!collectCmovCandidates(CurrLoop->getBlocks(), CmovInstGroups))
249 continue;
250
251 if (!checkForProfitableCmovCandidates(CurrLoop->getBlocks(),
252 CmovInstGroups))
253 continue;
254
255 Changed = true;
256 for (auto &Group : CmovInstGroups)
257 convertCmovInstsToBranches(Group);
258 }
259
260 return Changed;
261}
262
263bool X86CmovConversionImpl::unfoldNDDMemCmovs(MachineFunction &MF) {
264 bool Changed = false;
265 for (MachineBasicBlock &MBB : MF) {
266 for (MachineInstr &MI : make_early_inc_range(MBB)) {
267 unsigned Opc = MI.getOpcode();
268 if (Opc != X86::CMOV16rm_ND && Opc != X86::CMOV32rm_ND &&
269 Opc != X86::CMOV64rm_ND)
270 continue;
271 const MachineOperand &Base =
273 if (Base.isReg() && Base.getReg() == X86::RIP)
274 continue;
275
277 MRI->getRegClass(MI.getOperand(0).getReg()));
278 SmallVector<MachineInstr *, 2> NewMIs;
279 [[maybe_unused]] bool Unfolded =
280 TII->unfoldMemoryOperand(MF, MI, Reg, /*UnfoldLoad=*/true,
281 /*UnfoldStore=*/false, NewMIs);
282 assert(Unfolded && "Should never fail to unfold a loading cmov!");
283 for (MachineInstr *NewMI : NewMIs)
284 MBB.insert(MI.getIterator(), NewMI);
285 MachineInstr *NewCmov = NewMIs.back();
286 NewCmov->setFlags(MI.getFlags());
287 if (unsigned DebugInstrNum = MI.peekDebugInstrNum())
288 NewCmov->setDebugInstrNum(DebugInstrNum);
289 LLVM_DEBUG(dbgs() << "\tUnfolded NDD CMOV: "; NewCmov->dump());
290 MI.eraseFromParent();
291 Changed = true;
292 }
293 }
294 return Changed;
295}
296
297bool X86CmovConversionImpl::collectCmovCandidates(
298 ArrayRef<MachineBasicBlock *> Blocks, CmovGroups &CmovInstGroups,
299 bool IncludeLoads) {
300 //===--------------------------------------------------------------------===//
301 // Collect all CMOV-group-candidates and add them into CmovInstGroups.
302 //
303 // CMOV-group:
304 // CMOV instructions, in same MBB, that uses same EFLAGS def instruction.
305 //
306 // CMOV-group-candidate:
307 // CMOV-group where all the CMOV instructions are
308 // 1. consecutive.
309 // 2. have same condition code or opposite one.
310 // 3. have only operand registers (X86::CMOVrr).
311 //===--------------------------------------------------------------------===//
312 // List of possible improvement (TODO's):
313 // --------------------------------------
314 // TODO: Add support for X86::CMOVrm instructions.
315 // TODO: Add support for X86::SETcc instructions.
316 // TODO: Add support for CMOV-groups with non consecutive CMOV instructions.
317 //===--------------------------------------------------------------------===//
318
319 // Current processed CMOV-Group.
320 CmovGroup Group;
321 for (auto *MBB : Blocks) {
322 Group.clear();
323 // Condition code of first CMOV instruction current processed range and its
324 // opposite condition code.
325 X86::CondCode FirstCC = X86::COND_INVALID, FirstOppCC = X86::COND_INVALID,
326 MemOpCC = X86::COND_INVALID;
327 // Indicator of a non CMOVrr instruction in the current processed range.
328 bool FoundNonCMOVInst = false;
329 // Indicator for current processed CMOV-group if it should be skipped.
330 bool SkipGroup = false;
331
332 for (auto &I : *MBB) {
333 // Skip debug instructions.
334 if (I.isDebugInstr())
335 continue;
336
338 // Check if we found a X86::CMOVrr instruction. If it is marked as
339 // unpredictable, skip it and do not convert it to branch.
340 if (CC != X86::COND_INVALID &&
341 !I.getFlag(MachineInstr::MIFlag::Unpredictable) &&
342 (IncludeLoads || !I.mayLoad()) && !I.hasOrderedMemoryRef()) {
343 if (Group.empty()) {
344 // We found first CMOV in the range, reset flags.
345 FirstCC = CC;
347 // Clear out the prior group's memory operand CC.
348 MemOpCC = X86::COND_INVALID;
349 FoundNonCMOVInst = false;
350 SkipGroup = false;
351 }
352 Group.push_back(&I);
353 // Check if it is a non-consecutive CMOV instruction or it has different
354 // condition code than FirstCC or FirstOppCC.
355 if (FoundNonCMOVInst || (CC != FirstCC && CC != FirstOppCC))
356 // Mark the SKipGroup indicator to skip current processed CMOV-Group.
357 SkipGroup = true;
358 if (I.mayLoad()) {
359 if (MemOpCC == X86::COND_INVALID)
360 // The first memory operand CMOV.
361 MemOpCC = CC;
362 else if (CC != MemOpCC)
363 // Can't handle mixed conditions with memory operands.
364 SkipGroup = true;
365 }
366 // Check if we were relying on zero-extending behavior of the CMOV.
367 if (!SkipGroup &&
369 MRI->use_nodbg_instructions(I.defs().begin()->getReg()),
370 [&](MachineInstr &UseI) {
371 return UseI.getOpcode() == X86::SUBREG_TO_REG;
372 }))
373 // FIXME: We should model the cost of using an explicit MOV to handle
374 // the zero-extension rather than just refusing to handle this.
375 SkipGroup = true;
376 continue;
377 }
378 // If Group is empty, keep looking for first CMOV in the range.
379 if (Group.empty())
380 continue;
381
382 // We found a non X86::CMOVrr instruction.
383 FoundNonCMOVInst = true;
384 // Check if this instruction define EFLAGS, to determine end of processed
385 // range, as there would be no more instructions using current EFLAGS def.
386 if (I.definesRegister(X86::EFLAGS, /*TRI=*/nullptr)) {
387 // Check if current processed CMOV-group should not be skipped and add
388 // it as a CMOV-group-candidate.
389 if (!SkipGroup)
390 CmovInstGroups.push_back(Group);
391 else
392 ++NumOfSkippedCmovGroups;
393 Group.clear();
394 }
395 }
396 // End of basic block is considered end of range, check if current processed
397 // CMOV-group should not be skipped and add it as a CMOV-group-candidate.
398 if (Group.empty())
399 continue;
400 if (!SkipGroup)
401 CmovInstGroups.push_back(Group);
402 else
403 ++NumOfSkippedCmovGroups;
404 }
405
406 NumOfCmovGroupCandidate += CmovInstGroups.size();
407 return !CmovInstGroups.empty();
408}
409
410/// \returns Depth of CMOV instruction as if it was converted into branch.
411/// \param TrueOpDepth depth cost of CMOV true value operand.
412/// \param FalseOpDepth depth cost of CMOV false value operand.
413static unsigned getDepthOfOptCmov(unsigned TrueOpDepth, unsigned FalseOpDepth) {
414 // The depth of the result after branch conversion is
415 // TrueOpDepth * TrueOpProbability + FalseOpDepth * FalseOpProbability.
416 // As we have no info about branch weight, we assume 75% for one and 25% for
417 // the other, and pick the result with the largest resulting depth.
418 return std::max(
419 divideCeil(TrueOpDepth * 3 + FalseOpDepth, 4),
420 divideCeil(FalseOpDepth * 3 + TrueOpDepth, 4));
421}
422
423bool X86CmovConversionImpl::checkForProfitableCmovCandidates(
424 ArrayRef<MachineBasicBlock *> Blocks, CmovGroups &CmovInstGroups) {
425 struct DepthInfo {
426 /// Depth of original loop.
427 unsigned Depth;
428 /// Depth of optimized loop.
429 unsigned OptDepth;
430 };
431 /// Number of loop iterations to calculate depth for ?!
432 static const unsigned LoopIterations = 2;
433 DenseMap<MachineInstr *, DepthInfo> DepthMap;
434 DepthInfo LoopDepth[LoopIterations] = {{0, 0}, {0, 0}};
435 enum { PhyRegType = 0, VirRegType = 1, RegTypeNum = 2 };
436 /// For each register type maps the register to its last def instruction.
437 DenseMap<Register, MachineInstr *> RegDefMaps[RegTypeNum];
438 /// Maps register operand to its def instruction, which can be nullptr if it
439 /// is unknown (e.g., operand is defined outside the loop).
440 DenseMap<MachineOperand *, MachineInstr *> OperandToDefMap;
441
442 // Set depth of unknown instruction (i.e., nullptr) to zero.
443 DepthMap[nullptr] = {0, 0};
444
445 SmallPtrSet<MachineInstr *, 4> CmovInstructions;
446 for (auto &Group : CmovInstGroups)
447 CmovInstructions.insert_range(Group);
448
449 //===--------------------------------------------------------------------===//
450 // Step 1: Calculate instruction depth and loop depth.
451 // Optimized-Loop:
452 // loop with CMOV-group-candidates converted into branches.
453 //
454 // Instruction-Depth:
455 // instruction latency + max operand depth.
456 // * For CMOV instruction in optimized loop the depth is calculated as:
457 // CMOV latency + getDepthOfOptCmov(True-Op-Depth, False-Op-depth)
458 // TODO: Find a better way to estimate the latency of the branch instruction
459 // rather than using the CMOV latency.
460 //
461 // Loop-Depth:
462 // max instruction depth of all instructions in the loop.
463 // Note: instruction with max depth represents the critical-path in the loop.
464 //
465 // Loop-Depth[i]:
466 // Loop-Depth calculated for first `i` iterations.
467 // Note: it is enough to calculate depth for up to two iterations.
468 //
469 // Depth-Diff[i]:
470 // Number of cycles saved in first 'i` iterations by optimizing the loop.
471 //===--------------------------------------------------------------------===//
472 for (DepthInfo &MaxDepth : LoopDepth) {
473 for (auto *MBB : Blocks) {
474 // Clear physical registers Def map.
475 RegDefMaps[PhyRegType].clear();
476 for (MachineInstr &MI : *MBB) {
477 // Skip debug instructions.
478 if (MI.isDebugInstr())
479 continue;
480 unsigned MIDepth = 0;
481 unsigned MIDepthOpt = 0;
482 bool IsCMOV = CmovInstructions.count(&MI);
483 for (auto &MO : MI.uses()) {
484 // Checks for "isUse()" as "uses()" returns also implicit definitions.
485 if (!MO.isReg() || !MO.isUse())
486 continue;
487 Register Reg = MO.getReg();
488 auto &RDM = RegDefMaps[Reg.isVirtual()];
489 if (MachineInstr *DefMI = RDM.lookup(Reg)) {
490 OperandToDefMap[&MO] = DefMI;
491 DepthInfo Info = DepthMap.lookup(DefMI);
492 MIDepth = std::max(MIDepth, Info.Depth);
493 if (!IsCMOV)
494 MIDepthOpt = std::max(MIDepthOpt, Info.OptDepth);
495 }
496 }
497
498 if (IsCMOV)
499 MIDepthOpt = getDepthOfOptCmov(
500 DepthMap[OperandToDefMap.lookup(&MI.getOperand(1))].OptDepth,
501 DepthMap[OperandToDefMap.lookup(&MI.getOperand(2))].OptDepth);
502
503 // Iterates over all operands to handle implicit definitions as well.
504 for (auto &MO : MI.operands()) {
505 if (!MO.isReg() || !MO.isDef())
506 continue;
507 Register Reg = MO.getReg();
508 RegDefMaps[Reg.isVirtual()][Reg] = &MI;
509 }
510
511 unsigned Latency = TSchedModel.computeInstrLatency(&MI);
512 DepthMap[&MI] = {MIDepth += Latency, MIDepthOpt += Latency};
513 MaxDepth.Depth = std::max(MaxDepth.Depth, MIDepth);
514 MaxDepth.OptDepth = std::max(MaxDepth.OptDepth, MIDepthOpt);
515 }
516 }
517 }
518
519 unsigned Diff[LoopIterations] = {LoopDepth[0].Depth - LoopDepth[0].OptDepth,
520 LoopDepth[1].Depth - LoopDepth[1].OptDepth};
521
522 //===--------------------------------------------------------------------===//
523 // Step 2: Check if Loop worth to be optimized.
524 // Worth-Optimize-Loop:
525 // case 1: Diff[1] == Diff[0]
526 // Critical-path is iteration independent - there is no dependency
527 // of critical-path instructions on critical-path instructions of
528 // previous iteration.
529 // Thus, it is enough to check gain percent of 1st iteration -
530 // To be conservative, the optimized loop need to have a depth of
531 // 12.5% cycles less than original loop, per iteration.
532 //
533 // case 2: Diff[1] > Diff[0]
534 // Critical-path is iteration dependent - there is dependency of
535 // critical-path instructions on critical-path instructions of
536 // previous iteration.
537 // Thus, check the gain percent of the 2nd iteration (similar to the
538 // previous case), but it is also required to check the gradient of
539 // the gain - the change in Depth-Diff compared to the change in
540 // Loop-Depth between 1st and 2nd iterations.
541 // To be conservative, the gradient need to be at least 50%.
542 //
543 // In addition, In order not to optimize loops with very small gain, the
544 // gain (in cycles) after 2nd iteration should not be less than a given
545 // threshold. Thus, the check (Diff[1] >= cmov_converter_threshold) must
546 // apply.
547 //
548 // If loop is not worth optimizing, remove all CMOV-group-candidates.
549 //===--------------------------------------------------------------------===//
550 if (Diff[1] < STI->getCLOpts().cmov_converter_threshold)
551 return false;
552
553 bool WorthOptLoop = false;
554 if (Diff[1] == Diff[0])
555 WorthOptLoop = Diff[0] * 8 >= LoopDepth[0].Depth;
556 else if (Diff[1] > Diff[0])
557 WorthOptLoop =
558 (Diff[1] - Diff[0]) * 2 >= (LoopDepth[1].Depth - LoopDepth[0].Depth) &&
559 (Diff[1] * 8 >= LoopDepth[1].Depth);
560
561 if (!WorthOptLoop)
562 return false;
563
564 ++NumOfLoopCandidate;
565
566 //===--------------------------------------------------------------------===//
567 // Step 3: Check for each CMOV-group-candidate if it worth to be optimized.
568 // Worth-Optimize-Group:
569 // Iff it is worth to optimize all CMOV instructions in the group.
570 //
571 // Worth-Optimize-CMOV:
572 // Predicted branch is faster than CMOV by the difference between depth of
573 // condition operand and depth of taken (predicted) value operand.
574 // To be conservative, the gain of such CMOV transformation should cover at
575 // at least 25% of branch-misprediction-penalty.
576 //===--------------------------------------------------------------------===//
577 unsigned MispredictPenalty = STI->getMispredictionPenalty();
578 CmovGroups TempGroups;
579 std::swap(TempGroups, CmovInstGroups);
580 for (auto &Group : TempGroups) {
581 bool WorthOpGroup = true;
582 for (auto *MI : Group) {
583 // Avoid CMOV instruction which value is used as a pointer to load from.
584 // This is another conservative check to avoid converting CMOV instruction
585 // used with tree-search like algorithm, where the branch is unpredicted.
586 auto UIs = MRI->use_instructions(MI->defs().begin()->getReg());
587 if (hasSingleElement(UIs)) {
588 unsigned Op = UIs.begin()->getOpcode();
589 if (Op == X86::MOV64rm || Op == X86::MOV32rm) {
590 WorthOpGroup = false;
591 break;
592 }
593 }
594
595 unsigned CondCost =
596 DepthMap[OperandToDefMap.lookup(&MI->getOperand(4))].Depth;
597 unsigned ValCost = getDepthOfOptCmov(
598 DepthMap[OperandToDefMap.lookup(&MI->getOperand(1))].Depth,
599 DepthMap[OperandToDefMap.lookup(&MI->getOperand(2))].Depth);
600 if (ValCost > CondCost || (CondCost - ValCost) * 4 < MispredictPenalty) {
601 WorthOpGroup = false;
602 break;
603 }
604 }
605
606 if (WorthOpGroup)
607 CmovInstGroups.push_back(Group);
608 }
609
610 return !CmovInstGroups.empty();
611}
612
614 if (MI->killsRegister(X86::EFLAGS, /*TRI=*/nullptr))
615 return false;
616
617 // The EFLAGS operand of MI might be missing a kill marker.
618 // Figure out whether EFLAGS operand should LIVE after MI instruction.
619 MachineBasicBlock *BB = MI->getParent();
621
622 // Scan forward through BB for a use/def of EFLAGS.
623 for (auto I = std::next(ItrMI), E = BB->end(); I != E; ++I) {
624 if (I->readsRegister(X86::EFLAGS, /*TRI=*/nullptr))
625 return true;
626 if (I->definesRegister(X86::EFLAGS, /*TRI=*/nullptr))
627 return false;
628 }
629
630 // We hit the end of the block, check whether EFLAGS is live into a successor.
631 for (MachineBasicBlock *Succ : BB->successors())
632 if (Succ->isLiveIn(X86::EFLAGS))
633 return true;
634
635 return false;
636}
637
638/// Given /p First CMOV instruction and /p Last CMOV instruction representing a
639/// group of CMOV instructions, which may contain debug instructions in between,
640/// move all debug instructions to after the last CMOV instruction, making the
641/// CMOV group consecutive.
644 "Last instruction in a CMOV group must be a CMOV instruction");
645
646 SmallVector<MachineInstr *, 2> DBGInstructions;
647 for (auto I = First->getIterator(), E = Last->getIterator(); I != E; I++) {
648 if (I->isDebugInstr())
649 DBGInstructions.push_back(&*I);
650 }
651
652 // Splice the debug instruction after the cmov group.
653 MachineBasicBlock *MBB = First->getParent();
654 for (auto *MI : DBGInstructions)
655 MBB->insertAfter(Last, MI->removeFromParent());
656}
657
658void X86CmovConversionImpl::convertCmovInstsToBranches(
659 SmallVectorImpl<MachineInstr *> &Group) const {
660 assert(!Group.empty() && "No CMOV instructions to convert");
661 ++NumOfOptimizedCmovGroups;
662
663 // If the CMOV group is not packed, e.g., there are debug instructions between
664 // first CMOV and last CMOV, then pack the group and make the CMOV instruction
665 // consecutive by moving the debug instructions to after the last CMOV.
666 packCmovGroup(Group.front(), Group.back());
667
668 // To convert a CMOVcc instruction, we actually have to insert the diamond
669 // control-flow pattern. The incoming instruction knows the destination vreg
670 // to set, the condition code register to branch on, the true/false values to
671 // select between, and a branch opcode to use.
672
673 // Before
674 // -----
675 // MBB:
676 // cond = cmp ...
677 // v1 = CMOVge t1, f1, cond
678 // v2 = CMOVlt t2, f2, cond
679 // v3 = CMOVge v1, f3, cond
680 //
681 // After
682 // -----
683 // MBB:
684 // cond = cmp ...
685 // jge %SinkMBB
686 //
687 // FalseMBB:
688 // jmp %SinkMBB
689 //
690 // SinkMBB:
691 // %v1 = phi[%f1, %FalseMBB], [%t1, %MBB]
692 // %v2 = phi[%t2, %FalseMBB], [%f2, %MBB] ; For CMOV with OppCC switch
693 // ; true-value with false-value
694 // %v3 = phi[%f3, %FalseMBB], [%t1, %MBB] ; Phi instruction cannot use
695 // ; previous Phi instruction result
696
697 MachineInstr &MI = *Group.front();
698 MachineInstr *LastCMOV = Group.back();
699 DebugLoc DL = MI.getDebugLoc();
700
703 // Potentially swap the condition codes so that any memory operand to a CMOV
704 // is in the *false* position instead of the *true* position. We can invert
705 // any non-memory operand CMOV instructions to cope with this and we ensure
706 // memory operand CMOVs are only included with a single condition code.
707 if (llvm::any_of(Group, [&](MachineInstr *I) {
708 return I->mayLoad() && X86::getCondFromCMov(*I) == CC;
709 }))
710 std::swap(CC, OppCC);
711
712 MachineBasicBlock *MBB = MI.getParent();
715 const BasicBlock *BB = MBB->getBasicBlock();
716
717 MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(BB);
718 MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(BB);
719 F->insert(It, FalseMBB);
720 F->insert(It, SinkMBB);
721
722 // If the EFLAGS register isn't dead in the terminator, then claim that it's
723 // live into the sink and copy blocks.
724 if (checkEFLAGSLive(LastCMOV)) {
725 FalseMBB->addLiveIn(X86::EFLAGS);
726 SinkMBB->addLiveIn(X86::EFLAGS);
727 }
728
729 // Transfer the remainder of BB and its successor edges to SinkMBB.
730 SinkMBB->splice(SinkMBB->begin(), MBB,
731 std::next(MachineBasicBlock::iterator(LastCMOV)), MBB->end());
733
734 // Add the false and sink blocks as its successors.
735 MBB->addSuccessor(FalseMBB);
736 MBB->addSuccessor(SinkMBB);
737
738 // Create the conditional branch instruction.
739 BuildMI(MBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(CC);
740
741 // Add the sink block to the false block successors.
742 FalseMBB->addSuccessor(SinkMBB);
743
744 MachineInstrBuilder MIB;
747 std::next(MachineBasicBlock::iterator(LastCMOV));
748 MachineBasicBlock::iterator FalseInsertionPoint = FalseMBB->begin();
749 MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
750
751 // First we need to insert an explicit load on the false path for any memory
752 // operand. We also need to potentially do register rewriting here, but it is
753 // simpler as the memory operands are always on the false path so we can
754 // simply take that input, whatever it is.
755 DenseMap<Register, Register> FalseBBRegRewriteTable;
756 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd;) {
757 auto &MI = *MIIt++;
758 // Skip any CMOVs in this group which don't load from memory.
759 if (!MI.mayLoad()) {
760 // Remember the false-side register input.
761 Register FalseReg =
762 MI.getOperand(X86::getCondFromCMov(MI) == CC ? 1 : 2).getReg();
763 // Walk back through any intermediate cmovs referenced.
764 while (true) {
765 auto FRIt = FalseBBRegRewriteTable.find(FalseReg);
766 if (FRIt == FalseBBRegRewriteTable.end())
767 break;
768 FalseReg = FRIt->second;
769 }
770 FalseBBRegRewriteTable[MI.getOperand(0).getReg()] = FalseReg;
771 continue;
772 }
773
774 // The condition must be the *opposite* of the one we've decided to branch
775 // on as the branch will go *around* the load and the load should happen
776 // when the CMOV condition is false.
777 assert(X86::getCondFromCMov(MI) == OppCC &&
778 "Can only handle memory-operand cmov instructions with a condition "
779 "opposite to the selected branch direction.");
780
781 // The goal is to rewrite the cmov from:
782 //
783 // MBB:
784 // %A = CMOVcc %B (tied), (mem)
785 //
786 // to
787 //
788 // MBB:
789 // %A = CMOVcc %B (tied), %C
790 // FalseMBB:
791 // %C = MOV (mem)
792 //
793 // Which will allow the next loop to rewrite the CMOV in terms of a PHI:
794 //
795 // MBB:
796 // JMP!cc SinkMBB
797 // FalseMBB:
798 // %C = MOV (mem)
799 // SinkMBB:
800 // %A = PHI [ %C, FalseMBB ], [ %B, MBB]
801
802 // Get a fresh register to use as the destination of the MOV.
803 const TargetRegisterClass *RC = MRI->getRegClass(MI.getOperand(0).getReg());
804 Register TmpReg = MRI->createVirtualRegister(RC);
805
806 // Retain debug instr number when unfolded.
807 unsigned OldDebugInstrNum = MI.peekDebugInstrNum();
808 SmallVector<MachineInstr *, 4> NewMIs;
809 bool Unfolded = TII->unfoldMemoryOperand(*MBB->getParent(), MI, TmpReg,
810 /*UnfoldLoad*/ true,
811 /*UnfoldStore*/ false, NewMIs);
812 (void)Unfolded;
813 assert(Unfolded && "Should never fail to unfold a loading cmov!");
814
815 // Move the new CMOV to just before the old one and reset any impacted
816 // iterator.
817 auto *NewCMOV = NewMIs.pop_back_val();
818 assert(X86::getCondFromCMov(*NewCMOV) == OppCC &&
819 "Last new instruction isn't the expected CMOV!");
820 LLVM_DEBUG(dbgs() << "\tRewritten cmov: "; NewCMOV->dump());
822 if (&*MIItBegin == &MI)
823 MIItBegin = MachineBasicBlock::iterator(NewCMOV);
824
825 if (OldDebugInstrNum)
826 NewCMOV->setDebugInstrNum(OldDebugInstrNum);
827
828 // Sink whatever instructions were needed to produce the unfolded operand
829 // into the false block.
830 for (auto *NewMI : NewMIs) {
831 LLVM_DEBUG(dbgs() << "\tRewritten load instr: "; NewMI->dump());
832 FalseMBB->insert(FalseInsertionPoint, NewMI);
833 // Re-map any operands that are from other cmovs to the inputs for this block.
834 for (auto &MOp : NewMI->uses()) {
835 if (!MOp.isReg())
836 continue;
837 auto It = FalseBBRegRewriteTable.find(MOp.getReg());
838 if (It == FalseBBRegRewriteTable.end())
839 continue;
840
841 MOp.setReg(It->second);
842 // This might have been a kill when it referenced the cmov result, but
843 // it won't necessarily be once rewritten.
844 // FIXME: We could potentially improve this by tracking whether the
845 // operand to the cmov was also a kill, and then skipping the PHI node
846 // construction below.
847 MOp.setIsKill(false);
848 }
849 }
850 MBB->erase(&MI);
851
852 // Add this PHI to the rewrite table.
853 FalseBBRegRewriteTable[NewCMOV->getOperand(0).getReg()] = TmpReg;
854 }
855
856 // As we are creating the PHIs, we have to be careful if there is more than
857 // one. Later CMOVs may reference the results of earlier CMOVs, but later
858 // PHIs have to reference the individual true/false inputs from earlier PHIs.
859 // That also means that PHI construction must work forward from earlier to
860 // later, and that the code must maintain a mapping from earlier PHI's
861 // destination registers, and the registers that went into the PHI.
862 DenseMap<Register, std::pair<Register, Register>> RegRewriteTable;
863
864 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
865 Register DestReg = MIIt->getOperand(0).getReg();
866 Register Op1Reg = MIIt->getOperand(1).getReg();
867 Register Op2Reg = MIIt->getOperand(2).getReg();
868
869 // If this CMOV we are processing is the opposite condition from the jump we
870 // generated, then we have to swap the operands for the PHI that is going to
871 // be generated.
872 if (X86::getCondFromCMov(*MIIt) == OppCC)
873 std::swap(Op1Reg, Op2Reg);
874
875 auto Op1Itr = RegRewriteTable.find(Op1Reg);
876 if (Op1Itr != RegRewriteTable.end())
877 Op1Reg = Op1Itr->second.first;
878
879 auto Op2Itr = RegRewriteTable.find(Op2Reg);
880 if (Op2Itr != RegRewriteTable.end())
881 Op2Reg = Op2Itr->second.second;
882
883 // SinkMBB:
884 // %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, MBB ]
885 // ...
886 MIB = BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(X86::PHI), DestReg)
887 .addReg(Op1Reg)
888 .addMBB(FalseMBB)
889 .addReg(Op2Reg)
890 .addMBB(MBB);
891 (void)MIB;
892 LLVM_DEBUG(dbgs() << "\tFrom: "; MIIt->dump());
893 LLVM_DEBUG(dbgs() << "\tTo: "; MIB->dump());
894
895 // debug-info: we can just copy the instr-ref number from one instruction
896 // to the other, seeing how it's a one-for-one substitution.
897 if (unsigned InstrNum = MIIt->peekDebugInstrNum())
898 MIB->setDebugInstrNum(InstrNum);
899
900 // Add this PHI to the rewrite table.
901 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
902 }
903
904 // Reset the NoPHIs property if a PHI was inserted to prevent a conflict with
905 // the MachineVerifier during testing.
906 if (MIItBegin != MIItEnd)
907 F->getProperties().resetNoPHIs();
908
909 // Now remove the CMOV(s).
910 MBB->erase(MIItBegin, MIItEnd);
911
912 // Add new basic blocks to MachineLoopInfo.
913 if (MachineLoop *L = MLI->getLoopFor(MBB)) {
914 L->addBasicBlockToLoop(FalseMBB, *MLI);
915 L->addBasicBlockToLoop(SinkMBB, *MLI);
916 }
917}
918
919INITIALIZE_PASS_BEGIN(X86CmovConversionLegacy, DEBUG_TYPE,
920 "X86 cmov Conversion", false, false)
922INITIALIZE_PASS_END(X86CmovConversionLegacy, DEBUG_TYPE, "X86 cmov Conversion",
924
926 return new X86CmovConversionLegacy();
927}
928
929bool X86CmovConversionLegacy::runOnMachineFunction(MachineFunction &MF) {
930 if (skipFunction(MF.getFunction()))
931 return false;
932 MachineLoopInfo *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
933 X86CmovConversionImpl Impl(MLI);
934 return Impl.runOnMachineFunction(MF);
935}
936
937PreservedAnalyses
941 X86CmovConversionImpl Impl(MLI);
942 bool Changed = Impl.runOnMachineFunction(MF);
945}
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
#define DEBUG_TYPE
Hexagon Hardware Loops
IRTranslator LLVM IR MI
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
static bool checkEFLAGSLive(MachineInstr *MI)
static unsigned getDepthOfOptCmov(unsigned TrueOpDepth, unsigned FalseOpDepth)
static void packCmovGroup(MachineInstr *First, MachineInstr *Last)
Given /p First CMOV instruction and /p Last CMOV instruction representing a group of CMOV instruction...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
iterator end() const
iterator begin() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< succ_iterator > successors()
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 '...
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
void setFlags(unsigned flags)
void setDebugInstrNum(unsigned Num)
Set instruction number of this MachineInstr.
LLVM_ABI void dump() const
Analysis pass that exposes the MachineLoopInfo for a machine function.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
const X86InstrInfo * getInstrInfo() const override
const X86Options & getCLOpts() const
self_iterator getIterator()
Definition ilist_node.h:123
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
int getFirstAddrOperandIdx(const MachineInstr &MI)
Return the index of the instruction's first address operand, if it has a memory reference,...
CondCode GetOppositeBranchCondition(CondCode CC)
GetOppositeBranchCondition - Return the inverse of the specified cond, e.g.
bool foldNDDCmovLoads(const X86Subtarget &STI, const TargetMachine &TM)
Return true if ISel folds non-RIP-relative loads into NDD CMOVs so that X86CmovConversion converts th...
CondCode getCondFromCMov(const MachineInstr &MI)
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
FunctionPass * createX86CmovConversionLegacyPass()
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
bool hasSingleElement(ContainerTy &&C)
Returns true if the given container only contains a single element.
Definition STLExtras.h:300
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI CGPassBuilderOption getCGPassBuilderOption(const TargetMachine &TM)
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881