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"
200#include "llvm/Support/Format.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(cast<Constant>(LocalVar->stripPointerCasts()));
233
235 M, [&LocalVarsSet](Constant *C) { return LocalVarsSet.count(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
266 Func->getParent(), Intrinsic::donothing, {});
267
268 Value *UseInstance[1] = {
269 Builder.CreateConstInBoundsGEP1_32(SGV->getValueType(), SGV, 0)};
270
271 Builder.CreateCall(
272 Decl, {}, {OperandBundleDefT<Value *>("ExplicitUse", UseInstance)});
273 }
274
275public:
276 AMDGPULowerModuleLDS(const AMDGPUTargetMachine &TM_) : TM(TM_) {}
277
278 struct LDSVariableReplacement {
279 GlobalVariable *SGV = nullptr;
280 DenseMap<GlobalVariable *, Constant *> LDSVarsToConstantGEP;
281 };
282
283 // remap from lds global to a constantexpr gep to where it has been moved to
284 // for each kernel
285 // an array with an element for each kernel containing where the corresponding
286 // variable was remapped to
287
288 static Constant *getAddressesOfVariablesInKernel(
290 const DenseMap<GlobalVariable *, Constant *> &LDSVarsToConstantGEP) {
291 // Create a ConstantArray containing the address of each Variable within the
292 // kernel corresponding to LDSVarsToConstantGEP, or poison if that kernel
293 // does not allocate it
294
296 ArrayType *KernelOffsetsType = ArrayType::get(LocalPtrTy, Variables.size());
297
299 for (GlobalVariable *GV : Variables) {
300 auto ConstantGepIt = LDSVarsToConstantGEP.find(GV);
301 if (ConstantGepIt != LDSVarsToConstantGEP.end()) {
302 Elements.push_back(ConstantGepIt->second);
303 } else {
304 Elements.push_back(PoisonValue::get(LocalPtrTy));
305 }
306 }
307 return ConstantArray::get(KernelOffsetsType, Elements);
308 }
309
310 static GlobalVariable *buildLookupTable(
312 ArrayRef<Function *> kernels,
314 if (Variables.empty()) {
315 return nullptr;
316 }
317 LLVMContext &Ctx = M.getContext();
318
319 const size_t NumberVariables = Variables.size();
320 const size_t NumberKernels = kernels.size();
321
323 ArrayType *KernelOffsetsType = ArrayType::get(LocalPtrTy, NumberVariables);
324
325 ArrayType *AllKernelsOffsetsType =
326 ArrayType::get(KernelOffsetsType, NumberKernels);
327
328 Constant *Missing = PoisonValue::get(KernelOffsetsType);
329 std::vector<Constant *> overallConstantExprElts(NumberKernels);
330 for (size_t i = 0; i < NumberKernels; i++) {
331 auto Replacement = KernelToReplacement.find(kernels[i]);
332 overallConstantExprElts[i] =
333 (Replacement == KernelToReplacement.end())
334 ? Missing
335 : getAddressesOfVariablesInKernel(
336 Ctx, Variables, Replacement->second.LDSVarsToConstantGEP);
337 }
338
339 Constant *init =
340 ConstantArray::get(AllKernelsOffsetsType, overallConstantExprElts);
341
342 return new GlobalVariable(
343 M, AllKernelsOffsetsType, true, GlobalValue::InternalLinkage, init,
344 "llvm.amdgcn.lds.offset.table", nullptr, GlobalValue::NotThreadLocal,
346 }
347
348 void replaceUseWithTableLookup(Module &M, IRBuilder<> &Builder,
349 GlobalVariable *LookupTable,
350 GlobalVariable *GV, Use &U,
351 Value *OptionalIndex) {
352 // Table is a constant array of the same length as OrderedKernels
353 LLVMContext &Ctx = M.getContext();
354 Type *I32 = Type::getInt32Ty(Ctx);
355 auto *I = cast<Instruction>(U.getUser());
356
357 Value *tableKernelIndex = getTableLookupKernelIndex(M, I->getFunction());
358
359 if (auto *Phi = dyn_cast<PHINode>(I)) {
360 BasicBlock *BB = Phi->getIncomingBlock(U);
361 Builder.SetInsertPoint(&(*(BB->getFirstInsertionPt())));
362 } else {
363 Builder.SetInsertPoint(I);
364 }
365
366 SmallVector<Value *, 3> GEPIdx = {
367 ConstantInt::get(I32, 0),
368 tableKernelIndex,
369 };
370 if (OptionalIndex)
371 GEPIdx.push_back(OptionalIndex);
372
373 Value *Address = Builder.CreateInBoundsGEP(
374 LookupTable->getValueType(), LookupTable, GEPIdx, GV->getName());
375
376 Value *Loaded = Builder.CreateLoad(GV->getType(), Address);
377 U.set(Loaded);
378 }
379
380 void replaceUsesInInstructionsWithTableLookup(
381 Module &M, ArrayRef<GlobalVariable *> ModuleScopeVariables,
382 GlobalVariable *LookupTable) {
383
384 LLVMContext &Ctx = M.getContext();
385 IRBuilder<> Builder(M);
386 Builder.disableGEPCanonicalization();
387 Type *I32 = Type::getInt32Ty(Ctx);
388
389 for (size_t Index = 0; Index < ModuleScopeVariables.size(); Index++) {
390 auto *GV = ModuleScopeVariables[Index];
391
392 for (Use &U : make_early_inc_range(GV->uses())) {
393 auto *I = dyn_cast<Instruction>(U.getUser());
394 if (!I)
395 continue;
396
397 replaceUseWithTableLookup(M, Builder, LookupTable, GV, U,
398 ConstantInt::get(I32, Index));
399 }
400 }
401 }
402
403 static DenseSet<Function *> kernelsThatIndirectlyAccessAnyOfPassedVariables(
404 Module &M, GVUsesInfoTy &LDSUsesInfo,
405 DenseSet<GlobalVariable *> const &VariableSet) {
406
407 DenseSet<Function *> KernelSet;
408
409 if (VariableSet.empty())
410 return KernelSet;
411
412 for (Function &Func : M.functions()) {
413 if (Func.isDeclaration() || !isKernel(Func))
414 continue;
415 for (GlobalVariable *GV : LDSUsesInfo.IndirectAccess[&Func]) {
416 if (VariableSet.contains(GV)) {
417 KernelSet.insert(&Func);
418 break;
419 }
420 }
421 }
422
423 return KernelSet;
424 }
425
426 static GlobalVariable *
427 chooseBestVariableForModuleStrategy(const DataLayout &DL,
428 VariableFunctionMap &LDSVars) {
429 // Find the global variable with the most indirect uses from kernels
430
431 struct CandidateTy {
432 GlobalVariable *GV = nullptr;
433 size_t UserCount = 0;
434 size_t Size = 0;
435
436 CandidateTy() = default;
437
438 CandidateTy(GlobalVariable *GV, uint64_t UserCount, uint64_t AllocSize)
439 : GV(GV), UserCount(UserCount), Size(AllocSize) {}
440
441 bool operator<(const CandidateTy &Other) const {
442 // Fewer users makes module scope variable less attractive
443 if (UserCount < Other.UserCount) {
444 return true;
445 }
446 if (UserCount > Other.UserCount) {
447 return false;
448 }
449
450 // Bigger makes module scope variable less attractive
451 if (Size < Other.Size) {
452 return false;
453 }
454
455 if (Size > Other.Size) {
456 return true;
457 }
458
459 // Arbitrary but consistent
460 return GV->getName() < Other.GV->getName();
461 }
462 };
463
464 CandidateTy MostUsed;
465
466 for (auto &K : LDSVars) {
467 GlobalVariable *GV = K.first;
468 if (K.second.size() <= 1) {
469 // A variable reachable by only one kernel is best lowered with kernel
470 // strategy
471 continue;
472 }
473 CandidateTy Candidate(GV, K.second.size(), GV->getGlobalSize(DL));
474 if (MostUsed < Candidate)
475 MostUsed = Candidate;
476 }
477
478 return MostUsed.GV;
479 }
480
481 static void recordLDSAbsoluteAddress(Module *M, GlobalVariable *GV,
482 uint32_t Address) {
483 // Write the specified address into metadata where it can be retrieved by
484 // the assembler. Format is a half open range, [Address Address+1)
485 LLVMContext &Ctx = M->getContext();
486 auto *IntTy =
487 M->getDataLayout().getIntPtrType(Ctx, AMDGPUAS::LOCAL_ADDRESS);
488 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntTy, Address));
489 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntTy, Address + 1));
490 GV->setMetadata(LLVMContext::MD_absolute_symbol,
491 MDNode::get(Ctx, {MinC, MaxC}));
492 }
493
494 DenseMap<Function *, Value *> tableKernelIndexCache;
495 Value *getTableLookupKernelIndex(Module &M, Function *F) {
496 // Accesses from a function use the amdgcn_lds_kernel_id intrinsic which
497 // lowers to a read from a live in register. Emit it once in the entry
498 // block to spare deduplicating it later.
499 auto [It, Inserted] = tableKernelIndexCache.try_emplace(F);
500 if (Inserted) {
501 auto InsertAt = F->getEntryBlock().getFirstNonPHIOrAlloca();
502 IRBuilder<> Builder(&*InsertAt);
503
504 It->second = Builder.CreateIntrinsic(Intrinsic::amdgcn_lds_kernel_id, {});
505 }
506
507 return It->second;
508 }
509
510 static std::vector<Function *> assignLDSKernelIDToEachKernel(
511 Module *M, DenseSet<Function *> const &KernelsThatAllocateTableLDS,
512 DenseSet<Function *> const &KernelsThatIndirectlyAllocateDynamicLDS) {
513 // Associate kernels in the set with an arbitrary but reproducible order and
514 // annotate them with that order in metadata. This metadata is recognised by
515 // the backend and lowered to a SGPR which can be read from using
516 // amdgcn_lds_kernel_id.
517
518 std::vector<Function *> OrderedKernels;
519 if (!KernelsThatAllocateTableLDS.empty() ||
520 !KernelsThatIndirectlyAllocateDynamicLDS.empty()) {
521
522 for (Function &Func : M->functions()) {
523 if (Func.isDeclaration())
524 continue;
525 if (!isKernel(Func))
526 continue;
527
528 if (KernelsThatAllocateTableLDS.contains(&Func) ||
529 KernelsThatIndirectlyAllocateDynamicLDS.contains(&Func)) {
530 assert(Func.hasName()); // else fatal error earlier
531 OrderedKernels.push_back(&Func);
532 }
533 }
534
535 // Put them in an arbitrary but reproducible order
536 OrderedKernels = sortByName(std::move(OrderedKernels));
537
538 // Annotate the kernels with their order in this vector
539 LLVMContext &Ctx = M->getContext();
540 IRBuilder<> Builder(*M);
541
542 if (OrderedKernels.size() > UINT32_MAX) {
543 // 32 bit keeps it in one SGPR. > 2**32 kernels won't fit on the GPU
544 reportFatalUsageError("unimplemented LDS lowering for > 2**32 kernels");
545 }
546
547 for (size_t i = 0; i < OrderedKernels.size(); i++) {
548 Metadata *AttrMDArgs[1] = {
549 ConstantAsMetadata::get(Builder.getInt32(i)),
550 };
551 OrderedKernels[i]->setMetadata("llvm.amdgcn.lds.kernel.id",
552 MDNode::get(Ctx, AttrMDArgs));
553 }
554 }
555 return OrderedKernels;
556 }
557
558 void partitionVariablesIntoIndirectStrategies(
559 Module &M, GVUsesInfoTy const &LDSUsesInfo,
560 VariableFunctionMap &LDSToKernelsThatNeedToAccessItIndirectly,
561 DenseSet<GlobalVariable *> &ModuleScopeVariables,
562 DenseSet<GlobalVariable *> &TableLookupVariables,
563 DenseSet<GlobalVariable *> &KernelAccessVariables,
564 DenseSet<GlobalVariable *> &DynamicVariables) {
565 LDSLoweringKind LoweringKind = TM.getCLOpts().lower_module_lds_strategy;
566
567 GlobalVariable *HybridModuleRoot =
568 LoweringKind != LDSLoweringKind::hybrid
569 ? nullptr
570 : chooseBestVariableForModuleStrategy(
571 M.getDataLayout(), LDSToKernelsThatNeedToAccessItIndirectly);
572
573 DenseSet<Function *> const EmptySet;
574 DenseSet<Function *> const &HybridModuleRootKernels =
575 HybridModuleRoot
576 ? LDSToKernelsThatNeedToAccessItIndirectly[HybridModuleRoot]
577 : EmptySet;
578
579 for (auto &K : LDSToKernelsThatNeedToAccessItIndirectly) {
580 // Each iteration of this loop assigns exactly one global variable to
581 // exactly one of the implementation strategies.
582
583 GlobalVariable *GV = K.first;
585 assert(!K.second.empty());
586
587 if (AMDGPU::isDynamicLDS(*GV)) {
588 DynamicVariables.insert(GV);
589 continue;
590 }
591
592 switch (LoweringKind) {
593 case LDSLoweringKind::module:
594 ModuleScopeVariables.insert(GV);
595 break;
596
597 case LDSLoweringKind::table:
598 TableLookupVariables.insert(GV);
599 break;
600
601 case LDSLoweringKind::kernel:
602 if (K.second.size() == 1) {
603 KernelAccessVariables.insert(GV);
604 } else {
605 // FIXME: This should use DiagnosticInfo
607 "cannot lower LDS '" + GV->getName() +
608 "' to kernel access as it is reachable from multiple kernels");
609 }
610 break;
611
612 case LDSLoweringKind::hybrid: {
613 if (GV == HybridModuleRoot) {
614 assert(K.second.size() != 1);
615 ModuleScopeVariables.insert(GV);
616 } else if (K.second.size() == 1) {
617 KernelAccessVariables.insert(GV);
618 } else if (K.second == HybridModuleRootKernels) {
619 ModuleScopeVariables.insert(GV);
620 } else {
621 TableLookupVariables.insert(GV);
622 }
623 break;
624 }
625 }
626 }
627
628 // All LDS variables accessed indirectly have now been partitioned into
629 // the distinct lowering strategies.
630 assert(ModuleScopeVariables.size() + TableLookupVariables.size() +
631 KernelAccessVariables.size() + DynamicVariables.size() ==
632 LDSToKernelsThatNeedToAccessItIndirectly.size());
633 }
634
635 static GlobalVariable *lowerModuleScopeStructVariables(
636 Module &M, DenseSet<GlobalVariable *> const &ModuleScopeVariables,
637 DenseSet<Function *> const &KernelsThatAllocateModuleLDS) {
638 // Create a struct to hold the ModuleScopeVariables
639 // Replace all uses of those variables from non-kernel functions with the
640 // new struct instance Replace only the uses from kernel functions that will
641 // allocate this instance. That is a space optimisation - kernels that use a
642 // subset of the module scope struct and do not need to allocate it for
643 // indirect calls will only allocate the subset they use (they do so as part
644 // of the per-kernel lowering).
645 if (ModuleScopeVariables.empty()) {
646 return nullptr;
647 }
648
649 LLVMContext &Ctx = M.getContext();
650
651 LDSVariableReplacement ModuleScopeReplacement =
652 createLDSVariableReplacement(M, "llvm.amdgcn.module.lds",
653 ModuleScopeVariables);
654
655 appendToCompilerUsed(M, {static_cast<GlobalValue *>(
657 cast<Constant>(ModuleScopeReplacement.SGV),
658 PointerType::getUnqual(Ctx)))});
659
660 // module.lds will be allocated at zero in any kernel that allocates it
661 recordLDSAbsoluteAddress(&M, ModuleScopeReplacement.SGV, 0);
662
663 // historic
664 removeLocalVarsFromUsedLists(M, ModuleScopeVariables);
665
666 // Replace all uses of module scope variable from non-kernel functions
667 replaceLDSVariablesWithStruct(
668 M, ModuleScopeVariables, ModuleScopeReplacement, [&](Use &U) {
669 Instruction *I = dyn_cast<Instruction>(U.getUser());
670 if (!I) {
671 return false;
672 }
673 Function *F = I->getFunction();
674 return !isKernel(*F);
675 });
676
677 // Replace uses of module scope variable from kernel functions that
678 // allocate the module scope variable, otherwise leave them unchanged
679 // Record on each kernel whether the module scope global is used by it
680
681 for (Function &Func : M.functions()) {
682 if (Func.isDeclaration() || !isKernel(Func))
683 continue;
684
685 if (KernelsThatAllocateModuleLDS.contains(&Func)) {
686 replaceLDSVariablesWithStruct(
687 M, ModuleScopeVariables, ModuleScopeReplacement, [&](Use &U) {
688 Instruction *I = dyn_cast<Instruction>(U.getUser());
689 if (!I) {
690 return false;
691 }
692 Function *F = I->getFunction();
693 return F == &Func;
694 });
695
696 markUsedByKernel(&Func, ModuleScopeReplacement.SGV);
697 }
698 }
699
700 return ModuleScopeReplacement.SGV;
701 }
702
704 lowerKernelScopeStructVariables(
705 Module &M, GVUsesInfoTy &LDSUsesInfo,
706 DenseSet<GlobalVariable *> const &ModuleScopeVariables,
707 DenseSet<Function *> const &KernelsThatAllocateModuleLDS,
708 GlobalVariable *MaybeModuleScopeStruct) {
709
710 // Create a struct for each kernel for the non-module-scope variables.
711
713 for (Function &Func : M.functions()) {
714 if (Func.isDeclaration() || !isKernel(Func))
715 continue;
716
717 DenseSet<GlobalVariable *> KernelUsedVariables;
718 // Allocating variables that are used directly in this struct to get
719 // alignment aware allocation and predictable frame size.
720 for (auto &v : LDSUsesInfo.DirectAccess[&Func]) {
721 if (!AMDGPU::isDynamicLDS(*v)) {
722 KernelUsedVariables.insert(v);
723 }
724 }
725
726 // Allocating variables that are accessed indirectly so that a lookup of
727 // this struct instance can find them from nested functions.
728 for (auto &v : LDSUsesInfo.IndirectAccess[&Func]) {
729 if (!AMDGPU::isDynamicLDS(*v)) {
730 KernelUsedVariables.insert(v);
731 }
732 }
733
734 // Variables allocated in module lds must all resolve to that struct,
735 // not to the per-kernel instance.
736 if (KernelsThatAllocateModuleLDS.contains(&Func)) {
737 for (GlobalVariable *v : ModuleScopeVariables) {
738 KernelUsedVariables.erase(v);
739 }
740 }
741
742 if (KernelUsedVariables.empty()) {
743 // Either used no LDS, or the LDS it used was all in the module struct
744 // or dynamically sized
745 continue;
746 }
747
748 // The association between kernel function and LDS struct is done by
749 // symbol name, which only works if the function in question has a
750 // name This is not expected to be a problem in practice as kernels
751 // are called by name making anonymous ones (which are named by the
752 // backend) difficult to use. This does mean that llvm test cases need
753 // to name the kernels.
754 if (!Func.hasName()) {
755 reportFatalUsageError("anonymous kernels cannot use LDS variables");
756 }
757
758 std::string VarName =
759 (Twine("llvm.amdgcn.kernel.") + Func.getName() + ".lds").str();
760
761 auto Replacement =
762 createLDSVariableReplacement(M, VarName, KernelUsedVariables);
763
764 // If any indirect uses, create a direct use to ensure allocation
765 // TODO: Simpler to unconditionally mark used but that regresses
766 // codegen in test/CodeGen/AMDGPU/noclobber-barrier.ll
767 auto Accesses = LDSUsesInfo.IndirectAccess.find(&Func);
768 if ((Accesses != LDSUsesInfo.IndirectAccess.end()) &&
769 !Accesses->second.empty())
770 markUsedByKernel(&Func, Replacement.SGV);
771
772 // remove preserves existing codegen
773 removeLocalVarsFromUsedLists(M, KernelUsedVariables);
774 KernelToReplacement[&Func] = Replacement;
775
776 // Rewrite uses within kernel to the new struct
777 replaceLDSVariablesWithStruct(
778 M, KernelUsedVariables, Replacement, [&Func](Use &U) {
779 Instruction *I = dyn_cast<Instruction>(U.getUser());
780 return I && I->getFunction() == &Func;
781 });
782 }
783 return KernelToReplacement;
784 }
785
786 static GlobalVariable *
787 buildRepresentativeDynamicLDSInstance(Module &M, GVUsesInfoTy &LDSUsesInfo,
788 Function *func) {
789 // Create a dynamic lds variable with a name associated with the passed
790 // function that has the maximum alignment of any dynamic lds variable
791 // reachable from this kernel. Dynamic LDS is allocated after the static LDS
792 // allocation, possibly after alignment padding. The representative variable
793 // created here has the maximum alignment of any other dynamic variable
794 // reachable by that kernel. All dynamic LDS variables are allocated at the
795 // same address in each kernel in order to provide the documented aliasing
796 // semantics. Setting the alignment here allows this IR pass to accurately
797 // predict the exact constant at which it will be allocated.
798
799 assert(isKernel(*func));
800
801 LLVMContext &Ctx = M.getContext();
802 const DataLayout &DL = M.getDataLayout();
803 Align MaxDynamicAlignment(1);
804
805 auto UpdateMaxAlignment = [&MaxDynamicAlignment, &DL](GlobalVariable *GV) {
806 if (AMDGPU::isDynamicLDS(*GV)) {
807 MaxDynamicAlignment =
808 std::max(MaxDynamicAlignment, AMDGPU::getAlign(DL, GV));
809 }
810 };
811
812 for (GlobalVariable *GV : LDSUsesInfo.IndirectAccess[func]) {
813 UpdateMaxAlignment(GV);
814 }
815
816 for (GlobalVariable *GV : LDSUsesInfo.DirectAccess[func]) {
817 UpdateMaxAlignment(GV);
818 }
819
820 assert(func->hasName()); // Checked by caller
821 auto *emptyCharArray = ArrayType::get(Type::getInt8Ty(Ctx), 0);
823 M, emptyCharArray, false, GlobalValue::ExternalLinkage, nullptr,
824 Twine("llvm.amdgcn." + func->getName() + ".dynlds"), nullptr,
826 N->setAlignment(MaxDynamicAlignment);
827
829 return N;
830 }
831
832 DenseMap<Function *, GlobalVariable *> lowerDynamicLDSVariables(
833 Module &M, GVUsesInfoTy &LDSUsesInfo,
834 DenseSet<Function *> const &KernelsThatIndirectlyAllocateDynamicLDS,
835 DenseSet<GlobalVariable *> const &DynamicVariables,
836 std::vector<Function *> const &OrderedKernels) {
837 DenseMap<Function *, GlobalVariable *> KernelToCreatedDynamicLDS;
838 if (!KernelsThatIndirectlyAllocateDynamicLDS.empty()) {
839 LLVMContext &Ctx = M.getContext();
840 IRBuilder<> Builder(M);
842
843 std::vector<Constant *> newDynamicLDS;
844
845 // Table is built in the same order as OrderedKernels
846 for (auto &func : OrderedKernels) {
847
848 if (KernelsThatIndirectlyAllocateDynamicLDS.contains(func)) {
849 assert(isKernel(*func));
850 if (!func->hasName()) {
851 reportFatalUsageError("anonymous kernels cannot use LDS variables");
852 }
853
855 buildRepresentativeDynamicLDSInstance(M, LDSUsesInfo, func);
856
857 KernelToCreatedDynamicLDS[func] = N;
858
859 markUsedByKernel(func, N);
860
861 newDynamicLDS.push_back(N);
862 } else {
863 newDynamicLDS.push_back(PoisonValue::get(LocalPtrTy));
864 }
865 }
866 assert(OrderedKernels.size() == newDynamicLDS.size());
867
868 ArrayType *t = ArrayType::get(LocalPtrTy, newDynamicLDS.size());
869 Constant *init = ConstantArray::get(t, newDynamicLDS);
871 M, t, true, GlobalValue::InternalLinkage, init,
872 "llvm.amdgcn.dynlds.offset.table", nullptr,
874
875 for (GlobalVariable *GV : DynamicVariables) {
876 for (Use &U : make_early_inc_range(GV->uses())) {
877 auto *I = dyn_cast<Instruction>(U.getUser());
878 if (!I)
879 continue;
880 if (isKernel(*I->getFunction()))
881 continue;
882
883 replaceUseWithTableLookup(M, Builder, table, GV, U, nullptr);
884 }
885 }
886 }
887 return KernelToCreatedDynamicLDS;
888 }
889
890 // Per-TU mode for link-time LDS resolution. Instead of computing a global
891 // layout, create per-function LDS struct declarations so the linker can
892 // assign offsets across TUs.
893 bool runOnModuleLinkTime(Module &M) {
894 bool Changed = superAlignLDSGlobals(M);
895 Changed |=
897
898 CallGraph CG(M);
899 FunctionVariableMap KernelLDSUses, FunctionLDSUses;
900 getUsesOfGVByFunction(CG, M, isLDSVariableToLower, KernelLDSUses,
901 FunctionLDSUses);
902
903 if (KernelLDSUses.empty() && FunctionLDSUses.empty())
904 return Changed;
905
906 std::string ModuleId = getUniqueModuleId(&M);
907 assert(!ModuleId.empty() &&
908 "modules with LDS variables should have a unique ID");
909
910 FunctionVariableMap AllLDSUses;
911 for (auto &[F, Vars] : KernelLDSUses)
912 AllLDSUses[F].insert(Vars.begin(), Vars.end());
913 for (auto &[F, Vars] : FunctionLDSUses)
914 AllLDSUses[F].insert(Vars.begin(), Vars.end());
915
916 // Build reverse map: LDS variable -> functions that use it.
918 for (auto &[F, Vars] : AllLDSUses) {
919 for (GlobalVariable *V : Vars)
920 VarToFuncs[V].push_back(F);
921 }
922
923 // A variable is function-scope iff it has local linkage and exactly one
924 // user function. Everything else is global-scope and must remain as a
925 // standalone external declaration so the linker can assign a single shared
926 // offset.
927 DenseSet<GlobalVariable *> GlobalScopeVars;
928 DenseSet<GlobalVariable *> InternalMultiUserVars;
929 for (auto &[V, Funcs] : VarToFuncs) {
930 if (!V->hasLocalLinkage() || Funcs.size() > 1) {
931 GlobalScopeVars.insert(V);
932 if (V->hasLocalLinkage())
933 InternalMultiUserVars.insert(V);
934 }
935 }
936
937 // Wrap function-scope LDS into per-function structs (unchanged logic,
938 // but global-scope variables are excluded from the set).
940 DenseSet<GlobalVariable *> AllReplacedVars;
941 for (auto &KV : AllLDSUses) {
942 Function *F = KV.first;
943 DenseSet<GlobalVariable *> FuncScopeVars;
944 for (GlobalVariable *V : KV.second) {
945 if (!GlobalScopeVars.count(V))
946 FuncScopeVars.insert(V);
947 }
948
949 if (FuncScopeVars.empty())
950 continue;
951
952 std::string StructName =
953 F->hasLocalLinkage()
954 ? ("__amdgpu_lds." + F->getName() + "." + ModuleId).str()
955 : ("__amdgpu_lds." + F->getName()).str();
956 LDSVariableReplacement Replacement =
957 createLDSVariableReplacement(M, StructName, FuncScopeVars);
958
959 GlobalVariable *SGV = Replacement.SGV;
960 SGV->setLinkage(GlobalValue::ExternalLinkage);
961 SGV->setInitializer(nullptr);
962 FuncToLdsStruct.push_back({F, SGV});
963
964 replaceLDSVariablesWithStruct(
965 M, FuncScopeVars, Replacement, [F](const Use &U) {
966 auto *I = dyn_cast<Instruction>(U.getUser());
967 return I && I->getFunction() == F;
968 });
969
970 AllReplacedVars.insert(FuncScopeVars.begin(), FuncScopeVars.end());
971 }
972
973 // Internal-linkage LDS variables used by multiple functions would collide
974 // across TUs if promoted individually to external linkage (same name in
975 // different TUs). Pack them into a single per-module struct with a
976 // module-unique name so the linker treats them as one allocation unit.
977 if (!InternalMultiUserVars.empty()) {
978 std::string StructName = "__amdgpu_lds.__internal." + ModuleId;
979 LDSVariableReplacement Replacement =
980 createLDSVariableReplacement(M, StructName, InternalMultiUserVars);
981
982 GlobalVariable *SGV = Replacement.SGV;
983 SGV->setLinkage(GlobalValue::ExternalLinkage);
984 SGV->setInitializer(nullptr);
985
986 replaceLDSVariablesWithStruct(
987 M, InternalMultiUserVars, Replacement,
988 [](const Use &U) { return isa<Instruction>(U.getUser()); });
989
990 DenseSet<Function *> FuncsUsingInternalVars;
991 for (GlobalVariable *V : InternalMultiUserVars) {
992 for (Function *F : VarToFuncs[V])
993 FuncsUsingInternalVars.insert(F);
994 }
995 for (Function *F : FuncsUsingInternalVars)
996 FuncToLdsStruct.push_back({F, SGV});
997
998 AllReplacedVars.insert(InternalMultiUserVars.begin(),
999 InternalMultiUserVars.end());
1000 }
1001
1002 // Convert global-scope LDS to external declarations. Their uses remain
1003 // intact and ISel generates R_AMDGPU_ABS32_LO relocations for them.
1004 for (GlobalVariable *V : GlobalScopeVars) {
1005 V->setInitializer(nullptr);
1006 V->setLinkage(GlobalValue::ExternalLinkage);
1007 }
1008
1009 // Emit amdgpu.lds.uses metadata for struct and global-scope LDS.
1010 {
1011 LLVMContext &Ctx = M.getContext();
1012 NamedMDNode *LdsMD = M.getOrInsertNamedMetadata("amdgpu.lds.uses");
1013
1014 for (auto &[F, SGV] : FuncToLdsStruct)
1015 LdsMD->addOperand(MDNode::get(
1017
1018 for (auto &[V, Funcs] : VarToFuncs) {
1019 if (GlobalScopeVars.count(V) && !InternalMultiUserVars.count(V)) {
1020 for (Function *F : Funcs) {
1021 LdsMD->addOperand(MDNode::get(
1023 }
1024 }
1025 }
1026 }
1027
1028 DenseSet<GlobalVariable *> AllLDSVarsForCleanup = AllReplacedVars;
1029 AllLDSVarsForCleanup.insert(GlobalScopeVars.begin(), GlobalScopeVars.end());
1030 removeLocalVarsFromUsedLists(M, AllLDSVarsForCleanup);
1031 for (GlobalVariable *GV : AllReplacedVars) {
1033 if (GV->use_empty())
1034 GV->eraseFromParent();
1035 }
1036
1037 return true;
1038 }
1039
1040 bool runOnModule(Module &M) {
1042 return runOnModuleLinkTime(M);
1043 return runOnModuleNormal(M);
1044 }
1045
1046 bool runOnModuleNormal(Module &M) {
1047 bool Changed = superAlignLDSGlobals(M);
1048
1049 Changed |= any_of(M.globals(), isNotYetLoweredLDSVariable);
1050
1051 CallGraph CG(M);
1052
1054 isNotYetLoweredLDSVariable);
1055
1056 // For each kernel, what variables does it access directly or through
1057 // callees
1059
1060 // For each variable accessed through callees, which kernels access it
1061 VariableFunctionMap LDSToKernelsThatNeedToAccessItIndirectly;
1062 for (auto &K : LDSUsesInfo.IndirectAccess) {
1063 Function *F = K.first;
1064 assert(isKernel(*F));
1065 for (GlobalVariable *GV : K.second) {
1066 LDSToKernelsThatNeedToAccessItIndirectly[GV].insert(F);
1067 }
1068 }
1069
1070 // Partition variables accessed indirectly into the different strategies
1071 DenseSet<GlobalVariable *> ModuleScopeVariables;
1072 DenseSet<GlobalVariable *> TableLookupVariables;
1073 DenseSet<GlobalVariable *> KernelAccessVariables;
1074 DenseSet<GlobalVariable *> DynamicVariables;
1075 partitionVariablesIntoIndirectStrategies(
1076 M, LDSUsesInfo, LDSToKernelsThatNeedToAccessItIndirectly,
1077 ModuleScopeVariables, TableLookupVariables, KernelAccessVariables,
1078 DynamicVariables);
1079
1080 // If the kernel accesses a variable that is going to be stored in the
1081 // module instance through a call then that kernel needs to allocate the
1082 // module instance
1083 const DenseSet<Function *> KernelsThatAllocateModuleLDS =
1084 kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo,
1085 ModuleScopeVariables);
1086 const DenseSet<Function *> KernelsThatAllocateTableLDS =
1087 kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo,
1088 TableLookupVariables);
1089
1090 const DenseSet<Function *> KernelsThatIndirectlyAllocateDynamicLDS =
1091 kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo,
1092 DynamicVariables);
1093
1094 GlobalVariable *MaybeModuleScopeStruct = lowerModuleScopeStructVariables(
1095 M, ModuleScopeVariables, KernelsThatAllocateModuleLDS);
1096
1098 lowerKernelScopeStructVariables(M, LDSUsesInfo, ModuleScopeVariables,
1099 KernelsThatAllocateModuleLDS,
1100 MaybeModuleScopeStruct);
1101
1102 // Lower zero cost accesses to the kernel instances just created
1103 for (auto &GV : KernelAccessVariables) {
1104 auto &funcs = LDSToKernelsThatNeedToAccessItIndirectly[GV];
1105 assert(funcs.size() == 1); // Only one kernel can access it
1106 LDSVariableReplacement Replacement =
1107 KernelToReplacement[*(funcs.begin())];
1108
1110 Vec.insert(GV);
1111
1112 replaceLDSVariablesWithStruct(M, Vec, Replacement, [](Use &U) {
1113 return isa<Instruction>(U.getUser());
1114 });
1115 }
1116
1117 // The ith element of this vector is kernel id i
1118 std::vector<Function *> OrderedKernels =
1119 assignLDSKernelIDToEachKernel(&M, KernelsThatAllocateTableLDS,
1120 KernelsThatIndirectlyAllocateDynamicLDS);
1121
1122 if (!KernelsThatAllocateTableLDS.empty()) {
1123 // The order must be consistent between lookup table and accesses to
1124 // lookup table
1125 auto TableLookupVariablesOrdered =
1126 sortByName(std::vector<GlobalVariable *>(TableLookupVariables.begin(),
1127 TableLookupVariables.end()));
1128
1129 GlobalVariable *LookupTable = buildLookupTable(
1130 M, TableLookupVariablesOrdered, OrderedKernels, KernelToReplacement);
1131 replaceUsesInInstructionsWithTableLookup(M, TableLookupVariablesOrdered,
1132 LookupTable);
1133 }
1134
1135 DenseMap<Function *, GlobalVariable *> KernelToCreatedDynamicLDS =
1136 lowerDynamicLDSVariables(M, LDSUsesInfo,
1137 KernelsThatIndirectlyAllocateDynamicLDS,
1138 DynamicVariables, OrderedKernels);
1139
1140 // Strip amdgpu-no-lds-kernel-id from all functions reachable from the
1141 // kernel. We may have inferred this wasn't used prior to the pass.
1142 // TODO: We could filter out subgraphs that do not access LDS globals.
1143 for (auto *KernelSet : {&KernelsThatIndirectlyAllocateDynamicLDS,
1144 &KernelsThatAllocateTableLDS})
1145 for (Function *F : *KernelSet)
1146 removeFnAttrFromReachable(CG, F, {"amdgpu-no-lds-kernel-id"});
1147
1148 // All kernel frames have been allocated. Calculate and record the
1149 // addresses.
1150 {
1151 const DataLayout &DL = M.getDataLayout();
1152
1153 for (Function &Func : M.functions()) {
1154 if (Func.isDeclaration() || !isKernel(Func))
1155 continue;
1156
1157 // All three of these are optional. The first variable is allocated at
1158 // zero. They are allocated by AMDGPUMachineFunctionInfo as one block.
1159 // Layout:
1160 //{
1161 // module.lds
1162 // alignment padding
1163 // kernel instance
1164 // alignment padding
1165 // dynamic lds variables
1166 //}
1167
1168 const bool AllocateModuleScopeStruct =
1169 MaybeModuleScopeStruct &&
1170 KernelsThatAllocateModuleLDS.contains(&Func);
1171
1172 auto Replacement = KernelToReplacement.find(&Func);
1173 const bool AllocateKernelScopeStruct =
1174 Replacement != KernelToReplacement.end();
1175
1176 const bool AllocateDynamicVariable =
1177 KernelToCreatedDynamicLDS.contains(&Func);
1178
1179 uint32_t Offset = 0;
1180
1181 if (AllocateModuleScopeStruct) {
1182 // Allocated at zero, recorded once on construction, not once per
1183 // kernel
1184 Offset += MaybeModuleScopeStruct->getGlobalSize(DL);
1185 }
1186
1187 if (AllocateKernelScopeStruct) {
1188 GlobalVariable *KernelStruct = Replacement->second.SGV;
1189 Offset = alignTo(Offset, AMDGPU::getAlign(DL, KernelStruct));
1190 recordLDSAbsoluteAddress(&M, KernelStruct, Offset);
1191 Offset += KernelStruct->getGlobalSize(DL);
1192 }
1193
1194 // If there is dynamic allocation, the alignment needed is included in
1195 // the static frame size. There may be no reference to the dynamic
1196 // variable in the kernel itself, so without including it here, that
1197 // alignment padding could be missed.
1198 if (AllocateDynamicVariable) {
1199 GlobalVariable *DynamicVariable = KernelToCreatedDynamicLDS[&Func];
1200 Offset = alignTo(Offset, AMDGPU::getAlign(DL, DynamicVariable));
1201 recordLDSAbsoluteAddress(&M, DynamicVariable, Offset);
1202 }
1203
1204 if (Offset != 0) {
1205 (void)TM; // TODO: Account for target maximum LDS
1206 std::string Buffer;
1207 raw_string_ostream SS{Buffer};
1208 SS << format("%u", Offset);
1209
1210 // Instead of explicitly marking kernels that access dynamic variables
1211 // using special case metadata, annotate with min-lds == max-lds, i.e.
1212 // that there is no more space available for allocating more static
1213 // LDS variables. That is the right condition to prevent allocating
1214 // more variables which would collide with the addresses assigned to
1215 // dynamic variables.
1216 if (AllocateDynamicVariable)
1217 SS << format(",%u", Offset);
1218
1219 Func.addFnAttr("amdgpu-lds-size", Buffer);
1220 }
1221 }
1222 }
1223
1224 for (auto &GV : make_early_inc_range(M.globals()))
1225 if (isNotYetLoweredLDSVariable(GV)) {
1226 // probably want to remove from used lists
1228 if (GV.use_empty())
1229 GV.eraseFromParent();
1230 }
1231
1232 return Changed;
1233 }
1234
1235private:
1236 // An absolute address means a previous run already placed the variable.
1237 static bool isNotYetLoweredLDSVariable(const GlobalVariable &GV) {
1238 return isLDSVariableToLower(GV) && !GV.isAbsoluteSymbolRef();
1239 }
1240
1241 // Increase the alignment of LDS globals if necessary to maximise the chance
1242 // that we can use aligned LDS instructions to access them.
1243 bool superAlignLDSGlobals(Module &M) {
1244 const DataLayout &DL = M.getDataLayout();
1245 bool Changed = false;
1246 if (!TM.getCLOpts().super_align_lds_globals) {
1247 return Changed;
1248 }
1249
1250 for (auto &GV : M.globals()) {
1252 // Only changing alignment of LDS variables
1253 continue;
1254 }
1255 if (!GV.hasInitializer()) {
1256 // cuda/hip extern __shared__ variable, leave alignment alone
1257 continue;
1258 }
1259
1260 if (GV.isAbsoluteSymbolRef()) {
1261 // If the variable is already allocated, don't change the alignment
1262 continue;
1263 }
1264
1265 Align Alignment = AMDGPU::getAlign(DL, &GV);
1266 uint64_t GVSize = GV.getGlobalSize(DL);
1267
1268 if (GVSize > 8) {
1269 // We might want to use a b96 or b128 load/store
1270 Alignment = std::max(Alignment, Align(16));
1271 } else if (GVSize > 4) {
1272 // We might want to use a b64 load/store
1273 Alignment = std::max(Alignment, Align(8));
1274 } else if (GVSize > 2) {
1275 // We might want to use a b32 load/store
1276 Alignment = std::max(Alignment, Align(4));
1277 } else if (GVSize > 1) {
1278 // We might want to use a b16 load/store
1279 Alignment = std::max(Alignment, Align(2));
1280 }
1281
1282 if (Alignment != AMDGPU::getAlign(DL, &GV)) {
1283 Changed = true;
1284 GV.setAlignment(Alignment);
1285 }
1286 }
1287 return Changed;
1288 }
1289
1290 static LDSVariableReplacement createLDSVariableReplacement(
1291 Module &M, std::string VarName,
1292 DenseSet<GlobalVariable *> const &LDSVarsToTransform) {
1293 // Create a struct instance containing LDSVarsToTransform and map from those
1294 // variables to ConstantExprGEP
1295 // Variables may be introduced to meet alignment requirements. No aliasing
1296 // metadata is useful for these as they have no uses. Erased before return.
1297
1298 LLVMContext &Ctx = M.getContext();
1299 const DataLayout &DL = M.getDataLayout();
1300 assert(!LDSVarsToTransform.empty());
1301
1303 LayoutFields.reserve(LDSVarsToTransform.size());
1304 {
1305 // The order of fields in this struct depends on the order of
1306 // variables in the argument which varies when changing how they
1307 // are identified, leading to spurious test breakage.
1308 auto Sorted = sortByName(std::vector<GlobalVariable *>(
1309 LDSVarsToTransform.begin(), LDSVarsToTransform.end()));
1310
1311 for (GlobalVariable *GV : Sorted) {
1313 AMDGPU::getAlign(DL, GV));
1314 LayoutFields.emplace_back(F);
1315 }
1316 }
1317
1318 performOptimizedStructLayout(LayoutFields);
1319
1320 std::vector<GlobalVariable *> LocalVars;
1321 BitVector IsPaddingField;
1322 LocalVars.reserve(LDSVarsToTransform.size()); // will be at least this large
1323 IsPaddingField.reserve(LDSVarsToTransform.size());
1324 {
1325 uint64_t CurrentOffset = 0;
1326 for (auto &F : LayoutFields) {
1327 GlobalVariable *FGV =
1328 static_cast<GlobalVariable *>(const_cast<void *>(F.Id));
1329 Align DataAlign = F.Alignment;
1330
1331 uint64_t DataAlignV = DataAlign.value();
1332 if (uint64_t Rem = CurrentOffset % DataAlignV) {
1333 uint64_t Padding = DataAlignV - Rem;
1334
1335 // Append an array of padding bytes to meet alignment requested
1336 // Note (o + (a - (o % a)) ) % a == 0
1337 // (offset + Padding ) % align == 0
1338
1339 Type *ATy = ArrayType::get(Type::getInt8Ty(Ctx), Padding);
1340 LocalVars.push_back(new GlobalVariable(
1341 M, ATy, false, GlobalValue::InternalLinkage,
1343 AMDGPUAS::LOCAL_ADDRESS, false));
1344 IsPaddingField.push_back(true);
1345 CurrentOffset += Padding;
1346 }
1347
1348 LocalVars.push_back(FGV);
1349 IsPaddingField.push_back(false);
1350 CurrentOffset += F.Size;
1351 }
1352 }
1353
1354 std::vector<Type *> LocalVarTypes;
1355 LocalVarTypes.reserve(LocalVars.size());
1356 std::transform(
1357 LocalVars.cbegin(), LocalVars.cend(), std::back_inserter(LocalVarTypes),
1358 [](const GlobalVariable *V) -> Type * { return V->getValueType(); });
1359
1360 StructType *LDSTy = StructType::create(Ctx, LocalVarTypes, VarName + ".t");
1361
1362 Align StructAlign = AMDGPU::getAlign(DL, LocalVars[0]);
1363
1364 GlobalVariable *SGV = new GlobalVariable(
1365 M, LDSTy, false, GlobalValue::InternalLinkage, PoisonValue::get(LDSTy),
1367 false);
1368 SGV->setAlignment(StructAlign);
1369
1371 Type *I32 = Type::getInt32Ty(Ctx);
1372 for (size_t I = 0; I < LocalVars.size(); I++) {
1373 GlobalVariable *GV = LocalVars[I];
1374 Constant *GEPIdx[] = {ConstantInt::get(I32, 0), ConstantInt::get(I32, I)};
1376 DL, LDSTy, SGV, GEPIdx, GEPNoWrapFlags::inBounds());
1377 if (IsPaddingField[I]) {
1378 assert(GV->use_empty());
1379 GV->eraseFromParent();
1380 } else {
1381 Map[GV] = GEP;
1382 }
1383 }
1384 assert(Map.size() == LDSVarsToTransform.size());
1385 return {SGV, std::move(Map)};
1386 }
1387
1388 template <typename PredicateTy>
1389 static void replaceLDSVariablesWithStruct(
1390 Module &M, DenseSet<GlobalVariable *> const &LDSVarsToTransformArg,
1391 const LDSVariableReplacement &Replacement, PredicateTy Predicate) {
1392 LLVMContext &Ctx = M.getContext();
1393 const DataLayout &DL = M.getDataLayout();
1394
1395 // A hack... we need to insert the aliasing info in a predictable order for
1396 // lit tests. Would like to have them in a stable order already, ideally the
1397 // same order they get allocated, which might mean an ordered set container
1398 auto LDSVarsToTransform = sortByName(std::vector<GlobalVariable *>(
1399 LDSVarsToTransformArg.begin(), LDSVarsToTransformArg.end()));
1400
1401 // Create alias.scope and their lists. Each field in the new structure
1402 // does not alias with all other fields.
1403 SmallVector<MDNode *> AliasScopes;
1404 SmallVector<Metadata *> NoAliasList;
1405 const size_t NumberVars = LDSVarsToTransform.size();
1406 if (NumberVars > 1) {
1407 MDBuilder MDB(Ctx);
1408 AliasScopes.reserve(NumberVars);
1410 for (size_t I = 0; I < NumberVars; I++) {
1412 AliasScopes.push_back(Scope);
1413 }
1414 NoAliasList.append(&AliasScopes[1], AliasScopes.end());
1415 }
1416
1417 // Replace uses of ith variable with a constantexpr to the corresponding
1418 // field of the instance that will be allocated by AMDGPUMachineFunctionInfo
1419 for (size_t I = 0; I < NumberVars; I++) {
1420 GlobalVariable *GV = LDSVarsToTransform[I];
1421 Constant *GEP = Replacement.LDSVarsToConstantGEP.at(GV);
1422
1424
1425 APInt APOff(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
1426 GEP->stripAndAccumulateInBoundsConstantOffsets(DL, APOff);
1427 uint64_t Offset = APOff.getZExtValue();
1428
1429 Align A =
1430 commonAlignment(Replacement.SGV->getAlign().valueOrOne(), Offset);
1431
1432 if (I)
1433 NoAliasList[I - 1] = AliasScopes[I - 1];
1434 MDNode *NoAlias =
1435 NoAliasList.empty() ? nullptr : MDNode::get(Ctx, NoAliasList);
1436 MDNode *AliasScope =
1437 AliasScopes.empty() ? nullptr : MDNode::get(Ctx, {AliasScopes[I]});
1438
1439 refineUsesAlignmentAndAA(GEP, A, DL, AliasScope, NoAlias);
1440 }
1441 }
1442
1443 static void refineUsesAlignmentAndAA(Value *Ptr, Align A,
1444 const DataLayout &DL, MDNode *AliasScope,
1445 MDNode *NoAlias, unsigned MaxDepth = 5) {
1446 if (!MaxDepth || (A == 1 && !AliasScope))
1447 return;
1448
1449 for (User *U : Ptr->users()) {
1450 if (auto *I = dyn_cast<Instruction>(U)) {
1451 if (AliasScope && I->mayReadOrWriteMemory()) {
1452 MDNode *AS = I->getMetadata(LLVMContext::MD_alias_scope);
1453 AS = (AS ? MDNode::getMostGenericAliasScope(AS, AliasScope)
1454 : AliasScope);
1455 I->setMetadata(LLVMContext::MD_alias_scope, AS);
1456
1457 MDNode *NA = I->getMetadata(LLVMContext::MD_noalias);
1458
1459 // Scoped aliases can originate from two different domains.
1460 // First domain would be from LDS domain (created by this pass).
1461 // All entries (LDS vars) into LDS struct will have same domain.
1462
1463 // Second domain could be existing scoped aliases that are the
1464 // results of noalias params and subsequent optimizations that
1465 // may alter thesse sets.
1466
1467 // We need to be careful how we create new alias sets, and
1468 // have right scopes and domains for loads/stores of these new
1469 // LDS variables. We intersect NoAlias set if alias sets belong
1470 // to the same domain. This is the case if we have memcpy using
1471 // LDS variables. Both src and dst of memcpy would belong to
1472 // LDS struct, they donot alias.
1473 // On the other hand, if one of the domains is LDS and other is
1474 // existing domain prior to LDS, we need to have a union of all
1475 // these aliases set to preserve existing aliasing information.
1476
1477 SmallPtrSet<const MDNode *, 16> ExistingDomains, LDSDomains;
1480 auto Intersection = set_intersection(ExistingDomains, LDSDomains);
1481 if (Intersection.empty()) {
1482 NA = NA ? MDNode::concatenate(NA, NoAlias) : NoAlias;
1483 } else {
1484 NA = NA ? MDNode::intersect(NA, NoAlias) : NoAlias;
1485 }
1486 I->setMetadata(LLVMContext::MD_noalias, NA);
1487 }
1488 }
1489
1490 if (auto *LI = dyn_cast<LoadInst>(U)) {
1491 LI->setAlignment(std::max(A, LI->getAlign()));
1492 continue;
1493 }
1494 if (auto *SI = dyn_cast<StoreInst>(U)) {
1495 if (SI->getPointerOperand() == Ptr)
1496 SI->setAlignment(std::max(A, SI->getAlign()));
1497 continue;
1498 }
1499 if (auto *AI = dyn_cast<AtomicRMWInst>(U)) {
1500 // None of atomicrmw operations can work on pointers, but let's
1501 // check it anyway in case it will or we will process ConstantExpr.
1502 if (AI->getPointerOperand() == Ptr)
1503 AI->setAlignment(std::max(A, AI->getAlign()));
1504 continue;
1505 }
1506 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(U)) {
1507 if (AI->getPointerOperand() == Ptr)
1508 AI->setAlignment(std::max(A, AI->getAlign()));
1509 continue;
1510 }
1511 if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
1512 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
1513 APInt Off(BitWidth, 0);
1514 if (GEP->getPointerOperand() == Ptr) {
1515 Align GA;
1516 if (GEP->accumulateConstantOffset(DL, Off))
1517 GA = commonAlignment(A, Off.getLimitedValue());
1518 refineUsesAlignmentAndAA(GEP, GA, DL, AliasScope, NoAlias,
1519 MaxDepth - 1);
1520 }
1521 continue;
1522 }
1523 if (auto *I = dyn_cast<Instruction>(U)) {
1524 if (I->getOpcode() == Instruction::BitCast ||
1525 I->getOpcode() == Instruction::AddrSpaceCast)
1526 refineUsesAlignmentAndAA(I, A, DL, AliasScope, NoAlias, MaxDepth - 1);
1527 }
1528 }
1529 }
1530};
1531
1532class AMDGPULowerModuleLDSLegacy : public ModulePass {
1533public:
1534 const AMDGPUTargetMachine *TM;
1535 static char ID;
1536
1537 AMDGPULowerModuleLDSLegacy(const AMDGPUTargetMachine *TM = nullptr)
1538 : ModulePass(ID), TM(TM) {}
1539
1540 void getAnalysisUsage(AnalysisUsage &AU) const override {
1541 if (!TM)
1543 }
1544
1545 bool runOnModule(Module &M) override {
1546 if (!TM) {
1547 auto &TPC = getAnalysis<TargetPassConfig>();
1548 TM = &TPC.getTM<AMDGPUTargetMachine>();
1549 }
1550
1551 return AMDGPULowerModuleLDS(*TM).runOnModule(M);
1552 }
1553};
1554
1555} // namespace
1556char AMDGPULowerModuleLDSLegacy::ID = 0;
1557
1558char &llvm::AMDGPULowerModuleLDSLegacyPassID = AMDGPULowerModuleLDSLegacy::ID;
1559
1560INITIALIZE_PASS_BEGIN(AMDGPULowerModuleLDSLegacy, DEBUG_TYPE,
1561 "Lower uses of LDS variables from non-kernel functions",
1562 false, false)
1564INITIALIZE_PASS_END(AMDGPULowerModuleLDSLegacy, DEBUG_TYPE,
1565 "Lower uses of LDS variables from non-kernel functions",
1567
1568ModulePass *
1570 return new AMDGPULowerModuleLDSLegacy(TM);
1571}
1572
1575 return AMDGPULowerModuleLDS(TM).runOnModule(M) ? PreservedAnalyses::none()
1577}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t 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 ...
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.
const AMDGPUOptions & getCLOpts() const
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
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:364
void push_back(bool Val)
Definition BitVector.h:506
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:548
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH 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:1477
This is an important base class in LLVM.
Definition Constant.h:44
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
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
static GEPNoWrapFlags inBounds()
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:2987
bool runOnModule(Module &) override
ImmutablePasses are never run.
Definition Pass.h:300
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
MDNode * createAnonymousAliasScope(MDNode *Domain, StringRef Name=StringRef())
Return metadata appropriate for an alias scope root node.
Definition MDBuilder.h:195
LLVM_ABI MDNode * createAnonymousAliasScopeDomain(StringRef Description=StringRef(), bool DisjointScopes=false)
Return metadata appropriate for an alias scope domain node, described by Description,...
Metadata node.
Definition Metadata.h:1081
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:1579
static LLVM_ABI MDNode * intersect(MDNode *A, MDNode *B)
iterator find(const KeyT &Key)
Definition MapVector.h:157
iterator end()
Definition MapVector.h:70
bool empty() const
Definition MapVector.h:80
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:127
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:253
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:1797
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
static LLVM_ABI void collectScopedDomains(const MDNode *NoAlias, SmallPtrSetImpl< const MDNode * > &Domains, bool DisjointOnly=false)
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:512
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:556
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:314
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
bool erase(const ValueT &V)
Definition DenseSet.h:98
size_type size() const
Definition DenseSet.h:85
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:188
A raw_ostream that writes to an std::string.
@ 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.
MapVector< 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.
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:649
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:1762
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:1652
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
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:206
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:193
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:82