LLVM  7.0.0svn
InstructionSelect.cpp
Go to the documentation of this file.
1 //===- llvm/CodeGen/GlobalISel/InstructionSelect.cpp - InstructionSelect ---==//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This file implements the InstructionSelect class.
11 //===----------------------------------------------------------------------===//
12 
15 #include "llvm/ADT/ScopeExit.h"
16 #include "llvm/ADT/Twine.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/Function.h"
29 #include "llvm/Support/Debug.h"
31 
32 #define DEBUG_TYPE "instruction-select"
33 
34 using namespace llvm;
35 
36 #ifdef LLVM_GISEL_COV_PREFIX
38  CoveragePrefix("gisel-coverage-prefix", cl::init(LLVM_GISEL_COV_PREFIX),
39  cl::desc("Record GlobalISel rule coverage files of this "
40  "prefix if instrumentation was generated"));
41 #else
42 static const std::string CoveragePrefix = "";
43 #endif
44 
45 char InstructionSelect::ID = 0;
47  "Select target instructions out of generic instructions",
48  false, false)
51  "Select target instructions out of generic instructions",
52  false, false)
53 
54 InstructionSelect::InstructionSelect() : MachineFunctionPass(ID) {
56 }
57 
61 }
62 
64  const MachineRegisterInfo &MRI = MF.getRegInfo();
65 
66  // No matter what happens, whether we successfully select the function or not,
67  // nothing is going to use the vreg types after us. Make sure they disappear.
68  auto ClearVRegTypesOnReturn =
69  make_scope_exit([&]() { MRI.getVRegToType().clear(); });
70 
71  // If the ISel pipeline failed, do not bother running that pass.
72  if (MF.getProperties().hasProperty(
74  return false;
75 
76  DEBUG(dbgs() << "Selecting function: " << MF.getName() << '\n');
77 
78  const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>();
80  CodeGenCoverage CoverageInfo;
81  assert(ISel && "Cannot work without InstructionSelector");
82 
83  // An optimization remark emitter. Used to report failures.
84  MachineOptimizationRemarkEmitter MORE(MF, /*MBFI=*/nullptr);
85 
86  // FIXME: There are many other MF/MFI fields we need to initialize.
87 
88 #ifndef NDEBUG
89  // Check that our input is fully legal: we require the function to have the
90  // Legalized property, so it should be.
91  // FIXME: This should be in the MachineVerifier, but it can't use the
92  // LegalizerInfo as it's currently in the separate GlobalISel library.
93  // The RegBankSelected property is already checked in the verifier. Note
94  // that it has the same layering problem, but we only use inline methods so
95  // end up not needing to link against the GlobalISel library.
96  if (const LegalizerInfo *MLI = MF.getSubtarget().getLegalizerInfo())
97  for (MachineBasicBlock &MBB : MF)
98  for (MachineInstr &MI : MBB)
99  if (isPreISelGenericOpcode(MI.getOpcode()) && !MLI->isLegal(MI, MRI)) {
100  reportGISelFailure(MF, TPC, MORE, "gisel-select",
101  "instruction is not legal", MI);
102  return false;
103  }
104 
105 #endif
106  // FIXME: We could introduce new blocks and will need to fix the outer loop.
107  // Until then, keep track of the number of blocks to assert that we don't.
108  const size_t NumBlocks = MF.size();
109 
110  for (MachineBasicBlock *MBB : post_order(&MF)) {
111  if (MBB->empty())
112  continue;
113 
114  // Select instructions in reverse block order. We permit erasing so have
115  // to resort to manually iterating and recognizing the begin (rend) case.
116  bool ReachedBegin = false;
117  for (auto MII = std::prev(MBB->end()), Begin = MBB->begin();
118  !ReachedBegin;) {
119 #ifndef NDEBUG
120  // Keep track of the insertion range for debug printing.
121  const auto AfterIt = std::next(MII);
122 #endif
123  // Select this instruction.
124  MachineInstr &MI = *MII;
125 
126  // And have our iterator point to the next instruction, if there is one.
127  if (MII == Begin)
128  ReachedBegin = true;
129  else
130  --MII;
131 
132  DEBUG(dbgs() << "Selecting: \n " << MI);
133 
134  // We could have folded this instruction away already, making it dead.
135  // If so, erase it.
136  if (isTriviallyDead(MI, MRI)) {
137  DEBUG(dbgs() << "Is dead; erasing.\n");
139  continue;
140  }
141 
142  if (!ISel->select(MI, CoverageInfo)) {
143  // FIXME: It would be nice to dump all inserted instructions. It's
144  // not obvious how, esp. considering select() can insert after MI.
145  reportGISelFailure(MF, TPC, MORE, "gisel-select", "cannot select", MI);
146  return false;
147  }
148 
149  // Dump the range of instructions that MI expanded into.
150  DEBUG({
151  auto InsertedBegin = ReachedBegin ? MBB->begin() : std::next(MII);
152  dbgs() << "Into:\n";
153  for (auto &InsertedMI : make_range(InsertedBegin, AfterIt))
154  dbgs() << " " << InsertedMI;
155  dbgs() << '\n';
156  });
157  }
158  }
159 
160  const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
161 
162  for (MachineBasicBlock &MBB : MF) {
163  if (MBB.empty())
164  continue;
165 
166  // Try to find redundant copies b/w vregs of the same register class.
167  bool ReachedBegin = false;
168  for (auto MII = std::prev(MBB.end()), Begin = MBB.begin(); !ReachedBegin;) {
169  // Select this instruction.
170  MachineInstr &MI = *MII;
171 
172  // And have our iterator point to the next instruction, if there is one.
173  if (MII == Begin)
174  ReachedBegin = true;
175  else
176  --MII;
177  if (MI.getOpcode() != TargetOpcode::COPY)
178  continue;
179  unsigned SrcReg = MI.getOperand(1).getReg();
180  unsigned DstReg = MI.getOperand(0).getReg();
183  MachineRegisterInfo &MRI = MF.getRegInfo();
184  auto SrcRC = MRI.getRegClass(SrcReg);
185  auto DstRC = MRI.getRegClass(DstReg);
186  if (SrcRC == DstRC) {
187  MRI.replaceRegWith(DstReg, SrcReg);
189  }
190  }
191  }
192  }
193 
194  // Now that selection is complete, there are no more generic vregs. Verify
195  // that the size of the now-constrained vreg is unchanged and that it has a
196  // register class.
197  for (auto &VRegToType : MRI.getVRegToType()) {
198  unsigned VReg = VRegToType.first;
199  auto *RC = MRI.getRegClassOrNull(VReg);
200  MachineInstr *MI = nullptr;
201  if (!MRI.def_empty(VReg))
202  MI = &*MRI.def_instr_begin(VReg);
203  else if (!MRI.use_empty(VReg))
204  MI = &*MRI.use_instr_begin(VReg);
205 
206  if (MI && !RC) {
207  reportGISelFailure(MF, TPC, MORE, "gisel-select",
208  "VReg has no regclass after selection", *MI);
209  return false;
210  } else if (!RC)
211  continue;
212 
213  if (VRegToType.second.isValid() &&
214  VRegToType.second.getSizeInBits() > TRI.getRegSizeInBits(*RC)) {
215  reportGISelFailure(MF, TPC, MORE, "gisel-select",
216  "VReg has explicit size different from class size",
217  *MI);
218  return false;
219  }
220  }
221 
222  if (MF.size() != NumBlocks) {
223  MachineOptimizationRemarkMissed R("gisel-select", "GISelFailure",
224  MF.getFunction().getSubprogram(),
225  /*MBB=*/nullptr);
226  R << "inserting blocks is not supported yet";
227  reportGISelFailure(MF, TPC, MORE, R);
228  return false;
229  }
230 
231  auto &TLI = *MF.getSubtarget().getTargetLowering();
232  TLI.finalizeLowering(MF);
233 
234  CoverageInfo.emit(CoveragePrefix,
235  MF.getSubtarget()
236  .getTargetLowering()
237  ->getTargetMachine()
238  .getTarget()
239  .getBackendName());
240 
241  // FIXME: Should we accurately track changes?
242  return true;
243 }
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
void initializeInstructionSelectPass(PassRegistry &)
const MachineFunctionProperties & getProperties() const
Get the function properties.
unsigned getReg() const
getReg - Returns the register number.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
LLVM_NODISCARD detail::scope_exit< typename std::decay< Callable >::type > make_scope_exit(Callable &&F)
Definition: ScopeExit.h:59
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
bool emit(StringRef FilePrefix, StringRef BackendName) const
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:293
Target-Independent Code Generator Pass Configuration Options.
INITIALIZE_PASS_BEGIN(InstructionSelect, DEBUG_TYPE, "Select target instructions out of generic instructions", false, false) INITIALIZE_PASS_END(InstructionSelect
void eraseFromParentAndMarkDBGValuesForRemoval()
Unlink &#39;this&#39; from the containing basic block and delete it.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
virtual const LegalizerInfo * getLegalizerInfo() const
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:406
unsigned const MachineRegisterInfo * MRI
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Represent the analysis usage information of a pass.
use_instr_iterator use_instr_begin(unsigned RegNo) const
VRegToTypeMap & getVRegToType() const
Accessor for VRegToType.
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
bool def_empty(unsigned RegNo) const
def_empty - Return true if there are no instructions defining the specified register (it may be live-...
iterator_range< po_iterator< T > > post_order(const T &G)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
static const std::string CoveragePrefix
#define DEBUG_TYPE
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
The optimization diagnostic interface.
#define MORE()
Definition: regcomp.c:256
This pass is responsible for selecting generic machine instructions to target-specific instructions...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
bool use_empty(unsigned RegNo) const
use_empty - Return true if there are no instructions using the specified register.
def_instr_iterator def_instr_begin(unsigned RegNo) const
void replaceRegWith(unsigned FromReg, unsigned ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Provides the logic to select generic machine instructions.
bool isTriviallyDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
Check whether an instruction MI is dead: it only defines dead virtual registers, and doesn&#39;t have oth...
Definition: Utils.cpp:124
Representation of each machine instruction.
Definition: MachineInstr.h:60
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
virtual const InstructionSelector * getInstructionSelector() const
Diagnostic information for missed-optimization remarks.
const TargetRegisterClass * getRegClassOrNull(unsigned Reg) const
Return the register class of Reg, or null if Reg has not been assigned a register class yet...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool hasProperty(Property P) const
bool isPreISelGenericOpcode(unsigned Opcode)
Check whether the given Opcode is a generic opcode that is not supposed to appear after ISel...
Definition: TargetOpcodes.h:31
#define DEBUG(X)
Definition: Debug.h:118
IRTranslator LLVM IR MI
inst_range instructions(Function *F)
Definition: InstIterator.h:134
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:298
void reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC, MachineOptimizationRemarkEmitter &MORE, MachineOptimizationRemarkMissed &R)
Report an ISel error as a missed optimization remark to the LLVMContext&#39;s diagnostic stream...
Definition: Utils.cpp:145
This file describes how to lower LLVM code to machine code.