1 //====- X86FlagsCopyLowering.cpp - Lowers COPY nodes of EFLAGS ------------===//
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
7 //===----------------------------------------------------------------------===//
10 /// Lowers COPY nodes of EFLAGS by directly extracting and preserving individual
13 /// We have to do this by carefully analyzing and rewriting the usage of the
14 /// copied EFLAGS register because there is no general way to rematerialize the
15 /// entire EFLAGS register safely and efficiently. Using `popf` both forces
16 /// dynamic stack adjustment and can create correctness issues due to IF, TF,
17 /// and other non-status flags being overwritten. Using sequences involving
18 /// SAHF don't work on all x86 processors and are often quite slow compared to
19 /// directly testing a single status preserved in its own GPR.
21 //===----------------------------------------------------------------------===//
24 #include "X86InstrBuilder.h"
25 #include "X86InstrInfo.h"
26 #include "X86Subtarget.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/PostOrderIterator.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/ScopeExit.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/SparseBitVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineConstantPool.h"
38 #include "llvm/CodeGen/MachineDominators.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineFunctionPass.h"
41 #include "llvm/CodeGen/MachineInstr.h"
42 #include "llvm/CodeGen/MachineInstrBuilder.h"
43 #include "llvm/CodeGen/MachineModuleInfo.h"
44 #include "llvm/CodeGen/MachineOperand.h"
45 #include "llvm/CodeGen/MachineRegisterInfo.h"
46 #include "llvm/CodeGen/MachineSSAUpdater.h"
47 #include "llvm/CodeGen/TargetInstrInfo.h"
48 #include "llvm/CodeGen/TargetRegisterInfo.h"
49 #include "llvm/CodeGen/TargetSchedule.h"
50 #include "llvm/CodeGen/TargetSubtargetInfo.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/MC/MCSchedule.h"
53 #include "llvm/Pass.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/raw_ostream.h"
64 #define PASS_KEY "x86-flags-copy-lowering"
65 #define DEBUG_TYPE PASS_KEY
67 STATISTIC(NumCopiesEliminated
, "Number of copies of EFLAGS eliminated");
68 STATISTIC(NumSetCCsInserted
, "Number of setCC instructions inserted");
69 STATISTIC(NumTestsInserted
, "Number of test instructions inserted");
70 STATISTIC(NumAddsInserted
, "Number of adds instructions inserted");
74 // Convenient array type for storing registers associated with each condition.
75 using CondRegArray
= std::array
<unsigned, X86::LAST_VALID_COND
+ 1>;
77 class X86FlagsCopyLoweringPass
: public MachineFunctionPass
{
79 X86FlagsCopyLoweringPass() : MachineFunctionPass(ID
) { }
81 StringRef
getPassName() const override
{ return "X86 EFLAGS copy lowering"; }
82 bool runOnMachineFunction(MachineFunction
&MF
) override
;
83 void getAnalysisUsage(AnalysisUsage
&AU
) const override
;
85 /// Pass identification, replacement for typeid.
89 MachineRegisterInfo
*MRI
= nullptr;
90 const X86Subtarget
*Subtarget
= nullptr;
91 const X86InstrInfo
*TII
= nullptr;
92 const TargetRegisterInfo
*TRI
= nullptr;
93 const TargetRegisterClass
*PromoteRC
= nullptr;
94 MachineDominatorTree
*MDT
= nullptr;
96 CondRegArray
collectCondsInRegs(MachineBasicBlock
&MBB
,
97 MachineBasicBlock::iterator CopyDefI
);
99 Register
promoteCondToReg(MachineBasicBlock
&MBB
,
100 MachineBasicBlock::iterator TestPos
,
101 const DebugLoc
&TestLoc
, X86::CondCode Cond
);
102 std::pair
<unsigned, bool> getCondOrInverseInReg(
103 MachineBasicBlock
&TestMBB
, MachineBasicBlock::iterator TestPos
,
104 const DebugLoc
&TestLoc
, X86::CondCode Cond
, CondRegArray
&CondRegs
);
105 void insertTest(MachineBasicBlock
&MBB
, MachineBasicBlock::iterator Pos
,
106 const DebugLoc
&Loc
, unsigned Reg
);
108 void rewriteArithmetic(MachineBasicBlock
&TestMBB
,
109 MachineBasicBlock::iterator TestPos
,
110 const DebugLoc
&TestLoc
, MachineInstr
&MI
,
111 MachineOperand
&FlagUse
, CondRegArray
&CondRegs
);
112 void rewriteCMov(MachineBasicBlock
&TestMBB
,
113 MachineBasicBlock::iterator TestPos
, const DebugLoc
&TestLoc
,
114 MachineInstr
&CMovI
, MachineOperand
&FlagUse
,
115 CondRegArray
&CondRegs
);
116 void rewriteFCMov(MachineBasicBlock
&TestMBB
,
117 MachineBasicBlock::iterator TestPos
,
118 const DebugLoc
&TestLoc
, MachineInstr
&CMovI
,
119 MachineOperand
&FlagUse
, CondRegArray
&CondRegs
);
120 void rewriteCondJmp(MachineBasicBlock
&TestMBB
,
121 MachineBasicBlock::iterator TestPos
,
122 const DebugLoc
&TestLoc
, MachineInstr
&JmpI
,
123 CondRegArray
&CondRegs
);
124 void rewriteCopy(MachineInstr
&MI
, MachineOperand
&FlagUse
,
125 MachineInstr
&CopyDefI
);
126 void rewriteSetCC(MachineBasicBlock
&TestMBB
,
127 MachineBasicBlock::iterator TestPos
,
128 const DebugLoc
&TestLoc
, MachineInstr
&SetCCI
,
129 MachineOperand
&FlagUse
, CondRegArray
&CondRegs
);
132 } // end anonymous namespace
134 INITIALIZE_PASS_BEGIN(X86FlagsCopyLoweringPass
, DEBUG_TYPE
,
135 "X86 EFLAGS copy lowering", false, false)
136 INITIALIZE_PASS_END(X86FlagsCopyLoweringPass
, DEBUG_TYPE
,
137 "X86 EFLAGS copy lowering", false, false)
139 FunctionPass
*llvm::createX86FlagsCopyLoweringPass() {
140 return new X86FlagsCopyLoweringPass();
143 char X86FlagsCopyLoweringPass::ID
= 0;
145 void X86FlagsCopyLoweringPass::getAnalysisUsage(AnalysisUsage
&AU
) const {
146 AU
.addRequired
<MachineDominatorTree
>();
147 MachineFunctionPass::getAnalysisUsage(AU
);
151 /// An enumeration of the arithmetic instruction mnemonics which have
152 /// interesting flag semantics.
154 /// We can map instruction opcodes into these mnemonics to make it easy to
155 /// dispatch with specific functionality.
156 enum class FlagArithMnemonic
{
165 static FlagArithMnemonic
getMnemonicFromOpcode(unsigned Opcode
) {
168 report_fatal_error("No support for lowering a copy into EFLAGS when used "
169 "by this instruction!");
171 #define LLVM_EXPAND_INSTR_SIZES(MNEMONIC, SUFFIX) \
172 case X86::MNEMONIC##8##SUFFIX: \
173 case X86::MNEMONIC##16##SUFFIX: \
174 case X86::MNEMONIC##32##SUFFIX: \
175 case X86::MNEMONIC##64##SUFFIX:
177 #define LLVM_EXPAND_ADC_SBB_INSTR(MNEMONIC) \
178 LLVM_EXPAND_INSTR_SIZES(MNEMONIC, rr) \
179 LLVM_EXPAND_INSTR_SIZES(MNEMONIC, rr_REV) \
180 LLVM_EXPAND_INSTR_SIZES(MNEMONIC, rm) \
181 LLVM_EXPAND_INSTR_SIZES(MNEMONIC, mr) \
182 case X86::MNEMONIC##8ri: \
183 case X86::MNEMONIC##16ri8: \
184 case X86::MNEMONIC##32ri8: \
185 case X86::MNEMONIC##64ri8: \
186 case X86::MNEMONIC##16ri: \
187 case X86::MNEMONIC##32ri: \
188 case X86::MNEMONIC##64ri32: \
189 case X86::MNEMONIC##8mi: \
190 case X86::MNEMONIC##16mi8: \
191 case X86::MNEMONIC##32mi8: \
192 case X86::MNEMONIC##64mi8: \
193 case X86::MNEMONIC##16mi: \
194 case X86::MNEMONIC##32mi: \
195 case X86::MNEMONIC##64mi32: \
196 case X86::MNEMONIC##8i8: \
197 case X86::MNEMONIC##16i16: \
198 case X86::MNEMONIC##32i32: \
199 case X86::MNEMONIC##64i32:
201 LLVM_EXPAND_ADC_SBB_INSTR(ADC
)
202 return FlagArithMnemonic::ADC
;
204 LLVM_EXPAND_ADC_SBB_INSTR(SBB
)
205 return FlagArithMnemonic::SBB
;
207 #undef LLVM_EXPAND_ADC_SBB_INSTR
209 LLVM_EXPAND_INSTR_SIZES(RCL
, rCL
)
210 LLVM_EXPAND_INSTR_SIZES(RCL
, r1
)
211 LLVM_EXPAND_INSTR_SIZES(RCL
, ri
)
212 return FlagArithMnemonic::RCL
;
214 LLVM_EXPAND_INSTR_SIZES(RCR
, rCL
)
215 LLVM_EXPAND_INSTR_SIZES(RCR
, r1
)
216 LLVM_EXPAND_INSTR_SIZES(RCR
, ri
)
217 return FlagArithMnemonic::RCR
;
219 #undef LLVM_EXPAND_INSTR_SIZES
223 return FlagArithMnemonic::SETB
;
227 static MachineBasicBlock
&splitBlock(MachineBasicBlock
&MBB
,
228 MachineInstr
&SplitI
,
229 const X86InstrInfo
&TII
) {
230 MachineFunction
&MF
= *MBB
.getParent();
232 assert(SplitI
.getParent() == &MBB
&&
233 "Split instruction must be in the split block!");
234 assert(SplitI
.isBranch() &&
235 "Only designed to split a tail of branch instructions!");
236 assert(X86::getCondFromBranch(SplitI
) != X86::COND_INVALID
&&
237 "Must split on an actual jCC instruction!");
239 // Dig out the previous instruction to the split point.
240 MachineInstr
&PrevI
= *std::prev(SplitI
.getIterator());
241 assert(PrevI
.isBranch() && "Must split after a branch!");
242 assert(X86::getCondFromBranch(PrevI
) != X86::COND_INVALID
&&
243 "Must split after an actual jCC instruction!");
244 assert(!std::prev(PrevI
.getIterator())->isTerminator() &&
245 "Must only have this one terminator prior to the split!");
247 // Grab the one successor edge that will stay in `MBB`.
248 MachineBasicBlock
&UnsplitSucc
= *PrevI
.getOperand(0).getMBB();
250 // Analyze the original block to see if we are actually splitting an edge
251 // into two edges. This can happen when we have multiple conditional jumps to
252 // the same successor.
254 std::any_of(SplitI
.getIterator(), MBB
.instr_end(),
255 [&](MachineInstr
&MI
) {
256 assert(MI
.isTerminator() &&
257 "Should only have spliced terminators!");
259 MI
.operands(), [&](MachineOperand
&MOp
) {
260 return MOp
.isMBB() && MOp
.getMBB() == &UnsplitSucc
;
263 MBB
.getFallThrough() == &UnsplitSucc
;
265 MachineBasicBlock
&NewMBB
= *MF
.CreateMachineBasicBlock();
267 // Insert the new block immediately after the current one. Any existing
268 // fallthrough will be sunk into this new block anyways.
269 MF
.insert(std::next(MachineFunction::iterator(&MBB
)), &NewMBB
);
271 // Splice the tail of instructions into the new block.
272 NewMBB
.splice(NewMBB
.end(), &MBB
, SplitI
.getIterator(), MBB
.end());
274 // Copy the necessary succesors (and their probability info) into the new
276 for (auto SI
= MBB
.succ_begin(), SE
= MBB
.succ_end(); SI
!= SE
; ++SI
)
277 if (IsEdgeSplit
|| *SI
!= &UnsplitSucc
)
278 NewMBB
.copySuccessor(&MBB
, SI
);
279 // Normalize the probabilities if we didn't end up splitting the edge.
281 NewMBB
.normalizeSuccProbs();
283 // Now replace all of the moved successors in the original block with the new
284 // block. This will merge their probabilities.
285 for (MachineBasicBlock
*Succ
: NewMBB
.successors())
286 if (Succ
!= &UnsplitSucc
)
287 MBB
.replaceSuccessor(Succ
, &NewMBB
);
289 // We should always end up replacing at least one successor.
290 assert(MBB
.isSuccessor(&NewMBB
) &&
291 "Failed to make the new block a successor!");
293 // Now update all the PHIs.
294 for (MachineBasicBlock
*Succ
: NewMBB
.successors()) {
295 for (MachineInstr
&MI
: *Succ
) {
299 for (int OpIdx
= 1, NumOps
= MI
.getNumOperands(); OpIdx
< NumOps
;
301 MachineOperand
&OpV
= MI
.getOperand(OpIdx
);
302 MachineOperand
&OpMBB
= MI
.getOperand(OpIdx
+ 1);
303 assert(OpMBB
.isMBB() && "Block operand to a PHI is not a block!");
304 if (OpMBB
.getMBB() != &MBB
)
307 // Replace the operand for unsplit successors
308 if (!IsEdgeSplit
|| Succ
!= &UnsplitSucc
) {
309 OpMBB
.setMBB(&NewMBB
);
311 // We have to continue scanning as there may be multiple entries in
316 // When we have split the edge append a new successor.
317 MI
.addOperand(MF
, OpV
);
318 MI
.addOperand(MF
, MachineOperand::CreateMBB(&NewMBB
));
327 static X86::CondCode
getCondFromFCMOV(unsigned Opcode
) {
329 default: return X86::COND_INVALID
;
330 case X86::CMOVBE_Fp32
: case X86::CMOVBE_Fp64
: case X86::CMOVBE_Fp80
:
332 case X86::CMOVB_Fp32
: case X86::CMOVB_Fp64
: case X86::CMOVB_Fp80
:
334 case X86::CMOVE_Fp32
: case X86::CMOVE_Fp64
: case X86::CMOVE_Fp80
:
336 case X86::CMOVNBE_Fp32
: case X86::CMOVNBE_Fp64
: case X86::CMOVNBE_Fp80
:
338 case X86::CMOVNB_Fp32
: case X86::CMOVNB_Fp64
: case X86::CMOVNB_Fp80
:
340 case X86::CMOVNE_Fp32
: case X86::CMOVNE_Fp64
: case X86::CMOVNE_Fp80
:
342 case X86::CMOVNP_Fp32
: case X86::CMOVNP_Fp64
: case X86::CMOVNP_Fp80
:
344 case X86::CMOVP_Fp32
: case X86::CMOVP_Fp64
: case X86::CMOVP_Fp80
:
349 bool X86FlagsCopyLoweringPass::runOnMachineFunction(MachineFunction
&MF
) {
350 LLVM_DEBUG(dbgs() << "********** " << getPassName() << " : " << MF
.getName()
353 Subtarget
= &MF
.getSubtarget
<X86Subtarget
>();
354 MRI
= &MF
.getRegInfo();
355 TII
= Subtarget
->getInstrInfo();
356 TRI
= Subtarget
->getRegisterInfo();
357 MDT
= &getAnalysis
<MachineDominatorTree
>();
358 PromoteRC
= &X86::GR8RegClass
;
360 if (MF
.begin() == MF
.end())
361 // Nothing to do for a degenerate empty function...
364 // Collect the copies in RPO so that when there are chains where a copy is in
365 // turn copied again we visit the first one first. This ensures we can find
366 // viable locations for testing the original EFLAGS that dominate all the
367 // uses across complex CFGs.
368 SmallVector
<MachineInstr
*, 4> Copies
;
369 ReversePostOrderTraversal
<MachineFunction
*> RPOT(&MF
);
370 for (MachineBasicBlock
*MBB
: RPOT
)
371 for (MachineInstr
&MI
: *MBB
)
372 if (MI
.getOpcode() == TargetOpcode::COPY
&&
373 MI
.getOperand(0).getReg() == X86::EFLAGS
)
374 Copies
.push_back(&MI
);
376 for (MachineInstr
*CopyI
: Copies
) {
377 MachineBasicBlock
&MBB
= *CopyI
->getParent();
379 MachineOperand
&VOp
= CopyI
->getOperand(1);
380 assert(VOp
.isReg() &&
381 "The input to the copy for EFLAGS should always be a register!");
382 MachineInstr
&CopyDefI
= *MRI
->getVRegDef(VOp
.getReg());
383 if (CopyDefI
.getOpcode() != TargetOpcode::COPY
) {
384 // FIXME: The big likely candidate here are PHI nodes. We could in theory
385 // handle PHI nodes, but it gets really, really hard. Insanely hard. Hard
386 // enough that it is probably better to change every other part of LLVM
387 // to avoid creating them. The issue is that once we have PHIs we won't
388 // know which original EFLAGS value we need to capture with our setCCs
389 // below. The end result will be computing a complete set of setCCs that
390 // we *might* want, computing them in every place where we copy *out* of
391 // EFLAGS and then doing SSA formation on all of them to insert necessary
392 // PHI nodes and consume those here. Then hoping that somehow we DCE the
393 // unnecessary ones. This DCE seems very unlikely to be successful and so
394 // we will almost certainly end up with a glut of dead setCC
395 // instructions. Until we have a motivating test case and fail to avoid
396 // it by changing other parts of LLVM's lowering, we refuse to handle
397 // this complex case here.
399 dbgs() << "ERROR: Encountered unexpected def of an eflags copy: ";
402 "Cannot lower EFLAGS copy unless it is defined in turn by a copy!");
405 auto Cleanup
= make_scope_exit([&] {
406 // All uses of the EFLAGS copy are now rewritten, kill the copy into
407 // eflags and if dead the copy from.
408 CopyI
->eraseFromParent();
409 if (MRI
->use_empty(CopyDefI
.getOperand(0).getReg()))
410 CopyDefI
.eraseFromParent();
411 ++NumCopiesEliminated
;
414 MachineOperand
&DOp
= CopyI
->getOperand(0);
415 assert(DOp
.isDef() && "Expected register def!");
416 assert(DOp
.getReg() == X86::EFLAGS
&& "Unexpected copy def register!");
420 MachineBasicBlock
*TestMBB
= CopyDefI
.getParent();
421 auto TestPos
= CopyDefI
.getIterator();
422 DebugLoc TestLoc
= CopyDefI
.getDebugLoc();
424 LLVM_DEBUG(dbgs() << "Rewriting copy: "; CopyI
->dump());
426 // Walk up across live-in EFLAGS to find where they were actually def'ed.
428 // This copy's def may just be part of a region of blocks covered by
429 // a single def of EFLAGS and we want to find the top of that region where
432 // This is essentially a search for a *candidate* reaching definition
433 // location. We don't need to ever find the actual reaching definition here,
434 // but we want to walk up the dominator tree to find the highest point which
435 // would be viable for such a definition.
436 auto HasEFLAGSClobber
= [&](MachineBasicBlock::iterator Begin
,
437 MachineBasicBlock::iterator End
) {
438 // Scan backwards as we expect these to be relatively short and often find
439 // a clobber near the end.
441 llvm::reverse(llvm::make_range(Begin
, End
)), [&](MachineInstr
&MI
) {
442 // Flag any instruction (other than the copy we are
443 // currently rewriting) that defs EFLAGS.
444 return &MI
!= CopyI
&& MI
.findRegisterDefOperand(X86::EFLAGS
);
447 auto HasEFLAGSClobberPath
= [&](MachineBasicBlock
*BeginMBB
,
448 MachineBasicBlock
*EndMBB
) {
449 assert(MDT
->dominates(BeginMBB
, EndMBB
) &&
450 "Only support paths down the dominator tree!");
451 SmallPtrSet
<MachineBasicBlock
*, 4> Visited
;
452 SmallVector
<MachineBasicBlock
*, 4> Worklist
;
453 // We terminate at the beginning. No need to scan it.
454 Visited
.insert(BeginMBB
);
455 Worklist
.push_back(EndMBB
);
457 auto *MBB
= Worklist
.pop_back_val();
458 for (auto *PredMBB
: MBB
->predecessors()) {
459 if (!Visited
.insert(PredMBB
).second
)
461 if (HasEFLAGSClobber(PredMBB
->begin(), PredMBB
->end()))
463 // Enqueue this block to walk its predecessors.
464 Worklist
.push_back(PredMBB
);
466 } while (!Worklist
.empty());
467 // No clobber found along a path from the begin to end.
470 while (TestMBB
->isLiveIn(X86::EFLAGS
) && !TestMBB
->pred_empty() &&
471 !HasEFLAGSClobber(TestMBB
->begin(), TestPos
)) {
472 // Find the nearest common dominator of the predecessors, as
473 // that will be the best candidate to hoist into.
474 MachineBasicBlock
*HoistMBB
=
475 std::accumulate(std::next(TestMBB
->pred_begin()), TestMBB
->pred_end(),
476 *TestMBB
->pred_begin(),
477 [&](MachineBasicBlock
*LHS
, MachineBasicBlock
*RHS
) {
478 return MDT
->findNearestCommonDominator(LHS
, RHS
);
481 // Now we need to scan all predecessors that may be reached along paths to
482 // the hoist block. A clobber anywhere in any of these blocks the hoist.
483 // Note that this even handles loops because we require *no* clobbers.
484 if (HasEFLAGSClobberPath(HoistMBB
, TestMBB
))
487 // We also need the terminators to not sneakily clobber flags.
488 if (HasEFLAGSClobber(HoistMBB
->getFirstTerminator()->getIterator(),
489 HoistMBB
->instr_end()))
492 // We found a viable location, hoist our test position to it.
494 TestPos
= TestMBB
->getFirstTerminator()->getIterator();
495 // Clear the debug location as it would just be confusing after hoisting.
496 TestLoc
= DebugLoc();
499 auto DefIt
= llvm::find_if(
500 llvm::reverse(llvm::make_range(TestMBB
->instr_begin(), TestPos
)),
501 [&](MachineInstr
&MI
) {
502 return MI
.findRegisterDefOperand(X86::EFLAGS
);
504 if (DefIt
.base() != TestMBB
->instr_begin()) {
505 dbgs() << " Using EFLAGS defined by: ";
508 dbgs() << " Using live-in flags for BB:\n";
513 // While rewriting uses, we buffer jumps and rewrite them in a second pass
514 // because doing so will perturb the CFG that we are walking to find the
515 // uses in the first place.
516 SmallVector
<MachineInstr
*, 4> JmpIs
;
518 // Gather the condition flags that have already been preserved in
519 // registers. We do this from scratch each time as we expect there to be
520 // very few of them and we expect to not revisit the same copy definition
521 // many times. If either of those change sufficiently we could build a map
522 // of these up front instead.
523 CondRegArray CondRegs
= collectCondsInRegs(*TestMBB
, TestPos
);
525 // Collect the basic blocks we need to scan. Typically this will just be
526 // a single basic block but we may have to scan multiple blocks if the
527 // EFLAGS copy lives into successors.
528 SmallVector
<MachineBasicBlock
*, 2> Blocks
;
529 SmallPtrSet
<MachineBasicBlock
*, 2> VisitedBlocks
;
530 Blocks
.push_back(&MBB
);
533 MachineBasicBlock
&UseMBB
= *Blocks
.pop_back_val();
535 // Track when if/when we find a kill of the flags in this block.
536 bool FlagsKilled
= false;
538 // In most cases, we walk from the beginning to the end of the block. But
539 // when the block is the same block as the copy is from, we will visit it
540 // twice. The first time we start from the copy and go to the end. The
541 // second time we start from the beginning and go to the copy. This lets
542 // us handle copies inside of cycles.
543 // FIXME: This loop is *super* confusing. This is at least in part
544 // a symptom of all of this routine needing to be refactored into
545 // documentable components. Once done, there may be a better way to write
547 for (auto MII
= (&UseMBB
== &MBB
&& !VisitedBlocks
.count(&UseMBB
))
548 ? std::next(CopyI
->getIterator())
549 : UseMBB
.instr_begin(),
550 MIE
= UseMBB
.instr_end();
552 MachineInstr
&MI
= *MII
++;
553 // If we are in the original copy block and encounter either the copy
554 // def or the copy itself, break so that we don't re-process any part of
555 // the block or process the instructions in the range that was copied
557 if (&MI
== CopyI
|| &MI
== &CopyDefI
) {
558 assert(&UseMBB
== &MBB
&& VisitedBlocks
.count(&MBB
) &&
559 "Should only encounter these on the second pass over the "
564 MachineOperand
*FlagUse
= MI
.findRegisterUseOperand(X86::EFLAGS
);
566 if (MI
.findRegisterDefOperand(X86::EFLAGS
)) {
567 // If EFLAGS are defined, it's as-if they were killed. We can stop
570 // NB!!! Many instructions only modify some flags. LLVM currently
571 // models this as clobbering all flags, but if that ever changes
572 // this will need to be carefully updated to handle that more
580 LLVM_DEBUG(dbgs() << " Rewriting use: "; MI
.dump());
582 // Check the kill flag before we rewrite as that may change it.
583 if (FlagUse
->isKill())
586 // Once we encounter a branch, the rest of the instructions must also be
587 // branches. We can't rewrite in place here, so we handle them below.
589 // Note that we don't have to handle tail calls here, even conditional
590 // tail calls, as those are not introduced into the X86 MI until post-RA
591 // branch folding or black placement. As a consequence, we get to deal
592 // with the simpler formulation of conditional branches followed by tail
594 if (X86::getCondFromBranch(MI
) != X86::COND_INVALID
) {
595 auto JmpIt
= MI
.getIterator();
597 JmpIs
.push_back(&*JmpIt
);
599 } while (JmpIt
!= UseMBB
.instr_end() &&
600 X86::getCondFromBranch(*JmpIt
) !=
605 // Otherwise we can just rewrite in-place.
606 if (X86::getCondFromCMov(MI
) != X86::COND_INVALID
) {
607 rewriteCMov(*TestMBB
, TestPos
, TestLoc
, MI
, *FlagUse
, CondRegs
);
608 } else if (getCondFromFCMOV(MI
.getOpcode()) != X86::COND_INVALID
) {
609 rewriteFCMov(*TestMBB
, TestPos
, TestLoc
, MI
, *FlagUse
, CondRegs
);
610 } else if (X86::getCondFromSETCC(MI
) != X86::COND_INVALID
) {
611 rewriteSetCC(*TestMBB
, TestPos
, TestLoc
, MI
, *FlagUse
, CondRegs
);
612 } else if (MI
.getOpcode() == TargetOpcode::COPY
) {
613 rewriteCopy(MI
, *FlagUse
, CopyDefI
);
615 // We assume all other instructions that use flags also def them.
616 assert(MI
.findRegisterDefOperand(X86::EFLAGS
) &&
617 "Expected a def of EFLAGS for this instruction!");
619 // NB!!! Several arithmetic instructions only *partially* update
620 // flags. Theoretically, we could generate MI code sequences that
621 // would rely on this fact and observe different flags independently.
622 // But currently LLVM models all of these instructions as clobbering
623 // all the flags in an undef way. We rely on that to simplify the
627 // Generically handle remaining uses as arithmetic instructions.
628 rewriteArithmetic(*TestMBB
, TestPos
, TestLoc
, MI
, *FlagUse
,
632 // If this was the last use of the flags, we're done.
637 // If the flags were killed, we're done with this block.
641 // Otherwise we need to scan successors for ones where the flags live-in
642 // and queue those up for processing.
643 for (MachineBasicBlock
*SuccMBB
: UseMBB
.successors())
644 if (SuccMBB
->isLiveIn(X86::EFLAGS
) &&
645 VisitedBlocks
.insert(SuccMBB
).second
) {
646 // We currently don't do any PHI insertion and so we require that the
647 // test basic block dominates all of the use basic blocks. Further, we
648 // can't have a cycle from the test block back to itself as that would
649 // create a cycle requiring a PHI to break it.
651 // We could in theory do PHI insertion here if it becomes useful by
652 // just taking undef values in along every edge that we don't trace
653 // this EFLAGS copy along. This isn't as bad as fully general PHI
654 // insertion, but still seems like a great deal of complexity.
656 // Because it is theoretically possible that some earlier MI pass or
657 // other lowering transformation could induce this to happen, we do
658 // a hard check even in non-debug builds here.
659 if (SuccMBB
== TestMBB
|| !MDT
->dominates(TestMBB
, SuccMBB
)) {
662 << "ERROR: Encountered use that is not dominated by our test "
663 "basic block! Rewriting this would require inserting PHI "
664 "nodes to track the flag state across the CFG.\n\nTest "
667 dbgs() << "Use block:\n";
671 "Cannot lower EFLAGS copy when original copy def "
672 "does not dominate all uses.");
675 Blocks
.push_back(SuccMBB
);
677 // After this, EFLAGS will be recreated before each use.
678 SuccMBB
->removeLiveIn(X86::EFLAGS
);
680 } while (!Blocks
.empty());
682 // Now rewrite the jumps that use the flags. These we handle specially
683 // because if there are multiple jumps in a single basic block we'll have
684 // to do surgery on the CFG.
685 MachineBasicBlock
*LastJmpMBB
= nullptr;
686 for (MachineInstr
*JmpI
: JmpIs
) {
687 // Past the first jump within a basic block we need to split the blocks
689 if (JmpI
->getParent() == LastJmpMBB
)
690 splitBlock(*JmpI
->getParent(), *JmpI
, *TII
);
692 LastJmpMBB
= JmpI
->getParent();
694 rewriteCondJmp(*TestMBB
, TestPos
, TestLoc
, *JmpI
, CondRegs
);
697 // FIXME: Mark the last use of EFLAGS before the copy's def as a kill if
698 // the copy's def operand is itself a kill.
702 for (MachineBasicBlock
&MBB
: MF
)
703 for (MachineInstr
&MI
: MBB
)
704 if (MI
.getOpcode() == TargetOpcode::COPY
&&
705 (MI
.getOperand(0).getReg() == X86::EFLAGS
||
706 MI
.getOperand(1).getReg() == X86::EFLAGS
)) {
707 LLVM_DEBUG(dbgs() << "ERROR: Found a COPY involving EFLAGS: ";
709 llvm_unreachable("Unlowered EFLAGS copy!");
716 /// Collect any conditions that have already been set in registers so that we
717 /// can re-use them rather than adding duplicates.
718 CondRegArray
X86FlagsCopyLoweringPass::collectCondsInRegs(
719 MachineBasicBlock
&MBB
, MachineBasicBlock::iterator TestPos
) {
720 CondRegArray CondRegs
= {};
722 // Scan backwards across the range of instructions with live EFLAGS.
723 for (MachineInstr
&MI
:
724 llvm::reverse(llvm::make_range(MBB
.begin(), TestPos
))) {
725 X86::CondCode Cond
= X86::getCondFromSETCC(MI
);
726 if (Cond
!= X86::COND_INVALID
&& !MI
.mayStore() &&
727 MI
.getOperand(0).isReg() && MI
.getOperand(0).getReg().isVirtual()) {
728 assert(MI
.getOperand(0).isDef() &&
729 "A non-storing SETcc should always define a register!");
730 CondRegs
[Cond
] = MI
.getOperand(0).getReg();
733 // Stop scanning when we see the first definition of the EFLAGS as prior to
734 // this we would potentially capture the wrong flag state.
735 if (MI
.findRegisterDefOperand(X86::EFLAGS
))
741 Register
X86FlagsCopyLoweringPass::promoteCondToReg(
742 MachineBasicBlock
&TestMBB
, MachineBasicBlock::iterator TestPos
,
743 const DebugLoc
&TestLoc
, X86::CondCode Cond
) {
744 Register Reg
= MRI
->createVirtualRegister(PromoteRC
);
745 auto SetI
= BuildMI(TestMBB
, TestPos
, TestLoc
,
746 TII
->get(X86::SETCCr
), Reg
).addImm(Cond
);
748 LLVM_DEBUG(dbgs() << " save cond: "; SetI
->dump());
753 std::pair
<unsigned, bool> X86FlagsCopyLoweringPass::getCondOrInverseInReg(
754 MachineBasicBlock
&TestMBB
, MachineBasicBlock::iterator TestPos
,
755 const DebugLoc
&TestLoc
, X86::CondCode Cond
, CondRegArray
&CondRegs
) {
756 unsigned &CondReg
= CondRegs
[Cond
];
757 unsigned &InvCondReg
= CondRegs
[X86::GetOppositeBranchCondition(Cond
)];
758 if (!CondReg
&& !InvCondReg
)
759 CondReg
= promoteCondToReg(TestMBB
, TestPos
, TestLoc
, Cond
);
762 return {CondReg
, false};
764 return {InvCondReg
, true};
767 void X86FlagsCopyLoweringPass::insertTest(MachineBasicBlock
&MBB
,
768 MachineBasicBlock::iterator Pos
,
769 const DebugLoc
&Loc
, unsigned Reg
) {
771 BuildMI(MBB
, Pos
, Loc
, TII
->get(X86::TEST8rr
)).addReg(Reg
).addReg(Reg
);
773 LLVM_DEBUG(dbgs() << " test cond: "; TestI
->dump());
777 void X86FlagsCopyLoweringPass::rewriteArithmetic(
778 MachineBasicBlock
&TestMBB
, MachineBasicBlock::iterator TestPos
,
779 const DebugLoc
&TestLoc
, MachineInstr
&MI
, MachineOperand
&FlagUse
,
780 CondRegArray
&CondRegs
) {
781 // Arithmetic is either reading CF or OF. Figure out which condition we need
782 // to preserve in a register.
783 X86::CondCode Cond
= X86::COND_INVALID
;
785 // The addend to use to reset CF or OF when added to the flag value.
788 switch (getMnemonicFromOpcode(MI
.getOpcode())) {
789 case FlagArithMnemonic::ADC
:
790 case FlagArithMnemonic::RCL
:
791 case FlagArithMnemonic::RCR
:
792 case FlagArithMnemonic::SBB
:
793 case FlagArithMnemonic::SETB
:
794 Cond
= X86::COND_B
; // CF == 1
795 // Set up an addend that when one is added will need a carry due to not
796 // having a higher bit available.
801 // Now get a register that contains the value of the flag input to the
802 // arithmetic. We require exactly this flag to simplify the arithmetic
803 // required to materialize it back into the flag.
804 unsigned &CondReg
= CondRegs
[Cond
];
806 CondReg
= promoteCondToReg(TestMBB
, TestPos
, TestLoc
, Cond
);
808 MachineBasicBlock
&MBB
= *MI
.getParent();
810 // Insert an instruction that will set the flag back to the desired value.
811 Register TmpReg
= MRI
->createVirtualRegister(PromoteRC
);
813 BuildMI(MBB
, MI
.getIterator(), MI
.getDebugLoc(), TII
->get(X86::ADD8ri
))
814 .addDef(TmpReg
, RegState::Dead
)
818 LLVM_DEBUG(dbgs() << " add cond: "; AddI
->dump());
820 FlagUse
.setIsKill(true);
823 void X86FlagsCopyLoweringPass::rewriteCMov(MachineBasicBlock
&TestMBB
,
824 MachineBasicBlock::iterator TestPos
,
825 const DebugLoc
&TestLoc
,
827 MachineOperand
&FlagUse
,
828 CondRegArray
&CondRegs
) {
829 // First get the register containing this specific condition.
830 X86::CondCode Cond
= X86::getCondFromCMov(CMovI
);
833 std::tie(CondReg
, Inverted
) =
834 getCondOrInverseInReg(TestMBB
, TestPos
, TestLoc
, Cond
, CondRegs
);
836 MachineBasicBlock
&MBB
= *CMovI
.getParent();
838 // Insert a direct test of the saved register.
839 insertTest(MBB
, CMovI
.getIterator(), CMovI
.getDebugLoc(), CondReg
);
841 // Rewrite the CMov to use the !ZF flag from the test, and then kill its use
842 // of the flags afterward.
843 CMovI
.getOperand(CMovI
.getDesc().getNumOperands() - 1)
844 .setImm(Inverted
? X86::COND_E
: X86::COND_NE
);
845 FlagUse
.setIsKill(true);
846 LLVM_DEBUG(dbgs() << " fixed cmov: "; CMovI
.dump());
849 void X86FlagsCopyLoweringPass::rewriteFCMov(MachineBasicBlock
&TestMBB
,
850 MachineBasicBlock::iterator TestPos
,
851 const DebugLoc
&TestLoc
,
853 MachineOperand
&FlagUse
,
854 CondRegArray
&CondRegs
) {
855 // First get the register containing this specific condition.
856 X86::CondCode Cond
= getCondFromFCMOV(CMovI
.getOpcode());
859 std::tie(CondReg
, Inverted
) =
860 getCondOrInverseInReg(TestMBB
, TestPos
, TestLoc
, Cond
, CondRegs
);
862 MachineBasicBlock
&MBB
= *CMovI
.getParent();
864 // Insert a direct test of the saved register.
865 insertTest(MBB
, CMovI
.getIterator(), CMovI
.getDebugLoc(), CondReg
);
867 auto getFCMOVOpcode
= [](unsigned Opcode
, bool Inverted
) {
869 default: llvm_unreachable("Unexpected opcode!");
870 case X86::CMOVBE_Fp32
: case X86::CMOVNBE_Fp32
:
871 case X86::CMOVB_Fp32
: case X86::CMOVNB_Fp32
:
872 case X86::CMOVE_Fp32
: case X86::CMOVNE_Fp32
:
873 case X86::CMOVP_Fp32
: case X86::CMOVNP_Fp32
:
874 return Inverted
? X86::CMOVE_Fp32
: X86::CMOVNE_Fp32
;
875 case X86::CMOVBE_Fp64
: case X86::CMOVNBE_Fp64
:
876 case X86::CMOVB_Fp64
: case X86::CMOVNB_Fp64
:
877 case X86::CMOVE_Fp64
: case X86::CMOVNE_Fp64
:
878 case X86::CMOVP_Fp64
: case X86::CMOVNP_Fp64
:
879 return Inverted
? X86::CMOVE_Fp64
: X86::CMOVNE_Fp64
;
880 case X86::CMOVBE_Fp80
: case X86::CMOVNBE_Fp80
:
881 case X86::CMOVB_Fp80
: case X86::CMOVNB_Fp80
:
882 case X86::CMOVE_Fp80
: case X86::CMOVNE_Fp80
:
883 case X86::CMOVP_Fp80
: case X86::CMOVNP_Fp80
:
884 return Inverted
? X86::CMOVE_Fp80
: X86::CMOVNE_Fp80
;
888 // Rewrite the CMov to use the !ZF flag from the test.
889 CMovI
.setDesc(TII
->get(getFCMOVOpcode(CMovI
.getOpcode(), Inverted
)));
890 FlagUse
.setIsKill(true);
891 LLVM_DEBUG(dbgs() << " fixed fcmov: "; CMovI
.dump());
894 void X86FlagsCopyLoweringPass::rewriteCondJmp(
895 MachineBasicBlock
&TestMBB
, MachineBasicBlock::iterator TestPos
,
896 const DebugLoc
&TestLoc
, MachineInstr
&JmpI
, CondRegArray
&CondRegs
) {
897 // First get the register containing this specific condition.
898 X86::CondCode Cond
= X86::getCondFromBranch(JmpI
);
901 std::tie(CondReg
, Inverted
) =
902 getCondOrInverseInReg(TestMBB
, TestPos
, TestLoc
, Cond
, CondRegs
);
904 MachineBasicBlock
&JmpMBB
= *JmpI
.getParent();
906 // Insert a direct test of the saved register.
907 insertTest(JmpMBB
, JmpI
.getIterator(), JmpI
.getDebugLoc(), CondReg
);
909 // Rewrite the jump to use the !ZF flag from the test, and kill its use of
911 JmpI
.getOperand(1).setImm(Inverted
? X86::COND_E
: X86::COND_NE
);
912 JmpI
.findRegisterUseOperand(X86::EFLAGS
)->setIsKill(true);
913 LLVM_DEBUG(dbgs() << " fixed jCC: "; JmpI
.dump());
916 void X86FlagsCopyLoweringPass::rewriteCopy(MachineInstr
&MI
,
917 MachineOperand
&FlagUse
,
918 MachineInstr
&CopyDefI
) {
919 // Just replace this copy with the original copy def.
920 MRI
->replaceRegWith(MI
.getOperand(0).getReg(),
921 CopyDefI
.getOperand(0).getReg());
922 MI
.eraseFromParent();
925 void X86FlagsCopyLoweringPass::rewriteSetCC(MachineBasicBlock
&TestMBB
,
926 MachineBasicBlock::iterator TestPos
,
927 const DebugLoc
&TestLoc
,
928 MachineInstr
&SetCCI
,
929 MachineOperand
&FlagUse
,
930 CondRegArray
&CondRegs
) {
931 X86::CondCode Cond
= X86::getCondFromSETCC(SetCCI
);
932 // Note that we can't usefully rewrite this to the inverse without complex
933 // analysis of the users of the setCC. Largely we rely on duplicates which
934 // could have been avoided already being avoided here.
935 unsigned &CondReg
= CondRegs
[Cond
];
937 CondReg
= promoteCondToReg(TestMBB
, TestPos
, TestLoc
, Cond
);
939 // Rewriting a register def is trivial: we just replace the register and
941 if (!SetCCI
.mayStore()) {
942 assert(SetCCI
.getOperand(0).isReg() &&
943 "Cannot have a non-register defined operand to SETcc!");
944 Register OldReg
= SetCCI
.getOperand(0).getReg();
945 // Drop Kill flags on the old register before replacing. CondReg may have
946 // a longer live range.
947 MRI
->clearKillFlags(OldReg
);
948 MRI
->replaceRegWith(OldReg
, CondReg
);
949 SetCCI
.eraseFromParent();
953 // Otherwise, we need to emit a store.
954 auto MIB
= BuildMI(*SetCCI
.getParent(), SetCCI
.getIterator(),
955 SetCCI
.getDebugLoc(), TII
->get(X86::MOV8mr
));
956 // Copy the address operands.
957 for (int i
= 0; i
< X86::AddrNumOperands
; ++i
)
958 MIB
.add(SetCCI
.getOperand(i
));
962 MIB
.setMemRefs(SetCCI
.memoperands());
964 SetCCI
.eraseFromParent();