LLVM 24.0.0git
RISCVPostLegalizerCombiner.cpp
Go to the documentation of this file.
1//=== RISCVPostLegalizerCombiner.cpp --------------------------*- C++ -*-===//
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///
9/// \file
10/// Post-legalization combines on generic MachineInstrs.
11///
12/// The combines here must preserve instruction legality.
13///
14/// Combines which don't rely on instruction legality should go in the
15/// RISCVPreLegalizerCombiner.
16///
17//===----------------------------------------------------------------------===//
18
19#include "RISCV.h"
20#include "RISCVTargetMachine.h"
34#include "llvm/IR/Analysis.h"
37
38#define GET_GICOMBINER_DEPS
39#include "RISCVGenPostLegalizeGICombiner.inc"
40#undef GET_GICOMBINER_DEPS
41
42#define DEBUG_TYPE "riscv-postlegalizer-combiner"
43
44using namespace llvm;
45using namespace MIPatternMatch;
46
47namespace {
48
49#define GET_GICOMBINER_TYPES
50#include "RISCVGenPostLegalizeGICombiner.inc"
51#undef GET_GICOMBINER_TYPES
52
53/// Match: G_STORE (G_FCONSTANT +0.0), addr
54/// Return the source vreg in MatchInfo if matched.
55bool matchFoldFPZeroStore(MachineInstr &MI, MachineRegisterInfo &MRI,
56 const RISCVSubtarget &STI, Register &MatchInfo) {
57 if (MI.getOpcode() != TargetOpcode::G_STORE)
58 return false;
59
60 Register SrcReg = MI.getOperand(0).getReg();
61 if (!SrcReg.isVirtual())
62 return false;
63
64 if (!mi_match(SrcReg, MRI, m_PosZeroFP()))
65 return false;
66
67 unsigned ValBits = MRI.getType(SrcReg).getSizeInBits();
68 if ((ValBits == 16 && !STI.hasStdExtZfh()) ||
69 (ValBits == 32 && !STI.hasStdExtF()) ||
70 (ValBits == 64 && (!STI.hasStdExtD() || !STI.is64Bit())))
71 return false;
72
73 MatchInfo = SrcReg;
74 return true;
75}
76
77/// Apply: rewrite to G_STORE (G_CONSTANT 0 [XLEN]), addr
78void applyFoldFPZeroStore(MachineInstr &MI, MachineRegisterInfo &MRI,
80 Register &MatchInfo) {
81 const unsigned XLen = STI.getXLen();
82
83 auto Zero = B.buildConstant(LLT::integer(XLen), 0);
84 MI.getOperand(0).setReg(Zero.getReg(0));
85
86 MachineInstr *Def = MRI.getVRegDef(MatchInfo);
87 if (Def && MRI.use_nodbg_empty(MatchInfo))
88 Def->eraseFromParent();
89
90#ifndef NDEBUG
91 unsigned ValBits = MRI.getType(MatchInfo).getSizeInBits();
92 LLVM_DEBUG(dbgs() << formatv("[{0}] Fold FP zero store -> int zero "
93 "(XLEN={1}, ValBits={2}):\n {3}\n",
94 DEBUG_TYPE, XLen, ValBits, MI));
95#endif
96}
97
98// Match (X << (8 - Y)) - (X >> Y), where only bit Y in each byte of X
99// can be nonzero. For Y == 0 the right operand is X itself.
100bool matchSubShiftsToOrcB(MachineInstr &MI, MachineRegisterInfo &MRI,
101 const RISCVSubtarget &STI, GISelValueTracking &VT,
102 Register &MatchInfo) {
103 if (!STI.hasStdExtZbb())
104 return false;
105
106 LLT Ty = MRI.getType(MI.getOperand(0).getReg());
107 if (Ty != LLT::scalar(STI.getXLen()))
108 return false;
109
110 Register LHS = MI.getOperand(1).getReg();
111 Register RHS = MI.getOperand(2).getReg();
112 Register Src;
113 int64_t LeftShift;
114 if (!mi_match(LHS, MRI, m_GShl(m_Reg(Src), m_ICst(LeftShift))) ||
115 LeftShift < 1 || LeftShift > 8 || MRI.getType(Src) != Ty)
116 return false;
117
118 unsigned RightShift = 8 - LeftShift;
119 if (RightShift == 0) {
120 if (RHS != Src)
121 return false;
122 } else if (!mi_match(
123 RHS, MRI,
124 m_GLShr(m_SpecificReg(Src), m_SpecificICst(RightShift)))) {
125 return false;
126 }
127
128 // At least one shift must disappear to make the replacement profitable.
129 if (!MRI.hasOneNonDBGUse(LHS) &&
130 (RightShift == 0 || !MRI.hasOneNonDBGUse(RHS)))
131 return false;
132
133 APInt Mask = APInt::getSplat(STI.getXLen(), APInt(8, 1U << RightShift));
134 if (!VT.maskedValueIsZero(Src, ~Mask))
135 return false;
136
137 MatchInfo = Src;
138 return true;
139}
140
141void applySubShiftsToOrcB(MachineInstr &MI, MachineIRBuilder &B, Register Src) {
142 // The Zbb predicate and native XLEN type make G_ORC_B legal here.
143 // Leave dead shifts to the combiner's DCE so other users remain intact.
144 B.buildInstr(RISCV::G_ORC_B, {MI.getOperand(0)}, {Src});
145 MI.eraseFromParent();
146}
147
148class RISCVPostLegalizerCombinerImpl : public Combiner {
149protected:
150 const CombinerHelper Helper;
151 const RISCVPostLegalizerCombinerImplRuleConfig &RuleConfig;
152 const RISCVSubtarget &STI;
153
154public:
155 RISCVPostLegalizerCombinerImpl(
156 MachineFunction &MF, CombinerInfo &CInfo, GISelValueTracking &VT,
157 GISelCSEInfo *CSEInfo,
158 const RISCVPostLegalizerCombinerImplRuleConfig &RuleConfig,
159 const RISCVSubtarget &STI, MachineDominatorTree *MDT,
160 const LegalizerInfo *LI);
161
162 static const char *getName() { return "RISCVPostLegalizerCombiner"; }
163
164 bool tryCombineAll(MachineInstr &I) const override;
165
166private:
167#define GET_GICOMBINER_CLASS_MEMBERS
168#include "RISCVGenPostLegalizeGICombiner.inc"
169#undef GET_GICOMBINER_CLASS_MEMBERS
170};
171
172#define GET_GICOMBINER_IMPL
173#include "RISCVGenPostLegalizeGICombiner.inc"
174#undef GET_GICOMBINER_IMPL
175
176RISCVPostLegalizerCombinerImpl::RISCVPostLegalizerCombinerImpl(
178 GISelCSEInfo *CSEInfo,
179 const RISCVPostLegalizerCombinerImplRuleConfig &RuleConfig,
180 const RISCVSubtarget &STI, MachineDominatorTree *MDT,
181 const LegalizerInfo *LI)
182 : Combiner(MF, CInfo, &VT, CSEInfo),
183 Helper(Observer, B, /*IsPreLegalize*/ false, &VT, MDT, LI),
184 RuleConfig(RuleConfig), STI(STI),
186#include "RISCVGenPostLegalizeGICombiner.inc"
188{
189}
190
191class RISCVPostLegalizerCombinerLegacy : public MachineFunctionPass {
192public:
193 static char ID;
194
195 RISCVPostLegalizerCombinerLegacy();
196
197 StringRef getPassName() const override {
198 return "RISCVPostLegalizerCombiner";
199 }
200
201 bool runOnMachineFunction(MachineFunction &MF) override;
202 void getAnalysisUsage(AnalysisUsage &AU) const override;
203};
204} // end anonymous namespace
205
206void RISCVPostLegalizerCombinerLegacy::getAnalysisUsage(
207 AnalysisUsage &AU) const {
209 AU.setPreservesCFG();
217}
218
219RISCVPostLegalizerCombinerLegacy::RISCVPostLegalizerCombinerLegacy()
220 : MachineFunctionPass(ID) {}
221
222static bool
224 function_ref<bool()> ShouldSkip,
227 function_ref<GISelCSEInfo *()> GetCSEInfo) {
228 if (MF.getProperties().hasFailedISel())
229 return false;
230 assert(MF.getProperties().hasLegalized() && "Expected a legalized function?");
231 const Function &F = MF.getFunction();
232 bool EnableOpt =
233 MF.getTarget().getOptLevel() != CodeGenOptLevel::None && !ShouldSkip();
234
235 RISCVPostLegalizerCombinerImplRuleConfig RuleConfig;
236 if (!RuleConfig.parseCommandLineOption())
237 reportFatalUsageError("Invalid rule identifier");
238
240 const auto *LI = ST.getLegalizerInfo();
241
242 GISelValueTracking *VT = GetVT();
243 MachineDominatorTree *MDT = GetMDT();
244 GISelCSEInfo *CSEInfo = GetCSEInfo();
245
246 CombinerInfo CInfo(/*AllowIllegalOps*/ true, /*ShouldLegalizeIllegal*/ false,
247 /*LegalizerInfo*/ nullptr, EnableOpt, F.hasOptSize(),
248 F.hasMinSize());
249 RISCVPostLegalizerCombinerImpl Impl(MF, CInfo, *VT, CSEInfo, RuleConfig, ST,
250 MDT, LI);
251 return Impl.combineMachineInstrs();
252}
253
254char RISCVPostLegalizerCombinerLegacy::ID = 0;
255INITIALIZE_PASS_BEGIN(RISCVPostLegalizerCombinerLegacy, DEBUG_TYPE,
256 "Combine RISC-V MachineInstrs after legalization", false,
257 false)
260INITIALIZE_PASS_END(RISCVPostLegalizerCombinerLegacy, DEBUG_TYPE,
261 "Combine RISC-V MachineInstrs after legalization", false,
262 false)
263
265 return new RISCVPostLegalizerCombinerLegacy();
266}
267
268bool RISCVPostLegalizerCombinerLegacy::runOnMachineFunction(
269 MachineFunction &MF) {
271 MF, [&]() { return skipFunction(MF.getFunction()); },
272 [&]() {
273 return &getAnalysis<GISelValueTrackingAnalysisLegacy>().get(MF);
274 },
275 [&]() {
276 return &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
277 },
278 [&]() {
279 TargetPassConfig *TPC = &getAnalysis<TargetPassConfig>();
281 getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
282 return &Wrapper.get(TPC->getCSEConfig());
283 });
284}
285
290 MF,
291 [&]() {
292 return MF.getFunction().hasOptNone() ||
294 },
295 [&]() { return &MFAM.getResult<GISelValueTrackingAnalysis>(MF); },
296 [&]() { return &MFAM.getResult<MachineDominatorTreeAnalysis>(MF); },
297 [&]() { return MFAM.getResult<GISelCSEAnalysis>(MF).get(); });
300 .preserve<GISelValueTrackingAnalysis>()
301 .preserve<GISelCSEAnalysis>()
303}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define GET_GICOMBINER_CONSTRUCTOR_INITS
amdgpu aa AMDGPU Address space based Alias Analysis Wrapper
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Provides analysis for continuously CSEing during GISel passes.
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.
Provides analysis for querying information about KnownBits during GISel passes.
#define DEBUG_TYPE
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Contains matchers for matching SSA Machine Instructions.
This file declares the MachineIRBuilder class.
static bool runCombinerOnMachineFunction(MachineFunction &MF, bool IsOptNone, function_ref< bool()> ShouldSkip, function_ref< GISelValueTracking *()> GetVT, function_ref< MachineDominatorTree *()> GetMDT)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static StringRef getName(Value *V)
MachineRegisterInfo & MRI
static bool runCombinerOnMachineFunction(MachineFunction &MF, function_ref< bool()> ShouldSkip, function_ref< GISelValueTracking *()> GetVT, function_ref< MachineDominatorTree *()> GetMDT, function_ref< GISelCSEInfo *()> GetCSEInfo)
#define LLVM_DEBUG(...)
Definition Debug.h:119
Target-Independent Code Generator Pass Configuration Options pass.
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:648
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
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.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Combiner implementation.
Definition Combiner.h:33
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
bool hasOptNone() const
Do not optimize this function (-O0).
Definition Function.h:686
The actual analysis pass wrapper.
Definition CSEInfo.h:243
Simple wrapper that does the following.
Definition CSEInfo.h:213
The CSE Analysis object.
Definition CSEInfo.h:72
To use KnownBitsInfo analysis in a pass, KnownBitsInfo &Info = getAnalysis<GISelValueTrackingInfoAnal...
bool maskedValueIsZero(Register Val, const APInt &Mask)
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
static LLT integer(unsigned SizeInBits)
Analysis pass which computes a MachineDominatorTree.
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...
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.
Representation of each machine instruction.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition Pass.cpp:87
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
unsigned getXLen() const
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
Target-Independent Code Generator Pass Configuration Options.
virtual std::unique_ptr< CSEConfigBase > getCSEConfig() const
Returns the CSEConfig object to use for the current optimization level.
An efficient, type-erasing, non-owning reference to a callable.
Pass manager infrastructure for declaring and invalidating analyses.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
operand_type_match m_Reg()
SpecificConstantMatch m_SpecificICst(const APInt &RequestedValue)
Matches a constant equal to RequestedValue.
ConstantMatch< APInt > m_ICst(APInt &Cst)
auto m_PosZeroFP()
Matches a floating-point positive zero.
bool mi_match(Reg R, const MachineRegisterInfo &MRI, Pattern &&P)
SpecificRegisterMatch m_SpecificReg(Register RequestedReg)
Matches a register only if it is equal to RequestedReg.
BinaryOp_match< LHS, RHS, TargetOpcode::G_SHL, false > m_GShl(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, TargetOpcode::G_LSHR, false > m_GLShr(const LHS &L, const RHS &R)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
This is an optimization pass for GlobalISel generic memory operations.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
FunctionPass * createRISCVPostLegalizerCombinerLegacyPass()
LLVM_ABI void getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU)
Modify analysis usage so it preserves passes required for the SelectionDAG fallback.
Definition Utils.cpp:1297
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177