LLVM 24.0.0git
AMDGPUPerfHintAnalysis.cpp
Go to the documentation of this file.
1//===- AMDGPUPerfHintAnalysis.cpp - analysis of functions memory traffic --===//
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/// \brief Analyzes if a function potentially memory bound and if a kernel
11/// kernel may benefit from limiting number of waves to reduce cache thrashing.
12///
13//===----------------------------------------------------------------------===//
14
16#include "AMDGPU.h"
17#include "AMDGPUTargetMachine.h"
19#include "llvm/ADT/Statistic.h"
30
31using namespace llvm;
32
33#define DEBUG_TYPE "amdgpu-perf-hint"
34
35STATISTIC(NumMemBound, "Number of functions marked as memory bound");
36STATISTIC(NumLimitWave, "Number of functions marked as needing limit wave");
37
38namespace {
39
40struct AMDGPUPerfHint {
42
43public:
44 AMDGPUPerfHint(const AMDGPUOptions &CLOpts,
46 const SITargetLowering *TLI_)
47 : CLOpts(CLOpts), FIM(FIM_), TLI(TLI_) {}
48
50
51private:
52 struct MemAccessInfo {
53 const Value *V = nullptr;
54 const Value *Base = nullptr;
55 int64_t Offset = 0;
56 MemAccessInfo() = default;
57 bool isLargeStride(MemAccessInfo &Reference,
58 unsigned LargeStrideThresh) const;
59#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
60 Printable print() const {
61 return Printable([this](raw_ostream &OS) {
62 OS << "Value: " << *V << '\n'
63 << "Base: " << *Base << " Offset: " << Offset << '\n';
64 });
65 }
66#endif
67 };
68
69 MemAccessInfo makeMemAccessInfo(Instruction *) const;
70
71 const AMDGPUOptions &CLOpts;
72
73 MemAccessInfo LastAccess; // Last memory access info
74
76
77 const DataLayout *DL = nullptr;
78
79 const SITargetLowering *TLI;
80
81 AMDGPUPerfHintAnalysis::FuncInfo *visit(const Function &F);
82 static bool isMemBound(const AMDGPUOptions &CLOpts,
83 const AMDGPUPerfHintAnalysis::FuncInfo &F);
84 static bool needLimitWave(const AMDGPUOptions &CLOpts,
85 const AMDGPUPerfHintAnalysis::FuncInfo &F);
86
87 bool isIndirectAccess(const Instruction *Inst) const;
88
89 /// Check if the instruction is large stride.
90 /// The purpose is to identify memory access pattern like:
91 /// x = a[i];
92 /// y = a[i+1000];
93 /// z = a[i+2000];
94 /// In the above example, the second and third memory access will be marked
95 /// large stride memory access.
96 bool isLargeStride(const Instruction *Inst);
97
98 bool isGlobalAddr(const Value *V) const;
99 bool isLocalAddr(const Value *V) const;
100 bool isGlobalLoadUsedInBB(const Instruction &) const;
101};
102
103static std::pair<const Value *, const Type *> getMemoryInstrPtrAndType(
104 const Instruction *Inst) {
105 if (const auto *LI = dyn_cast<LoadInst>(Inst))
106 return {LI->getPointerOperand(), LI->getType()};
107 if (const auto *SI = dyn_cast<StoreInst>(Inst))
108 return {SI->getPointerOperand(), SI->getValueOperand()->getType()};
109 if (const auto *AI = dyn_cast<AtomicCmpXchgInst>(Inst))
110 return {AI->getPointerOperand(), AI->getCompareOperand()->getType()};
111 if (const auto *AI = dyn_cast<AtomicRMWInst>(Inst))
112 return {AI->getPointerOperand(), AI->getValOperand()->getType()};
113 if (const auto *MI = dyn_cast<AnyMemIntrinsic>(Inst))
114 return {MI->getRawDest(), Type::getInt8Ty(MI->getContext())};
115
116 return {nullptr, nullptr};
117}
118
119bool AMDGPUPerfHint::isIndirectAccess(const Instruction *Inst) const {
120 LLVM_DEBUG(dbgs() << "[isIndirectAccess] " << *Inst << '\n');
121 SmallPtrSet<const Value *, 32> WorkSet;
122 SmallPtrSet<const Value *, 32> Visited;
123 if (const Value *MO = getMemoryInstrPtrAndType(Inst).first) {
124 if (isGlobalAddr(MO))
125 WorkSet.insert(MO);
126 }
127
128 while (!WorkSet.empty()) {
129 const Value *V = *WorkSet.begin();
130 WorkSet.erase(*WorkSet.begin());
131 if (!Visited.insert(V).second)
132 continue;
133 LLVM_DEBUG(dbgs() << " check: " << *V << '\n');
134
135 if (const auto *LD = dyn_cast<LoadInst>(V)) {
136 const auto *M = LD->getPointerOperand();
137 if (isGlobalAddr(M)) {
138 LLVM_DEBUG(dbgs() << " is IA\n");
139 return true;
140 }
141 continue;
142 }
143
144 if (const auto *GEP = dyn_cast<GetElementPtrInst>(V)) {
145 const auto *P = GEP->getPointerOperand();
146 WorkSet.insert(P);
147 for (unsigned I = 1, E = GEP->getNumIndices() + 1; I != E; ++I)
148 WorkSet.insert(GEP->getOperand(I));
149 continue;
150 }
151
152 if (const auto *U = dyn_cast<UnaryInstruction>(V)) {
153 WorkSet.insert(U->getOperand(0));
154 continue;
155 }
156
157 if (const auto *BO = dyn_cast<BinaryOperator>(V)) {
158 WorkSet.insert(BO->getOperand(0));
159 WorkSet.insert(BO->getOperand(1));
160 continue;
161 }
162
163 if (const auto *S = dyn_cast<SelectInst>(V)) {
164 WorkSet.insert(S->getFalseValue());
165 WorkSet.insert(S->getTrueValue());
166 continue;
167 }
168
169 if (const auto *E = dyn_cast<ExtractElementInst>(V)) {
170 WorkSet.insert(E->getVectorOperand());
171 continue;
172 }
173
174 LLVM_DEBUG(dbgs() << " dropped\n");
175 }
176
177 LLVM_DEBUG(dbgs() << " is not IA\n");
178 return false;
179}
180
181// Returns true if the global load `I` is used in its own basic block.
182bool AMDGPUPerfHint::isGlobalLoadUsedInBB(const Instruction &I) const {
183 const auto *Ld = dyn_cast<LoadInst>(&I);
184 if (!Ld)
185 return false;
186 if (!isGlobalAddr(Ld->getPointerOperand()))
187 return false;
188
189 for (const Instruction *UsrInst : Ld->users()) {
190 if (UsrInst->getParent() == I.getParent())
191 return true;
192 }
193
194 return false;
195}
196
197AMDGPUPerfHintAnalysis::FuncInfo *AMDGPUPerfHint::visit(const Function &F) {
198 AMDGPUPerfHintAnalysis::FuncInfo &FI = FIM[&F];
199
200 LLVM_DEBUG(dbgs() << "[AMDGPUPerfHint] process " << F.getName() << '\n');
201
202 for (auto &B : F) {
203 LastAccess = MemAccessInfo();
204 uint64_t UsedGlobalLoadsInBB = 0;
205 for (auto &I : B) {
206 if (const Type *Ty = getMemoryInstrPtrAndType(&I).second) {
207 uint64_t Size = divideCeil(Ty->getPrimitiveSizeInBits(), 32);
208 // TODO: Check if the global load and its user are close to each other
209 // instead (Or do this analysis in GCNSchedStrategy?).
210 if (isGlobalLoadUsedInBB(I))
211 UsedGlobalLoadsInBB += Size;
212 if (isIndirectAccess(&I))
213 FI.IAMInstCost += Size;
214 if (isLargeStride(&I))
215 FI.LSMInstCost += Size;
216 FI.MemInstCost += Size;
217 FI.InstCost += Size;
218 continue;
219 }
220 if (auto *CB = dyn_cast<CallBase>(&I)) {
221 Function *Callee = CB->getCalledFunction();
222 if (!Callee || Callee->isDeclaration()) {
223 ++FI.InstCost;
224 continue;
225 }
226 if (&F == Callee) // Handle immediate recursion
227 continue;
228
229 auto Loc = FIM.find(Callee);
230 if (Loc == FIM.end())
231 continue;
232
233 FI.MemInstCost += Loc->second.MemInstCost;
234 FI.InstCost += Loc->second.InstCost;
235 FI.IAMInstCost += Loc->second.IAMInstCost;
236 FI.LSMInstCost += Loc->second.LSMInstCost;
237 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
238 TargetLoweringBase::AddrMode AM;
240 AM.BaseGV = dyn_cast_or_null<GlobalValue>(const_cast<Value *>(Ptr));
241 AM.HasBaseReg = !AM.BaseGV;
242 if (TLI->isLegalAddressingMode(*DL, AM, GEP->getResultElementType(),
243 GEP->getPointerAddressSpace()))
244 // Offset will likely be folded into load or store
245 continue;
246 ++FI.InstCost;
247 } else {
248 ++FI.InstCost;
249 }
250 }
251
252 if (!FI.HasDenseGlobalMemAcc) {
253 uint64_t GlobalMemAccPercentage = UsedGlobalLoadsInBB * 100 / B.size();
254 if (GlobalMemAccPercentage > 50) {
255 LLVM_DEBUG(dbgs() << "[HasDenseGlobalMemAcc] Set to true since "
256 << B.getName() << " has " << GlobalMemAccPercentage
257 << "% global memory access\n");
258 FI.HasDenseGlobalMemAcc = true;
259 }
260 }
261 }
262
263 return &FI;
264}
265
266bool AMDGPUPerfHint::runOnFunction(Function &F) {
267 const Module &M = *F.getParent();
268 DL = &M.getDataLayout();
269
270 if (F.hasFnAttribute("amdgpu-wave-limiter") &&
271 F.hasFnAttribute("amdgpu-memory-bound"))
272 return false;
273
274 const AMDGPUPerfHintAnalysis::FuncInfo *Info = visit(F);
275
276 LLVM_DEBUG(dbgs() << F.getName() << " MemInst cost: " << Info->MemInstCost
277 << '\n'
278 << " IAMInst cost: " << Info->IAMInstCost << '\n'
279 << " LSMInst cost: " << Info->LSMInstCost << '\n'
280 << " TotalInst cost: " << Info->InstCost << '\n');
281
282 bool Changed = false;
283
284 if (isMemBound(CLOpts, *Info)) {
285 LLVM_DEBUG(dbgs() << F.getName() << " is memory bound\n");
286 NumMemBound++;
287 F.addFnAttr("amdgpu-memory-bound", "true");
288 Changed = true;
289 }
290
291 if (AMDGPU::isEntryFunctionCC(F.getCallingConv()) &&
292 needLimitWave(CLOpts, *Info)) {
293 LLVM_DEBUG(dbgs() << F.getName() << " needs limit wave\n");
294 NumLimitWave++;
295 F.addFnAttr("amdgpu-wave-limiter", "true");
296 Changed = true;
297 }
298
299 return Changed;
300}
301
302bool AMDGPUPerfHint::isMemBound(const AMDGPUOptions &CLOpts,
303 const AMDGPUPerfHintAnalysis::FuncInfo &FI) {
304 // Reverting optimal scheduling in favour of occupancy with basic block(s)
305 // having dense global memory access can potentially hurt performance.
307 return true;
308
309 return FI.MemInstCost * 100 / FI.InstCost > CLOpts.membound_threshold;
310}
311
312bool AMDGPUPerfHint::needLimitWave(const AMDGPUOptions &CLOpts,
313 const AMDGPUPerfHintAnalysis::FuncInfo &FI) {
314 return ((FI.MemInstCost + FI.IAMInstCost * CLOpts.indirect_access_weight +
315 FI.LSMInstCost * CLOpts.large_stride_weight) *
316 100 / FI.InstCost) > CLOpts.limit_wave_threshold;
317}
318
319bool AMDGPUPerfHint::isGlobalAddr(const Value *V) const {
320 if (auto *PT = dyn_cast<PointerType>(V->getType())) {
321 unsigned As = PT->getAddressSpace();
322 // Flat likely points to global too.
324 }
325 return false;
326}
327
328bool AMDGPUPerfHint::isLocalAddr(const Value *V) const {
329 if (auto *PT = dyn_cast<PointerType>(V->getType()))
330 return PT->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS;
331 return false;
332}
333
334bool AMDGPUPerfHint::isLargeStride(const Instruction *Inst) {
335 LLVM_DEBUG(dbgs() << "[isLargeStride] " << *Inst << '\n');
336
337 MemAccessInfo MAI = makeMemAccessInfo(const_cast<Instruction *>(Inst));
338 bool IsLargeStride =
339 MAI.isLargeStride(LastAccess, CLOpts.large_stride_threshold);
340 if (MAI.Base)
341 LastAccess = std::move(MAI);
342
343 return IsLargeStride;
344}
345
346AMDGPUPerfHint::MemAccessInfo
347AMDGPUPerfHint::makeMemAccessInfo(Instruction *Inst) const {
348 MemAccessInfo MAI;
349 const Value *MO = getMemoryInstrPtrAndType(Inst).first;
350
351 LLVM_DEBUG(dbgs() << "[isLargeStride] MO: " << *MO << '\n');
352 // Do not treat local-addr memory access as large stride.
353 if (isLocalAddr(MO))
354 return MAI;
355
356 MAI.V = MO;
357 MAI.Base = GetPointerBaseWithConstantOffset(MO, MAI.Offset, *DL);
358 return MAI;
359}
360
361bool AMDGPUPerfHint::MemAccessInfo::isLargeStride(
362 MemAccessInfo &Reference, unsigned LargeStrideThresh) const {
363
364 if (!Base || !Reference.Base || Base != Reference.Base)
365 return false;
366
367 uint64_t Diff = Offset > Reference.Offset ? Offset - Reference.Offset
368 : Reference.Offset - Offset;
369 bool Result = Diff > LargeStrideThresh;
370 LLVM_DEBUG(dbgs() << "[isLargeStride compare]\n"
371 << print() << "<=>\n"
372 << Reference.print() << "Result:" << Result << '\n');
373 return Result;
374}
375
376class AMDGPUPerfHintAnalysisLegacy : public CallGraphSCCPass {
377private:
378 // FIXME: This is relying on maintaining state between different SCCs.
379 AMDGPUPerfHintAnalysis Impl;
380
381public:
382 static char ID;
383
384 AMDGPUPerfHintAnalysisLegacy() : CallGraphSCCPass(ID) {}
385
386 bool runOnSCC(CallGraphSCC &SCC) override;
387
388 void getAnalysisUsage(AnalysisUsage &AU) const override {
389 AU.setPreservesAll();
390 }
391};
392
393} // namespace
394
396 auto FI = FIM.find(F);
397 if (FI == FIM.end())
398 return false;
399
400 return AMDGPUPerfHint::isMemBound(
401 F->getContext().getLibraryOptions().get<AMDGPUOptions>(), FI->second);
402}
403
405 auto FI = FIM.find(F);
406 if (FI == FIM.end())
407 return false;
408
409 return AMDGPUPerfHint::needLimitWave(
410 F->getContext().getLibraryOptions().get<AMDGPUOptions>(), FI->second);
411}
412
414 CallGraphSCC &SCC) {
415 bool Changed = false;
416 for (CallGraphNode *I : SCC) {
417 Function *F = I->getFunction();
418 if (!F || F->isDeclaration())
419 continue;
420
421 const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(*F);
422 AMDGPUPerfHint Analyzer(TM.getCLOpts(), FIM, ST.getTargetLowering());
423
424 if (Analyzer.runOnFunction(*F))
425 Changed = true;
426 }
427
428 return Changed;
429}
430
432 LazyCallGraph &CG) {
433 bool Changed = false;
434
435 CG.buildRefSCCs();
436
438 for (LazyCallGraph::SCC &SCC : RC) {
439 if (SCC.size() != 1)
440 continue;
441 Function &F = SCC.begin()->getFunction();
442 // TODO: Skip without norecurse, or interposable?
443 if (F.isDeclaration())
444 continue;
445
446 const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(F);
447 AMDGPUPerfHint Analyzer(TM.getCLOpts(), FIM, ST.getTargetLowering());
448 if (Analyzer.runOnFunction(F))
449 Changed = true;
450 }
451 }
452
453 return Changed;
454}
455
456char AMDGPUPerfHintAnalysisLegacy::ID = 0;
457char &llvm::AMDGPUPerfHintAnalysisLegacyID = AMDGPUPerfHintAnalysisLegacy::ID;
458
459INITIALIZE_PASS(AMDGPUPerfHintAnalysisLegacy, DEBUG_TYPE,
460 "Analysis if a function is memory bound", true, true)
461
462bool AMDGPUPerfHintAnalysisLegacy::runOnSCC(CallGraphSCC &SCC) {
463 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
464 if (!TPC)
465 return false;
466
467 const GCNTargetMachine &TM = TPC->getTM<GCNTargetMachine>();
468 return Impl.runOnSCC(TM, SCC);
469}
470
473 auto &CG = AM.getResult<LazyCallGraphAnalysis>(M);
474
475 bool Changed = Impl->run(TM, CG);
476 if (!Changed)
477 return PreservedAnalyses::all();
478
481 return PA;
482}
const TargetLowering & TLI
uint64_t uint64_t
Analyzes if a function potentially memory bound and if a kernel kernel may benefit from limiting numb...
The AMDGPU TargetMachine interface definition for hw codegen targets.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
Hexagon Common GEP
IRTranslator LLVM IR MI
Implements a lazy call graph analysis and related passes for the new pass manager.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
bool isMemoryBound(const Function *F) const
bool needsWaveLimiter(const Function *F) const
bool run(const GCNTargetMachine &TM, LazyCallGraph &CG)
bool runOnSCC(const GCNTargetMachine &TM, CallGraphSCC &SCC)
ValueMap< const Function *, FuncInfo > FuncInfoMap
const AMDGPUOptions & getCLOpts() const
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
void setPreservesAll()
Set by analyses that do not transform their input at all.
A node in the call graph for a module.
Definition CallGraph.h:162
CallGraphSCC - This is a single SCC that a CallGraphSCCPass is run on.
An analysis pass which computes the call graph for a module.
A RefSCC of the call graph.
An SCC of the call graph.
A lazily constructed view of the call graph of a module.
LLVM_ABI void buildRefSCCs()
iterator_range< postorder_ref_scc_iterator > postorder_ref_sccs()
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
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 & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
bool erase(PtrType Ptr)
Remove pointer from the set.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
iterator begin() const
virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AddrSpace, Instruction *I=nullptr) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
iterator find(const KeyT &Val)
Definition ValueMap.h:160
iterator end()
Definition ValueMap.h:139
@ LOCAL_ADDRESS
Address space for local memory.
@ FLAT_ADDRESS
Address space for flat memory.
@ GLOBAL_ADDRESS
Address space for global memory (RAT0, VTX0).
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
char & AMDGPUPerfHintAnalysisLegacyID
std::unique_ptr< AMDGPUPerfHintAnalysis > Impl
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)