LLVM  14.0.0git
AMDGPUPreLegalizerCombiner.cpp
Go to the documentation of this file.
1 //=== lib/CodeGen/GlobalISel/AMDGPUPreLegalizerCombiner.cpp ---------------===//
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 // This pass does combining of machine instructions at the generic MI level,
10 // before the legalizer.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AMDGPU.h"
15 #include "AMDGPUCombinerHelper.h"
16 #include "AMDGPULegalizerInfo.h"
17 #include "GCNSubtarget.h"
27 
28 #define DEBUG_TYPE "amdgpu-prelegalizer-combiner"
29 
30 using namespace llvm;
31 using namespace MIPatternMatch;
32 
34 protected:
39 
40 public:
42  AMDGPUCombinerHelper &Helper)
43  : B(B), MF(B.getMF()), MRI(*B.getMRI()), Helper(Helper){};
44 
46  int64_t Cmp1 = 0;
47  int64_t Cmp2 = 0;
49  };
50 
51  bool matchClampI64ToI16(MachineInstr &MI, MachineRegisterInfo &MRI,
52  MachineFunction &MF,
53  ClampI64ToI16MatchInfo &MatchInfo);
54 
55  void applyClampI64ToI16(MachineInstr &MI,
56  const ClampI64ToI16MatchInfo &MatchInfo);
57 };
58 
61  ClampI64ToI16MatchInfo &MatchInfo) {
62  assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Invalid instruction!");
63 
64  // Try to find a pattern where an i64 value should get clamped to short.
65  const LLT SrcType = MRI.getType(MI.getOperand(1).getReg());
66  if (SrcType != LLT::scalar(64))
67  return false;
68 
69  const LLT DstType = MRI.getType(MI.getOperand(0).getReg());
70  if (DstType != LLT::scalar(16))
71  return false;
72 
73  Register Base;
74 
75  auto IsApplicableForCombine = [&MatchInfo]() -> bool {
76  const auto Cmp1 = MatchInfo.Cmp1;
77  const auto Cmp2 = MatchInfo.Cmp2;
78  const auto Diff = std::abs(Cmp2 - Cmp1);
79 
80  // If the difference between both comparison values is 0 or 1, there is no
81  // need to clamp.
82  if (Diff == 0 || Diff == 1)
83  return false;
84 
85  const int64_t Min = std::numeric_limits<int16_t>::min();
86  const int64_t Max = std::numeric_limits<int16_t>::max();
87 
88  // Check if the comparison values are between SHORT_MIN and SHORT_MAX.
89  return ((Cmp2 >= Cmp1 && Cmp1 >= Min && Cmp2 <= Max) ||
90  (Cmp1 >= Cmp2 && Cmp1 <= Max && Cmp2 >= Min));
91  };
92 
93  // Try to match a combination of min / max MIR opcodes.
94  if (mi_match(MI.getOperand(1).getReg(), MRI,
95  m_GSMin(m_Reg(Base), m_ICst(MatchInfo.Cmp1)))) {
96  if (mi_match(Base, MRI,
97  m_GSMax(m_Reg(MatchInfo.Origin), m_ICst(MatchInfo.Cmp2)))) {
98  return IsApplicableForCombine();
99  }
100  }
101 
102  if (mi_match(MI.getOperand(1).getReg(), MRI,
103  m_GSMax(m_Reg(Base), m_ICst(MatchInfo.Cmp1)))) {
104  if (mi_match(Base, MRI,
105  m_GSMin(m_Reg(MatchInfo.Origin), m_ICst(MatchInfo.Cmp2)))) {
106  return IsApplicableForCombine();
107  }
108  }
109 
110  return false;
111 }
112 
113 // We want to find a combination of instructions that
114 // gets generated when an i64 gets clamped to i16.
115 // The corresponding pattern is:
116 // G_MAX / G_MAX for i16 <= G_TRUNC i64.
117 // This can be efficiently written as following:
118 // v_cvt_pk_i16_i32 v0, v0, v1
119 // v_med3_i32 v0, Clamp_Min, v0, Clamp_Max
121  MachineInstr &MI, const ClampI64ToI16MatchInfo &MatchInfo) {
122 
123  Register Src = MatchInfo.Origin;
124  assert(MI.getParent()->getParent()->getRegInfo().getType(Src) ==
125  LLT::scalar(64));
126  const LLT S32 = LLT::scalar(32);
127 
128  B.setMBB(*MI.getParent());
129  B.setInstrAndDebugLoc(MI);
130 
131  auto Unmerge = B.buildUnmerge(S32, Src);
132 
133  assert(MI.getOpcode() != AMDGPU::G_AMDGPU_CVT_PK_I16_I32);
134 
135  const LLT V2S16 = LLT::fixed_vector(2, 16);
136  auto CvtPk =
137  B.buildInstr(AMDGPU::G_AMDGPU_CVT_PK_I16_I32, {V2S16},
138  {Unmerge.getReg(0), Unmerge.getReg(1)}, MI.getFlags());
139 
140  auto MinBoundary = std::min(MatchInfo.Cmp1, MatchInfo.Cmp2);
141  auto MaxBoundary = std::max(MatchInfo.Cmp1, MatchInfo.Cmp2);
142  auto MinBoundaryDst = B.buildConstant(S32, MinBoundary);
143  auto MaxBoundaryDst = B.buildConstant(S32, MaxBoundary);
144 
145  auto Bitcast = B.buildBitcast({S32}, CvtPk);
146 
147  auto Med3 = B.buildInstr(
148  AMDGPU::G_AMDGPU_SMED3, {S32},
149  {MinBoundaryDst.getReg(0), Bitcast.getReg(0), MaxBoundaryDst.getReg(0)},
150  MI.getFlags());
151 
152  B.buildTrunc(MI.getOperand(0).getReg(), Med3);
153 
154  MI.eraseFromParent();
155 }
156 
158 protected:
161 
162 public:
164  AMDGPUCombinerHelper &Helper,
165  AMDGPUPreLegalizerCombinerHelper &PreLegalizerHelper)
166  : Helper(Helper), PreLegalizerHelper(PreLegalizerHelper) {}
167 };
168 
169 #define AMDGPUPRELEGALIZERCOMBINERHELPER_GENCOMBINERHELPER_DEPS
170 #include "AMDGPUGenPreLegalizeGICombiner.inc"
171 #undef AMDGPUPRELEGALIZERCOMBINERHELPER_GENCOMBINERHELPER_DEPS
172 
173 namespace {
174 #define AMDGPUPRELEGALIZERCOMBINERHELPER_GENCOMBINERHELPER_H
175 #include "AMDGPUGenPreLegalizeGICombiner.inc"
176 #undef AMDGPUPRELEGALIZERCOMBINERHELPER_GENCOMBINERHELPER_H
177 
178 class AMDGPUPreLegalizerCombinerInfo final : public CombinerInfo {
179  GISelKnownBits *KB;
181 
182 public:
183  AMDGPUGenPreLegalizerCombinerHelperRuleConfig GeneratedRuleCfg;
184 
185  AMDGPUPreLegalizerCombinerInfo(bool EnableOpt, bool OptSize, bool MinSize,
187  : CombinerInfo(/*AllowIllegalOps*/ true, /*ShouldLegalizeIllegal*/ false,
188  /*LegalizerInfo*/ nullptr, EnableOpt, OptSize, MinSize),
189  KB(KB), MDT(MDT) {
190  if (!GeneratedRuleCfg.parseCommandLineOption())
191  report_fatal_error("Invalid rule identifier");
192  }
193 
194  virtual bool combine(GISelChangeObserver &Observer, MachineInstr &MI,
195  MachineIRBuilder &B) const override;
196 };
197 
199  MachineInstr &MI,
200  MachineIRBuilder &B) const {
201  AMDGPUCombinerHelper Helper(Observer, B, KB, MDT);
202  AMDGPUPreLegalizerCombinerHelper PreLegalizerHelper(B, Helper);
203  AMDGPUGenPreLegalizerCombinerHelper Generated(GeneratedRuleCfg, Helper,
204  PreLegalizerHelper);
205 
206  if (Generated.tryCombineAll(Observer, MI, B))
207  return true;
208 
209  switch (MI.getOpcode()) {
210  case TargetOpcode::G_CONCAT_VECTORS:
211  return Helper.tryCombineConcatVectors(MI);
212  case TargetOpcode::G_SHUFFLE_VECTOR:
213  return Helper.tryCombineShuffleVector(MI);
214  }
215 
216  return false;
217 }
218 
219 #define AMDGPUPRELEGALIZERCOMBINERHELPER_GENCOMBINERHELPER_CPP
220 #include "AMDGPUGenPreLegalizeGICombiner.inc"
221 #undef AMDGPUPRELEGALIZERCOMBINERHELPER_GENCOMBINERHELPER_CPP
222 
223 // Pass boilerplate
224 // ================
225 
226 class AMDGPUPreLegalizerCombiner : public MachineFunctionPass {
227 public:
228  static char ID;
229 
230  AMDGPUPreLegalizerCombiner(bool IsOptNone = false);
231 
232  StringRef getPassName() const override {
233  return "AMDGPUPreLegalizerCombiner";
234  }
235 
236  bool runOnMachineFunction(MachineFunction &MF) override;
237 
238  void getAnalysisUsage(AnalysisUsage &AU) const override;
239 private:
240  bool IsOptNone;
241 };
242 } // end anonymous namespace
243 
244 void AMDGPUPreLegalizerCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
246  AU.setPreservesCFG();
250  if (!IsOptNone) {
253  }
254 
258 }
259 
260 AMDGPUPreLegalizerCombiner::AMDGPUPreLegalizerCombiner(bool IsOptNone)
261  : MachineFunctionPass(ID), IsOptNone(IsOptNone) {
262  initializeAMDGPUPreLegalizerCombinerPass(*PassRegistry::getPassRegistry());
263 }
264 
265 bool AMDGPUPreLegalizerCombiner::runOnMachineFunction(MachineFunction &MF) {
266  if (MF.getProperties().hasProperty(
267  MachineFunctionProperties::Property::FailedISel))
268  return false;
269  auto *TPC = &getAnalysis<TargetPassConfig>();
270  const Function &F = MF.getFunction();
271  bool EnableOpt =
272  MF.getTarget().getOptLevel() != CodeGenOpt::None && !skipFunction(F);
273  GISelKnownBits *KB = &getAnalysis<GISelKnownBitsAnalysis>().get(MF);
274  MachineDominatorTree *MDT =
275  IsOptNone ? nullptr : &getAnalysis<MachineDominatorTree>();
276  AMDGPUPreLegalizerCombinerInfo PCInfo(EnableOpt, F.hasOptSize(),
277  F.hasMinSize(), KB, MDT);
278  // Enable CSE.
280  getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
281  auto *CSEInfo = &Wrapper.get(TPC->getCSEConfig());
282 
283  Combiner C(PCInfo, TPC);
284  return C.combineMachineInstrs(MF, CSEInfo);
285 }
286 
288 INITIALIZE_PASS_BEGIN(AMDGPUPreLegalizerCombiner, DEBUG_TYPE,
289  "Combine AMDGPU machine instrs before legalization",
290  false, false)
293 INITIALIZE_PASS_END(AMDGPUPreLegalizerCombiner, DEBUG_TYPE,
294  "Combine AMDGPU machine instrs before legalization", false,
295  false)
296 
297 namespace llvm {
299  return new AMDGPUPreLegalizerCombiner(IsOptNone);
300 }
301 } // end namespace llvm
AMDGPUCombinerHelper
Definition: AMDGPUCombinerHelper.h:20
MIPatternMatch.h
llvm::TargetMachine::getOptLevel
CodeGenOpt::Level getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
Definition: TargetMachine.cpp:188
AMDGPUPreLegalizerCombinerHelper::matchClampI64ToI16
bool matchClampI64ToI16(MachineInstr &MI, MachineRegisterInfo &MRI, MachineFunction &MF, ClampI64ToI16MatchInfo &MatchInfo)
Definition: AMDGPUPreLegalizerCombiner.cpp:59
CombinerInfo.h
AMDGPUPreLegalizerCombinerHelperState::Helper
AMDGPUCombinerHelper & Helper
Definition: AMDGPUPreLegalizerCombiner.cpp:159
llvm::MachineFunctionProperties::hasProperty
bool hasProperty(Property P) const
Definition: MachineFunction.h:169
MI
IRTranslator LLVM IR MI
Definition: IRTranslator.cpp:105
AMDGPUPreLegalizerCombinerHelper::MRI
MachineRegisterInfo & MRI
Definition: AMDGPUPreLegalizerCombiner.cpp:37
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AllocatorList.h:23
llvm::GISelCSEAnalysisWrapperPass
The actual analysis pass wrapper.
Definition: CSEInfo.h:220
llvm::MIPatternMatch::m_Reg
operand_type_match m_Reg()
Definition: MIPatternMatch.h:152
llvm::GISelKnownBits
Definition: GISelKnownBits.h:29
llvm::MachineRegisterInfo
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Definition: MachineRegisterInfo.h:52
llvm::Function
Definition: Function.h:62
AMDGPUPreLegalizerCombinerHelper::ClampI64ToI16MatchInfo::Cmp2
int64_t Cmp2
Definition: AMDGPUPreLegalizerCombiner.cpp:47
Wrapper
amdgpu aa AMDGPU Address space based Alias Analysis Wrapper
Definition: AMDGPUAliasAnalysis.cpp:31
llvm::LegacyLegalizeActions::Bitcast
@ Bitcast
Perform the operation on a different, but equivalently sized type.
Definition: LegacyLegalizerInfo.h:54
GISelKnownBits.h
llvm::MachineFunctionPass
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Definition: MachineFunctionPass.h:30
llvm::MIPatternMatch::m_GSMax
BinaryOp_match< LHS, RHS, TargetOpcode::G_SMAX, false > m_GSMax(const LHS &L, const RHS &R)
Definition: MIPatternMatch.h:400
AMDGPUPreLegalizerCombinerHelper::ClampI64ToI16MatchInfo::Cmp1
int64_t Cmp1
Definition: AMDGPUPreLegalizerCombiner.cpp:46
llvm::getSelectionDAGFallbackAnalysisUsage
void getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU)
Modify analysis usage so it preserves passes required for the SelectionDAG fallback.
Definition: Utils.cpp:870
llvm::MIPatternMatch::m_GSMin
BinaryOp_match< LHS, RHS, TargetOpcode::G_SMIN, false > m_GSMin(const LHS &L, const RHS &R)
Definition: MIPatternMatch.h:406
llvm::CombinerInfo
Definition: CombinerInfo.h:27
llvm::MachineFunctionPass::getAnalysisUsage
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Definition: MachineFunctionPass.cpp:102
F
#define F(x, y, z)
Definition: MD5.cpp:56
llvm::LLT::fixed_vector
static LLT fixed_vector(unsigned NumElements, unsigned ScalarSizeInBits)
Get a low-level fixed-width vector of some number of elements and element width.
Definition: LowLevelTypeImpl.h:75
llvm::GISelKnownBitsAnalysis
To use KnownBitsInfo analysis in a pass, KnownBitsInfo &Info = getAnalysis<GISelKnownBitsInfoAnalysis...
Definition: GISelKnownBits.h:113
TargetMachine.h
GCNSubtarget.h
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
AMDGPUPreLegalizerCombinerHelperState::PreLegalizerHelper
AMDGPUPreLegalizerCombinerHelper & PreLegalizerHelper
Definition: AMDGPUPreLegalizerCombiner.cpp:160
AMDGPUPreLegalizerCombinerHelper::B
MachineIRBuilder & B
Definition: AMDGPUPreLegalizerCombiner.cpp:35
llvm::AnalysisUsage
Represent the analysis usage information of a pass.
Definition: PassAnalysisSupport.h:47
llvm::MachineFunction::getProperties
const MachineFunctionProperties & getProperties() const
Get the function properties.
Definition: MachineFunction.h:725
false
Definition: StackSlotColoring.cpp:142
B
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
AMDGPUPreLegalizerCombinerHelper
Definition: AMDGPUPreLegalizerCombiner.cpp:33
AMDGPUPreLegalizerCombinerHelperState
Definition: AMDGPUPreLegalizerCombiner.cpp:157
llvm::report_fatal_error
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:143
AMDGPUPreLegalizerCombinerHelper::MF
MachineFunction & MF
Definition: AMDGPUPreLegalizerCombiner.cpp:36
llvm::None
const NoneType None
Definition: None.h:23
INITIALIZE_PASS_END
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:58
llvm::TargetPassConfig
Target-Independent Code Generator Pass Configuration Options.
Definition: TargetPassConfig.h:84
Combine
Hexagon Vector Combine
Definition: HexagonVectorCombine.cpp:1524
AMDGPUMCTargetDesc.h
llvm::MachineIRBuilder
Helper class to build MachineInstr.
Definition: MachineIRBuilder.h:212
llvm::MachineInstr
Representation of each machine instruction.
Definition: MachineInstr.h:64
llvm::Combiner
Definition: Combiner.h:27
INITIALIZE_PASS_DEPENDENCY
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
AMDGPUPreLegalizerCombinerHelper::AMDGPUPreLegalizerCombinerHelper
AMDGPUPreLegalizerCombinerHelper(MachineIRBuilder &B, AMDGPUCombinerHelper &Helper)
Definition: AMDGPUPreLegalizerCombiner.cpp:41
TargetPassConfig.h
AMDGPUPreLegalizerCombinerHelper::ClampI64ToI16MatchInfo::Origin
Register Origin
Definition: AMDGPUPreLegalizerCombiner.cpp:48
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
AMDGPUPreLegalizerCombinerHelper::ClampI64ToI16MatchInfo
Definition: AMDGPUPreLegalizerCombiner.cpp:45
llvm::MachineFunction
Definition: MachineFunction.h:234
CombinerHelper.h
llvm::min
Expected< ExpressionValue > min(const ExpressionValue &Lhs, const ExpressionValue &Rhs)
Definition: FileCheck.cpp:357
AMDGPUPreLegalizerCombinerHelper::Helper
AMDGPUCombinerHelper & Helper
Definition: AMDGPUPreLegalizerCombiner.cpp:38
AMDGPUPreLegalizerCombinerHelper::applyClampI64ToI16
void applyClampI64ToI16(MachineInstr &MI, const ClampI64ToI16MatchInfo &MatchInfo)
Definition: AMDGPUPreLegalizerCombiner.cpp:120
llvm::AnalysisUsage::setPreservesCFG
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:253
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:57
AMDGPU.h
llvm::AnalysisUsage::addPreserved
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Definition: PassAnalysisSupport.h:98
Combiner.h
DEBUG_TYPE
#define DEBUG_TYPE
Definition: AMDGPUPreLegalizerCombiner.cpp:28
llvm::GISelChangeObserver
Abstract class that contains various methods for clients to notify about changes.
Definition: GISelChangeObserver.h:29
MRI
unsigned const MachineRegisterInfo * MRI
Definition: AArch64AdvSIMDScalarPass.cpp:105
llvm::Register
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
llvm::MachineFunction::getFunction
Function & getFunction()
Return the LLVM function that this machine code represents.
Definition: MachineFunction.h:600
llvm::MachineFunction::getTarget
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Definition: MachineFunction.h:630
legalization
Combine AMDGPU machine instrs before legalization
Definition: AMDGPUPreLegalizerCombiner.cpp:294
llvm::GISelCSEAnalysisWrapper
Simple wrapper that does the following.
Definition: CSEInfo.h:202
llvm::MIPatternMatch::m_ICst
ConstantMatch m_ICst(int64_t &Cst)
Definition: MIPatternMatch.h:74
llvm::initializeAMDGPUPreLegalizerCombinerPass
void initializeAMDGPUPreLegalizerCombinerPass(PassRegistry &)
AMDGPULegalizerInfo.h
llvm::MachineRegisterInfo::getType
LLT getType(Register Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register.
Definition: MachineRegisterInfo.h:732
AMDGPUCombinerHelper.h
llvm::createAMDGPUPreLegalizeCombiner
FunctionPass * createAMDGPUPreLegalizeCombiner(bool IsOptNone)
Definition: AMDGPUPreLegalizerCombiner.cpp:298
llvm::max
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:340
AMDGPUPreLegalizerCombinerHelperState::AMDGPUPreLegalizerCombinerHelperState
AMDGPUPreLegalizerCombinerHelperState(AMDGPUCombinerHelper &Helper, AMDGPUPreLegalizerCombinerHelper &PreLegalizerHelper)
Definition: AMDGPUPreLegalizerCombiner.cpp:163
llvm::FunctionPass
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
llvm::MIPatternMatch::mi_match
bool mi_match(Reg R, const MachineRegisterInfo &MRI, Pattern &&P)
Definition: MIPatternMatch.h:24
llvm::AnalysisUsage::addRequired
AnalysisUsage & addRequired()
Definition: PassAnalysisSupport.h:75
llvm::MachineDominatorTree
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
Definition: MachineDominators.h:46
combine
vector combine
Definition: VectorCombine.cpp:1217
llvm::LLT::scalar
static LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
Definition: LowLevelTypeImpl.h:43
llvm::abs
APFloat abs(APFloat X)
Returns the absolute value of the argument.
Definition: APFloat.h:1282
INITIALIZE_PASS_BEGIN
INITIALIZE_PASS_BEGIN(AMDGPUPreLegalizerCombiner, DEBUG_TYPE, "Combine AMDGPU machine instrs before legalization", false, false) INITIALIZE_PASS_END(AMDGPUPreLegalizerCombiner
llvm::sampleprof::Base
@ Base
Definition: Discriminator.h:58
machine
coro Split coroutine into a set of functions driving its state machine
Definition: CoroSplit.cpp:2275
MachineDominators.h
llvm::Intrinsic::ID
unsigned ID
Definition: TargetTransformInfo.h:38
llvm::LLT
Definition: LowLevelTypeImpl.h:40