LegalizerInfo.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. //===- lib/CodeGen/GlobalISel/LegalizerInfo.cpp - Legalizer ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Implement an interface to specify and query how an illegal operation on a
  10. // given type should be expanded.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
  14. #include "llvm/ADT/SmallBitVector.h"
  15. #include "llvm/CodeGen/MachineInstr.h"
  16. #include "llvm/CodeGen/MachineOperand.h"
  17. #include "llvm/CodeGen/MachineRegisterInfo.h"
  18. #include "llvm/CodeGen/TargetOpcodes.h"
  19. #include "llvm/MC/MCInstrDesc.h"
  20. #include "llvm/MC/MCInstrInfo.h"
  21. #include "llvm/Support/Debug.h"
  22. #include "llvm/Support/ErrorHandling.h"
  23. #include "llvm/Support/LowLevelTypeImpl.h"
  24. #include <algorithm>
  25. using namespace llvm;
  26. using namespace LegalizeActions;
  27. #define DEBUG_TYPE "legalizer-info"
  28. cl::opt<bool> llvm::DisableGISelLegalityCheck(
  29. "disable-gisel-legality-check",
  30. cl::desc("Don't verify that MIR is fully legal between GlobalISel passes"),
  31. cl::Hidden);
  32. raw_ostream &llvm::operator<<(raw_ostream &OS, LegalizeAction Action) {
  33. switch (Action) {
  34. case Legal:
  35. OS << "Legal";
  36. break;
  37. case NarrowScalar:
  38. OS << "NarrowScalar";
  39. break;
  40. case WidenScalar:
  41. OS << "WidenScalar";
  42. break;
  43. case FewerElements:
  44. OS << "FewerElements";
  45. break;
  46. case MoreElements:
  47. OS << "MoreElements";
  48. break;
  49. case Bitcast:
  50. OS << "Bitcast";
  51. break;
  52. case Lower:
  53. OS << "Lower";
  54. break;
  55. case Libcall:
  56. OS << "Libcall";
  57. break;
  58. case Custom:
  59. OS << "Custom";
  60. break;
  61. case Unsupported:
  62. OS << "Unsupported";
  63. break;
  64. case NotFound:
  65. OS << "NotFound";
  66. break;
  67. case UseLegacyRules:
  68. OS << "UseLegacyRules";
  69. break;
  70. }
  71. return OS;
  72. }
  73. raw_ostream &LegalityQuery::print(raw_ostream &OS) const {
  74. OS << Opcode << ", Tys={";
  75. for (const auto &Type : Types) {
  76. OS << Type << ", ";
  77. }
  78. OS << "}, Opcode=";
  79. OS << Opcode << ", MMOs={";
  80. for (const auto &MMODescr : MMODescrs) {
  81. OS << MMODescr.MemoryTy << ", ";
  82. }
  83. OS << "}";
  84. return OS;
  85. }
  86. #ifndef NDEBUG
  87. // Make sure the rule won't (trivially) loop forever.
  88. static bool hasNoSimpleLoops(const LegalizeRule &Rule, const LegalityQuery &Q,
  89. const std::pair<unsigned, LLT> &Mutation) {
  90. switch (Rule.getAction()) {
  91. case Legal:
  92. case Custom:
  93. case Lower:
  94. case MoreElements:
  95. case FewerElements:
  96. break;
  97. default:
  98. return Q.Types[Mutation.first] != Mutation.second;
  99. }
  100. return true;
  101. }
  102. // Make sure the returned mutation makes sense for the match type.
  103. static bool mutationIsSane(const LegalizeRule &Rule,
  104. const LegalityQuery &Q,
  105. std::pair<unsigned, LLT> Mutation) {
  106. // If the user wants a custom mutation, then we can't really say much about
  107. // it. Return true, and trust that they're doing the right thing.
  108. if (Rule.getAction() == Custom || Rule.getAction() == Legal)
  109. return true;
  110. const unsigned TypeIdx = Mutation.first;
  111. const LLT OldTy = Q.Types[TypeIdx];
  112. const LLT NewTy = Mutation.second;
  113. switch (Rule.getAction()) {
  114. case FewerElements:
  115. if (!OldTy.isVector())
  116. return false;
  117. [[fallthrough]];
  118. case MoreElements: {
  119. // MoreElements can go from scalar to vector.
  120. const ElementCount OldElts = OldTy.isVector() ?
  121. OldTy.getElementCount() : ElementCount::getFixed(1);
  122. if (NewTy.isVector()) {
  123. if (Rule.getAction() == FewerElements) {
  124. // Make sure the element count really decreased.
  125. if (ElementCount::isKnownGE(NewTy.getElementCount(), OldElts))
  126. return false;
  127. } else {
  128. // Make sure the element count really increased.
  129. if (ElementCount::isKnownLE(NewTy.getElementCount(), OldElts))
  130. return false;
  131. }
  132. } else if (Rule.getAction() == MoreElements)
  133. return false;
  134. // Make sure the element type didn't change.
  135. return NewTy.getScalarType() == OldTy.getScalarType();
  136. }
  137. case NarrowScalar:
  138. case WidenScalar: {
  139. if (OldTy.isVector()) {
  140. // Number of elements should not change.
  141. if (!NewTy.isVector() || OldTy.getNumElements() != NewTy.getNumElements())
  142. return false;
  143. } else {
  144. // Both types must be vectors
  145. if (NewTy.isVector())
  146. return false;
  147. }
  148. if (Rule.getAction() == NarrowScalar) {
  149. // Make sure the size really decreased.
  150. if (NewTy.getScalarSizeInBits() >= OldTy.getScalarSizeInBits())
  151. return false;
  152. } else {
  153. // Make sure the size really increased.
  154. if (NewTy.getScalarSizeInBits() <= OldTy.getScalarSizeInBits())
  155. return false;
  156. }
  157. return true;
  158. }
  159. case Bitcast: {
  160. return OldTy != NewTy && OldTy.getSizeInBits() == NewTy.getSizeInBits();
  161. }
  162. default:
  163. return true;
  164. }
  165. }
  166. #endif
  167. LegalizeActionStep LegalizeRuleSet::apply(const LegalityQuery &Query) const {
  168. LLVM_DEBUG(dbgs() << "Applying legalizer ruleset to: "; Query.print(dbgs());
  169. dbgs() << "\n");
  170. if (Rules.empty()) {
  171. LLVM_DEBUG(dbgs() << ".. fallback to legacy rules (no rules defined)\n");
  172. return {LegalizeAction::UseLegacyRules, 0, LLT{}};
  173. }
  174. for (const LegalizeRule &Rule : Rules) {
  175. if (Rule.match(Query)) {
  176. LLVM_DEBUG(dbgs() << ".. match\n");
  177. std::pair<unsigned, LLT> Mutation = Rule.determineMutation(Query);
  178. LLVM_DEBUG(dbgs() << ".. .. " << Rule.getAction() << ", "
  179. << Mutation.first << ", " << Mutation.second << "\n");
  180. assert(mutationIsSane(Rule, Query, Mutation) &&
  181. "legality mutation invalid for match");
  182. assert(hasNoSimpleLoops(Rule, Query, Mutation) && "Simple loop detected");
  183. return {Rule.getAction(), Mutation.first, Mutation.second};
  184. } else
  185. LLVM_DEBUG(dbgs() << ".. no match\n");
  186. }
  187. LLVM_DEBUG(dbgs() << ".. unsupported\n");
  188. return {LegalizeAction::Unsupported, 0, LLT{}};
  189. }
  190. bool LegalizeRuleSet::verifyTypeIdxsCoverage(unsigned NumTypeIdxs) const {
  191. #ifndef NDEBUG
  192. if (Rules.empty()) {
  193. LLVM_DEBUG(
  194. dbgs() << ".. type index coverage check SKIPPED: no rules defined\n");
  195. return true;
  196. }
  197. const int64_t FirstUncovered = TypeIdxsCovered.find_first_unset();
  198. if (FirstUncovered < 0) {
  199. LLVM_DEBUG(dbgs() << ".. type index coverage check SKIPPED:"
  200. " user-defined predicate detected\n");
  201. return true;
  202. }
  203. const bool AllCovered = (FirstUncovered >= NumTypeIdxs);
  204. if (NumTypeIdxs > 0)
  205. LLVM_DEBUG(dbgs() << ".. the first uncovered type index: " << FirstUncovered
  206. << ", " << (AllCovered ? "OK" : "FAIL") << "\n");
  207. return AllCovered;
  208. #else
  209. return true;
  210. #endif
  211. }
  212. bool LegalizeRuleSet::verifyImmIdxsCoverage(unsigned NumImmIdxs) const {
  213. #ifndef NDEBUG
  214. if (Rules.empty()) {
  215. LLVM_DEBUG(
  216. dbgs() << ".. imm index coverage check SKIPPED: no rules defined\n");
  217. return true;
  218. }
  219. const int64_t FirstUncovered = ImmIdxsCovered.find_first_unset();
  220. if (FirstUncovered < 0) {
  221. LLVM_DEBUG(dbgs() << ".. imm index coverage check SKIPPED:"
  222. " user-defined predicate detected\n");
  223. return true;
  224. }
  225. const bool AllCovered = (FirstUncovered >= NumImmIdxs);
  226. LLVM_DEBUG(dbgs() << ".. the first uncovered imm index: " << FirstUncovered
  227. << ", " << (AllCovered ? "OK" : "FAIL") << "\n");
  228. return AllCovered;
  229. #else
  230. return true;
  231. #endif
  232. }
  233. /// Helper function to get LLT for the given type index.
  234. static LLT getTypeFromTypeIdx(const MachineInstr &MI,
  235. const MachineRegisterInfo &MRI, unsigned OpIdx,
  236. unsigned TypeIdx) {
  237. assert(TypeIdx < MI.getNumOperands() && "Unexpected TypeIdx");
  238. // G_UNMERGE_VALUES has variable number of operands, but there is only
  239. // one source type and one destination type as all destinations must be the
  240. // same type. So, get the last operand if TypeIdx == 1.
  241. if (MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES && TypeIdx == 1)
  242. return MRI.getType(MI.getOperand(MI.getNumOperands() - 1).getReg());
  243. return MRI.getType(MI.getOperand(OpIdx).getReg());
  244. }
  245. unsigned LegalizerInfo::getOpcodeIdxForOpcode(unsigned Opcode) const {
  246. assert(Opcode >= FirstOp && Opcode <= LastOp && "Unsupported opcode");
  247. return Opcode - FirstOp;
  248. }
  249. unsigned LegalizerInfo::getActionDefinitionsIdx(unsigned Opcode) const {
  250. unsigned OpcodeIdx = getOpcodeIdxForOpcode(Opcode);
  251. if (unsigned Alias = RulesForOpcode[OpcodeIdx].getAlias()) {
  252. LLVM_DEBUG(dbgs() << ".. opcode " << Opcode << " is aliased to " << Alias
  253. << "\n");
  254. OpcodeIdx = getOpcodeIdxForOpcode(Alias);
  255. assert(RulesForOpcode[OpcodeIdx].getAlias() == 0 && "Cannot chain aliases");
  256. }
  257. return OpcodeIdx;
  258. }
  259. const LegalizeRuleSet &
  260. LegalizerInfo::getActionDefinitions(unsigned Opcode) const {
  261. unsigned OpcodeIdx = getActionDefinitionsIdx(Opcode);
  262. return RulesForOpcode[OpcodeIdx];
  263. }
  264. LegalizeRuleSet &LegalizerInfo::getActionDefinitionsBuilder(unsigned Opcode) {
  265. unsigned OpcodeIdx = getActionDefinitionsIdx(Opcode);
  266. auto &Result = RulesForOpcode[OpcodeIdx];
  267. assert(!Result.isAliasedByAnother() && "Modifying this opcode will modify aliases");
  268. return Result;
  269. }
  270. LegalizeRuleSet &LegalizerInfo::getActionDefinitionsBuilder(
  271. std::initializer_list<unsigned> Opcodes) {
  272. unsigned Representative = *Opcodes.begin();
  273. assert(Opcodes.size() >= 2 &&
  274. "Initializer list must have at least two opcodes");
  275. for (unsigned Op : llvm::drop_begin(Opcodes))
  276. aliasActionDefinitions(Representative, Op);
  277. auto &Return = getActionDefinitionsBuilder(Representative);
  278. Return.setIsAliasedByAnother();
  279. return Return;
  280. }
  281. void LegalizerInfo::aliasActionDefinitions(unsigned OpcodeTo,
  282. unsigned OpcodeFrom) {
  283. assert(OpcodeTo != OpcodeFrom && "Cannot alias to self");
  284. assert(OpcodeTo >= FirstOp && OpcodeTo <= LastOp && "Unsupported opcode");
  285. const unsigned OpcodeFromIdx = getOpcodeIdxForOpcode(OpcodeFrom);
  286. RulesForOpcode[OpcodeFromIdx].aliasTo(OpcodeTo);
  287. }
  288. LegalizeActionStep
  289. LegalizerInfo::getAction(const LegalityQuery &Query) const {
  290. LegalizeActionStep Step = getActionDefinitions(Query.Opcode).apply(Query);
  291. if (Step.Action != LegalizeAction::UseLegacyRules) {
  292. return Step;
  293. }
  294. return getLegacyLegalizerInfo().getAction(Query);
  295. }
  296. LegalizeActionStep
  297. LegalizerInfo::getAction(const MachineInstr &MI,
  298. const MachineRegisterInfo &MRI) const {
  299. SmallVector<LLT, 8> Types;
  300. SmallBitVector SeenTypes(8);
  301. ArrayRef<MCOperandInfo> OpInfo = MI.getDesc().operands();
  302. // FIXME: probably we'll need to cache the results here somehow?
  303. for (unsigned i = 0; i < MI.getDesc().getNumOperands(); ++i) {
  304. if (!OpInfo[i].isGenericType())
  305. continue;
  306. // We must only record actions once for each TypeIdx; otherwise we'd
  307. // try to legalize operands multiple times down the line.
  308. unsigned TypeIdx = OpInfo[i].getGenericTypeIndex();
  309. if (SeenTypes[TypeIdx])
  310. continue;
  311. SeenTypes.set(TypeIdx);
  312. LLT Ty = getTypeFromTypeIdx(MI, MRI, i, TypeIdx);
  313. Types.push_back(Ty);
  314. }
  315. SmallVector<LegalityQuery::MemDesc, 2> MemDescrs;
  316. for (const auto &MMO : MI.memoperands())
  317. MemDescrs.push_back({*MMO});
  318. return getAction({MI.getOpcode(), Types, MemDescrs});
  319. }
  320. bool LegalizerInfo::isLegal(const MachineInstr &MI,
  321. const MachineRegisterInfo &MRI) const {
  322. return getAction(MI, MRI).Action == Legal;
  323. }
  324. bool LegalizerInfo::isLegalOrCustom(const MachineInstr &MI,
  325. const MachineRegisterInfo &MRI) const {
  326. auto Action = getAction(MI, MRI).Action;
  327. // If the action is custom, it may not necessarily modify the instruction,
  328. // so we have to assume it's legal.
  329. return Action == Legal || Action == Custom;
  330. }
  331. unsigned LegalizerInfo::getExtOpcodeForWideningConstant(LLT SmallTy) const {
  332. return SmallTy.isByteSized() ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
  333. }
  334. /// \pre Type indices of every opcode form a dense set starting from 0.
  335. void LegalizerInfo::verify(const MCInstrInfo &MII) const {
  336. #ifndef NDEBUG
  337. std::vector<unsigned> FailedOpcodes;
  338. for (unsigned Opcode = FirstOp; Opcode <= LastOp; ++Opcode) {
  339. const MCInstrDesc &MCID = MII.get(Opcode);
  340. const unsigned NumTypeIdxs = std::accumulate(
  341. MCID.operands().begin(), MCID.operands().end(), 0U,
  342. [](unsigned Acc, const MCOperandInfo &OpInfo) {
  343. return OpInfo.isGenericType()
  344. ? std::max(OpInfo.getGenericTypeIndex() + 1U, Acc)
  345. : Acc;
  346. });
  347. const unsigned NumImmIdxs = std::accumulate(
  348. MCID.operands().begin(), MCID.operands().end(), 0U,
  349. [](unsigned Acc, const MCOperandInfo &OpInfo) {
  350. return OpInfo.isGenericImm()
  351. ? std::max(OpInfo.getGenericImmIndex() + 1U, Acc)
  352. : Acc;
  353. });
  354. LLVM_DEBUG(dbgs() << MII.getName(Opcode) << " (opcode " << Opcode
  355. << "): " << NumTypeIdxs << " type ind"
  356. << (NumTypeIdxs == 1 ? "ex" : "ices") << ", "
  357. << NumImmIdxs << " imm ind"
  358. << (NumImmIdxs == 1 ? "ex" : "ices") << "\n");
  359. const LegalizeRuleSet &RuleSet = getActionDefinitions(Opcode);
  360. if (!RuleSet.verifyTypeIdxsCoverage(NumTypeIdxs))
  361. FailedOpcodes.push_back(Opcode);
  362. else if (!RuleSet.verifyImmIdxsCoverage(NumImmIdxs))
  363. FailedOpcodes.push_back(Opcode);
  364. }
  365. if (!FailedOpcodes.empty()) {
  366. errs() << "The following opcodes have ill-defined legalization rules:";
  367. for (unsigned Opcode : FailedOpcodes)
  368. errs() << " " << MII.getName(Opcode);
  369. errs() << "\n";
  370. report_fatal_error("ill-defined LegalizerInfo"
  371. ", try -debug-only=legalizer-info for details");
  372. }
  373. #endif
  374. }
  375. #ifndef NDEBUG
  376. // FIXME: This should be in the MachineVerifier, but it can't use the
  377. // LegalizerInfo as it's currently in the separate GlobalISel library.
  378. // Note that RegBankSelected property already checked in the verifier
  379. // has the same layering problem, but we only use inline methods so
  380. // end up not needing to link against the GlobalISel library.
  381. const MachineInstr *llvm::machineFunctionIsIllegal(const MachineFunction &MF) {
  382. if (const LegalizerInfo *MLI = MF.getSubtarget().getLegalizerInfo()) {
  383. const MachineRegisterInfo &MRI = MF.getRegInfo();
  384. for (const MachineBasicBlock &MBB : MF)
  385. for (const MachineInstr &MI : MBB)
  386. if (isPreISelGenericOpcode(MI.getOpcode()) &&
  387. !MLI->isLegalOrCustom(MI, MRI))
  388. return &MI;
  389. }
  390. return nullptr;
  391. }
  392. #endif