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 
12 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
13 #include "llvm/ADT/PostOrderIterator.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/CodeGen/GlobalISel/InstructionSelector.h"
16 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
17 #include "llvm/CodeGen/GlobalISel/Utils.h"
18 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/TargetLowering.h"
21 #include "llvm/CodeGen/TargetPassConfig.h"
22 #include "llvm/CodeGen/TargetSubtargetInfo.h"
23 #include "llvm/Config/config.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/TargetRegistry.h"
29 
30 #define DEBUG_TYPE "instruction-select"
31 
32 using namespace llvm;
33 
34 #ifdef LLVM_GISEL_COV_PREFIX
35 static cl::opt<std::string>
36     CoveragePrefix("gisel-coverage-prefix", cl::init(LLVM_GISEL_COV_PREFIX),
37                    cl::desc("Record GlobalISel rule coverage files of this "
38                             "prefix if instrumentation was generated"));
39 #else
40 static const std::string CoveragePrefix = "";
41 #endif
42 
43 char InstructionSelect::ID = 0;
44 INITIALIZE_PASS_BEGIN(InstructionSelect, DEBUG_TYPE,
45                       "Select target instructions out of generic instructions",
46                       false, false)
47 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
48 INITIALIZE_PASS_END(InstructionSelect, DEBUG_TYPE,
49                     "Select target instructions out of generic instructions",
50                     false, false)
51 
52 InstructionSelect::InstructionSelect() : MachineFunctionPass(ID) { }
53 
54 void InstructionSelect::getAnalysisUsage(AnalysisUsage &AU) const {
55   AU.addRequired<TargetPassConfig>();
56   getSelectionDAGFallbackAnalysisUsage(AU);
57   MachineFunctionPass::getAnalysisUsage(AU);
58 }
59 
60 bool InstructionSelect::runOnMachineFunction(MachineFunction &MF) {
61   // If the ISel pipeline failed, do not bother running that pass.
62   if (MF.getProperties().hasProperty(
63           MachineFunctionProperties::Property::FailedISel))
64     return false;
65 
66   LLVM_DEBUG(dbgs() << "Selecting function: " << MF.getName() << '\n');
67 
68   const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>();
69   InstructionSelector *ISel = MF.getSubtarget().getInstructionSelector();
70   CodeGenCoverage CoverageInfo;
71   assert(ISel && "Cannot work without InstructionSelector");
72   ISel->setupMF(MF, CoverageInfo);
73 
74   // An optimization remark emitter. Used to report failures.
75   MachineOptimizationRemarkEmitter MORE(MF, /*MBFI=*/nullptr);
76 
77   // FIXME: There are many other MF/MFI fields we need to initialize.
78 
79   MachineRegisterInfo &MRI = MF.getRegInfo();
80 #ifndef NDEBUG
81   // Check that our input is fully legal: we require the function to have the
82   // Legalized property, so it should be.
83   // FIXME: This should be in the MachineVerifier, as the RegBankSelected
84   // property check already is.
85   if (!DisableGISelLegalityCheck)
86     if (const MachineInstr *MI = machineFunctionIsIllegal(MF)) {
87       reportGISelFailure(MF, TPC, MORE, "gisel-select",
88                          "instruction is not legal", *MI);
89       return false;
90     }
91   // FIXME: We could introduce new blocks and will need to fix the outer loop.
92   // Until then, keep track of the number of blocks to assert that we don't.
93   const size_t NumBlocks = MF.size();
94 #endif
95 
96   for (MachineBasicBlock *MBB : post_order(&MF)) {
97     if (MBB->empty())
98       continue;
99 
100     // Select instructions in reverse block order. We permit erasing so have
101     // to resort to manually iterating and recognizing the begin (rend) case.
102     bool ReachedBegin = false;
103     for (auto MII = std::prev(MBB->end()), Begin = MBB->begin();
104          !ReachedBegin;) {
105 #ifndef NDEBUG
106       // Keep track of the insertion range for debug printing.
107       const auto AfterIt = std::next(MII);
108 #endif
109       // Select this instruction.
110       MachineInstr &MI = *MII;
111 
112       // And have our iterator point to the next instruction, if there is one.
113       if (MII == Begin)
114         ReachedBegin = true;
115       else
116         --MII;
117 
118       LLVM_DEBUG(dbgs() << "Selecting: \n  " << MI);
119 
120       // We could have folded this instruction away already, making it dead.
121       // If so, erase it.
122       if (isTriviallyDead(MI, MRI)) {
123         LLVM_DEBUG(dbgs() << "Is dead; erasing.\n");
124         MI.eraseFromParentAndMarkDBGValuesForRemoval();
125         continue;
126       }
127 
128       if (!ISel->select(MI)) {
129         // FIXME: It would be nice to dump all inserted instructions.  It's
130         // not obvious how, esp. considering select() can insert after MI.
131         reportGISelFailure(MF, TPC, MORE, "gisel-select", "cannot select", MI);
132         return false;
133       }
134 
135       // Dump the range of instructions that MI expanded into.
136       LLVM_DEBUG({
137         auto InsertedBegin = ReachedBegin ? MBB->begin() : std::next(MII);
138         dbgs() << "Into:\n";
139         for (auto &InsertedMI : make_range(InsertedBegin, AfterIt))
140           dbgs() << "  " << InsertedMI;
141         dbgs() << '\n';
142       });
143     }
144   }
145 
146   for (MachineBasicBlock &MBB : MF) {
147     if (MBB.empty())
148       continue;
149 
150     // Try to find redundant copies b/w vregs of the same register class.
151     bool ReachedBegin = false;
152     for (auto MII = std::prev(MBB.end()), Begin = MBB.begin(); !ReachedBegin;) {
153       // Select this instruction.
154       MachineInstr &MI = *MII;
155 
156       // And have our iterator point to the next instruction, if there is one.
157       if (MII == Begin)
158         ReachedBegin = true;
159       else
160         --MII;
161       if (MI.getOpcode() != TargetOpcode::COPY)
162         continue;
163       unsigned SrcReg = MI.getOperand(1).getReg();
164       unsigned DstReg = MI.getOperand(0).getReg();
165       if (Register::isVirtualRegister(SrcReg) &&
166           Register::isVirtualRegister(DstReg)) {
167         auto SrcRC = MRI.getRegClass(SrcReg);
168         auto DstRC = MRI.getRegClass(DstReg);
169         if (SrcRC == DstRC) {
170           MRI.replaceRegWith(DstReg, SrcReg);
171           MI.eraseFromParentAndMarkDBGValuesForRemoval();
172         }
173       }
174     }
175   }
176 
177 #ifndef NDEBUG
178   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
179   // Now that selection is complete, there are no more generic vregs.  Verify
180   // that the size of the now-constrained vreg is unchanged and that it has a
181   // register class.
182   for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
183     unsigned VReg = Register::index2VirtReg(I);
184 
185     MachineInstr *MI = nullptr;
186     if (!MRI.def_empty(VReg))
187       MI = &*MRI.def_instr_begin(VReg);
188     else if (!MRI.use_empty(VReg))
189       MI = &*MRI.use_instr_begin(VReg);
190     if (!MI)
191       continue;
192 
193     const TargetRegisterClass *RC = MRI.getRegClassOrNull(VReg);
194     if (!RC) {
195       reportGISelFailure(MF, TPC, MORE, "gisel-select",
196                          "VReg has no regclass after selection", *MI);
197       return false;
198     }
199 
200     const LLT Ty = MRI.getType(VReg);
201     if (Ty.isValid() && Ty.getSizeInBits() > TRI.getRegSizeInBits(*RC)) {
202       reportGISelFailure(
203           MF, TPC, MORE, "gisel-select",
204           "VReg's low-level type and register class have different sizes", *MI);
205       return false;
206     }
207   }
208 
209   if (MF.size() != NumBlocks) {
210     MachineOptimizationRemarkMissed R("gisel-select", "GISelFailure",
211                                       MF.getFunction().getSubprogram(),
212                                       /*MBB=*/nullptr);
213     R << "inserting blocks is not supported yet";
214     reportGISelFailure(MF, TPC, MORE, R);
215     return false;
216   }
217 #endif
218   auto &TLI = *MF.getSubtarget().getTargetLowering();
219   TLI.finalizeLowering(MF);
220 
221   LLVM_DEBUG({
222     dbgs() << "Rules covered by selecting function: " << MF.getName() << ":";
223     for (auto RuleID : CoverageInfo.covered())
224       dbgs() << " id" << RuleID;
225     dbgs() << "\n\n";
226   });
227   CoverageInfo.emit(CoveragePrefix,
228                     MF.getSubtarget()
229                         .getTargetLowering()
230                         ->getTargetMachine()
231                         .getTarget()
232                         .getBackendName());
233 
234   // If we successfully selected the function nothing is going to use the vreg
235   // types after us (otherwise MIRPrinter would need them). Make sure the types
236   // disappear.
237   MRI.clearVirtRegTypes();
238 
239   // FIXME: Should we accurately track changes?
240   return true;
241 }
242