LLVM 24.0.0git
AMDGPULowerModuleLDSPass.cpp
Go to the documentation of this file.
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"
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"
199#include "llvm/Pass.h"
201#include "llvm/Support/Format.h"
206
207#include <cstdio>
208
209#define DEBUG_TYPE "amdgpu-lower-module-lds"
210
211using namespace llvm;
212using namespace AMDGPU;
213
214namespace {
215
216cl::opt<bool> SuperAlignLDSGlobals(
217 "amdgpu-super-align-lds-globals",
218 cl::desc("Increase alignment of LDS if it is not on align boundary"),
219 cl::init(true), cl::Hidden);
220
221enum class LoweringKind { module, table, kernel, hybrid };
222cl::opt<LoweringKind> LoweringKindLoc(
223 "amdgpu-lower-module-lds-strategy",
224 cl::desc("Specify lowering strategy for function LDS access:"), cl::Hidden,
225 cl::init(LoweringKind::hybrid),
227 clEnumValN(LoweringKind::table, "table", "Lower via table lookup"),
228 clEnumValN(LoweringKind::module, "module", "Lower via module struct"),
230 LoweringKind::kernel, "kernel",
231 "Lower variables reachable from one kernel, otherwise abort"),
232 clEnumValN(LoweringKind::hybrid, "hybrid",
233 "Lower via mixture of above strategies")));
234
235template <typename T> std::vector<T> sortByName(std::vector<T> &&V) {
236 llvm::sort(V, [](const auto *L, const auto *R) {
237 return L->getName() < R->getName();
238 });
239 return {std::move(V)};
240}
241
242class AMDGPULowerModuleLDS {
243 const AMDGPUTargetMachine &TM;
244
245 static void
246 removeLocalVarsFromUsedLists(Module &M,
247 const DenseSet<GlobalVariable *> &LocalVars) {
248 // The verifier rejects used lists containing an inttoptr of a constant
249 // so remove the variables from these lists before replaceAllUsesWith
250 SmallPtrSet<Constant *, 8> LocalVarsSet;
251 for (GlobalVariable *LocalVar : LocalVars)
252 LocalVarsSet.insert(cast<Constant>(LocalVar->stripPointerCasts()));
253
255 M, [&LocalVarsSet](Constant *C) { return LocalVarsSet.count(C); });
256
257 for (GlobalVariable *LocalVar : LocalVars)
258 LocalVar->removeDeadConstantUsers();
259 }
260
261 static void markUsedByKernel(Function *Func, GlobalVariable *SGV) {
262 // The llvm.amdgcn.module.lds instance is implicitly used by all kernels
263 // that might call a function which accesses a field within it. This is
264 // presently approximated to 'all kernels' if there are any such functions
265 // in the module. This implicit use is redefined as an explicit use here so
266 // that later passes, specifically PromoteAlloca, account for the required
267 // memory without any knowledge of this transform.
268
269 // An operand bundle on llvm.donothing works because the call instruction
270 // survives until after the last pass that needs to account for LDS. It is
271 // better than inline asm as the latter survives until the end of codegen. A
272 // totally robust solution would be a function with the same semantics as
273 // llvm.donothing that takes a pointer to the instance and is lowered to a
274 // no-op after LDS is allocated, but that is not presently necessary.
275
276 // This intrinsic is eliminated shortly before instruction selection. It
277 // does not suffice to indicate to ISel that a given global which is not
278 // immediately used by the kernel must still be allocated by it. An
279 // equivalent target specific intrinsic which lasts until immediately after
280 // codegen would suffice for that, but one would still need to ensure that
281 // the variables are allocated in the anticipated order.
282 BasicBlock *Entry = &Func->getEntryBlock();
283 IRBuilder<> Builder(Entry, Entry->getFirstNonPHIIt());
284
286 Func->getParent(), Intrinsic::donothing, {});
287
288 Value *UseInstance[1] = {
289 Builder.CreateConstInBoundsGEP1_32(SGV->getValueType(), SGV, 0)};
290
291 Builder.CreateCall(
292 Decl, {}, {OperandBundleDefT<Value *>("ExplicitUse", UseInstance)});
293 }
294
295public:
296 AMDGPULowerModuleLDS(const AMDGPUTargetMachine &TM_) : TM(TM_) {}
297
298 struct LDSVariableReplacement {
299 GlobalVariable *SGV = nullptr;
300 DenseMap<GlobalVariable *, Constant *> LDSVarsToConstantGEP;
301 };
302
303 // remap from lds global to a constantexpr gep to where it has been moved to
304 // for each kernel
305 // an array with an element for each kernel containing where the corresponding
306 // variable was remapped to
307
308 static Constant *getAddressesOfVariablesInKernel(
310 const DenseMap<GlobalVariable *, Constant *> &LDSVarsToConstantGEP) {
311 // Create a ConstantArray containing the address of each Variable within the
312 // kernel corresponding to LDSVarsToConstantGEP, or poison if that kernel
313 // does not allocate it
314
316 ArrayType *KernelOffsetsType = ArrayType::get(LocalPtrTy, Variables.size());
317
319 for (GlobalVariable *GV : Variables) {
320 auto ConstantGepIt = LDSVarsToConstantGEP.find(GV);
321 if (ConstantGepIt != LDSVarsToConstantGEP.end()) {
322 Elements.push_back(ConstantGepIt->second);
323 } else {
324 Elements.push_back(PoisonValue::get(LocalPtrTy));
325 }
326 }
327 return ConstantArray::get(KernelOffsetsType, Elements);
328 }
329
330 static GlobalVariable *buildLookupTable(
332 ArrayRef<Function *> kernels,
334 if (Variables.empty()) {
335 return nullptr;
336 }
337 LLVMContext &Ctx = M.getContext();
338
339 const size_t NumberVariables = Variables.size();
340 const size_t NumberKernels = kernels.size();
341
343 ArrayType *KernelOffsetsType = ArrayType::get(LocalPtrTy, NumberVariables);
344
345 ArrayType *AllKernelsOffsetsType =
346 ArrayType::get(KernelOffsetsType, NumberKernels);
347
348 Constant *Missing = PoisonValue::get(KernelOffsetsType);
349 std::vector<Constant *> overallConstantExprElts(NumberKernels);
350 for (size_t i = 0; i < NumberKernels; i++) {
351 auto Replacement = KernelToReplacement.find(kernels[i]);
352 overallConstantExprElts[i] =
353 (Replacement == KernelToReplacement.end())
354 ? Missing
355 : getAddressesOfVariablesInKernel(
356 Ctx, Variables, Replacement->second.LDSVarsToConstantGEP);
357 }
358
359 Constant *init =
360 ConstantArray::get(AllKernelsOffsetsType, overallConstantExprElts);
361
362 return new GlobalVariable(
363 M, AllKernelsOffsetsType, true, GlobalValue::InternalLinkage, init,
364 "llvm.amdgcn.lds.offset.table", nullptr, GlobalValue::NotThreadLocal,
366 }
367
368 void replaceUseWithTableLookup(Module &M, IRBuilder<> &Builder,
369 GlobalVariable *LookupTable,
370 GlobalVariable *GV, Use &U,
371 Value *OptionalIndex) {
372 // Table is a constant array of the same length as OrderedKernels
373 LLVMContext &Ctx = M.getContext();
374 Type *I32 = Type::getInt32Ty(Ctx);
375 auto *I = cast<Instruction>(U.getUser());
376
377 Value *tableKernelIndex = getTableLookupKernelIndex(M, I->getFunction());
378
379 if (auto *Phi = dyn_cast<PHINode>(I)) {
380 BasicBlock *BB = Phi->getIncomingBlock(U);
381 Builder.SetInsertPoint(&(*(BB->getFirstInsertionPt())));
382 } else {
383 Builder.SetInsertPoint(I);
384 }
385
386 SmallVector<Value *, 3> GEPIdx = {
387 ConstantInt::get(I32, 0),
388 tableKernelIndex,
389 };
390 if (OptionalIndex)
391 GEPIdx.push_back(OptionalIndex);
392
393 Value *Address = Builder.CreateInBoundsGEP(
394 LookupTable->getValueType(), LookupTable, GEPIdx, GV->getName());
395
396 Value *Loaded = Builder.CreateLoad(GV->getType(), Address);
397 U.set(Loaded);
398 }
399
400 void replaceUsesInInstructionsWithTableLookup(
401 Module &M, ArrayRef<GlobalVariable *> ModuleScopeVariables,
402 GlobalVariable *LookupTable) {
403
404 LLVMContext &Ctx = M.getContext();
405 IRBuilder<> Builder(Ctx);
406 Type *I32 = Type::getInt32Ty(Ctx);
407
408 for (size_t Index = 0; Index < ModuleScopeVariables.size(); Index++) {
409 auto *GV = ModuleScopeVariables[Index];
410
411 for (Use &U : make_early_inc_range(GV->uses())) {
412 auto *I = dyn_cast<Instruction>(U.getUser());
413 if (!I)
414 continue;
415
416 replaceUseWithTableLookup(M, Builder, LookupTable, GV, U,
417 ConstantInt::get(I32, Index));
418 }
419 }
420 }
421
422 static DenseSet<Function *> kernelsThatIndirectlyAccessAnyOfPassedVariables(
423 Module &M, GVUsesInfoTy &LDSUsesInfo,
424 DenseSet<GlobalVariable *> const &VariableSet) {
425
426 DenseSet<Function *> KernelSet;
427
428 if (VariableSet.empty())
429 return KernelSet;
430
431 for (Function &Func : M.functions()) {
432 if (Func.isDeclaration() || !isKernel(Func))
433 continue;
434 for (GlobalVariable *GV : LDSUsesInfo.IndirectAccess[&Func]) {
435 if (VariableSet.contains(GV)) {
436 KernelSet.insert(&Func);
437 break;
438 }
439 }
440 }
441
442 return KernelSet;
443 }
444
445 static GlobalVariable *
446 chooseBestVariableForModuleStrategy(const DataLayout &DL,
447 VariableFunctionMap &LDSVars) {
448 // Find the global variable with the most indirect uses from kernels
449
450 struct CandidateTy {
451 GlobalVariable *GV = nullptr;
452 size_t UserCount = 0;
453 size_t Size = 0;
454
455 CandidateTy() = default;
456
457 CandidateTy(GlobalVariable *GV, uint64_t UserCount, uint64_t AllocSize)
458 : GV(GV), UserCount(UserCount), Size(AllocSize) {}
459
460 bool operator<(const CandidateTy &Other) const {
461 // Fewer users makes module scope variable less attractive
462 if (UserCount < Other.UserCount) {
463 return true;
464 }
465 if (UserCount > Other.UserCount) {
466 return false;
467 }
468
469 // Bigger makes module scope variable less attractive
470 if (Size < Other.Size) {
471 return false;
472 }
473
474 if (Size > Other.Size) {
475 return true;
476 }
477
478 // Arbitrary but consistent
479 return GV->getName() < Other.GV->getName();
480 }
481 };
482
483 CandidateTy MostUsed;
484
485 for (auto &K : LDSVars) {
486 GlobalVariable *GV = K.first;
487 if (K.second.size() <= 1) {
488 // A variable reachable by only one kernel is best lowered with kernel
489 // strategy
490 continue;
491 }
492 CandidateTy Candidate(GV, K.second.size(), GV->getGlobalSize(DL));
493 if (MostUsed < Candidate)
494 MostUsed = Candidate;
495 }
496
497 return MostUsed.GV;
498 }
499
500 static void recordLDSAbsoluteAddress(Module *M, GlobalVariable *GV,
501 uint32_t Address) {
502 // Write the specified address into metadata where it can be retrieved by
503 // the assembler. Format is a half open range, [Address Address+1)
504 LLVMContext &Ctx = M->getContext();
505 auto *IntTy =
506 M->getDataLayout().getIntPtrType(Ctx, AMDGPUAS::LOCAL_ADDRESS);
507 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntTy, Address));
508 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntTy, Address + 1));
509 GV->setMetadata(LLVMContext::MD_absolute_symbol,
510 MDNode::get(Ctx, {MinC, MaxC}));
511 }
512
513 DenseMap<Function *, Value *> tableKernelIndexCache;
514 Value *getTableLookupKernelIndex(Module &M, Function *F) {
515 // Accesses from a function use the amdgcn_lds_kernel_id intrinsic which
516 // lowers to a read from a live in register. Emit it once in the entry
517 // block to spare deduplicating it later.
518 auto [It, Inserted] = tableKernelIndexCache.try_emplace(F);
519 if (Inserted) {
520 auto InsertAt = F->getEntryBlock().getFirstNonPHIOrDbgOrAlloca();
521 IRBuilder<> Builder(&*InsertAt);
522
523 It->second = Builder.CreateIntrinsic(Intrinsic::amdgcn_lds_kernel_id, {});
524 }
525
526 return It->second;
527 }
528
529 static std::vector<Function *> assignLDSKernelIDToEachKernel(
530 Module *M, DenseSet<Function *> const &KernelsThatAllocateTableLDS,
531 DenseSet<Function *> const &KernelsThatIndirectlyAllocateDynamicLDS) {
532 // Associate kernels in the set with an arbitrary but reproducible order and
533 // annotate them with that order in metadata. This metadata is recognised by
534 // the backend and lowered to a SGPR which can be read from using
535 // amdgcn_lds_kernel_id.
536
537 std::vector<Function *> OrderedKernels;
538 if (!KernelsThatAllocateTableLDS.empty() ||
539 !KernelsThatIndirectlyAllocateDynamicLDS.empty()) {
540
541 for (Function &Func : M->functions()) {
542 if (Func.isDeclaration())
543 continue;
544 if (!isKernel(Func))
545 continue;
546
547 if (KernelsThatAllocateTableLDS.contains(&Func) ||
548 KernelsThatIndirectlyAllocateDynamicLDS.contains(&Func)) {
549 assert(Func.hasName()); // else fatal error earlier
550 OrderedKernels.push_back(&Func);
551 }
552 }
553
554 // Put them in an arbitrary but reproducible order
555 OrderedKernels = sortByName(std::move(OrderedKernels));
556
557 // Annotate the kernels with their order in this vector
558 LLVMContext &Ctx = M->getContext();
559 IRBuilder<> Builder(Ctx);
560
561 if (OrderedKernels.size() > UINT32_MAX) {
562 // 32 bit keeps it in one SGPR. > 2**32 kernels won't fit on the GPU
563 reportFatalUsageError("unimplemented LDS lowering for > 2**32 kernels");
564 }
565
566 for (size_t i = 0; i < OrderedKernels.size(); i++) {
567 Metadata *AttrMDArgs[1] = {
568 ConstantAsMetadata::get(Builder.getInt32(i)),
569 };
570 OrderedKernels[i]->setMetadata("llvm.amdgcn.lds.kernel.id",
571 MDNode::get(Ctx, AttrMDArgs));
572 }
573 }
574 return OrderedKernels;
575 }
576
577 static void partitionVariablesIntoIndirectStrategies(
578 Module &M, GVUsesInfoTy const &LDSUsesInfo,
579 VariableFunctionMap &LDSToKernelsThatNeedToAccessItIndirectly,
580 DenseSet<GlobalVariable *> &ModuleScopeVariables,
581 DenseSet<GlobalVariable *> &TableLookupVariables,
582 DenseSet<GlobalVariable *> &KernelAccessVariables,
583 DenseSet<GlobalVariable *> &DynamicVariables) {
584
585 GlobalVariable *HybridModuleRoot =
586 LoweringKindLoc != LoweringKind::hybrid
587 ? nullptr
588 : chooseBestVariableForModuleStrategy(
589 M.getDataLayout(), LDSToKernelsThatNeedToAccessItIndirectly);
590
591 DenseSet<Function *> const EmptySet;
592 DenseSet<Function *> const &HybridModuleRootKernels =
593 HybridModuleRoot
594 ? LDSToKernelsThatNeedToAccessItIndirectly[HybridModuleRoot]
595 : EmptySet;
596
597 for (auto &K : LDSToKernelsThatNeedToAccessItIndirectly) {
598 // Each iteration of this loop assigns exactly one global variable to
599 // exactly one of the implementation strategies.
600
601 GlobalVariable *GV = K.first;
603 assert(!K.second.empty());
604
605 if (AMDGPU::isDynamicLDS(*GV)) {
606 DynamicVariables.insert(GV);
607 continue;
608 }
609
610 switch (LoweringKindLoc) {
611 case LoweringKind::module:
612 ModuleScopeVariables.insert(GV);
613 break;
614
615 case LoweringKind::table:
616 TableLookupVariables.insert(GV);
617 break;
618
619 case LoweringKind::kernel:
620 if (K.second.size() == 1) {
621 KernelAccessVariables.insert(GV);
622 } else {
623 // FIXME: This should use DiagnosticInfo
625 "cannot lower LDS '" + GV->getName() +
626 "' to kernel access as it is reachable from multiple kernels");
627 }
628 break;
629
630 case LoweringKind::hybrid: {
631 if (GV == HybridModuleRoot) {
632 assert(K.second.size() != 1);
633 ModuleScopeVariables.insert(GV);
634 } else if (K.second.size() == 1) {
635 KernelAccessVariables.insert(GV);
636 } else if (K.second == HybridModuleRootKernels) {
637 ModuleScopeVariables.insert(GV);
638 } else {
639 TableLookupVariables.insert(GV);
640 }
641 break;
642 }
643 }
644 }
645
646 // All LDS variables accessed indirectly have now been partitioned into
647 // the distinct lowering strategies.
648 assert(ModuleScopeVariables.size() + TableLookupVariables.size() +
649 KernelAccessVariables.size() + DynamicVariables.size() ==
650 LDSToKernelsThatNeedToAccessItIndirectly.size());
651 }
652
653 static GlobalVariable *lowerModuleScopeStructVariables(
654 Module &M, DenseSet<GlobalVariable *> const &ModuleScopeVariables,
655 DenseSet<Function *> const &KernelsThatAllocateModuleLDS) {
656 // Create a struct to hold the ModuleScopeVariables
657 // Replace all uses of those variables from non-kernel functions with the
658 // new struct instance Replace only the uses from kernel functions that will
659 // allocate this instance. That is a space optimisation - kernels that use a
660 // subset of the module scope struct and do not need to allocate it for
661 // indirect calls will only allocate the subset they use (they do so as part
662 // of the per-kernel lowering).
663 if (ModuleScopeVariables.empty()) {
664 return nullptr;
665 }
666
667 LLVMContext &Ctx = M.getContext();
668
669 LDSVariableReplacement ModuleScopeReplacement =
670 createLDSVariableReplacement(M, "llvm.amdgcn.module.lds",
671 ModuleScopeVariables);
672
673 appendToCompilerUsed(M, {static_cast<GlobalValue *>(
675 cast<Constant>(ModuleScopeReplacement.SGV),
676 PointerType::getUnqual(Ctx)))});
677
678 // module.lds will be allocated at zero in any kernel that allocates it
679 recordLDSAbsoluteAddress(&M, ModuleScopeReplacement.SGV, 0);
680
681 // historic
682 removeLocalVarsFromUsedLists(M, ModuleScopeVariables);
683
684 // Replace all uses of module scope variable from non-kernel functions
685 replaceLDSVariablesWithStruct(
686 M, ModuleScopeVariables, ModuleScopeReplacement, [&](Use &U) {
687 Instruction *I = dyn_cast<Instruction>(U.getUser());
688 if (!I) {
689 return false;
690 }
691 Function *F = I->getFunction();
692 return !isKernel(*F);
693 });
694
695 // Replace uses of module scope variable from kernel functions that
696 // allocate the module scope variable, otherwise leave them unchanged
697 // Record on each kernel whether the module scope global is used by it
698
699 for (Function &Func : M.functions()) {
700 if (Func.isDeclaration() || !isKernel(Func))
701 continue;
702
703 if (KernelsThatAllocateModuleLDS.contains(&Func)) {
704 replaceLDSVariablesWithStruct(
705 M, ModuleScopeVariables, ModuleScopeReplacement, [&](Use &U) {
706 Instruction *I = dyn_cast<Instruction>(U.getUser());
707 if (!I) {
708 return false;
709 }
710 Function *F = I->getFunction();
711 return F == &Func;
712 });
713
714 markUsedByKernel(&Func, ModuleScopeReplacement.SGV);
715 }
716 }
717
718 return ModuleScopeReplacement.SGV;
719 }
720
722 lowerKernelScopeStructVariables(
723 Module &M, GVUsesInfoTy &LDSUsesInfo,
724 DenseSet<GlobalVariable *> const &ModuleScopeVariables,
725 DenseSet<Function *> const &KernelsThatAllocateModuleLDS,
726 GlobalVariable *MaybeModuleScopeStruct) {
727
728 // Create a struct for each kernel for the non-module-scope variables.
729
731 for (Function &Func : M.functions()) {
732 if (Func.isDeclaration() || !isKernel(Func))
733 continue;
734
735 DenseSet<GlobalVariable *> KernelUsedVariables;
736 // Allocating variables that are used directly in this struct to get
737 // alignment aware allocation and predictable frame size.
738 for (auto &v : LDSUsesInfo.DirectAccess[&Func]) {
739 if (!AMDGPU::isDynamicLDS(*v)) {
740 KernelUsedVariables.insert(v);
741 }
742 }
743
744 // Allocating variables that are accessed indirectly so that a lookup of
745 // this struct instance can find them from nested functions.
746 for (auto &v : LDSUsesInfo.IndirectAccess[&Func]) {
747 if (!AMDGPU::isDynamicLDS(*v)) {
748 KernelUsedVariables.insert(v);
749 }
750 }
751
752 // Variables allocated in module lds must all resolve to that struct,
753 // not to the per-kernel instance.
754 if (KernelsThatAllocateModuleLDS.contains(&Func)) {
755 for (GlobalVariable *v : ModuleScopeVariables) {
756 KernelUsedVariables.erase(v);
757 }
758 }
759
760 if (KernelUsedVariables.empty()) {
761 // Either used no LDS, or the LDS it used was all in the module struct
762 // or dynamically sized
763 continue;
764 }
765
766 // The association between kernel function and LDS struct is done by
767 // symbol name, which only works if the function in question has a
768 // name This is not expected to be a problem in practice as kernels
769 // are called by name making anonymous ones (which are named by the
770 // backend) difficult to use. This does mean that llvm test cases need
771 // to name the kernels.
772 if (!Func.hasName()) {
773 reportFatalUsageError("anonymous kernels cannot use LDS variables");
774 }
775
776 std::string VarName =
777 (Twine("llvm.amdgcn.kernel.") + Func.getName() + ".lds").str();
778
779 auto Replacement =
780 createLDSVariableReplacement(M, VarName, KernelUsedVariables);
781
782 // If any indirect uses, create a direct use to ensure allocation
783 // TODO: Simpler to unconditionally mark used but that regresses
784 // codegen in test/CodeGen/AMDGPU/noclobber-barrier.ll
785 auto Accesses = LDSUsesInfo.IndirectAccess.find(&Func);
786 if ((Accesses != LDSUsesInfo.IndirectAccess.end()) &&
787 !Accesses->second.empty())
788 markUsedByKernel(&Func, Replacement.SGV);
789
790 // remove preserves existing codegen
791 removeLocalVarsFromUsedLists(M, KernelUsedVariables);
792 KernelToReplacement[&Func] = Replacement;
793
794 // Rewrite uses within kernel to the new struct
795 replaceLDSVariablesWithStruct(
796 M, KernelUsedVariables, Replacement, [&Func](Use &U) {
797 Instruction *I = dyn_cast<Instruction>(U.getUser());
798 return I && I->getFunction() == &Func;
799 });
800 }
801 return KernelToReplacement;
802 }
803
804 static GlobalVariable *
805 buildRepresentativeDynamicLDSInstance(Module &M, GVUsesInfoTy &LDSUsesInfo,
806 Function *func) {
807 // Create a dynamic lds variable with a name associated with the passed
808 // function that has the maximum alignment of any dynamic lds variable
809 // reachable from this kernel. Dynamic LDS is allocated after the static LDS
810 // allocation, possibly after alignment padding. The representative variable
811 // created here has the maximum alignment of any other dynamic variable
812 // reachable by that kernel. All dynamic LDS variables are allocated at the
813 // same address in each kernel in order to provide the documented aliasing
814 // semantics. Setting the alignment here allows this IR pass to accurately
815 // predict the exact constant at which it will be allocated.
816
817 assert(isKernel(*func));
818
819 LLVMContext &Ctx = M.getContext();
820 const DataLayout &DL = M.getDataLayout();
821 Align MaxDynamicAlignment(1);
822
823 auto UpdateMaxAlignment = [&MaxDynamicAlignment, &DL](GlobalVariable *GV) {
824 if (AMDGPU::isDynamicLDS(*GV)) {
825 MaxDynamicAlignment =
826 std::max(MaxDynamicAlignment, AMDGPU::getAlign(DL, GV));
827 }
828 };
829
830 for (GlobalVariable *GV : LDSUsesInfo.IndirectAccess[func]) {
831 UpdateMaxAlignment(GV);
832 }
833
834 for (GlobalVariable *GV : LDSUsesInfo.DirectAccess[func]) {
835 UpdateMaxAlignment(GV);
836 }
837
838 assert(func->hasName()); // Checked by caller
839 auto *emptyCharArray = ArrayType::get(Type::getInt8Ty(Ctx), 0);
841 M, emptyCharArray, false, GlobalValue::ExternalLinkage, nullptr,
842 Twine("llvm.amdgcn." + func->getName() + ".dynlds"), nullptr,
844 N->setAlignment(MaxDynamicAlignment);
845
847 return N;
848 }
849
850 DenseMap<Function *, GlobalVariable *> lowerDynamicLDSVariables(
851 Module &M, GVUsesInfoTy &LDSUsesInfo,
852 DenseSet<Function *> const &KernelsThatIndirectlyAllocateDynamicLDS,
853 DenseSet<GlobalVariable *> const &DynamicVariables,
854 std::vector<Function *> const &OrderedKernels) {
855 DenseMap<Function *, GlobalVariable *> KernelToCreatedDynamicLDS;
856 if (!KernelsThatIndirectlyAllocateDynamicLDS.empty()) {
857 LLVMContext &Ctx = M.getContext();
858 IRBuilder<> Builder(Ctx);
860
861 std::vector<Constant *> newDynamicLDS;
862
863 // Table is built in the same order as OrderedKernels
864 for (auto &func : OrderedKernels) {
865
866 if (KernelsThatIndirectlyAllocateDynamicLDS.contains(func)) {
867 assert(isKernel(*func));
868 if (!func->hasName()) {
869 reportFatalUsageError("anonymous kernels cannot use LDS variables");
870 }
871
873 buildRepresentativeDynamicLDSInstance(M, LDSUsesInfo, func);
874
875 KernelToCreatedDynamicLDS[func] = N;
876
877 markUsedByKernel(func, N);
878
879 newDynamicLDS.push_back(N);
880 } else {
881 newDynamicLDS.push_back(PoisonValue::get(LocalPtrTy));
882 }
883 }
884 assert(OrderedKernels.size() == newDynamicLDS.size());
885
886 ArrayType *t = ArrayType::get(LocalPtrTy, newDynamicLDS.size());
887 Constant *init = ConstantArray::get(t, newDynamicLDS);
888 GlobalVariable *table = new GlobalVariable(
889 M, t, true, GlobalValue::InternalLinkage, init,
890 "llvm.amdgcn.dynlds.offset.table", nullptr,
892
893 for (GlobalVariable *GV : DynamicVariables) {
894 for (Use &U : make_early_inc_range(GV->uses())) {
895 auto *I = dyn_cast<Instruction>(U.getUser());
896 if (!I)
897 continue;
898 if (isKernel(*I->getFunction()))
899 continue;
900
901 replaceUseWithTableLookup(M, Builder, table, GV, U, nullptr);
902 }
903 }
904 }
905 return KernelToCreatedDynamicLDS;
906 }
907
908 // Per-TU mode for link-time LDS resolution. Instead of computing a global
909 // layout, create per-function LDS struct declarations so the linker can
910 // assign offsets across TUs.
911 bool runOnModuleLinkTime(Module &M) {
912 bool Changed = superAlignLDSGlobals(M);
913 Changed |=
915
916 CallGraph CG(M);
917 FunctionVariableMap KernelLDSUses, FunctionLDSUses;
918 getUsesOfGVByFunction(CG, M, isLDSVariableToLower, KernelLDSUses,
919 FunctionLDSUses);
920
921 if (KernelLDSUses.empty() && FunctionLDSUses.empty())
922 return Changed;
923
924 std::string ModuleId = getUniqueModuleId(&M);
925 assert(!ModuleId.empty() &&
926 "modules with LDS variables should have a unique ID");
927
928 FunctionVariableMap AllLDSUses;
929 for (auto &[F, Vars] : KernelLDSUses)
930 AllLDSUses[F].insert(Vars.begin(), Vars.end());
931 for (auto &[F, Vars] : FunctionLDSUses)
932 AllLDSUses[F].insert(Vars.begin(), Vars.end());
933
934 // Build reverse map: LDS variable -> functions that use it.
936 for (auto &[F, Vars] : AllLDSUses) {
937 for (GlobalVariable *V : Vars)
938 VarToFuncs[V].push_back(F);
939 }
940
941 // A variable is function-scope iff it has local linkage and exactly one
942 // user function. Everything else is global-scope and must remain as a
943 // standalone external declaration so the linker can assign a single shared
944 // offset.
945 DenseSet<GlobalVariable *> GlobalScopeVars;
946 DenseSet<GlobalVariable *> InternalMultiUserVars;
947 for (auto &[V, Funcs] : VarToFuncs) {
948 if (!V->hasLocalLinkage() || Funcs.size() > 1) {
949 GlobalScopeVars.insert(V);
950 if (V->hasLocalLinkage())
951 InternalMultiUserVars.insert(V);
952 }
953 }
954
955 // Wrap function-scope LDS into per-function structs (unchanged logic,
956 // but global-scope variables are excluded from the set).
958 DenseSet<GlobalVariable *> AllReplacedVars;
959 for (auto &KV : AllLDSUses) {
960 Function *F = KV.first;
961 DenseSet<GlobalVariable *> FuncScopeVars;
962 for (GlobalVariable *V : KV.second) {
963 if (!GlobalScopeVars.count(V))
964 FuncScopeVars.insert(V);
965 }
966
967 if (FuncScopeVars.empty())
968 continue;
969
970 std::string StructName =
971 F->hasLocalLinkage()
972 ? ("__amdgpu_lds." + F->getName() + ModuleId).str()
973 : ("__amdgpu_lds." + F->getName()).str();
974 LDSVariableReplacement Replacement =
975 createLDSVariableReplacement(M, StructName, FuncScopeVars);
976
977 GlobalVariable *SGV = Replacement.SGV;
978 SGV->setLinkage(GlobalValue::ExternalLinkage);
979 SGV->setInitializer(nullptr);
980 FuncToLdsStruct.push_back({F, SGV});
981
982 replaceLDSVariablesWithStruct(
983 M, FuncScopeVars, Replacement, [F](const Use &U) {
984 auto *I = dyn_cast<Instruction>(U.getUser());
985 return I && I->getFunction() == F;
986 });
987
988 AllReplacedVars.insert(FuncScopeVars.begin(), FuncScopeVars.end());
989 }
990
991 // Internal-linkage LDS variables used by multiple functions would collide
992 // across TUs if promoted individually to external linkage (same name in
993 // different TUs). Pack them into a single per-module struct with a
994 // module-unique name so the linker treats them as one allocation unit.
995 if (!InternalMultiUserVars.empty()) {
996 std::string StructName = "__amdgpu_lds.__internal" + ModuleId;
997 LDSVariableReplacement Replacement =
998 createLDSVariableReplacement(M, StructName, InternalMultiUserVars);
999
1000 GlobalVariable *SGV = Replacement.SGV;
1001 SGV->setLinkage(GlobalValue::ExternalLinkage);
1002 SGV->setInitializer(nullptr);
1003
1004 replaceLDSVariablesWithStruct(
1005 M, InternalMultiUserVars, Replacement,
1006 [](const Use &U) { return isa<Instruction>(U.getUser()); });
1007
1008 DenseSet<Function *> FuncsUsingInternalVars;
1009 for (GlobalVariable *V : InternalMultiUserVars) {
1010 for (Function *F : VarToFuncs[V])
1011 FuncsUsingInternalVars.insert(F);
1012 }
1013 for (Function *F : FuncsUsingInternalVars)
1014 FuncToLdsStruct.push_back({F, SGV});
1015
1016 AllReplacedVars.insert(InternalMultiUserVars.begin(),
1017 InternalMultiUserVars.end());
1018 }
1019
1020 // Convert global-scope LDS to external declarations. Their uses remain
1021 // intact and ISel generates R_AMDGPU_ABS32_LO relocations for them.
1022 for (GlobalVariable *V : GlobalScopeVars) {
1023 V->setInitializer(nullptr);
1024 V->setLinkage(GlobalValue::ExternalLinkage);
1025 }
1026
1027 // Emit amdgpu.lds.uses metadata for struct and global-scope LDS.
1028 {
1029 LLVMContext &Ctx = M.getContext();
1030 NamedMDNode *LdsMD = M.getOrInsertNamedMetadata("amdgpu.lds.uses");
1031
1032 for (auto &[F, SGV] : FuncToLdsStruct)
1033 LdsMD->addOperand(MDNode::get(
1035
1036 for (auto &[V, Funcs] : VarToFuncs) {
1037 if (GlobalScopeVars.count(V) && !InternalMultiUserVars.count(V)) {
1038 for (Function *F : Funcs) {
1039 LdsMD->addOperand(MDNode::get(
1041 }
1042 }
1043 }
1044 }
1045
1046 DenseSet<GlobalVariable *> AllLDSVarsForCleanup = AllReplacedVars;
1047 AllLDSVarsForCleanup.insert(GlobalScopeVars.begin(), GlobalScopeVars.end());
1048 removeLocalVarsFromUsedLists(M, AllLDSVarsForCleanup);
1049 for (GlobalVariable *GV : AllReplacedVars) {
1051 if (GV->use_empty())
1052 GV->eraseFromParent();
1053 }
1054
1055 return true;
1056 }
1057
1058 bool runOnModule(Module &M) {
1060 return runOnModuleLinkTime(M);
1061 return runOnModuleNormal(M);
1062 }
1063
1064 bool runOnModuleNormal(Module &M) {
1065 bool Changed = superAlignLDSGlobals(M);
1066
1067 Changed |= any_of(M.globals(), isNotYetLoweredLDSVariable);
1068
1069 CallGraph CG(M);
1070
1072 isNotYetLoweredLDSVariable);
1073
1074 // For each kernel, what variables does it access directly or through
1075 // callees
1077
1078 // For each variable accessed through callees, which kernels access it
1079 VariableFunctionMap LDSToKernelsThatNeedToAccessItIndirectly;
1080 for (auto &K : LDSUsesInfo.IndirectAccess) {
1081 Function *F = K.first;
1082 assert(isKernel(*F));
1083 for (GlobalVariable *GV : K.second) {
1084 LDSToKernelsThatNeedToAccessItIndirectly[GV].insert(F);
1085 }
1086 }
1087
1088 // Partition variables accessed indirectly into the different strategies
1089 DenseSet<GlobalVariable *> ModuleScopeVariables;
1090 DenseSet<GlobalVariable *> TableLookupVariables;
1091 DenseSet<GlobalVariable *> KernelAccessVariables;
1092 DenseSet<GlobalVariable *> DynamicVariables;
1093 partitionVariablesIntoIndirectStrategies(
1094 M, LDSUsesInfo, LDSToKernelsThatNeedToAccessItIndirectly,
1095 ModuleScopeVariables, TableLookupVariables, KernelAccessVariables,
1096 DynamicVariables);
1097
1098 // If the kernel accesses a variable that is going to be stored in the
1099 // module instance through a call then that kernel needs to allocate the
1100 // module instance
1101 const DenseSet<Function *> KernelsThatAllocateModuleLDS =
1102 kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo,
1103 ModuleScopeVariables);
1104 const DenseSet<Function *> KernelsThatAllocateTableLDS =
1105 kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo,
1106 TableLookupVariables);
1107
1108 const DenseSet<Function *> KernelsThatIndirectlyAllocateDynamicLDS =
1109 kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo,
1110 DynamicVariables);
1111
1112 GlobalVariable *MaybeModuleScopeStruct = lowerModuleScopeStructVariables(
1113 M, ModuleScopeVariables, KernelsThatAllocateModuleLDS);
1114
1116 lowerKernelScopeStructVariables(M, LDSUsesInfo, ModuleScopeVariables,
1117 KernelsThatAllocateModuleLDS,
1118 MaybeModuleScopeStruct);
1119
1120 // Lower zero cost accesses to the kernel instances just created
1121 for (auto &GV : KernelAccessVariables) {
1122 auto &funcs = LDSToKernelsThatNeedToAccessItIndirectly[GV];
1123 assert(funcs.size() == 1); // Only one kernel can access it
1124 LDSVariableReplacement Replacement =
1125 KernelToReplacement[*(funcs.begin())];
1126
1128 Vec.insert(GV);
1129
1130 replaceLDSVariablesWithStruct(M, Vec, Replacement, [](Use &U) {
1131 return isa<Instruction>(U.getUser());
1132 });
1133 }
1134
1135 // The ith element of this vector is kernel id i
1136 std::vector<Function *> OrderedKernels =
1137 assignLDSKernelIDToEachKernel(&M, KernelsThatAllocateTableLDS,
1138 KernelsThatIndirectlyAllocateDynamicLDS);
1139
1140 if (!KernelsThatAllocateTableLDS.empty()) {
1141 LLVMContext &Ctx = M.getContext();
1142 IRBuilder<> Builder(Ctx);
1143
1144 // The order must be consistent between lookup table and accesses to
1145 // lookup table
1146 auto TableLookupVariablesOrdered =
1147 sortByName(std::vector<GlobalVariable *>(TableLookupVariables.begin(),
1148 TableLookupVariables.end()));
1149
1150 GlobalVariable *LookupTable = buildLookupTable(
1151 M, TableLookupVariablesOrdered, OrderedKernels, KernelToReplacement);
1152 replaceUsesInInstructionsWithTableLookup(M, TableLookupVariablesOrdered,
1153 LookupTable);
1154 }
1155
1156 DenseMap<Function *, GlobalVariable *> KernelToCreatedDynamicLDS =
1157 lowerDynamicLDSVariables(M, LDSUsesInfo,
1158 KernelsThatIndirectlyAllocateDynamicLDS,
1159 DynamicVariables, OrderedKernels);
1160
1161 // Strip amdgpu-no-lds-kernel-id from all functions reachable from the
1162 // kernel. We may have inferred this wasn't used prior to the pass.
1163 // TODO: We could filter out subgraphs that do not access LDS globals.
1164 for (auto *KernelSet : {&KernelsThatIndirectlyAllocateDynamicLDS,
1165 &KernelsThatAllocateTableLDS})
1166 for (Function *F : *KernelSet)
1167 removeFnAttrFromReachable(CG, F, {"amdgpu-no-lds-kernel-id"});
1168
1169 // All kernel frames have been allocated. Calculate and record the
1170 // addresses.
1171 {
1172 const DataLayout &DL = M.getDataLayout();
1173
1174 for (Function &Func : M.functions()) {
1175 if (Func.isDeclaration() || !isKernel(Func))
1176 continue;
1177
1178 // All three of these are optional. The first variable is allocated at
1179 // zero. They are allocated by AMDGPUMachineFunctionInfo as one block.
1180 // Layout:
1181 //{
1182 // module.lds
1183 // alignment padding
1184 // kernel instance
1185 // alignment padding
1186 // dynamic lds variables
1187 //}
1188
1189 const bool AllocateModuleScopeStruct =
1190 MaybeModuleScopeStruct &&
1191 KernelsThatAllocateModuleLDS.contains(&Func);
1192
1193 auto Replacement = KernelToReplacement.find(&Func);
1194 const bool AllocateKernelScopeStruct =
1195 Replacement != KernelToReplacement.end();
1196
1197 const bool AllocateDynamicVariable =
1198 KernelToCreatedDynamicLDS.contains(&Func);
1199
1200 uint32_t Offset = 0;
1201
1202 if (AllocateModuleScopeStruct) {
1203 // Allocated at zero, recorded once on construction, not once per
1204 // kernel
1205 Offset += MaybeModuleScopeStruct->getGlobalSize(DL);
1206 }
1207
1208 if (AllocateKernelScopeStruct) {
1209 GlobalVariable *KernelStruct = Replacement->second.SGV;
1210 Offset = alignTo(Offset, AMDGPU::getAlign(DL, KernelStruct));
1211 recordLDSAbsoluteAddress(&M, KernelStruct, Offset);
1212 Offset += KernelStruct->getGlobalSize(DL);
1213 }
1214
1215 // If there is dynamic allocation, the alignment needed is included in
1216 // the static frame size. There may be no reference to the dynamic
1217 // variable in the kernel itself, so without including it here, that
1218 // alignment padding could be missed.
1219 if (AllocateDynamicVariable) {
1220 GlobalVariable *DynamicVariable = KernelToCreatedDynamicLDS[&Func];
1221 Offset = alignTo(Offset, AMDGPU::getAlign(DL, DynamicVariable));
1222 recordLDSAbsoluteAddress(&M, DynamicVariable, Offset);
1223 }
1224
1225 if (Offset != 0) {
1226 (void)TM; // TODO: Account for target maximum LDS
1227 std::string Buffer;
1228 raw_string_ostream SS{Buffer};
1229 SS << format("%u", Offset);
1230
1231 // Instead of explicitly marking kernels that access dynamic variables
1232 // using special case metadata, annotate with min-lds == max-lds, i.e.
1233 // that there is no more space available for allocating more static
1234 // LDS variables. That is the right condition to prevent allocating
1235 // more variables which would collide with the addresses assigned to
1236 // dynamic variables.
1237 if (AllocateDynamicVariable)
1238 SS << format(",%u", Offset);
1239
1240 Func.addFnAttr("amdgpu-lds-size", Buffer);
1241 }
1242 }
1243 }
1244
1245 for (auto &GV : make_early_inc_range(M.globals()))
1246 if (isNotYetLoweredLDSVariable(GV)) {
1247 // probably want to remove from used lists
1249 if (GV.use_empty())
1250 GV.eraseFromParent();
1251 }
1252
1253 return Changed;
1254 }
1255
1256private:
1257 // An absolute address means a previous run already placed the variable.
1258 static bool isNotYetLoweredLDSVariable(const GlobalVariable &GV) {
1259 return isLDSVariableToLower(GV) && !GV.isAbsoluteSymbolRef();
1260 }
1261
1262 // Increase the alignment of LDS globals if necessary to maximise the chance
1263 // that we can use aligned LDS instructions to access them.
1264 static bool superAlignLDSGlobals(Module &M) {
1265 const DataLayout &DL = M.getDataLayout();
1266 bool Changed = false;
1267 if (!SuperAlignLDSGlobals) {
1268 return Changed;
1269 }
1270
1271 for (auto &GV : M.globals()) {
1273 // Only changing alignment of LDS variables
1274 continue;
1275 }
1276 if (!GV.hasInitializer()) {
1277 // cuda/hip extern __shared__ variable, leave alignment alone
1278 continue;
1279 }
1280
1281 if (GV.isAbsoluteSymbolRef()) {
1282 // If the variable is already allocated, don't change the alignment
1283 continue;
1284 }
1285
1286 Align Alignment = AMDGPU::getAlign(DL, &GV);
1287 uint64_t GVSize = GV.getGlobalSize(DL);
1288
1289 if (GVSize > 8) {
1290 // We might want to use a b96 or b128 load/store
1291 Alignment = std::max(Alignment, Align(16));
1292 } else if (GVSize > 4) {
1293 // We might want to use a b64 load/store
1294 Alignment = std::max(Alignment, Align(8));
1295 } else if (GVSize > 2) {
1296 // We might want to use a b32 load/store
1297 Alignment = std::max(Alignment, Align(4));
1298 } else if (GVSize > 1) {
1299 // We might want to use a b16 load/store
1300 Alignment = std::max(Alignment, Align(2));
1301 }
1302
1303 if (Alignment != AMDGPU::getAlign(DL, &GV)) {
1304 Changed = true;
1305 GV.setAlignment(Alignment);
1306 }
1307 }
1308 return Changed;
1309 }
1310
1311 static LDSVariableReplacement createLDSVariableReplacement(
1312 Module &M, std::string VarName,
1313 DenseSet<GlobalVariable *> const &LDSVarsToTransform) {
1314 // Create a struct instance containing LDSVarsToTransform and map from those
1315 // variables to ConstantExprGEP
1316 // Variables may be introduced to meet alignment requirements. No aliasing
1317 // metadata is useful for these as they have no uses. Erased before return.
1318
1319 LLVMContext &Ctx = M.getContext();
1320 const DataLayout &DL = M.getDataLayout();
1321 assert(!LDSVarsToTransform.empty());
1322
1324 LayoutFields.reserve(LDSVarsToTransform.size());
1325 {
1326 // The order of fields in this struct depends on the order of
1327 // variables in the argument which varies when changing how they
1328 // are identified, leading to spurious test breakage.
1329 auto Sorted = sortByName(std::vector<GlobalVariable *>(
1330 LDSVarsToTransform.begin(), LDSVarsToTransform.end()));
1331
1332 for (GlobalVariable *GV : Sorted) {
1334 AMDGPU::getAlign(DL, GV));
1335 LayoutFields.emplace_back(F);
1336 }
1337 }
1338
1339 performOptimizedStructLayout(LayoutFields);
1340
1341 std::vector<GlobalVariable *> LocalVars;
1342 BitVector IsPaddingField;
1343 LocalVars.reserve(LDSVarsToTransform.size()); // will be at least this large
1344 IsPaddingField.reserve(LDSVarsToTransform.size());
1345 {
1346 uint64_t CurrentOffset = 0;
1347 for (auto &F : LayoutFields) {
1348 GlobalVariable *FGV =
1349 static_cast<GlobalVariable *>(const_cast<void *>(F.Id));
1350 Align DataAlign = F.Alignment;
1351
1352 uint64_t DataAlignV = DataAlign.value();
1353 if (uint64_t Rem = CurrentOffset % DataAlignV) {
1354 uint64_t Padding = DataAlignV - Rem;
1355
1356 // Append an array of padding bytes to meet alignment requested
1357 // Note (o + (a - (o % a)) ) % a == 0
1358 // (offset + Padding ) % align == 0
1359
1360 Type *ATy = ArrayType::get(Type::getInt8Ty(Ctx), Padding);
1361 LocalVars.push_back(new GlobalVariable(
1362 M, ATy, false, GlobalValue::InternalLinkage,
1364 AMDGPUAS::LOCAL_ADDRESS, false));
1365 IsPaddingField.push_back(true);
1366 CurrentOffset += Padding;
1367 }
1368
1369 LocalVars.push_back(FGV);
1370 IsPaddingField.push_back(false);
1371 CurrentOffset += F.Size;
1372 }
1373 }
1374
1375 std::vector<Type *> LocalVarTypes;
1376 LocalVarTypes.reserve(LocalVars.size());
1377 std::transform(
1378 LocalVars.cbegin(), LocalVars.cend(), std::back_inserter(LocalVarTypes),
1379 [](const GlobalVariable *V) -> Type * { return V->getValueType(); });
1380
1381 StructType *LDSTy = StructType::create(Ctx, LocalVarTypes, VarName + ".t");
1382
1383 Align StructAlign = AMDGPU::getAlign(DL, LocalVars[0]);
1384
1385 GlobalVariable *SGV = new GlobalVariable(
1386 M, LDSTy, false, GlobalValue::InternalLinkage, PoisonValue::get(LDSTy),
1388 false);
1389 SGV->setAlignment(StructAlign);
1390
1392 Type *I32 = Type::getInt32Ty(Ctx);
1393 for (size_t I = 0; I < LocalVars.size(); I++) {
1394 GlobalVariable *GV = LocalVars[I];
1395 Constant *GEPIdx[] = {ConstantInt::get(I32, 0), ConstantInt::get(I32, I)};
1396 Constant *GEP = ConstantExpr::getGetElementPtr(LDSTy, SGV, GEPIdx, true);
1397 if (IsPaddingField[I]) {
1398 assert(GV->use_empty());
1399 GV->eraseFromParent();
1400 } else {
1401 Map[GV] = GEP;
1402 }
1403 }
1404 assert(Map.size() == LDSVarsToTransform.size());
1405 return {SGV, std::move(Map)};
1406 }
1407
1408 template <typename PredicateTy>
1409 static void replaceLDSVariablesWithStruct(
1410 Module &M, DenseSet<GlobalVariable *> const &LDSVarsToTransformArg,
1411 const LDSVariableReplacement &Replacement, PredicateTy Predicate) {
1412 LLVMContext &Ctx = M.getContext();
1413 const DataLayout &DL = M.getDataLayout();
1414
1415 // A hack... we need to insert the aliasing info in a predictable order for
1416 // lit tests. Would like to have them in a stable order already, ideally the
1417 // same order they get allocated, which might mean an ordered set container
1418 auto LDSVarsToTransform = sortByName(std::vector<GlobalVariable *>(
1419 LDSVarsToTransformArg.begin(), LDSVarsToTransformArg.end()));
1420
1421 // Create alias.scope and their lists. Each field in the new structure
1422 // does not alias with all other fields.
1423 SmallVector<MDNode *> AliasScopes;
1424 SmallVector<Metadata *> NoAliasList;
1425 const size_t NumberVars = LDSVarsToTransform.size();
1426 if (NumberVars > 1) {
1427 MDBuilder MDB(Ctx);
1428 AliasScopes.reserve(NumberVars);
1430 for (size_t I = 0; I < NumberVars; I++) {
1432 AliasScopes.push_back(Scope);
1433 }
1434 NoAliasList.append(&AliasScopes[1], AliasScopes.end());
1435 }
1436
1437 // Replace uses of ith variable with a constantexpr to the corresponding
1438 // field of the instance that will be allocated by AMDGPUMachineFunctionInfo
1439 for (size_t I = 0; I < NumberVars; I++) {
1440 GlobalVariable *GV = LDSVarsToTransform[I];
1441 Constant *GEP = Replacement.LDSVarsToConstantGEP.at(GV);
1442
1444
1445 APInt APOff(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
1446 GEP->stripAndAccumulateInBoundsConstantOffsets(DL, APOff);
1447 uint64_t Offset = APOff.getZExtValue();
1448
1449 Align A =
1450 commonAlignment(Replacement.SGV->getAlign().valueOrOne(), Offset);
1451
1452 if (I)
1453 NoAliasList[I - 1] = AliasScopes[I - 1];
1454 MDNode *NoAlias =
1455 NoAliasList.empty() ? nullptr : MDNode::get(Ctx, NoAliasList);
1456 MDNode *AliasScope =
1457 AliasScopes.empty() ? nullptr : MDNode::get(Ctx, {AliasScopes[I]});
1458
1459 refineUsesAlignmentAndAA(GEP, A, DL, AliasScope, NoAlias);
1460 }
1461 }
1462
1463 static void refineUsesAlignmentAndAA(Value *Ptr, Align A,
1464 const DataLayout &DL, MDNode *AliasScope,
1465 MDNode *NoAlias, unsigned MaxDepth = 5) {
1466 if (!MaxDepth || (A == 1 && !AliasScope))
1467 return;
1468
1469 ScopedNoAliasAAResult ScopedNoAlias;
1470
1471 for (User *U : Ptr->users()) {
1472 if (auto *I = dyn_cast<Instruction>(U)) {
1473 if (AliasScope && I->mayReadOrWriteMemory()) {
1474 MDNode *AS = I->getMetadata(LLVMContext::MD_alias_scope);
1475 AS = (AS ? MDNode::getMostGenericAliasScope(AS, AliasScope)
1476 : AliasScope);
1477 I->setMetadata(LLVMContext::MD_alias_scope, AS);
1478
1479 MDNode *NA = I->getMetadata(LLVMContext::MD_noalias);
1480
1481 // Scoped aliases can originate from two different domains.
1482 // First domain would be from LDS domain (created by this pass).
1483 // All entries (LDS vars) into LDS struct will have same domain.
1484
1485 // Second domain could be existing scoped aliases that are the
1486 // results of noalias params and subsequent optimizations that
1487 // may alter thesse sets.
1488
1489 // We need to be careful how we create new alias sets, and
1490 // have right scopes and domains for loads/stores of these new
1491 // LDS variables. We intersect NoAlias set if alias sets belong
1492 // to the same domain. This is the case if we have memcpy using
1493 // LDS variables. Both src and dst of memcpy would belong to
1494 // LDS struct, they donot alias.
1495 // On the other hand, if one of the domains is LDS and other is
1496 // existing domain prior to LDS, we need to have a union of all
1497 // these aliases set to preserve existing aliasing information.
1498
1499 SmallPtrSet<const MDNode *, 16> ExistingDomains, LDSDomains;
1500 ScopedNoAlias.collectScopedDomains(NA, ExistingDomains);
1501 ScopedNoAlias.collectScopedDomains(NoAlias, LDSDomains);
1502 auto Intersection = set_intersection(ExistingDomains, LDSDomains);
1503 if (Intersection.empty()) {
1504 NA = NA ? MDNode::concatenate(NA, NoAlias) : NoAlias;
1505 } else {
1506 NA = NA ? MDNode::intersect(NA, NoAlias) : NoAlias;
1507 }
1508 I->setMetadata(LLVMContext::MD_noalias, NA);
1509 }
1510 }
1511
1512 if (auto *LI = dyn_cast<LoadInst>(U)) {
1513 LI->setAlignment(std::max(A, LI->getAlign()));
1514 continue;
1515 }
1516 if (auto *SI = dyn_cast<StoreInst>(U)) {
1517 if (SI->getPointerOperand() == Ptr)
1518 SI->setAlignment(std::max(A, SI->getAlign()));
1519 continue;
1520 }
1521 if (auto *AI = dyn_cast<AtomicRMWInst>(U)) {
1522 // None of atomicrmw operations can work on pointers, but let's
1523 // check it anyway in case it will or we will process ConstantExpr.
1524 if (AI->getPointerOperand() == Ptr)
1525 AI->setAlignment(std::max(A, AI->getAlign()));
1526 continue;
1527 }
1528 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(U)) {
1529 if (AI->getPointerOperand() == Ptr)
1530 AI->setAlignment(std::max(A, AI->getAlign()));
1531 continue;
1532 }
1533 if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
1534 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
1535 APInt Off(BitWidth, 0);
1536 if (GEP->getPointerOperand() == Ptr) {
1537 Align GA;
1538 if (GEP->accumulateConstantOffset(DL, Off))
1539 GA = commonAlignment(A, Off.getLimitedValue());
1540 refineUsesAlignmentAndAA(GEP, GA, DL, AliasScope, NoAlias,
1541 MaxDepth - 1);
1542 }
1543 continue;
1544 }
1545 if (auto *I = dyn_cast<Instruction>(U)) {
1546 if (I->getOpcode() == Instruction::BitCast ||
1547 I->getOpcode() == Instruction::AddrSpaceCast)
1548 refineUsesAlignmentAndAA(I, A, DL, AliasScope, NoAlias, MaxDepth - 1);
1549 }
1550 }
1551 }
1552};
1553
1554class AMDGPULowerModuleLDSLegacy : public ModulePass {
1555public:
1556 const AMDGPUTargetMachine *TM;
1557 static char ID;
1558
1559 AMDGPULowerModuleLDSLegacy(const AMDGPUTargetMachine *TM = nullptr)
1560 : ModulePass(ID), TM(TM) {}
1561
1562 void getAnalysisUsage(AnalysisUsage &AU) const override {
1563 if (!TM)
1565 }
1566
1567 bool runOnModule(Module &M) override {
1568 if (!TM) {
1569 auto &TPC = getAnalysis<TargetPassConfig>();
1570 TM = &TPC.getTM<AMDGPUTargetMachine>();
1571 }
1572
1573 return AMDGPULowerModuleLDS(*TM).runOnModule(M);
1574 }
1575};
1576
1577} // namespace
1578char AMDGPULowerModuleLDSLegacy::ID = 0;
1579
1580char &llvm::AMDGPULowerModuleLDSLegacyPassID = AMDGPULowerModuleLDSLegacy::ID;
1581
1582INITIALIZE_PASS_BEGIN(AMDGPULowerModuleLDSLegacy, DEBUG_TYPE,
1583 "Lower uses of LDS variables from non-kernel functions",
1584 false, false)
1586INITIALIZE_PASS_END(AMDGPULowerModuleLDSLegacy, DEBUG_TYPE,
1587 "Lower uses of LDS variables from non-kernel functions",
1589
1590ModulePass *
1592 return new AMDGPULowerModuleLDSLegacy(TM);
1593}
1594
1597 return AMDGPULowerModuleLDS(TM).runOnModule(M) ? PreservedAnalyses::none()
1599}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
unsigned uint64_t
The AMDGPU TargetMachine interface definition for hw codegen targets.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Forward Handle Accesses
#define DEBUG_TYPE
Hexagon Common GEP
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
const std::string FatArchTraits< MachO::fat_arch >::StructName
This file provides an interface for laying out a sequence of fields as a struct in a way that attempt...
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file contains some templates that are useful if you are working with the STL at all.
This is the interface for a metadata-based scoped no-alias analysis.
This file defines generic set operations that may be used on set's of different types,...
Target-Independent Code Generator Pass Configuration Options pass.
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void reserve(unsigned N)
Reserve space for atleast N bits in the bitvector.
Definition BitVector.h:363
void push_back(bool Val)
Definition BitVector.h:505
The basic data container for the call graph of a Module of IR.
Definition CallGraph.h:72
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:537
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1470
This is an important base class in LLVM.
Definition Constant.h:43
LLVM_ABI void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:251
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:341
iterator end()
Definition DenseMap.h:169
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:242
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
LLVM_ABI bool isAbsoluteSymbolRef() const
Returns whether this is a reference to an absolute symbol.
Definition Globals.cpp:526
PointerType * getType() const
Global values are always pointers.
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
bool hasInitializer() const
Definitions have initializers, declarations don't.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:609
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2908
bool runOnModule(Module &) override
ImmutablePasses are never run.
Definition Pass.h:302
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
MDNode * createAnonymousAliasScope(MDNode *Domain, StringRef Name=StringRef())
Return metadata appropriate for an alias scope root node.
Definition MDBuilder.h:195
MDNode * createAnonymousAliasScopeDomain(StringRef Name=StringRef())
Return metadata appropriate for an alias scope domain node.
Definition MDBuilder.h:188
Metadata node.
Definition Metadata.h:1069
static LLVM_ABI MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * concatenate(MDNode *A, MDNode *B)
Methods for metadata merging.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
static LLVM_ABI MDNode * intersect(MDNode *A, MDNode *B)
Root of the metadata hierarchy.
Definition Metadata.h:64
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A tuple of MDNodes.
Definition Metadata.h:1755
LLVM_ABI void addOperand(MDNode *M)
A container for an operand bundle being viewed as a set of values rather than a set of uses.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:887
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
A simple AA result which uses scoped-noalias metadata to answer queries.
static LLVM_ABI void collectScopedDomains(const MDNode *NoAlias, SmallPtrSetImpl< const MDNode * > &Domains)
Collect the set of scoped domains relevant to the noalias scopes.
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Class to represent struct types.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:662
Target-Independent Code Generator Pass Configuration Options.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:506
LLVM Value Representation.
Definition Value.h:75
iterator_range< user_iterator > users()
Definition Value.h:428
bool use_empty() const
Definition Value.h:348
LLVM_ABI bool replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
Definition Value.cpp:561
iterator_range< use_iterator > uses()
Definition Value.h:382
bool hasName() const
Definition Value.h:263
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
bool erase(const ValueT &V)
Definition DenseSet.h:97
size_type size() const
Definition DenseSet.h:84
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
A raw_ostream that writes to an std::string.
Changed
@ LOCAL_ADDRESS
Address space for local memory.
@ CONSTANT_ADDRESS
Address space for constant memory (VTX2).
GVUsesInfoTy getTransitiveUsesOfLDSForLowering(const CallGraph &CG, Module &M)
Collects all uses of LDS Global Variables in M using getUsesOfGVByFunction, with isLDSVariableToLower...
bool isDynamicLDS(const GlobalVariable &GV)
void removeFnAttrFromReachable(CallGraph &CG, Function *KernelRoot, ArrayRef< StringRef > FnAttrs)
Strip FnAttr attribute from any functions where we may have introduced its use.
bool eliminateGVConstantExprUsesFromAllInstructions(Module &M, function_ref< bool(const GlobalVariable &)> Filter)
Iterates over all GlobalVariables in M, and whenever Filter returns true, replace all constant users ...
LLVM_READNONE constexpr bool isKernel(CallingConv::ID CC)
void getUsesOfGVByFunction(const CallGraph &CG, Module &M, function_ref< bool(const GlobalVariable &)> Filter, FunctionVariableMap &Kernels, FunctionVariableMap &Functions)
Finds uses of Global Variables on a per-function basis.
DenseMap< Function *, DenseSet< GlobalVariable * > > FunctionVariableMap
bool isLDSVariableToLower(const GlobalVariable &GV)
Align getAlign(const DataLayout &DL, const GlobalVariable *GV)
DenseMap< GlobalVariable *, DenseSet< Function * > > VariableFunctionMap
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI std::string getUniqueModuleId(Module *M)
Produce a unique identifier for this module by taking the MD5 sum of the names of the module's strong...
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
char & AMDGPULowerModuleLDSLegacyPassID
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
S1Ty set_intersection(const S1Ty &S1, const S2Ty &S2)
set_intersection(A, B) - Return A ^ B
LLVM_ABI void removeFromUsedLists(Module &M, function_ref< bool(Constant *)> ShouldRemove)
Removes global values from the llvm.used and llvm.compiler.used arrays.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
ModulePass * createAMDGPULowerModuleLDSLegacyPass(const AMDGPUTargetMachine *TM=nullptr)
@ Other
Any other memory.
Definition ModRef.h:68
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
LLVM_ABI std::pair< uint64_t, Align > performOptimizedStructLayout(MutableArrayRef< OptimizedStructLayoutField > Fields)
Compute a layout for a struct containing the given fields, making a best-effort attempt to minimize t...
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
#define N
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
const AMDGPUTargetMachine & TM
Definition AMDGPU.h:212
FunctionVariableMap DirectAccess
FunctionVariableMap IndirectAccess
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77