49 #define DEBUG_TYPE "regbankselect"
56 "Run the Fast mode (default mapping)"),
57 clEnumValN(RegBankSelect::Mode::Greedy,
"regbankselect-greedy",
58 "Use the Greedy mode (best local mapping)")));
63 "Assign register bank of generic virtual registers",
69 "Assign register bank of generic virtual registers",
false,
72 RegBankSelect::RegBankSelect(
Mode RunningMode)
78 DEBUG(
dbgs() <<
"RegBankSelect mode overrided by command line\n");
84 assert(RBI &&
"Cannot work without RegisterBankInfo");
87 TPC = &getAnalysis<TargetPassConfig>();
89 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
90 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
96 MORE = llvm::make_unique<MachineOptimizationRemarkEmitter>(MF, MBFI);
110 bool RegBankSelect::assignmentMatch(
112 bool &OnlyAssign)
const {
124 OnlyAssign = CurRegBank ==
nullptr;
125 DEBUG(
dbgs() <<
"Does assignment already match: ";
126 if (CurRegBank)
dbgs() << *CurRegBank;
else dbgs() <<
"none";
127 dbgs() <<
" against ";
128 assert(DesiredRegBrank &&
"The mapping must be valid");
129 dbgs() << *DesiredRegBrank <<
'\n';);
130 return CurRegBank == DesiredRegBrank;
133 bool RegBankSelect::repairReg(
141 assert(NewVRegs.begin() != NewVRegs.end() &&
"We should not have to repair");
145 unsigned Src = MO.
getReg();
146 unsigned Dst = *NewVRegs.begin();
155 "We are about to create several defs for Dst");
167 std::unique_ptr<MachineInstr *[]> NewInstrs(
171 for (
const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
177 InsertPt->insert(*CurMI);
178 NewInstrs[Idx++] = CurMI;
186 uint64_t RegBankSelect::getRepairCost(
189 assert(MO.
isReg() &&
"We should only repair register operand");
196 assert((!IsSameNumOfValues || CurRegBank) &&
"We should not have to repair");
207 if (IsSameNumOfValues) {
225 RBI->
copyCost(*DesiredRegBrank, *CurRegBank,
239 "Do not know how to map this instruction");
242 MappingCost Cost = MappingCost::ImpossibleCost();
246 MappingCost CurCost =
247 computeMapping(MI, *CurMapping, LocalRepairPts, &Cost);
248 if (CurCost < Cost) {
249 DEBUG(
dbgs() <<
"New best: " << CurCost <<
'\n');
251 BestMapping = CurMapping;
253 for (RepairingPlacement &RepairPt : LocalRepairPts)
261 BestMapping = *PossibleMappings.begin();
265 assert(BestMapping &&
"No suitable mapping for instruction");
269 void RegBankSelect::tryAvoidingSplit(
273 assert(RepairPt.
hasSplit() &&
"We should not have to adjust for split");
279 "Repairing placement does not match operand");
291 "Need to split for the first terminator?!");
298 RepairPt.
switchTo(RepairingPlacement::RepairingKind::Reassign);
313 "This code is for the def of a terminator");
347 unsigned Reg = MO.
getReg();
361 "Do not know which outgoing edges are relevant");
364 "Do not know where each terminator ends up");
378 assert(
false &&
"Repairing cost may not be accurate");
383 RepairPt.
switchTo(RepairingPlacement::RepairingKind::Impossible);
388 RegBankSelect::MappingCost RegBankSelect::computeMapping(
391 const RegBankSelect::MappingCost *BestCost) {
392 assert((MBFI || !BestCost) &&
"Costs comparison require MBFI");
395 return MappingCost::ImpossibleCost();
399 bool Saturated = Cost.addLocalCost(InstrMapping.
getCost());
400 assert(!Saturated &&
"Possible mapping saturated the cost");
401 DEBUG(
dbgs() <<
"Evaluating mapping cost for: " << MI);
402 DEBUG(
dbgs() <<
"With: " << InstrMapping <<
'\n');
404 if (BestCost && Cost > *BestCost) {
405 DEBUG(
dbgs() <<
"Mapping is too expensive from the start\n");
413 for (
unsigned OpIdx = 0, EndOpIdx = InstrMapping.
getNumOperands();
414 OpIdx != EndOpIdx; ++OpIdx) {
418 unsigned Reg = MO.
getReg();
423 InstrMapping.getOperandMapping(OpIdx);
426 if (assignmentMatch(Reg, ValMapping, Assign)) {
427 DEBUG(
dbgs() <<
"=> is free (match).\n");
431 DEBUG(
dbgs() <<
"=> is free (simple assignment).\n");
432 RepairPts.
emplace_back(RepairingPlacement(MI, OpIdx, *TRI, *
this,
440 RepairingPlacement &RepairPt = RepairPts.
back();
445 if (RepairPt.hasSplit())
446 tryAvoidingSplit(RepairPt, MO, ValMapping);
449 if (!RepairPt.canMaterialize()) {
450 DEBUG(
dbgs() <<
"Mapping involves impossible repairing\n");
451 return MappingCost::ImpossibleCost();
456 if (!BestCost || Saturated)
461 assert(MBFI && MBPI &&
"Cost computation requires MBFI and MBPI");
473 uint64_t RepairCost = getRepairCost(MO, ValMapping);
480 const uint64_t PercentageForBias = 5;
481 uint64_t Bias = (RepairCost * PercentageForBias + 99) / 100;
486 assert(((RepairCost < RepairCost * PercentageForBias) &&
487 (RepairCost * PercentageForBias <
488 RepairCost * PercentageForBias + 99)) &&
489 "Repairing involves more than a billion of instructions?!");
490 for (
const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
491 assert(InsertPt->canMaterialize() &&
"We should not have made it here");
493 if (!InsertPt->isSplit())
494 Saturated = Cost.addLocalCost(RepairCost);
496 uint64_t CostForInsertPt = RepairCost;
499 assert(CostForInsertPt + Bias > CostForInsertPt &&
500 "Repairing + split bias overflows");
501 CostForInsertPt += Bias;
502 uint64_t PtCost = InsertPt->frequency(*
this) * CostForInsertPt;
504 if ((Saturated = PtCost < CostForInsertPt))
507 Saturated = Cost.addNonLocalCost(PtCost);
512 if (BestCost && Cost > *BestCost) {
513 DEBUG(
dbgs() <<
"Mapping is too expensive, stop processing\n");
523 DEBUG(
dbgs() <<
"Total cost is: " << Cost <<
"\n");
527 bool RegBankSelect::applyMapping(
534 for (RepairingPlacement &RepairPt : RepairPts) {
535 if (!RepairPt.canMaterialize() ||
539 "This should not make its way in the list");
540 unsigned OpIdx = RepairPt.getOpIdx();
543 InstrMapping.getOperandMapping(OpIdx);
544 unsigned Reg = MO.
getReg();
546 switch (RepairPt.getKind()) {
549 "Reassignment should only be for simple mapping");
553 OpdMapper.createVRegs(OpIdx);
554 if (!repairReg(MO, ValMapping, RepairPt, OpdMapper.getVRegs(OpIdx)))
563 DEBUG(
dbgs() <<
"Actual mapping of the operands: " << OpdMapper <<
'\n');
564 RBI->applyMapping(OpdMapper);
577 MappingCost DefaultCost = computeMapping(MI, *BestMapping, RepairPts);
579 if (DefaultCost == MappingCost::ImpossibleCost())
583 RBI->getInstrPossibleMappings(MI);
584 if (PossibleMappings.
empty())
586 BestMapping = &findBestMapping(MI, PossibleMappings, RepairPts);
589 assert(BestMapping->
verify(MI) &&
"Invalid instruction mapping");
591 DEBUG(
dbgs() <<
"Best Mapping: " << *BestMapping <<
'\n');
595 return applyMapping(MI, *BestMapping, RepairPts);
606 Mode SaveOptMode = OptMode;
607 if (F->hasFnAttribute(Attribute::OptimizeNone))
622 "instruction is not legal", MI);
648 if (!assignInstr(MI)) {
650 "unable to map instruction", MI);
655 OptMode = SaveOptMode;
666 : Kind(Kind), OpIdx(OpIdx),
669 assert(MO.
isReg() &&
"Trying to repair a non-reg operand");
671 if (Kind != RepairingKind::Insert)
675 bool Before = !MO.
isDef();
701 unsigned Reg = MO.
getReg();
703 for (
auto Begin = Pred.
begin(); It != Begin && It->isTerminator(); --It)
704 if (It->modifiesRegister(Reg, &TRI)) {
715 if (It == Pred.
end())
723 unsigned Reg = MO.
getReg();
728 --It != Begin && It->isTerminator();)
729 if (It->modifiesRegister(Reg, &TRI)) {
742 assert(It->modifiesRegister(Reg, &TRI) &&
"Do not know where to split");
769 InsertPoints.emplace_back(&Point);
778 "Splitting before phis requires more points");
780 "Splitting between phis does not make sense");
783 void RegBankSelect::InstrInsertPoint::materialize() {
808 return Instr.isTerminator();
811 return Instr.getPrevNode() && Instr.getPrevNode()->isTerminator();
821 return MBFI->
getBlockFreq(Instr.getParent()).getFrequency();
832 void RegBankSelect::EdgeInsertPoint::materialize() {
837 assert(Src.isSuccessor(DstOrSplit) && DstOrSplit->isPredecessor(&Src) &&
838 "This point has already been split");
840 assert(NewBB &&
"Invalid call to materialize");
866 assert(Src.succ_size() > 1 && DstOrSplit->pred_size() > 1 &&
867 "Edge is not critical");
868 return Src.canSplitCriticalEdge(DstOrSplit);
871 RegBankSelect::MappingCost::MappingCost(
const BlockFrequency &LocalFreq)
872 : LocalFreq(LocalFreq.getFrequency()) {}
874 bool RegBankSelect::MappingCost::addLocalCost(uint64_t Cost) {
876 if (LocalCost + Cost < LocalCost) {
881 return isSaturated();
884 bool RegBankSelect::MappingCost::addNonLocalCost(uint64_t Cost) {
886 if (NonLocalCost + Cost < NonLocalCost) {
890 NonLocalCost += Cost;
891 return isSaturated();
894 bool RegBankSelect::MappingCost::isSaturated()
const {
895 return LocalCost == UINT64_MAX - 1 && NonLocalCost == UINT64_MAX &&
896 LocalFreq == UINT64_MAX;
899 void RegBankSelect::MappingCost::saturate() {
900 *
this = ImpossibleCost();
904 RegBankSelect::MappingCost RegBankSelect::MappingCost::ImpossibleCost() {
905 return MappingCost(UINT64_MAX, UINT64_MAX, UINT64_MAX);
914 if ((*
this == ImpossibleCost()) || (Cost == ImpossibleCost()))
915 return (*
this == ImpossibleCost()) < (Cost == ImpossibleCost());
918 if (isSaturated() || Cost.isSaturated())
919 return isSaturated() < Cost.isSaturated();
926 uint64_t ThisLocalAdjust;
927 uint64_t OtherLocalAdjust;
932 if (NonLocalCost == Cost.NonLocalCost)
935 return LocalCost < Cost.LocalCost;
940 OtherLocalAdjust = 0;
941 if (LocalCost < Cost.LocalCost)
942 OtherLocalAdjust = Cost.LocalCost - LocalCost;
944 ThisLocalAdjust = LocalCost - Cost.LocalCost;
946 ThisLocalAdjust = LocalCost;
947 OtherLocalAdjust = Cost.LocalCost;
951 uint64_t ThisNonLocalAdjust = 0;
952 uint64_t OtherNonLocalAdjust = 0;
953 if (NonLocalCost < Cost.NonLocalCost)
954 OtherNonLocalAdjust = Cost.NonLocalCost - NonLocalCost;
956 ThisNonLocalAdjust = NonLocalCost - Cost.NonLocalCost;
958 uint64_t ThisScaledCost = ThisLocalAdjust * LocalFreq;
960 bool ThisOverflows = ThisLocalAdjust && (ThisScaledCost < ThisLocalAdjust ||
961 ThisScaledCost < LocalFreq);
962 uint64_t OtherScaledCost = OtherLocalAdjust * Cost.LocalFreq;
964 bool OtherOverflows =
966 (OtherScaledCost < OtherLocalAdjust || OtherScaledCost < Cost.LocalFreq);
968 ThisOverflows |= ThisNonLocalAdjust &&
969 ThisScaledCost + ThisNonLocalAdjust < ThisNonLocalAdjust;
970 ThisScaledCost += ThisNonLocalAdjust;
971 OtherOverflows |= OtherNonLocalAdjust &&
972 OtherScaledCost + OtherNonLocalAdjust < OtherNonLocalAdjust;
973 OtherScaledCost += OtherNonLocalAdjust;
976 if (ThisOverflows && OtherOverflows)
979 if (ThisOverflows || OtherOverflows)
980 return ThisOverflows < OtherOverflows;
982 return ThisScaledCost < OtherScaledCost;
986 return LocalCost == Cost.LocalCost && NonLocalCost == Cost.NonLocalCost &&
987 LocalFreq == Cost.LocalFreq;
990 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
997 void RegBankSelect::MappingCost::print(
raw_ostream &OS)
const {
998 if (*
this == ImpossibleCost()) {
1002 if (isSaturated()) {
1006 OS << LocalFreq <<
" * " << LocalCost <<
" + " << NonLocalCost;
Pass interface - Implemented by all 'passes'.
virtual unsigned copyCost(const RegisterBank &A, const RegisterBank &B, unsigned Size) const
Get the cost of a copy from B to A, or put differently, get the cost of A = COPY B.
bool canMaterialize() const override
Check whether this insertion point can be materialized.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
bool hasProperty(Property P) const
MachineBasicBlock * getMBB() const
#define LLVM_LIKELY(EXPR)
Helper class that represents how the value of an instruction may be mapped and what is the related co...
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
Reparing code needs to happen before InsertPoints.
static bool isTargetSpecificOpcode(unsigned Opcode)
Check whether the given Opcode is a target-specific opcode.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
static void dump(StringRef Title, SpillInfo const &Spills)
Helper class used to get/create the virtual registers that will be used to replace the MachineOperand...
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void setRegBank(unsigned Reg, const RegisterBank &RegBank)
Set the register bank to RegBank for Reg.
Mode
List of the modes supported by the RegBankSelect pass.
const MachineInstrBuilder & addDef(unsigned RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
void switchTo(RepairingKind NewKind)
Change the type of this repairing placement to NewKind.
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
iterator_range< succ_iterator > successors()
const PartialMapping * BreakDown
How the value is broken down between the different register banks.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Mark this repairing placement as impossible.
virtual const InstructionMapping & getInstrMapping(const MachineInstr &MI) const
Get the mapping of the different operands of MI on the register bank.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
virtual const RegisterBankInfo * getRegBankInfo() const
If the information for the register banks is available, return it.
Abstract class used to represent an insertion point in a CFG.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isReg() const
isReg - Tests if this is a MO_Register operand.
const MachineFunctionProperties & getProperties() const
Get the function properties.
Reg
All possible values of the reg field in the ModR/M byte.
RepairingKind
Define the kind of action this repairing needs.
This file contains the simple types necessary to represent the attributes associated with functions a...
virtual bool isGlobalISelAbortEnabled() const
Check whether or not GlobalISel should abort on error.
Target-Independent Code Generator Pass Configuration Options.
LLVM_NODISCARD bool empty() const
unsigned getOpIdx() const
virtual bool isSplit() const
Does this point involve splitting an edge or block? As soon as ::getPoint is called and thus...
MachineInstrBuilder buildInstrNoInsert(unsigned Opcode)
Build but don't insert <empty> = Opcode <empty>.
MachineFunction & getMF()
Getter for the function we currently build.
virtual bool canMaterialize() const
Check whether this insertion point can be materialized.
iterator getLastNonDebugInstr()
Returns an iterator to the last non-debug instruction in the basic block, or end().
Printable PrintReg(unsigned Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubRegIdx=0)
Prints virtual and physical registers with or without a TRI instance.
RepairingPlacement(MachineInstr &MI, unsigned OpIdx, const TargetRegisterInfo &TRI, Pass &P, RepairingKind Kind=RepairingKind::Insert)
Create a repairing placement for the OpIdx-th operand of MI.
const RegisterBank * RegBank
Register bank where the partial value lives.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
uint64_t frequency(const Pass &P) const override
Frequency of the insertion point.
ValuesClass values(OptsTy...Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Function Alias Analysis false
This pass implements the reg bank selector pass used in the GlobalISel pipeline.
Insertion point on an edge.
static unsigned getSizeInBits(unsigned Reg, const MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI)
Get the size in bits of Reg.
const MachineOperand & getOperand(unsigned i) const
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Represent the analysis usage information of a pass.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
static const unsigned End
unsigned getNumInsertPoints() const
void initializeRegBankSelectPass(PassRegistry &)
void setMF(MachineFunction &)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
bool readsRegister(unsigned Reg, const TargetRegisterInfo *TRI=nullptr) const
Return true if the MachineInstr reads the specified register.
Struct used to represent the placement of a repairing point for a given operand.
static cl::opt< RegBankSelect::Mode > RegBankSelectMode(cl::desc("Mode of the RegBankSelect pass"), cl::Hidden, cl::Optional, cl::values(clEnumValN(RegBankSelect::Mode::Fast,"regbankselect-fast","Run the Fast mode (default mapping)"), clEnumValN(RegBankSelect::Mode::Greedy,"regbankselect-greedy","Use the Greedy mode (best local mapping)")))
MachineInstr * CloneMachineInstr(const MachineInstr *Orig)
CloneMachineInstr - Create a new MachineInstr which is a copy of the 'Orig' instruction, identical in all ways except the instruction has no parent, prev, or next.
RegisterBank & getRegBank(unsigned ID)
Get the register bank identified by ID.
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
This class implements the register bank concept.
Helper struct that represents how a value is mapped through different register banks.
unsigned getCost() const
Get the cost.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
A range adaptor for a pair of iterators.
static bool isPreISelGenericOpcode(unsigned Opcode)
Check whether the given Opcode is a generic opcode that is not supposed to appear after ISel...
bool isValid() const
Check whether this object is valid.
INITIALIZE_PASS_BEGIN(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false)
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
llvm_unreachable("Unknown RegBank!")
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Representation of each machine instruction.
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
void emplace_back(ArgTypes &&...Args)
Insertion point before or after an instruction.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
void setMBB(MachineBasicBlock &MBB)
Set the insertion point to the end of MBB.
InstrInsertPoint(MachineInstr &Instr, bool Before=true)
Create an insertion point before (Before=true) or after Instr.
uint64_t frequency(const Pass &P) const override
Frequency of the insertion point.
unsigned getNumOperands() const
Get the number of operands.
Fast - This calling convention attempts to make calls as fast as possible (e.g.
void addInsertPoint(MachineBasicBlock &MBB, bool Beginning)
iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
bool runOnMachineFunction(MachineFunction &MF) override
Walk through MF and assign a register bank to every virtual register that are still mapped to nothing...
unsigned getReg() const
getReg - Returns the register number.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
MachineBasicBlock * SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P)
Split the critical edge from this block to the given successor block, and return the newly created bl...
bool operator<(int64_t V1, const APSInt &V2)
const MachineInstrBuilder & addUse(unsigned RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register use operand.
unsigned NumBreakDowns
Number of partial mapping to break down this value.
bool verify(const MachineInstr &MI) const
Verifiy that this mapping makes sense for MI.
(Re)assign the register bank of the operand.
virtual const LegalizerInfo * getLegalizerInfo() const
This class implements an extremely fast bulk output stream that can only output to a stream...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual void print(raw_ostream &O, const Module *M) const
print - Print out the internal state of the pass.
bool operator==(uint64_t V1, const APInt &V2)
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
uint64_t frequency(const Pass &P) const override
Frequency of the insertion point.
BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
void reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC, MachineOptimizationRemarkEmitter &MORE, MachineOptimizationRemarkMissed &R)
Report an ISel error as a missed optimization remark to the LLVMContext's diagnostic stream...
Insertion point at the beginning or end of a basic block.
Nothing to repair, just drop this action.
bool isUnconditionalBranch(QueryType Type=AnyInBundle) const
Return true if this is a branch which always transfers control flow to some other block...
bool isSplit() const override
Does this point involve splitting an edge or block? As soon as ::getPoint is called and thus...