1//===-- AMDGPULowerModuleLDSPass.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// This pass eliminates local data store, LDS, uses from non-kernel functions.
10// LDS is contiguous memory allocated per kernel execution.
11//
12// Background.
13//
14// The programming model is global variables, or equivalently function local
15// static variables, accessible from kernels or other functions. For uses from
16// kernels this is straightforward - assign an integer to the kernel for the
17// memory required by all the variables combined, allocate them within that.
18// For uses from functions there are performance tradeoffs to choose between.
19//
20// This model means the GPU runtime can specify the amount of memory allocated.
21// If this is more than the kernel assumed, the excess can be made available
22// using a language specific feature, which IR represents as a variable with
23// no initializer. This feature is referred to here as "Dynamic LDS" and is
24// lowered slightly differently to the normal case.
25//
26// Consequences of this GPU feature:
27// - memory is limited and exceeding it halts compilation
28// - a global accessed by one kernel exists independent of other kernels
29// - a global exists independent of simultaneous execution of the same kernel
30// - the address of the global may be different from different kernels as they
31// do not alias, which permits only allocating variables they use
32// - if the address is allowed to differ, functions need help to find it
33//
34// Uses from kernels are implemented here by grouping them in a per-kernel
35// struct instance. This duplicates the variables, accurately modelling their
36// aliasing properties relative to a single global representation. It also
37// permits control over alignment via padding.
38//
39// Uses from functions are more complicated and the primary purpose of this
40// IR pass. Several different lowering are chosen between to meet requirements
41// to avoid allocating any LDS where it is not necessary, as that impacts
42// occupancy and may fail the compilation, while not imposing overhead on a
43// feature whose primary advantage over global memory is performance. The basic
44// design goal is to avoid one kernel imposing overhead on another.
45//
46// Implementation.
47//
48// LDS variables with constant annotation or non-undef initializer are passed
49// through unchanged for simplification or error diagnostics in later passes.
50// Non-undef initializers are not yet implemented for LDS.
51//
52// LDS variables that are always allocated at the same address can be found
53// by lookup at that address. Otherwise runtime information/cost is required.
54//
55// The simplest strategy possible is to group all LDS variables in a single
56// struct and allocate that struct in every kernel such that the original
57// variables are always at the same address. LDS is however a limited resource
58// so this strategy is unusable in practice. It is not implemented here.
59//
60// Strategy | Precise allocation | Zero runtime cost | General purpose |
61// --------+--------------------+-------------------+-----------------+
62// Module | No | Yes | Yes |
63// Table | Yes | No | Yes |
64// Kernel | Yes | Yes | No |
65// Hybrid | Yes | Partial | Yes |
66//
67// "Module" spends LDS memory to save cycles. "Table" spends cycles and global
68// memory to save LDS. "Kernel" is as fast as kernel allocation but only works
69// for variables that are known reachable from a single kernel. "Hybrid" picks
70// between all three. When forced to choose between LDS and cycles we minimise
71// LDS use.
72
73// The "module" lowering implemented here finds LDS variables which are used by
74// non-kernel functions and creates a new struct with a field for each of those
75// LDS variables. Variables that are only used from kernels are excluded.
76//
77// The "table" lowering implemented here has three components.
78// First kernels are assigned a unique integer identifier which is available in
79// functions it calls through the intrinsic amdgcn_lds_kernel_id. The integer
80// is passed through a specific SGPR, thus works with indirect calls.
81// Second, each kernel allocates LDS variables independent of other kernels and
82// writes the addresses it chose for each variable into an array in consistent
83// order. If the kernel does not allocate a given variable, it writes undef to
84// the corresponding array location. These arrays are written to a constant
85// table in the order matching the kernel unique integer identifier.
86// Third, uses from non-kernel functions are replaced with a table lookup using
87// the intrinsic function to find the address of the variable.
88//
89// "Kernel" lowering is only applicable for variables that are unambiguously
90// reachable from exactly one kernel. For those cases, accesses to the variable
91// can be lowered to ConstantExpr address of a struct instance specific to that
92// one kernel. This is zero cost in space and in compute. It will raise a fatal
93// error on any variable that might be reachable from multiple kernels and is
94// thus most easily used as part of the hybrid lowering strategy.
95//
96// Hybrid lowering is a mixture of the above. It uses the zero cost kernel
97// lowering where it can. It lowers the variable accessed by the greatest
98// number of kernels using the module strategy as that is free for the first
99// variable. Any futher variables that can be lowered with the module strategy
100// without incurring LDS memory overhead are. The remaining ones are lowered
101// via table.
102//
103// Consequences
104// - No heuristics or user controlled magic numbers, hybrid is the right choice
105// - Kernels that don't use functions (or have had them all inlined) are not
106// affected by any lowering for kernels that do.
107// - Kernels that don't make indirect function calls are not affected by those
108// that do.
109// - Variables which are used by lots of kernels, e.g. those injected by a
110// language runtime in most kernels, are expected to have no overhead
111// - Implementations that instantiate templates per-kernel where those templates
112// use LDS are expected to hit the "Kernel" lowering strategy
113// - The runtime properties impose a cost in compiler implementation complexity
114//
115// Dynamic LDS implementation
116// Dynamic LDS is lowered similarly to the "table" strategy above and uses the
117// same intrinsic to identify which kernel is at the root of the dynamic call
118// graph. This relies on the specified behaviour that all dynamic LDS variables
119// alias one another, i.e. are at the same address, with respect to a given
120// kernel. Therefore this pass creates new dynamic LDS variables for each kernel
121// that allocates any dynamic LDS and builds a table of addresses out of those.
122// The AMDGPUPromoteAlloca pass skips kernels that use dynamic LDS.
123// The corresponding optimisation for "kernel" lowering where the table lookup
124// is elided is not implemented.
125//
126//
127// Implementation notes / limitations
128// A single LDS global variable represents an instance per kernel that can reach
129// said variables. This pass essentially specialises said variables per kernel.
130// Handling ConstantExpr during the pass complicated this significantly so now
131// all ConstantExpr uses of LDS variables are expanded to instructions. This
132// may need amending when implementing non-undef initialisers.
133//
134// Lowering is split between this IR pass and the back end. This pass chooses
135// where given variables should be allocated and marks them with metadata,
136// MD_absolute_symbol. The backend places the variables in coincidentally the
137// same location and raises a fatal error if something has gone awry. This works
138// in practice because the only pass between this one and the backend that
139// changes LDS is PromoteAlloca and the changes it makes do not conflict.
140//
141// Addresses are written to constant global arrays based on the same metadata.
142//
143// The backend lowers LDS variables in the order of traversal of the function.
144// This is at odds with the deterministic layout required. The workaround is to
145// allocate the fixed-address variables immediately upon starting the function
146// where they can be placed as intended. This requires a means of mapping from
147// the function to the variables that it allocates. For the module scope lds,
148// this is via metadata indicating whether the variable is not required. If a
149// pass deletes that metadata, a fatal error on disagreement with the absolute
150// symbol metadata will occur. For kernel scope and dynamic, this is by _name_
151// correspondence between the function and the variable. It requires the
152// kernel to have a name (which is only a limitation for tests in practice) and
153// for nothing to rename the corresponding symbols. This is a hazard if the pass
154// is run multiple times during debugging. Alternative schemes considered all
155// involve bespoke metadata.
156//
157// If the name correspondence can be replaced, multiple distinct kernels that
158// have the same memory layout can map to the same kernel id (as the address
159// itself is handled by the absolute symbol metadata) and that will allow more
160// uses of the "kernel" style faster lowering and reduce the size of the lookup
161// tables.
162//
163// There is a test that checks this does not fire for a graphics shader. This
164// lowering is expected to work for graphics if the isKernel test is changed.
165//
166// The current markUsedByKernel is sufficient for PromoteAlloca but is elided
167// before codegen. Replacing this with an equivalent intrinsic which lasts until
168// shortly after the machine function lowering of LDS would help break the name
169// mapping. The other part needed is probably to amend PromoteAlloca to embed
170// the LDS variables it creates in the same struct created here. That avoids the
171// current hazard where a PromoteAlloca LDS variable might be allocated before
172// the kernel scope (and thus error on the address check). Given a new invariant
173// that no LDS variables exist outside of the structs managed here, and an
174// intrinsic that lasts until after the LDS frame lowering, it should be
175// possible to drop the name mapping and fold equivalent memory layouts.
176//
177//===----------------------------------------------------------------------===//
178
179#include "AMDGPU.h"
180#include "AMDGPUMemoryUtils.h"
181#include "AMDGPUTargetMachine.h"
182#include "Utils/AMDGPUBaseInfo.h"
183#include "llvm/ADT/BitVector.h"
184#include "llvm/ADT/STLExtras.h"
185#include "llvm/ADT/SetOperations.h"
186#include "llvm/Analysis/CallGraph.h"
187#include "llvm/Analysis/ScopedNoAliasAA.h"
188#include "llvm/CodeGen/TargetPassConfig.h"
189#include "llvm/IR/Constants.h"
190#include "llvm/IR/DerivedTypes.h"
191#include "llvm/IR/Dominators.h"
192#include "llvm/IR/IRBuilder.h"
193#include "llvm/IR/InlineAsm.h"
194#include "llvm/IR/Instructions.h"
195#include "llvm/IR/IntrinsicsAMDGPU.h"
196#include "llvm/IR/MDBuilder.h"
197#include "llvm/IR/ReplaceConstant.h"
198#include "llvm/InitializePasses.h"
199#include "llvm/Pass.h"
200#include "llvm/Support/Format.h"
201#include "llvm/Support/OptimizedStructLayout.h"
202#include "llvm/Support/raw_ostream.h"
203#include "llvm/Transforms/Utils/BasicBlockUtils.h"
204#include "llvm/Transforms/Utils/ModuleUtils.h"
205
206#include <cstdio>
207
208#define DEBUG_TYPE "amdgpu-lower-module-lds"
209
210using namespace llvm;
211using namespace AMDGPU;
212
213namespace {
214
215template <typename T> std::vector<T> sortByName(std::vector<T> &&V) {
216 llvm::sort(V, [](const auto *L, const auto *R) {
217 return L->getName() < R->getName();
218 });
219 return {std::move(V)};
220}
221
222class AMDGPULowerModuleLDS {
223 const AMDGPUTargetMachine &TM;
224
225 static void
226 removeLocalVarsFromUsedLists(Module &M,
227 const DenseSet<GlobalVariable *> &LocalVars) {
228 // The verifier rejects used lists containing an inttoptr of a constant
229 // so remove the variables from these lists before replaceAllUsesWith
230 SmallPtrSet<Constant *, 8> LocalVarsSet;
231 for (GlobalVariable *LocalVar : LocalVars)
232 LocalVarsSet.insert(Ptr: cast<Constant>(Val: LocalVar->stripPointerCasts()));
233
234 removeFromUsedLists(
235 M, ShouldRemove: [&LocalVarsSet](Constant *C) { return LocalVarsSet.count(Ptr: C); });
236
237 for (GlobalVariable *LocalVar : LocalVars)
238 LocalVar->removeDeadConstantUsers();
239 }
240
241 static void markUsedByKernel(Function *Func, GlobalVariable *SGV) {
242 // The llvm.amdgcn.module.lds instance is implicitly used by all kernels
243 // that might call a function which accesses a field within it. This is
244 // presently approximated to 'all kernels' if there are any such functions
245 // in the module. This implicit use is redefined as an explicit use here so
246 // that later passes, specifically PromoteAlloca, account for the required
247 // memory without any knowledge of this transform.
248
249 // An operand bundle on llvm.donothing works because the call instruction
250 // survives until after the last pass that needs to account for LDS. It is
251 // better than inline asm as the latter survives until the end of codegen. A
252 // totally robust solution would be a function with the same semantics as
253 // llvm.donothing that takes a pointer to the instance and is lowered to a
254 // no-op after LDS is allocated, but that is not presently necessary.
255
256 // This intrinsic is eliminated shortly before instruction selection. It
257 // does not suffice to indicate to ISel that a given global which is not
258 // immediately used by the kernel must still be allocated by it. An
259 // equivalent target specific intrinsic which lasts until immediately after
260 // codegen would suffice for that, but one would still need to ensure that
261 // the variables are allocated in the anticipated order.
262 BasicBlock *Entry = &Func->getEntryBlock();
263 IRBuilder<> Builder(Entry->getFirstNonPHIIt());
264
265 Function *Decl = Intrinsic::getOrInsertDeclaration(
266 M: Func->getParent(), id: Intrinsic::donothing, OverloadTys: {});
267
268 Value *UseInstance[] = {SGV};
269
270 Builder.CreateCall(
271 Callee: Decl, Args: {}, OpBundles: {OperandBundleDefT<Value *>("ExplicitUse", UseInstance)});
272 }
273
274public:
275 AMDGPULowerModuleLDS(const AMDGPUTargetMachine &TM_) : TM(TM_) {}
276
277 struct LDSVariableReplacement {
278 GlobalVariable *SGV = nullptr;
279 DenseMap<GlobalVariable *, Constant *> LDSVarsToConstantGEP;
280 };
281
282 // remap from lds global to a constantexpr gep to where it has been moved to
283 // for each kernel
284 // an array with an element for each kernel containing where the corresponding
285 // variable was remapped to
286
287 static Constant *getAddressesOfVariablesInKernel(
288 LLVMContext &Ctx, ArrayRef<GlobalVariable *> Variables,
289 const DenseMap<GlobalVariable *, Constant *> &LDSVarsToConstantGEP) {
290 // Create a ConstantArray containing the address of each Variable within the
291 // kernel corresponding to LDSVarsToConstantGEP, or poison if that kernel
292 // does not allocate it
293
294 Type *LocalPtrTy = PointerType::get(C&: Ctx, AddressSpace: AMDGPUAS::LOCAL_ADDRESS);
295 ArrayType *KernelOffsetsType = ArrayType::get(ElementType: LocalPtrTy, NumElements: Variables.size());
296
297 SmallVector<Constant *> Elements;
298 for (GlobalVariable *GV : Variables) {
299 auto ConstantGepIt = LDSVarsToConstantGEP.find(Val: GV);
300 if (ConstantGepIt != LDSVarsToConstantGEP.end()) {
301 Elements.push_back(Elt: ConstantGepIt->second);
302 } else {
303 Elements.push_back(Elt: PoisonValue::get(T: LocalPtrTy));
304 }
305 }
306 return ConstantArray::get(T: KernelOffsetsType, V: Elements);
307 }
308
309 static GlobalVariable *buildLookupTable(
310 Module &M, ArrayRef<GlobalVariable *> Variables,
311 ArrayRef<Function *> kernels,
312 DenseMap<Function *, LDSVariableReplacement> &KernelToReplacement) {
313 if (Variables.empty()) {
314 return nullptr;
315 }
316 LLVMContext &Ctx = M.getContext();
317
318 const size_t NumberVariables = Variables.size();
319 const size_t NumberKernels = kernels.size();
320
321 Type *LocalPtrTy = PointerType::get(C&: Ctx, AddressSpace: AMDGPUAS::LOCAL_ADDRESS);
322 ArrayType *KernelOffsetsType = ArrayType::get(ElementType: LocalPtrTy, NumElements: NumberVariables);
323
324 ArrayType *AllKernelsOffsetsType =
325 ArrayType::get(ElementType: KernelOffsetsType, NumElements: NumberKernels);
326
327 Constant *Missing = PoisonValue::get(T: KernelOffsetsType);
328 std::vector<Constant *> overallConstantExprElts(NumberKernels);
329 for (size_t i = 0; i < NumberKernels; i++) {
330 auto Replacement = KernelToReplacement.find(Val: kernels[i]);
331 overallConstantExprElts[i] =
332 (Replacement == KernelToReplacement.end())
333 ? Missing
334 : getAddressesOfVariablesInKernel(
335 Ctx, Variables, LDSVarsToConstantGEP: Replacement->second.LDSVarsToConstantGEP);
336 }
337
338 Constant *init =
339 ConstantArray::get(T: AllKernelsOffsetsType, V: overallConstantExprElts);
340
341 return new GlobalVariable(
342 M, AllKernelsOffsetsType, true, GlobalValue::InternalLinkage, init,
343 "llvm.amdgcn.lds.offset.table", nullptr, GlobalValue::NotThreadLocal,
344 AMDGPUAS::CONSTANT_ADDRESS);
345 }
346
347 void replaceUseWithTableLookup(Module &M, IRBuilder<> &Builder,
348 GlobalVariable *LookupTable,
349 GlobalVariable *GV, Use &U,
350 Value *OptionalIndex) {
351 // Table is a constant array of the same length as OrderedKernels
352 LLVMContext &Ctx = M.getContext();
353 Type *I32 = Type::getInt32Ty(C&: Ctx);
354 auto *I = cast<Instruction>(Val: U.getUser());
355
356 Value *tableKernelIndex = getTableLookupKernelIndex(M, F: I->getFunction());
357
358 if (auto *Phi = dyn_cast<PHINode>(Val: I)) {
359 BasicBlock *BB = Phi->getIncomingBlock(U);
360 Builder.SetInsertPoint(&(*(BB->getFirstInsertionPt())));
361 } else {
362 Builder.SetInsertPoint(I);
363 }
364
365 SmallVector<Value *, 3> GEPIdx = {
366 ConstantInt::get(Ty: I32, V: 0),
367 tableKernelIndex,
368 };
369 if (OptionalIndex)
370 GEPIdx.push_back(Elt: OptionalIndex);
371
372 Value *Address = Builder.CreateInBoundsGEP(
373 Ty: LookupTable->getValueType(), Ptr: LookupTable, IdxList: GEPIdx, Name: GV->getName());
374
375 Value *Loaded = Builder.CreateLoad(Ty: GV->getType(), Ptr: Address);
376 U.set(Loaded);
377 }
378
379 void replaceUsesInInstructionsWithTableLookup(
380 Module &M, ArrayRef<GlobalVariable *> ModuleScopeVariables,
381 GlobalVariable *LookupTable) {
382
383 LLVMContext &Ctx = M.getContext();
384 IRBuilder<> Builder(M);
385 Type *I32 = Type::getInt32Ty(C&: Ctx);
386
387 for (size_t Index = 0; Index < ModuleScopeVariables.size(); Index++) {
388 auto *GV = ModuleScopeVariables[Index];
389
390 for (Use &U : make_early_inc_range(Range: GV->uses())) {
391 auto *I = dyn_cast<Instruction>(Val: U.getUser());
392 if (!I)
393 continue;
394
395 replaceUseWithTableLookup(M, Builder, LookupTable, GV, U,
396 OptionalIndex: ConstantInt::get(Ty: I32, V: Index));
397 }
398 }
399 }
400
401 static DenseSet<Function *> kernelsThatIndirectlyAccessAnyOfPassedVariables(
402 Module &M, GVUsesInfoTy &LDSUsesInfo,
403 DenseSet<GlobalVariable *> const &VariableSet) {
404
405 DenseSet<Function *> KernelSet;
406
407 if (VariableSet.empty())
408 return KernelSet;
409
410 for (Function &Func : M.functions()) {
411 if (Func.isDeclaration() || !isKernel(F: Func))
412 continue;
413 for (GlobalVariable *GV : LDSUsesInfo.IndirectAccess[&Func]) {
414 if (VariableSet.contains(V: GV)) {
415 KernelSet.insert(V: &Func);
416 break;
417 }
418 }
419 }
420
421 return KernelSet;
422 }
423
424 static GlobalVariable *
425 chooseBestVariableForModuleStrategy(const DataLayout &DL,
426 VariableFunctionMap &LDSVars) {
427 // Find the global variable with the most indirect uses from kernels
428
429 struct CandidateTy {
430 GlobalVariable *GV = nullptr;
431 size_t UserCount = 0;
432 size_t Size = 0;
433
434 CandidateTy() = default;
435
436 CandidateTy(GlobalVariable *GV, uint64_t UserCount, uint64_t AllocSize)
437 : GV(GV), UserCount(UserCount), Size(AllocSize) {}
438
439 bool operator<(const CandidateTy &Other) const {
440 // Fewer users makes module scope variable less attractive
441 if (UserCount < Other.UserCount) {
442 return true;
443 }
444 if (UserCount > Other.UserCount) {
445 return false;
446 }
447
448 // Bigger makes module scope variable less attractive
449 if (Size < Other.Size) {
450 return false;
451 }
452
453 if (Size > Other.Size) {
454 return true;
455 }
456
457 // Arbitrary but consistent
458 return GV->getName() < Other.GV->getName();
459 }
460 };
461
462 CandidateTy MostUsed;
463
464 for (auto &K : LDSVars) {
465 GlobalVariable *GV = K.first;
466 if (K.second.size() <= 1) {
467 // A variable reachable by only one kernel is best lowered with kernel
468 // strategy
469 continue;
470 }
471 CandidateTy Candidate(GV, K.second.size(), GV->getGlobalSize(DL));
472 if (MostUsed < Candidate)
473 MostUsed = Candidate;
474 }
475
476 return MostUsed.GV;
477 }
478
479 static void recordLDSAbsoluteAddress(Module *M, GlobalVariable *GV,
480 uint32_t Address) {
481 // Write the specified address into metadata where it can be retrieved by
482 // the assembler. Format is a half open range, [Address Address+1)
483 LLVMContext &Ctx = M->getContext();
484 auto *IntTy =
485 M->getDataLayout().getIntPtrType(C&: Ctx, AddressSpace: AMDGPUAS::LOCAL_ADDRESS);
486 auto *MinC = ConstantAsMetadata::get(C: ConstantInt::get(Ty: IntTy, V: Address));
487 auto *MaxC = ConstantAsMetadata::get(C: ConstantInt::get(Ty: IntTy, V: Address + 1));
488 GV->setMetadata(KindID: LLVMContext::MD_absolute_symbol,
489 Node: MDNode::get(Context&: Ctx, MDs: {MinC, MaxC}));
490 }
491
492 DenseMap<Function *, Value *> tableKernelIndexCache;
493 Value *getTableLookupKernelIndex(Module &M, Function *F) {
494 // Accesses from a function use the amdgcn_lds_kernel_id intrinsic which
495 // lowers to a read from a live in register. Emit it once in the entry
496 // block to spare deduplicating it later.
497 auto [It, Inserted] = tableKernelIndexCache.try_emplace(Key: F);
498 if (Inserted) {
499 auto InsertAt = F->getEntryBlock().getFirstNonPHIOrAlloca();
500 IRBuilder<> Builder(&*InsertAt);
501
502 It->second = Builder.CreateIntrinsic(ID: Intrinsic::amdgcn_lds_kernel_id, Args: {});
503 }
504
505 return It->second;
506 }
507
508 static std::vector<Function *> assignLDSKernelIDToEachKernel(
509 Module *M, DenseSet<Function *> const &KernelsThatAllocateTableLDS,
510 DenseSet<Function *> const &KernelsThatIndirectlyAllocateDynamicLDS) {
511 // Associate kernels in the set with an arbitrary but reproducible order and
512 // annotate them with that order in metadata. This metadata is recognised by
513 // the backend and lowered to a SGPR which can be read from using
514 // amdgcn_lds_kernel_id.
515
516 std::vector<Function *> OrderedKernels;
517 if (!KernelsThatAllocateTableLDS.empty() ||
518 !KernelsThatIndirectlyAllocateDynamicLDS.empty()) {
519
520 for (Function &Func : M->functions()) {
521 if (Func.isDeclaration())
522 continue;
523 if (!isKernel(F: Func))
524 continue;
525
526 if (KernelsThatAllocateTableLDS.contains(V: &Func) ||
527 KernelsThatIndirectlyAllocateDynamicLDS.contains(V: &Func)) {
528 assert(Func.hasName()); // else fatal error earlier
529 OrderedKernels.push_back(x: &Func);
530 }
531 }
532
533 // Put them in an arbitrary but reproducible order
534 OrderedKernels = sortByName(V: std::move(OrderedKernels));
535
536 // Annotate the kernels with their order in this vector
537 LLVMContext &Ctx = M->getContext();
538 IRBuilder<> Builder(*M);
539
540 if (OrderedKernels.size() > UINT32_MAX) {
541 // 32 bit keeps it in one SGPR. > 2**32 kernels won't fit on the GPU
542 reportFatalUsageError(reason: "unimplemented LDS lowering for > 2**32 kernels");
543 }
544
545 for (size_t i = 0; i < OrderedKernels.size(); i++) {
546 Metadata *AttrMDArgs[1] = {
547 ConstantAsMetadata::get(C: Builder.getInt32(C: i)),
548 };
549 OrderedKernels[i]->setMetadata(Kind: "llvm.amdgcn.lds.kernel.id",
550 Node: MDNode::get(Context&: Ctx, MDs: AttrMDArgs));
551 }
552 }
553 return OrderedKernels;
554 }
555
556 void partitionVariablesIntoIndirectStrategies(
557 Module &M, GVUsesInfoTy const &LDSUsesInfo,
558 VariableFunctionMap &LDSToKernelsThatNeedToAccessItIndirectly,
559 DenseSet<GlobalVariable *> &ModuleScopeVariables,
560 DenseSet<GlobalVariable *> &TableLookupVariables,
561 DenseSet<GlobalVariable *> &KernelAccessVariables,
562 DenseSet<GlobalVariable *> &DynamicVariables) {
563 LDSLoweringKind LoweringKind = TM.getCLOpts().lower_module_lds_strategy;
564
565 GlobalVariable *HybridModuleRoot =
566 LoweringKind != LDSLoweringKind::hybrid
567 ? nullptr
568 : chooseBestVariableForModuleStrategy(
569 DL: M.getDataLayout(), LDSVars&: LDSToKernelsThatNeedToAccessItIndirectly);
570
571 DenseSet<Function *> const EmptySet;
572 DenseSet<Function *> const &HybridModuleRootKernels =
573 HybridModuleRoot
574 ? LDSToKernelsThatNeedToAccessItIndirectly[HybridModuleRoot]
575 : EmptySet;
576
577 for (auto &K : LDSToKernelsThatNeedToAccessItIndirectly) {
578 // Each iteration of this loop assigns exactly one global variable to
579 // exactly one of the implementation strategies.
580
581 GlobalVariable *GV = K.first;
582 assert(AMDGPU::isLDSVariableToLower(*GV));
583 assert(!K.second.empty());
584
585 if (AMDGPU::isDynamicLDS(GV: *GV)) {
586 DynamicVariables.insert(V: GV);
587 continue;
588 }
589
590 switch (LoweringKind) {
591 case LDSLoweringKind::module:
592 ModuleScopeVariables.insert(V: GV);
593 break;
594
595 case LDSLoweringKind::table:
596 TableLookupVariables.insert(V: GV);
597 break;
598
599 case LDSLoweringKind::kernel:
600 if (K.second.size() == 1) {
601 KernelAccessVariables.insert(V: GV);
602 } else {
603 // FIXME: This should use DiagnosticInfo
604 reportFatalUsageError(
605 reason: "cannot lower LDS '" + GV->getName() +
606 "' to kernel access as it is reachable from multiple kernels");
607 }
608 break;
609
610 case LDSLoweringKind::hybrid: {
611 if (GV == HybridModuleRoot) {
612 assert(K.second.size() != 1);
613 ModuleScopeVariables.insert(V: GV);
614 } else if (K.second.size() == 1) {
615 KernelAccessVariables.insert(V: GV);
616 } else if (K.second == HybridModuleRootKernels) {
617 ModuleScopeVariables.insert(V: GV);
618 } else {
619 TableLookupVariables.insert(V: GV);
620 }
621 break;
622 }
623 }
624 }
625
626 // All LDS variables accessed indirectly have now been partitioned into
627 // the distinct lowering strategies.
628 assert(ModuleScopeVariables.size() + TableLookupVariables.size() +
629 KernelAccessVariables.size() + DynamicVariables.size() ==
630 LDSToKernelsThatNeedToAccessItIndirectly.size());
631 }
632
633 static GlobalVariable *lowerModuleScopeStructVariables(
634 Module &M, DenseSet<GlobalVariable *> const &ModuleScopeVariables,
635 DenseSet<Function *> const &KernelsThatAllocateModuleLDS) {
636 // Create a struct to hold the ModuleScopeVariables
637 // Replace all uses of those variables from non-kernel functions with the
638 // new struct instance Replace only the uses from kernel functions that will
639 // allocate this instance. That is a space optimisation - kernels that use a
640 // subset of the module scope struct and do not need to allocate it for
641 // indirect calls will only allocate the subset they use (they do so as part
642 // of the per-kernel lowering).
643 if (ModuleScopeVariables.empty()) {
644 return nullptr;
645 }
646
647 LLVMContext &Ctx = M.getContext();
648
649 LDSVariableReplacement ModuleScopeReplacement =
650 createLDSVariableReplacement(M, VarName: "llvm.amdgcn.module.lds",
651 LDSVarsToTransform: ModuleScopeVariables);
652
653 appendToCompilerUsed(M, Values: {static_cast<GlobalValue *>(
654 ConstantExpr::getPointerBitCastOrAddrSpaceCast(
655 C: cast<Constant>(Val: ModuleScopeReplacement.SGV),
656 Ty: PointerType::getUnqual(C&: Ctx)))});
657
658 // module.lds will be allocated at zero in any kernel that allocates it
659 recordLDSAbsoluteAddress(M: &M, GV: ModuleScopeReplacement.SGV, Address: 0);
660
661 // historic
662 removeLocalVarsFromUsedLists(M, LocalVars: ModuleScopeVariables);
663
664 // Replace all uses of module scope variable from non-kernel functions
665 replaceLDSVariablesWithStruct(
666 M, LDSVarsToTransformArg: ModuleScopeVariables, Replacement: ModuleScopeReplacement, Predicate: [&](Use &U) {
667 Instruction *I = dyn_cast<Instruction>(Val: U.getUser());
668 if (!I) {
669 return false;
670 }
671 Function *F = I->getFunction();
672 return !isKernel(F: *F);
673 });
674
675 // Replace uses of module scope variable from kernel functions that
676 // allocate the module scope variable, otherwise leave them unchanged
677 // Record on each kernel whether the module scope global is used by it
678
679 for (Function &Func : M.functions()) {
680 if (Func.isDeclaration() || !isKernel(F: Func))
681 continue;
682
683 if (KernelsThatAllocateModuleLDS.contains(V: &Func)) {
684 replaceLDSVariablesWithStruct(
685 M, LDSVarsToTransformArg: ModuleScopeVariables, Replacement: ModuleScopeReplacement, Predicate: [&](Use &U) {
686 Instruction *I = dyn_cast<Instruction>(Val: U.getUser());
687 if (!I) {
688 return false;
689 }
690 Function *F = I->getFunction();
691 return F == &Func;
692 });
693
694 markUsedByKernel(Func: &Func, SGV: ModuleScopeReplacement.SGV);
695 }
696 }
697
698 return ModuleScopeReplacement.SGV;
699 }
700
701 static DenseMap<Function *, LDSVariableReplacement>
702 lowerKernelScopeStructVariables(
703 Module &M, GVUsesInfoTy &LDSUsesInfo,
704 DenseSet<GlobalVariable *> const &ModuleScopeVariables,
705 DenseSet<Function *> const &KernelsThatAllocateModuleLDS,
706 GlobalVariable *MaybeModuleScopeStruct) {
707
708 // Create a struct for each kernel for the non-module-scope variables.
709
710 DenseMap<Function *, LDSVariableReplacement> KernelToReplacement;
711 for (Function &Func : M.functions()) {
712 if (Func.isDeclaration() || !isKernel(F: Func))
713 continue;
714
715 DenseSet<GlobalVariable *> KernelUsedVariables;
716 // Allocating variables that are used directly in this struct to get
717 // alignment aware allocation and predictable frame size.
718 for (auto &v : LDSUsesInfo.DirectAccess[&Func]) {
719 if (!AMDGPU::isDynamicLDS(GV: *v)) {
720 KernelUsedVariables.insert(V: v);
721 }
722 }
723
724 // Allocating variables that are accessed indirectly so that a lookup of
725 // this struct instance can find them from nested functions.
726 for (auto &v : LDSUsesInfo.IndirectAccess[&Func]) {
727 if (!AMDGPU::isDynamicLDS(GV: *v)) {
728 KernelUsedVariables.insert(V: v);
729 }
730 }
731
732 // Variables allocated in module lds must all resolve to that struct,
733 // not to the per-kernel instance.
734 if (KernelsThatAllocateModuleLDS.contains(V: &Func)) {
735 for (GlobalVariable *v : ModuleScopeVariables) {
736 KernelUsedVariables.erase(V: v);
737 }
738 }
739
740 if (KernelUsedVariables.empty()) {
741 // Either used no LDS, or the LDS it used was all in the module struct
742 // or dynamically sized
743 continue;
744 }
745
746 // The association between kernel function and LDS struct is done by
747 // symbol name, which only works if the function in question has a
748 // name This is not expected to be a problem in practice as kernels
749 // are called by name making anonymous ones (which are named by the
750 // backend) difficult to use. This does mean that llvm test cases need
751 // to name the kernels.
752 if (!Func.hasName()) {
753 reportFatalUsageError(reason: "anonymous kernels cannot use LDS variables");
754 }
755
756 std::string VarName =
757 (Twine("llvm.amdgcn.kernel.") + Func.getName() + ".lds").str();
758
759 auto Replacement =
760 createLDSVariableReplacement(M, VarName, LDSVarsToTransform: KernelUsedVariables);
761
762 // If any indirect uses, create a direct use to ensure allocation
763 // TODO: Simpler to unconditionally mark used but that regresses
764 // codegen in test/CodeGen/AMDGPU/noclobber-barrier.ll
765 auto Accesses = LDSUsesInfo.IndirectAccess.find(Key: &Func);
766 if ((Accesses != LDSUsesInfo.IndirectAccess.end()) &&
767 !Accesses->second.empty())
768 markUsedByKernel(Func: &Func, SGV: Replacement.SGV);
769
770 // remove preserves existing codegen
771 removeLocalVarsFromUsedLists(M, LocalVars: KernelUsedVariables);
772 KernelToReplacement[&Func] = Replacement;
773
774 // Rewrite uses within kernel to the new struct
775 replaceLDSVariablesWithStruct(
776 M, LDSVarsToTransformArg: KernelUsedVariables, Replacement, Predicate: [&Func](Use &U) {
777 Instruction *I = dyn_cast<Instruction>(Val: U.getUser());
778 return I && I->getFunction() == &Func;
779 });
780 }
781 return KernelToReplacement;
782 }
783
784 static GlobalVariable *
785 buildRepresentativeDynamicLDSInstance(Module &M, GVUsesInfoTy &LDSUsesInfo,
786 Function *func) {
787 // Create a dynamic lds variable with a name associated with the passed
788 // function that has the maximum alignment of any dynamic lds variable
789 // reachable from this kernel. Dynamic LDS is allocated after the static LDS
790 // allocation, possibly after alignment padding. The representative variable
791 // created here has the maximum alignment of any other dynamic variable
792 // reachable by that kernel. All dynamic LDS variables are allocated at the
793 // same address in each kernel in order to provide the documented aliasing
794 // semantics. Setting the alignment here allows this IR pass to accurately
795 // predict the exact constant at which it will be allocated.
796
797 assert(isKernel(*func));
798
799 LLVMContext &Ctx = M.getContext();
800 const DataLayout &DL = M.getDataLayout();
801 Align MaxDynamicAlignment(1);
802
803 auto UpdateMaxAlignment = [&MaxDynamicAlignment, &DL](GlobalVariable *GV) {
804 if (AMDGPU::isDynamicLDS(GV: *GV)) {
805 MaxDynamicAlignment =
806 std::max(a: MaxDynamicAlignment, b: AMDGPU::getAlign(DL, GV));
807 }
808 };
809
810 for (GlobalVariable *GV : LDSUsesInfo.IndirectAccess[func]) {
811 UpdateMaxAlignment(GV);
812 }
813
814 for (GlobalVariable *GV : LDSUsesInfo.DirectAccess[func]) {
815 UpdateMaxAlignment(GV);
816 }
817
818 assert(func->hasName()); // Checked by caller
819 auto *emptyCharArray = ArrayType::get(ElementType: Type::getInt8Ty(C&: Ctx), NumElements: 0);
820 GlobalVariable *N = new GlobalVariable(
821 M, emptyCharArray, false, GlobalValue::ExternalLinkage, nullptr,
822 Twine("llvm.amdgcn." + func->getName() + ".dynlds"), nullptr,
823 GlobalValue::NotThreadLocal, AMDGPUAS::LOCAL_ADDRESS, false);
824 N->setAlignment(MaxDynamicAlignment);
825
826 assert(AMDGPU::isDynamicLDS(*N));
827 return N;
828 }
829
830 DenseMap<Function *, GlobalVariable *> lowerDynamicLDSVariables(
831 Module &M, GVUsesInfoTy &LDSUsesInfo,
832 DenseSet<Function *> const &KernelsThatIndirectlyAllocateDynamicLDS,
833 DenseSet<GlobalVariable *> const &DynamicVariables,
834 std::vector<Function *> const &OrderedKernels) {
835 DenseMap<Function *, GlobalVariable *> KernelToCreatedDynamicLDS;
836 if (!KernelsThatIndirectlyAllocateDynamicLDS.empty()) {
837 LLVMContext &Ctx = M.getContext();
838 IRBuilder<> Builder(M);
839 Type *LocalPtrTy = PointerType::get(C&: Ctx, AddressSpace: AMDGPUAS::LOCAL_ADDRESS);
840
841 std::vector<Constant *> newDynamicLDS;
842
843 // Table is built in the same order as OrderedKernels
844 for (auto &func : OrderedKernels) {
845
846 if (KernelsThatIndirectlyAllocateDynamicLDS.contains(V: func)) {
847 assert(isKernel(*func));
848 if (!func->hasName()) {
849 reportFatalUsageError(reason: "anonymous kernels cannot use LDS variables");
850 }
851
852 GlobalVariable *N =
853 buildRepresentativeDynamicLDSInstance(M, LDSUsesInfo, func);
854
855 KernelToCreatedDynamicLDS[func] = N;
856
857 markUsedByKernel(Func: func, SGV: N);
858
859 newDynamicLDS.push_back(x: N);
860 } else {
861 newDynamicLDS.push_back(x: PoisonValue::get(T: LocalPtrTy));
862 }
863 }
864 assert(OrderedKernels.size() == newDynamicLDS.size());
865
866 ArrayType *t = ArrayType::get(ElementType: LocalPtrTy, NumElements: newDynamicLDS.size());
867 Constant *init = ConstantArray::get(T: t, V: newDynamicLDS);
868 GlobalVariable *table = new GlobalVariable(
869 M, t, true, GlobalValue::InternalLinkage, init,
870 "llvm.amdgcn.dynlds.offset.table", nullptr,
871 GlobalValue::NotThreadLocal, AMDGPUAS::CONSTANT_ADDRESS);
872
873 for (GlobalVariable *GV : DynamicVariables) {
874 for (Use &U : make_early_inc_range(Range: GV->uses())) {
875 auto *I = dyn_cast<Instruction>(Val: U.getUser());
876 if (!I)
877 continue;
878 if (isKernel(F: *I->getFunction()))
879 continue;
880
881 replaceUseWithTableLookup(M, Builder, LookupTable: table, GV, U, OptionalIndex: nullptr);
882 }
883 }
884 }
885 return KernelToCreatedDynamicLDS;
886 }
887
888 // Per-TU mode for link-time LDS resolution. Instead of computing a global
889 // layout, create per-function LDS struct declarations so the linker can
890 // assign offsets across TUs.
891 bool runOnModuleLinkTime(Module &M) {
892 bool Changed = superAlignLDSGlobals(M);
893 Changed |=
894 eliminateGVConstantExprUsesFromAllInstructions(M, Filter: isLDSVariableToLower);
895
896 CallGraph CG(M);
897 FunctionVariableMap KernelLDSUses, FunctionLDSUses;
898 getUsesOfGVByFunction(CG, M, Filter: isLDSVariableToLower, Kernels&: KernelLDSUses,
899 Functions&: FunctionLDSUses);
900
901 if (KernelLDSUses.empty() && FunctionLDSUses.empty())
902 return Changed;
903
904 std::string ModuleId = getUniqueModuleId(M: &M);
905 assert(!ModuleId.empty() &&
906 "modules with LDS variables should have a unique ID");
907
908 FunctionVariableMap AllLDSUses;
909 for (auto &[F, Vars] : KernelLDSUses)
910 AllLDSUses[F].insert(I: Vars.begin(), E: Vars.end());
911 for (auto &[F, Vars] : FunctionLDSUses)
912 AllLDSUses[F].insert(I: Vars.begin(), E: Vars.end());
913
914 // Build reverse map: LDS variable -> functions that use it.
915 DenseMap<GlobalVariable *, SmallVector<Function *, 4>> VarToFuncs;
916 for (auto &[F, Vars] : AllLDSUses) {
917 for (GlobalVariable *V : Vars)
918 VarToFuncs[V].push_back(Elt: F);
919 }
920
921 // A variable is function-scope iff it has local linkage and exactly one
922 // user function. Everything else is global-scope and must remain as a
923 // standalone external declaration so the linker can assign a single shared
924 // offset.
925 DenseSet<GlobalVariable *> GlobalScopeVars;
926 DenseSet<GlobalVariable *> InternalMultiUserVars;
927 for (auto &[V, Funcs] : VarToFuncs) {
928 if (!V->hasLocalLinkage() || Funcs.size() > 1) {
929 GlobalScopeVars.insert(V);
930 if (V->hasLocalLinkage())
931 InternalMultiUserVars.insert(V);
932 }
933 }
934
935 // Wrap function-scope LDS into per-function structs (unchanged logic,
936 // but global-scope variables are excluded from the set).
937 SmallVector<std::pair<Function *, GlobalVariable *>, 4> FuncToLdsStruct;
938 DenseSet<GlobalVariable *> AllReplacedVars;
939 for (auto &KV : AllLDSUses) {
940 Function *F = KV.first;
941 DenseSet<GlobalVariable *> FuncScopeVars;
942 for (GlobalVariable *V : KV.second) {
943 if (!GlobalScopeVars.count(V))
944 FuncScopeVars.insert(V);
945 }
946
947 if (FuncScopeVars.empty())
948 continue;
949
950 std::string StructName =
951 F->hasLocalLinkage()
952 ? ("__amdgpu_lds." + F->getName() + "." + ModuleId).str()
953 : ("__amdgpu_lds." + F->getName()).str();
954 LDSVariableReplacement Replacement =
955 createLDSVariableReplacement(M, VarName: StructName, LDSVarsToTransform: FuncScopeVars);
956
957 GlobalVariable *SGV = Replacement.SGV;
958 SGV->setLinkage(GlobalValue::ExternalLinkage);
959 SGV->setInitializer(nullptr);
960 FuncToLdsStruct.push_back(Elt: {F, SGV});
961
962 replaceLDSVariablesWithStruct(
963 M, LDSVarsToTransformArg: FuncScopeVars, Replacement, Predicate: [F](const Use &U) {
964 auto *I = dyn_cast<Instruction>(Val: U.getUser());
965 return I && I->getFunction() == F;
966 });
967
968 AllReplacedVars.insert(I: FuncScopeVars.begin(), E: FuncScopeVars.end());
969 }
970
971 // Internal-linkage LDS variables used by multiple functions would collide
972 // across TUs if promoted individually to external linkage (same name in
973 // different TUs). Pack them into a single per-module struct with a
974 // module-unique name so the linker treats them as one allocation unit.
975 if (!InternalMultiUserVars.empty()) {
976 std::string StructName = "__amdgpu_lds.__internal." + ModuleId;
977 LDSVariableReplacement Replacement =
978 createLDSVariableReplacement(M, VarName: StructName, LDSVarsToTransform: InternalMultiUserVars);
979
980 GlobalVariable *SGV = Replacement.SGV;
981 SGV->setLinkage(GlobalValue::ExternalLinkage);
982 SGV->setInitializer(nullptr);
983
984 replaceLDSVariablesWithStruct(
985 M, LDSVarsToTransformArg: InternalMultiUserVars, Replacement,
986 Predicate: [](const Use &U) { return isa<Instruction>(Val: U.getUser()); });
987
988 DenseSet<Function *> FuncsUsingInternalVars;
989 for (GlobalVariable *V : InternalMultiUserVars) {
990 for (Function *F : VarToFuncs[V])
991 FuncsUsingInternalVars.insert(V: F);
992 }
993 for (Function *F : FuncsUsingInternalVars)
994 FuncToLdsStruct.push_back(Elt: {F, SGV});
995
996 AllReplacedVars.insert(I: InternalMultiUserVars.begin(),
997 E: InternalMultiUserVars.end());
998 }
999
1000 // Convert global-scope LDS to external declarations. Their uses remain
1001 // intact and ISel generates R_AMDGPU_ABS32_LO relocations for them.
1002 for (GlobalVariable *V : GlobalScopeVars) {
1003 V->setInitializer(nullptr);
1004 V->setLinkage(GlobalValue::ExternalLinkage);
1005 }
1006
1007 // Emit amdgpu.lds.uses metadata for struct and global-scope LDS.
1008 {
1009 LLVMContext &Ctx = M.getContext();
1010 NamedMDNode *LdsMD = M.getOrInsertNamedMetadata(Name: "amdgpu.lds.uses");
1011
1012 for (auto &[F, SGV] : FuncToLdsStruct)
1013 LdsMD->addOperand(M: MDNode::get(
1014 Context&: Ctx, MDs: {ValueAsMetadata::get(V: F), ValueAsMetadata::get(V: SGV)}));
1015
1016 for (auto &[V, Funcs] : VarToFuncs) {
1017 if (GlobalScopeVars.count(V) && !InternalMultiUserVars.count(V)) {
1018 for (Function *F : Funcs) {
1019 LdsMD->addOperand(M: MDNode::get(
1020 Context&: Ctx, MDs: {ValueAsMetadata::get(V: F), ValueAsMetadata::get(V)}));
1021 }
1022 }
1023 }
1024 }
1025
1026 DenseSet<GlobalVariable *> AllLDSVarsForCleanup = AllReplacedVars;
1027 AllLDSVarsForCleanup.insert(I: GlobalScopeVars.begin(), E: GlobalScopeVars.end());
1028 removeLocalVarsFromUsedLists(M, LocalVars: AllLDSVarsForCleanup);
1029 for (GlobalVariable *GV : AllReplacedVars) {
1030 GV->removeDeadConstantUsers();
1031 if (GV->use_empty())
1032 GV->eraseFromParent();
1033 }
1034
1035 return true;
1036 }
1037
1038 bool runOnModule(Module &M) {
1039 if (AMDGPUTargetMachine::EnableObjectLinking)
1040 return runOnModuleLinkTime(M);
1041 return runOnModuleNormal(M);
1042 }
1043
1044 bool runOnModuleNormal(Module &M) {
1045 bool Changed = superAlignLDSGlobals(M);
1046
1047 Changed |= any_of(Range: M.globals(), P: isNotYetLoweredLDSVariable);
1048
1049 CallGraph CG(M);
1050
1051 eliminateGVConstantExprUsesFromAllInstructions(M,
1052 Filter: isNotYetLoweredLDSVariable);
1053
1054 // For each kernel, what variables does it access directly or through
1055 // callees
1056 GVUsesInfoTy LDSUsesInfo = getTransitiveUsesOfLDSForLowering(CG, M);
1057
1058 // For each variable accessed through callees, which kernels access it
1059 VariableFunctionMap LDSToKernelsThatNeedToAccessItIndirectly;
1060 for (auto &K : LDSUsesInfo.IndirectAccess) {
1061 Function *F = K.first;
1062 assert(isKernel(*F));
1063 for (GlobalVariable *GV : K.second) {
1064 LDSToKernelsThatNeedToAccessItIndirectly[GV].insert(V: F);
1065 }
1066 }
1067
1068 // Partition variables accessed indirectly into the different strategies
1069 DenseSet<GlobalVariable *> ModuleScopeVariables;
1070 DenseSet<GlobalVariable *> TableLookupVariables;
1071 DenseSet<GlobalVariable *> KernelAccessVariables;
1072 DenseSet<GlobalVariable *> DynamicVariables;
1073 partitionVariablesIntoIndirectStrategies(
1074 M, LDSUsesInfo, LDSToKernelsThatNeedToAccessItIndirectly,
1075 ModuleScopeVariables, TableLookupVariables, KernelAccessVariables,
1076 DynamicVariables);
1077
1078 // If the kernel accesses a variable that is going to be stored in the
1079 // module instance through a call then that kernel needs to allocate the
1080 // module instance
1081 const DenseSet<Function *> KernelsThatAllocateModuleLDS =
1082 kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo,
1083 VariableSet: ModuleScopeVariables);
1084 const DenseSet<Function *> KernelsThatAllocateTableLDS =
1085 kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo,
1086 VariableSet: TableLookupVariables);
1087
1088 const DenseSet<Function *> KernelsThatIndirectlyAllocateDynamicLDS =
1089 kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo,
1090 VariableSet: DynamicVariables);
1091
1092 GlobalVariable *MaybeModuleScopeStruct = lowerModuleScopeStructVariables(
1093 M, ModuleScopeVariables, KernelsThatAllocateModuleLDS);
1094
1095 DenseMap<Function *, LDSVariableReplacement> KernelToReplacement =
1096 lowerKernelScopeStructVariables(M, LDSUsesInfo, ModuleScopeVariables,
1097 KernelsThatAllocateModuleLDS,
1098 MaybeModuleScopeStruct);
1099
1100 // Lower zero cost accesses to the kernel instances just created
1101 for (auto &GV : KernelAccessVariables) {
1102 auto &funcs = LDSToKernelsThatNeedToAccessItIndirectly[GV];
1103 assert(funcs.size() == 1); // Only one kernel can access it
1104 LDSVariableReplacement Replacement =
1105 KernelToReplacement[*(funcs.begin())];
1106
1107 DenseSet<GlobalVariable *> Vec;
1108 Vec.insert(V: GV);
1109
1110 replaceLDSVariablesWithStruct(M, LDSVarsToTransformArg: Vec, Replacement, Predicate: [](Use &U) {
1111 return isa<Instruction>(Val: U.getUser());
1112 });
1113 }
1114
1115 // The ith element of this vector is kernel id i
1116 std::vector<Function *> OrderedKernels =
1117 assignLDSKernelIDToEachKernel(M: &M, KernelsThatAllocateTableLDS,
1118 KernelsThatIndirectlyAllocateDynamicLDS);
1119
1120 if (!KernelsThatAllocateTableLDS.empty()) {
1121 // The order must be consistent between lookup table and accesses to
1122 // lookup table
1123 auto TableLookupVariablesOrdered =
1124 sortByName(V: std::vector<GlobalVariable *>(TableLookupVariables.begin(),
1125 TableLookupVariables.end()));
1126
1127 GlobalVariable *LookupTable = buildLookupTable(
1128 M, Variables: TableLookupVariablesOrdered, kernels: OrderedKernels, KernelToReplacement);
1129 replaceUsesInInstructionsWithTableLookup(M, ModuleScopeVariables: TableLookupVariablesOrdered,
1130 LookupTable);
1131 }
1132
1133 DenseMap<Function *, GlobalVariable *> KernelToCreatedDynamicLDS =
1134 lowerDynamicLDSVariables(M, LDSUsesInfo,
1135 KernelsThatIndirectlyAllocateDynamicLDS,
1136 DynamicVariables, OrderedKernels);
1137
1138 // Strip amdgpu-no-lds-kernel-id from all functions reachable from the
1139 // kernel. We may have inferred this wasn't used prior to the pass.
1140 // TODO: We could filter out subgraphs that do not access LDS globals.
1141 for (auto *KernelSet : {&KernelsThatIndirectlyAllocateDynamicLDS,
1142 &KernelsThatAllocateTableLDS})
1143 for (Function *F : *KernelSet)
1144 removeFnAttrFromReachable(CG, KernelRoot: F, FnAttrs: {"amdgpu-no-lds-kernel-id"});
1145
1146 // All kernel frames have been allocated. Calculate and record the
1147 // addresses.
1148 {
1149 const DataLayout &DL = M.getDataLayout();
1150
1151 for (Function &Func : M.functions()) {
1152 if (Func.isDeclaration() || !isKernel(F: Func))
1153 continue;
1154
1155 // All three of these are optional. The first variable is allocated at
1156 // zero. They are allocated by AMDGPUMachineFunctionInfo as one block.
1157 // Layout:
1158 //{
1159 // module.lds
1160 // alignment padding
1161 // kernel instance
1162 // alignment padding
1163 // dynamic lds variables
1164 //}
1165
1166 const bool AllocateModuleScopeStruct =
1167 MaybeModuleScopeStruct &&
1168 KernelsThatAllocateModuleLDS.contains(V: &Func);
1169
1170 auto Replacement = KernelToReplacement.find(Val: &Func);
1171 const bool AllocateKernelScopeStruct =
1172 Replacement != KernelToReplacement.end();
1173
1174 const bool AllocateDynamicVariable =
1175 KernelToCreatedDynamicLDS.contains(Val: &Func);
1176
1177 uint32_t Offset = 0;
1178
1179 if (AllocateModuleScopeStruct) {
1180 // Allocated at zero, recorded once on construction, not once per
1181 // kernel
1182 Offset += MaybeModuleScopeStruct->getGlobalSize(DL);
1183 }
1184
1185 if (AllocateKernelScopeStruct) {
1186 GlobalVariable *KernelStruct = Replacement->second.SGV;
1187 Offset = alignTo(Size: Offset, A: AMDGPU::getAlign(DL, GV: KernelStruct));
1188 recordLDSAbsoluteAddress(M: &M, GV: KernelStruct, Address: Offset);
1189 Offset += KernelStruct->getGlobalSize(DL);
1190 }
1191
1192 // If there is dynamic allocation, the alignment needed is included in
1193 // the static frame size. There may be no reference to the dynamic
1194 // variable in the kernel itself, so without including it here, that
1195 // alignment padding could be missed.
1196 if (AllocateDynamicVariable) {
1197 GlobalVariable *DynamicVariable = KernelToCreatedDynamicLDS[&Func];
1198 Offset = alignTo(Size: Offset, A: AMDGPU::getAlign(DL, GV: DynamicVariable));
1199 recordLDSAbsoluteAddress(M: &M, GV: DynamicVariable, Address: Offset);
1200 }
1201
1202 if (Offset != 0) {
1203 (void)TM; // TODO: Account for target maximum LDS
1204 std::string Buffer;
1205 raw_string_ostream SS{Buffer};
1206 SS << format(Fmt: "%u", Vals: Offset);
1207
1208 // Instead of explicitly marking kernels that access dynamic variables
1209 // using special case metadata, annotate with min-lds == max-lds, i.e.
1210 // that there is no more space available for allocating more static
1211 // LDS variables. That is the right condition to prevent allocating
1212 // more variables which would collide with the addresses assigned to
1213 // dynamic variables.
1214 if (AllocateDynamicVariable)
1215 SS << format(Fmt: ",%u", Vals: Offset);
1216
1217 Func.addFnAttr(Kind: "amdgpu-lds-size", Val: Buffer);
1218 }
1219 }
1220 }
1221
1222 for (auto &GV : make_early_inc_range(Range: M.globals()))
1223 if (isNotYetLoweredLDSVariable(GV)) {
1224 // probably want to remove from used lists
1225 GV.removeDeadConstantUsers();
1226 if (GV.use_empty())
1227 GV.eraseFromParent();
1228 }
1229
1230 return Changed;
1231 }
1232
1233private:
1234 // An absolute address means a previous run already placed the variable.
1235 static bool isNotYetLoweredLDSVariable(const GlobalVariable &GV) {
1236 return isLDSVariableToLower(GV) && !GV.isAbsoluteSymbolRef();
1237 }
1238
1239 // Increase the alignment of LDS globals if necessary to maximise the chance
1240 // that we can use aligned LDS instructions to access them.
1241 bool superAlignLDSGlobals(Module &M) {
1242 const DataLayout &DL = M.getDataLayout();
1243 bool Changed = false;
1244 if (!TM.getCLOpts().super_align_lds_globals) {
1245 return Changed;
1246 }
1247
1248 for (auto &GV : M.globals()) {
1249 if (GV.getType()->getPointerAddressSpace() != AMDGPUAS::LOCAL_ADDRESS) {
1250 // Only changing alignment of LDS variables
1251 continue;
1252 }
1253 if (!GV.hasInitializer()) {
1254 // cuda/hip extern __shared__ variable, leave alignment alone
1255 continue;
1256 }
1257
1258 if (GV.isAbsoluteSymbolRef()) {
1259 // If the variable is already allocated, don't change the alignment
1260 continue;
1261 }
1262
1263 Align Alignment = AMDGPU::getAlign(DL, GV: &GV);
1264 uint64_t GVSize = GV.getGlobalSize(DL);
1265
1266 if (GVSize > 8) {
1267 // We might want to use a b96 or b128 load/store
1268 Alignment = std::max(a: Alignment, b: Align(16));
1269 } else if (GVSize > 4) {
1270 // We might want to use a b64 load/store
1271 Alignment = std::max(a: Alignment, b: Align(8));
1272 } else if (GVSize > 2) {
1273 // We might want to use a b32 load/store
1274 Alignment = std::max(a: Alignment, b: Align(4));
1275 } else if (GVSize > 1) {
1276 // We might want to use a b16 load/store
1277 Alignment = std::max(a: Alignment, b: Align(2));
1278 }
1279
1280 if (Alignment != AMDGPU::getAlign(DL, GV: &GV)) {
1281 Changed = true;
1282 GV.setAlignment(Alignment);
1283 }
1284 }
1285 return Changed;
1286 }
1287
1288 static LDSVariableReplacement createLDSVariableReplacement(
1289 Module &M, std::string VarName,
1290 DenseSet<GlobalVariable *> const &LDSVarsToTransform) {
1291 // Create a struct instance containing LDSVarsToTransform and map from those
1292 // variables to ConstantExprGEP
1293 // Variables may be introduced to meet alignment requirements. No aliasing
1294 // metadata is useful for these as they have no uses. Erased before return.
1295
1296 LLVMContext &Ctx = M.getContext();
1297 const DataLayout &DL = M.getDataLayout();
1298 assert(!LDSVarsToTransform.empty());
1299
1300 SmallVector<OptimizedStructLayoutField, 8> LayoutFields;
1301 LayoutFields.reserve(N: LDSVarsToTransform.size());
1302 {
1303 // The order of fields in this struct depends on the order of
1304 // variables in the argument which varies when changing how they
1305 // are identified, leading to spurious test breakage.
1306 auto Sorted = sortByName(V: std::vector<GlobalVariable *>(
1307 LDSVarsToTransform.begin(), LDSVarsToTransform.end()));
1308
1309 for (GlobalVariable *GV : Sorted) {
1310 OptimizedStructLayoutField F(GV, GV->getGlobalSize(DL),
1311 AMDGPU::getAlign(DL, GV));
1312 LayoutFields.emplace_back(Args&: F);
1313 }
1314 }
1315
1316 performOptimizedStructLayout(Fields: LayoutFields);
1317
1318 std::vector<GlobalVariable *> LocalVars;
1319 BitVector IsPaddingField;
1320 LocalVars.reserve(n: LDSVarsToTransform.size()); // will be at least this large
1321 IsPaddingField.reserve(N: LDSVarsToTransform.size());
1322 {
1323 uint64_t CurrentOffset = 0;
1324 for (auto &F : LayoutFields) {
1325 GlobalVariable *FGV =
1326 static_cast<GlobalVariable *>(const_cast<void *>(F.Id));
1327 Align DataAlign = F.Alignment;
1328
1329 uint64_t DataAlignV = DataAlign.value();
1330 if (uint64_t Rem = CurrentOffset % DataAlignV) {
1331 uint64_t Padding = DataAlignV - Rem;
1332
1333 // Append an array of padding bytes to meet alignment requested
1334 // Note (o + (a - (o % a)) ) % a == 0
1335 // (offset + Padding ) % align == 0
1336
1337 Type *ATy = ArrayType::get(ElementType: Type::getInt8Ty(C&: Ctx), NumElements: Padding);
1338 LocalVars.push_back(x: new GlobalVariable(
1339 M, ATy, false, GlobalValue::InternalLinkage,
1340 PoisonValue::get(T: ATy), "", nullptr, GlobalValue::NotThreadLocal,
1341 AMDGPUAS::LOCAL_ADDRESS, false));
1342 IsPaddingField.push_back(Val: true);
1343 CurrentOffset += Padding;
1344 }
1345
1346 LocalVars.push_back(x: FGV);
1347 IsPaddingField.push_back(Val: false);
1348 CurrentOffset += F.Size;
1349 }
1350 }
1351
1352 std::vector<Type *> LocalVarTypes;
1353 LocalVarTypes.reserve(n: LocalVars.size());
1354 std::transform(
1355 first: LocalVars.cbegin(), last: LocalVars.cend(), result: std::back_inserter(x&: LocalVarTypes),
1356 unary_op: [](const GlobalVariable *V) -> Type * { return V->getValueType(); });
1357
1358 StructType *LDSTy = StructType::create(Context&: Ctx, Elements: LocalVarTypes, Name: VarName + ".t");
1359
1360 Align StructAlign = AMDGPU::getAlign(DL, GV: LocalVars[0]);
1361
1362 GlobalVariable *SGV = new GlobalVariable(
1363 M, LDSTy, false, GlobalValue::InternalLinkage, PoisonValue::get(T: LDSTy),
1364 VarName, nullptr, GlobalValue::NotThreadLocal, AMDGPUAS::LOCAL_ADDRESS,
1365 false);
1366 SGV->setAlignment(StructAlign);
1367
1368 DenseMap<GlobalVariable *, Constant *> Map;
1369 Type *I32 = Type::getInt32Ty(C&: Ctx);
1370 for (size_t I = 0; I < LocalVars.size(); I++) {
1371 GlobalVariable *GV = LocalVars[I];
1372 Constant *GEPIdx[] = {ConstantInt::get(Ty: I32, V: 0), ConstantInt::get(Ty: I32, V: I)};
1373 Constant *GEP = ConstantExpr::getGetElementPtr(
1374 DL, Ty: LDSTy, C: SGV, IdxList: GEPIdx, NW: GEPNoWrapFlags::inBounds());
1375 if (IsPaddingField[I]) {
1376 assert(GV->use_empty());
1377 GV->eraseFromParent();
1378 } else {
1379 Map[GV] = GEP;
1380 }
1381 }
1382 assert(Map.size() == LDSVarsToTransform.size());
1383 return {.SGV: SGV, .LDSVarsToConstantGEP: std::move(Map)};
1384 }
1385
1386 template <typename PredicateTy>
1387 static void replaceLDSVariablesWithStruct(
1388 Module &M, DenseSet<GlobalVariable *> const &LDSVarsToTransformArg,
1389 const LDSVariableReplacement &Replacement, PredicateTy Predicate) {
1390 LLVMContext &Ctx = M.getContext();
1391 const DataLayout &DL = M.getDataLayout();
1392
1393 // A hack... we need to insert the aliasing info in a predictable order for
1394 // lit tests. Would like to have them in a stable order already, ideally the
1395 // same order they get allocated, which might mean an ordered set container
1396 auto LDSVarsToTransform = sortByName(V: std::vector<GlobalVariable *>(
1397 LDSVarsToTransformArg.begin(), LDSVarsToTransformArg.end()));
1398
1399 // Create alias.scope and their lists. Each field in the new structure
1400 // does not alias with all other fields.
1401 SmallVector<MDNode *> AliasScopes;
1402 SmallVector<Metadata *> NoAliasList;
1403 const size_t NumberVars = LDSVarsToTransform.size();
1404 if (NumberVars > 1) {
1405 MDBuilder MDB(Ctx);
1406 AliasScopes.reserve(N: NumberVars);
1407 MDNode *Domain = MDB.createAnonymousAliasScopeDomain();
1408 for (size_t I = 0; I < NumberVars; I++) {
1409 MDNode *Scope = MDB.createAnonymousAliasScope(Domain);
1410 AliasScopes.push_back(Elt: Scope);
1411 }
1412 NoAliasList.append(in_start: &AliasScopes[1], in_end: AliasScopes.end());
1413 }
1414
1415 // Replace uses of ith variable with a constantexpr to the corresponding
1416 // field of the instance that will be allocated by AMDGPUMachineFunctionInfo
1417 for (size_t I = 0; I < NumberVars; I++) {
1418 GlobalVariable *GV = LDSVarsToTransform[I];
1419 Constant *GEP = Replacement.LDSVarsToConstantGEP.at(Val: GV);
1420
1421 GV->replaceUsesWithIf(New: GEP, ShouldReplace: Predicate);
1422
1423 APInt APOff(DL.getIndexTypeSizeInBits(Ty: GEP->getType()), 0);
1424 GEP->stripAndAccumulateInBoundsConstantOffsets(DL, Offset&: APOff);
1425 uint64_t Offset = APOff.getZExtValue();
1426
1427 Align A =
1428 commonAlignment(A: Replacement.SGV->getAlign().valueOrOne(), Offset);
1429
1430 if (I)
1431 NoAliasList[I - 1] = AliasScopes[I - 1];
1432 MDNode *NoAlias =
1433 NoAliasList.empty() ? nullptr : MDNode::get(Context&: Ctx, MDs: NoAliasList);
1434 MDNode *AliasScope =
1435 AliasScopes.empty() ? nullptr : MDNode::get(Context&: Ctx, MDs: {AliasScopes[I]});
1436
1437 refineUsesAlignmentAndAA(Ptr: GEP, A, DL, AliasScope, NoAlias);
1438 }
1439 }
1440
1441 static void refineUsesAlignmentAndAA(Value *Ptr, Align A,
1442 const DataLayout &DL, MDNode *AliasScope,
1443 MDNode *NoAlias, unsigned MaxDepth = 5) {
1444 if (!MaxDepth || (A == 1 && !AliasScope))
1445 return;
1446
1447 for (User *U : Ptr->users()) {
1448 if (auto *I = dyn_cast<Instruction>(Val: U)) {
1449 if (AliasScope && I->mayReadOrWriteMemory()) {
1450 MDNode *AS = I->getMetadata(KindID: LLVMContext::MD_alias_scope);
1451 AS = (AS ? MDNode::getMostGenericAliasScope(A: AS, B: AliasScope)
1452 : AliasScope);
1453 I->setMetadata(KindID: LLVMContext::MD_alias_scope, Node: AS);
1454
1455 MDNode *NA = I->getMetadata(KindID: LLVMContext::MD_noalias);
1456
1457 // Scoped aliases can originate from two different domains.
1458 // First domain would be from LDS domain (created by this pass).
1459 // All entries (LDS vars) into LDS struct will have same domain.
1460
1461 // Second domain could be existing scoped aliases that are the
1462 // results of noalias params and subsequent optimizations that
1463 // may alter thesse sets.
1464
1465 // We need to be careful how we create new alias sets, and
1466 // have right scopes and domains for loads/stores of these new
1467 // LDS variables. We intersect NoAlias set if alias sets belong
1468 // to the same domain. This is the case if we have memcpy using
1469 // LDS variables. Both src and dst of memcpy would belong to
1470 // LDS struct, they donot alias.
1471 // On the other hand, if one of the domains is LDS and other is
1472 // existing domain prior to LDS, we need to have a union of all
1473 // these aliases set to preserve existing aliasing information.
1474
1475 SmallPtrSet<const MDNode *, 16> ExistingDomains, LDSDomains;
1476 ScopedNoAliasAAResult::collectScopedDomains(NoAlias: NA, Domains&: ExistingDomains);
1477 ScopedNoAliasAAResult::collectScopedDomains(NoAlias, Domains&: LDSDomains);
1478 auto Intersection = set_intersection(S1: ExistingDomains, S2: LDSDomains);
1479 if (Intersection.empty()) {
1480 NA = NA ? MDNode::concatenate(A: NA, B: NoAlias) : NoAlias;
1481 } else {
1482 NA = NA ? MDNode::intersect(A: NA, B: NoAlias) : NoAlias;
1483 }
1484 I->setMetadata(KindID: LLVMContext::MD_noalias, Node: NA);
1485 }
1486 }
1487
1488 if (auto *LI = dyn_cast<LoadInst>(Val: U)) {
1489 LI->setAlignment(std::max(a: A, b: LI->getAlign()));
1490 continue;
1491 }
1492 if (auto *SI = dyn_cast<StoreInst>(Val: U)) {
1493 if (SI->getPointerOperand() == Ptr)
1494 SI->setAlignment(std::max(a: A, b: SI->getAlign()));
1495 continue;
1496 }
1497 if (auto *AI = dyn_cast<AtomicRMWInst>(Val: U)) {
1498 // None of atomicrmw operations can work on pointers, but let's
1499 // check it anyway in case it will or we will process ConstantExpr.
1500 if (AI->getPointerOperand() == Ptr)
1501 AI->setAlignment(std::max(a: A, b: AI->getAlign()));
1502 continue;
1503 }
1504 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(Val: U)) {
1505 if (AI->getPointerOperand() == Ptr)
1506 AI->setAlignment(std::max(a: A, b: AI->getAlign()));
1507 continue;
1508 }
1509 if (auto *GEP = dyn_cast<GetElementPtrInst>(Val: U)) {
1510 unsigned BitWidth = DL.getIndexTypeSizeInBits(Ty: GEP->getType());
1511 APInt Off(BitWidth, 0);
1512 if (GEP->getPointerOperand() == Ptr) {
1513 Align GA;
1514 if (GEP->accumulateConstantOffset(DL, Offset&: Off))
1515 GA = commonAlignment(A, Offset: Off.getLimitedValue());
1516 refineUsesAlignmentAndAA(Ptr: GEP, A: GA, DL, AliasScope, NoAlias,
1517 MaxDepth: MaxDepth - 1);
1518 }
1519 continue;
1520 }
1521 if (auto *I = dyn_cast<Instruction>(Val: U)) {
1522 if (I->getOpcode() == Instruction::BitCast ||
1523 I->getOpcode() == Instruction::AddrSpaceCast)
1524 refineUsesAlignmentAndAA(Ptr: I, A, DL, AliasScope, NoAlias, MaxDepth: MaxDepth - 1);
1525 }
1526 }
1527 }
1528};
1529
1530class AMDGPULowerModuleLDSLegacy : public ModulePass {
1531public:
1532 const AMDGPUTargetMachine *TM;
1533 static char ID;
1534
1535 AMDGPULowerModuleLDSLegacy(const AMDGPUTargetMachine *TM = nullptr)
1536 : ModulePass(ID), TM(TM) {}
1537
1538 void getAnalysisUsage(AnalysisUsage &AU) const override {
1539 if (!TM)
1540 AU.addRequired<TargetPassConfig>();
1541 }
1542
1543 bool runOnModule(Module &M) override {
1544 if (!TM) {
1545 auto &TPC = getAnalysis<TargetPassConfig>();
1546 TM = &TPC.getTM<AMDGPUTargetMachine>();
1547 }
1548
1549 return AMDGPULowerModuleLDS(*TM).runOnModule(M);
1550 }
1551};
1552
1553} // namespace
1554char AMDGPULowerModuleLDSLegacy::ID = 0;
1555
1556char &llvm::AMDGPULowerModuleLDSLegacyPassID = AMDGPULowerModuleLDSLegacy::ID;
1557
1558INITIALIZE_PASS_BEGIN(AMDGPULowerModuleLDSLegacy, DEBUG_TYPE,
1559 "Lower uses of LDS variables from non-kernel functions",
1560 false, false)
1561INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
1562INITIALIZE_PASS_END(AMDGPULowerModuleLDSLegacy, DEBUG_TYPE,
1563 "Lower uses of LDS variables from non-kernel functions",
1564 false, false)
1565
1566ModulePass *
1567llvm::createAMDGPULowerModuleLDSLegacyPass(const AMDGPUTargetMachine *TM) {
1568 return new AMDGPULowerModuleLDSLegacy(TM);
1569}
1570
1571PreservedAnalyses AMDGPULowerModuleLDSPass::run(Module &M,
1572 ModuleAnalysisManager &) {
1573 return AMDGPULowerModuleLDS(TM).runOnModule(M) ? PreservedAnalyses::none()
1574 : PreservedAnalyses::all();
1575}
1576