LLVM 20.0.0git
SPIRVPreLegalizerCombiner.cpp
Go to the documentation of this file.
1
2//===-- SPIRVPreLegalizerCombiner.cpp - combine legalization ----*- C++ -*-===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass does combining of machine instructions at the generic MI level,
11// before the legalizer.
12//
13//===----------------------------------------------------------------------===//
14
15#include "SPIRV.h"
16#include "SPIRVTargetMachine.h"
17#include "llvm/ADT/STLExtras.h"
35#include "llvm/IR/IntrinsicsSPIRV.h"
36#include "llvm/Support/Debug.h"
37
38#define GET_GICOMBINER_DEPS
39#include "SPIRVGenPreLegalizeGICombiner.inc"
40#undef GET_GICOMBINER_DEPS
41
42#define DEBUG_TYPE "spirv-prelegalizer-combiner"
43
44using namespace llvm;
45using namespace MIPatternMatch;
46
47namespace {
48
49#define GET_GICOMBINER_TYPES
50#include "SPIRVGenPreLegalizeGICombiner.inc"
51#undef GET_GICOMBINER_TYPES
52
53/// This match is part of a combine that
54/// rewrites length(X - Y) to distance(X, Y)
55/// (f32 (g_intrinsic length
56/// (g_fsub (vXf32 X) (vXf32 Y))))
57/// ->
58/// (f32 (g_intrinsic distance
59/// (vXf32 X) (vXf32 Y)))
60///
61bool matchLengthToDistance(MachineInstr &MI, MachineRegisterInfo &MRI) {
62 if (MI.getOpcode() != TargetOpcode::G_INTRINSIC ||
63 cast<GIntrinsic>(MI).getIntrinsicID() != Intrinsic::spv_length)
64 return false;
65
66 // First operand of MI is `G_INTRINSIC` so start at operand 2.
67 Register SubReg = MI.getOperand(2).getReg();
68 MachineInstr *SubInstr = MRI.getVRegDef(SubReg);
69 if (!SubInstr || SubInstr->getOpcode() != TargetOpcode::G_FSUB)
70 return false;
71
72 return true;
73}
74void applySPIRVDistance(MachineInstr &MI, MachineRegisterInfo &MRI,
76
77 // Extract the operands for X and Y from the match criteria.
78 Register SubDestReg = MI.getOperand(2).getReg();
79 MachineInstr *SubInstr = MRI.getVRegDef(SubDestReg);
80 Register SubOperand1 = SubInstr->getOperand(1).getReg();
81 Register SubOperand2 = SubInstr->getOperand(2).getReg();
82
83 // Remove the original `spv_length` instruction.
84
85 Register ResultReg = MI.getOperand(0).getReg();
86 DebugLoc DL = MI.getDebugLoc();
87 MachineBasicBlock &MBB = *MI.getParent();
88 MachineBasicBlock::iterator InsertPt = MI.getIterator();
89
90 // Build the `spv_distance` intrinsic.
91 MachineInstrBuilder NewInstr =
92 BuildMI(MBB, InsertPt, DL, B.getTII().get(TargetOpcode::G_INTRINSIC));
93 NewInstr
94 .addDef(ResultReg) // Result register
95 .addIntrinsicID(Intrinsic::spv_distance) // Intrinsic ID
96 .addUse(SubOperand1) // Operand X
97 .addUse(SubOperand2); // Operand Y
98
99 auto RemoveAllUses = [&](Register Reg) {
101 for (auto &UseMI : MRI.use_instructions(Reg))
102 UsesToErase.push_back(&UseMI);
103
104 // calling eraseFromParent to early invalidates the iterator.
105 for (auto *MIToErase : UsesToErase)
106 MIToErase->eraseFromParent();
107 };
108 RemoveAllUses(SubDestReg); // remove all uses of FSUB Result
109 SubInstr->eraseFromParent(); // remove FSUB instruction
110}
111
112class SPIRVPreLegalizerCombinerImpl : public Combiner {
113protected:
114 const CombinerHelper Helper;
115 const SPIRVPreLegalizerCombinerImplRuleConfig &RuleConfig;
116 const SPIRVSubtarget &STI;
117
118public:
119 SPIRVPreLegalizerCombinerImpl(
120 MachineFunction &MF, CombinerInfo &CInfo, const TargetPassConfig *TPC,
121 GISelKnownBits &KB, GISelCSEInfo *CSEInfo,
122 const SPIRVPreLegalizerCombinerImplRuleConfig &RuleConfig,
123 const SPIRVSubtarget &STI, MachineDominatorTree *MDT,
124 const LegalizerInfo *LI);
125
126 static const char *getName() { return "SPIRVPreLegalizerCombiner"; }
127
128 bool tryCombineAll(MachineInstr &I) const override;
129
130 bool tryCombineAllImpl(MachineInstr &I) const;
131
132private:
133#define GET_GICOMBINER_CLASS_MEMBERS
134#include "SPIRVGenPreLegalizeGICombiner.inc"
135#undef GET_GICOMBINER_CLASS_MEMBERS
136};
137
138#define GET_GICOMBINER_IMPL
139#include "SPIRVGenPreLegalizeGICombiner.inc"
140#undef GET_GICOMBINER_IMPL
141
142SPIRVPreLegalizerCombinerImpl::SPIRVPreLegalizerCombinerImpl(
143 MachineFunction &MF, CombinerInfo &CInfo, const TargetPassConfig *TPC,
144 GISelKnownBits &KB, GISelCSEInfo *CSEInfo,
145 const SPIRVPreLegalizerCombinerImplRuleConfig &RuleConfig,
146 const SPIRVSubtarget &STI, MachineDominatorTree *MDT,
147 const LegalizerInfo *LI)
148 : Combiner(MF, CInfo, TPC, &KB, CSEInfo),
149 Helper(Observer, B, /*IsPreLegalize*/ true, &KB, MDT, LI),
150 RuleConfig(RuleConfig), STI(STI),
152#include "SPIRVGenPreLegalizeGICombiner.inc"
154{
155}
156
157bool SPIRVPreLegalizerCombinerImpl::tryCombineAll(MachineInstr &MI) const {
158 return tryCombineAllImpl(MI);
159}
160
161// Pass boilerplate
162// ================
163
164class SPIRVPreLegalizerCombiner : public MachineFunctionPass {
165public:
166 static char ID;
167
168 SPIRVPreLegalizerCombiner();
169
170 StringRef getPassName() const override { return "SPIRVPreLegalizerCombiner"; }
171
172 bool runOnMachineFunction(MachineFunction &MF) override;
173
174 void getAnalysisUsage(AnalysisUsage &AU) const override;
175
176private:
177 SPIRVPreLegalizerCombinerImplRuleConfig RuleConfig;
178};
179
180} // end anonymous namespace
181
182void SPIRVPreLegalizerCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
184 AU.setPreservesCFG();
191}
192
193SPIRVPreLegalizerCombiner::SPIRVPreLegalizerCombiner()
196
197 if (!RuleConfig.parseCommandLineOption())
198 report_fatal_error("Invalid rule identifier");
199}
200
201bool SPIRVPreLegalizerCombiner::runOnMachineFunction(MachineFunction &MF) {
202 if (MF.getProperties().hasProperty(
203 MachineFunctionProperties::Property::FailedISel))
204 return false;
205 auto &TPC = getAnalysis<TargetPassConfig>();
206
208 const auto *LI = ST.getLegalizerInfo();
209
210 const Function &F = MF.getFunction();
211 bool EnableOpt =
212 MF.getTarget().getOptLevel() != CodeGenOptLevel::None && !skipFunction(F);
213 GISelKnownBits *KB = &getAnalysis<GISelKnownBitsAnalysis>().get(MF);
215 &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
216 CombinerInfo CInfo(/*AllowIllegalOps*/ true, /*ShouldLegalizeIllegal*/ false,
217 /*LegalizerInfo*/ nullptr, EnableOpt, F.hasOptSize(),
218 F.hasMinSize());
219 // Disable fixed-point iteration to reduce compile-time
220 CInfo.MaxIterations = 1;
221 CInfo.ObserverLvl = CombinerInfo::ObserverLevel::SinglePass;
222 // This is the first Combiner, so the input IR might contain dead
223 // instructions.
224 CInfo.EnableFullDCE = false;
225 SPIRVPreLegalizerCombinerImpl Impl(MF, CInfo, &TPC, *KB, /*CSEInfo*/ nullptr,
226 RuleConfig, ST, MDT, LI);
227 return Impl.combineMachineInstrs();
228}
229
230char SPIRVPreLegalizerCombiner::ID = 0;
231INITIALIZE_PASS_BEGIN(SPIRVPreLegalizerCombiner, DEBUG_TYPE,
232 "Combine SPIRV machine instrs before legalization", false,
233 false)
236INITIALIZE_PASS_END(SPIRVPreLegalizerCombiner, DEBUG_TYPE,
237 "Combine SPIRV machine instrs before legalization", false,
238 false)
239
240namespace llvm {
242 return new SPIRVPreLegalizerCombiner();
243}
244} // end namespace llvm
unsigned SubReg
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
basic Basic Alias true
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Provides analysis for continuously CSEing during GISel passes.
This file implements a version of MachineIRBuilder which CSEs insts within a MachineBasicBlock.
This contains common combine transformations that may be used in a combine pass,or by the target else...
Option class for Targets to specify which operations are combined how and when.
This contains the base class for all Combiners generated by TableGen.
This contains common code to allow clients to notify changes to machine instr.
Provides analysis for querying information about KnownBits during GISel passes.
Declares convenience wrapper classes for interpreting MachineInstr instances as specific generic oper...
Hexagon Vector Combine
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Contains matchers for matching SSA Machine Instructions.
This file declares the MachineIRBuilder class.
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:57
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
static StringRef getName(Value *V)
#define GET_GICOMBINER_CONSTRUCTOR_INITS
#define DEBUG_TYPE
Combine SPIRV machine instrs before legalization
This file contains some templates that are useful if you are working with the STL at all.
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.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:256
Combiner implementation.
Definition: Combiner.h:34
virtual bool tryCombineAll(MachineInstr &I) const =0
A debug info location.
Definition: DebugLoc.h:33
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
The CSE Analysis object.
Definition: CSEInfo.h:70
To use KnownBitsInfo analysis in a pass, KnownBitsInfo &Info = getAnalysis<GISelKnownBitsInfoAnalysis...
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
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.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
bool hasProperty(Property P) const
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineFunctionProperties & getProperties() const
Get the function properties.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Helper class to build MachineInstr.
const MachineInstrBuilder & addIntrinsicID(Intrinsic::ID ID) const
const MachineInstrBuilder & addUse(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addDef(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
Definition: MachineInstr.h:69
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:575
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:585
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
Target-Independent Code Generator Pass Configuration Options.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
Reg
All possible values of the reg field in the ModR/M byte.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
void initializeSPIRVPreLegalizerCombinerPass(PassRegistry &)
FunctionPass * createSPIRVPreLegalizerCombiner()
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
void getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU)
Modify analysis usage so it preserves passes required for the SelectionDAG fallback.
Definition: Utils.cpp:1168
auto instrs(const MachineBasicBlock &BB)