Legalizer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. //===-- llvm/CodeGen/GlobalISel/Legalizer.cpp -----------------------------===//
  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. /// \file This file implements the LegalizerHelper class to legalize individual
  10. /// instructions and the LegalizePass wrapper pass for the primary
  11. /// legalization.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/CodeGen/GlobalISel/Legalizer.h"
  15. #include "llvm/ADT/PostOrderIterator.h"
  16. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  17. #include "llvm/CodeGen/GlobalISel/CSEInfo.h"
  18. #include "llvm/CodeGen/GlobalISel/CSEMIRBuilder.h"
  19. #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
  20. #include "llvm/CodeGen/GlobalISel/GISelWorkList.h"
  21. #include "llvm/CodeGen/GlobalISel/LegalizationArtifactCombiner.h"
  22. #include "llvm/CodeGen/GlobalISel/LegalizerHelper.h"
  23. #include "llvm/CodeGen/GlobalISel/LostDebugLocObserver.h"
  24. #include "llvm/CodeGen/GlobalISel/Utils.h"
  25. #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
  26. #include "llvm/CodeGen/TargetPassConfig.h"
  27. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  28. #include "llvm/InitializePasses.h"
  29. #include "llvm/Support/Debug.h"
  30. #include "llvm/Support/Error.h"
  31. #define DEBUG_TYPE "legalizer"
  32. using namespace llvm;
  33. static cl::opt<bool>
  34. EnableCSEInLegalizer("enable-cse-in-legalizer",
  35. cl::desc("Should enable CSE in Legalizer"),
  36. cl::Optional, cl::init(false));
  37. // This is a temporary hack, should be removed soon.
  38. static cl::opt<bool> AllowGInsertAsArtifact(
  39. "allow-ginsert-as-artifact",
  40. cl::desc("Allow G_INSERT to be considered an artifact. Hack around AMDGPU "
  41. "test infinite loops."),
  42. cl::Optional, cl::init(true));
  43. enum class DebugLocVerifyLevel {
  44. None,
  45. Legalizations,
  46. LegalizationsAndArtifactCombiners,
  47. };
  48. #ifndef NDEBUG
  49. static cl::opt<DebugLocVerifyLevel> VerifyDebugLocs(
  50. "verify-legalizer-debug-locs",
  51. cl::desc("Verify that debug locations are handled"),
  52. cl::values(
  53. clEnumValN(DebugLocVerifyLevel::None, "none", "No verification"),
  54. clEnumValN(DebugLocVerifyLevel::Legalizations, "legalizations",
  55. "Verify legalizations"),
  56. clEnumValN(DebugLocVerifyLevel::LegalizationsAndArtifactCombiners,
  57. "legalizations+artifactcombiners",
  58. "Verify legalizations and artifact combines")),
  59. cl::init(DebugLocVerifyLevel::Legalizations));
  60. #else
  61. // Always disable it for release builds by preventing the observer from being
  62. // installed.
  63. static const DebugLocVerifyLevel VerifyDebugLocs = DebugLocVerifyLevel::None;
  64. #endif
  65. char Legalizer::ID = 0;
  66. INITIALIZE_PASS_BEGIN(Legalizer, DEBUG_TYPE,
  67. "Legalize the Machine IR a function's Machine IR", false,
  68. false)
  69. INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
  70. INITIALIZE_PASS_DEPENDENCY(GISelCSEAnalysisWrapperPass)
  71. INITIALIZE_PASS_END(Legalizer, DEBUG_TYPE,
  72. "Legalize the Machine IR a function's Machine IR", false,
  73. false)
  74. Legalizer::Legalizer() : MachineFunctionPass(ID) { }
  75. void Legalizer::getAnalysisUsage(AnalysisUsage &AU) const {
  76. AU.addRequired<TargetPassConfig>();
  77. AU.addRequired<GISelCSEAnalysisWrapperPass>();
  78. AU.addPreserved<GISelCSEAnalysisWrapperPass>();
  79. getSelectionDAGFallbackAnalysisUsage(AU);
  80. MachineFunctionPass::getAnalysisUsage(AU);
  81. }
  82. void Legalizer::init(MachineFunction &MF) {
  83. }
  84. static bool isArtifact(const MachineInstr &MI) {
  85. switch (MI.getOpcode()) {
  86. default:
  87. return false;
  88. case TargetOpcode::G_TRUNC:
  89. case TargetOpcode::G_ZEXT:
  90. case TargetOpcode::G_ANYEXT:
  91. case TargetOpcode::G_SEXT:
  92. case TargetOpcode::G_MERGE_VALUES:
  93. case TargetOpcode::G_UNMERGE_VALUES:
  94. case TargetOpcode::G_CONCAT_VECTORS:
  95. case TargetOpcode::G_BUILD_VECTOR:
  96. case TargetOpcode::G_EXTRACT:
  97. return true;
  98. case TargetOpcode::G_INSERT:
  99. return AllowGInsertAsArtifact;
  100. }
  101. }
  102. using InstListTy = GISelWorkList<256>;
  103. using ArtifactListTy = GISelWorkList<128>;
  104. namespace {
  105. class LegalizerWorkListManager : public GISelChangeObserver {
  106. InstListTy &InstList;
  107. ArtifactListTy &ArtifactList;
  108. #ifndef NDEBUG
  109. SmallVector<MachineInstr *, 4> NewMIs;
  110. #endif
  111. public:
  112. LegalizerWorkListManager(InstListTy &Insts, ArtifactListTy &Arts)
  113. : InstList(Insts), ArtifactList(Arts) {}
  114. void createdOrChangedInstr(MachineInstr &MI) {
  115. // Only legalize pre-isel generic instructions.
  116. // Legalization process could generate Target specific pseudo
  117. // instructions with generic types. Don't record them
  118. if (isPreISelGenericOpcode(MI.getOpcode())) {
  119. if (isArtifact(MI))
  120. ArtifactList.insert(&MI);
  121. else
  122. InstList.insert(&MI);
  123. }
  124. }
  125. void createdInstr(MachineInstr &MI) override {
  126. LLVM_DEBUG(NewMIs.push_back(&MI));
  127. createdOrChangedInstr(MI);
  128. }
  129. void printNewInstrs() {
  130. LLVM_DEBUG({
  131. for (const auto *MI : NewMIs)
  132. dbgs() << ".. .. New MI: " << *MI;
  133. NewMIs.clear();
  134. });
  135. }
  136. void erasingInstr(MachineInstr &MI) override {
  137. LLVM_DEBUG(dbgs() << ".. .. Erasing: " << MI);
  138. InstList.remove(&MI);
  139. ArtifactList.remove(&MI);
  140. }
  141. void changingInstr(MachineInstr &MI) override {
  142. LLVM_DEBUG(dbgs() << ".. .. Changing MI: " << MI);
  143. }
  144. void changedInstr(MachineInstr &MI) override {
  145. // When insts change, we want to revisit them to legalize them again.
  146. // We'll consider them the same as created.
  147. LLVM_DEBUG(dbgs() << ".. .. Changed MI: " << MI);
  148. createdOrChangedInstr(MI);
  149. }
  150. };
  151. } // namespace
  152. Legalizer::MFResult
  153. Legalizer::legalizeMachineFunction(MachineFunction &MF, const LegalizerInfo &LI,
  154. ArrayRef<GISelChangeObserver *> AuxObservers,
  155. LostDebugLocObserver &LocObserver,
  156. MachineIRBuilder &MIRBuilder) {
  157. MIRBuilder.setMF(MF);
  158. MachineRegisterInfo &MRI = MF.getRegInfo();
  159. // Populate worklists.
  160. InstListTy InstList;
  161. ArtifactListTy ArtifactList;
  162. ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
  163. // Perform legalization bottom up so we can DCE as we legalize.
  164. // Traverse BB in RPOT and within each basic block, add insts top down,
  165. // so when we pop_back_val in the legalization process, we traverse bottom-up.
  166. for (auto *MBB : RPOT) {
  167. if (MBB->empty())
  168. continue;
  169. for (MachineInstr &MI : *MBB) {
  170. // Only legalize pre-isel generic instructions: others don't have types
  171. // and are assumed to be legal.
  172. if (!isPreISelGenericOpcode(MI.getOpcode()))
  173. continue;
  174. if (isArtifact(MI))
  175. ArtifactList.deferred_insert(&MI);
  176. else
  177. InstList.deferred_insert(&MI);
  178. }
  179. }
  180. ArtifactList.finalize();
  181. InstList.finalize();
  182. // This observer keeps the worklists updated.
  183. LegalizerWorkListManager WorkListObserver(InstList, ArtifactList);
  184. // We want both WorkListObserver as well as all the auxiliary observers (e.g.
  185. // CSEInfo) to observe all changes. Use the wrapper observer.
  186. GISelObserverWrapper WrapperObserver(&WorkListObserver);
  187. for (GISelChangeObserver *Observer : AuxObservers)
  188. WrapperObserver.addObserver(Observer);
  189. // Now install the observer as the delegate to MF.
  190. // This will keep all the observers notified about new insertions/deletions.
  191. RAIIMFObsDelInstaller Installer(MF, WrapperObserver);
  192. LegalizerHelper Helper(MF, LI, WrapperObserver, MIRBuilder);
  193. LegalizationArtifactCombiner ArtCombiner(MIRBuilder, MRI, LI);
  194. bool Changed = false;
  195. SmallVector<MachineInstr *, 128> RetryList;
  196. do {
  197. LLVM_DEBUG(dbgs() << "=== New Iteration ===\n");
  198. assert(RetryList.empty() && "Expected no instructions in RetryList");
  199. unsigned NumArtifacts = ArtifactList.size();
  200. while (!InstList.empty()) {
  201. MachineInstr &MI = *InstList.pop_back_val();
  202. assert(isPreISelGenericOpcode(MI.getOpcode()) &&
  203. "Expecting generic opcode");
  204. if (isTriviallyDead(MI, MRI)) {
  205. salvageDebugInfo(MRI, MI);
  206. eraseInstr(MI, MRI, &LocObserver);
  207. continue;
  208. }
  209. // Do the legalization for this instruction.
  210. auto Res = Helper.legalizeInstrStep(MI, LocObserver);
  211. // Error out if we couldn't legalize this instruction. We may want to
  212. // fall back to DAG ISel instead in the future.
  213. if (Res == LegalizerHelper::UnableToLegalize) {
  214. // Move illegal artifacts to RetryList instead of aborting because
  215. // legalizing InstList may generate artifacts that allow
  216. // ArtifactCombiner to combine away them.
  217. if (isArtifact(MI)) {
  218. LLVM_DEBUG(dbgs() << ".. Not legalized, moving to artifacts retry\n");
  219. assert(NumArtifacts == 0 &&
  220. "Artifacts are only expected in instruction list starting the "
  221. "second iteration, but each iteration starting second must "
  222. "start with an empty artifacts list");
  223. (void)NumArtifacts;
  224. RetryList.push_back(&MI);
  225. continue;
  226. }
  227. Helper.MIRBuilder.stopObservingChanges();
  228. return {Changed, &MI};
  229. }
  230. WorkListObserver.printNewInstrs();
  231. LocObserver.checkpoint();
  232. Changed |= Res == LegalizerHelper::Legalized;
  233. }
  234. // Try to combine the instructions in RetryList again if there
  235. // are new artifacts. If not, stop legalizing.
  236. if (!RetryList.empty()) {
  237. if (!ArtifactList.empty()) {
  238. while (!RetryList.empty())
  239. ArtifactList.insert(RetryList.pop_back_val());
  240. } else {
  241. LLVM_DEBUG(dbgs() << "No new artifacts created, not retrying!\n");
  242. Helper.MIRBuilder.stopObservingChanges();
  243. return {Changed, RetryList.front()};
  244. }
  245. }
  246. LocObserver.checkpoint();
  247. while (!ArtifactList.empty()) {
  248. MachineInstr &MI = *ArtifactList.pop_back_val();
  249. assert(isPreISelGenericOpcode(MI.getOpcode()) &&
  250. "Expecting generic opcode");
  251. if (isTriviallyDead(MI, MRI)) {
  252. salvageDebugInfo(MRI, MI);
  253. eraseInstr(MI, MRI, &LocObserver);
  254. continue;
  255. }
  256. SmallVector<MachineInstr *, 4> DeadInstructions;
  257. LLVM_DEBUG(dbgs() << "Trying to combine: " << MI);
  258. if (ArtCombiner.tryCombineInstruction(MI, DeadInstructions,
  259. WrapperObserver)) {
  260. WorkListObserver.printNewInstrs();
  261. eraseInstrs(DeadInstructions, MRI, &LocObserver);
  262. LocObserver.checkpoint(
  263. VerifyDebugLocs ==
  264. DebugLocVerifyLevel::LegalizationsAndArtifactCombiners);
  265. Changed = true;
  266. continue;
  267. }
  268. // If this was not an artifact (that could be combined away), this might
  269. // need special handling. Add it to InstList, so when it's processed
  270. // there, it has to be legal or specially handled.
  271. else {
  272. LLVM_DEBUG(dbgs() << ".. Not combined, moving to instructions list\n");
  273. InstList.insert(&MI);
  274. }
  275. }
  276. } while (!InstList.empty());
  277. return {Changed, /*FailedOn*/ nullptr};
  278. }
  279. bool Legalizer::runOnMachineFunction(MachineFunction &MF) {
  280. // If the ISel pipeline failed, do not bother running that pass.
  281. if (MF.getProperties().hasProperty(
  282. MachineFunctionProperties::Property::FailedISel))
  283. return false;
  284. LLVM_DEBUG(dbgs() << "Legalize Machine IR for: " << MF.getName() << '\n');
  285. init(MF);
  286. const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>();
  287. GISelCSEAnalysisWrapper &Wrapper =
  288. getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
  289. MachineOptimizationRemarkEmitter MORE(MF, /*MBFI=*/nullptr);
  290. const size_t NumBlocks = MF.size();
  291. std::unique_ptr<MachineIRBuilder> MIRBuilder;
  292. GISelCSEInfo *CSEInfo = nullptr;
  293. bool EnableCSE = EnableCSEInLegalizer.getNumOccurrences()
  294. ? EnableCSEInLegalizer
  295. : TPC.isGISelCSEEnabled();
  296. if (EnableCSE) {
  297. MIRBuilder = std::make_unique<CSEMIRBuilder>();
  298. CSEInfo = &Wrapper.get(TPC.getCSEConfig());
  299. MIRBuilder->setCSEInfo(CSEInfo);
  300. } else
  301. MIRBuilder = std::make_unique<MachineIRBuilder>();
  302. SmallVector<GISelChangeObserver *, 1> AuxObservers;
  303. if (EnableCSE && CSEInfo) {
  304. // We want CSEInfo in addition to WorkListObserver to observe all changes.
  305. AuxObservers.push_back(CSEInfo);
  306. }
  307. assert(!CSEInfo || !errorToBool(CSEInfo->verify()));
  308. LostDebugLocObserver LocObserver(DEBUG_TYPE);
  309. if (VerifyDebugLocs > DebugLocVerifyLevel::None)
  310. AuxObservers.push_back(&LocObserver);
  311. const LegalizerInfo &LI = *MF.getSubtarget().getLegalizerInfo();
  312. MFResult Result =
  313. legalizeMachineFunction(MF, LI, AuxObservers, LocObserver, *MIRBuilder);
  314. if (Result.FailedOn) {
  315. reportGISelFailure(MF, TPC, MORE, "gisel-legalize",
  316. "unable to legalize instruction", *Result.FailedOn);
  317. return false;
  318. }
  319. // For now don't support if new blocks are inserted - we would need to fix the
  320. // outer loop for that.
  321. if (MF.size() != NumBlocks) {
  322. MachineOptimizationRemarkMissed R("gisel-legalize", "GISelFailure",
  323. MF.getFunction().getSubprogram(),
  324. /*MBB=*/nullptr);
  325. R << "inserting blocks is not supported yet";
  326. reportGISelFailure(MF, TPC, MORE, R);
  327. return false;
  328. }
  329. if (LocObserver.getNumLostDebugLocs()) {
  330. MachineOptimizationRemarkMissed R("gisel-legalize", "LostDebugLoc",
  331. MF.getFunction().getSubprogram(),
  332. /*MBB=*/&*MF.begin());
  333. R << "lost "
  334. << ore::NV("NumLostDebugLocs", LocObserver.getNumLostDebugLocs())
  335. << " debug locations during pass";
  336. reportGISelWarning(MF, TPC, MORE, R);
  337. // Example remark:
  338. // --- !Missed
  339. // Pass: gisel-legalize
  340. // Name: GISelFailure
  341. // DebugLoc: { File: '.../legalize-urem.mir', Line: 1, Column: 0 }
  342. // Function: test_urem_s32
  343. // Args:
  344. // - String: 'lost '
  345. // - NumLostDebugLocs: '1'
  346. // - String: ' debug locations during pass'
  347. // ...
  348. }
  349. // If for some reason CSE was not enabled, make sure that we invalidate the
  350. // CSEInfo object (as we currently declare that the analysis is preserved).
  351. // The next time get on the wrapper is called, it will force it to recompute
  352. // the analysis.
  353. if (!EnableCSE)
  354. Wrapper.setComputed(false);
  355. return Result.Changed;
  356. }