LLVM  13.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 "AMDGPULegalizerInfo.h"
16 #include "GCNSubtarget.h"
26 
27 #define DEBUG_TYPE "amdgpu-prelegalizer-combiner"
28 
29 using namespace llvm;
30 using namespace MIPatternMatch;
31 
33 protected:
38 
39 public:
41  : B(B), MF(B.getMF()), MRI(*B.getMRI()), Helper(Helper){};
42 
44  int64_t Cmp1 = 0;
45  int64_t Cmp2 = 0;
47  };
48 
49  bool matchClampI64ToI16(MachineInstr &MI, MachineRegisterInfo &MRI,
50  MachineFunction &MF,
51  ClampI64ToI16MatchInfo &MatchInfo);
52 
53  void applyClampI64ToI16(MachineInstr &MI,
54  const ClampI64ToI16MatchInfo &MatchInfo);
55 };
56 
59  ClampI64ToI16MatchInfo &MatchInfo) {
60  assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Invalid instruction!");
61 
62  // Try to find a pattern where an i64 value should get clamped to short.
63  const LLT SrcType = MRI.getType(MI.getOperand(1).getReg());
64  if (SrcType != LLT::scalar(64))
65  return false;
66 
67  const LLT DstType = MRI.getType(MI.getOperand(0).getReg());
68  if (DstType != LLT::scalar(16))
69  return false;
70 
71  Register Base;
72 
73  auto IsApplicableForCombine = [&MatchInfo]() -> bool {
74  const auto Cmp1 = MatchInfo.Cmp1;
75  const auto Cmp2 = MatchInfo.Cmp2;
76  const auto Diff = std::abs(Cmp2 - Cmp1);
77 
78  // If the difference between both comparison values is 0 or 1, there is no
79  // need to clamp.
80  if (Diff == 0 || Diff == 1)
81  return false;
82 
83  const int64_t Min = std::numeric_limits<int16_t>::min();
84  const int64_t Max = std::numeric_limits<int16_t>::max();
85 
86  // Check if the comparison values are between SHORT_MIN and SHORT_MAX.
87  return ((Cmp2 >= Cmp1 && Cmp1 >= Min && Cmp2 <= Max) ||
88  (Cmp1 >= Cmp2 && Cmp1 <= Max && Cmp2 >= Min));
89  };
90 
91  // Try to match a combination of min / max MIR opcodes.
92  if (mi_match(MI.getOperand(1).getReg(), MRI,
93  m_GSMin(m_Reg(Base), m_ICst(MatchInfo.Cmp1)))) {
94  if (mi_match(Base, MRI,
95  m_GSMax(m_Reg(MatchInfo.Origin), m_ICst(MatchInfo.Cmp2)))) {
96  return IsApplicableForCombine();
97  }
98  }
99 
100  if (mi_match(MI.getOperand(1).getReg(), MRI,
101  m_GSMax(m_Reg(Base), m_ICst(MatchInfo.Cmp1)))) {
102  if (mi_match(Base, MRI,
103  m_GSMin(m_Reg(MatchInfo.Origin), m_ICst(MatchInfo.Cmp2)))) {
104  return IsApplicableForCombine();
105  }
106  }
107 
108  return false;
109 }
110 
111 // We want to find a combination of instructions that
112 // gets generated when an i64 gets clamped to i16.
113 // The corresponding pattern is:
114 // G_MAX / G_MAX for i16 <= G_TRUNC i64.
115 // This can be efficiently written as following:
116 // v_cvt_pk_i16_i32 v0, v0, v1
117 // v_med3_i32 v0, Clamp_Min, v0, Clamp_Max
119  MachineInstr &MI, const ClampI64ToI16MatchInfo &MatchInfo) {
120 
121  Register Src = MatchInfo.Origin;
122  assert(MI.getParent()->getParent()->getRegInfo().getType(Src) ==
123  LLT::scalar(64));
124  const LLT S32 = LLT::scalar(32);
125 
126  B.setMBB(*MI.getParent());
127  B.setInstrAndDebugLoc(MI);
128 
129  auto Unmerge = B.buildUnmerge(S32, Src);
130 
131  assert(MI.getOpcode() != AMDGPU::G_AMDGPU_CVT_PK_I16_I32);
132 
133  const LLT V2S16 = LLT::vector(2, 16);
134  auto CvtPk =
135  B.buildInstr(AMDGPU::G_AMDGPU_CVT_PK_I16_I32, {V2S16},
136  {Unmerge.getReg(0), Unmerge.getReg(1)}, MI.getFlags());
137 
138  auto MinBoundary = std::min(MatchInfo.Cmp1, MatchInfo.Cmp2);
139  auto MaxBoundary = std::max(MatchInfo.Cmp1, MatchInfo.Cmp2);
140  auto MinBoundaryDst = B.buildConstant(S32, MinBoundary);
141  auto MaxBoundaryDst = B.buildConstant(S32, MaxBoundary);
142 
143  auto Bitcast = B.buildBitcast({S32}, CvtPk);
144 
145  auto Med3 = B.buildInstr(
146  AMDGPU::G_AMDGPU_MED3, {S32},
147  {MinBoundaryDst.getReg(0), Bitcast.getReg(0), MaxBoundaryDst.getReg(0)},
148  MI.getFlags());
149 
150  B.buildTrunc(MI.getOperand(0).getReg(), Med3);
151 
152  MI.eraseFromParent();
153 }
154 
156 protected:
159 
160 public:
162  CombinerHelper &Helper,
163  AMDGPUPreLegalizerCombinerHelper &PreLegalizerHelper)
164  : Helper(Helper), PreLegalizerHelper(PreLegalizerHelper) {}
165 };
166 
167 #define AMDGPUPRELEGALIZERCOMBINERHELPER_GENCOMBINERHELPER_DEPS
168 #include "AMDGPUGenPreLegalizeGICombiner.inc"
169 #undef AMDGPUPRELEGALIZERCOMBINERHELPER_GENCOMBINERHELPER_DEPS
170 
171 namespace {
172 #define AMDGPUPRELEGALIZERCOMBINERHELPER_GENCOMBINERHELPER_H
173 #include "AMDGPUGenPreLegalizeGICombiner.inc"
174 #undef AMDGPUPRELEGALIZERCOMBINERHELPER_GENCOMBINERHELPER_H
175 
176 class AMDGPUPreLegalizerCombinerInfo final : public CombinerInfo {
177  GISelKnownBits *KB;
179 
180 public:
181  AMDGPUGenPreLegalizerCombinerHelperRuleConfig GeneratedRuleCfg;
182 
183  AMDGPUPreLegalizerCombinerInfo(bool EnableOpt, bool OptSize, bool MinSize,
185  : CombinerInfo(/*AllowIllegalOps*/ true, /*ShouldLegalizeIllegal*/ false,
186  /*LegalizerInfo*/ nullptr, EnableOpt, OptSize, MinSize),
187  KB(KB), MDT(MDT) {
188  if (!GeneratedRuleCfg.parseCommandLineOption())
189  report_fatal_error("Invalid rule identifier");
190  }
191 
192  virtual bool combine(GISelChangeObserver &Observer, MachineInstr &MI,
193  MachineIRBuilder &B) const override;
194 };
195 
197  MachineInstr &MI,
198  MachineIRBuilder &B) const {
199  CombinerHelper Helper(Observer, B, KB, MDT);
200  AMDGPUPreLegalizerCombinerHelper PreLegalizerHelper(B, Helper);
201  AMDGPUGenPreLegalizerCombinerHelper Generated(GeneratedRuleCfg, Helper,
202  PreLegalizerHelper);
203 
204  if (Generated.tryCombineAll(Observer, MI, B, Helper))
205  return true;
206 
207  switch (MI.getOpcode()) {
208  case TargetOpcode::G_CONCAT_VECTORS:
209  return Helper.tryCombineConcatVectors(MI);
210  case TargetOpcode::G_SHUFFLE_VECTOR:
211  return Helper.tryCombineShuffleVector(MI);
212  }
213 
214  return false;
215 }
216 
217 #define AMDGPUPRELEGALIZERCOMBINERHELPER_GENCOMBINERHELPER_CPP
218 #include "AMDGPUGenPreLegalizeGICombiner.inc"
219 #undef AMDGPUPRELEGALIZERCOMBINERHELPER_GENCOMBINERHELPER_CPP
220 
221 // Pass boilerplate
222 // ================
223 
224 class AMDGPUPreLegalizerCombiner : public MachineFunctionPass {
225 public:
226  static char ID;
227 
228  AMDGPUPreLegalizerCombiner(bool IsOptNone = false);
229 
230  StringRef getPassName() const override {
231  return "AMDGPUPreLegalizerCombiner";
232  }
233 
234  bool runOnMachineFunction(MachineFunction &MF) override;
235 
236  void getAnalysisUsage(AnalysisUsage &AU) const override;
237 private:
238  bool IsOptNone;
239 };
240 } // end anonymous namespace
241 
242 void AMDGPUPreLegalizerCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
244  AU.setPreservesCFG();
248  if (!IsOptNone) {
251  }
252 
256 }
257 
258 AMDGPUPreLegalizerCombiner::AMDGPUPreLegalizerCombiner(bool IsOptNone)
259  : MachineFunctionPass(ID), IsOptNone(IsOptNone) {
260  initializeAMDGPUPreLegalizerCombinerPass(*PassRegistry::getPassRegistry());
261 }
262 
263 bool AMDGPUPreLegalizerCombiner::runOnMachineFunction(MachineFunction &MF) {
264  if (MF.getProperties().hasProperty(
265  MachineFunctionProperties::Property::FailedISel))
266  return false;
267  auto *TPC = &getAnalysis<TargetPassConfig>();
268  const Function &F = MF.getFunction();
269  bool EnableOpt =
270  MF.getTarget().getOptLevel() != CodeGenOpt::None && !skipFunction(F);
271  GISelKnownBits *KB = &getAnalysis<GISelKnownBitsAnalysis>().get(MF);
272  MachineDominatorTree *MDT =
273  IsOptNone ? nullptr : &getAnalysis<MachineDominatorTree>();
274  AMDGPUPreLegalizerCombinerInfo PCInfo(EnableOpt, F.hasOptSize(),
275  F.hasMinSize(), KB, MDT);
276  // Enable CSE.
278  getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
279  auto *CSEInfo = &Wrapper.get(TPC->getCSEConfig());
280 
281  Combiner C(PCInfo, TPC);
282  return C.combineMachineInstrs(MF, CSEInfo);
283 }
284 
286 INITIALIZE_PASS_BEGIN(AMDGPUPreLegalizerCombiner, DEBUG_TYPE,
287  "Combine AMDGPU machine instrs before legalization",
288  false, false)
291 INITIALIZE_PASS_END(AMDGPUPreLegalizerCombiner, DEBUG_TYPE,
292  "Combine AMDGPU machine instrs before legalization", false,
293  false)
294 
295 namespace llvm {
297  return new AMDGPUPreLegalizerCombiner(IsOptNone);
298 }
299 } // end namespace llvm
MIPatternMatch.h
llvm::TargetMachine::getOptLevel
CodeGenOpt::Level getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
Definition: TargetMachine.cpp:198
AMDGPUPreLegalizerCombinerHelper::matchClampI64ToI16
bool matchClampI64ToI16(MachineInstr &MI, MachineRegisterInfo &MRI, MachineFunction &MF, ClampI64ToI16MatchInfo &MatchInfo)
Definition: AMDGPUPreLegalizerCombiner.cpp:57
CombinerInfo.h
llvm::MachineFunctionProperties::hasProperty
bool hasProperty(Property P) const
Definition: MachineFunction.h:162
MI
IRTranslator LLVM IR MI
Definition: IRTranslator.cpp:100
AMDGPUPreLegalizerCombinerHelper::MRI
MachineRegisterInfo & MRI
Definition: AMDGPUPreLegalizerCombiner.cpp:36
llvm
Definition: AllocatorList.h:23
AMDGPUPreLegalizerCombinerHelper::AMDGPUPreLegalizerCombinerHelper
AMDGPUPreLegalizerCombinerHelper(MachineIRBuilder &B, CombinerHelper &Helper)
Definition: AMDGPUPreLegalizerCombiner.cpp:40
llvm::GISelCSEAnalysisWrapperPass
The actual analysis pass wrapper.
Definition: CSEInfo.h:220
AMDGPUPreLegalizerCombinerHelper::Helper
CombinerHelper & Helper
Definition: AMDGPUPreLegalizerCombiner.cpp:37
llvm::MIPatternMatch::m_Reg
operand_type_match m_Reg()
Definition: MIPatternMatch.h:106
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:61
AMDGPUPreLegalizerCombinerHelper::ClampI64ToI16MatchInfo::Cmp2
int64_t Cmp2
Definition: AMDGPUPreLegalizerCombiner.cpp:45
Wrapper
amdgpu aa AMDGPU Address space based Alias Analysis Wrapper
Definition: AMDGPUAliasAnalysis.cpp:30
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:312
AMDGPUPreLegalizerCombinerHelper::ClampI64ToI16MatchInfo::Cmp1
int64_t Cmp1
Definition: AMDGPUPreLegalizerCombiner.cpp:44
llvm::getSelectionDAGFallbackAnalysisUsage
void getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU)
Modify analysis usage so it preserves passes required for the SelectionDAG fallback.
Definition: Utils.cpp:741
llvm::MIPatternMatch::m_GSMin
BinaryOp_match< LHS, RHS, TargetOpcode::G_SMIN, false > m_GSMin(const LHS &L, const RHS &R)
Definition: MIPatternMatch.h:318
llvm::CombinerInfo
Definition: CombinerInfo.h:27
INITIALIZE_PASS_END
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Definition: RegBankSelect.cpp:69
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::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:158
AMDGPUPreLegalizerCombinerHelper::B
MachineIRBuilder & B
Definition: AMDGPUPreLegalizerCombiner.cpp:34
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:646
false
Definition: StackSlotColoring.cpp:142
B
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
AMDGPUPreLegalizerCombinerHelper
Definition: AMDGPUPreLegalizerCombiner.cpp:32
AMDGPUPreLegalizerCombinerHelperState
Definition: AMDGPUPreLegalizerCombiner.cpp:155
llvm::report_fatal_error
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
llvm::LLT::vector
static LLT vector(uint16_t NumElements, unsigned ScalarSizeInBits)
Get a low-level vector of some number of elements and element width.
Definition: LowLevelTypeImpl.h:58
llvm::CombinerHelper
Definition: CombinerHelper.h:89
AMDGPUPreLegalizerCombinerHelper::MF
MachineFunction & MF
Definition: AMDGPUPreLegalizerCombiner.cpp:35
llvm::None
const NoneType None
Definition: None.h:23
llvm::TargetPassConfig
Target-Independent Code Generator Pass Configuration Options.
Definition: TargetPassConfig.h:84
Combine
Hexagon Vector Combine
Definition: HexagonVectorCombine.cpp:1483
AMDGPUMCTargetDesc.h
llvm::MachineIRBuilder
Helper class to build MachineInstr.
Definition: MachineIRBuilder.h:220
llvm::MachineInstr
Representation of each machine instruction.
Definition: MachineInstr.h:64
llvm::Combiner
Definition: Combiner.h:27
INITIALIZE_PASS_DEPENDENCY
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
llvm::LegalizeActions::Bitcast
@ Bitcast
Perform the operation on a different, but equivalently sized type.
Definition: LegalizerInfo.h:72
TargetPassConfig.h
AMDGPUPreLegalizerCombinerHelper::ClampI64ToI16MatchInfo::Origin
Register Origin
Definition: AMDGPUPreLegalizerCombiner.cpp:46
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
AMDGPUPreLegalizerCombinerHelper::ClampI64ToI16MatchInfo
Definition: AMDGPUPreLegalizerCombiner.cpp:43
llvm::MachineFunction
Definition: MachineFunction.h:227
CombinerHelper.h
llvm::min
Expected< ExpressionValue > min(const ExpressionValue &Lhs, const ExpressionValue &Rhs)
Definition: FileCheck.cpp:357
AMDGPUPreLegalizerCombinerHelper::applyClampI64ToI16
void applyClampI64ToI16(MachineInstr &MI, const ClampI64ToI16MatchInfo &MatchInfo)
Definition: AMDGPUPreLegalizerCombiner.cpp:118
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:27
llvm::GISelChangeObserver
Abstract class that contains various methods for clients to notify about changes.
Definition: GISelChangeObserver.h:29
AMDGPUPreLegalizerCombinerHelperState::AMDGPUPreLegalizerCombinerHelperState
AMDGPUPreLegalizerCombinerHelperState(CombinerHelper &Helper, AMDGPUPreLegalizerCombinerHelper &PreLegalizerHelper)
Definition: AMDGPUPreLegalizerCombiner.cpp:161
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:521
llvm::MachineFunction::getTarget
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Definition: MachineFunction.h:551
legalization
Combine AMDGPU machine instrs before legalization
Definition: AMDGPUPreLegalizerCombiner.cpp:292
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:69
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
llvm::createAMDGPUPreLegalizeCombiner
FunctionPass * createAMDGPUPreLegalizeCombiner(bool IsOptNone)
Definition: AMDGPUPreLegalizerCombiner.cpp:296
llvm::max
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:350
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:45
combine
vector combine
Definition: VectorCombine.cpp:833
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:1272
INITIALIZE_PASS_BEGIN
INITIALIZE_PASS_BEGIN(AMDGPUPreLegalizerCombiner, DEBUG_TYPE, "Combine AMDGPU machine instrs before legalization", false, false) INITIALIZE_PASS_END(AMDGPUPreLegalizerCombiner
AMDGPUPreLegalizerCombinerHelperState::Helper
CombinerHelper & Helper
Definition: AMDGPUPreLegalizerCombiner.cpp:157
machine
coro Split coroutine into a set of functions driving its state machine
Definition: CoroSplit.cpp:2246
MachineDominators.h
llvm::Intrinsic::ID
unsigned ID
Definition: TargetTransformInfo.h:38
llvm::LLT
Definition: LowLevelTypeImpl.h:40