LLVM 20.0.0git
InstructionSelect.cpp
Go to the documentation of this file.
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
14#include "llvm/ADT/ScopeExit.h"
28#include "llvm/Config/config.h"
29#include "llvm/IR/Function.h"
33#include "llvm/Support/Debug.h"
36
37#define DEBUG_TYPE "instruction-select"
38
39using namespace llvm;
40
41DEBUG_COUNTER(GlobalISelCounter, "globalisel",
42 "Controls whether to select function with GlobalISel");
43
44#ifdef LLVM_GISEL_COV_PREFIX
46 CoveragePrefix("gisel-coverage-prefix", cl::init(LLVM_GISEL_COV_PREFIX),
47 cl::desc("Record GlobalISel rule coverage files of this "
48 "prefix if instrumentation was generated"));
49#else
50static const std::string CoveragePrefix;
51#endif
52
55 "Select target instructions out of generic instructions",
56 false, false)
62 "Select target instructions out of generic instructions",
64
66 : MachineFunctionPass(PassID), OptLevel(OL) {}
67
72
76 }
79}
80
82 // If the ISel pipeline failed, do not bother running that pass.
85 return false;
86
87 LLVM_DEBUG(dbgs() << "Selecting function: " << MF.getName() << '\n');
88
89 const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>();
91 ISel->setTargetPassConfig(&TPC);
92
93 CodeGenOptLevel OldOptLevel = OptLevel;
94 auto RestoreOptLevel = make_scope_exit([=]() { OptLevel = OldOptLevel; });
96 : MF.getTarget().getOptLevel();
97
98 GISelKnownBits *KB = &getAnalysis<GISelKnownBitsAnalysis>().get(MF);
100 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
101 if (PSI && PSI->hasProfileSummary())
102 BFI = &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI();
103 }
104
105 CodeGenCoverage CoverageInfo;
106 assert(ISel && "Cannot work without InstructionSelector");
107 ISel->setupMF(MF, KB, &CoverageInfo, PSI, BFI);
108
109 // An optimization remark emitter. Used to report failures.
110 MachineOptimizationRemarkEmitter MORE(MF, /*MBFI=*/nullptr);
111 ISel->setRemarkEmitter(&MORE);
112
113 // FIXME: There are many other MF/MFI fields we need to initialize.
114
116#ifndef NDEBUG
117 // Check that our input is fully legal: we require the function to have the
118 // Legalized property, so it should be.
119 // FIXME: This should be in the MachineVerifier, as the RegBankSelected
120 // property check already is.
122 if (const MachineInstr *MI = machineFunctionIsIllegal(MF)) {
123 reportGISelFailure(MF, TPC, MORE, "gisel-select",
124 "instruction is not legal", *MI);
125 return false;
126 }
127 // FIXME: We could introduce new blocks and will need to fix the outer loop.
128 // Until then, keep track of the number of blocks to assert that we don't.
129 const size_t NumBlocks = MF.size();
130#endif
131 // Keep track of selected blocks, so we can delete unreachable ones later.
132 DenseSet<MachineBasicBlock *> SelectedBlocks;
133
134 for (MachineBasicBlock *MBB : post_order(&MF)) {
135 ISel->CurMBB = MBB;
136 SelectedBlocks.insert(MBB);
137 if (MBB->empty())
138 continue;
139
140 // Select instructions in reverse block order. We permit erasing so have
141 // to resort to manually iterating and recognizing the begin (rend) case.
142 bool ReachedBegin = false;
143 for (auto MII = std::prev(MBB->end()), Begin = MBB->begin();
144 !ReachedBegin;) {
145#ifndef NDEBUG
146 // Keep track of the insertion range for debug printing.
147 const auto AfterIt = std::next(MII);
148#endif
149 // Select this instruction.
150 MachineInstr &MI = *MII;
151
152 // And have our iterator point to the next instruction, if there is one.
153 if (MII == Begin)
154 ReachedBegin = true;
155 else
156 --MII;
157
158 LLVM_DEBUG(dbgs() << "Selecting: \n " << MI);
159
160 // We could have folded this instruction away already, making it dead.
161 // If so, erase it.
162 if (isTriviallyDead(MI, MRI)) {
163 LLVM_DEBUG(dbgs() << "Is dead; erasing.\n");
165 MI.eraseFromParent();
166 continue;
167 }
168
169 // Eliminate hints or G_CONSTANT_FOLD_BARRIER.
170 if (isPreISelGenericOptimizationHint(MI.getOpcode()) ||
171 MI.getOpcode() == TargetOpcode::G_CONSTANT_FOLD_BARRIER) {
172 auto [DstReg, SrcReg] = MI.getFirst2Regs();
173
174 // At this point, the destination register class of the op may have
175 // been decided.
176 //
177 // Propagate that through to the source register.
178 const TargetRegisterClass *DstRC = MRI.getRegClassOrNull(DstReg);
179 if (DstRC)
180 MRI.setRegClass(SrcReg, DstRC);
181 assert(canReplaceReg(DstReg, SrcReg, MRI) &&
182 "Must be able to replace dst with src!");
183 MI.eraseFromParent();
184 MRI.replaceRegWith(DstReg, SrcReg);
185 continue;
186 }
187
188 if (MI.getOpcode() == TargetOpcode::G_INVOKE_REGION_START) {
189 MI.eraseFromParent();
190 continue;
191 }
192
193 if (!ISel->select(MI)) {
194 // FIXME: It would be nice to dump all inserted instructions. It's
195 // not obvious how, esp. considering select() can insert after MI.
196 reportGISelFailure(MF, TPC, MORE, "gisel-select", "cannot select", MI);
197 return false;
198 }
199
200 // Dump the range of instructions that MI expanded into.
201 LLVM_DEBUG({
202 auto InsertedBegin = ReachedBegin ? MBB->begin() : std::next(MII);
203 dbgs() << "Into:\n";
204 for (auto &InsertedMI : make_range(InsertedBegin, AfterIt))
205 dbgs() << " " << InsertedMI;
206 dbgs() << '\n';
207 });
208 }
209 }
210
211 for (MachineBasicBlock &MBB : MF) {
212 if (MBB.empty())
213 continue;
214
215 if (!SelectedBlocks.contains(&MBB)) {
216 // This is an unreachable block and therefore hasn't been selected, since
217 // the main selection loop above uses a postorder block traversal.
218 // We delete all the instructions in this block since it's unreachable.
219 MBB.clear();
220 // Don't delete the block in case the block has it's address taken or is
221 // still being referenced by a phi somewhere.
222 continue;
223 }
224 // Try to find redundant copies b/w vregs of the same register class.
225 bool ReachedBegin = false;
226 for (auto MII = std::prev(MBB.end()), Begin = MBB.begin(); !ReachedBegin;) {
227 // Select this instruction.
228 MachineInstr &MI = *MII;
229
230 // And have our iterator point to the next instruction, if there is one.
231 if (MII == Begin)
232 ReachedBegin = true;
233 else
234 --MII;
235 if (MI.getOpcode() != TargetOpcode::COPY)
236 continue;
237 Register SrcReg = MI.getOperand(1).getReg();
238 Register DstReg = MI.getOperand(0).getReg();
239 if (SrcReg.isVirtual() && DstReg.isVirtual()) {
240 auto SrcRC = MRI.getRegClass(SrcReg);
241 auto DstRC = MRI.getRegClass(DstReg);
242 if (SrcRC == DstRC) {
243 MRI.replaceRegWith(DstReg, SrcReg);
244 MI.eraseFromParent();
245 }
246 }
247 }
248 }
249
250#ifndef NDEBUG
252 // Now that selection is complete, there are no more generic vregs. Verify
253 // that the size of the now-constrained vreg is unchanged and that it has a
254 // register class.
255 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
257
258 MachineInstr *MI = nullptr;
259 if (!MRI.def_empty(VReg))
260 MI = &*MRI.def_instr_begin(VReg);
261 else if (!MRI.use_empty(VReg)) {
262 MI = &*MRI.use_instr_begin(VReg);
263 // Debug value instruction is permitted to use undefined vregs.
264 if (MI->isDebugValue())
265 continue;
266 }
267 if (!MI)
268 continue;
269
270 const TargetRegisterClass *RC = MRI.getRegClassOrNull(VReg);
271 if (!RC) {
272 reportGISelFailure(MF, TPC, MORE, "gisel-select",
273 "VReg has no regclass after selection", *MI);
274 return false;
275 }
276
277 const LLT Ty = MRI.getType(VReg);
278 if (Ty.isValid() &&
279 TypeSize::isKnownGT(Ty.getSizeInBits(), TRI.getRegSizeInBits(*RC))) {
281 MF, TPC, MORE, "gisel-select",
282 "VReg's low-level type and register class have different sizes", *MI);
283 return false;
284 }
285 }
286
287 if (MF.size() != NumBlocks) {
288 MachineOptimizationRemarkMissed R("gisel-select", "GISelFailure",
290 /*MBB=*/nullptr);
291 R << "inserting blocks is not supported yet";
292 reportGISelFailure(MF, TPC, MORE, R);
293 return false;
294 }
295#endif
296
297 if (!DebugCounter::shouldExecute(GlobalISelCounter)) {
298 dbgs() << "Falling back for function " << MF.getName() << "\n";
300 return false;
301 }
302
303 // Determine if there are any calls in this machine function. Ported from
304 // SelectionDAG.
305 MachineFrameInfo &MFI = MF.getFrameInfo();
306 for (const auto &MBB : MF) {
307 if (MFI.hasCalls() && MF.hasInlineAsm())
308 break;
309
310 for (const auto &MI : MBB) {
311 if ((MI.isCall() && !MI.isReturn()) || MI.isStackAligningInlineAsm())
312 MFI.setHasCalls(true);
313 if (MI.isInlineAsm())
314 MF.setHasInlineAsm(true);
315 }
316 }
317
318 // FIXME: FinalizeISel pass calls finalizeLowering, so it's called twice.
319 auto &TLI = *MF.getSubtarget().getTargetLowering();
320 TLI.finalizeLowering(MF);
321
322 LLVM_DEBUG({
323 dbgs() << "Rules covered by selecting function: " << MF.getName() << ":";
324 for (auto RuleID : CoverageInfo.covered())
325 dbgs() << " id" << RuleID;
326 dbgs() << "\n\n";
327 });
328 CoverageInfo.emit(CoveragePrefix,
329 TLI.getTargetMachine().getTarget().getBackendName());
330
331 // If we successfully selected the function nothing is going to use the vreg
332 // types after us (otherwise MIRPrinter would need them). Make sure the types
333 // disappear.
334 MRI.clearVirtRegTypes();
335
336 // FIXME: Should we accurately track changes?
337 return true;
338}
unsigned const MachineRegisterInfo * MRI
amdgpu AMDGPU Register Bank Select
MachineBasicBlock & MBB
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
Definition: DebugCounter.h:190
#define LLVM_DEBUG(X)
Definition: Debug.h:101
Provides analysis for querying information about KnownBits during GISel passes.
IRTranslator LLVM IR MI
Select target instructions out of generic instructions
#define DEBUG_TYPE
static const std::string CoveragePrefix
Interface for Targets to specify which operations they can successfully select and how the others sho...
#define I(x, y, z)
Definition: MD5.cpp:58
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
unsigned const TargetRegisterInfo * TRI
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:59
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
iterator_range< const_covered_iterator > covered() const
bool emit(StringRef FilePrefix, StringRef BackendName) const
static bool shouldExecute(unsigned CounterName)
Definition: DebugCounter.h:87
Implements a dense probed hash-table based set.
Definition: DenseSet.h:271
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1830
bool hasOptNone() const
Do not optimize this function (-O0).
Definition: Function.h:692
virtual void setupMF(MachineFunction &mf, GISelKnownBits *kb, CodeGenCoverage *covinfo=nullptr, ProfileSummaryInfo *psi=nullptr, BlockFrequencyInfo *bfi=nullptr)
Setup per-MF executor state.
To use KnownBitsInfo analysis in a pass, KnownBitsInfo &Info = getAnalysis<GISelKnownBitsInfoAnalysis...
This pass is responsible for selecting generic machine instructions to target-specific instructions.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
ProfileSummaryInfo * PSI
BlockFrequencyInfo * BFI
virtual bool select(MachineInstr &I)=0
Select the (possibly generic) instruction I to only use target-specific opcodes.
void setTargetPassConfig(const TargetPassConfig *T)
void setRemarkEmitter(MachineOptimizationRemarkEmitter *M)
constexpr bool isValid() const
Definition: LowLevelType.h:145
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
Definition: LowLevelType.h:193
This is an alternative analysis pass to BlockFrequencyInfoWrapperPass.
static void getLazyBFIAnalysisUsage(AnalysisUsage &AU)
Helper for client passes to set up the analysis usage on behalf of this pass.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasCalls() const
Return true if the current function has any function calls.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
MachineFunctionProperties & set(Property P)
bool hasProperty(Property P) const
void setHasInlineAsm(bool B)
Set a flag that indicates that the function contains inline assembly.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
bool hasInlineAsm() const
Returns true if the function contains any inline assembly.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
unsigned size() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineFunctionProperties & getProperties() const
Get the function properties.
Representation of each machine instruction.
Definition: MachineInstr.h:69
Diagnostic information for missed-optimization remarks.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
bool hasProfileSummary() const
Returns true if profile summary is available.
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition: Register.h:84
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:91
virtual void finalizeLowering(MachineFunction &MF) const
Execute target specific actions to finalize target lowering.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
Target-Independent Code Generator Pass Configuration Options.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual InstructionSelector * getInstructionSelector() const
virtual const TargetLowering * getTargetLowering() const
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:206
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition: DenseSet.h:185
static constexpr bool isKnownGT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition: TypeSize.h:225
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition: ScopeExit.h:59
void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition: Utils.cpp:1671
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< po_iterator< T > > post_order(const T &G)
bool isPreISelGenericOptimizationHint(unsigned Opcode)
Definition: TargetOpcodes.h:42
cl::opt< bool > DisableGISelLegalityCheck
bool canReplaceReg(Register DstReg, Register SrcReg, MachineRegisterInfo &MRI)
Check if DstReg can be replaced with SrcReg depending on the register constraints.
Definition: Utils.cpp:201
void reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC, MachineOptimizationRemarkEmitter &MORE, MachineOptimizationRemarkMissed &R)
Report an ISel error as a missed optimization remark to the LLVMContext's diagnostic stream.
Definition: Utils.cpp:275
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
const MachineInstr * machineFunctionIsIllegal(const MachineFunction &MF)
Checks that MIR is fully legal, returns an illegal instruction if it's not, nullptr otherwise.
CodeGenOptLevel
Code generation optimization level.
Definition: CodeGen.h:54
void getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU)
Modify analysis usage so it preserves passes required for the SelectionDAG fallback.
Definition: Utils.cpp:1161
bool isTriviallyDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
Check whether an instruction MI is dead: it only defines dead virtual registers, and doesn't have oth...
Definition: Utils.cpp:222
#define MORE()
Definition: regcomp.c:252