Path: blob/main/contrib/llvm-project/llvm/lib/Target/X86/X86FlagsCopyLowering.cpp
35269 views
//====- X86FlagsCopyLowering.cpp - Lowers COPY nodes of EFLAGS ------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7/// \file8///9/// Lowers COPY nodes of EFLAGS by directly extracting and preserving individual10/// flag bits.11///12/// We have to do this by carefully analyzing and rewriting the usage of the13/// copied EFLAGS register because there is no general way to rematerialize the14/// entire EFLAGS register safely and efficiently. Using `popf` both forces15/// dynamic stack adjustment and can create correctness issues due to IF, TF,16/// and other non-status flags being overwritten. Using sequences involving17/// SAHF don't work on all x86 processors and are often quite slow compared to18/// directly testing a single status preserved in its own GPR.19///20//===----------------------------------------------------------------------===//2122#include "X86.h"23#include "X86InstrBuilder.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/MachineFunctionPass.h"38#include "llvm/CodeGen/MachineInstr.h"39#include "llvm/CodeGen/MachineInstrBuilder.h"40#include "llvm/CodeGen/MachineModuleInfo.h"41#include "llvm/CodeGen/MachineOperand.h"42#include "llvm/CodeGen/MachineRegisterInfo.h"43#include "llvm/CodeGen/MachineSSAUpdater.h"44#include "llvm/CodeGen/TargetInstrInfo.h"45#include "llvm/CodeGen/TargetRegisterInfo.h"46#include "llvm/CodeGen/TargetSchedule.h"47#include "llvm/CodeGen/TargetSubtargetInfo.h"48#include "llvm/IR/DebugLoc.h"49#include "llvm/MC/MCSchedule.h"50#include "llvm/Pass.h"51#include "llvm/Support/CommandLine.h"52#include "llvm/Support/Debug.h"53#include "llvm/Support/raw_ostream.h"54#include <algorithm>55#include <cassert>56#include <iterator>57#include <utility>5859using namespace llvm;6061#define PASS_KEY "x86-flags-copy-lowering"62#define DEBUG_TYPE PASS_KEY6364STATISTIC(NumCopiesEliminated, "Number of copies of EFLAGS eliminated");65STATISTIC(NumSetCCsInserted, "Number of setCC instructions inserted");66STATISTIC(NumTestsInserted, "Number of test instructions inserted");67STATISTIC(NumAddsInserted, "Number of adds instructions inserted");68STATISTIC(NumNFsConvertedTo, "Number of NF instructions converted to");6970namespace {7172// Convenient array type for storing registers associated with each condition.73using CondRegArray = std::array<unsigned, X86::LAST_VALID_COND + 1>;7475class X86FlagsCopyLoweringPass : public MachineFunctionPass {76public:77X86FlagsCopyLoweringPass() : MachineFunctionPass(ID) {}7879StringRef getPassName() const override { return "X86 EFLAGS copy lowering"; }80bool runOnMachineFunction(MachineFunction &MF) override;81void getAnalysisUsage(AnalysisUsage &AU) const override;8283/// Pass identification, replacement for typeid.84static char ID;8586private:87MachineRegisterInfo *MRI = nullptr;88const X86Subtarget *Subtarget = nullptr;89const X86InstrInfo *TII = nullptr;90const TargetRegisterInfo *TRI = nullptr;91const TargetRegisterClass *PromoteRC = nullptr;92MachineDominatorTree *MDT = nullptr;9394CondRegArray collectCondsInRegs(MachineBasicBlock &MBB,95MachineBasicBlock::iterator CopyDefI);9697Register promoteCondToReg(MachineBasicBlock &MBB,98MachineBasicBlock::iterator TestPos,99const DebugLoc &TestLoc, X86::CondCode Cond);100std::pair<unsigned, bool> getCondOrInverseInReg(101MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,102const DebugLoc &TestLoc, X86::CondCode Cond, CondRegArray &CondRegs);103void insertTest(MachineBasicBlock &MBB, MachineBasicBlock::iterator Pos,104const DebugLoc &Loc, unsigned Reg);105106void rewriteSetCC(MachineBasicBlock &MBB, MachineBasicBlock::iterator Pos,107const DebugLoc &Loc, MachineInstr &MI,108CondRegArray &CondRegs);109void rewriteArithmetic(MachineBasicBlock &MBB,110MachineBasicBlock::iterator Pos, const DebugLoc &Loc,111MachineInstr &MI, CondRegArray &CondRegs);112void rewriteMI(MachineBasicBlock &MBB, MachineBasicBlock::iterator Pos,113const DebugLoc &Loc, MachineInstr &MI, CondRegArray &CondRegs);114};115116} // end anonymous namespace117118INITIALIZE_PASS_BEGIN(X86FlagsCopyLoweringPass, DEBUG_TYPE,119"X86 EFLAGS copy lowering", false, false)120INITIALIZE_PASS_END(X86FlagsCopyLoweringPass, DEBUG_TYPE,121"X86 EFLAGS copy lowering", false, false)122123FunctionPass *llvm::createX86FlagsCopyLoweringPass() {124return new X86FlagsCopyLoweringPass();125}126127char X86FlagsCopyLoweringPass::ID = 0;128129void X86FlagsCopyLoweringPass::getAnalysisUsage(AnalysisUsage &AU) const {130AU.addUsedIfAvailable<MachineDominatorTreeWrapperPass>();131MachineFunctionPass::getAnalysisUsage(AU);132}133134static bool isArithmeticOp(unsigned Opc) {135return X86::isADC(Opc) || X86::isSBB(Opc) || X86::isRCL(Opc) ||136X86::isRCR(Opc) || (Opc == X86::SETB_C32r || Opc == X86::SETB_C64r);137}138139static MachineBasicBlock &splitBlock(MachineBasicBlock &MBB,140MachineInstr &SplitI,141const X86InstrInfo &TII) {142MachineFunction &MF = *MBB.getParent();143144assert(SplitI.getParent() == &MBB &&145"Split instruction must be in the split block!");146assert(SplitI.isBranch() &&147"Only designed to split a tail of branch instructions!");148assert(X86::getCondFromBranch(SplitI) != X86::COND_INVALID &&149"Must split on an actual jCC instruction!");150151// Dig out the previous instruction to the split point.152MachineInstr &PrevI = *std::prev(SplitI.getIterator());153assert(PrevI.isBranch() && "Must split after a branch!");154assert(X86::getCondFromBranch(PrevI) != X86::COND_INVALID &&155"Must split after an actual jCC instruction!");156assert(!std::prev(PrevI.getIterator())->isTerminator() &&157"Must only have this one terminator prior to the split!");158159// Grab the one successor edge that will stay in `MBB`.160MachineBasicBlock &UnsplitSucc = *PrevI.getOperand(0).getMBB();161162// Analyze the original block to see if we are actually splitting an edge163// into two edges. This can happen when we have multiple conditional jumps to164// the same successor.165bool IsEdgeSplit =166std::any_of(SplitI.getIterator(), MBB.instr_end(),167[&](MachineInstr &MI) {168assert(MI.isTerminator() &&169"Should only have spliced terminators!");170return llvm::any_of(171MI.operands(), [&](MachineOperand &MOp) {172return MOp.isMBB() && MOp.getMBB() == &UnsplitSucc;173});174}) ||175MBB.getFallThrough() == &UnsplitSucc;176177MachineBasicBlock &NewMBB = *MF.CreateMachineBasicBlock();178179// Insert the new block immediately after the current one. Any existing180// fallthrough will be sunk into this new block anyways.181MF.insert(std::next(MachineFunction::iterator(&MBB)), &NewMBB);182183// Splice the tail of instructions into the new block.184NewMBB.splice(NewMBB.end(), &MBB, SplitI.getIterator(), MBB.end());185186// Copy the necessary succesors (and their probability info) into the new187// block.188for (auto SI = MBB.succ_begin(), SE = MBB.succ_end(); SI != SE; ++SI)189if (IsEdgeSplit || *SI != &UnsplitSucc)190NewMBB.copySuccessor(&MBB, SI);191// Normalize the probabilities if we didn't end up splitting the edge.192if (!IsEdgeSplit)193NewMBB.normalizeSuccProbs();194195// Now replace all of the moved successors in the original block with the new196// block. This will merge their probabilities.197for (MachineBasicBlock *Succ : NewMBB.successors())198if (Succ != &UnsplitSucc)199MBB.replaceSuccessor(Succ, &NewMBB);200201// We should always end up replacing at least one successor.202assert(MBB.isSuccessor(&NewMBB) &&203"Failed to make the new block a successor!");204205// Now update all the PHIs.206for (MachineBasicBlock *Succ : NewMBB.successors()) {207for (MachineInstr &MI : *Succ) {208if (!MI.isPHI())209break;210211for (int OpIdx = 1, NumOps = MI.getNumOperands(); OpIdx < NumOps;212OpIdx += 2) {213MachineOperand &OpV = MI.getOperand(OpIdx);214MachineOperand &OpMBB = MI.getOperand(OpIdx + 1);215assert(OpMBB.isMBB() && "Block operand to a PHI is not a block!");216if (OpMBB.getMBB() != &MBB)217continue;218219// Replace the operand for unsplit successors220if (!IsEdgeSplit || Succ != &UnsplitSucc) {221OpMBB.setMBB(&NewMBB);222223// We have to continue scanning as there may be multiple entries in224// the PHI.225continue;226}227228// When we have split the edge append a new successor.229MI.addOperand(MF, OpV);230MI.addOperand(MF, MachineOperand::CreateMBB(&NewMBB));231break;232}233}234}235236return NewMBB;237}238239enum EFLAGSClobber { NoClobber, EvitableClobber, InevitableClobber };240241static EFLAGSClobber getClobberType(const MachineInstr &MI) {242const MachineOperand *FlagDef =243MI.findRegisterDefOperand(X86::EFLAGS, /*TRI=*/nullptr);244if (!FlagDef)245return NoClobber;246if (FlagDef->isDead() && X86::getNFVariant(MI.getOpcode()))247return EvitableClobber;248249return InevitableClobber;250}251252bool X86FlagsCopyLoweringPass::runOnMachineFunction(MachineFunction &MF) {253LLVM_DEBUG(dbgs() << "********** " << getPassName() << " : " << MF.getName()254<< " **********\n");255256Subtarget = &MF.getSubtarget<X86Subtarget>();257MRI = &MF.getRegInfo();258TII = Subtarget->getInstrInfo();259TRI = Subtarget->getRegisterInfo();260PromoteRC = &X86::GR8RegClass;261262if (MF.empty())263// Nothing to do for a degenerate empty function...264return false;265266if (none_of(MRI->def_instructions(X86::EFLAGS), [](const MachineInstr &MI) {267return MI.getOpcode() == TargetOpcode::COPY;268}))269return false;270271// We change the code, so we don't preserve the dominator tree anyway. If we272// got a valid MDT from the pass manager, use that, otherwise construct one273// now. This is an optimization that avoids unnecessary MDT construction for274// functions that have no flag copies.275276auto MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();277std::unique_ptr<MachineDominatorTree> OwnedMDT;278if (MDTWrapper) {279MDT = &MDTWrapper->getDomTree();280} else {281OwnedMDT = std::make_unique<MachineDominatorTree>();282OwnedMDT->getBase().recalculate(MF);283MDT = OwnedMDT.get();284}285286// Collect the copies in RPO so that when there are chains where a copy is in287// turn copied again we visit the first one first. This ensures we can find288// viable locations for testing the original EFLAGS that dominate all the289// uses across complex CFGs.290SmallSetVector<MachineInstr *, 4> Copies;291ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);292for (MachineBasicBlock *MBB : RPOT)293for (MachineInstr &MI : *MBB)294if (MI.getOpcode() == TargetOpcode::COPY &&295MI.getOperand(0).getReg() == X86::EFLAGS)296Copies.insert(&MI);297298// Try to elminate the copys by transform the instructions between copy and299// copydef to the NF (no flags update) variants, e.g.300//301// %1:gr64 = COPY $eflags302// OP1 implicit-def dead $eflags303// $eflags = COPY %1304// OP2 cc, implicit $eflags305//306// ->307//308// OP1_NF309// OP2 implicit $eflags310if (Subtarget->hasNF()) {311SmallSetVector<MachineInstr *, 4> RemovedCopies;312// CopyIIt may be invalidated by removing copies.313auto CopyIIt = Copies.begin(), CopyIEnd = Copies.end();314while (CopyIIt != CopyIEnd) {315auto NCopyIIt = std::next(CopyIIt);316SmallSetVector<MachineInstr *, 4> EvitableClobbers;317MachineInstr *CopyI = *CopyIIt;318MachineOperand &VOp = CopyI->getOperand(1);319MachineInstr *CopyDefI = MRI->getVRegDef(VOp.getReg());320MachineBasicBlock *CopyIMBB = CopyI->getParent();321MachineBasicBlock *CopyDefIMBB = CopyDefI->getParent();322// Walk all basic blocks reachable in depth-first iteration on the inverse323// CFG from CopyIMBB to CopyDefIMBB. These blocks are all the blocks that324// may be executed between the execution of CopyDefIMBB and CopyIMBB. On325// all execution paths, instructions from CopyDefI to CopyI (exclusive)326// has to be NF-convertible if it clobbers flags.327for (auto BI = idf_begin(CopyIMBB), BE = idf_end(CopyDefIMBB); BI != BE;328++BI) {329MachineBasicBlock *MBB = *BI;330for (auto I = (MBB != CopyDefIMBB)331? MBB->begin()332: std::next(MachineBasicBlock::iterator(CopyDefI)),333E = (MBB != CopyIMBB) ? MBB->end()334: MachineBasicBlock::iterator(CopyI);335I != E; ++I) {336MachineInstr &MI = *I;337EFLAGSClobber ClobberType = getClobberType(MI);338if (ClobberType == NoClobber)339continue;340341if (ClobberType == InevitableClobber)342goto ProcessNextCopyI;343344assert(ClobberType == EvitableClobber && "unexpected workflow");345EvitableClobbers.insert(&MI);346}347}348// Covert evitable clobbers into NF variants and remove the copyies.349RemovedCopies.insert(CopyI);350CopyI->eraseFromParent();351if (MRI->use_nodbg_empty(CopyDefI->getOperand(0).getReg())) {352RemovedCopies.insert(CopyDefI);353CopyDefI->eraseFromParent();354}355++NumCopiesEliminated;356for (auto *Clobber : EvitableClobbers) {357unsigned NewOpc = X86::getNFVariant(Clobber->getOpcode());358assert(NewOpc && "evitable clobber must have a NF variant");359Clobber->setDesc(TII->get(NewOpc));360Clobber->removeOperand(361Clobber->findRegisterDefOperand(X86::EFLAGS, /*TRI=*/nullptr)362->getOperandNo());363++NumNFsConvertedTo;364}365// Update liveins for basic blocks in the path366for (auto BI = idf_begin(CopyIMBB), BE = idf_end(CopyDefIMBB); BI != BE;367++BI)368if (*BI != CopyDefIMBB)369BI->addLiveIn(X86::EFLAGS);370ProcessNextCopyI:371CopyIIt = NCopyIIt;372}373Copies.set_subtract(RemovedCopies);374}375376// For the rest of copies that cannot be eliminated by NF transform, we use377// setcc to preserve the flags in GPR32 before OP1, and recheck its value378// before using the flags, e.g.379//380// %1:gr64 = COPY $eflags381// OP1 implicit-def dead $eflags382// $eflags = COPY %1383// OP2 cc, implicit $eflags384//385// ->386//387// %1:gr8 = SETCCr cc, implicit $eflags388// OP1 implicit-def dead $eflags389// TEST8rr %1, %1, implicit-def $eflags390// OP2 ne, implicit $eflags391for (MachineInstr *CopyI : Copies) {392MachineBasicBlock &MBB = *CopyI->getParent();393394MachineOperand &VOp = CopyI->getOperand(1);395assert(VOp.isReg() &&396"The input to the copy for EFLAGS should always be a register!");397MachineInstr &CopyDefI = *MRI->getVRegDef(VOp.getReg());398if (CopyDefI.getOpcode() != TargetOpcode::COPY) {399// FIXME: The big likely candidate here are PHI nodes. We could in theory400// handle PHI nodes, but it gets really, really hard. Insanely hard. Hard401// enough that it is probably better to change every other part of LLVM402// to avoid creating them. The issue is that once we have PHIs we won't403// know which original EFLAGS value we need to capture with our setCCs404// below. The end result will be computing a complete set of setCCs that405// we *might* want, computing them in every place where we copy *out* of406// EFLAGS and then doing SSA formation on all of them to insert necessary407// PHI nodes and consume those here. Then hoping that somehow we DCE the408// unnecessary ones. This DCE seems very unlikely to be successful and so409// we will almost certainly end up with a glut of dead setCC410// instructions. Until we have a motivating test case and fail to avoid411// it by changing other parts of LLVM's lowering, we refuse to handle412// this complex case here.413LLVM_DEBUG(414dbgs() << "ERROR: Encountered unexpected def of an eflags copy: ";415CopyDefI.dump());416report_fatal_error(417"Cannot lower EFLAGS copy unless it is defined in turn by a copy!");418}419420auto Cleanup = make_scope_exit([&] {421// All uses of the EFLAGS copy are now rewritten, kill the copy into422// eflags and if dead the copy from.423CopyI->eraseFromParent();424if (MRI->use_empty(CopyDefI.getOperand(0).getReg()))425CopyDefI.eraseFromParent();426++NumCopiesEliminated;427});428429MachineOperand &DOp = CopyI->getOperand(0);430assert(DOp.isDef() && "Expected register def!");431assert(DOp.getReg() == X86::EFLAGS && "Unexpected copy def register!");432if (DOp.isDead())433continue;434435MachineBasicBlock *TestMBB = CopyDefI.getParent();436auto TestPos = CopyDefI.getIterator();437DebugLoc TestLoc = CopyDefI.getDebugLoc();438439LLVM_DEBUG(dbgs() << "Rewriting copy: "; CopyI->dump());440441// Walk up across live-in EFLAGS to find where they were actually def'ed.442//443// This copy's def may just be part of a region of blocks covered by444// a single def of EFLAGS and we want to find the top of that region where445// possible.446//447// This is essentially a search for a *candidate* reaching definition448// location. We don't need to ever find the actual reaching definition here,449// but we want to walk up the dominator tree to find the highest point which450// would be viable for such a definition.451auto HasEFLAGSClobber = [&](MachineBasicBlock::iterator Begin,452MachineBasicBlock::iterator End) {453// Scan backwards as we expect these to be relatively short and often find454// a clobber near the end.455return llvm::any_of(456llvm::reverse(llvm::make_range(Begin, End)), [&](MachineInstr &MI) {457// Flag any instruction (other than the copy we are458// currently rewriting) that defs EFLAGS.459return &MI != CopyI &&460MI.findRegisterDefOperand(X86::EFLAGS, /*TRI=*/nullptr);461});462};463auto HasEFLAGSClobberPath = [&](MachineBasicBlock *BeginMBB,464MachineBasicBlock *EndMBB) {465assert(MDT->dominates(BeginMBB, EndMBB) &&466"Only support paths down the dominator tree!");467SmallPtrSet<MachineBasicBlock *, 4> Visited;468SmallVector<MachineBasicBlock *, 4> Worklist;469// We terminate at the beginning. No need to scan it.470Visited.insert(BeginMBB);471Worklist.push_back(EndMBB);472do {473auto *MBB = Worklist.pop_back_val();474for (auto *PredMBB : MBB->predecessors()) {475if (!Visited.insert(PredMBB).second)476continue;477if (HasEFLAGSClobber(PredMBB->begin(), PredMBB->end()))478return true;479// Enqueue this block to walk its predecessors.480Worklist.push_back(PredMBB);481}482} while (!Worklist.empty());483// No clobber found along a path from the begin to end.484return false;485};486while (TestMBB->isLiveIn(X86::EFLAGS) && !TestMBB->pred_empty() &&487!HasEFLAGSClobber(TestMBB->begin(), TestPos)) {488// Find the nearest common dominator of the predecessors, as489// that will be the best candidate to hoist into.490MachineBasicBlock *HoistMBB =491std::accumulate(std::next(TestMBB->pred_begin()), TestMBB->pred_end(),492*TestMBB->pred_begin(),493[&](MachineBasicBlock *LHS, MachineBasicBlock *RHS) {494return MDT->findNearestCommonDominator(LHS, RHS);495});496497// Now we need to scan all predecessors that may be reached along paths to498// the hoist block. A clobber anywhere in any of these blocks the hoist.499// Note that this even handles loops because we require *no* clobbers.500if (HasEFLAGSClobberPath(HoistMBB, TestMBB))501break;502503// We also need the terminators to not sneakily clobber flags.504if (HasEFLAGSClobber(HoistMBB->getFirstTerminator()->getIterator(),505HoistMBB->instr_end()))506break;507508// We found a viable location, hoist our test position to it.509TestMBB = HoistMBB;510TestPos = TestMBB->getFirstTerminator()->getIterator();511// Clear the debug location as it would just be confusing after hoisting.512TestLoc = DebugLoc();513}514LLVM_DEBUG({515auto DefIt = llvm::find_if(516llvm::reverse(llvm::make_range(TestMBB->instr_begin(), TestPos)),517[&](MachineInstr &MI) {518return MI.findRegisterDefOperand(X86::EFLAGS, /*TRI=*/nullptr);519});520if (DefIt.base() != TestMBB->instr_begin()) {521dbgs() << " Using EFLAGS defined by: ";522DefIt->dump();523} else {524dbgs() << " Using live-in flags for BB:\n";525TestMBB->dump();526}527});528529// While rewriting uses, we buffer jumps and rewrite them in a second pass530// because doing so will perturb the CFG that we are walking to find the531// uses in the first place.532SmallVector<MachineInstr *, 4> JmpIs;533534// Gather the condition flags that have already been preserved in535// registers. We do this from scratch each time as we expect there to be536// very few of them and we expect to not revisit the same copy definition537// many times. If either of those change sufficiently we could build a map538// of these up front instead.539CondRegArray CondRegs = collectCondsInRegs(*TestMBB, TestPos);540541// Collect the basic blocks we need to scan. Typically this will just be542// a single basic block but we may have to scan multiple blocks if the543// EFLAGS copy lives into successors.544SmallVector<MachineBasicBlock *, 2> Blocks;545SmallPtrSet<MachineBasicBlock *, 2> VisitedBlocks;546Blocks.push_back(&MBB);547548do {549MachineBasicBlock &UseMBB = *Blocks.pop_back_val();550551// Track when if/when we find a kill of the flags in this block.552bool FlagsKilled = false;553554// In most cases, we walk from the beginning to the end of the block. But555// when the block is the same block as the copy is from, we will visit it556// twice. The first time we start from the copy and go to the end. The557// second time we start from the beginning and go to the copy. This lets558// us handle copies inside of cycles.559// FIXME: This loop is *super* confusing. This is at least in part560// a symptom of all of this routine needing to be refactored into561// documentable components. Once done, there may be a better way to write562// this loop.563for (auto MII = (&UseMBB == &MBB && !VisitedBlocks.count(&UseMBB))564? std::next(CopyI->getIterator())565: UseMBB.instr_begin(),566MIE = UseMBB.instr_end();567MII != MIE;) {568MachineInstr &MI = *MII++;569// If we are in the original copy block and encounter either the copy570// def or the copy itself, break so that we don't re-process any part of571// the block or process the instructions in the range that was copied572// over.573if (&MI == CopyI || &MI == &CopyDefI) {574assert(&UseMBB == &MBB && VisitedBlocks.count(&MBB) &&575"Should only encounter these on the second pass over the "576"original block.");577break;578}579580MachineOperand *FlagUse =581MI.findRegisterUseOperand(X86::EFLAGS, /*TRI=*/nullptr);582FlagsKilled = MI.modifiesRegister(X86::EFLAGS, TRI);583584if (!FlagUse && FlagsKilled)585break;586else if (!FlagUse)587continue;588589LLVM_DEBUG(dbgs() << " Rewriting use: "; MI.dump());590591// Check the kill flag before we rewrite as that may change it.592if (FlagUse->isKill())593FlagsKilled = true;594595// Once we encounter a branch, the rest of the instructions must also be596// branches. We can't rewrite in place here, so we handle them below.597//598// Note that we don't have to handle tail calls here, even conditional599// tail calls, as those are not introduced into the X86 MI until post-RA600// branch folding or black placement. As a consequence, we get to deal601// with the simpler formulation of conditional branches followed by tail602// calls.603if (X86::getCondFromBranch(MI) != X86::COND_INVALID) {604auto JmpIt = MI.getIterator();605do {606JmpIs.push_back(&*JmpIt);607++JmpIt;608} while (JmpIt != UseMBB.instr_end() &&609X86::getCondFromBranch(*JmpIt) != X86::COND_INVALID);610break;611}612613// Otherwise we can just rewrite in-place.614unsigned Opc = MI.getOpcode();615if (Opc == TargetOpcode::COPY) {616// Just replace this copy with the original copy def.617MRI->replaceRegWith(MI.getOperand(0).getReg(),618CopyDefI.getOperand(0).getReg());619MI.eraseFromParent();620} else if (X86::isSETCC(Opc)) {621rewriteSetCC(*TestMBB, TestPos, TestLoc, MI, CondRegs);622} else if (isArithmeticOp(Opc)) {623rewriteArithmetic(*TestMBB, TestPos, TestLoc, MI, CondRegs);624} else {625rewriteMI(*TestMBB, TestPos, TestLoc, MI, CondRegs);626}627628// If this was the last use of the flags, we're done.629if (FlagsKilled)630break;631}632633// If the flags were killed, we're done with this block.634if (FlagsKilled)635continue;636637// Otherwise we need to scan successors for ones where the flags live-in638// and queue those up for processing.639for (MachineBasicBlock *SuccMBB : UseMBB.successors())640if (SuccMBB->isLiveIn(X86::EFLAGS) &&641VisitedBlocks.insert(SuccMBB).second) {642// We currently don't do any PHI insertion and so we require that the643// test basic block dominates all of the use basic blocks. Further, we644// can't have a cycle from the test block back to itself as that would645// create a cycle requiring a PHI to break it.646//647// We could in theory do PHI insertion here if it becomes useful by648// just taking undef values in along every edge that we don't trace649// this EFLAGS copy along. This isn't as bad as fully general PHI650// insertion, but still seems like a great deal of complexity.651//652// Because it is theoretically possible that some earlier MI pass or653// other lowering transformation could induce this to happen, we do654// a hard check even in non-debug builds here.655if (SuccMBB == TestMBB || !MDT->dominates(TestMBB, SuccMBB)) {656LLVM_DEBUG({657dbgs()658<< "ERROR: Encountered use that is not dominated by our test "659"basic block! Rewriting this would require inserting PHI "660"nodes to track the flag state across the CFG.\n\nTest "661"block:\n";662TestMBB->dump();663dbgs() << "Use block:\n";664SuccMBB->dump();665});666report_fatal_error(667"Cannot lower EFLAGS copy when original copy def "668"does not dominate all uses.");669}670671Blocks.push_back(SuccMBB);672673// After this, EFLAGS will be recreated before each use.674SuccMBB->removeLiveIn(X86::EFLAGS);675}676} while (!Blocks.empty());677678// Now rewrite the jumps that use the flags. These we handle specially679// because if there are multiple jumps in a single basic block we'll have680// to do surgery on the CFG.681MachineBasicBlock *LastJmpMBB = nullptr;682for (MachineInstr *JmpI : JmpIs) {683// Past the first jump within a basic block we need to split the blocks684// apart.685if (JmpI->getParent() == LastJmpMBB)686splitBlock(*JmpI->getParent(), *JmpI, *TII);687else688LastJmpMBB = JmpI->getParent();689690rewriteMI(*TestMBB, TestPos, TestLoc, *JmpI, CondRegs);691}692693// FIXME: Mark the last use of EFLAGS before the copy's def as a kill if694// the copy's def operand is itself a kill.695}696697#ifndef NDEBUG698for (MachineBasicBlock &MBB : MF)699for (MachineInstr &MI : MBB)700if (MI.getOpcode() == TargetOpcode::COPY &&701(MI.getOperand(0).getReg() == X86::EFLAGS ||702MI.getOperand(1).getReg() == X86::EFLAGS)) {703LLVM_DEBUG(dbgs() << "ERROR: Found a COPY involving EFLAGS: ";704MI.dump());705llvm_unreachable("Unlowered EFLAGS copy!");706}707#endif708709return true;710}711712/// Collect any conditions that have already been set in registers so that we713/// can re-use them rather than adding duplicates.714CondRegArray X86FlagsCopyLoweringPass::collectCondsInRegs(715MachineBasicBlock &MBB, MachineBasicBlock::iterator TestPos) {716CondRegArray CondRegs = {};717718// Scan backwards across the range of instructions with live EFLAGS.719for (MachineInstr &MI :720llvm::reverse(llvm::make_range(MBB.begin(), TestPos))) {721X86::CondCode Cond = X86::getCondFromSETCC(MI);722if (Cond != X86::COND_INVALID && !MI.mayStore() &&723MI.getOperand(0).isReg() && MI.getOperand(0).getReg().isVirtual()) {724assert(MI.getOperand(0).isDef() &&725"A non-storing SETcc should always define a register!");726CondRegs[Cond] = MI.getOperand(0).getReg();727}728729// Stop scanning when we see the first definition of the EFLAGS as prior to730// this we would potentially capture the wrong flag state.731if (MI.findRegisterDefOperand(X86::EFLAGS, /*TRI=*/nullptr))732break;733}734return CondRegs;735}736737Register X86FlagsCopyLoweringPass::promoteCondToReg(738MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,739const DebugLoc &TestLoc, X86::CondCode Cond) {740Register Reg = MRI->createVirtualRegister(PromoteRC);741auto SetI = BuildMI(TestMBB, TestPos, TestLoc, TII->get(X86::SETCCr), Reg)742.addImm(Cond);743(void)SetI;744LLVM_DEBUG(dbgs() << " save cond: "; SetI->dump());745++NumSetCCsInserted;746return Reg;747}748749std::pair<unsigned, bool> X86FlagsCopyLoweringPass::getCondOrInverseInReg(750MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,751const DebugLoc &TestLoc, X86::CondCode Cond, CondRegArray &CondRegs) {752unsigned &CondReg = CondRegs[Cond];753unsigned &InvCondReg = CondRegs[X86::GetOppositeBranchCondition(Cond)];754if (!CondReg && !InvCondReg)755CondReg = promoteCondToReg(TestMBB, TestPos, TestLoc, Cond);756757if (CondReg)758return {CondReg, false};759else760return {InvCondReg, true};761}762763void X86FlagsCopyLoweringPass::insertTest(MachineBasicBlock &MBB,764MachineBasicBlock::iterator Pos,765const DebugLoc &Loc, unsigned Reg) {766auto TestI =767BuildMI(MBB, Pos, Loc, TII->get(X86::TEST8rr)).addReg(Reg).addReg(Reg);768(void)TestI;769LLVM_DEBUG(dbgs() << " test cond: "; TestI->dump());770++NumTestsInserted;771}772773void X86FlagsCopyLoweringPass::rewriteSetCC(MachineBasicBlock &MBB,774MachineBasicBlock::iterator Pos,775const DebugLoc &Loc,776MachineInstr &MI,777CondRegArray &CondRegs) {778X86::CondCode Cond = X86::getCondFromSETCC(MI);779// Note that we can't usefully rewrite this to the inverse without complex780// analysis of the users of the setCC. Largely we rely on duplicates which781// could have been avoided already being avoided here.782unsigned &CondReg = CondRegs[Cond];783if (!CondReg)784CondReg = promoteCondToReg(MBB, Pos, Loc, Cond);785786// Rewriting a register def is trivial: we just replace the register and787// remove the setcc.788if (!MI.mayStore()) {789assert(MI.getOperand(0).isReg() &&790"Cannot have a non-register defined operand to SETcc!");791Register OldReg = MI.getOperand(0).getReg();792// Drop Kill flags on the old register before replacing. CondReg may have793// a longer live range.794MRI->clearKillFlags(OldReg);795MRI->replaceRegWith(OldReg, CondReg);796MI.eraseFromParent();797return;798}799800// Otherwise, we need to emit a store.801auto MIB = BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(),802TII->get(X86::MOV8mr));803// Copy the address operands.804for (int i = 0; i < X86::AddrNumOperands; ++i)805MIB.add(MI.getOperand(i));806807MIB.addReg(CondReg);808MIB.setMemRefs(MI.memoperands());809MI.eraseFromParent();810}811812void X86FlagsCopyLoweringPass::rewriteArithmetic(813MachineBasicBlock &MBB, MachineBasicBlock::iterator Pos,814const DebugLoc &Loc, MachineInstr &MI, CondRegArray &CondRegs) {815// Arithmetic is either reading CF or OF.816X86::CondCode Cond = X86::COND_B; // CF == 1817// The addend to use to reset CF or OF when added to the flag value.818// Set up an addend that when one is added will need a carry due to not819// having a higher bit available.820int Addend = 255;821822// Now get a register that contains the value of the flag input to the823// arithmetic. We require exactly this flag to simplify the arithmetic824// required to materialize it back into the flag.825unsigned &CondReg = CondRegs[Cond];826if (!CondReg)827CondReg = promoteCondToReg(MBB, Pos, Loc, Cond);828829// Insert an instruction that will set the flag back to the desired value.830Register TmpReg = MRI->createVirtualRegister(PromoteRC);831auto AddI =832BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(),833TII->get(Subtarget->hasNDD() ? X86::ADD8ri_ND : X86::ADD8ri))834.addDef(TmpReg, RegState::Dead)835.addReg(CondReg)836.addImm(Addend);837(void)AddI;838LLVM_DEBUG(dbgs() << " add cond: "; AddI->dump());839++NumAddsInserted;840MI.findRegisterUseOperand(X86::EFLAGS, /*TRI=*/nullptr)->setIsKill(true);841}842843static X86::CondCode getImplicitCondFromMI(unsigned Opc) {844#define FROM_TO(A, B) \845case X86::CMOV##A##_Fp32: \846case X86::CMOV##A##_Fp64: \847case X86::CMOV##A##_Fp80: \848return X86::COND_##B;849850switch (Opc) {851default:852return X86::COND_INVALID;853FROM_TO(B, B)854FROM_TO(E, E)855FROM_TO(P, P)856FROM_TO(BE, BE)857FROM_TO(NB, AE)858FROM_TO(NE, NE)859FROM_TO(NP, NP)860FROM_TO(NBE, A)861}862#undef FROM_TO863}864865static unsigned getOpcodeWithCC(unsigned Opc, X86::CondCode CC) {866assert((CC == X86::COND_E || CC == X86::COND_NE) && "Unexpected CC");867#define CASE(A) \868case X86::CMOVB_##A: \869case X86::CMOVE_##A: \870case X86::CMOVP_##A: \871case X86::CMOVBE_##A: \872case X86::CMOVNB_##A: \873case X86::CMOVNE_##A: \874case X86::CMOVNP_##A: \875case X86::CMOVNBE_##A: \876return (CC == X86::COND_E) ? X86::CMOVE_##A : X86::CMOVNE_##A;877switch (Opc) {878default:879llvm_unreachable("Unexpected opcode");880CASE(Fp32)881CASE(Fp64)882CASE(Fp80)883}884#undef CASE885}886887void X86FlagsCopyLoweringPass::rewriteMI(MachineBasicBlock &MBB,888MachineBasicBlock::iterator Pos,889const DebugLoc &Loc, MachineInstr &MI,890CondRegArray &CondRegs) {891// First get the register containing this specific condition.892bool IsImplicitCC = false;893X86::CondCode CC = X86::getCondFromMI(MI);894if (CC == X86::COND_INVALID) {895CC = getImplicitCondFromMI(MI.getOpcode());896IsImplicitCC = true;897}898assert(CC != X86::COND_INVALID && "Unknown EFLAG user!");899unsigned CondReg;900bool Inverted;901std::tie(CondReg, Inverted) =902getCondOrInverseInReg(MBB, Pos, Loc, CC, CondRegs);903904// Insert a direct test of the saved register.905insertTest(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(), CondReg);906907// Rewrite the instruction to use the !ZF flag from the test, and then kill908// its use of the flags afterward.909X86::CondCode NewCC = Inverted ? X86::COND_E : X86::COND_NE;910if (IsImplicitCC)911MI.setDesc(TII->get(getOpcodeWithCC(MI.getOpcode(), NewCC)));912else913MI.getOperand(MI.getDesc().getNumOperands() - 1).setImm(NewCC);914915MI.findRegisterUseOperand(X86::EFLAGS, /*TRI=*/nullptr)->setIsKill(true);916LLVM_DEBUG(dbgs() << " fixed instruction: "; MI.dump());917}918919920