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 /// Collect all CMOV-group-candidates in \p CurrLoop and update \p
107 /// CmovInstGroups accordingly.
108 ///
109 /// \param Blocks List of blocks to process.
110 /// \param CmovInstGroups List of consecutive CMOV instructions in CurrLoop.
111 /// \returns true iff it found any CMOV-group-candidate.
112 bool collectCmovCandidates(ArrayRef<MachineBasicBlock *> Blocks,
113 CmovGroups &CmovInstGroups,
114 bool IncludeLoads = false);
115
116 /// Check if it is profitable to transform each CMOV-group-candidates into
117 /// branch. Remove all groups that are not profitable from \p CmovInstGroups.
118 ///
119 /// \param Blocks List of blocks to process.
120 /// \param CmovInstGroups List of consecutive CMOV instructions in CurrLoop.
121 /// \returns true iff any CMOV-group-candidate remain.
122 bool checkForProfitableCmovCandidates(ArrayRef<MachineBasicBlock *> Blocks,
123 CmovGroups &CmovInstGroups);
124
125 /// Convert the given list of consecutive CMOV instructions into a branch.
126 ///
127 /// \param Group Consecutive CMOV instructions to be converted into branch.
128 void convertCmovInstsToBranches(SmallVectorImpl<MachineInstr *> &Group) const;
129};
130
131class X86CmovConversionLegacy : public MachineFunctionPass {
132public:
133 X86CmovConversionLegacy() : MachineFunctionPass(ID) {}
134
135 StringRef getPassName() const override { return "X86 cmov Conversion"; }
136 bool runOnMachineFunction(MachineFunction &MF) override;
137 void getAnalysisUsage(AnalysisUsage &AU) const override;
138
139 /// Pass identification, replacement for typeid.
140 static char ID;
141};
142
143} // end anonymous namespace
144
145char X86CmovConversionLegacy::ID = 0;
146
147void X86CmovConversionLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
149 AU.addRequired<MachineLoopInfoWrapperPass>();
150 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
151}
152
153bool X86CmovConversionImpl::runOnMachineFunction(MachineFunction &MF) {
154 STI = &MF.getSubtarget<X86Subtarget>();
155 const X86Options &CLOpts = STI->getCLOpts();
156 if (!CLOpts.cmov_converter)
157 return false;
158
159 // If the SelectOptimize pass is enabled, cmovs have already been optimized.
161 return false;
162
163 LLVM_DEBUG(dbgs() << "********** " << DEBUG_TYPE << " : " << MF.getName()
164 << "**********\n");
165
166 bool Changed = false;
167 MRI = &MF.getRegInfo();
168 TII = STI->getInstrInfo();
169 TSchedModel.init(STI);
170
171 // Before we handle the more subtle cases of register-register CMOVs inside
172 // of potentially hot loops, we want to quickly remove all CMOVs
173 // (cmov_converter_force_all) or the ones with a memory operand
174 // (cmov_converter_force_mem_operand). The latter CMOV will risk a stall
175 // waiting for the load to complete that speculative execution behind a branch
176 // is better suited to handle on modern x86 chips.
177 if (CLOpts.cmov_converter_force_mem_operand ||
178 CLOpts.cmov_converter_force_all) {
179 CmovGroups AllCmovGroups;
180 SmallVector<MachineBasicBlock *, 4> Blocks(llvm::make_pointer_range(MF));
181 if (collectCmovCandidates(Blocks, AllCmovGroups, /*IncludeLoads*/ true)) {
182 for (auto &Group : AllCmovGroups) {
183 // Skip any group that doesn't do at least one memory operand cmov.
184 if (CLOpts.cmov_converter_force_mem_operand &&
185 !CLOpts.cmov_converter_force_all &&
186 llvm::none_of(Group, [&](MachineInstr *I) { return I->mayLoad(); }))
187 continue;
188
189 // For CMOV groups which we can rewrite and which contain a memory load,
190 // always rewrite them. On x86, a CMOV will dramatically amplify any
191 // memory latency by blocking speculative execution.
192 Changed = true;
193 convertCmovInstsToBranches(Group);
194 }
195 }
196 // Early return as cmov_converter_force_all converts all CmovGroups.
197 if (CLOpts.cmov_converter_force_all)
198 return Changed;
199 }
200
201 //===--------------------------------------------------------------------===//
202 // Register-operand Conversion Algorithm
203 // ---------
204 // For each innermost loop
205 // collectCmovCandidates() {
206 // Find all CMOV-group-candidates.
207 // }
208 //
209 // checkForProfitableCmovCandidates() {
210 // * Calculate both loop-depth and optimized-loop-depth.
211 // * Use these depth to check for loop transformation profitability.
212 // * Check for CMOV-group-candidate transformation profitability.
213 // }
214 //
215 // For each profitable CMOV-group-candidate
216 // convertCmovInstsToBranches() {
217 // * Create FalseBB, SinkBB, Conditional branch to SinkBB.
218 // * Replace each CMOV instruction with a PHI instruction in SinkBB.
219 // }
220 //
221 // Note: For more details, see each function description.
222 //===--------------------------------------------------------------------===//
223
224 // Build up the loops in pre-order.
226 // Note that we need to check size on each iteration as we accumulate child
227 // loops.
228 for (int i = 0; i < (int)Loops.size(); ++i)
229 llvm::append_range(Loops, Loops[i]->getSubLoops());
230
231 for (MachineLoop *CurrLoop : Loops) {
232 // Optimize only innermost loops.
233 if (!CurrLoop->getSubLoops().empty())
234 continue;
235
236 // List of consecutive CMOV instructions to be processed.
237 CmovGroups CmovInstGroups;
238
239 if (!collectCmovCandidates(CurrLoop->getBlocks(), CmovInstGroups))
240 continue;
241
242 if (!checkForProfitableCmovCandidates(CurrLoop->getBlocks(),
243 CmovInstGroups))
244 continue;
245
246 Changed = true;
247 for (auto &Group : CmovInstGroups)
248 convertCmovInstsToBranches(Group);
249 }
250
251 return Changed;
252}
253
254bool X86CmovConversionImpl::collectCmovCandidates(
255 ArrayRef<MachineBasicBlock *> Blocks, CmovGroups &CmovInstGroups,
256 bool IncludeLoads) {
257 //===--------------------------------------------------------------------===//
258 // Collect all CMOV-group-candidates and add them into CmovInstGroups.
259 //
260 // CMOV-group:
261 // CMOV instructions, in same MBB, that uses same EFLAGS def instruction.
262 //
263 // CMOV-group-candidate:
264 // CMOV-group where all the CMOV instructions are
265 // 1. consecutive.
266 // 2. have same condition code or opposite one.
267 // 3. have only operand registers (X86::CMOVrr).
268 //===--------------------------------------------------------------------===//
269 // List of possible improvement (TODO's):
270 // --------------------------------------
271 // TODO: Add support for X86::CMOVrm instructions.
272 // TODO: Add support for X86::SETcc instructions.
273 // TODO: Add support for CMOV-groups with non consecutive CMOV instructions.
274 //===--------------------------------------------------------------------===//
275
276 // Current processed CMOV-Group.
277 CmovGroup Group;
278 for (auto *MBB : Blocks) {
279 Group.clear();
280 // Condition code of first CMOV instruction current processed range and its
281 // opposite condition code.
282 X86::CondCode FirstCC = X86::COND_INVALID, FirstOppCC = X86::COND_INVALID,
283 MemOpCC = X86::COND_INVALID;
284 // Indicator of a non CMOVrr instruction in the current processed range.
285 bool FoundNonCMOVInst = false;
286 // Indicator for current processed CMOV-group if it should be skipped.
287 bool SkipGroup = false;
288
289 for (auto &I : *MBB) {
290 // Skip debug instructions.
291 if (I.isDebugInstr())
292 continue;
293
295 // Check if we found a X86::CMOVrr instruction. If it is marked as
296 // unpredictable, skip it and do not convert it to branch.
297 if (CC != X86::COND_INVALID &&
298 !I.getFlag(MachineInstr::MIFlag::Unpredictable) &&
299 (IncludeLoads || !I.mayLoad()) && !I.hasOrderedMemoryRef()) {
300 if (Group.empty()) {
301 // We found first CMOV in the range, reset flags.
302 FirstCC = CC;
304 // Clear out the prior group's memory operand CC.
305 MemOpCC = X86::COND_INVALID;
306 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;
315 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 }
323 // Check if we were relying on zero-extending behavior of the CMOV.
324 if (!SkipGroup &&
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;
333 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, /*TRI=*/nullptr)) {
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 // The depth of the result after branch conversion is
372 // TrueOpDepth * TrueOpProbability + FalseOpDepth * FalseOpProbability.
373 // As we have no info about branch weight, we assume 75% for one and 25% for
374 // the other, and pick the result with the largest resulting depth.
375 return std::max(
376 divideCeil(TrueOpDepth * 3 + FalseOpDepth, 4),
377 divideCeil(FalseOpDepth * 3 + TrueOpDepth, 4));
378}
379
380bool X86CmovConversionImpl::checkForProfitableCmovCandidates(
381 ArrayRef<MachineBasicBlock *> Blocks, CmovGroups &CmovInstGroups) {
382 struct DepthInfo {
383 /// Depth of original loop.
384 unsigned Depth;
385 /// Depth of optimized loop.
386 unsigned OptDepth;
387 };
388 /// Number of loop iterations to calculate depth for ?!
389 static const unsigned LoopIterations = 2;
390 DenseMap<MachineInstr *, DepthInfo> DepthMap;
391 DepthInfo LoopDepth[LoopIterations] = {{0, 0}, {0, 0}};
392 enum { PhyRegType = 0, VirRegType = 1, RegTypeNum = 2 };
393 /// For each register type maps the register to its last def instruction.
394 DenseMap<Register, MachineInstr *> RegDefMaps[RegTypeNum];
395 /// Maps register operand to its def instruction, which can be nullptr if it
396 /// is unknown (e.g., operand is defined outside the loop).
397 DenseMap<MachineOperand *, MachineInstr *> OperandToDefMap;
398
399 // Set depth of unknown instruction (i.e., nullptr) to zero.
400 DepthMap[nullptr] = {0, 0};
401
402 SmallPtrSet<MachineInstr *, 4> CmovInstructions;
403 for (auto &Group : CmovInstGroups)
404 CmovInstructions.insert_range(Group);
405
406 //===--------------------------------------------------------------------===//
407 // Step 1: Calculate instruction depth and loop depth.
408 // Optimized-Loop:
409 // loop with CMOV-group-candidates converted into branches.
410 //
411 // Instruction-Depth:
412 // instruction latency + max operand depth.
413 // * For CMOV instruction in optimized loop the depth is calculated as:
414 // CMOV latency + getDepthOfOptCmov(True-Op-Depth, False-Op-depth)
415 // TODO: Find a better way to estimate the latency of the branch instruction
416 // rather than using the CMOV latency.
417 //
418 // Loop-Depth:
419 // max instruction depth of all instructions in the loop.
420 // Note: instruction with max depth represents the critical-path in the loop.
421 //
422 // Loop-Depth[i]:
423 // Loop-Depth calculated for first `i` iterations.
424 // Note: it is enough to calculate depth for up to two iterations.
425 //
426 // Depth-Diff[i]:
427 // Number of cycles saved in first 'i` iterations by optimizing the loop.
428 //===--------------------------------------------------------------------===//
429 for (DepthInfo &MaxDepth : LoopDepth) {
430 for (auto *MBB : Blocks) {
431 // Clear physical registers Def map.
432 RegDefMaps[PhyRegType].clear();
433 for (MachineInstr &MI : *MBB) {
434 // Skip debug instructions.
435 if (MI.isDebugInstr())
436 continue;
437 unsigned MIDepth = 0;
438 unsigned MIDepthOpt = 0;
439 bool IsCMOV = CmovInstructions.count(&MI);
440 for (auto &MO : MI.uses()) {
441 // Checks for "isUse()" as "uses()" returns also implicit definitions.
442 if (!MO.isReg() || !MO.isUse())
443 continue;
444 Register Reg = MO.getReg();
445 auto &RDM = RegDefMaps[Reg.isVirtual()];
446 if (MachineInstr *DefMI = RDM.lookup(Reg)) {
447 OperandToDefMap[&MO] = DefMI;
448 DepthInfo Info = DepthMap.lookup(DefMI);
449 MIDepth = std::max(MIDepth, Info.Depth);
450 if (!IsCMOV)
451 MIDepthOpt = std::max(MIDepthOpt, Info.OptDepth);
452 }
453 }
454
455 if (IsCMOV)
456 MIDepthOpt = getDepthOfOptCmov(
457 DepthMap[OperandToDefMap.lookup(&MI.getOperand(1))].OptDepth,
458 DepthMap[OperandToDefMap.lookup(&MI.getOperand(2))].OptDepth);
459
460 // Iterates over all operands to handle implicit definitions as well.
461 for (auto &MO : MI.operands()) {
462 if (!MO.isReg() || !MO.isDef())
463 continue;
464 Register Reg = MO.getReg();
465 RegDefMaps[Reg.isVirtual()][Reg] = &MI;
466 }
467
468 unsigned Latency = TSchedModel.computeInstrLatency(&MI);
469 DepthMap[&MI] = {MIDepth += Latency, MIDepthOpt += Latency};
470 MaxDepth.Depth = std::max(MaxDepth.Depth, MIDepth);
471 MaxDepth.OptDepth = std::max(MaxDepth.OptDepth, MIDepthOpt);
472 }
473 }
474 }
475
476 unsigned Diff[LoopIterations] = {LoopDepth[0].Depth - LoopDepth[0].OptDepth,
477 LoopDepth[1].Depth - LoopDepth[1].OptDepth};
478
479 //===--------------------------------------------------------------------===//
480 // Step 2: Check if Loop worth to be optimized.
481 // Worth-Optimize-Loop:
482 // case 1: Diff[1] == Diff[0]
483 // Critical-path is iteration independent - there is no dependency
484 // of critical-path instructions on critical-path instructions of
485 // previous iteration.
486 // Thus, it is enough to check gain percent of 1st iteration -
487 // To be conservative, the optimized loop need to have a depth of
488 // 12.5% cycles less than original loop, per iteration.
489 //
490 // case 2: Diff[1] > Diff[0]
491 // Critical-path is iteration dependent - there is dependency of
492 // critical-path instructions on critical-path instructions of
493 // previous iteration.
494 // Thus, check the gain percent of the 2nd iteration (similar to the
495 // previous case), but it is also required to check the gradient of
496 // the gain - the change in Depth-Diff compared to the change in
497 // Loop-Depth between 1st and 2nd iterations.
498 // To be conservative, the gradient need to be at least 50%.
499 //
500 // In addition, In order not to optimize loops with very small gain, the
501 // gain (in cycles) after 2nd iteration should not be less than a given
502 // threshold. Thus, the check (Diff[1] >= cmov_converter_threshold) must
503 // apply.
504 //
505 // If loop is not worth optimizing, remove all CMOV-group-candidates.
506 //===--------------------------------------------------------------------===//
507 if (Diff[1] < STI->getCLOpts().cmov_converter_threshold)
508 return false;
509
510 bool WorthOptLoop = false;
511 if (Diff[1] == Diff[0])
512 WorthOptLoop = Diff[0] * 8 >= LoopDepth[0].Depth;
513 else if (Diff[1] > Diff[0])
514 WorthOptLoop =
515 (Diff[1] - Diff[0]) * 2 >= (LoopDepth[1].Depth - LoopDepth[0].Depth) &&
516 (Diff[1] * 8 >= LoopDepth[1].Depth);
517
518 if (!WorthOptLoop)
519 return false;
520
521 ++NumOfLoopCandidate;
522
523 //===--------------------------------------------------------------------===//
524 // Step 3: Check for each CMOV-group-candidate if it worth to be optimized.
525 // Worth-Optimize-Group:
526 // Iff it is worth to optimize all CMOV instructions in the group.
527 //
528 // Worth-Optimize-CMOV:
529 // Predicted branch is faster than CMOV by the difference between depth of
530 // condition operand and depth of taken (predicted) value operand.
531 // To be conservative, the gain of such CMOV transformation should cover at
532 // at least 25% of branch-misprediction-penalty.
533 //===--------------------------------------------------------------------===//
534 unsigned MispredictPenalty = STI->getMispredictionPenalty();
535 CmovGroups TempGroups;
536 std::swap(TempGroups, CmovInstGroups);
537 for (auto &Group : TempGroups) {
538 bool WorthOpGroup = true;
539 for (auto *MI : Group) {
540 // Avoid CMOV instruction which value is used as a pointer to load from.
541 // This is another conservative check to avoid converting CMOV instruction
542 // used with tree-search like algorithm, where the branch is unpredicted.
543 auto UIs = MRI->use_instructions(MI->defs().begin()->getReg());
544 if (hasSingleElement(UIs)) {
545 unsigned Op = UIs.begin()->getOpcode();
546 if (Op == X86::MOV64rm || Op == X86::MOV32rm) {
547 WorthOpGroup = false;
548 break;
549 }
550 }
551
552 unsigned CondCost =
553 DepthMap[OperandToDefMap.lookup(&MI->getOperand(4))].Depth;
554 unsigned ValCost = getDepthOfOptCmov(
555 DepthMap[OperandToDefMap.lookup(&MI->getOperand(1))].Depth,
556 DepthMap[OperandToDefMap.lookup(&MI->getOperand(2))].Depth);
557 if (ValCost > CondCost || (CondCost - ValCost) * 4 < MispredictPenalty) {
558 WorthOpGroup = false;
559 break;
560 }
561 }
562
563 if (WorthOpGroup)
564 CmovInstGroups.push_back(Group);
565 }
566
567 return !CmovInstGroups.empty();
568}
569
571 if (MI->killsRegister(X86::EFLAGS, /*TRI=*/nullptr))
572 return false;
573
574 // The EFLAGS operand of MI might be missing a kill marker.
575 // Figure out whether EFLAGS operand should LIVE after MI instruction.
576 MachineBasicBlock *BB = MI->getParent();
578
579 // Scan forward through BB for a use/def of EFLAGS.
580 for (auto I = std::next(ItrMI), E = BB->end(); I != E; ++I) {
581 if (I->readsRegister(X86::EFLAGS, /*TRI=*/nullptr))
582 return true;
583 if (I->definesRegister(X86::EFLAGS, /*TRI=*/nullptr))
584 return false;
585 }
586
587 // We hit the end of the block, check whether EFLAGS is live into a successor.
588 for (MachineBasicBlock *Succ : BB->successors())
589 if (Succ->isLiveIn(X86::EFLAGS))
590 return true;
591
592 return false;
593}
594
595/// Given /p First CMOV instruction and /p Last CMOV instruction representing a
596/// group of CMOV instructions, which may contain debug instructions in between,
597/// move all debug instructions to after the last CMOV instruction, making the
598/// CMOV group consecutive.
601 "Last instruction in a CMOV group must be a CMOV instruction");
602
603 SmallVector<MachineInstr *, 2> DBGInstructions;
604 for (auto I = First->getIterator(), E = Last->getIterator(); I != E; I++) {
605 if (I->isDebugInstr())
606 DBGInstructions.push_back(&*I);
607 }
608
609 // Splice the debug instruction after the cmov group.
610 MachineBasicBlock *MBB = First->getParent();
611 for (auto *MI : DBGInstructions)
612 MBB->insertAfter(Last, MI->removeFromParent());
613}
614
615void X86CmovConversionImpl::convertCmovInstsToBranches(
616 SmallVectorImpl<MachineInstr *> &Group) const {
617 assert(!Group.empty() && "No CMOV instructions to convert");
618 ++NumOfOptimizedCmovGroups;
619
620 // If the CMOV group is not packed, e.g., there are debug instructions between
621 // first CMOV and last CMOV, then pack the group and make the CMOV instruction
622 // consecutive by moving the debug instructions to after the last CMOV.
623 packCmovGroup(Group.front(), Group.back());
624
625 // To convert a CMOVcc instruction, we actually have to insert the diamond
626 // control-flow pattern. The incoming instruction knows the destination vreg
627 // to set, the condition code register to branch on, the true/false values to
628 // select between, and a branch opcode to use.
629
630 // Before
631 // -----
632 // MBB:
633 // cond = cmp ...
634 // v1 = CMOVge t1, f1, cond
635 // v2 = CMOVlt t2, f2, cond
636 // v3 = CMOVge v1, f3, cond
637 //
638 // After
639 // -----
640 // MBB:
641 // cond = cmp ...
642 // jge %SinkMBB
643 //
644 // FalseMBB:
645 // jmp %SinkMBB
646 //
647 // SinkMBB:
648 // %v1 = phi[%f1, %FalseMBB], [%t1, %MBB]
649 // %v2 = phi[%t2, %FalseMBB], [%f2, %MBB] ; For CMOV with OppCC switch
650 // ; true-value with false-value
651 // %v3 = phi[%f3, %FalseMBB], [%t1, %MBB] ; Phi instruction cannot use
652 // ; previous Phi instruction result
653
654 MachineInstr &MI = *Group.front();
655 MachineInstr *LastCMOV = Group.back();
656 DebugLoc DL = MI.getDebugLoc();
657
660 // Potentially swap the condition codes so that any memory operand to a CMOV
661 // is in the *false* position instead of the *true* position. We can invert
662 // any non-memory operand CMOV instructions to cope with this and we ensure
663 // memory operand CMOVs are only included with a single condition code.
664 if (llvm::any_of(Group, [&](MachineInstr *I) {
665 return I->mayLoad() && X86::getCondFromCMov(*I) == CC;
666 }))
667 std::swap(CC, OppCC);
668
669 MachineBasicBlock *MBB = MI.getParent();
672 const BasicBlock *BB = MBB->getBasicBlock();
673
674 MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(BB);
675 MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(BB);
676 F->insert(It, FalseMBB);
677 F->insert(It, SinkMBB);
678
679 // If the EFLAGS register isn't dead in the terminator, then claim that it's
680 // live into the sink and copy blocks.
681 if (checkEFLAGSLive(LastCMOV)) {
682 FalseMBB->addLiveIn(X86::EFLAGS);
683 SinkMBB->addLiveIn(X86::EFLAGS);
684 }
685
686 // Transfer the remainder of BB and its successor edges to SinkMBB.
687 SinkMBB->splice(SinkMBB->begin(), MBB,
688 std::next(MachineBasicBlock::iterator(LastCMOV)), MBB->end());
690
691 // Add the false and sink blocks as its successors.
692 MBB->addSuccessor(FalseMBB);
693 MBB->addSuccessor(SinkMBB);
694
695 // Create the conditional branch instruction.
696 BuildMI(MBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(CC);
697
698 // Add the sink block to the false block successors.
699 FalseMBB->addSuccessor(SinkMBB);
700
701 MachineInstrBuilder MIB;
704 std::next(MachineBasicBlock::iterator(LastCMOV));
705 MachineBasicBlock::iterator FalseInsertionPoint = FalseMBB->begin();
706 MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
707
708 // First we need to insert an explicit load on the false path for any memory
709 // operand. We also need to potentially do register rewriting here, but it is
710 // simpler as the memory operands are always on the false path so we can
711 // simply take that input, whatever it is.
712 DenseMap<Register, Register> FalseBBRegRewriteTable;
713 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd;) {
714 auto &MI = *MIIt++;
715 // Skip any CMOVs in this group which don't load from memory.
716 if (!MI.mayLoad()) {
717 // Remember the false-side register input.
718 Register FalseReg =
719 MI.getOperand(X86::getCondFromCMov(MI) == CC ? 1 : 2).getReg();
720 // Walk back through any intermediate cmovs referenced.
721 while (true) {
722 auto FRIt = FalseBBRegRewriteTable.find(FalseReg);
723 if (FRIt == FalseBBRegRewriteTable.end())
724 break;
725 FalseReg = FRIt->second;
726 }
727 FalseBBRegRewriteTable[MI.getOperand(0).getReg()] = FalseReg;
728 continue;
729 }
730
731 // The condition must be the *opposite* of the one we've decided to branch
732 // on as the branch will go *around* the load and the load should happen
733 // when the CMOV condition is false.
734 assert(X86::getCondFromCMov(MI) == OppCC &&
735 "Can only handle memory-operand cmov instructions with a condition "
736 "opposite to the selected branch direction.");
737
738 // The goal is to rewrite the cmov from:
739 //
740 // MBB:
741 // %A = CMOVcc %B (tied), (mem)
742 //
743 // to
744 //
745 // MBB:
746 // %A = CMOVcc %B (tied), %C
747 // FalseMBB:
748 // %C = MOV (mem)
749 //
750 // Which will allow the next loop to rewrite the CMOV in terms of a PHI:
751 //
752 // MBB:
753 // JMP!cc SinkMBB
754 // FalseMBB:
755 // %C = MOV (mem)
756 // SinkMBB:
757 // %A = PHI [ %C, FalseMBB ], [ %B, MBB]
758
759 // Get a fresh register to use as the destination of the MOV.
760 const TargetRegisterClass *RC = MRI->getRegClass(MI.getOperand(0).getReg());
761 Register TmpReg = MRI->createVirtualRegister(RC);
762
763 // Retain debug instr number when unfolded.
764 unsigned OldDebugInstrNum = MI.peekDebugInstrNum();
765 SmallVector<MachineInstr *, 4> NewMIs;
766 bool Unfolded = TII->unfoldMemoryOperand(*MBB->getParent(), MI, TmpReg,
767 /*UnfoldLoad*/ true,
768 /*UnfoldStore*/ false, NewMIs);
769 (void)Unfolded;
770 assert(Unfolded && "Should never fail to unfold a loading cmov!");
771
772 // Move the new CMOV to just before the old one and reset any impacted
773 // iterator.
774 auto *NewCMOV = NewMIs.pop_back_val();
775 assert(X86::getCondFromCMov(*NewCMOV) == OppCC &&
776 "Last new instruction isn't the expected CMOV!");
777 LLVM_DEBUG(dbgs() << "\tRewritten cmov: "; NewCMOV->dump());
779 if (&*MIItBegin == &MI)
780 MIItBegin = MachineBasicBlock::iterator(NewCMOV);
781
782 if (OldDebugInstrNum)
783 NewCMOV->setDebugInstrNum(OldDebugInstrNum);
784
785 // Sink whatever instructions were needed to produce the unfolded operand
786 // into the false block.
787 for (auto *NewMI : NewMIs) {
788 LLVM_DEBUG(dbgs() << "\tRewritten load instr: "; NewMI->dump());
789 FalseMBB->insert(FalseInsertionPoint, NewMI);
790 // Re-map any operands that are from other cmovs to the inputs for this block.
791 for (auto &MOp : NewMI->uses()) {
792 if (!MOp.isReg())
793 continue;
794 auto It = FalseBBRegRewriteTable.find(MOp.getReg());
795 if (It == FalseBBRegRewriteTable.end())
796 continue;
797
798 MOp.setReg(It->second);
799 // This might have been a kill when it referenced the cmov result, but
800 // it won't necessarily be once rewritten.
801 // FIXME: We could potentially improve this by tracking whether the
802 // operand to the cmov was also a kill, and then skipping the PHI node
803 // construction below.
804 MOp.setIsKill(false);
805 }
806 }
807 MBB->erase(&MI);
808
809 // Add this PHI to the rewrite table.
810 FalseBBRegRewriteTable[NewCMOV->getOperand(0).getReg()] = TmpReg;
811 }
812
813 // As we are creating the PHIs, we have to be careful if there is more than
814 // one. Later CMOVs may reference the results of earlier CMOVs, but later
815 // PHIs have to reference the individual true/false inputs from earlier PHIs.
816 // That also means that PHI construction must work forward from earlier to
817 // later, and that the code must maintain a mapping from earlier PHI's
818 // destination registers, and the registers that went into the PHI.
819 DenseMap<Register, std::pair<Register, Register>> RegRewriteTable;
820
821 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
822 Register DestReg = MIIt->getOperand(0).getReg();
823 Register Op1Reg = MIIt->getOperand(1).getReg();
824 Register Op2Reg = MIIt->getOperand(2).getReg();
825
826 // If this CMOV we are processing is the opposite condition from the jump we
827 // generated, then we have to swap the operands for the PHI that is going to
828 // be generated.
829 if (X86::getCondFromCMov(*MIIt) == OppCC)
830 std::swap(Op1Reg, Op2Reg);
831
832 auto Op1Itr = RegRewriteTable.find(Op1Reg);
833 if (Op1Itr != RegRewriteTable.end())
834 Op1Reg = Op1Itr->second.first;
835
836 auto Op2Itr = RegRewriteTable.find(Op2Reg);
837 if (Op2Itr != RegRewriteTable.end())
838 Op2Reg = Op2Itr->second.second;
839
840 // SinkMBB:
841 // %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, MBB ]
842 // ...
843 MIB = BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(X86::PHI), DestReg)
844 .addReg(Op1Reg)
845 .addMBB(FalseMBB)
846 .addReg(Op2Reg)
847 .addMBB(MBB);
848 (void)MIB;
849 LLVM_DEBUG(dbgs() << "\tFrom: "; MIIt->dump());
850 LLVM_DEBUG(dbgs() << "\tTo: "; MIB->dump());
851
852 // debug-info: we can just copy the instr-ref number from one instruction
853 // to the other, seeing how it's a one-for-one substitution.
854 if (unsigned InstrNum = MIIt->peekDebugInstrNum())
855 MIB->setDebugInstrNum(InstrNum);
856
857 // Add this PHI to the rewrite table.
858 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
859 }
860
861 // Reset the NoPHIs property if a PHI was inserted to prevent a conflict with
862 // the MachineVerifier during testing.
863 if (MIItBegin != MIItEnd)
864 F->getProperties().resetNoPHIs();
865
866 // Now remove the CMOV(s).
867 MBB->erase(MIItBegin, MIItEnd);
868
869 // Add new basic blocks to MachineLoopInfo.
870 if (MachineLoop *L = MLI->getLoopFor(MBB)) {
871 L->addBasicBlockToLoop(FalseMBB, *MLI);
872 L->addBasicBlockToLoop(SinkMBB, *MLI);
873 }
874}
875
876INITIALIZE_PASS_BEGIN(X86CmovConversionLegacy, DEBUG_TYPE,
877 "X86 cmov Conversion", false, false)
879INITIALIZE_PASS_END(X86CmovConversionLegacy, DEBUG_TYPE, "X86 cmov Conversion",
881
883 return new X86CmovConversionLegacy();
884}
885
886bool X86CmovConversionLegacy::runOnMachineFunction(MachineFunction &MF) {
887 if (skipFunction(MF.getFunction()))
888 return false;
889 MachineLoopInfo *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
890 X86CmovConversionImpl Impl(MLI);
891 return Impl.runOnMachineFunction(MF);
892}
893
894PreservedAnalyses
898 X86CmovConversionImpl Impl(MLI);
899 bool Changed = Impl.runOnMachineFunction(MF);
902}
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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
const HexagonInstrInfo * TII
Hexagon Hardware Loops
IRTranslator LLVM IR MI
#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:171
#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 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
CondCode GetOppositeBranchCondition(CondCode CC)
GetOppositeBranchCondition - Return the inverse of the specified cond, e.g.
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
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