LLVM  6.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  // Now that selection is complete, there are no more generic vregs. Verify
163  // that the size of the now-constrained vreg is unchanged and that it has a
164  // register class.
165  for (auto &VRegToType : MRI.getVRegToType()) {
166  unsigned VReg = VRegToType.first;
167  auto *RC = MRI.getRegClassOrNull(VReg);
168  MachineInstr *MI = nullptr;
169  if (!MRI.def_empty(VReg))
170  MI = &*MRI.def_instr_begin(VReg);
171  else if (!MRI.use_empty(VReg))
172  MI = &*MRI.use_instr_begin(VReg);
173 
174  if (MI && !RC) {
175  reportGISelFailure(MF, TPC, MORE, "gisel-select",
176  "VReg has no regclass after selection", *MI);
177  return false;
178  } else if (!RC)
179  continue;
180 
181  if (VRegToType.second.isValid() &&
182  VRegToType.second.getSizeInBits() > TRI.getRegSizeInBits(*RC)) {
183  reportGISelFailure(MF, TPC, MORE, "gisel-select",
184  "VReg has explicit size different from class size",
185  *MI);
186  return false;
187  }
188  }
189 
190  if (MF.size() != NumBlocks) {
191  MachineOptimizationRemarkMissed R("gisel-select", "GISelFailure",
192  MF.getFunction()->getSubprogram(),
193  /*MBB=*/nullptr);
194  R << "inserting blocks is not supported yet";
195  reportGISelFailure(MF, TPC, MORE, R);
196  return false;
197  }
198 
199  auto &TLI = *MF.getSubtarget().getTargetLowering();
200  TLI.finalizeLowering(MF);
201 
202  CoverageInfo.emit(CoveragePrefix,
203  MF.getSubtarget()
204  .getTargetLowering()
205  ->getTargetMachine()
206  .getTarget()
207  .getBackendName());
208 
209  // FIXME: Should we accurately track changes?
210  return true;
211 }
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
void initializeInstructionSelectPass(PassRegistry &)
const MachineFunctionProperties & getProperties() const
Get the function properties.
LLVM_NODISCARD detail::scope_exit< typename std::decay< Callable >::type > make_scope_exit(Callable &&F)
Definition: ScopeExit.h:47
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
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
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:59
Representation of each machine instruction.
Definition: MachineInstr.h:59
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
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:80
This file describes how to lower LLVM code to machine code.