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