InstructionSelect.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. //===- llvm/CodeGen/GlobalISel/InstructionSelect.cpp - InstructionSelect ---==//
  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. /// \file
  9. /// This file implements the InstructionSelect class.
  10. //===----------------------------------------------------------------------===//
  11. #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
  12. #include "llvm/ADT/PostOrderIterator.h"
  13. #include "llvm/ADT/ScopeExit.h"
  14. #include "llvm/ADT/Twine.h"
  15. #include "llvm/Analysis/BlockFrequencyInfo.h"
  16. #include "llvm/Analysis/LazyBlockFrequencyInfo.h"
  17. #include "llvm/Analysis/ProfileSummaryInfo.h"
  18. #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
  19. #include "llvm/CodeGen/GlobalISel/InstructionSelector.h"
  20. #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
  21. #include "llvm/CodeGen/GlobalISel/Utils.h"
  22. #include "llvm/CodeGen/MachineFrameInfo.h"
  23. #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
  24. #include "llvm/CodeGen/MachineRegisterInfo.h"
  25. #include "llvm/CodeGen/TargetInstrInfo.h"
  26. #include "llvm/CodeGen/TargetLowering.h"
  27. #include "llvm/CodeGen/TargetPassConfig.h"
  28. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  29. #include "llvm/Config/config.h"
  30. #include "llvm/IR/Constants.h"
  31. #include "llvm/IR/Function.h"
  32. #include "llvm/MC/TargetRegistry.h"
  33. #include "llvm/Support/CommandLine.h"
  34. #include "llvm/Support/Debug.h"
  35. #include "llvm/Target/TargetMachine.h"
  36. #define DEBUG_TYPE "instruction-select"
  37. using namespace llvm;
  38. #ifdef LLVM_GISEL_COV_PREFIX
  39. static cl::opt<std::string>
  40. CoveragePrefix("gisel-coverage-prefix", cl::init(LLVM_GISEL_COV_PREFIX),
  41. cl::desc("Record GlobalISel rule coverage files of this "
  42. "prefix if instrumentation was generated"));
  43. #else
  44. static const std::string CoveragePrefix;
  45. #endif
  46. char InstructionSelect::ID = 0;
  47. INITIALIZE_PASS_BEGIN(InstructionSelect, DEBUG_TYPE,
  48. "Select target instructions out of generic instructions",
  49. false, false)
  50. INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
  51. INITIALIZE_PASS_DEPENDENCY(GISelKnownBitsAnalysis)
  52. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  53. INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass)
  54. INITIALIZE_PASS_END(InstructionSelect, DEBUG_TYPE,
  55. "Select target instructions out of generic instructions",
  56. false, false)
  57. InstructionSelect::InstructionSelect(CodeGenOpt::Level OL)
  58. : MachineFunctionPass(ID), OptLevel(OL) {}
  59. // In order not to crash when calling getAnalysis during testing with -run-pass
  60. // we use the default opt level here instead of None, so that the addRequired()
  61. // calls are made in getAnalysisUsage().
  62. InstructionSelect::InstructionSelect()
  63. : MachineFunctionPass(ID), OptLevel(CodeGenOpt::Default) {}
  64. void InstructionSelect::getAnalysisUsage(AnalysisUsage &AU) const {
  65. AU.addRequired<TargetPassConfig>();
  66. AU.addRequired<GISelKnownBitsAnalysis>();
  67. AU.addPreserved<GISelKnownBitsAnalysis>();
  68. if (OptLevel != CodeGenOpt::None) {
  69. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  70. LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
  71. }
  72. getSelectionDAGFallbackAnalysisUsage(AU);
  73. MachineFunctionPass::getAnalysisUsage(AU);
  74. }
  75. bool InstructionSelect::runOnMachineFunction(MachineFunction &MF) {
  76. // If the ISel pipeline failed, do not bother running that pass.
  77. if (MF.getProperties().hasProperty(
  78. MachineFunctionProperties::Property::FailedISel))
  79. return false;
  80. LLVM_DEBUG(dbgs() << "Selecting function: " << MF.getName() << '\n');
  81. const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>();
  82. InstructionSelector *ISel = MF.getSubtarget().getInstructionSelector();
  83. CodeGenOpt::Level OldOptLevel = OptLevel;
  84. auto RestoreOptLevel = make_scope_exit([=]() { OptLevel = OldOptLevel; });
  85. OptLevel = MF.getFunction().hasOptNone() ? CodeGenOpt::None
  86. : MF.getTarget().getOptLevel();
  87. GISelKnownBits *KB = &getAnalysis<GISelKnownBitsAnalysis>().get(MF);
  88. if (OptLevel != CodeGenOpt::None) {
  89. PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  90. if (PSI && PSI->hasProfileSummary())
  91. BFI = &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI();
  92. }
  93. CodeGenCoverage CoverageInfo;
  94. assert(ISel && "Cannot work without InstructionSelector");
  95. ISel->setupMF(MF, KB, CoverageInfo, PSI, BFI);
  96. // An optimization remark emitter. Used to report failures.
  97. MachineOptimizationRemarkEmitter MORE(MF, /*MBFI=*/nullptr);
  98. // FIXME: There are many other MF/MFI fields we need to initialize.
  99. MachineRegisterInfo &MRI = MF.getRegInfo();
  100. #ifndef NDEBUG
  101. // Check that our input is fully legal: we require the function to have the
  102. // Legalized property, so it should be.
  103. // FIXME: This should be in the MachineVerifier, as the RegBankSelected
  104. // property check already is.
  105. if (!DisableGISelLegalityCheck)
  106. if (const MachineInstr *MI = machineFunctionIsIllegal(MF)) {
  107. reportGISelFailure(MF, TPC, MORE, "gisel-select",
  108. "instruction is not legal", *MI);
  109. return false;
  110. }
  111. // FIXME: We could introduce new blocks and will need to fix the outer loop.
  112. // Until then, keep track of the number of blocks to assert that we don't.
  113. const size_t NumBlocks = MF.size();
  114. #endif
  115. // Keep track of selected blocks, so we can delete unreachable ones later.
  116. DenseSet<MachineBasicBlock *> SelectedBlocks;
  117. for (MachineBasicBlock *MBB : post_order(&MF)) {
  118. ISel->CurMBB = MBB;
  119. SelectedBlocks.insert(MBB);
  120. if (MBB->empty())
  121. continue;
  122. // Select instructions in reverse block order. We permit erasing so have
  123. // to resort to manually iterating and recognizing the begin (rend) case.
  124. bool ReachedBegin = false;
  125. for (auto MII = std::prev(MBB->end()), Begin = MBB->begin();
  126. !ReachedBegin;) {
  127. #ifndef NDEBUG
  128. // Keep track of the insertion range for debug printing.
  129. const auto AfterIt = std::next(MII);
  130. #endif
  131. // Select this instruction.
  132. MachineInstr &MI = *MII;
  133. // And have our iterator point to the next instruction, if there is one.
  134. if (MII == Begin)
  135. ReachedBegin = true;
  136. else
  137. --MII;
  138. LLVM_DEBUG(dbgs() << "Selecting: \n " << MI);
  139. // We could have folded this instruction away already, making it dead.
  140. // If so, erase it.
  141. if (isTriviallyDead(MI, MRI)) {
  142. LLVM_DEBUG(dbgs() << "Is dead; erasing.\n");
  143. MI.eraseFromParent();
  144. continue;
  145. }
  146. // Eliminate hints.
  147. if (isPreISelGenericOptimizationHint(MI.getOpcode())) {
  148. Register DstReg = MI.getOperand(0).getReg();
  149. Register SrcReg = MI.getOperand(1).getReg();
  150. // At this point, the destination register class of the hint may have
  151. // been decided.
  152. //
  153. // Propagate that through to the source register.
  154. const TargetRegisterClass *DstRC = MRI.getRegClassOrNull(DstReg);
  155. if (DstRC)
  156. MRI.setRegClass(SrcReg, DstRC);
  157. assert(canReplaceReg(DstReg, SrcReg, MRI) &&
  158. "Must be able to replace dst with src!");
  159. MI.eraseFromParent();
  160. MRI.replaceRegWith(DstReg, SrcReg);
  161. continue;
  162. }
  163. if (!ISel->select(MI)) {
  164. // FIXME: It would be nice to dump all inserted instructions. It's
  165. // not obvious how, esp. considering select() can insert after MI.
  166. reportGISelFailure(MF, TPC, MORE, "gisel-select", "cannot select", MI);
  167. return false;
  168. }
  169. // Dump the range of instructions that MI expanded into.
  170. LLVM_DEBUG({
  171. auto InsertedBegin = ReachedBegin ? MBB->begin() : std::next(MII);
  172. dbgs() << "Into:\n";
  173. for (auto &InsertedMI : make_range(InsertedBegin, AfterIt))
  174. dbgs() << " " << InsertedMI;
  175. dbgs() << '\n';
  176. });
  177. }
  178. }
  179. for (MachineBasicBlock &MBB : MF) {
  180. if (MBB.empty())
  181. continue;
  182. if (!SelectedBlocks.contains(&MBB)) {
  183. // This is an unreachable block and therefore hasn't been selected, since
  184. // the main selection loop above uses a postorder block traversal.
  185. // We delete all the instructions in this block since it's unreachable.
  186. MBB.clear();
  187. // Don't delete the block in case the block has it's address taken or is
  188. // still being referenced by a phi somewhere.
  189. continue;
  190. }
  191. // Try to find redundant copies b/w vregs of the same register class.
  192. bool ReachedBegin = false;
  193. for (auto MII = std::prev(MBB.end()), Begin = MBB.begin(); !ReachedBegin;) {
  194. // Select this instruction.
  195. MachineInstr &MI = *MII;
  196. // And have our iterator point to the next instruction, if there is one.
  197. if (MII == Begin)
  198. ReachedBegin = true;
  199. else
  200. --MII;
  201. if (MI.getOpcode() != TargetOpcode::COPY)
  202. continue;
  203. Register SrcReg = MI.getOperand(1).getReg();
  204. Register DstReg = MI.getOperand(0).getReg();
  205. if (Register::isVirtualRegister(SrcReg) &&
  206. Register::isVirtualRegister(DstReg)) {
  207. auto SrcRC = MRI.getRegClass(SrcReg);
  208. auto DstRC = MRI.getRegClass(DstReg);
  209. if (SrcRC == DstRC) {
  210. MRI.replaceRegWith(DstReg, SrcReg);
  211. MI.eraseFromParent();
  212. }
  213. }
  214. }
  215. }
  216. #ifndef NDEBUG
  217. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  218. // Now that selection is complete, there are no more generic vregs. Verify
  219. // that the size of the now-constrained vreg is unchanged and that it has a
  220. // register class.
  221. for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
  222. unsigned VReg = Register::index2VirtReg(I);
  223. MachineInstr *MI = nullptr;
  224. if (!MRI.def_empty(VReg))
  225. MI = &*MRI.def_instr_begin(VReg);
  226. else if (!MRI.use_empty(VReg)) {
  227. MI = &*MRI.use_instr_begin(VReg);
  228. // Debug value instruction is permitted to use undefined vregs.
  229. if (MI->isDebugValue())
  230. continue;
  231. }
  232. if (!MI)
  233. continue;
  234. const TargetRegisterClass *RC = MRI.getRegClassOrNull(VReg);
  235. if (!RC) {
  236. reportGISelFailure(MF, TPC, MORE, "gisel-select",
  237. "VReg has no regclass after selection", *MI);
  238. return false;
  239. }
  240. const LLT Ty = MRI.getType(VReg);
  241. if (Ty.isValid() && Ty.getSizeInBits() > TRI.getRegSizeInBits(*RC)) {
  242. reportGISelFailure(
  243. MF, TPC, MORE, "gisel-select",
  244. "VReg's low-level type and register class have different sizes", *MI);
  245. return false;
  246. }
  247. }
  248. if (MF.size() != NumBlocks) {
  249. MachineOptimizationRemarkMissed R("gisel-select", "GISelFailure",
  250. MF.getFunction().getSubprogram(),
  251. /*MBB=*/nullptr);
  252. R << "inserting blocks is not supported yet";
  253. reportGISelFailure(MF, TPC, MORE, R);
  254. return false;
  255. }
  256. #endif
  257. // Determine if there are any calls in this machine function. Ported from
  258. // SelectionDAG.
  259. MachineFrameInfo &MFI = MF.getFrameInfo();
  260. for (const auto &MBB : MF) {
  261. if (MFI.hasCalls() && MF.hasInlineAsm())
  262. break;
  263. for (const auto &MI : MBB) {
  264. if ((MI.isCall() && !MI.isReturn()) || MI.isStackAligningInlineAsm())
  265. MFI.setHasCalls(true);
  266. if (MI.isInlineAsm())
  267. MF.setHasInlineAsm(true);
  268. }
  269. }
  270. // FIXME: FinalizeISel pass calls finalizeLowering, so it's called twice.
  271. auto &TLI = *MF.getSubtarget().getTargetLowering();
  272. TLI.finalizeLowering(MF);
  273. LLVM_DEBUG({
  274. dbgs() << "Rules covered by selecting function: " << MF.getName() << ":";
  275. for (auto RuleID : CoverageInfo.covered())
  276. dbgs() << " id" << RuleID;
  277. dbgs() << "\n\n";
  278. });
  279. CoverageInfo.emit(CoveragePrefix,
  280. TLI.getTargetMachine().getTarget().getBackendName());
  281. // If we successfully selected the function nothing is going to use the vreg
  282. // types after us (otherwise MIRPrinter would need them). Make sure the types
  283. // disappear.
  284. MRI.clearVirtRegTypes();
  285. // FIXME: Should we accurately track changes?
  286. return true;
  287. }