1//====- X86FlagsCopyLowering.cpp - Lowers COPY nodes of EFLAGS ------------===//
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/// \file
9///
10/// Lowers COPY nodes of EFLAGS by directly extracting and preserving individual
11/// flag bits.
12///
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.
20///
21//===----------------------------------------------------------------------===//
22
23#include "X86.h"
24#include "X86InstrInfo.h"
25#include "X86Subtarget.h"
26#include "llvm/ADT/DepthFirstIterator.h"
27#include "llvm/ADT/PostOrderIterator.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/ScopeExit.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/Statistic.h"
33#include "llvm/CodeGen/MachineBasicBlock.h"
34#include "llvm/CodeGen/MachineConstantPool.h"
35#include "llvm/CodeGen/MachineDominators.h"
36#include "llvm/CodeGen/MachineFunction.h"
37#include "llvm/CodeGen/MachineFunctionAnalysisManager.h"
38#include "llvm/CodeGen/MachineFunctionPass.h"
39#include "llvm/CodeGen/MachineInstr.h"
40#include "llvm/CodeGen/MachineInstrBuilder.h"
41#include "llvm/CodeGen/MachineModuleInfo.h"
42#include "llvm/CodeGen/MachineOperand.h"
43#include "llvm/CodeGen/MachinePassManager.h"
44#include "llvm/CodeGen/MachineRegisterInfo.h"
45#include "llvm/CodeGen/MachineSSAUpdater.h"
46#include "llvm/CodeGen/RegisterClassInfo.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/Analysis.h"
52#include "llvm/IR/DebugLoc.h"
53#include "llvm/MC/MCSchedule.h"
54#include "llvm/Pass.h"
55#include "llvm/Support/Debug.h"
56#include "llvm/Support/raw_ostream.h"
57#include <cassert>
58#include <iterator>
59#include <utility>
60
61using namespace llvm;
62
63#define PASS_KEY "x86-flags-copy-lowering"
64#define DEBUG_TYPE PASS_KEY
65
66STATISTIC(NumCopiesEliminated, "Number of copies of EFLAGS eliminated");
67STATISTIC(NumSetCCsInserted, "Number of setCC instructions inserted");
68STATISTIC(NumTestsInserted, "Number of test instructions inserted");
69STATISTIC(NumAddsInserted, "Number of adds instructions inserted");
70STATISTIC(NumNFsConvertedTo, "Number of NF instructions converted to");
71
72namespace {
73
74// Convenient array type for storing registers associated with each condition.
75using CondRegArray = std::array<Register, X86::LAST_VALID_COND + 1>;
76
77class X86FlagsCopyLoweringImpl {
78public:
79 X86FlagsCopyLoweringImpl(MachineDominatorTree *MDT) : MDT(MDT) {}
80
81 bool runOnMachineFunction(MachineFunction &MF);
82
83private:
84 MachineRegisterInfo *MRI = nullptr;
85 const X86Subtarget *Subtarget = nullptr;
86 const X86InstrInfo *TII = nullptr;
87 const TargetRegisterInfo *TRI = nullptr;
88 const TargetRegisterClass *PromoteRC = nullptr;
89 MachineDominatorTree *MDT = nullptr;
90
91 CondRegArray collectCondsInRegs(MachineBasicBlock &MBB,
92 MachineBasicBlock::iterator CopyDefI);
93
94 Register promoteCondToReg(MachineBasicBlock &MBB,
95 MachineBasicBlock::iterator TestPos,
96 const DebugLoc &TestLoc, X86::CondCode Cond);
97 std::pair<Register, bool> getCondOrInverseInReg(
98 MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
99 const DebugLoc &TestLoc, X86::CondCode Cond, CondRegArray &CondRegs);
100 void insertTest(MachineBasicBlock &MBB, MachineBasicBlock::iterator Pos,
101 const DebugLoc &Loc, Register Reg);
102
103 void rewriteSetCC(MachineBasicBlock &MBB, MachineBasicBlock::iterator Pos,
104 const DebugLoc &Loc, MachineInstr &MI,
105 CondRegArray &CondRegs);
106 void rewriteArithmetic(MachineBasicBlock &MBB,
107 MachineBasicBlock::iterator Pos, const DebugLoc &Loc,
108 MachineInstr &MI, CondRegArray &CondRegs);
109 void rewriteMI(MachineBasicBlock &MBB, MachineBasicBlock::iterator Pos,
110 const DebugLoc &Loc, MachineInstr &MI, CondRegArray &CondRegs);
111};
112
113class X86FlagsCopyLoweringLegacy : public MachineFunctionPass {
114public:
115 X86FlagsCopyLoweringLegacy() : MachineFunctionPass(ID) {}
116
117 StringRef getPassName() const override { return "X86 EFLAGS copy lowering"; }
118 bool runOnMachineFunction(MachineFunction &MF) override;
119 void getAnalysisUsage(AnalysisUsage &AU) const override;
120
121 /// Pass identification, replacement for typeid.
122 static char ID;
123};
124
125} // end anonymous namespace
126
127INITIALIZE_PASS_BEGIN(X86FlagsCopyLoweringLegacy, DEBUG_TYPE,
128 "X86 EFLAGS copy lowering", false, false)
129INITIALIZE_PASS_END(X86FlagsCopyLoweringLegacy, DEBUG_TYPE,
130 "X86 EFLAGS copy lowering", false, false)
131
132FunctionPass *llvm::createX86FlagsCopyLoweringLegacyPass() {
133 return new X86FlagsCopyLoweringLegacy();
134}
135
136char X86FlagsCopyLoweringLegacy::ID = 0;
137
138void X86FlagsCopyLoweringLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
139 AU.addUsedIfAvailable<MachineDominatorTreeWrapperPass>();
140 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
141 MachineFunctionPass::getAnalysisUsage(AU);
142}
143
144static bool isArithmeticOp(unsigned Opc) {
145 return X86::isADC(Opcode: Opc) || X86::isSBB(Opcode: Opc) || X86::isRCL(Opcode: Opc) ||
146 X86::isRCR(Opcode: Opc) || (Opc == X86::SETB_C32r || Opc == X86::SETB_C64r);
147}
148
149static MachineBasicBlock &splitBlock(MachineBasicBlock &MBB,
150 MachineInstr &SplitI,
151 const X86InstrInfo &TII) {
152 MachineFunction &MF = *MBB.getParent();
153
154 assert(SplitI.getParent() == &MBB &&
155 "Split instruction must be in the split block!");
156 assert(SplitI.isBranch() &&
157 "Only designed to split a tail of branch instructions!");
158 assert(X86::getCondFromBranch(SplitI) != X86::COND_INVALID &&
159 "Must split on an actual jCC instruction!");
160
161 // Dig out the previous instruction to the split point.
162 MachineInstr &PrevI = *std::prev(x: SplitI.getIterator());
163 assert(PrevI.isBranch() && "Must split after a branch!");
164 assert(X86::getCondFromBranch(PrevI) != X86::COND_INVALID &&
165 "Must split after an actual jCC instruction!");
166 assert(!std::prev(PrevI.getIterator())->isTerminator() &&
167 "Must only have this one terminator prior to the split!");
168
169 // Grab the one successor edge that will stay in `MBB`.
170 MachineBasicBlock &UnsplitSucc = *PrevI.getOperand(i: 0).getMBB();
171
172 // Analyze the original block to see if we are actually splitting an edge
173 // into two edges. This can happen when we have multiple conditional jumps to
174 // the same successor.
175 bool IsEdgeSplit =
176 std::any_of(first: SplitI.getIterator(), last: MBB.instr_end(),
177 pred: [&](MachineInstr &MI) {
178 assert(MI.isTerminator() &&
179 "Should only have spliced terminators!");
180 return llvm::any_of(
181 Range: MI.operands(), P: [&](MachineOperand &MOp) {
182 return MOp.isMBB() && MOp.getMBB() == &UnsplitSucc;
183 });
184 }) ||
185 MBB.getFallThrough() == &UnsplitSucc;
186
187 MachineBasicBlock &NewMBB = *MF.CreateMachineBasicBlock();
188
189 // Insert the new block immediately after the current one. Any existing
190 // fallthrough will be sunk into this new block anyways.
191 MF.insert(MBBI: std::next(x: MachineFunction::iterator(&MBB)), MBB: &NewMBB);
192
193 // Splice the tail of instructions into the new block.
194 NewMBB.splice(Where: NewMBB.end(), Other: &MBB, From: SplitI.getIterator(), To: MBB.end());
195
196 // Copy the necessary succesors (and their probability info) into the new
197 // block.
198 for (auto SI = MBB.succ_begin(), SE = MBB.succ_end(); SI != SE; ++SI)
199 if (IsEdgeSplit || *SI != &UnsplitSucc)
200 NewMBB.copySuccessor(Orig: &MBB, I: SI);
201 // Normalize the probabilities if we didn't end up splitting the edge.
202 if (!IsEdgeSplit)
203 NewMBB.normalizeSuccProbs();
204
205 // Now replace all of the moved successors in the original block with the new
206 // block. This will merge their probabilities.
207 for (MachineBasicBlock *Succ : NewMBB.successors())
208 if (Succ != &UnsplitSucc)
209 MBB.replaceSuccessor(Old: Succ, New: &NewMBB);
210
211 // We should always end up replacing at least one successor.
212 assert(MBB.isSuccessor(&NewMBB) &&
213 "Failed to make the new block a successor!");
214
215 // Now update all the PHIs.
216 for (MachineBasicBlock *Succ : NewMBB.successors()) {
217 for (MachineInstr &MI : *Succ) {
218 if (!MI.isPHI())
219 break;
220
221 for (int OpIdx = 1, NumOps = MI.getNumOperands(); OpIdx < NumOps;
222 OpIdx += 2) {
223 MachineOperand &OpV = MI.getOperand(i: OpIdx);
224 MachineOperand &OpMBB = MI.getOperand(i: OpIdx + 1);
225 assert(OpMBB.isMBB() && "Block operand to a PHI is not a block!");
226 if (OpMBB.getMBB() != &MBB)
227 continue;
228
229 // Replace the operand for unsplit successors
230 if (!IsEdgeSplit || Succ != &UnsplitSucc) {
231 OpMBB.setMBB(&NewMBB);
232
233 // We have to continue scanning as there may be multiple entries in
234 // the PHI.
235 continue;
236 }
237
238 // When we have split the edge append a new successor.
239 MI.addOperand(MF, Op: OpV);
240 MI.addOperand(MF, Op: MachineOperand::CreateMBB(MBB: &NewMBB));
241 break;
242 }
243 }
244 }
245
246 return NewMBB;
247}
248
249enum EFLAGSClobber { NoClobber, EvitableClobber, InevitableClobber };
250
251static EFLAGSClobber getClobberType(const MachineInstr &MI) {
252 const MachineOperand *FlagDef =
253 MI.findRegisterDefOperand(Reg: X86::EFLAGS, /*TRI=*/nullptr);
254 if (!FlagDef)
255 return NoClobber;
256
257 if (X86::getNFVariantIfClobberRemovable(MI))
258 return EvitableClobber;
259
260 return InevitableClobber;
261}
262
263bool X86FlagsCopyLoweringImpl::runOnMachineFunction(MachineFunction &MF) {
264 LLVM_DEBUG(dbgs() << "********** " << PASS_KEY << " : " << MF.getName()
265 << " **********\n");
266
267 Subtarget = &MF.getSubtarget<X86Subtarget>();
268 MRI = &MF.getRegInfo();
269 TII = Subtarget->getInstrInfo();
270 TRI = Subtarget->getRegisterInfo();
271 PromoteRC = &X86::GR8RegClass;
272
273 if (MF.empty())
274 // Nothing to do for a degenerate empty function...
275 return false;
276
277 if (none_of(Range: MRI->def_instructions(Reg: X86::EFLAGS), P: [](const MachineInstr &MI) {
278 return MI.getOpcode() == TargetOpcode::COPY;
279 }))
280 return false;
281
282 // We change the code, so we don't preserve the dominator tree anyway. If we
283 // got a valid MDT from the pass manager, use that, otherwise construct one
284 // now. This is an optimization that avoids unnecessary MDT construction for
285 // functions that have no flag copies.
286 std::unique_ptr<MachineDominatorTree> OwnedMDT;
287 if (!MDT) {
288 OwnedMDT = std::make_unique<MachineDominatorTree>(args&: MF);
289 MDT = OwnedMDT.get();
290 }
291
292 // Collect the copies in RPO so that when there are chains where a copy is in
293 // turn copied again we visit the first one first. This ensures we can find
294 // viable locations for testing the original EFLAGS that dominate all the
295 // uses across complex CFGs.
296 SmallSetVector<MachineInstr *, 4> Copies;
297 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
298 for (MachineBasicBlock *MBB : RPOT)
299 for (MachineInstr &MI : *MBB)
300 if (MI.getOpcode() == TargetOpcode::COPY &&
301 MI.getOperand(i: 0).getReg() == X86::EFLAGS)
302 Copies.insert(X: &MI);
303
304 // Try to elminate the copys by transform the instructions between copy and
305 // copydef to the NF (no flags update) variants, e.g.
306 //
307 // %1:gr64 = COPY $eflags
308 // OP1 implicit-def dead $eflags
309 // $eflags = COPY %1
310 // OP2 cc, implicit $eflags
311 //
312 // ->
313 //
314 // OP1_NF
315 // OP2 implicit $eflags
316 if (Subtarget->hasNF()) {
317 SmallSetVector<MachineInstr *, 4> RemovedCopies;
318 // CopyIIt may be invalidated by removing copies.
319 auto CopyIIt = Copies.begin(), CopyIEnd = Copies.end();
320 while (CopyIIt != CopyIEnd) {
321 auto NCopyIIt = std::next(x: CopyIIt);
322 SmallSetVector<MachineInstr *, 4> EvitableClobbers;
323 MachineInstr *CopyI = *CopyIIt;
324 MachineOperand &VOp = CopyI->getOperand(i: 1);
325 MachineInstr *CopyDefI = MRI->getVRegDef(Reg: VOp.getReg());
326 MachineBasicBlock *CopyIMBB = CopyI->getParent();
327 MachineBasicBlock *CopyDefIMBB = CopyDefI->getParent();
328 // Walk all basic blocks reachable in depth-first iteration on the inverse
329 // CFG from CopyIMBB to CopyDefIMBB. These blocks are all the blocks that
330 // may be executed between the execution of CopyDefIMBB and CopyIMBB. On
331 // all execution paths, instructions from CopyDefI to CopyI (exclusive)
332 // has to be NF-convertible if it clobbers flags.
333 for (auto BI = idf_begin(G: CopyIMBB), BE = idf_end(G: CopyDefIMBB); BI != BE;
334 ++BI) {
335 MachineBasicBlock *MBB = *BI;
336 for (auto I = (MBB != CopyDefIMBB)
337 ? MBB->begin()
338 : std::next(x: MachineBasicBlock::iterator(CopyDefI)),
339 E = (MBB != CopyIMBB) ? MBB->end()
340 : MachineBasicBlock::iterator(CopyI);
341 I != E; ++I) {
342 MachineInstr &MI = *I;
343 EFLAGSClobber ClobberType = getClobberType(MI);
344 if (ClobberType == NoClobber)
345 continue;
346
347 if (ClobberType == InevitableClobber)
348 goto ProcessNextCopyI;
349
350 assert(ClobberType == EvitableClobber && "unexpected workflow");
351 EvitableClobbers.insert(X: &MI);
352 }
353 }
354 // Covert evitable clobbers into NF variants and remove the copyies.
355 RemovedCopies.insert(X: CopyI);
356 CopyI->eraseFromParent();
357 if (MRI->use_nodbg_empty(RegNo: CopyDefI->getOperand(i: 0).getReg())) {
358 RemovedCopies.insert(X: CopyDefI);
359 CopyDefI->eraseFromParent();
360 }
361 ++NumCopiesEliminated;
362 for (auto *Clobber : EvitableClobbers) {
363 unsigned NewOpc = X86::getNFVariant(Opc: Clobber->getOpcode());
364 assert(NewOpc && "evitable clobber must have a NF variant");
365 Clobber->setDesc(TII->get(Opcode: NewOpc));
366 Clobber->removeOperand(
367 OpNo: Clobber->findRegisterDefOperand(Reg: X86::EFLAGS, /*TRI=*/nullptr)
368 ->getOperandNo());
369 ++NumNFsConvertedTo;
370 }
371 // Update liveins for basic blocks in the path
372 for (auto BI = idf_begin(G: CopyIMBB), BE = idf_end(G: CopyDefIMBB); BI != BE;
373 ++BI)
374 if (*BI != CopyDefIMBB)
375 BI->addLiveIn(PhysReg: X86::EFLAGS);
376 ProcessNextCopyI:
377 CopyIIt = NCopyIIt;
378 }
379 Copies.set_subtract(RemovedCopies);
380 }
381
382 // For the rest of copies that cannot be eliminated by NF transform, we use
383 // setcc to preserve the flags in GPR32 before OP1, and recheck its value
384 // before using the flags, e.g.
385 //
386 // %1:gr64 = COPY $eflags
387 // OP1 implicit-def dead $eflags
388 // $eflags = COPY %1
389 // OP2 cc, implicit $eflags
390 //
391 // ->
392 //
393 // %1:gr8 = SETCCr cc, implicit $eflags
394 // OP1 implicit-def dead $eflags
395 // TEST8rr %1, %1, implicit-def $eflags
396 // OP2 ne, implicit $eflags
397 for (MachineInstr *CopyI : Copies) {
398 MachineBasicBlock &MBB = *CopyI->getParent();
399
400 MachineOperand &VOp = CopyI->getOperand(i: 1);
401 assert(VOp.isReg() &&
402 "The input to the copy for EFLAGS should always be a register!");
403 MachineInstr &CopyDefI = *MRI->getVRegDef(Reg: VOp.getReg());
404 if (CopyDefI.getOpcode() != TargetOpcode::COPY) {
405 // FIXME: The big likely candidate here are PHI nodes. We could in theory
406 // handle PHI nodes, but it gets really, really hard. Insanely hard. Hard
407 // enough that it is probably better to change every other part of LLVM
408 // to avoid creating them. The issue is that once we have PHIs we won't
409 // know which original EFLAGS value we need to capture with our setCCs
410 // below. The end result will be computing a complete set of setCCs that
411 // we *might* want, computing them in every place where we copy *out* of
412 // EFLAGS and then doing SSA formation on all of them to insert necessary
413 // PHI nodes and consume those here. Then hoping that somehow we DCE the
414 // unnecessary ones. This DCE seems very unlikely to be successful and so
415 // we will almost certainly end up with a glut of dead setCC
416 // instructions. Until we have a motivating test case and fail to avoid
417 // it by changing other parts of LLVM's lowering, we refuse to handle
418 // this complex case here.
419 LLVM_DEBUG(
420 dbgs() << "ERROR: Encountered unexpected def of an eflags copy: ";
421 CopyDefI.dump());
422 report_fatal_error(
423 reason: "Cannot lower EFLAGS copy unless it is defined in turn by a copy!");
424 }
425
426 llvm::scope_exit Cleanup([&] {
427 // All uses of the EFLAGS copy are now rewritten, kill the copy into
428 // eflags and if dead the copy from.
429 CopyI->eraseFromParent();
430 if (MRI->use_empty(RegNo: CopyDefI.getOperand(i: 0).getReg()))
431 CopyDefI.eraseFromParent();
432 ++NumCopiesEliminated;
433 });
434
435 MachineOperand &DOp = CopyI->getOperand(i: 0);
436 assert(DOp.isDef() && "Expected register def!");
437 assert(DOp.getReg() == X86::EFLAGS && "Unexpected copy def register!");
438 if (DOp.isDead())
439 continue;
440
441 MachineBasicBlock *TestMBB = CopyDefI.getParent();
442 auto TestPos = CopyDefI.getIterator();
443 DebugLoc TestLoc = CopyDefI.getDebugLoc();
444
445 LLVM_DEBUG(dbgs() << "Rewriting copy: "; CopyI->dump());
446
447 // Walk up across live-in EFLAGS to find where they were actually def'ed.
448 //
449 // This copy's def may just be part of a region of blocks covered by
450 // a single def of EFLAGS and we want to find the top of that region where
451 // possible.
452 //
453 // This is essentially a search for a *candidate* reaching definition
454 // location. We don't need to ever find the actual reaching definition here,
455 // but we want to walk up the dominator tree to find the highest point which
456 // would be viable for such a definition.
457 auto HasEFLAGSClobber = [&](MachineBasicBlock::iterator Begin,
458 MachineBasicBlock::iterator End) {
459 // Scan backwards as we expect these to be relatively short and often find
460 // a clobber near the end.
461 return llvm::any_of(
462 Range: llvm::reverse(C: llvm::make_range(x: Begin, y: End)), P: [&](MachineInstr &MI) {
463 // Flag any instruction (other than the copy we are
464 // currently rewriting) that defs EFLAGS.
465 return &MI != CopyI &&
466 MI.findRegisterDefOperand(Reg: X86::EFLAGS, /*TRI=*/nullptr);
467 });
468 };
469 auto HasEFLAGSClobberPath = [&](MachineBasicBlock *BeginMBB,
470 MachineBasicBlock *EndMBB) {
471 assert(MDT->dominates(BeginMBB, EndMBB) &&
472 "Only support paths down the dominator tree!");
473 SmallPtrSet<MachineBasicBlock *, 4> Visited;
474 SmallVector<MachineBasicBlock *, 4> Worklist;
475 // We terminate at the beginning. No need to scan it.
476 Visited.insert(Ptr: BeginMBB);
477 Worklist.push_back(Elt: EndMBB);
478 do {
479 auto *MBB = Worklist.pop_back_val();
480 for (auto *PredMBB : MBB->predecessors()) {
481 if (!Visited.insert(Ptr: PredMBB).second)
482 continue;
483 if (HasEFLAGSClobber(PredMBB->begin(), PredMBB->end()))
484 return true;
485 // Enqueue this block to walk its predecessors.
486 Worklist.push_back(Elt: PredMBB);
487 }
488 } while (!Worklist.empty());
489 // No clobber found along a path from the begin to end.
490 return false;
491 };
492 while (TestMBB->isLiveIn(Reg: X86::EFLAGS) && !TestMBB->pred_empty() &&
493 !HasEFLAGSClobber(TestMBB->begin(), TestPos)) {
494 // Find the nearest common dominator of the predecessors, as
495 // that will be the best candidate to hoist into.
496 MachineBasicBlock *HoistMBB =
497 std::accumulate(first: std::next(x: TestMBB->pred_begin()), last: TestMBB->pred_end(),
498 init: *TestMBB->pred_begin(),
499 binary_op: [&](MachineBasicBlock *LHS, MachineBasicBlock *RHS) {
500 return MDT->findNearestCommonDominator(A: LHS, B: RHS);
501 });
502
503 // Now we need to scan all predecessors that may be reached along paths to
504 // the hoist block. A clobber anywhere in any of these blocks the hoist.
505 // Note that this even handles loops because we require *no* clobbers.
506 if (HasEFLAGSClobberPath(HoistMBB, TestMBB))
507 break;
508
509 // We also need the terminators to not sneakily clobber flags.
510 if (HasEFLAGSClobber(HoistMBB->getFirstTerminator()->getIterator(),
511 HoistMBB->instr_end()))
512 break;
513
514 // We found a viable location, hoist our test position to it.
515 TestMBB = HoistMBB;
516 TestPos = TestMBB->getFirstTerminator()->getIterator();
517 // Clear the debug location as it would just be confusing after hoisting.
518 TestLoc = DebugLoc();
519 }
520 LLVM_DEBUG({
521 auto DefIt = llvm::find_if(
522 llvm::reverse(llvm::make_range(TestMBB->instr_begin(), TestPos)),
523 [&](MachineInstr &MI) {
524 return MI.findRegisterDefOperand(X86::EFLAGS, /*TRI=*/nullptr);
525 });
526 if (DefIt.base() != TestMBB->instr_begin()) {
527 dbgs() << " Using EFLAGS defined by: ";
528 DefIt->dump();
529 } else {
530 dbgs() << " Using live-in flags for BB:\n";
531 TestMBB->dump();
532 }
533 });
534
535 // While rewriting uses, we buffer jumps and rewrite them in a second pass
536 // because doing so will perturb the CFG that we are walking to find the
537 // uses in the first place.
538 SmallVector<MachineInstr *, 4> JmpIs;
539
540 // Gather the condition flags that have already been preserved in
541 // registers. We do this from scratch each time as we expect there to be
542 // very few of them and we expect to not revisit the same copy definition
543 // many times. If either of those change sufficiently we could build a map
544 // of these up front instead.
545 CondRegArray CondRegs = collectCondsInRegs(MBB&: *TestMBB, CopyDefI: TestPos);
546
547 // Collect the basic blocks we need to scan. Typically this will just be
548 // a single basic block but we may have to scan multiple blocks if the
549 // EFLAGS copy lives into successors.
550 SmallVector<MachineBasicBlock *, 2> Blocks;
551 SmallPtrSet<MachineBasicBlock *, 2> VisitedBlocks;
552 Blocks.push_back(Elt: &MBB);
553
554 do {
555 MachineBasicBlock &UseMBB = *Blocks.pop_back_val();
556
557 // Track when if/when we find a kill of the flags in this block.
558 bool FlagsKilled = false;
559
560 // In most cases, we walk from the beginning to the end of the block. But
561 // when the block is the same block as the copy is from, we will visit it
562 // twice. The first time we start from the copy and go to the end. The
563 // second time we start from the beginning and go to the copy. This lets
564 // us handle copies inside of cycles.
565 // FIXME: This loop is *super* confusing. This is at least in part
566 // a symptom of all of this routine needing to be refactored into
567 // documentable components. Once done, there may be a better way to write
568 // this loop.
569 for (auto MII = (&UseMBB == &MBB && !VisitedBlocks.count(Ptr: &UseMBB))
570 ? std::next(x: CopyI->getIterator())
571 : UseMBB.instr_begin(),
572 MIE = UseMBB.instr_end();
573 MII != MIE;) {
574 MachineInstr &MI = *MII++;
575 // If we are in the original copy block and encounter either the copy
576 // def or the copy itself, break so that we don't re-process any part of
577 // the block or process the instructions in the range that was copied
578 // over.
579 if (&MI == CopyI || &MI == &CopyDefI) {
580 assert(&UseMBB == &MBB && VisitedBlocks.count(&MBB) &&
581 "Should only encounter these on the second pass over the "
582 "original block.");
583 break;
584 }
585
586 MachineOperand *FlagUse =
587 MI.findRegisterUseOperand(Reg: X86::EFLAGS, /*TRI=*/nullptr);
588 FlagsKilled = MI.modifiesRegister(Reg: X86::EFLAGS, TRI);
589
590 if (!FlagUse && FlagsKilled)
591 break;
592 else if (!FlagUse)
593 continue;
594
595 LLVM_DEBUG(dbgs() << " Rewriting use: "; MI.dump());
596
597 // Check the kill flag before we rewrite as that may change it.
598 if (FlagUse->isKill())
599 FlagsKilled = true;
600
601 // Once we encounter a branch, the rest of the instructions must also be
602 // branches. We can't rewrite in place here, so we handle them below.
603 //
604 // Note that we don't have to handle tail calls here, even conditional
605 // tail calls, as those are not introduced into the X86 MI until post-RA
606 // branch folding or black placement. As a consequence, we get to deal
607 // with the simpler formulation of conditional branches followed by tail
608 // calls.
609 if (X86::getCondFromBranch(MI) != X86::COND_INVALID) {
610 auto JmpIt = MI.getIterator();
611 do {
612 JmpIs.push_back(Elt: &*JmpIt);
613 ++JmpIt;
614 } while (JmpIt != UseMBB.instr_end() &&
615 X86::getCondFromBranch(MI: *JmpIt) != X86::COND_INVALID);
616 break;
617 }
618
619 // Otherwise we can just rewrite in-place.
620 unsigned Opc = MI.getOpcode();
621 if (Opc == TargetOpcode::COPY) {
622 // Just replace this copy with the original copy def.
623 MRI->replaceRegWith(FromReg: MI.getOperand(i: 0).getReg(),
624 ToReg: CopyDefI.getOperand(i: 0).getReg());
625 MI.eraseFromParent();
626 } else if (X86::isSETCC(Opcode: Opc) || X86::isSETZUCC(Opcode: Opc)) {
627 rewriteSetCC(MBB&: *TestMBB, Pos: TestPos, Loc: TestLoc, MI, CondRegs);
628 } else if (isArithmeticOp(Opc)) {
629 rewriteArithmetic(MBB&: *TestMBB, Pos: TestPos, Loc: TestLoc, MI, CondRegs);
630 } else {
631 rewriteMI(MBB&: *TestMBB, Pos: TestPos, Loc: TestLoc, MI, CondRegs);
632 }
633
634 // If this was the last use of the flags, we're done.
635 if (FlagsKilled)
636 break;
637 }
638
639 // If the flags were killed, we're done with this block.
640 if (FlagsKilled)
641 continue;
642
643 // Otherwise we need to scan successors for ones where the flags live-in
644 // and queue those up for processing.
645 for (MachineBasicBlock *SuccMBB : UseMBB.successors())
646 if (SuccMBB->isLiveIn(Reg: X86::EFLAGS) &&
647 VisitedBlocks.insert(Ptr: SuccMBB).second) {
648 // We currently don't do any PHI insertion and so we require that the
649 // test basic block dominates all of the use basic blocks. Further, we
650 // can't have a cycle from the test block back to itself as that would
651 // create a cycle requiring a PHI to break it.
652 //
653 // We could in theory do PHI insertion here if it becomes useful by
654 // just taking undef values in along every edge that we don't trace
655 // this EFLAGS copy along. This isn't as bad as fully general PHI
656 // insertion, but still seems like a great deal of complexity.
657 //
658 // Because it is theoretically possible that some earlier MI pass or
659 // other lowering transformation could induce this to happen, we do
660 // a hard check even in non-debug builds here.
661 if (SuccMBB == TestMBB || !MDT->dominates(A: TestMBB, B: SuccMBB)) {
662 LLVM_DEBUG({
663 dbgs()
664 << "ERROR: Encountered use that is not dominated by our test "
665 "basic block! Rewriting this would require inserting PHI "
666 "nodes to track the flag state across the CFG.\n\nTest "
667 "block:\n";
668 TestMBB->dump();
669 dbgs() << "Use block:\n";
670 SuccMBB->dump();
671 });
672 report_fatal_error(
673 reason: "Cannot lower EFLAGS copy when original copy def "
674 "does not dominate all uses.");
675 }
676
677 Blocks.push_back(Elt: SuccMBB);
678
679 // After this, EFLAGS will be recreated before each use.
680 SuccMBB->removeLiveIn(Reg: X86::EFLAGS);
681 }
682 } while (!Blocks.empty());
683
684 // Now rewrite the jumps that use the flags. These we handle specially
685 // because if there are multiple jumps in a single basic block we'll have
686 // to do surgery on the CFG.
687 MachineBasicBlock *LastJmpMBB = nullptr;
688 for (MachineInstr *JmpI : JmpIs) {
689 // Past the first jump within a basic block we need to split the blocks
690 // apart.
691 if (JmpI->getParent() == LastJmpMBB)
692 splitBlock(MBB&: *JmpI->getParent(), SplitI&: *JmpI, TII: *TII);
693 else
694 LastJmpMBB = JmpI->getParent();
695
696 rewriteMI(MBB&: *TestMBB, Pos: TestPos, Loc: TestLoc, MI&: *JmpI, CondRegs);
697 }
698
699 // FIXME: Mark the last use of EFLAGS before the copy's def as a kill if
700 // the copy's def operand is itself a kill.
701 }
702
703#ifndef NDEBUG
704 // Check reachable blocks for unlowered EFLAGS copies.
705 for (MachineBasicBlock *MBB : depth_first(&MF))
706 for (MachineInstr &MI : *MBB)
707 if (MI.getOpcode() == TargetOpcode::COPY &&
708 (MI.getOperand(0).getReg() == X86::EFLAGS ||
709 MI.getOperand(1).getReg() == X86::EFLAGS)) {
710 LLVM_DEBUG(dbgs() << "ERROR: Found a COPY involving EFLAGS: ";
711 MI.dump());
712 llvm_unreachable("Unlowered EFLAGS copy!");
713 }
714#endif
715
716 return true;
717}
718
719/// Collect any conditions that have already been set in registers so that we
720/// can re-use them rather than adding duplicates.
721CondRegArray X86FlagsCopyLoweringImpl::collectCondsInRegs(
722 MachineBasicBlock &MBB, MachineBasicBlock::iterator TestPos) {
723 CondRegArray CondRegs = {};
724
725 // Scan backwards across the range of instructions with live EFLAGS.
726 for (MachineInstr &MI :
727 llvm::reverse(C: llvm::make_range(x: MBB.begin(), y: TestPos))) {
728 X86::CondCode Cond = X86::getCondFromSETCC(MI);
729 if (Cond != X86::COND_INVALID && !MI.mayStore() &&
730 MI.getOperand(i: 0).isReg() && MI.getOperand(i: 0).getReg().isVirtual()) {
731 assert(MI.getOperand(0).isDef() &&
732 "A non-storing SETcc should always define a register!");
733 CondRegs[Cond] = MI.getOperand(i: 0).getReg();
734 }
735
736 // Stop scanning when we see the first definition of the EFLAGS as prior to
737 // this we would potentially capture the wrong flag state.
738 if (MI.findRegisterDefOperand(Reg: X86::EFLAGS, /*TRI=*/nullptr))
739 break;
740 }
741 return CondRegs;
742}
743
744Register X86FlagsCopyLoweringImpl::promoteCondToReg(
745 MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
746 const DebugLoc &TestLoc, X86::CondCode Cond) {
747 Register Reg = MRI->createVirtualRegister(RegClass: PromoteRC);
748 auto SetI =
749 BuildMI(BB&: TestMBB, I: TestPos, MIMD: TestLoc,
750 MCID: TII->get(Opcode: (!Subtarget->hasZU() || Subtarget->preferLegacySetCC())
751 ? X86::SETCCr
752 : X86::SETZUCCr),
753 DestReg: Reg)
754 .addImm(Val: Cond);
755 (void)SetI;
756 LLVM_DEBUG(dbgs() << " save cond: "; SetI->dump());
757 ++NumSetCCsInserted;
758 return Reg;
759}
760
761std::pair<Register, bool> X86FlagsCopyLoweringImpl::getCondOrInverseInReg(
762 MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
763 const DebugLoc &TestLoc, X86::CondCode Cond, CondRegArray &CondRegs) {
764 Register &CondReg = CondRegs[Cond];
765 Register &InvCondReg = CondRegs[X86::GetOppositeBranchCondition(CC: Cond)];
766 if (!CondReg && !InvCondReg)
767 CondReg = promoteCondToReg(TestMBB, TestPos, TestLoc, Cond);
768
769 if (CondReg)
770 return {CondReg, false};
771 else
772 return {InvCondReg, true};
773}
774
775void X86FlagsCopyLoweringImpl::insertTest(MachineBasicBlock &MBB,
776 MachineBasicBlock::iterator Pos,
777 const DebugLoc &Loc, Register Reg) {
778 auto TestI =
779 BuildMI(BB&: MBB, I: Pos, MIMD: Loc, MCID: TII->get(Opcode: X86::TEST8rr)).addReg(RegNo: Reg).addReg(RegNo: Reg);
780 (void)TestI;
781 LLVM_DEBUG(dbgs() << " test cond: "; TestI->dump());
782 ++NumTestsInserted;
783}
784
785void X86FlagsCopyLoweringImpl::rewriteSetCC(MachineBasicBlock &MBB,
786 MachineBasicBlock::iterator Pos,
787 const DebugLoc &Loc,
788 MachineInstr &MI,
789 CondRegArray &CondRegs) {
790 X86::CondCode Cond = X86::getCondFromSETCC(MI);
791 // Note that we can't usefully rewrite this to the inverse without complex
792 // analysis of the users of the setCC. Largely we rely on duplicates which
793 // could have been avoided already being avoided here.
794 Register &CondReg = CondRegs[Cond];
795 if (!CondReg)
796 CondReg = promoteCondToReg(TestMBB&: MBB, TestPos: Pos, TestLoc: Loc, Cond);
797
798 // Rewriting a register def is trivial: we just replace the register and
799 // remove the setcc.
800 if (!MI.mayStore()) {
801 assert(MI.getOperand(0).isReg() &&
802 "Cannot have a non-register defined operand to SETcc!");
803 Register OldReg = MI.getOperand(i: 0).getReg();
804 // Drop Kill flags on the old register before replacing. CondReg may have
805 // a longer live range.
806 MRI->clearKillFlags(Reg: OldReg);
807 MRI->replaceRegWith(FromReg: OldReg, ToReg: CondReg);
808 MI.eraseFromParent();
809 return;
810 }
811
812 // Otherwise, we need to emit a store.
813 auto MIB = BuildMI(BB&: *MI.getParent(), I: MI.getIterator(), MIMD: MI.getDebugLoc(),
814 MCID: TII->get(Opcode: X86::MOV8mr));
815 // Copy the address operands.
816 for (int i = 0; i < X86::AddrNumOperands; ++i)
817 MIB.add(MO: MI.getOperand(i));
818
819 MIB.addReg(RegNo: CondReg);
820 MIB.setMemRefs(MI.memoperands());
821 MI.eraseFromParent();
822}
823
824void X86FlagsCopyLoweringImpl::rewriteArithmetic(
825 MachineBasicBlock &MBB, MachineBasicBlock::iterator Pos,
826 const DebugLoc &Loc, MachineInstr &MI, CondRegArray &CondRegs) {
827 // Arithmetic is either reading CF or OF.
828 X86::CondCode Cond = X86::COND_B; // CF == 1
829 // The addend to use to reset CF or OF when added to the flag value.
830 // Set up an addend that when one is added will need a carry due to not
831 // having a higher bit available.
832 int Addend = 255;
833
834 // Now get a register that contains the value of the flag input to the
835 // arithmetic. We require exactly this flag to simplify the arithmetic
836 // required to materialize it back into the flag.
837 Register &CondReg = CondRegs[Cond];
838 if (!CondReg)
839 CondReg = promoteCondToReg(TestMBB&: MBB, TestPos: Pos, TestLoc: Loc, Cond);
840
841 // Insert an instruction that will set the flag back to the desired value.
842 Register TmpReg = MRI->createVirtualRegister(RegClass: PromoteRC);
843 auto AddI =
844 BuildMI(BB&: *MI.getParent(), I: MI.getIterator(), MIMD: MI.getDebugLoc(),
845 MCID: TII->get(Opcode: Subtarget->hasNDD() ? X86::ADD8ri_ND : X86::ADD8ri))
846 .addDef(RegNo: TmpReg, Flags: RegState::Dead)
847 .addReg(RegNo: CondReg)
848 .addImm(Val: Addend);
849 (void)AddI;
850 LLVM_DEBUG(dbgs() << " add cond: "; AddI->dump());
851 ++NumAddsInserted;
852 MI.findRegisterUseOperand(Reg: X86::EFLAGS, /*TRI=*/nullptr)->setIsKill(true);
853}
854
855static X86::CondCode getImplicitCondFromMI(unsigned Opc) {
856#define FROM_TO(A, B) \
857 case X86::CMOV##A##_Fp32: \
858 case X86::CMOV##A##_Fp64: \
859 case X86::CMOV##A##_Fp80: \
860 return X86::COND_##B;
861
862 switch (Opc) {
863 default:
864 return X86::COND_INVALID;
865 FROM_TO(B, B)
866 FROM_TO(E, E)
867 FROM_TO(P, P)
868 FROM_TO(BE, BE)
869 FROM_TO(NB, AE)
870 FROM_TO(NE, NE)
871 FROM_TO(NP, NP)
872 FROM_TO(NBE, A)
873 }
874#undef FROM_TO
875}
876
877static unsigned getOpcodeWithCC(unsigned Opc, X86::CondCode CC) {
878 assert((CC == X86::COND_E || CC == X86::COND_NE) && "Unexpected CC");
879#define CASE(A) \
880 case X86::CMOVB_##A: \
881 case X86::CMOVE_##A: \
882 case X86::CMOVP_##A: \
883 case X86::CMOVBE_##A: \
884 case X86::CMOVNB_##A: \
885 case X86::CMOVNE_##A: \
886 case X86::CMOVNP_##A: \
887 case X86::CMOVNBE_##A: \
888 return (CC == X86::COND_E) ? X86::CMOVE_##A : X86::CMOVNE_##A;
889 switch (Opc) {
890 default:
891 llvm_unreachable("Unexpected opcode");
892 CASE(Fp32)
893 CASE(Fp64)
894 CASE(Fp80)
895 }
896#undef CASE
897}
898
899void X86FlagsCopyLoweringImpl::rewriteMI(MachineBasicBlock &MBB,
900 MachineBasicBlock::iterator Pos,
901 const DebugLoc &Loc, MachineInstr &MI,
902 CondRegArray &CondRegs) {
903 // First get the register containing this specific condition.
904 bool IsImplicitCC = false;
905 X86::CondCode CC = X86::getCondFromMI(MI);
906 if (CC == X86::COND_INVALID) {
907 CC = getImplicitCondFromMI(Opc: MI.getOpcode());
908 IsImplicitCC = true;
909 }
910 assert(CC != X86::COND_INVALID && "Unknown EFLAG user!");
911 Register CondReg;
912 bool Inverted;
913 std::tie(args&: CondReg, args&: Inverted) =
914 getCondOrInverseInReg(TestMBB&: MBB, TestPos: Pos, TestLoc: Loc, Cond: CC, CondRegs);
915
916 // Insert a direct test of the saved register.
917 insertTest(MBB&: *MI.getParent(), Pos: MI.getIterator(), Loc: MI.getDebugLoc(), Reg: CondReg);
918
919 // Rewrite the instruction to use the !ZF flag from the test, and then kill
920 // its use of the flags afterward.
921 X86::CondCode NewCC = Inverted ? X86::COND_E : X86::COND_NE;
922 if (IsImplicitCC)
923 MI.setDesc(TII->get(Opcode: getOpcodeWithCC(Opc: MI.getOpcode(), CC: NewCC)));
924 else
925 MI.getOperand(i: MI.getDesc().getNumOperands() - 1).setImm(NewCC);
926
927 MI.findRegisterUseOperand(Reg: X86::EFLAGS, /*TRI=*/nullptr)->setIsKill(true);
928 LLVM_DEBUG(dbgs() << " fixed instruction: "; MI.dump());
929}
930
931bool X86FlagsCopyLoweringLegacy::runOnMachineFunction(MachineFunction &MF) {
932 auto *MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
933 MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
934 return X86FlagsCopyLoweringImpl(MDT).runOnMachineFunction(MF);
935}
936
937PreservedAnalyses
938X86FlagsCopyLoweringPass::run(MachineFunction &MF,
939 MachineFunctionAnalysisManager &MFAM) {
940 MachineDominatorTree *MDT =
941 MFAM.getCachedResult<MachineDominatorTreeAnalysis>(IR&: MF);
942 bool Changed = X86FlagsCopyLoweringImpl(MDT).runOnMachineFunction(MF);
943 return Changed ? PreservedAnalyses::all()
944 : getMachineFunctionPassPreservedAnalyses();
945}
946