32 #include "llvm/Config/llvm-config.h" 50 #define DEBUG_TYPE "regbankselect" 57 "Run the Fast mode (default mapping)"),
58 clEnumValN(RegBankSelect::Mode::Greedy,
"regbankselect-greedy",
59 "Use the Greedy mode (best local mapping)")));
64 "Assign register bank of generic virtual registers",
70 "Assign register bank of generic virtual registers",
false,
73 RegBankSelect::RegBankSelect(
Mode RunningMode)
78 LLVM_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 = std::make_unique<MachineOptimizationRemarkEmitter>(MF, MBFI);
111 bool RegBankSelect::assignmentMatch(
113 bool &OnlyAssign)
const {
125 OnlyAssign = CurRegBank ==
nullptr;
127 if (CurRegBank)
dbgs() << *CurRegBank;
else dbgs() <<
"none";
128 dbgs() <<
" against ";
129 assert(DesiredRegBank &&
"The mapping must be valid");
130 dbgs() << *DesiredRegBank <<
'\n';);
131 return CurRegBank == DesiredRegBank;
134 bool RegBankSelect::repairReg(
140 "need new vreg for each breakdown");
143 assert(!NewVRegs.empty() &&
"We should not have to repair");
159 "We are about to create several defs for Dst");
177 if (RegTy.isVector()) {
179 MergeOp = TargetOpcode::G_BUILD_VECTOR;
183 RegTy.getSizeInBits()) &&
186 "don't understand this value breakdown");
188 MergeOp = TargetOpcode::G_CONCAT_VECTORS;
191 MergeOp = TargetOpcode::G_MERGE_VALUES;
198 MergeBuilder.
addUse(SrcReg);
205 UnMergeBuilder.
addDef(DefReg);
218 std::unique_ptr<MachineInstr *[]> NewInstrs(
222 for (
const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
228 InsertPt->insert(*CurMI);
229 NewInstrs[Idx++] = CurMI;
237 uint64_t RegBankSelect::getRepairCost(
240 assert(MO.
isReg() &&
"We should only repair register operand");
262 if (IsSameNumOfValues) {
279 unsigned Cost = RBI->
copyCost(*DesiredRegBank, *CurRegBank,
280 RBI->getSizeInBits(MO.
getReg(), *MRI, *TRI));
293 "Do not know how to map this instruction");
296 MappingCost Cost = MappingCost::ImpossibleCost();
300 MappingCost CurCost =
301 computeMapping(MI, *CurMapping, LocalRepairPts, &Cost);
302 if (CurCost < Cost) {
305 BestMapping = CurMapping;
315 BestMapping = *PossibleMappings.begin();
319 assert(BestMapping &&
"No suitable mapping for instruction");
323 void RegBankSelect::tryAvoidingSplit(
327 assert(RepairPt.
hasSplit() &&
"We should not have to adjust for split");
333 "Repairing placement does not match operand");
345 "Need to split for the first terminator?!");
367 "This code is for the def of a terminator");
415 "Do not know which outgoing edges are relevant");
418 "Do not know where each terminator ends up");
432 assert(
false &&
"Repairing cost may not be accurate");
437 RepairPt.
switchTo(RepairingPlacement::RepairingKind::Impossible);
442 RegBankSelect::MappingCost RegBankSelect::computeMapping(
445 const RegBankSelect::MappingCost *BestCost) {
446 assert((MBFI || !BestCost) &&
"Costs comparison require MBFI");
449 return MappingCost::ImpossibleCost();
453 bool Saturated = Cost.addLocalCost(InstrMapping.
getCost());
454 assert(!Saturated &&
"Possible mapping saturated the cost");
458 if (BestCost && Cost > *BestCost) {
459 LLVM_DEBUG(
dbgs() <<
"Mapping is too expensive from the start\n");
467 for (
unsigned OpIdx = 0, EndOpIdx = InstrMapping.
getNumOperands();
468 OpIdx != EndOpIdx; ++OpIdx) {
477 InstrMapping.getOperandMapping(OpIdx);
480 if (assignmentMatch(Reg, ValMapping, Assign)) {
500 tryAvoidingSplit(RepairPt, MO, ValMapping);
505 return MappingCost::ImpossibleCost();
510 if (!BestCost || Saturated)
515 assert(MBFI && MBPI &&
"Cost computation requires MBFI and MBPI");
527 uint64_t RepairCost = getRepairCost(MO, ValMapping);
531 return MappingCost::ImpossibleCost();
534 const uint64_t PercentageForBias = 5;
535 uint64_t Bias = (RepairCost * PercentageForBias + 99) / 100;
540 assert(((RepairCost < RepairCost * PercentageForBias) &&
541 (RepairCost * PercentageForBias <
542 RepairCost * PercentageForBias + 99)) &&
543 "Repairing involves more than a billion of instructions?!");
544 for (
const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
545 assert(InsertPt->canMaterialize() &&
"We should not have made it here");
547 if (!InsertPt->isSplit())
548 Saturated = Cost.addLocalCost(RepairCost);
550 uint64_t CostForInsertPt = RepairCost;
553 assert(CostForInsertPt + Bias > CostForInsertPt &&
554 "Repairing + split bias overflows");
555 CostForInsertPt += Bias;
556 uint64_t PtCost = InsertPt->frequency(*
this) * CostForInsertPt;
558 if ((Saturated = PtCost < CostForInsertPt))
561 Saturated = Cost.addNonLocalCost(PtCost);
566 if (BestCost && Cost > *BestCost) {
567 LLVM_DEBUG(
dbgs() <<
"Mapping is too expensive, stop processing\n");
581 bool RegBankSelect::applyMapping(
593 "This should not make its way in the list");
594 unsigned OpIdx = RepairPt.
getOpIdx();
597 InstrMapping.getOperandMapping(OpIdx);
603 "Reassignment should only be for simple mapping");
608 if (!repairReg(MO, ValMapping, RepairPt, OpdMapper.
getVRegs(OpIdx)))
617 LLVM_DEBUG(
dbgs() <<
"Actual mapping of the operands: " << OpdMapper <<
'\n');
618 RBI->applyMapping(OpdMapper);
631 MappingCost DefaultCost = computeMapping(MI, *BestMapping, RepairPts);
633 if (DefaultCost == MappingCost::ImpossibleCost())
637 RBI->getInstrPossibleMappings(MI);
638 if (PossibleMappings.
empty())
640 BestMapping = &findBestMapping(MI, PossibleMappings, RepairPts);
643 assert(BestMapping->
verify(MI) &&
"Invalid instruction mapping");
649 return applyMapping(MI, *BestMapping, RepairPts);
660 Mode SaveOptMode = OptMode;
672 "instruction is not legal", *MI);
696 if (!assignInstr(MI)) {
698 "unable to map instruction", MI);
706 if (NextInstBB != MBB) {
707 LLVM_DEBUG(
dbgs() <<
"Instruction mapping changed control flow\n");
716 OptMode = SaveOptMode;
727 : Kind(Kind), OpIdx(OpIdx),
730 assert(MO.
isReg() &&
"Trying to repair a non-reg operand");
732 if (Kind != RepairingKind::Insert)
736 bool Before = !MO.
isDef();
764 for (
auto Begin = Pred.
begin(); It != Begin && It->isTerminator(); --It)
765 if (It->modifiesRegister(Reg, &TRI)) {
776 if (It == Pred.
end())
789 for (; It != REnd && It->isTerminator(); ++It) {
791 "copy insertion in middle of terminators not handled");
809 "Do not know where to split");
845 "Splitting before phis requires more points");
847 "Splitting between phis does not make sense");
850 void RegBankSelect::InstrInsertPoint::materialize() {
899 void RegBankSelect::EdgeInsertPoint::materialize() {
904 assert(Src.isSuccessor(DstOrSplit) && DstOrSplit->isPredecessor(&Src) &&
905 "This point has already been split");
907 assert(NewBB &&
"Invalid call to materialize");
933 assert(Src.succ_size() > 1 && DstOrSplit->pred_size() > 1 &&
934 "Edge is not critical");
935 return Src.canSplitCriticalEdge(DstOrSplit);
938 RegBankSelect::MappingCost::MappingCost(
const BlockFrequency &LocalFreq)
941 bool RegBankSelect::MappingCost::addLocalCost(uint64_t Cost) {
943 if (LocalCost + Cost < LocalCost) {
948 return isSaturated();
951 bool RegBankSelect::MappingCost::addNonLocalCost(uint64_t Cost) {
953 if (NonLocalCost + Cost < NonLocalCost) {
957 NonLocalCost += Cost;
958 return isSaturated();
961 bool RegBankSelect::MappingCost::isSaturated()
const {
966 void RegBankSelect::MappingCost::saturate() {
967 *
this = ImpossibleCost();
971 RegBankSelect::MappingCost RegBankSelect::MappingCost::ImpossibleCost() {
981 if ((*
this == ImpossibleCost()) || (Cost == ImpossibleCost()))
982 return (*
this == ImpossibleCost()) < (Cost == ImpossibleCost());
985 if (isSaturated() || Cost.isSaturated())
986 return isSaturated() < Cost.isSaturated();
993 uint64_t ThisLocalAdjust;
994 uint64_t OtherLocalAdjust;
999 if (NonLocalCost == Cost.NonLocalCost)
1002 return LocalCost < Cost.LocalCost;
1006 ThisLocalAdjust = 0;
1007 OtherLocalAdjust = 0;
1008 if (LocalCost < Cost.LocalCost)
1009 OtherLocalAdjust = Cost.LocalCost - LocalCost;
1011 ThisLocalAdjust = LocalCost - Cost.LocalCost;
1013 ThisLocalAdjust = LocalCost;
1014 OtherLocalAdjust = Cost.LocalCost;
1018 uint64_t ThisNonLocalAdjust = 0;
1019 uint64_t OtherNonLocalAdjust = 0;
1020 if (NonLocalCost < Cost.NonLocalCost)
1021 OtherNonLocalAdjust = Cost.NonLocalCost - NonLocalCost;
1023 ThisNonLocalAdjust = NonLocalCost - Cost.NonLocalCost;
1025 uint64_t ThisScaledCost = ThisLocalAdjust * LocalFreq;
1027 bool ThisOverflows = ThisLocalAdjust && (ThisScaledCost < ThisLocalAdjust ||
1028 ThisScaledCost < LocalFreq);
1029 uint64_t OtherScaledCost = OtherLocalAdjust * Cost.LocalFreq;
1031 bool OtherOverflows =
1033 (OtherScaledCost < OtherLocalAdjust || OtherScaledCost < Cost.LocalFreq);
1035 ThisOverflows |= ThisNonLocalAdjust &&
1036 ThisScaledCost + ThisNonLocalAdjust < ThisNonLocalAdjust;
1037 ThisScaledCost += ThisNonLocalAdjust;
1038 OtherOverflows |= OtherNonLocalAdjust &&
1039 OtherScaledCost + OtherNonLocalAdjust < OtherNonLocalAdjust;
1040 OtherScaledCost += OtherNonLocalAdjust;
1043 if (ThisOverflows && OtherOverflows)
1046 if (ThisOverflows || OtherOverflows)
1047 return ThisOverflows < OtherOverflows;
1049 return ThisScaledCost < OtherScaledCost;
1053 return LocalCost == Cost.LocalCost && NonLocalCost == Cost.NonLocalCost &&
1054 LocalFreq == Cost.LocalFreq;
1057 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1065 if (*
this == ImpossibleCost()) {
1069 if (isSaturated()) {
1073 OS << LocalFreq <<
" * " << LocalCost <<
" + " << NonLocalCost;
Pass interface - Implemented by all 'passes'.
reference emplace_back(ArgTypes &&... Args)
bool canMaterialize() const override
Check whether this insertion point can be materialized.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
typename SuperClass::const_iterator const_iterator
MachineBasicBlock * getMBB() const
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
unsigned getNumInsertPoints() const
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
void getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU)
Modify analysis usage so it preserves passes required for the SelectionDAG fallback.
#define LLVM_LIKELY(EXPR)
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
INITIALIZE_PASS_BEGIN(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false)
const MachineFunctionProperties & getProperties() const
Get the function properties.
Helper class that represents how the value of an instruction may be mapped and what is the related co...
unsigned getCost() const
Get the cost.
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
unsigned getOpIdx() const
Reparing code needs to happen before InsertPoints.
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLT getType(unsigned Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register...
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...
virtual const RegisterBankInfo * getRegBankInfo() const
If the information for the register banks is available, return it.
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
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.
void switchTo(RepairingKind NewKind)
Change the type of this repairing placement to NewKind.
iterator_range< succ_iterator > successors()
const PartialMapping * BreakDown
How the value is broken down between the different register banks.
bool partsAllUniform() const
void setMF(MachineFunction &MF)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Mark this repairing placement as impossible.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Abstract class used to represent an insertion point in a CFG.
virtual unsigned getBreakDownCost(const ValueMapping &ValMapping, const RegisterBank *CurBank=nullptr) const
Get the cost of using ValMapping to decompose a register.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
RepairingKind
Define the kind of action this repairing needs.
This file contains the simple types necessary to represent the attributes associated with functions a...
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineInstrBuilder & addDef(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
Target-Independent Code Generator Pass Configuration Options.
iterator_range< SmallVectorImpl< Register >::const_iterator > getVRegs(unsigned OpIdx, bool ForDebug=false) const
Get all the virtual registers required to map the OpIdx-th operand of the instruction.
MachineInstrBuilder buildInstrNoInsert(unsigned Opcode)
Build but don't insert <empty> = Opcode <empty>.
MachineFunction & getMF()
Getter for the function we currently build.
iterator getLastNonDebugInstr()
Returns an iterator to the last non-debug instruction in the basic block, or end().
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.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
const RegisterBank * RegBank
Register bank where the partial value lives.
uint64_t frequency(const Pass &P) const override
Frequency of the insertion point.
const MachineInstrBuilder & addUse(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register use operand.
bool isPreISelOpcode(QueryType Type=IgnoreBundle) const
Return true if this is an instruction that should go through the usual legalization steps...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
This pass implements the reg bank selector pass used in the GlobalISel pipeline.
Insertion point on an edge.
virtual const InstructionMapping & getInstrMapping(const MachineInstr &MI) const
Get the mapping of the different operands of MI on the register bank.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
bool canMaterialize() const
BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
unsigned Length
Length of this mapping in bits.
Represent the analysis usage information of a pass.
bool isTargetSpecificOpcode(unsigned Opcode)
Check whether the given Opcode is a target-specific opcode.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
cl::opt< bool > DisableGISelLegalityCheck
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool isValid() const
Check whether this object is valid.
bool verify(const MachineInstr &MI) const
Verifiy that this mapping makes sense for MI.
const MachineInstr * machineFunctionIsIllegal(const MachineFunction &MF)
Checks that MIR is fully legal, returns an illegal instruction if it's not, nullptr otherwise...
bool readsRegister(Register Reg, const TargetRegisterInfo *TRI=nullptr) const
Return true if the MachineInstr reads the specified register.
RepairingKind getKind() const
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
bool isGlobalISelAbortEnabled() const
Check whether or not GlobalISel should abort on error.
Align max(MaybeAlign Lhs, Align Rhs)
Struct used to represent the placement of a repairing point for a given operand.
MachineInstr * CloneMachineInstr(const MachineInstr *Orig)
Create a new MachineInstr which is a copy of Orig, identical in all ways except the instruction has n...
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.
const Function & getFunction() const
Return the LLVM function that this machine code represents.
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.
virtual bool canMaterialize() const
Check whether this insertion point can be materialized.
bool isUnconditionalBranch(QueryType Type=AnyInBundle) const
Return true if this is a branch which always transfers control flow to some other block...
void createVRegs(unsigned OpIdx)
Create as many new virtual registers as needed for the mapping of the OpIdx-th operand.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
const MachineBasicBlock * getParent() const
bool operator==(const StringView &LHS, const StringView &RHS)
BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
Representation of each machine instruction.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
Insertion point before or after an instruction.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
LLVM_NODISCARD bool empty() const
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.
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.
bool WasMaterialized
Tell if the insert point has already been materialized.
virtual void print(raw_ostream &OS, const Module *M) const
print - Print out the internal state of the pass.
void addInsertPoint(MachineBasicBlock &MBB, bool Beginning)
iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
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)")))
bool runOnMachineFunction(MachineFunction &MF) override
Walk through MF and assign a register bank to every virtual register that are still mapped to nothing...
bool isReg() const
isReg - Tests if this is a MO_Register operand.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool hasProperty(Property P) const
MachineBasicBlock * SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P)
Split the critical edge from this block to the given successor block, and return the newly created bl...
unsigned NumBreakDowns
Number of partial mapping to break down this value.
Fast - This calling convention attempts to make calls as fast as possible (e.g.
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
(Re)assign the register bank of the operand.
virtual bool isSplit() const
Does this point involve splitting an edge or block? As soon as ::getPoint is called and thus...
This class implements an extremely fast bulk output stream that can only output to a stream...
bool operator<(const DeltaInfo &LHS, int64_t Delta)
Register getReg() const
getReg - Returns the register number.
uint64_t frequency(const Pass &P) const override
Frequency of the insertion point.
unsigned getNumOperands() const
Get the number of operands.
const MachineOperand & getOperand(unsigned i) 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.
Wrapper class representing virtual and physical registers.
bool isSplit() const override
Does this point involve splitting an edge or block? As soon as ::getPoint is called and thus...