blob: c18739254b0d153ba38a2c98ad3ac5b7a872f626 [file] [log] [blame]
Chandler Carruth19618fc2018-04-10 01:41:17 +00001//====- X86FlagsCopyLowering.cpp - Lowers COPY nodes of EFLAGS ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10///
11/// Lowers COPY nodes of EFLAGS by directly extracting and preserving individual
12/// flag bits.
13///
14/// We have to do this by carefully analyzing and rewriting the usage of the
15/// copied EFLAGS register because there is no general way to rematerialize the
16/// entire EFLAGS register safely and efficiently. Using `popf` both forces
17/// dynamic stack adjustment and can create correctness issues due to IF, TF,
18/// and other non-status flags being overwritten. Using sequences involving
19/// SAHF don't work on all x86 processors and are often quite slow compared to
20/// directly testing a single status preserved in its own GPR.
21///
22//===----------------------------------------------------------------------===//
23
24#include "X86.h"
25#include "X86InstrBuilder.h"
26#include "X86InstrInfo.h"
27#include "X86Subtarget.h"
28#include "llvm/ADT/ArrayRef.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/ScopeExit.h"
32#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/SmallSet.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/SparseBitVector.h"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/CodeGen/MachineBasicBlock.h"
38#include "llvm/CodeGen/MachineConstantPool.h"
Chandler Carruth1f876182018-04-18 15:13:16 +000039#include "llvm/CodeGen/MachineDominators.h"
Chandler Carruth19618fc2018-04-10 01:41:17 +000040#include "llvm/CodeGen/MachineFunction.h"
41#include "llvm/CodeGen/MachineFunctionPass.h"
42#include "llvm/CodeGen/MachineInstr.h"
43#include "llvm/CodeGen/MachineInstrBuilder.h"
44#include "llvm/CodeGen/MachineModuleInfo.h"
45#include "llvm/CodeGen/MachineOperand.h"
46#include "llvm/CodeGen/MachineRegisterInfo.h"
47#include "llvm/CodeGen/MachineSSAUpdater.h"
48#include "llvm/CodeGen/TargetInstrInfo.h"
49#include "llvm/CodeGen/TargetRegisterInfo.h"
50#include "llvm/CodeGen/TargetSchedule.h"
51#include "llvm/CodeGen/TargetSubtargetInfo.h"
52#include "llvm/IR/DebugLoc.h"
53#include "llvm/MC/MCSchedule.h"
54#include "llvm/Pass.h"
55#include "llvm/Support/CommandLine.h"
56#include "llvm/Support/Debug.h"
57#include "llvm/Support/raw_ostream.h"
58#include <algorithm>
59#include <cassert>
60#include <iterator>
61#include <utility>
62
63using namespace llvm;
64
65#define PASS_KEY "x86-flags-copy-lowering"
66#define DEBUG_TYPE PASS_KEY
67
68STATISTIC(NumCopiesEliminated, "Number of copies of EFLAGS eliminated");
69STATISTIC(NumSetCCsInserted, "Number of setCC instructions inserted");
70STATISTIC(NumTestsInserted, "Number of test instructions inserted");
71STATISTIC(NumAddsInserted, "Number of adds instructions inserted");
72
73namespace llvm {
74
75void initializeX86FlagsCopyLoweringPassPass(PassRegistry &);
76
77} // end namespace llvm
78
79namespace {
80
81// Convenient array type for storing registers associated with each condition.
82using CondRegArray = std::array<unsigned, X86::LAST_VALID_COND + 1>;
83
84class X86FlagsCopyLoweringPass : public MachineFunctionPass {
85public:
86 X86FlagsCopyLoweringPass() : MachineFunctionPass(ID) {
87 initializeX86FlagsCopyLoweringPassPass(*PassRegistry::getPassRegistry());
88 }
89
90 StringRef getPassName() const override { return "X86 EFLAGS copy lowering"; }
91 bool runOnMachineFunction(MachineFunction &MF) override;
92 void getAnalysisUsage(AnalysisUsage &AU) const override;
93
94 /// Pass identification, replacement for typeid.
95 static char ID;
96
97private:
98 MachineRegisterInfo *MRI;
99 const X86InstrInfo *TII;
100 const TargetRegisterInfo *TRI;
101 const TargetRegisterClass *PromoteRC;
Chandler Carruth1f876182018-04-18 15:13:16 +0000102 MachineDominatorTree *MDT;
Chandler Carruth19618fc2018-04-10 01:41:17 +0000103
104 CondRegArray collectCondsInRegs(MachineBasicBlock &MBB,
105 MachineInstr &CopyDefI);
106
107 unsigned promoteCondToReg(MachineBasicBlock &MBB,
108 MachineBasicBlock::iterator TestPos,
109 DebugLoc TestLoc, X86::CondCode Cond);
110 std::pair<unsigned, bool>
111 getCondOrInverseInReg(MachineBasicBlock &TestMBB,
112 MachineBasicBlock::iterator TestPos, DebugLoc TestLoc,
113 X86::CondCode Cond, CondRegArray &CondRegs);
114 void insertTest(MachineBasicBlock &MBB, MachineBasicBlock::iterator Pos,
115 DebugLoc Loc, unsigned Reg);
116
117 void rewriteArithmetic(MachineBasicBlock &TestMBB,
118 MachineBasicBlock::iterator TestPos, DebugLoc TestLoc,
119 MachineInstr &MI, MachineOperand &FlagUse,
120 CondRegArray &CondRegs);
121 void rewriteCMov(MachineBasicBlock &TestMBB,
122 MachineBasicBlock::iterator TestPos, DebugLoc TestLoc,
123 MachineInstr &CMovI, MachineOperand &FlagUse,
124 CondRegArray &CondRegs);
125 void rewriteCondJmp(MachineBasicBlock &TestMBB,
126 MachineBasicBlock::iterator TestPos, DebugLoc TestLoc,
127 MachineInstr &JmpI, CondRegArray &CondRegs);
128 void rewriteCopy(MachineInstr &MI, MachineOperand &FlagUse,
129 MachineInstr &CopyDefI);
130 void rewriteSetCC(MachineBasicBlock &TestMBB,
131 MachineBasicBlock::iterator TestPos, DebugLoc TestLoc,
132 MachineInstr &SetCCI, MachineOperand &FlagUse,
133 CondRegArray &CondRegs);
134};
135
136} // end anonymous namespace
137
138INITIALIZE_PASS_BEGIN(X86FlagsCopyLoweringPass, DEBUG_TYPE,
139 "X86 EFLAGS copy lowering", false, false)
140INITIALIZE_PASS_END(X86FlagsCopyLoweringPass, DEBUG_TYPE,
141 "X86 EFLAGS copy lowering", false, false)
142
143FunctionPass *llvm::createX86FlagsCopyLoweringPass() {
144 return new X86FlagsCopyLoweringPass();
145}
146
147char X86FlagsCopyLoweringPass::ID = 0;
148
149void X86FlagsCopyLoweringPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth1f876182018-04-18 15:13:16 +0000150 AU.addRequired<MachineDominatorTree>();
Chandler Carruth19618fc2018-04-10 01:41:17 +0000151 MachineFunctionPass::getAnalysisUsage(AU);
152}
153
154namespace {
155/// An enumeration of the arithmetic instruction mnemonics which have
156/// interesting flag semantics.
157///
158/// We can map instruction opcodes into these mnemonics to make it easy to
159/// dispatch with specific functionality.
160enum class FlagArithMnemonic {
161 ADC,
162 ADCX,
163 ADOX,
164 RCL,
165 RCR,
166 SBB,
167};
168} // namespace
169
170static FlagArithMnemonic getMnemonicFromOpcode(unsigned Opcode) {
171 switch (Opcode) {
172 default:
173 report_fatal_error("No support for lowering a copy into EFLAGS when used "
174 "by this instruction!");
175
176#define LLVM_EXPAND_INSTR_SIZES(MNEMONIC, SUFFIX) \
177 case X86::MNEMONIC##8##SUFFIX: \
178 case X86::MNEMONIC##16##SUFFIX: \
179 case X86::MNEMONIC##32##SUFFIX: \
180 case X86::MNEMONIC##64##SUFFIX:
181
182#define LLVM_EXPAND_ADC_SBB_INSTR(MNEMONIC) \
183 LLVM_EXPAND_INSTR_SIZES(MNEMONIC, rr) \
184 LLVM_EXPAND_INSTR_SIZES(MNEMONIC, rr_REV) \
185 LLVM_EXPAND_INSTR_SIZES(MNEMONIC, rm) \
186 LLVM_EXPAND_INSTR_SIZES(MNEMONIC, mr) \
187 case X86::MNEMONIC##8ri: \
188 case X86::MNEMONIC##16ri8: \
189 case X86::MNEMONIC##32ri8: \
190 case X86::MNEMONIC##64ri8: \
191 case X86::MNEMONIC##16ri: \
192 case X86::MNEMONIC##32ri: \
193 case X86::MNEMONIC##64ri32: \
194 case X86::MNEMONIC##8mi: \
195 case X86::MNEMONIC##16mi8: \
196 case X86::MNEMONIC##32mi8: \
197 case X86::MNEMONIC##64mi8: \
198 case X86::MNEMONIC##16mi: \
199 case X86::MNEMONIC##32mi: \
200 case X86::MNEMONIC##64mi32: \
201 case X86::MNEMONIC##8i8: \
202 case X86::MNEMONIC##16i16: \
203 case X86::MNEMONIC##32i32: \
204 case X86::MNEMONIC##64i32:
205
206 LLVM_EXPAND_ADC_SBB_INSTR(ADC)
207 return FlagArithMnemonic::ADC;
208
209 LLVM_EXPAND_ADC_SBB_INSTR(SBB)
210 return FlagArithMnemonic::SBB;
211
212#undef LLVM_EXPAND_ADC_SBB_INSTR
213
214 LLVM_EXPAND_INSTR_SIZES(RCL, rCL)
215 LLVM_EXPAND_INSTR_SIZES(RCL, r1)
216 LLVM_EXPAND_INSTR_SIZES(RCL, ri)
217 return FlagArithMnemonic::RCL;
218
219 LLVM_EXPAND_INSTR_SIZES(RCR, rCL)
220 LLVM_EXPAND_INSTR_SIZES(RCR, r1)
221 LLVM_EXPAND_INSTR_SIZES(RCR, ri)
222 return FlagArithMnemonic::RCR;
223
224#undef LLVM_EXPAND_INSTR_SIZES
225
226 case X86::ADCX32rr:
227 case X86::ADCX64rr:
228 case X86::ADCX32rm:
229 case X86::ADCX64rm:
230 return FlagArithMnemonic::ADCX;
231
232 case X86::ADOX32rr:
233 case X86::ADOX64rr:
234 case X86::ADOX32rm:
235 case X86::ADOX64rm:
236 return FlagArithMnemonic::ADOX;
237 }
238}
239
240static MachineBasicBlock &splitBlock(MachineBasicBlock &MBB,
241 MachineInstr &SplitI,
242 const X86InstrInfo &TII) {
243 MachineFunction &MF = *MBB.getParent();
244
245 assert(SplitI.getParent() == &MBB &&
246 "Split instruction must be in the split block!");
247 assert(SplitI.isBranch() &&
248 "Only designed to split a tail of branch instructions!");
249 assert(X86::getCondFromBranchOpc(SplitI.getOpcode()) != X86::COND_INVALID &&
250 "Must split on an actual jCC instruction!");
251
252 // Dig out the previous instruction to the split point.
253 MachineInstr &PrevI = *std::prev(SplitI.getIterator());
254 assert(PrevI.isBranch() && "Must split after a branch!");
255 assert(X86::getCondFromBranchOpc(PrevI.getOpcode()) != X86::COND_INVALID &&
256 "Must split after an actual jCC instruction!");
257 assert(!std::prev(PrevI.getIterator())->isTerminator() &&
258 "Must only have this one terminator prior to the split!");
259
260 // Grab the one successor edge that will stay in `MBB`.
261 MachineBasicBlock &UnsplitSucc = *PrevI.getOperand(0).getMBB();
262
263 // Analyze the original block to see if we are actually splitting an edge
264 // into two edges. This can happen when we have multiple conditional jumps to
265 // the same successor.
266 bool IsEdgeSplit =
267 std::any_of(SplitI.getIterator(), MBB.instr_end(),
268 [&](MachineInstr &MI) {
269 assert(MI.isTerminator() &&
270 "Should only have spliced terminators!");
271 return llvm::any_of(
272 MI.operands(), [&](MachineOperand &MOp) {
273 return MOp.isMBB() && MOp.getMBB() == &UnsplitSucc;
274 });
275 }) ||
276 MBB.getFallThrough() == &UnsplitSucc;
277
278 MachineBasicBlock &NewMBB = *MF.CreateMachineBasicBlock();
279
280 // Insert the new block immediately after the current one. Any existing
281 // fallthrough will be sunk into this new block anyways.
282 MF.insert(std::next(MachineFunction::iterator(&MBB)), &NewMBB);
283
284 // Splice the tail of instructions into the new block.
285 NewMBB.splice(NewMBB.end(), &MBB, SplitI.getIterator(), MBB.end());
286
287 // Copy the necessary succesors (and their probability info) into the new
288 // block.
289 for (auto SI = MBB.succ_begin(), SE = MBB.succ_end(); SI != SE; ++SI)
290 if (IsEdgeSplit || *SI != &UnsplitSucc)
291 NewMBB.copySuccessor(&MBB, SI);
292 // Normalize the probabilities if we didn't end up splitting the edge.
293 if (!IsEdgeSplit)
294 NewMBB.normalizeSuccProbs();
295
296 // Now replace all of the moved successors in the original block with the new
297 // block. This will merge their probabilities.
298 for (MachineBasicBlock *Succ : NewMBB.successors())
299 if (Succ != &UnsplitSucc)
300 MBB.replaceSuccessor(Succ, &NewMBB);
301
302 // We should always end up replacing at least one successor.
303 assert(MBB.isSuccessor(&NewMBB) &&
304 "Failed to make the new block a successor!");
305
306 // Now update all the PHIs.
307 for (MachineBasicBlock *Succ : NewMBB.successors()) {
308 for (MachineInstr &MI : *Succ) {
309 if (!MI.isPHI())
310 break;
311
312 for (int OpIdx = 1, NumOps = MI.getNumOperands(); OpIdx < NumOps;
313 OpIdx += 2) {
314 MachineOperand &OpV = MI.getOperand(OpIdx);
315 MachineOperand &OpMBB = MI.getOperand(OpIdx + 1);
316 assert(OpMBB.isMBB() && "Block operand to a PHI is not a block!");
317 if (OpMBB.getMBB() != &MBB)
318 continue;
319
320 // Replace the operand for unsplit successors
321 if (!IsEdgeSplit || Succ != &UnsplitSucc) {
322 OpMBB.setMBB(&NewMBB);
323
324 // We have to continue scanning as there may be multiple entries in
325 // the PHI.
326 continue;
327 }
328
329 // When we have split the edge append a new successor.
330 MI.addOperand(MF, OpV);
331 MI.addOperand(MF, MachineOperand::CreateMBB(&NewMBB));
332 break;
333 }
334 }
335 }
336
337 return NewMBB;
338}
339
340bool X86FlagsCopyLoweringPass::runOnMachineFunction(MachineFunction &MF) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000341 LLVM_DEBUG(dbgs() << "********** " << getPassName() << " : " << MF.getName()
342 << " **********\n");
Chandler Carruth19618fc2018-04-10 01:41:17 +0000343
344 auto &Subtarget = MF.getSubtarget<X86Subtarget>();
345 MRI = &MF.getRegInfo();
346 TII = Subtarget.getInstrInfo();
347 TRI = Subtarget.getRegisterInfo();
Chandler Carruth1f876182018-04-18 15:13:16 +0000348 MDT = &getAnalysis<MachineDominatorTree>();
Chandler Carruth19618fc2018-04-10 01:41:17 +0000349 PromoteRC = &X86::GR8RegClass;
350
351 if (MF.begin() == MF.end())
352 // Nothing to do for a degenerate empty function...
353 return false;
354
355 SmallVector<MachineInstr *, 4> Copies;
356 for (MachineBasicBlock &MBB : MF)
357 for (MachineInstr &MI : MBB)
358 if (MI.getOpcode() == TargetOpcode::COPY &&
359 MI.getOperand(0).getReg() == X86::EFLAGS)
360 Copies.push_back(&MI);
361
362 for (MachineInstr *CopyI : Copies) {
363 MachineBasicBlock &MBB = *CopyI->getParent();
364
365 MachineOperand &VOp = CopyI->getOperand(1);
366 assert(VOp.isReg() &&
367 "The input to the copy for EFLAGS should always be a register!");
368 MachineInstr &CopyDefI = *MRI->getVRegDef(VOp.getReg());
369 if (CopyDefI.getOpcode() != TargetOpcode::COPY) {
370 // FIXME: The big likely candidate here are PHI nodes. We could in theory
371 // handle PHI nodes, but it gets really, really hard. Insanely hard. Hard
372 // enough that it is probably better to change every other part of LLVM
373 // to avoid creating them. The issue is that once we have PHIs we won't
374 // know which original EFLAGS value we need to capture with our setCCs
375 // below. The end result will be computing a complete set of setCCs that
376 // we *might* want, computing them in every place where we copy *out* of
377 // EFLAGS and then doing SSA formation on all of them to insert necessary
378 // PHI nodes and consume those here. Then hoping that somehow we DCE the
379 // unnecessary ones. This DCE seems very unlikely to be successful and so
380 // we will almost certainly end up with a glut of dead setCC
381 // instructions. Until we have a motivating test case and fail to avoid
382 // it by changing other parts of LLVM's lowering, we refuse to handle
383 // this complex case here.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000384 LLVM_DEBUG(
385 dbgs() << "ERROR: Encountered unexpected def of an eflags copy: ";
386 CopyDefI.dump());
Chandler Carruth19618fc2018-04-10 01:41:17 +0000387 report_fatal_error(
388 "Cannot lower EFLAGS copy unless it is defined in turn by a copy!");
389 }
390
391 auto Cleanup = make_scope_exit([&] {
392 // All uses of the EFLAGS copy are now rewritten, kill the copy into
393 // eflags and if dead the copy from.
394 CopyI->eraseFromParent();
395 if (MRI->use_empty(CopyDefI.getOperand(0).getReg()))
396 CopyDefI.eraseFromParent();
397 ++NumCopiesEliminated;
398 });
399
400 MachineOperand &DOp = CopyI->getOperand(0);
401 assert(DOp.isDef() && "Expected register def!");
402 assert(DOp.getReg() == X86::EFLAGS && "Unexpected copy def register!");
403 if (DOp.isDead())
404 continue;
405
406 MachineBasicBlock &TestMBB = *CopyDefI.getParent();
407 auto TestPos = CopyDefI.getIterator();
408 DebugLoc TestLoc = CopyDefI.getDebugLoc();
409
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000410 LLVM_DEBUG(dbgs() << "Rewriting copy: "; CopyI->dump());
Chandler Carruth19618fc2018-04-10 01:41:17 +0000411
412 // Scan for usage of newly set EFLAGS so we can rewrite them. We just buffer
413 // jumps because their usage is very constrained.
414 bool FlagsKilled = false;
415 SmallVector<MachineInstr *, 4> JmpIs;
416
417 // Gather the condition flags that have already been preserved in
418 // registers. We do this from scratch each time as we expect there to be
419 // very few of them and we expect to not revisit the same copy definition
420 // many times. If either of those change sufficiently we could build a map
421 // of these up front instead.
422 CondRegArray CondRegs = collectCondsInRegs(TestMBB, CopyDefI);
423
Chandler Carruth1f876182018-04-18 15:13:16 +0000424 // Collect the basic blocks we need to scan. Typically this will just be
425 // a single basic block but we may have to scan multiple blocks if the
426 // EFLAGS copy lives into successors.
427 SmallVector<MachineBasicBlock *, 2> Blocks;
428 SmallPtrSet<MachineBasicBlock *, 2> VisitedBlocks;
429 Blocks.push_back(&MBB);
430 VisitedBlocks.insert(&MBB);
431
432 do {
433 MachineBasicBlock &UseMBB = *Blocks.pop_back_val();
434
435 // We currently don't do any PHI insertion and so we require that the
436 // test basic block dominates all of the use basic blocks.
437 //
438 // We could in theory do PHI insertion here if it becomes useful by just
439 // taking undef values in along every edge that we don't trace this
440 // EFLAGS copy along. This isn't as bad as fully general PHI insertion,
441 // but still seems like a great deal of complexity.
442 //
443 // Because it is theoretically possible that some earlier MI pass or
444 // other lowering transformation could induce this to happen, we do
445 // a hard check even in non-debug builds here.
446 if (&TestMBB != &UseMBB && !MDT->dominates(&TestMBB, &UseMBB)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000447 LLVM_DEBUG({
Chandler Carruth1f876182018-04-18 15:13:16 +0000448 dbgs() << "ERROR: Encountered use that is not dominated by our test "
449 "basic block! Rewriting this would require inserting PHI "
450 "nodes to track the flag state across the CFG.\n\nTest "
451 "block:\n";
452 TestMBB.dump();
453 dbgs() << "Use block:\n";
454 UseMBB.dump();
455 });
456 report_fatal_error("Cannot lower EFLAGS copy when original copy def "
457 "does not dominate all uses.");
458 }
459
460 for (auto MII = &UseMBB == &MBB ? std::next(CopyI->getIterator())
461 : UseMBB.instr_begin(),
462 MIE = UseMBB.instr_end();
463 MII != MIE;) {
464 MachineInstr &MI = *MII++;
465 MachineOperand *FlagUse = MI.findRegisterUseOperand(X86::EFLAGS);
466 if (!FlagUse) {
467 if (MI.findRegisterDefOperand(X86::EFLAGS)) {
468 // If EFLAGS are defined, it's as-if they were killed. We can stop
469 // scanning here.
470 //
471 // NB!!! Many instructions only modify some flags. LLVM currently
472 // models this as clobbering all flags, but if that ever changes
473 // this will need to be carefully updated to handle that more
474 // complex logic.
475 FlagsKilled = true;
476 break;
477 }
478 continue;
479 }
480
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000481 LLVM_DEBUG(dbgs() << " Rewriting use: "; MI.dump());
Chandler Carruth1f876182018-04-18 15:13:16 +0000482
483 // Check the kill flag before we rewrite as that may change it.
484 if (FlagUse->isKill())
Chandler Carruth19618fc2018-04-10 01:41:17 +0000485 FlagsKilled = true;
Chandler Carruth1f876182018-04-18 15:13:16 +0000486
487 // Once we encounter a branch, the rest of the instructions must also be
488 // branches. We can't rewrite in place here, so we handle them below.
489 //
490 // Note that we don't have to handle tail calls here, even conditional
491 // tail calls, as those are not introduced into the X86 MI until post-RA
492 // branch folding or black placement. As a consequence, we get to deal
493 // with the simpler formulation of conditional branches followed by tail
494 // calls.
495 if (X86::getCondFromBranchOpc(MI.getOpcode()) != X86::COND_INVALID) {
496 auto JmpIt = MI.getIterator();
497 do {
498 JmpIs.push_back(&*JmpIt);
499 ++JmpIt;
500 } while (JmpIt != UseMBB.instr_end() &&
501 X86::getCondFromBranchOpc(JmpIt->getOpcode()) !=
502 X86::COND_INVALID);
Chandler Carruth19618fc2018-04-10 01:41:17 +0000503 break;
504 }
Chandler Carruth1f876182018-04-18 15:13:16 +0000505
506 // Otherwise we can just rewrite in-place.
507 if (X86::getCondFromCMovOpc(MI.getOpcode()) != X86::COND_INVALID) {
508 rewriteCMov(TestMBB, TestPos, TestLoc, MI, *FlagUse, CondRegs);
509 } else if (X86::getCondFromSETOpc(MI.getOpcode()) !=
510 X86::COND_INVALID) {
511 rewriteSetCC(TestMBB, TestPos, TestLoc, MI, *FlagUse, CondRegs);
512 } else if (MI.getOpcode() == TargetOpcode::COPY) {
513 rewriteCopy(MI, *FlagUse, CopyDefI);
514 } else {
515 // We assume that arithmetic instructions that use flags also def
516 // them.
517 assert(MI.findRegisterDefOperand(X86::EFLAGS) &&
518 "Expected a def of EFLAGS for this instruction!");
519
520 // NB!!! Several arithmetic instructions only *partially* update
521 // flags. Theoretically, we could generate MI code sequences that
522 // would rely on this fact and observe different flags independently.
523 // But currently LLVM models all of these instructions as clobbering
524 // all the flags in an undef way. We rely on that to simplify the
525 // logic.
526 FlagsKilled = true;
527
528 rewriteArithmetic(TestMBB, TestPos, TestLoc, MI, *FlagUse, CondRegs);
529 break;
530 }
531
532 // If this was the last use of the flags, we're done.
533 if (FlagsKilled)
534 break;
Chandler Carruth19618fc2018-04-10 01:41:17 +0000535 }
536
Chandler Carruth1f876182018-04-18 15:13:16 +0000537 // If the flags were killed, we're done with this block.
Chandler Carruth19618fc2018-04-10 01:41:17 +0000538 if (FlagsKilled)
539 break;
Chandler Carruth19618fc2018-04-10 01:41:17 +0000540
Chandler Carruth1f876182018-04-18 15:13:16 +0000541 // Otherwise we need to scan successors for ones where the flags live-in
542 // and queue those up for processing.
543 for (MachineBasicBlock *SuccMBB : UseMBB.successors())
544 if (SuccMBB->isLiveIn(X86::EFLAGS) &&
545 VisitedBlocks.insert(SuccMBB).second)
546 Blocks.push_back(SuccMBB);
547 } while (!Blocks.empty());
Chandler Carruth19618fc2018-04-10 01:41:17 +0000548
549 // Now rewrite the jumps that use the flags. These we handle specially
Chandler Carruth1f876182018-04-18 15:13:16 +0000550 // because if there are multiple jumps in a single basic block we'll have
551 // to do surgery on the CFG.
552 MachineBasicBlock *LastJmpMBB = nullptr;
Chandler Carruth19618fc2018-04-10 01:41:17 +0000553 for (MachineInstr *JmpI : JmpIs) {
Chandler Carruth1f876182018-04-18 15:13:16 +0000554 // Past the first jump within a basic block we need to split the blocks
555 // apart.
556 if (JmpI->getParent() == LastJmpMBB)
Chandler Carruth19618fc2018-04-10 01:41:17 +0000557 splitBlock(*JmpI->getParent(), *JmpI, *TII);
Chandler Carruth1f876182018-04-18 15:13:16 +0000558 else
559 LastJmpMBB = JmpI->getParent();
Chandler Carruth19618fc2018-04-10 01:41:17 +0000560
561 rewriteCondJmp(TestMBB, TestPos, TestLoc, *JmpI, CondRegs);
562 }
563
564 // FIXME: Mark the last use of EFLAGS before the copy's def as a kill if
565 // the copy's def operand is itself a kill.
566 }
567
568#ifndef NDEBUG
569 for (MachineBasicBlock &MBB : MF)
570 for (MachineInstr &MI : MBB)
571 if (MI.getOpcode() == TargetOpcode::COPY &&
572 (MI.getOperand(0).getReg() == X86::EFLAGS ||
573 MI.getOperand(1).getReg() == X86::EFLAGS)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000574 LLVM_DEBUG(dbgs() << "ERROR: Found a COPY involving EFLAGS: ";
575 MI.dump());
Chandler Carruth19618fc2018-04-10 01:41:17 +0000576 llvm_unreachable("Unlowered EFLAGS copy!");
577 }
578#endif
579
580 return true;
581}
582
583/// Collect any conditions that have already been set in registers so that we
584/// can re-use them rather than adding duplicates.
585CondRegArray
586X86FlagsCopyLoweringPass::collectCondsInRegs(MachineBasicBlock &MBB,
587 MachineInstr &CopyDefI) {
588 CondRegArray CondRegs = {};
589
590 // Scan backwards across the range of instructions with live EFLAGS.
591 for (MachineInstr &MI : llvm::reverse(
592 llvm::make_range(MBB.instr_begin(), CopyDefI.getIterator()))) {
593 X86::CondCode Cond = X86::getCondFromSETOpc(MI.getOpcode());
594 if (Cond != X86::COND_INVALID && MI.getOperand(0).isReg() &&
595 TRI->isVirtualRegister(MI.getOperand(0).getReg()))
596 CondRegs[Cond] = MI.getOperand(0).getReg();
597
598 // Stop scanning when we see the first definition of the EFLAGS as prior to
599 // this we would potentially capture the wrong flag state.
600 if (MI.findRegisterDefOperand(X86::EFLAGS))
601 break;
602 }
603 return CondRegs;
604}
605
606unsigned X86FlagsCopyLoweringPass::promoteCondToReg(
607 MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
608 DebugLoc TestLoc, X86::CondCode Cond) {
609 unsigned Reg = MRI->createVirtualRegister(PromoteRC);
610 auto SetI = BuildMI(TestMBB, TestPos, TestLoc,
611 TII->get(X86::getSETFromCond(Cond)), Reg);
612 (void)SetI;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000613 LLVM_DEBUG(dbgs() << " save cond: "; SetI->dump());
Chandler Carruth19618fc2018-04-10 01:41:17 +0000614 ++NumSetCCsInserted;
615 return Reg;
616}
617
618std::pair<unsigned, bool> X86FlagsCopyLoweringPass::getCondOrInverseInReg(
619 MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
620 DebugLoc TestLoc, X86::CondCode Cond, CondRegArray &CondRegs) {
621 unsigned &CondReg = CondRegs[Cond];
622 unsigned &InvCondReg = CondRegs[X86::GetOppositeBranchCondition(Cond)];
623 if (!CondReg && !InvCondReg)
624 CondReg = promoteCondToReg(TestMBB, TestPos, TestLoc, Cond);
625
626 if (CondReg)
627 return {CondReg, false};
628 else
629 return {InvCondReg, true};
630}
631
632void X86FlagsCopyLoweringPass::insertTest(MachineBasicBlock &MBB,
633 MachineBasicBlock::iterator Pos,
634 DebugLoc Loc, unsigned Reg) {
Chandler Carruth19618fc2018-04-10 01:41:17 +0000635 auto TestI =
Chandler Carruthccd3ecb2018-04-18 15:52:50 +0000636 BuildMI(MBB, Pos, Loc, TII->get(X86::TEST8rr)).addReg(Reg).addReg(Reg);
Chandler Carruth19618fc2018-04-10 01:41:17 +0000637 (void)TestI;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000638 LLVM_DEBUG(dbgs() << " test cond: "; TestI->dump());
Chandler Carruth19618fc2018-04-10 01:41:17 +0000639 ++NumTestsInserted;
640}
641
642void X86FlagsCopyLoweringPass::rewriteArithmetic(
643 MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
644 DebugLoc TestLoc, MachineInstr &MI, MachineOperand &FlagUse,
645 CondRegArray &CondRegs) {
646 // Arithmetic is either reading CF or OF. Figure out which condition we need
647 // to preserve in a register.
648 X86::CondCode Cond;
649
650 // The addend to use to reset CF or OF when added to the flag value.
651 int Addend;
652
653 switch (getMnemonicFromOpcode(MI.getOpcode())) {
654 case FlagArithMnemonic::ADC:
655 case FlagArithMnemonic::ADCX:
656 case FlagArithMnemonic::RCL:
657 case FlagArithMnemonic::RCR:
658 case FlagArithMnemonic::SBB:
659 Cond = X86::COND_B; // CF == 1
660 // Set up an addend that when one is added will need a carry due to not
661 // having a higher bit available.
662 Addend = 255;
663 break;
664
665 case FlagArithMnemonic::ADOX:
666 Cond = X86::COND_O; // OF == 1
667 // Set up an addend that when one is added will turn from positive to
668 // negative and thus overflow in the signed domain.
669 Addend = 127;
670 break;
671 }
672
673 // Now get a register that contains the value of the flag input to the
674 // arithmetic. We require exactly this flag to simplify the arithmetic
675 // required to materialize it back into the flag.
676 unsigned &CondReg = CondRegs[Cond];
677 if (!CondReg)
678 CondReg = promoteCondToReg(TestMBB, TestPos, TestLoc, Cond);
679
680 MachineBasicBlock &MBB = *MI.getParent();
681
682 // Insert an instruction that will set the flag back to the desired value.
683 unsigned TmpReg = MRI->createVirtualRegister(PromoteRC);
684 auto AddI =
685 BuildMI(MBB, MI.getIterator(), MI.getDebugLoc(), TII->get(X86::ADD8ri))
686 .addDef(TmpReg, RegState::Dead)
687 .addReg(CondReg)
688 .addImm(Addend);
689 (void)AddI;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000690 LLVM_DEBUG(dbgs() << " add cond: "; AddI->dump());
Chandler Carruth19618fc2018-04-10 01:41:17 +0000691 ++NumAddsInserted;
692 FlagUse.setIsKill(true);
693}
694
695void X86FlagsCopyLoweringPass::rewriteCMov(MachineBasicBlock &TestMBB,
696 MachineBasicBlock::iterator TestPos,
697 DebugLoc TestLoc,
698 MachineInstr &CMovI,
699 MachineOperand &FlagUse,
700 CondRegArray &CondRegs) {
701 // First get the register containing this specific condition.
702 X86::CondCode Cond = X86::getCondFromCMovOpc(CMovI.getOpcode());
703 unsigned CondReg;
704 bool Inverted;
705 std::tie(CondReg, Inverted) =
706 getCondOrInverseInReg(TestMBB, TestPos, TestLoc, Cond, CondRegs);
707
708 MachineBasicBlock &MBB = *CMovI.getParent();
709
710 // Insert a direct test of the saved register.
711 insertTest(MBB, CMovI.getIterator(), CMovI.getDebugLoc(), CondReg);
712
713 // Rewrite the CMov to use the !ZF flag from the test (but match register
714 // size and memory operand), and then kill its use of the flags afterward.
715 auto &CMovRC = *MRI->getRegClass(CMovI.getOperand(0).getReg());
716 CMovI.setDesc(TII->get(X86::getCMovFromCond(
717 Inverted ? X86::COND_E : X86::COND_NE, TRI->getRegSizeInBits(CMovRC) / 8,
718 !CMovI.memoperands_empty())));
719 FlagUse.setIsKill(true);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000720 LLVM_DEBUG(dbgs() << " fixed cmov: "; CMovI.dump());
Chandler Carruth19618fc2018-04-10 01:41:17 +0000721}
722
723void X86FlagsCopyLoweringPass::rewriteCondJmp(
724 MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
725 DebugLoc TestLoc, MachineInstr &JmpI, CondRegArray &CondRegs) {
726 // First get the register containing this specific condition.
727 X86::CondCode Cond = X86::getCondFromBranchOpc(JmpI.getOpcode());
728 unsigned CondReg;
729 bool Inverted;
730 std::tie(CondReg, Inverted) =
731 getCondOrInverseInReg(TestMBB, TestPos, TestLoc, Cond, CondRegs);
732
733 MachineBasicBlock &JmpMBB = *JmpI.getParent();
734
735 // Insert a direct test of the saved register.
736 insertTest(JmpMBB, JmpI.getIterator(), JmpI.getDebugLoc(), CondReg);
737
738 // Rewrite the jump to use the !ZF flag from the test, and kill its use of
739 // flags afterward.
740 JmpI.setDesc(TII->get(
741 X86::GetCondBranchFromCond(Inverted ? X86::COND_E : X86::COND_NE)));
742 const int ImplicitEFLAGSOpIdx = 1;
743 JmpI.getOperand(ImplicitEFLAGSOpIdx).setIsKill(true);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000744 LLVM_DEBUG(dbgs() << " fixed jCC: "; JmpI.dump());
Chandler Carruth19618fc2018-04-10 01:41:17 +0000745}
746
747void X86FlagsCopyLoweringPass::rewriteCopy(MachineInstr &MI,
748 MachineOperand &FlagUse,
749 MachineInstr &CopyDefI) {
Hiroshi Inoue372ffa12018-04-13 11:37:06 +0000750 // Just replace this copy with the original copy def.
Chandler Carruth19618fc2018-04-10 01:41:17 +0000751 MRI->replaceRegWith(MI.getOperand(0).getReg(),
752 CopyDefI.getOperand(0).getReg());
753 MI.eraseFromParent();
754}
755
756void X86FlagsCopyLoweringPass::rewriteSetCC(MachineBasicBlock &TestMBB,
757 MachineBasicBlock::iterator TestPos,
758 DebugLoc TestLoc,
759 MachineInstr &SetCCI,
760 MachineOperand &FlagUse,
761 CondRegArray &CondRegs) {
762 X86::CondCode Cond = X86::getCondFromSETOpc(SetCCI.getOpcode());
763 // Note that we can't usefully rewrite this to the inverse without complex
764 // analysis of the users of the setCC. Largely we rely on duplicates which
765 // could have been avoided already being avoided here.
766 unsigned &CondReg = CondRegs[Cond];
767 if (!CondReg)
768 CondReg = promoteCondToReg(TestMBB, TestPos, TestLoc, Cond);
769
Craig Topperee2c1de2018-04-11 01:09:10 +0000770 // Rewriting a register def is trivial: we just replace the register and
771 // remove the setcc.
772 if (!SetCCI.mayStore()) {
773 assert(SetCCI.getOperand(0).isReg() &&
774 "Cannot have a non-register defined operand to SETcc!");
775 MRI->replaceRegWith(SetCCI.getOperand(0).getReg(), CondReg);
776 SetCCI.eraseFromParent();
777 return;
778 }
779
780 // Otherwise, we need to emit a store.
781 auto MIB = BuildMI(*SetCCI.getParent(), SetCCI.getIterator(),
782 SetCCI.getDebugLoc(), TII->get(X86::MOV8mr));
783 // Copy the address operands.
784 for (int i = 0; i < X86::AddrNumOperands; ++i)
785 MIB.add(SetCCI.getOperand(i));
786
787 MIB.addReg(CondReg);
788
789 MIB->setMemRefs(SetCCI.memoperands_begin(), SetCCI.memoperands_end());
790
Chandler Carruth19618fc2018-04-10 01:41:17 +0000791 SetCCI.eraseFromParent();
Craig Topperee2c1de2018-04-11 01:09:10 +0000792 return;
Chandler Carruth19618fc2018-04-10 01:41:17 +0000793}