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 
15 #include "AMDGPU.h"
16 #include "AMDGPUPerfHintAnalysis.h"
17 #include "Utils/AMDGPUBaseInfo.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/CallGraph.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/CodeGen/TargetLowering.h"
23 #include "llvm/CodeGen/TargetPassConfig.h"
24 #include "llvm/CodeGen/TargetSubtargetInfo.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Target/TargetMachine.h"
29 
30 using namespace llvm;
31 
32 #define DEBUG_TYPE "amdgpu-perf-hint"
33 
34 static cl::opt<unsigned>
35     MemBoundThresh("amdgpu-membound-threshold", cl::init(50), cl::Hidden,
36                    cl::desc("Function mem bound threshold in %"));
37 
38 static cl::opt<unsigned>
39     LimitWaveThresh("amdgpu-limit-wave-threshold", cl::init(50), cl::Hidden,
40                     cl::desc("Kernel limit wave threshold in %"));
41 
42 static cl::opt<unsigned>
43     IAWeight("amdgpu-indirect-access-weight", cl::init(1000), cl::Hidden,
44              cl::desc("Indirect access memory instruction weight"));
45 
46 static cl::opt<unsigned>
47     LSWeight("amdgpu-large-stride-weight", cl::init(1000), cl::Hidden,
48              cl::desc("Large stride memory access weight"));
49 
50 static cl::opt<unsigned>
51     LargeStrideThresh("amdgpu-large-stride-threshold", cl::init(64), cl::Hidden,
52                       cl::desc("Large stride memory access threshold"));
53 
54 STATISTIC(NumMemBound, "Number of functions marked as memory bound");
55 STATISTIC(NumLimitWave, "Number of functions marked as needing limit wave");
56 
57 char llvm::AMDGPUPerfHintAnalysis::ID = 0;
58 char &llvm::AMDGPUPerfHintAnalysisID = AMDGPUPerfHintAnalysis::ID;
59 
60 INITIALIZE_PASS(AMDGPUPerfHintAnalysis, DEBUG_TYPE,
61                 "Analysis if a function is memory bound", true, true)
62 
63 namespace {
64 
65 struct AMDGPUPerfHint {
66   friend AMDGPUPerfHintAnalysis;
67 
68 public:
69   AMDGPUPerfHint(AMDGPUPerfHintAnalysis::FuncInfoMap &FIM_,
70                  const TargetLowering *TLI_)
71       : FIM(FIM_), DL(nullptr), TLI(TLI_) {}
72 
73   bool runOnFunction(Function &F);
74 
75 private:
76   struct MemAccessInfo {
77     const Value *V;
78     const Value *Base;
79     int64_t Offset;
80     MemAccessInfo() : V(nullptr), Base(nullptr), Offset(0) {}
81     bool isLargeStride(MemAccessInfo &Reference) const;
82 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
83     Printable print() const {
84       return Printable([this](raw_ostream &OS) {
85         OS << "Value: " << *V << '\n'
86            << "Base: " << *Base << " Offset: " << Offset << '\n';
87       });
88     }
89 #endif
90   };
91 
92   MemAccessInfo makeMemAccessInfo(Instruction *) const;
93 
94   MemAccessInfo LastAccess; // Last memory access info
95 
96   AMDGPUPerfHintAnalysis::FuncInfoMap &FIM;
97 
98   const DataLayout *DL;
99 
100   const TargetLowering *TLI;
101 
102   AMDGPUPerfHintAnalysis::FuncInfo *visit(const Function &F);
103   static bool isMemBound(const AMDGPUPerfHintAnalysis::FuncInfo &F);
104   static bool needLimitWave(const AMDGPUPerfHintAnalysis::FuncInfo &F);
105 
106   bool isIndirectAccess(const Instruction *Inst) const;
107 
108   /// Check if the instruction is large stride.
109   /// The purpose is to identify memory access pattern like:
110   /// x = a[i];
111   /// y = a[i+1000];
112   /// z = a[i+2000];
113   /// In the above example, the second and third memory access will be marked
114   /// large stride memory access.
115   bool isLargeStride(const Instruction *Inst);
116 
117   bool isGlobalAddr(const Value *V) const;
118   bool isLocalAddr(const Value *V) const;
119 };
120 
121 static std::pair<const Value *, const Type *> getMemoryInstrPtrAndType(
122     const Instruction *Inst) {
123   if (auto LI = dyn_cast<LoadInst>(Inst))
124     return {LI->getPointerOperand(), LI->getType()};
125   if (auto SI = dyn_cast<StoreInst>(Inst))
126     return {SI->getPointerOperand(), SI->getValueOperand()->getType()};
127   if (auto AI = dyn_cast<AtomicCmpXchgInst>(Inst))
128     return {AI->getPointerOperand(), AI->getCompareOperand()->getType()};
129   if (auto AI = dyn_cast<AtomicRMWInst>(Inst))
130     return {AI->getPointerOperand(), AI->getValOperand()->getType()};
131   if (auto MI = dyn_cast<AnyMemIntrinsic>(Inst))
132     return {MI->getRawDest(), Type::getInt8Ty(MI->getContext())};
133 
134   return {nullptr, nullptr};
135 }
136 
137 bool AMDGPUPerfHint::isIndirectAccess(const Instruction *Inst) const {
138   LLVM_DEBUG(dbgs() << "[isIndirectAccess] " << *Inst << '\n');
139   SmallSet<const Value *, 32> WorkSet;
140   SmallSet<const Value *, 32> Visited;
141   if (const Value *MO = getMemoryInstrPtrAndType(Inst).first) {
142     if (isGlobalAddr(MO))
143       WorkSet.insert(MO);
144   }
145 
146   while (!WorkSet.empty()) {
147     const Value *V = *WorkSet.begin();
148     WorkSet.erase(*WorkSet.begin());
149     if (!Visited.insert(V).second)
150       continue;
151     LLVM_DEBUG(dbgs() << "  check: " << *V << '\n');
152 
153     if (auto LD = dyn_cast<LoadInst>(V)) {
154       auto M = LD->getPointerOperand();
155       if (isGlobalAddr(M)) {
156         LLVM_DEBUG(dbgs() << "    is IA\n");
157         return true;
158       }
159       continue;
160     }
161 
162     if (auto GEP = dyn_cast<GetElementPtrInst>(V)) {
163       auto P = GEP->getPointerOperand();
164       WorkSet.insert(P);
165       for (unsigned I = 1, E = GEP->getNumIndices() + 1; I != E; ++I)
166         WorkSet.insert(GEP->getOperand(I));
167       continue;
168     }
169 
170     if (auto U = dyn_cast<UnaryInstruction>(V)) {
171       WorkSet.insert(U->getOperand(0));
172       continue;
173     }
174 
175     if (auto BO = dyn_cast<BinaryOperator>(V)) {
176       WorkSet.insert(BO->getOperand(0));
177       WorkSet.insert(BO->getOperand(1));
178       continue;
179     }
180 
181     if (auto S = dyn_cast<SelectInst>(V)) {
182       WorkSet.insert(S->getFalseValue());
183       WorkSet.insert(S->getTrueValue());
184       continue;
185     }
186 
187     if (auto E = dyn_cast<ExtractElementInst>(V)) {
188       WorkSet.insert(E->getVectorOperand());
189       continue;
190     }
191 
192     LLVM_DEBUG(dbgs() << "    dropped\n");
193   }
194 
195   LLVM_DEBUG(dbgs() << "  is not IA\n");
196   return false;
197 }
198 
199 AMDGPUPerfHintAnalysis::FuncInfo *AMDGPUPerfHint::visit(const Function &F) {
200   AMDGPUPerfHintAnalysis::FuncInfo &FI = FIM[&F];
201 
202   LLVM_DEBUG(dbgs() << "[AMDGPUPerfHint] process " << F.getName() << '\n');
203 
204   for (auto &B : F) {
205     LastAccess = MemAccessInfo();
206     for (auto &I : B) {
207       if (const Type *Ty = getMemoryInstrPtrAndType(&I).second) {
208         unsigned Size = divideCeil(Ty->getPrimitiveSizeInBits(), 32);
209         if (isIndirectAccess(&I))
210           FI.IAMInstCost += Size;
211         if (isLargeStride(&I))
212           FI.LSMInstCost += Size;
213         FI.MemInstCost += Size;
214         FI.InstCost += Size;
215         continue;
216       }
217       if (auto *CB = dyn_cast<CallBase>(&I)) {
218         Function *Callee = CB->getCalledFunction();
219         if (!Callee || Callee->isDeclaration()) {
220           ++FI.InstCost;
221           continue;
222         }
223         if (&F == Callee) // Handle immediate recursion
224           continue;
225 
226         auto Loc = FIM.find(Callee);
227         if (Loc == FIM.end())
228           continue;
229 
230         FI.MemInstCost += Loc->second.MemInstCost;
231         FI.InstCost += Loc->second.InstCost;
232         FI.IAMInstCost += Loc->second.IAMInstCost;
233         FI.LSMInstCost += Loc->second.LSMInstCost;
234       } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
235         TargetLoweringBase::AddrMode AM;
236         auto *Ptr = GetPointerBaseWithConstantOffset(GEP, AM.BaseOffs, *DL);
237         AM.BaseGV = dyn_cast_or_null<GlobalValue>(const_cast<Value *>(Ptr));
238         AM.HasBaseReg = !AM.BaseGV;
239         if (TLI->isLegalAddressingMode(*DL, AM, GEP->getResultElementType(),
240                                        GEP->getPointerAddressSpace()))
241           // Offset will likely be folded into load or store
242           continue;
243         ++FI.InstCost;
244       } else {
245         ++FI.InstCost;
246       }
247     }
248   }
249 
250   return &FI;
251 }
252 
253 bool AMDGPUPerfHint::runOnFunction(Function &F) {
254   const Module &M = *F.getParent();
255   DL = &M.getDataLayout();
256 
257   if (F.hasFnAttribute("amdgpu-wave-limiter") &&
258       F.hasFnAttribute("amdgpu-memory-bound"))
259     return false;
260 
261   const AMDGPUPerfHintAnalysis::FuncInfo *Info = visit(F);
262 
263   LLVM_DEBUG(dbgs() << F.getName() << " MemInst cost: " << Info->MemInstCost
264                     << '\n'
265                     << " IAMInst cost: " << Info->IAMInstCost << '\n'
266                     << " LSMInst cost: " << Info->LSMInstCost << '\n'
267                     << " TotalInst cost: " << Info->InstCost << '\n');
268 
269   bool Changed = false;
270 
271   if (isMemBound(*Info)) {
272     LLVM_DEBUG(dbgs() << F.getName() << " is memory bound\n");
273     NumMemBound++;
274     F.addFnAttr("amdgpu-memory-bound", "true");
275     Changed = true;
276   }
277 
278   if (AMDGPU::isEntryFunctionCC(F.getCallingConv()) && needLimitWave(*Info)) {
279     LLVM_DEBUG(dbgs() << F.getName() << " needs limit wave\n");
280     NumLimitWave++;
281     F.addFnAttr("amdgpu-wave-limiter", "true");
282     Changed = true;
283   }
284 
285   return Changed;
286 }
287 
288 bool AMDGPUPerfHint::isMemBound(const AMDGPUPerfHintAnalysis::FuncInfo &FI) {
289   return FI.MemInstCost * 100 / FI.InstCost > MemBoundThresh;
290 }
291 
292 bool AMDGPUPerfHint::needLimitWave(const AMDGPUPerfHintAnalysis::FuncInfo &FI) {
293   return ((FI.MemInstCost + FI.IAMInstCost * IAWeight +
294            FI.LSMInstCost * LSWeight) * 100 / FI.InstCost) > LimitWaveThresh;
295 }
296 
297 bool AMDGPUPerfHint::isGlobalAddr(const Value *V) const {
298   if (auto PT = dyn_cast<PointerType>(V->getType())) {
299     unsigned As = PT->getAddressSpace();
300     // Flat likely points to global too.
301     return As == AMDGPUAS::GLOBAL_ADDRESS || As == AMDGPUAS::FLAT_ADDRESS;
302   }
303   return false;
304 }
305 
306 bool AMDGPUPerfHint::isLocalAddr(const Value *V) const {
307   if (auto PT = dyn_cast<PointerType>(V->getType()))
308     return PT->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS;
309   return false;
310 }
311 
312 bool AMDGPUPerfHint::isLargeStride(const Instruction *Inst) {
313   LLVM_DEBUG(dbgs() << "[isLargeStride] " << *Inst << '\n');
314 
315   MemAccessInfo MAI = makeMemAccessInfo(const_cast<Instruction *>(Inst));
316   bool IsLargeStride = MAI.isLargeStride(LastAccess);
317   if (MAI.Base)
318     LastAccess = std::move(MAI);
319 
320   return IsLargeStride;
321 }
322 
323 AMDGPUPerfHint::MemAccessInfo
324 AMDGPUPerfHint::makeMemAccessInfo(Instruction *Inst) const {
325   MemAccessInfo MAI;
326   const Value *MO = getMemoryInstrPtrAndType(Inst).first;
327 
328   LLVM_DEBUG(dbgs() << "[isLargeStride] MO: " << *MO << '\n');
329   // Do not treat local-addr memory access as large stride.
330   if (isLocalAddr(MO))
331     return MAI;
332 
333   MAI.V = MO;
334   MAI.Base = GetPointerBaseWithConstantOffset(MO, MAI.Offset, *DL);
335   return MAI;
336 }
337 
338 bool AMDGPUPerfHint::MemAccessInfo::isLargeStride(
339     MemAccessInfo &Reference) const {
340 
341   if (!Base || !Reference.Base || Base != Reference.Base)
342     return false;
343 
344   uint64_t Diff = Offset > Reference.Offset ? Offset - Reference.Offset
345                                             : Reference.Offset - Offset;
346   bool Result = Diff > LargeStrideThresh;
347   LLVM_DEBUG(dbgs() << "[isLargeStride compare]\n"
348                << print() << "<=>\n"
349                << Reference.print() << "Result:" << Result << '\n');
350   return Result;
351 }
352 } // namespace
353 
354 bool AMDGPUPerfHintAnalysis::runOnSCC(CallGraphSCC &SCC) {
355   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
356   if (!TPC)
357     return false;
358 
359   const TargetMachine &TM = TPC->getTM<TargetMachine>();
360 
361   bool Changed = false;
362   for (CallGraphNode *I : SCC) {
363     Function *F = I->getFunction();
364     if (!F || F->isDeclaration())
365       continue;
366 
367     const TargetSubtargetInfo *ST = TM.getSubtargetImpl(*F);
368     AMDGPUPerfHint Analyzer(FIM, ST->getTargetLowering());
369 
370     if (Analyzer.runOnFunction(*F))
371       Changed = true;
372   }
373 
374   return Changed;
375 }
376 
377 bool AMDGPUPerfHintAnalysis::isMemoryBound(const Function *F) const {
378   auto FI = FIM.find(F);
379   if (FI == FIM.end())
380     return false;
381 
382   return AMDGPUPerfHint::isMemBound(FI->second);
383 }
384 
385 bool AMDGPUPerfHintAnalysis::needsWaveLimiter(const Function *F) const {
386   auto FI = FIM.find(F);
387   if (FI == FIM.end())
388     return false;
389 
390   return AMDGPUPerfHint::needLimitWave(FI->second);
391 }
392