38 #define DEBUG_TYPE "legalizer-info" 41 "disable-gisel-legality-check",
42 cl::desc(
"Don't verify that MIR is fully legal between GlobalISel passes"),
57 OS <<
"FewerElements";
78 OS <<
"UseLegacyRules";
85 OS << Opcode <<
", Tys={";
86 for (
const auto &
Type : Types) {
91 OS << Opcode <<
", MMOs={";
92 for (
const auto &MMODescr : MMODescrs) {
93 OS << MMODescr.SizeInBits <<
", ";
103 const std::pair<unsigned, LLT> &
Mutation) {
111 return Q.
Types[Mutation.first] != Mutation.second;
119 std::pair<unsigned, LLT>
Mutation) {
125 const unsigned TypeIdx = Mutation.first;
127 const LLT NewTy = Mutation.second;
186 LLVM_DEBUG(
dbgs() <<
".. fallback to legacy rules (no rules defined)\n");
190 if (Rule.match(Query)) {
192 std::pair<unsigned, LLT>
Mutation = Rule.determineMutation(Query);
194 << Mutation.first <<
", " << Mutation.second <<
"\n");
196 "legality mutation invalid for match");
198 return {Rule.getAction(), Mutation.first, Mutation.second};
210 dbgs() <<
".. type index coverage check SKIPPED: no rules defined\n");
213 const int64_t FirstUncovered = TypeIdxsCovered.find_first_unset();
214 if (FirstUncovered < 0) {
216 " user-defined predicate detected\n");
219 const bool AllCovered = (FirstUncovered >= NumTypeIdxs);
221 LLVM_DEBUG(
dbgs() <<
".. the first uncovered type index: " << FirstUncovered
222 <<
", " << (AllCovered ?
"OK" :
"FAIL") <<
"\n");
233 dbgs() <<
".. imm index coverage check SKIPPED: no rules defined\n");
236 const int64_t FirstUncovered = ImmIdxsCovered.find_first_unset();
237 if (FirstUncovered < 0) {
239 " user-defined predicate detected\n");
242 const bool AllCovered = (FirstUncovered >= NumImmIdxs);
243 LLVM_DEBUG(
dbgs() <<
".. the first uncovered imm index: " << FirstUncovered
244 <<
", " << (AllCovered ?
"OK" :
"FAIL") <<
"\n");
255 setScalarAction(TargetOpcode::G_ANYEXT, 1, {{1,
Legal}});
256 setScalarAction(TargetOpcode::G_ZEXT, 1, {{1,
Legal}});
257 setScalarAction(TargetOpcode::G_SEXT, 1, {{1,
Legal}});
258 setScalarAction(TargetOpcode::G_TRUNC, 0, {{1,
Legal}});
259 setScalarAction(TargetOpcode::G_TRUNC, 1, {{1,
Legal}});
261 setScalarAction(TargetOpcode::G_INTRINSIC, 0, {{1,
Legal}});
262 setScalarAction(TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS, 0, {{1,
Legal}});
283 setScalarAction(TargetOpcode::G_FNEG, 0, {{1,
Lower}});
287 assert(TablesInitialized ==
false);
289 for (
unsigned OpcodeIdx = 0; OpcodeIdx <= LastOp - FirstOp; ++OpcodeIdx) {
290 const unsigned Opcode = FirstOp + OpcodeIdx;
291 for (
unsigned TypeIdx = 0; TypeIdx != SpecifiedActions[OpcodeIdx].size();
298 std::map<uint16_t, SizeAndActionsVec> AddressSpace2SpecifiedActions;
300 std::map<uint16_t, SizeAndActionsVec> ElemSize2SpecifiedActions;
301 for (
auto LLT2Action : SpecifiedActions[OpcodeIdx][TypeIdx]) {
302 const LLT Type = LLT2Action.first;
305 auto SizeAction = std::make_pair(Type.
getSizeInBits(), Action);
311 .push_back(SizeAction);
313 ScalarSpecifiedActions.push_back(SizeAction);
321 if (TypeIdx < ScalarSizeChangeStrategies[OpcodeIdx].
size() &&
322 ScalarSizeChangeStrategies[OpcodeIdx][TypeIdx] !=
nullptr)
323 S = ScalarSizeChangeStrategies[OpcodeIdx][TypeIdx];
325 checkPartialSizeAndActionsVector(ScalarSpecifiedActions);
326 setScalarAction(Opcode, TypeIdx, S(ScalarSpecifiedActions));
330 for (
auto PointerSpecifiedActions : AddressSpace2SpecifiedActions) {
332 checkPartialSizeAndActionsVector(PointerSpecifiedActions.second);
336 Opcode, TypeIdx, PointerSpecifiedActions.first,
342 for (
auto VectorSpecifiedActions : ElemSize2SpecifiedActions) {
344 const uint16_t ElementSize = VectorSpecifiedActions.first;
345 ElementSizesSeen.push_back({ElementSize,
Legal});
346 checkPartialSizeAndActionsVector(VectorSpecifiedActions.second);
352 for (
SizeAndAction BitsizeAndAction : VectorSpecifiedActions.second) {
353 assert(BitsizeAndAction.first % ElementSize == 0);
354 const uint16_t NumElements = BitsizeAndAction.first / ElementSize;
355 NumElementsActions.push_back({NumElements, BitsizeAndAction.second});
357 setVectorNumElementAction(
358 Opcode, TypeIdx, ElementSize,
364 if (TypeIdx < VectorElementSizeChangeStrategies[OpcodeIdx].
size() &&
365 VectorElementSizeChangeStrategies[OpcodeIdx][TypeIdx] !=
nullptr)
366 VectorElementSizeChangeStrategy =
367 VectorElementSizeChangeStrategies[OpcodeIdx][TypeIdx];
368 setScalarInVectorAction(
369 Opcode, TypeIdx, VectorElementSizeChangeStrategy(ElementSizesSeen));
373 TablesInitialized =
true;
380 std::pair<LegalizeAction, LLT>
381 LegalizerInfo::getAspectAction(
const InstrAspect &Aspect)
const {
382 assert(TablesInitialized &&
"backend forgot to call computeTables");
386 return findScalarLegalAction(Aspect);
388 return findVectorLegalAction(Aspect);
399 if (MI.
getOpcode() == TargetOpcode::G_UNMERGE_VALUES && TypeIdx == 1)
405 assert(Opcode >= FirstOp && Opcode <= LastOp &&
"Unsupported opcode");
406 return Opcode - FirstOp;
411 if (
unsigned Alias = RulesForOpcode[OpcodeIdx].getAlias()) {
412 LLVM_DEBUG(
dbgs() <<
".. opcode " << Opcode <<
" is aliased to " << Alias
415 assert(RulesForOpcode[OpcodeIdx].getAlias() == 0 &&
"Cannot chain aliases");
424 return RulesForOpcode[OpcodeIdx];
429 auto &Result = RulesForOpcode[OpcodeIdx];
430 assert(!Result.isAliasedByAnother() &&
"Modifying this opcode will modify aliases");
435 std::initializer_list<unsigned> Opcodes) {
436 unsigned Representative = *Opcodes.begin();
439 "Initializer list must have at least two opcodes");
441 for (
auto I = Opcodes.begin() + 1,
E = Opcodes.end();
I !=
E; ++
I)
445 Return.setIsAliasedByAnother();
450 unsigned OpcodeFrom) {
451 assert(OpcodeTo != OpcodeFrom &&
"Cannot alias to self");
452 assert(OpcodeTo >= FirstOp && OpcodeTo <= LastOp &&
"Unsupported opcode");
454 RulesForOpcode[OpcodeFromIdx].
aliasTo(OpcodeTo);
464 for (
unsigned i = 0; i < Query.
Types.size(); ++i) {
465 auto Action = getAspectAction({Query.
Opcode, i, Query.
Types[i]});
466 if (Action.first !=
Legal) {
468 << Action.first <<
", " << Action.second <<
"\n");
469 return {Action.first, i, Action.second};
485 if (!OpInfo[i].isGenericType())
491 if (SeenTypes[TypeIdx])
494 SeenTypes.
set(TypeIdx);
502 MemDescrs.
push_back({8 * MMO->getSize() ,
503 8 * MMO->getAlignment(),
504 MMO->getOrdering()});
533 unsigned LargestSizeSoFar = 0;
534 if (v.size() >= 1 && v[0].first != 1)
535 result.push_back({1, IncreaseAction});
536 for (
size_t i = 0; i < v.size(); ++i) {
537 result.push_back(v[i]);
538 LargestSizeSoFar = v[i].first;
539 if (i + 1 < v.size() && v[i + 1].first != v[i].first + 1) {
540 result.push_back({LargestSizeSoFar + 1, IncreaseAction});
541 LargestSizeSoFar = v[i].first + 1;
544 result.push_back({LargestSizeSoFar + 1, DecreaseAction});
553 if (v.size() == 0 || v[0].first != 1)
554 result.push_back({1, IncreaseAction});
555 for (
size_t i = 0; i < v.size(); ++i) {
556 result.push_back(v[i]);
557 if (i + 1 == v.size() || v[i + 1].first != v[i].first + 1) {
558 result.push_back({v[i].first + 1, DecreaseAction});
572 assert(It != Vec.begin() &&
"Does Vec not start with size 1?");
573 int VecIdx = It - Vec.begin() - 1;
581 return {
Size, Action};
596 for (
int i = VecIdx - 1; i >= 0; --i)
599 return {Vec[i].first, Action};
605 for (std::size_t i = VecIdx + 1; i < Vec.size(); ++i)
608 return {Vec[i].first, Action};
620 std::pair<LegalizeAction, LLT>
621 LegalizerInfo::findScalarLegalAction(
const InstrAspect &Aspect)
const {
628 AddrSpace2PointerActions[OpcodeIdx].
end()) {
633 ? AddrSpace2PointerActions[OpcodeIdx]
636 : ScalarActions[OpcodeIdx];
637 if (Aspect.
Idx >= Actions.
size())
649 std::pair<LegalizeAction, LLT>
650 LegalizerInfo::findVectorLegalAction(
const InstrAspect &Aspect)
const {
657 const unsigned TypeIdx = Aspect.
Idx;
658 if (TypeIdx >= ScalarInVectorActions[OpcodeIdx].
size())
661 ScalarInVectorActions[OpcodeIdx][TypeIdx];
663 LLT IntermediateType;
664 auto ElementSizeAndAction =
668 if (ElementSizeAndAction.second !=
Legal)
669 return {ElementSizeAndAction.second, IntermediateType};
671 auto i = NumElements2Actions[OpcodeIdx].find(
672 IntermediateType.getScalarSizeInBits());
673 if (i == NumElements2Actions[OpcodeIdx].
end()) {
674 return {
NotFound, IntermediateType};
677 auto NumElementsAndAction =
678 findAction(NumElementsVec, IntermediateType.getNumElements());
679 return {NumElementsAndAction.second,
681 IntermediateType.getScalarSizeInBits())};
691 return SmallTy.
isByteSized() ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
697 std::vector<unsigned> FailedOpcodes;
698 for (
unsigned Opcode = FirstOp; Opcode <= LastOp; ++Opcode) {
700 const unsigned NumTypeIdxs = std::accumulate(
704 ?
std::max(OpInfo.getGenericTypeIndex() + 1U, Acc)
707 const unsigned NumImmIdxs = std::accumulate(
711 ?
std::max(OpInfo.getGenericImmIndex() + 1U, Acc)
715 <<
"): " << NumTypeIdxs <<
" type ind" 716 << (NumTypeIdxs == 1 ?
"ex" :
"ices") <<
", " 717 << NumImmIdxs <<
" imm ind" 718 << (NumImmIdxs == 1 ?
"ex" :
"ices") <<
"\n");
720 if (!RuleSet.verifyTypeIdxsCoverage(NumTypeIdxs))
721 FailedOpcodes.push_back(Opcode);
722 else if (!RuleSet.verifyImmIdxsCoverage(NumImmIdxs))
723 FailedOpcodes.push_back(Opcode);
725 if (!FailedOpcodes.empty()) {
726 errs() <<
"The following opcodes have ill-defined legalization rules:";
727 for (
unsigned Opcode : FailedOpcodes)
732 ", try -debug-only=legalizer-info for details");
749 !MLI->isLegalOrCustom(
MI, MRI))
bool isLegalOrCustom(const MachineInstr &MI, const MachineRegisterInfo &MRI) const
const_iterator end(StringRef path)
Get end iterator over path.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
static LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
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.
virtual unsigned getExtOpcodeForWideningConstant(LLT SmallTy) const
Return the opcode (SEXT/ZEXT/ANYEXT) that should be performed while widening a constant of type Small...
static SizeAndActionsVec increaseToLargerTypesAndDecreaseToLargest(const SizeAndActionsVec &v, LegalizeAction IncreaseAction, LegalizeAction DecreaseAction)
Helper function to implement many typical SizeChangeStrategy functions.
unsigned getScalarSizeInBits() const
The operation should be implemented in terms of a wider scalar base-type.
raw_ostream & print(raw_ostream &OS) const
std::function< SizeAndActionsVec(const SizeAndActionsVec &v)> SizeChangeStrategy
void push_back(const T &Elt)
The LegalityQuery object bundles together all the information that's needed to decide whether a given...
Describe properties that are true of each instruction in the target description file.
static LLT getTypeFromTypeIdx(const MachineInstr &MI, const MachineRegisterInfo &MRI, unsigned OpIdx, unsigned TypeIdx)
Helper function to get LLT for the given type index.
std::vector< SizeAndAction > SizeAndActionsVec
The (vector) operation should be implemented by splitting it into sub-vectors where the operation is ...
Libcall
RTLIB::Libcall enum - This enum defines all of the runtime library calls the backend can emit...
static SizeAndActionsVec narrowToSmallerAndUnsupportedIfTooSmall(const SizeAndActionsVec &v)
LLT getScalarType() const
LLT getType(unsigned Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register...
const_opInfo_iterator opInfo_begin() const
const LegalizeRuleSet & getActionDefinitions(unsigned Opcode) const
Get the action definitions for the given opcode.
static SizeAndActionsVec unsupportedForDifferentSizes(const SizeAndActionsVec &v)
A SizeChangeStrategy for the common case where legalization for a particular operation consists of on...
The operation should be synthesized from multiple instructions acting on a narrower scalar base-type...
LegalizeActionStep getAction(const LegalityQuery &Query) const
Determine what action should be taken to legalize the described instruction.
static SizeAndActionsVec widenToLargerTypesUnsupportedOtherwise(const SizeAndActionsVec &v)
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
unsigned getNumOperands() const
Retuns the total number of operands.
LegalizeAction getAction() const
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
This operation is completely unsupported on the target.
LLT getElementType() const
Returns the vector's element type. Only valid for vector types.
void verify(const MCInstrInfo &MII) const
Perform simple self-diagnostic and assert if there is anything obviously wrong with the actions set u...
auto partition_point(R &&Range, Predicate P) -> decltype(adl_begin(Range))
Binary search for the first iterator in a range where a predicate is false.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
The (vector) operation should be implemented by widening the input vector and ignoring the lanes adde...
void computeTables()
Compute any ancillary tables needed to quickly decide how an operation should be handled.
void aliasActionDefinitions(unsigned OpcodeTo, unsigned OpcodeFrom)
static LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
The operation itself must be expressed in terms of simpler actions on this target.
bool isGenericType() const
virtual const LegalizerInfo * getLegalizerInfo() const
Abstract class that contains various methods for clients to notify about changes. ...
static SizeAndActionsVec decreaseToSmallerTypesAndIncreaseToSmallest(const SizeAndActionsVec &v, LegalizeAction DecreaseAction, LegalizeAction IncreaseAction)
Helper function to implement many typical SizeChangeStrategy functions.
unsigned const MachineRegisterInfo * MRI
ArrayRef< MachineMemOperand * > memoperands() const
Access to memory operands of the instruction.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
The instances of the Type class are immutable: once they are created, they are never changed...
Sentinel value for when no action was found in the specified table.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
virtual bool legalizeIntrinsic(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &MIRBuilder) const
Return true if MI is either legal or has been legalized and false if not legal.
Helper class to build MachineInstr.
Interface to description of machine instruction set.
bool isLegal(const LegalityQuery &Query) const
bool verifyTypeIdxsCoverage(unsigned NumTypeIdxs) const
Check if there is no type index which is obviously not handled by the LegalizeRuleSet in any way at a...
unsigned getAddressSpace() const
bool verifyImmIdxsCoverage(unsigned NumImmIdxs) const
Check if there is no imm index which is obviously not handled by the LegalizeRuleSet in any way at al...
Legalization is decided based on an instruction's opcode, which type slot we're considering, and what the existing type is.
StringRef getName(unsigned Opcode) const
Returns the name for the instructions with the given opcode.
cl::opt< bool > DisableGISelLegalityCheck
LegalizeRuleSet & getActionDefinitionsBuilder(unsigned Opcode)
Get the action definition builder for the given opcode.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void sort(IteratorTy Start, IteratorTy End)
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
const MachineInstr * machineFunctionIsIllegal(const MachineFunction &MF)
Checks that MIR is fully legal, returns an illegal instruction if it's not, nullptr otherwise...
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.
static bool mutationIsSane(const LegalizeRule &Rule, const LegalityQuery &Q, std::pair< unsigned, LLT > Mutation)
Align max(MaybeAlign Lhs, Align Rhs)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
The operation should be implemented as a call to some kind of runtime support library.
unsigned getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
The target wants to do something special with this combination of operand and type.
unsigned getOpcodeIdxForOpcode(unsigned Opcode) const
virtual bool legalizeCustom(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &MIRBuilder, GISelChangeObserver &Observer) const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static unsigned getReg(const void *D, unsigned RC, unsigned RegNo)
A single rule in a legalizer info ruleset.
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.
LegalizeAction Action
The action to take or the final answer.
static bool needsLegalizingToDifferentSize(const LegalizeAction Action)
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Fall back onto the old rules.
static SizeAndActionsVec widenToLargerTypesAndNarrowToLargest(const SizeAndActionsVec &v)
A SizeChangeStrategy for the common case where legalization for a particular operation consists of wi...
static SizeAndActionsVec moreToWiderTypesAndLessToWidest(const SizeAndActionsVec &v)
A SizeChangeStrategy for the common case where legalization for a particular vector operation consist...
LegalizeActionStep apply(const LegalityQuery &Query) const
Apply the ruleset to the given LegalityQuery.
const_opInfo_iterator opInfo_end() const
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
void aliasTo(unsigned Opcode)
void setLegalizeScalarToDifferentSizeStrategy(const unsigned Opcode, const unsigned TypeIdx, SizeChangeStrategy S)
The setAction calls record the non-size-changing legalization actions to take on specificly-sized typ...
bool isGenericImm() const
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
static bool hasNoSimpleLoops(const LegalizeRule &Rule, const LegalityQuery &Q, const std::pair< unsigned, LLT > &Mutation)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isPreISelGenericOpcode(unsigned Opcode)
Check whether the given Opcode is a generic opcode that is not supposed to appear after ISel...
uint16_t getNumElements() const
Returns the number of elements in a vector LLT.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
const MCOperandInfo * OpInfo
unsigned getActionDefinitionsIdx(unsigned Opcode) const
This class implements an extremely fast bulk output stream that can only output to a stream...
unsigned getGenericTypeIndex() const
static LLT vector(uint16_t NumElements, unsigned ScalarSizeInBits)
Get a low-level vector of some number of elements and element width.
Register getReg() const
getReg - Returns the register number.
This holds information about one operand of a machine instruction, indicating the register class for ...
const MachineOperand & getOperand(unsigned i) const
The operation is expected to be selectable directly by the target, and no transformation is necessary...
std::pair< uint16_t, LegalizeAction > SizeAndAction