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::scalar(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
98class RISCVPostLegalizerCombinerImpl : public Combiner {
99protected:
100 const CombinerHelper Helper;
101 const RISCVPostLegalizerCombinerImplRuleConfig &RuleConfig;
102 const RISCVSubtarget &STI;
103
104public:
105 RISCVPostLegalizerCombinerImpl(
106 MachineFunction &MF, CombinerInfo &CInfo, GISelValueTracking &VT,
107 GISelCSEInfo *CSEInfo,
108 const RISCVPostLegalizerCombinerImplRuleConfig &RuleConfig,
109 const RISCVSubtarget &STI, MachineDominatorTree *MDT,
110 const LegalizerInfo *LI);
111
112 static const char *getName() { return "RISCVPostLegalizerCombiner"; }
113
114 bool tryCombineAll(MachineInstr &I) const override;
115
116private:
117#define GET_GICOMBINER_CLASS_MEMBERS
118#include "RISCVGenPostLegalizeGICombiner.inc"
119#undef GET_GICOMBINER_CLASS_MEMBERS
120};
121
122#define GET_GICOMBINER_IMPL
123#include "RISCVGenPostLegalizeGICombiner.inc"
124#undef GET_GICOMBINER_IMPL
125
126RISCVPostLegalizerCombinerImpl::RISCVPostLegalizerCombinerImpl(
128 GISelCSEInfo *CSEInfo,
129 const RISCVPostLegalizerCombinerImplRuleConfig &RuleConfig,
130 const RISCVSubtarget &STI, MachineDominatorTree *MDT,
131 const LegalizerInfo *LI)
132 : Combiner(MF, CInfo, &VT, CSEInfo),
133 Helper(Observer, B, /*IsPreLegalize*/ false, &VT, MDT, LI),
134 RuleConfig(RuleConfig), STI(STI),
136#include "RISCVGenPostLegalizeGICombiner.inc"
138{
139}
140
141class RISCVPostLegalizerCombinerLegacy : public MachineFunctionPass {
142public:
143 static char ID;
144
145 RISCVPostLegalizerCombinerLegacy();
146
147 StringRef getPassName() const override {
148 return "RISCVPostLegalizerCombiner";
149 }
150
151 bool runOnMachineFunction(MachineFunction &MF) override;
152 void getAnalysisUsage(AnalysisUsage &AU) const override;
153};
154} // end anonymous namespace
155
156void RISCVPostLegalizerCombinerLegacy::getAnalysisUsage(
157 AnalysisUsage &AU) const {
159 AU.setPreservesCFG();
167}
168
169RISCVPostLegalizerCombinerLegacy::RISCVPostLegalizerCombinerLegacy()
170 : MachineFunctionPass(ID) {}
171
172static bool
174 function_ref<bool()> ShouldSkip,
177 function_ref<GISelCSEInfo *()> GetCSEInfo) {
178 if (MF.getProperties().hasFailedISel())
179 return false;
180 assert(MF.getProperties().hasLegalized() && "Expected a legalized function?");
181 const Function &F = MF.getFunction();
182 bool EnableOpt =
183 MF.getTarget().getOptLevel() != CodeGenOptLevel::None && !ShouldSkip();
184
185 RISCVPostLegalizerCombinerImplRuleConfig RuleConfig;
186 if (!RuleConfig.parseCommandLineOption())
187 reportFatalUsageError("Invalid rule identifier");
188
190 const auto *LI = ST.getLegalizerInfo();
191
192 GISelValueTracking *VT = GetVT();
193 MachineDominatorTree *MDT = GetMDT();
194 GISelCSEInfo *CSEInfo = GetCSEInfo();
195
196 CombinerInfo CInfo(/*AllowIllegalOps*/ true, /*ShouldLegalizeIllegal*/ false,
197 /*LegalizerInfo*/ nullptr, EnableOpt, F.hasOptSize(),
198 F.hasMinSize());
199 RISCVPostLegalizerCombinerImpl Impl(MF, CInfo, *VT, CSEInfo, RuleConfig, ST,
200 MDT, LI);
201 return Impl.combineMachineInstrs();
202}
203
204char RISCVPostLegalizerCombinerLegacy::ID = 0;
205INITIALIZE_PASS_BEGIN(RISCVPostLegalizerCombinerLegacy, DEBUG_TYPE,
206 "Combine RISC-V MachineInstrs after legalization", false,
207 false)
210INITIALIZE_PASS_END(RISCVPostLegalizerCombinerLegacy, DEBUG_TYPE,
211 "Combine RISC-V MachineInstrs after legalization", false,
212 false)
213
215 return new RISCVPostLegalizerCombinerLegacy();
216}
217
218bool RISCVPostLegalizerCombinerLegacy::runOnMachineFunction(
219 MachineFunction &MF) {
221 MF, [&]() { return skipFunction(MF.getFunction()); },
222 [&]() {
223 return &getAnalysis<GISelValueTrackingAnalysisLegacy>().get(MF);
224 },
225 [&]() {
226 return &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
227 },
228 [&]() {
229 TargetPassConfig *TPC = &getAnalysis<TargetPassConfig>();
231 getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
232 return &Wrapper.get(TPC->getCSEConfig());
233 });
234}
235
240 MF,
241 [&]() {
242 return MF.getFunction().hasOptNone() ||
244 },
245 [&]() { return &MFAM.getResult<GISelValueTrackingAnalysis>(MF); },
246 [&]() { return &MFAM.getResult<MachineDominatorTreeAnalysis>(MF); },
247 [&]() { return MFAM.getResult<GISelCSEAnalysis>(MF).get(); });
250 .preserve<GISelValueTrackingAnalysis>()
251 .preserve<GISelCSEAnalysis>()
253}
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.
#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.
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:244
Simple wrapper that does the following.
Definition CSEInfo.h:214
The CSE Analysis object.
Definition CSEInfo.h:72
To use KnownBitsInfo analysis in a pass, KnownBitsInfo &Info = getAnalysis<GISelValueTrackingInfoAnal...
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
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.
auto m_PosZeroFP()
Matches a floating-point positive zero.
bool mi_match(Reg R, const MachineRegisterInfo &MRI, Pattern &&P)
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:1156
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177