xref: /llvm-project/llvm/lib/Target/AMDGPU/AMDGPULowerModuleLDSPass.cpp (revision 6043d4dfec1e47b6e314f3643f576ab808f246dc)
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 "Utils/AMDGPUBaseInfo.h"
181 #include "Utils/AMDGPUMemoryUtils.h"
182 #include "llvm/ADT/BitVector.h"
183 #include "llvm/ADT/DenseMap.h"
184 #include "llvm/ADT/DenseSet.h"
185 #include "llvm/ADT/STLExtras.h"
186 #include "llvm/ADT/SetOperations.h"
187 #include "llvm/ADT/SetVector.h"
188 #include "llvm/Analysis/CallGraph.h"
189 #include "llvm/IR/Constants.h"
190 #include "llvm/IR/DerivedTypes.h"
191 #include "llvm/IR/IRBuilder.h"
192 #include "llvm/IR/InlineAsm.h"
193 #include "llvm/IR/Instructions.h"
194 #include "llvm/IR/IntrinsicsAMDGPU.h"
195 #include "llvm/IR/MDBuilder.h"
196 #include "llvm/IR/ReplaceConstant.h"
197 #include "llvm/InitializePasses.h"
198 #include "llvm/Pass.h"
199 #include "llvm/Support/CommandLine.h"
200 #include "llvm/Support/Debug.h"
201 #include "llvm/Support/Format.h"
202 #include "llvm/Support/OptimizedStructLayout.h"
203 #include "llvm/Support/raw_ostream.h"
204 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
205 #include "llvm/Transforms/Utils/ModuleUtils.h"
206 
207 #include <tuple>
208 #include <vector>
209 
210 #include <cstdio>
211 
212 #define DEBUG_TYPE "amdgpu-lower-module-lds"
213 
214 using namespace llvm;
215 
216 namespace {
217 
218 cl::opt<bool> SuperAlignLDSGlobals(
219     "amdgpu-super-align-lds-globals",
220     cl::desc("Increase alignment of LDS if it is not on align boundary"),
221     cl::init(true), cl::Hidden);
222 
223 enum class LoweringKind { module, table, kernel, hybrid };
224 cl::opt<LoweringKind> LoweringKindLoc(
225     "amdgpu-lower-module-lds-strategy",
226     cl::desc("Specify lowering strategy for function LDS access:"), cl::Hidden,
227     cl::init(LoweringKind::hybrid),
228     cl::values(
229         clEnumValN(LoweringKind::table, "table", "Lower via table lookup"),
230         clEnumValN(LoweringKind::module, "module", "Lower via module struct"),
231         clEnumValN(
232             LoweringKind::kernel, "kernel",
233             "Lower variables reachable from one kernel, otherwise abort"),
234         clEnumValN(LoweringKind::hybrid, "hybrid",
235                    "Lower via mixture of above strategies")));
236 
237 bool isKernelLDS(const Function *F) {
238   // Some weirdness here. AMDGPU::isKernelCC does not call into
239   // AMDGPU::isKernel with the calling conv, it instead calls into
240   // isModuleEntryFunction which returns true for more calling conventions
241   // than AMDGPU::isKernel does. There's a FIXME on AMDGPU::isKernel.
242   // There's also a test that checks that the LDS lowering does not hit on
243   // a graphics shader, denoted amdgpu_ps, so stay with the limited case.
244   // Putting LDS in the name of the function to draw attention to this.
245   return AMDGPU::isKernel(F->getCallingConv());
246 }
247 
248 template <typename T> std::vector<T> sortByName(std::vector<T> &&V) {
249   llvm::sort(V.begin(), V.end(), [](const auto *L, const auto *R) {
250     return L->getName() < R->getName();
251   });
252   return {std::move(V)};
253 }
254 
255 class AMDGPULowerModuleLDS : public ModulePass {
256 
257   static void
258   removeLocalVarsFromUsedLists(Module &M,
259                                const DenseSet<GlobalVariable *> &LocalVars) {
260     // The verifier rejects used lists containing an inttoptr of a constant
261     // so remove the variables from these lists before replaceAllUsesWith
262     SmallPtrSet<Constant *, 8> LocalVarsSet;
263     for (GlobalVariable *LocalVar : LocalVars)
264       LocalVarsSet.insert(cast<Constant>(LocalVar->stripPointerCasts()));
265 
266     removeFromUsedLists(
267         M, [&LocalVarsSet](Constant *C) { return LocalVarsSet.count(C); });
268 
269     for (GlobalVariable *LocalVar : LocalVars)
270       LocalVar->removeDeadConstantUsers();
271   }
272 
273   static void markUsedByKernel(IRBuilder<> &Builder, Function *Func,
274                                GlobalVariable *SGV) {
275     // The llvm.amdgcn.module.lds instance is implicitly used by all kernels
276     // that might call a function which accesses a field within it. This is
277     // presently approximated to 'all kernels' if there are any such functions
278     // in the module. This implicit use is redefined as an explicit use here so
279     // that later passes, specifically PromoteAlloca, account for the required
280     // memory without any knowledge of this transform.
281 
282     // An operand bundle on llvm.donothing works because the call instruction
283     // survives until after the last pass that needs to account for LDS. It is
284     // better than inline asm as the latter survives until the end of codegen. A
285     // totally robust solution would be a function with the same semantics as
286     // llvm.donothing that takes a pointer to the instance and is lowered to a
287     // no-op after LDS is allocated, but that is not presently necessary.
288 
289     // This intrinsic is eliminated shortly before instruction selection. It
290     // does not suffice to indicate to ISel that a given global which is not
291     // immediately used by the kernel must still be allocated by it. An
292     // equivalent target specific intrinsic which lasts until immediately after
293     // codegen would suffice for that, but one would still need to ensure that
294     // the variables are allocated in the anticpated order.
295 
296     LLVMContext &Ctx = Func->getContext();
297 
298     Builder.SetInsertPoint(Func->getEntryBlock().getFirstNonPHI());
299 
300     FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx), {});
301 
302     Function *Decl =
303         Intrinsic::getDeclaration(Func->getParent(), Intrinsic::donothing, {});
304 
305     Value *UseInstance[1] = {Builder.CreateInBoundsGEP(
306         SGV->getValueType(), SGV, ConstantInt::get(Type::getInt32Ty(Ctx), 0))};
307 
308     Builder.CreateCall(FTy, Decl, {},
309                        {OperandBundleDefT<Value *>("ExplicitUse", UseInstance)},
310                        "");
311   }
312 
313   static bool eliminateConstantExprUsesOfLDSFromAllInstructions(Module &M) {
314     // Constants are uniqued within LLVM. A ConstantExpr referring to a LDS
315     // global may have uses from multiple different functions as a result.
316     // This pass specialises LDS variables with respect to the kernel that
317     // allocates them.
318 
319     // This is semantically equivalent to (the unimplemented as slow):
320     // for (auto &F : M.functions())
321     //   for (auto &BB : F)
322     //     for (auto &I : BB)
323     //       for (Use &Op : I.operands())
324     //         if (constantExprUsesLDS(Op))
325     //           replaceConstantExprInFunction(I, Op);
326 
327     SmallVector<Constant *> LDSGlobals;
328     for (auto &GV : M.globals())
329       if (AMDGPU::isLDSVariableToLower(GV))
330         LDSGlobals.push_back(&GV);
331 
332     return convertUsersOfConstantsToInstructions(LDSGlobals);
333   }
334 
335 public:
336   static char ID;
337 
338   AMDGPULowerModuleLDS() : ModulePass(ID) {
339     initializeAMDGPULowerModuleLDSPass(*PassRegistry::getPassRegistry());
340   }
341 
342   using FunctionVariableMap = DenseMap<Function *, DenseSet<GlobalVariable *>>;
343 
344   using VariableFunctionMap = DenseMap<GlobalVariable *, DenseSet<Function *>>;
345 
346   static void getUsesOfLDSByFunction(CallGraph const &CG, Module &M,
347                                      FunctionVariableMap &kernels,
348                                      FunctionVariableMap &functions) {
349 
350     // Get uses from the current function, excluding uses by called functions
351     // Two output variables to avoid walking the globals list twice
352     for (auto &GV : M.globals()) {
353       if (!AMDGPU::isLDSVariableToLower(GV)) {
354         continue;
355       }
356 
357       if (GV.isAbsoluteSymbolRef()) {
358         report_fatal_error(
359             "LDS variables with absolute addresses are unimplemented.");
360       }
361 
362       for (User *V : GV.users()) {
363         if (auto *I = dyn_cast<Instruction>(V)) {
364           Function *F = I->getFunction();
365           if (isKernelLDS(F)) {
366             kernels[F].insert(&GV);
367           } else {
368             functions[F].insert(&GV);
369           }
370         }
371       }
372     }
373   }
374 
375   struct LDSUsesInfoTy {
376     FunctionVariableMap direct_access;
377     FunctionVariableMap indirect_access;
378   };
379 
380   static LDSUsesInfoTy getTransitiveUsesOfLDS(CallGraph const &CG, Module &M) {
381 
382     FunctionVariableMap direct_map_kernel;
383     FunctionVariableMap direct_map_function;
384     getUsesOfLDSByFunction(CG, M, direct_map_kernel, direct_map_function);
385 
386     // Collect variables that are used by functions whose address has escaped
387     DenseSet<GlobalVariable *> VariablesReachableThroughFunctionPointer;
388     for (Function &F : M.functions()) {
389       if (!isKernelLDS(&F))
390         if (F.hasAddressTaken(nullptr,
391                               /* IgnoreCallbackUses */ false,
392                               /* IgnoreAssumeLikeCalls */ false,
393                               /* IgnoreLLVMUsed */ true,
394                               /* IgnoreArcAttachedCall */ false)) {
395           set_union(VariablesReachableThroughFunctionPointer,
396                     direct_map_function[&F]);
397         }
398     }
399 
400     auto functionMakesUnknownCall = [&](const Function *F) -> bool {
401       assert(!F->isDeclaration());
402       for (const CallGraphNode::CallRecord &R : *CG[F]) {
403         if (!R.second->getFunction()) {
404           return true;
405         }
406       }
407       return false;
408     };
409 
410     // Work out which variables are reachable through function calls
411     FunctionVariableMap transitive_map_function = direct_map_function;
412 
413     // If the function makes any unknown call, assume the worst case that it can
414     // access all variables accessed by functions whose address escaped
415     for (Function &F : M.functions()) {
416       if (!F.isDeclaration() && functionMakesUnknownCall(&F)) {
417         if (!isKernelLDS(&F)) {
418           set_union(transitive_map_function[&F],
419                     VariablesReachableThroughFunctionPointer);
420         }
421       }
422     }
423 
424     // Direct implementation of collecting all variables reachable from each
425     // function
426     for (Function &Func : M.functions()) {
427       if (Func.isDeclaration() || isKernelLDS(&Func))
428         continue;
429 
430       DenseSet<Function *> seen; // catches cycles
431       SmallVector<Function *, 4> wip{&Func};
432 
433       while (!wip.empty()) {
434         Function *F = wip.pop_back_val();
435 
436         // Can accelerate this by referring to transitive map for functions that
437         // have already been computed, with more care than this
438         set_union(transitive_map_function[&Func], direct_map_function[F]);
439 
440         for (const CallGraphNode::CallRecord &R : *CG[F]) {
441           Function *ith = R.second->getFunction();
442           if (ith) {
443             if (!seen.contains(ith)) {
444               seen.insert(ith);
445               wip.push_back(ith);
446             }
447           }
448         }
449       }
450     }
451 
452     // direct_map_kernel lists which variables are used by the kernel
453     // find the variables which are used through a function call
454     FunctionVariableMap indirect_map_kernel;
455 
456     for (Function &Func : M.functions()) {
457       if (Func.isDeclaration() || !isKernelLDS(&Func))
458         continue;
459 
460       for (const CallGraphNode::CallRecord &R : *CG[&Func]) {
461         Function *ith = R.second->getFunction();
462         if (ith) {
463           set_union(indirect_map_kernel[&Func], transitive_map_function[ith]);
464         } else {
465           set_union(indirect_map_kernel[&Func],
466                     VariablesReachableThroughFunctionPointer);
467         }
468       }
469     }
470 
471     return {std::move(direct_map_kernel), std::move(indirect_map_kernel)};
472   }
473 
474   struct LDSVariableReplacement {
475     GlobalVariable *SGV = nullptr;
476     DenseMap<GlobalVariable *, Constant *> LDSVarsToConstantGEP;
477   };
478 
479   // remap from lds global to a constantexpr gep to where it has been moved to
480   // for each kernel
481   // an array with an element for each kernel containing where the corresponding
482   // variable was remapped to
483 
484   static Constant *getAddressesOfVariablesInKernel(
485       LLVMContext &Ctx, ArrayRef<GlobalVariable *> Variables,
486       const DenseMap<GlobalVariable *, Constant *> &LDSVarsToConstantGEP) {
487     // Create a ConstantArray containing the address of each Variable within the
488     // kernel corresponding to LDSVarsToConstantGEP, or poison if that kernel
489     // does not allocate it
490     // TODO: Drop the ptrtoint conversion
491 
492     Type *I32 = Type::getInt32Ty(Ctx);
493 
494     ArrayType *KernelOffsetsType = ArrayType::get(I32, Variables.size());
495 
496     SmallVector<Constant *> Elements;
497     for (size_t i = 0; i < Variables.size(); i++) {
498       GlobalVariable *GV = Variables[i];
499       auto ConstantGepIt = LDSVarsToConstantGEP.find(GV);
500       if (ConstantGepIt != LDSVarsToConstantGEP.end()) {
501         auto elt = ConstantExpr::getPtrToInt(ConstantGepIt->second, I32);
502         Elements.push_back(elt);
503       } else {
504         Elements.push_back(PoisonValue::get(I32));
505       }
506     }
507     return ConstantArray::get(KernelOffsetsType, Elements);
508   }
509 
510   static GlobalVariable *buildLookupTable(
511       Module &M, ArrayRef<GlobalVariable *> Variables,
512       ArrayRef<Function *> kernels,
513       DenseMap<Function *, LDSVariableReplacement> &KernelToReplacement) {
514     if (Variables.empty()) {
515       return nullptr;
516     }
517     LLVMContext &Ctx = M.getContext();
518 
519     const size_t NumberVariables = Variables.size();
520     const size_t NumberKernels = kernels.size();
521 
522     ArrayType *KernelOffsetsType =
523         ArrayType::get(Type::getInt32Ty(Ctx), NumberVariables);
524 
525     ArrayType *AllKernelsOffsetsType =
526         ArrayType::get(KernelOffsetsType, NumberKernels);
527 
528     Constant *Missing = PoisonValue::get(KernelOffsetsType);
529     std::vector<Constant *> overallConstantExprElts(NumberKernels);
530     for (size_t i = 0; i < NumberKernels; i++) {
531       auto Replacement = KernelToReplacement.find(kernels[i]);
532       overallConstantExprElts[i] =
533           (Replacement == KernelToReplacement.end())
534               ? Missing
535               : getAddressesOfVariablesInKernel(
536                     Ctx, Variables, Replacement->second.LDSVarsToConstantGEP);
537     }
538 
539     Constant *init =
540         ConstantArray::get(AllKernelsOffsetsType, overallConstantExprElts);
541 
542     return new GlobalVariable(
543         M, AllKernelsOffsetsType, true, GlobalValue::InternalLinkage, init,
544         "llvm.amdgcn.lds.offset.table", nullptr, GlobalValue::NotThreadLocal,
545         AMDGPUAS::CONSTANT_ADDRESS);
546   }
547 
548   void replaceUseWithTableLookup(Module &M, IRBuilder<> &Builder,
549                                  GlobalVariable *LookupTable,
550                                  GlobalVariable *GV, Use &U,
551                                  Value *OptionalIndex) {
552     // Table is a constant array of the same length as OrderedKernels
553     LLVMContext &Ctx = M.getContext();
554     Type *I32 = Type::getInt32Ty(Ctx);
555     auto *I = cast<Instruction>(U.getUser());
556 
557     Value *tableKernelIndex = getTableLookupKernelIndex(M, I->getFunction());
558 
559     if (auto *Phi = dyn_cast<PHINode>(I)) {
560       BasicBlock *BB = Phi->getIncomingBlock(U);
561       Builder.SetInsertPoint(&(*(BB->getFirstInsertionPt())));
562     } else {
563       Builder.SetInsertPoint(I);
564     }
565 
566     SmallVector<Value *, 3> GEPIdx = {
567         ConstantInt::get(I32, 0),
568         tableKernelIndex,
569     };
570     if (OptionalIndex)
571       GEPIdx.push_back(OptionalIndex);
572 
573     Value *Address = Builder.CreateInBoundsGEP(
574         LookupTable->getValueType(), LookupTable, GEPIdx, GV->getName());
575 
576     Value *loaded = Builder.CreateLoad(I32, Address);
577 
578     Value *replacement =
579         Builder.CreateIntToPtr(loaded, GV->getType(), GV->getName());
580 
581     U.set(replacement);
582   }
583 
584   void replaceUsesInInstructionsWithTableLookup(
585       Module &M, ArrayRef<GlobalVariable *> ModuleScopeVariables,
586       GlobalVariable *LookupTable) {
587 
588     LLVMContext &Ctx = M.getContext();
589     IRBuilder<> Builder(Ctx);
590     Type *I32 = Type::getInt32Ty(Ctx);
591 
592     for (size_t Index = 0; Index < ModuleScopeVariables.size(); Index++) {
593       auto *GV = ModuleScopeVariables[Index];
594 
595       for (Use &U : make_early_inc_range(GV->uses())) {
596         auto *I = dyn_cast<Instruction>(U.getUser());
597         if (!I)
598           continue;
599 
600         replaceUseWithTableLookup(M, Builder, LookupTable, GV, U,
601                                   ConstantInt::get(I32, Index));
602       }
603     }
604   }
605 
606   static DenseSet<Function *> kernelsThatIndirectlyAccessAnyOfPassedVariables(
607       Module &M, LDSUsesInfoTy &LDSUsesInfo,
608       DenseSet<GlobalVariable *> const &VariableSet) {
609 
610     DenseSet<Function *> KernelSet;
611 
612     if (VariableSet.empty())
613       return KernelSet;
614 
615     for (Function &Func : M.functions()) {
616       if (Func.isDeclaration() || !isKernelLDS(&Func))
617         continue;
618       for (GlobalVariable *GV : LDSUsesInfo.indirect_access[&Func]) {
619         if (VariableSet.contains(GV)) {
620           KernelSet.insert(&Func);
621           break;
622         }
623       }
624     }
625 
626     return KernelSet;
627   }
628 
629   static GlobalVariable *
630   chooseBestVariableForModuleStrategy(const DataLayout &DL,
631                                       VariableFunctionMap &LDSVars) {
632     // Find the global variable with the most indirect uses from kernels
633 
634     struct CandidateTy {
635       GlobalVariable *GV = nullptr;
636       size_t UserCount = 0;
637       size_t Size = 0;
638 
639       CandidateTy() = default;
640 
641       CandidateTy(GlobalVariable *GV, uint64_t UserCount, uint64_t AllocSize)
642           : GV(GV), UserCount(UserCount), Size(AllocSize) {}
643 
644       bool operator<(const CandidateTy &Other) const {
645         // Fewer users makes module scope variable less attractive
646         if (UserCount < Other.UserCount) {
647           return true;
648         }
649         if (UserCount > Other.UserCount) {
650           return false;
651         }
652 
653         // Bigger makes module scope variable less attractive
654         if (Size < Other.Size) {
655           return false;
656         }
657 
658         if (Size > Other.Size) {
659           return true;
660         }
661 
662         // Arbitrary but consistent
663         return GV->getName() < Other.GV->getName();
664       }
665     };
666 
667     CandidateTy MostUsed;
668 
669     for (auto &K : LDSVars) {
670       GlobalVariable *GV = K.first;
671       if (K.second.size() <= 1) {
672         // A variable reachable by only one kernel is best lowered with kernel
673         // strategy
674         continue;
675       }
676       CandidateTy Candidate(
677           GV, K.second.size(),
678           DL.getTypeAllocSize(GV->getValueType()).getFixedValue());
679       if (MostUsed < Candidate)
680         MostUsed = Candidate;
681     }
682 
683     return MostUsed.GV;
684   }
685 
686   static void recordLDSAbsoluteAddress(Module *M, GlobalVariable *GV,
687                                        uint32_t Address) {
688     // Write the specified address into metadata where it can be retrieved by
689     // the assembler. Format is a half open range, [Address Address+1)
690     LLVMContext &Ctx = M->getContext();
691     auto *IntTy =
692         M->getDataLayout().getIntPtrType(Ctx, AMDGPUAS::LOCAL_ADDRESS);
693     auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntTy, Address));
694     auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntTy, Address + 1));
695     GV->setMetadata(LLVMContext::MD_absolute_symbol,
696                     MDNode::get(Ctx, {MinC, MaxC}));
697   }
698 
699   DenseMap<Function *, Value *> tableKernelIndexCache;
700   Value *getTableLookupKernelIndex(Module &M, Function *F) {
701     // Accesses from a function use the amdgcn_lds_kernel_id intrinsic which
702     // lowers to a read from a live in register. Emit it once in the entry
703     // block to spare deduplicating it later.
704     if (tableKernelIndexCache.count(F) == 0) {
705       LLVMContext &Ctx = M.getContext();
706       IRBuilder<> Builder(Ctx);
707       FunctionType *FTy = FunctionType::get(Type::getInt32Ty(Ctx), {});
708       Function *Decl =
709           Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_lds_kernel_id, {});
710 
711       BasicBlock::iterator it =
712           F->getEntryBlock().getFirstNonPHIOrDbgOrAlloca();
713       Instruction &i = *it;
714       Builder.SetInsertPoint(&i);
715 
716       tableKernelIndexCache[F] = Builder.CreateCall(FTy, Decl, {});
717     }
718 
719     return tableKernelIndexCache[F];
720   }
721 
722   static std::vector<Function *> assignLDSKernelIDToEachKernel(
723       Module *M, DenseSet<Function *> const &KernelsThatAllocateTableLDS,
724       DenseSet<Function *> const &KernelsThatIndirectlyAllocateDynamicLDS) {
725     // Associate kernels in the set with an arbirary but reproducible order and
726     // annotate them with that order in metadata. This metadata is recognised by
727     // the backend and lowered to a SGPR which can be read from using
728     // amdgcn_lds_kernel_id.
729 
730     std::vector<Function *> OrderedKernels;
731     if (!KernelsThatAllocateTableLDS.empty() ||
732         !KernelsThatIndirectlyAllocateDynamicLDS.empty()) {
733 
734       for (Function &Func : M->functions()) {
735         if (Func.isDeclaration())
736           continue;
737         if (!isKernelLDS(&Func))
738           continue;
739 
740         if (KernelsThatAllocateTableLDS.contains(&Func) ||
741             KernelsThatIndirectlyAllocateDynamicLDS.contains(&Func)) {
742           assert(Func.hasName()); // else fatal error earlier
743           OrderedKernels.push_back(&Func);
744         }
745       }
746 
747       // Put them in an arbitrary but reproducible order
748       OrderedKernels = sortByName(std::move(OrderedKernels));
749 
750       // Annotate the kernels with their order in this vector
751       LLVMContext &Ctx = M->getContext();
752       IRBuilder<> Builder(Ctx);
753 
754       if (OrderedKernels.size() > UINT32_MAX) {
755         // 32 bit keeps it in one SGPR. > 2**32 kernels won't fit on the GPU
756         report_fatal_error("Unimplemented LDS lowering for > 2**32 kernels");
757       }
758 
759       for (size_t i = 0; i < OrderedKernels.size(); i++) {
760         Metadata *AttrMDArgs[1] = {
761             ConstantAsMetadata::get(Builder.getInt32(i)),
762         };
763         OrderedKernels[i]->setMetadata("llvm.amdgcn.lds.kernel.id",
764                                        MDNode::get(Ctx, AttrMDArgs));
765       }
766     }
767     return OrderedKernels;
768   }
769 
770   static void partitionVariablesIntoIndirectStrategies(
771       Module &M, LDSUsesInfoTy const &LDSUsesInfo,
772       VariableFunctionMap &LDSToKernelsThatNeedToAccessItIndirectly,
773       DenseSet<GlobalVariable *> &ModuleScopeVariables,
774       DenseSet<GlobalVariable *> &TableLookupVariables,
775       DenseSet<GlobalVariable *> &KernelAccessVariables,
776       DenseSet<GlobalVariable *> &DynamicVariables) {
777 
778     GlobalVariable *HybridModuleRoot =
779         LoweringKindLoc != LoweringKind::hybrid
780             ? nullptr
781             : chooseBestVariableForModuleStrategy(
782                   M.getDataLayout(), LDSToKernelsThatNeedToAccessItIndirectly);
783 
784     DenseSet<Function *> const EmptySet;
785     DenseSet<Function *> const &HybridModuleRootKernels =
786         HybridModuleRoot
787             ? LDSToKernelsThatNeedToAccessItIndirectly[HybridModuleRoot]
788             : EmptySet;
789 
790     for (auto &K : LDSToKernelsThatNeedToAccessItIndirectly) {
791       // Each iteration of this loop assigns exactly one global variable to
792       // exactly one of the implementation strategies.
793 
794       GlobalVariable *GV = K.first;
795       assert(AMDGPU::isLDSVariableToLower(*GV));
796       assert(K.second.size() != 0);
797 
798       if (AMDGPU::isDynamicLDS(*GV)) {
799         DynamicVariables.insert(GV);
800         continue;
801       }
802 
803       switch (LoweringKindLoc) {
804       case LoweringKind::module:
805         ModuleScopeVariables.insert(GV);
806         break;
807 
808       case LoweringKind::table:
809         TableLookupVariables.insert(GV);
810         break;
811 
812       case LoweringKind::kernel:
813         if (K.second.size() == 1) {
814           KernelAccessVariables.insert(GV);
815         } else {
816           report_fatal_error(
817               "cannot lower LDS '" + GV->getName() +
818               "' to kernel access as it is reachable from multiple kernels");
819         }
820         break;
821 
822       case LoweringKind::hybrid: {
823         if (GV == HybridModuleRoot) {
824           assert(K.second.size() != 1);
825           ModuleScopeVariables.insert(GV);
826         } else if (K.second.size() == 1) {
827           KernelAccessVariables.insert(GV);
828         } else if (set_is_subset(K.second, HybridModuleRootKernels)) {
829           ModuleScopeVariables.insert(GV);
830         } else {
831           TableLookupVariables.insert(GV);
832         }
833         break;
834       }
835       }
836     }
837 
838     // All LDS variables accessed indirectly have now been partitioned into
839     // the distinct lowering strategies.
840     assert(ModuleScopeVariables.size() + TableLookupVariables.size() +
841                KernelAccessVariables.size() + DynamicVariables.size() ==
842            LDSToKernelsThatNeedToAccessItIndirectly.size());
843   }
844 
845   static GlobalVariable *lowerModuleScopeStructVariables(
846       Module &M, DenseSet<GlobalVariable *> const &ModuleScopeVariables,
847       DenseSet<Function *> const &KernelsThatAllocateModuleLDS) {
848     // Create a struct to hold the ModuleScopeVariables
849     // Replace all uses of those variables from non-kernel functions with the
850     // new struct instance Replace only the uses from kernel functions that will
851     // allocate this instance. That is a space optimisation - kernels that use a
852     // subset of the module scope struct and do not need to allocate it for
853     // indirect calls will only allocate the subset they use (they do so as part
854     // of the per-kernel lowering).
855     if (ModuleScopeVariables.empty()) {
856       return nullptr;
857     }
858 
859     LLVMContext &Ctx = M.getContext();
860 
861     LDSVariableReplacement ModuleScopeReplacement =
862         createLDSVariableReplacement(M, "llvm.amdgcn.module.lds",
863                                      ModuleScopeVariables);
864 
865     appendToCompilerUsed(M, {static_cast<GlobalValue *>(
866                                 ConstantExpr::getPointerBitCastOrAddrSpaceCast(
867                                     cast<Constant>(ModuleScopeReplacement.SGV),
868                                     Type::getInt8PtrTy(Ctx)))});
869 
870     // module.lds will be allocated at zero in any kernel that allocates it
871     recordLDSAbsoluteAddress(&M, ModuleScopeReplacement.SGV, 0);
872 
873     // historic
874     removeLocalVarsFromUsedLists(M, ModuleScopeVariables);
875 
876     // Replace all uses of module scope variable from non-kernel functions
877     replaceLDSVariablesWithStruct(
878         M, ModuleScopeVariables, ModuleScopeReplacement, [&](Use &U) {
879           Instruction *I = dyn_cast<Instruction>(U.getUser());
880           if (!I) {
881             return false;
882           }
883           Function *F = I->getFunction();
884           return !isKernelLDS(F);
885         });
886 
887     // Replace uses of module scope variable from kernel functions that
888     // allocate the module scope variable, otherwise leave them unchanged
889     // Record on each kernel whether the module scope global is used by it
890 
891     IRBuilder<> Builder(Ctx);
892 
893     for (Function &Func : M.functions()) {
894       if (Func.isDeclaration() || !isKernelLDS(&Func))
895         continue;
896 
897       if (KernelsThatAllocateModuleLDS.contains(&Func)) {
898         replaceLDSVariablesWithStruct(
899             M, ModuleScopeVariables, ModuleScopeReplacement, [&](Use &U) {
900               Instruction *I = dyn_cast<Instruction>(U.getUser());
901               if (!I) {
902                 return false;
903               }
904               Function *F = I->getFunction();
905               return F == &Func;
906             });
907 
908         markUsedByKernel(Builder, &Func, ModuleScopeReplacement.SGV);
909       }
910     }
911 
912     return ModuleScopeReplacement.SGV;
913   }
914 
915   static DenseMap<Function *, LDSVariableReplacement>
916   lowerKernelScopeStructVariables(
917       Module &M, LDSUsesInfoTy &LDSUsesInfo,
918       DenseSet<GlobalVariable *> const &ModuleScopeVariables,
919       DenseSet<Function *> const &KernelsThatAllocateModuleLDS,
920       GlobalVariable *MaybeModuleScopeStruct) {
921 
922     // Create a struct for each kernel for the non-module-scope variables.
923 
924     IRBuilder<> Builder(M.getContext());
925     DenseMap<Function *, LDSVariableReplacement> KernelToReplacement;
926     for (Function &Func : M.functions()) {
927       if (Func.isDeclaration() || !isKernelLDS(&Func))
928         continue;
929 
930       DenseSet<GlobalVariable *> KernelUsedVariables;
931       // Allocating variables that are used directly in this struct to get
932       // alignment aware allocation and predictable frame size.
933       for (auto &v : LDSUsesInfo.direct_access[&Func]) {
934         if (!AMDGPU::isDynamicLDS(*v)) {
935           KernelUsedVariables.insert(v);
936         }
937       }
938 
939       // Allocating variables that are accessed indirectly so that a lookup of
940       // this struct instance can find them from nested functions.
941       for (auto &v : LDSUsesInfo.indirect_access[&Func]) {
942         if (!AMDGPU::isDynamicLDS(*v)) {
943           KernelUsedVariables.insert(v);
944         }
945       }
946 
947       // Variables allocated in module lds must all resolve to that struct,
948       // not to the per-kernel instance.
949       if (KernelsThatAllocateModuleLDS.contains(&Func)) {
950         for (GlobalVariable *v : ModuleScopeVariables) {
951           KernelUsedVariables.erase(v);
952         }
953       }
954 
955       if (KernelUsedVariables.empty()) {
956         // Either used no LDS, or the LDS it used was all in the module struct
957         // or dynamically sized
958         continue;
959       }
960 
961       // The association between kernel function and LDS struct is done by
962       // symbol name, which only works if the function in question has a
963       // name This is not expected to be a problem in practice as kernels
964       // are called by name making anonymous ones (which are named by the
965       // backend) difficult to use. This does mean that llvm test cases need
966       // to name the kernels.
967       if (!Func.hasName()) {
968         report_fatal_error("Anonymous kernels cannot use LDS variables");
969       }
970 
971       std::string VarName =
972           (Twine("llvm.amdgcn.kernel.") + Func.getName() + ".lds").str();
973 
974       auto Replacement =
975           createLDSVariableReplacement(M, VarName, KernelUsedVariables);
976 
977       // If any indirect uses, create a direct use to ensure allocation
978       // TODO: Simpler to unconditionally mark used but that regresses
979       // codegen in test/CodeGen/AMDGPU/noclobber-barrier.ll
980       auto Accesses = LDSUsesInfo.indirect_access.find(&Func);
981       if ((Accesses != LDSUsesInfo.indirect_access.end()) &&
982           !Accesses->second.empty())
983         markUsedByKernel(Builder, &Func, Replacement.SGV);
984 
985       // remove preserves existing codegen
986       removeLocalVarsFromUsedLists(M, KernelUsedVariables);
987       KernelToReplacement[&Func] = Replacement;
988 
989       // Rewrite uses within kernel to the new struct
990       replaceLDSVariablesWithStruct(
991           M, KernelUsedVariables, Replacement, [&Func](Use &U) {
992             Instruction *I = dyn_cast<Instruction>(U.getUser());
993             return I && I->getFunction() == &Func;
994           });
995     }
996     return KernelToReplacement;
997   }
998 
999   static GlobalVariable *
1000   buildRepresentativeDynamicLDSInstance(Module &M, LDSUsesInfoTy &LDSUsesInfo,
1001                                         Function *func) {
1002     // Create a dynamic lds variable with a name associated with the passed
1003     // function that has the maximum alignment of any dynamic lds variable
1004     // reachable from this kernel. Dynamic LDS is allocated after the static LDS
1005     // allocation, possibly after alignment padding. The representative variable
1006     // created here has the maximum alignment of any other dynamic variable
1007     // reachable by that kernel. All dynamic LDS variables are allocated at the
1008     // same address in each kernel in order to provide the documented aliasing
1009     // semantics. Setting the alignment here allows this IR pass to accurately
1010     // predict the exact constant at which it will be allocated.
1011 
1012     assert(isKernelLDS(func));
1013 
1014     LLVMContext &Ctx = M.getContext();
1015     const DataLayout &DL = M.getDataLayout();
1016     Align MaxDynamicAlignment(1);
1017 
1018     auto UpdateMaxAlignment = [&MaxDynamicAlignment, &DL](GlobalVariable *GV) {
1019       if (AMDGPU::isDynamicLDS(*GV)) {
1020         MaxDynamicAlignment =
1021             std::max(MaxDynamicAlignment, AMDGPU::getAlign(DL, GV));
1022       }
1023     };
1024 
1025     for (GlobalVariable *GV : LDSUsesInfo.indirect_access[func]) {
1026       UpdateMaxAlignment(GV);
1027     }
1028 
1029     for (GlobalVariable *GV : LDSUsesInfo.direct_access[func]) {
1030       UpdateMaxAlignment(GV);
1031     }
1032 
1033     assert(func->hasName()); // Checked by caller
1034     auto emptyCharArray = ArrayType::get(Type::getInt8Ty(Ctx), 0);
1035     GlobalVariable *N = new GlobalVariable(
1036         M, emptyCharArray, false, GlobalValue::ExternalLinkage, nullptr,
1037         Twine("llvm.amdgcn." + func->getName() + ".dynlds"), nullptr, GlobalValue::NotThreadLocal, AMDGPUAS::LOCAL_ADDRESS,
1038         false);
1039     N->setAlignment(MaxDynamicAlignment);
1040 
1041     assert(AMDGPU::isDynamicLDS(*N));
1042     return N;
1043   }
1044 
1045   DenseMap<Function *, GlobalVariable *> lowerDynamicLDSVariables(
1046       Module &M, LDSUsesInfoTy &LDSUsesInfo,
1047       DenseSet<Function *> const &KernelsThatIndirectlyAllocateDynamicLDS,
1048       DenseSet<GlobalVariable *> const &DynamicVariables,
1049       std::vector<Function *> const &OrderedKernels) {
1050     DenseMap<Function *, GlobalVariable *> KernelToCreatedDynamicLDS;
1051     if (!KernelsThatIndirectlyAllocateDynamicLDS.empty()) {
1052       LLVMContext &Ctx = M.getContext();
1053       IRBuilder<> Builder(Ctx);
1054       Type *I32 = Type::getInt32Ty(Ctx);
1055 
1056       std::vector<Constant *> newDynamicLDS;
1057 
1058       // Table is built in the same order as OrderedKernels
1059       for (auto &func : OrderedKernels) {
1060 
1061         if (KernelsThatIndirectlyAllocateDynamicLDS.contains(func)) {
1062           assert(isKernelLDS(func));
1063           if (!func->hasName()) {
1064             report_fatal_error("Anonymous kernels cannot use LDS variables");
1065           }
1066 
1067           GlobalVariable *N =
1068               buildRepresentativeDynamicLDSInstance(M, LDSUsesInfo, func);
1069 
1070           KernelToCreatedDynamicLDS[func] = N;
1071 
1072           markUsedByKernel(Builder, func, N);
1073 
1074           auto emptyCharArray = ArrayType::get(Type::getInt8Ty(Ctx), 0);
1075           auto GEP = ConstantExpr::getGetElementPtr(
1076               emptyCharArray, N, ConstantInt::get(I32, 0), true);
1077           newDynamicLDS.push_back(ConstantExpr::getPtrToInt(GEP, I32));
1078         } else {
1079           newDynamicLDS.push_back(PoisonValue::get(I32));
1080         }
1081       }
1082       assert(OrderedKernels.size() == newDynamicLDS.size());
1083 
1084       ArrayType *t = ArrayType::get(I32, newDynamicLDS.size());
1085       Constant *init = ConstantArray::get(t, newDynamicLDS);
1086       GlobalVariable *table = new GlobalVariable(
1087           M, t, true, GlobalValue::InternalLinkage, init,
1088           "llvm.amdgcn.dynlds.offset.table", nullptr,
1089           GlobalValue::NotThreadLocal, AMDGPUAS::CONSTANT_ADDRESS);
1090 
1091       for (GlobalVariable *GV : DynamicVariables) {
1092         for (Use &U : make_early_inc_range(GV->uses())) {
1093           auto *I = dyn_cast<Instruction>(U.getUser());
1094           if (!I)
1095             continue;
1096           if (isKernelLDS(I->getFunction()))
1097             continue;
1098 
1099           replaceUseWithTableLookup(M, Builder, table, GV, U, nullptr);
1100         }
1101       }
1102     }
1103     return KernelToCreatedDynamicLDS;
1104   }
1105 
1106   bool runOnModule(Module &M) override {
1107     CallGraph CG = CallGraph(M);
1108     bool Changed = superAlignLDSGlobals(M);
1109 
1110     Changed |= eliminateConstantExprUsesOfLDSFromAllInstructions(M);
1111 
1112     Changed = true; // todo: narrow this down
1113 
1114     // For each kernel, what variables does it access directly or through
1115     // callees
1116     LDSUsesInfoTy LDSUsesInfo = getTransitiveUsesOfLDS(CG, M);
1117 
1118     // For each variable accessed through callees, which kernels access it
1119     VariableFunctionMap LDSToKernelsThatNeedToAccessItIndirectly;
1120     for (auto &K : LDSUsesInfo.indirect_access) {
1121       Function *F = K.first;
1122       assert(isKernelLDS(F));
1123       for (GlobalVariable *GV : K.second) {
1124         LDSToKernelsThatNeedToAccessItIndirectly[GV].insert(F);
1125       }
1126     }
1127 
1128     // Partition variables accessed indirectly into the different strategies
1129     DenseSet<GlobalVariable *> ModuleScopeVariables;
1130     DenseSet<GlobalVariable *> TableLookupVariables;
1131     DenseSet<GlobalVariable *> KernelAccessVariables;
1132     DenseSet<GlobalVariable *> DynamicVariables;
1133     partitionVariablesIntoIndirectStrategies(
1134         M, LDSUsesInfo, LDSToKernelsThatNeedToAccessItIndirectly,
1135         ModuleScopeVariables, TableLookupVariables, KernelAccessVariables,
1136         DynamicVariables);
1137 
1138     // If the kernel accesses a variable that is going to be stored in the
1139     // module instance through a call then that kernel needs to allocate the
1140     // module instance
1141     const DenseSet<Function *> KernelsThatAllocateModuleLDS =
1142         kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo,
1143                                                         ModuleScopeVariables);
1144     const DenseSet<Function *> KernelsThatAllocateTableLDS =
1145         kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo,
1146                                                         TableLookupVariables);
1147 
1148     const DenseSet<Function *> KernelsThatIndirectlyAllocateDynamicLDS =
1149         kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo,
1150                                                         DynamicVariables);
1151 
1152     GlobalVariable *MaybeModuleScopeStruct = lowerModuleScopeStructVariables(
1153         M, ModuleScopeVariables, KernelsThatAllocateModuleLDS);
1154 
1155     DenseMap<Function *, LDSVariableReplacement> KernelToReplacement =
1156         lowerKernelScopeStructVariables(M, LDSUsesInfo, ModuleScopeVariables,
1157                                         KernelsThatAllocateModuleLDS,
1158                                         MaybeModuleScopeStruct);
1159 
1160     // Lower zero cost accesses to the kernel instances just created
1161     for (auto &GV : KernelAccessVariables) {
1162       auto &funcs = LDSToKernelsThatNeedToAccessItIndirectly[GV];
1163       assert(funcs.size() == 1); // Only one kernel can access it
1164       LDSVariableReplacement Replacement =
1165           KernelToReplacement[*(funcs.begin())];
1166 
1167       DenseSet<GlobalVariable *> Vec;
1168       Vec.insert(GV);
1169 
1170       replaceLDSVariablesWithStruct(M, Vec, Replacement, [](Use &U) {
1171         return isa<Instruction>(U.getUser());
1172       });
1173     }
1174 
1175     // The ith element of this vector is kernel id i
1176     std::vector<Function *> OrderedKernels =
1177         assignLDSKernelIDToEachKernel(&M, KernelsThatAllocateTableLDS,
1178                                       KernelsThatIndirectlyAllocateDynamicLDS);
1179 
1180     if (!KernelsThatAllocateTableLDS.empty()) {
1181       LLVMContext &Ctx = M.getContext();
1182       IRBuilder<> Builder(Ctx);
1183 
1184       // The order must be consistent between lookup table and accesses to
1185       // lookup table
1186       auto TableLookupVariablesOrdered =
1187           sortByName(std::vector<GlobalVariable *>(TableLookupVariables.begin(),
1188                                                    TableLookupVariables.end()));
1189 
1190       GlobalVariable *LookupTable = buildLookupTable(
1191           M, TableLookupVariablesOrdered, OrderedKernels, KernelToReplacement);
1192       replaceUsesInInstructionsWithTableLookup(M, TableLookupVariablesOrdered,
1193                                                LookupTable);
1194     }
1195 
1196     DenseMap<Function *, GlobalVariable *> KernelToCreatedDynamicLDS =
1197         lowerDynamicLDSVariables(M, LDSUsesInfo,
1198                                  KernelsThatIndirectlyAllocateDynamicLDS,
1199                                  DynamicVariables, OrderedKernels);
1200 
1201     // All kernel frames have been allocated. Calculate and record the
1202     // addresses.
1203     {
1204       const DataLayout &DL = M.getDataLayout();
1205 
1206       for (Function &Func : M.functions()) {
1207         if (Func.isDeclaration() || !isKernelLDS(&Func))
1208           continue;
1209 
1210         // All three of these are optional. The first variable is allocated at
1211         // zero. They are allocated by AMDGPUMachineFunction as one block.
1212         // Layout:
1213         //{
1214         //  module.lds
1215         //  alignment padding
1216         //  kernel instance
1217         //  alignment padding
1218         //  dynamic lds variables
1219         //}
1220 
1221         const bool AllocateModuleScopeStruct =
1222             MaybeModuleScopeStruct &&
1223             KernelsThatAllocateModuleLDS.contains(&Func);
1224 
1225         auto Replacement = KernelToReplacement.find(&Func);
1226         const bool AllocateKernelScopeStruct =
1227             Replacement != KernelToReplacement.end();
1228 
1229         const bool AllocateDynamicVariable =
1230             KernelToCreatedDynamicLDS.contains(&Func);
1231 
1232         uint32_t Offset = 0;
1233 
1234         if (AllocateModuleScopeStruct) {
1235           // Allocated at zero, recorded once on construction, not once per
1236           // kernel
1237           Offset += DL.getTypeAllocSize(MaybeModuleScopeStruct->getValueType());
1238         }
1239 
1240         if (AllocateKernelScopeStruct) {
1241           GlobalVariable *KernelStruct = Replacement->second.SGV;
1242           Offset = alignTo(Offset, AMDGPU::getAlign(DL, KernelStruct));
1243           recordLDSAbsoluteAddress(&M, KernelStruct, Offset);
1244           Offset += DL.getTypeAllocSize(KernelStruct->getValueType());
1245         }
1246 
1247         // If there is dynamic allocation, the alignment needed is included in
1248         // the static frame size. There may be no reference to the dynamic
1249         // variable in the kernel itself, so without including it here, that
1250         // alignment padding could be missed.
1251         if (AllocateDynamicVariable) {
1252           GlobalVariable *DynamicVariable = KernelToCreatedDynamicLDS[&Func];
1253           Offset = alignTo(Offset, AMDGPU::getAlign(DL, DynamicVariable));
1254           recordLDSAbsoluteAddress(&M, DynamicVariable, Offset);
1255         }
1256 
1257         if (Offset != 0) {
1258           std::string Buffer;
1259           raw_string_ostream SS{Buffer};
1260           SS << format("%u", Offset);
1261 
1262           // Instead of explictly marking kernels that access dynamic variables
1263           // using special case metadata, annotate with min-lds == max-lds, i.e.
1264           // that there is no more space available for allocating more static
1265           // LDS variables. That is the right condition to prevent allocating
1266           // more variables which would collide with the addresses assigned to
1267           // dynamic variables.
1268           if (AllocateDynamicVariable)
1269             SS << format(",%u", Offset);
1270 
1271           Func.addFnAttr("amdgpu-lds-size", Buffer);
1272         }
1273       }
1274     }
1275 
1276     for (auto &GV : make_early_inc_range(M.globals()))
1277       if (AMDGPU::isLDSVariableToLower(GV)) {
1278         // probably want to remove from used lists
1279         GV.removeDeadConstantUsers();
1280         if (GV.use_empty())
1281           GV.eraseFromParent();
1282       }
1283 
1284     return Changed;
1285   }
1286 
1287 private:
1288   // Increase the alignment of LDS globals if necessary to maximise the chance
1289   // that we can use aligned LDS instructions to access them.
1290   static bool superAlignLDSGlobals(Module &M) {
1291     const DataLayout &DL = M.getDataLayout();
1292     bool Changed = false;
1293     if (!SuperAlignLDSGlobals) {
1294       return Changed;
1295     }
1296 
1297     for (auto &GV : M.globals()) {
1298       if (GV.getType()->getPointerAddressSpace() != AMDGPUAS::LOCAL_ADDRESS) {
1299         // Only changing alignment of LDS variables
1300         continue;
1301       }
1302       if (!GV.hasInitializer()) {
1303         // cuda/hip extern __shared__ variable, leave alignment alone
1304         continue;
1305       }
1306 
1307       Align Alignment = AMDGPU::getAlign(DL, &GV);
1308       TypeSize GVSize = DL.getTypeAllocSize(GV.getValueType());
1309 
1310       if (GVSize > 8) {
1311         // We might want to use a b96 or b128 load/store
1312         Alignment = std::max(Alignment, Align(16));
1313       } else if (GVSize > 4) {
1314         // We might want to use a b64 load/store
1315         Alignment = std::max(Alignment, Align(8));
1316       } else if (GVSize > 2) {
1317         // We might want to use a b32 load/store
1318         Alignment = std::max(Alignment, Align(4));
1319       } else if (GVSize > 1) {
1320         // We might want to use a b16 load/store
1321         Alignment = std::max(Alignment, Align(2));
1322       }
1323 
1324       if (Alignment != AMDGPU::getAlign(DL, &GV)) {
1325         Changed = true;
1326         GV.setAlignment(Alignment);
1327       }
1328     }
1329     return Changed;
1330   }
1331 
1332   static LDSVariableReplacement createLDSVariableReplacement(
1333       Module &M, std::string VarName,
1334       DenseSet<GlobalVariable *> const &LDSVarsToTransform) {
1335     // Create a struct instance containing LDSVarsToTransform and map from those
1336     // variables to ConstantExprGEP
1337     // Variables may be introduced to meet alignment requirements. No aliasing
1338     // metadata is useful for these as they have no uses. Erased before return.
1339 
1340     LLVMContext &Ctx = M.getContext();
1341     const DataLayout &DL = M.getDataLayout();
1342     assert(!LDSVarsToTransform.empty());
1343 
1344     SmallVector<OptimizedStructLayoutField, 8> LayoutFields;
1345     LayoutFields.reserve(LDSVarsToTransform.size());
1346     {
1347       // The order of fields in this struct depends on the order of
1348       // varables in the argument which varies when changing how they
1349       // are identified, leading to spurious test breakage.
1350       auto Sorted = sortByName(std::vector<GlobalVariable *>(
1351           LDSVarsToTransform.begin(), LDSVarsToTransform.end()));
1352 
1353       for (GlobalVariable *GV : Sorted) {
1354         OptimizedStructLayoutField F(GV,
1355                                      DL.getTypeAllocSize(GV->getValueType()),
1356                                      AMDGPU::getAlign(DL, GV));
1357         LayoutFields.emplace_back(F);
1358       }
1359     }
1360 
1361     performOptimizedStructLayout(LayoutFields);
1362 
1363     std::vector<GlobalVariable *> LocalVars;
1364     BitVector IsPaddingField;
1365     LocalVars.reserve(LDSVarsToTransform.size()); // will be at least this large
1366     IsPaddingField.reserve(LDSVarsToTransform.size());
1367     {
1368       uint64_t CurrentOffset = 0;
1369       for (size_t I = 0; I < LayoutFields.size(); I++) {
1370         GlobalVariable *FGV = static_cast<GlobalVariable *>(
1371             const_cast<void *>(LayoutFields[I].Id));
1372         Align DataAlign = LayoutFields[I].Alignment;
1373 
1374         uint64_t DataAlignV = DataAlign.value();
1375         if (uint64_t Rem = CurrentOffset % DataAlignV) {
1376           uint64_t Padding = DataAlignV - Rem;
1377 
1378           // Append an array of padding bytes to meet alignment requested
1379           // Note (o +      (a - (o % a)) ) % a == 0
1380           //      (offset + Padding       ) % align == 0
1381 
1382           Type *ATy = ArrayType::get(Type::getInt8Ty(Ctx), Padding);
1383           LocalVars.push_back(new GlobalVariable(
1384               M, ATy, false, GlobalValue::InternalLinkage, UndefValue::get(ATy),
1385               "", nullptr, GlobalValue::NotThreadLocal, AMDGPUAS::LOCAL_ADDRESS,
1386               false));
1387           IsPaddingField.push_back(true);
1388           CurrentOffset += Padding;
1389         }
1390 
1391         LocalVars.push_back(FGV);
1392         IsPaddingField.push_back(false);
1393         CurrentOffset += LayoutFields[I].Size;
1394       }
1395     }
1396 
1397     std::vector<Type *> LocalVarTypes;
1398     LocalVarTypes.reserve(LocalVars.size());
1399     std::transform(
1400         LocalVars.cbegin(), LocalVars.cend(), std::back_inserter(LocalVarTypes),
1401         [](const GlobalVariable *V) -> Type * { return V->getValueType(); });
1402 
1403     StructType *LDSTy = StructType::create(Ctx, LocalVarTypes, VarName + ".t");
1404 
1405     Align StructAlign = AMDGPU::getAlign(DL, LocalVars[0]);
1406 
1407     GlobalVariable *SGV = new GlobalVariable(
1408         M, LDSTy, false, GlobalValue::InternalLinkage, UndefValue::get(LDSTy),
1409         VarName, nullptr, GlobalValue::NotThreadLocal, AMDGPUAS::LOCAL_ADDRESS,
1410         false);
1411     SGV->setAlignment(StructAlign);
1412 
1413     DenseMap<GlobalVariable *, Constant *> Map;
1414     Type *I32 = Type::getInt32Ty(Ctx);
1415     for (size_t I = 0; I < LocalVars.size(); I++) {
1416       GlobalVariable *GV = LocalVars[I];
1417       Constant *GEPIdx[] = {ConstantInt::get(I32, 0), ConstantInt::get(I32, I)};
1418       Constant *GEP = ConstantExpr::getGetElementPtr(LDSTy, SGV, GEPIdx, true);
1419       if (IsPaddingField[I]) {
1420         assert(GV->use_empty());
1421         GV->eraseFromParent();
1422       } else {
1423         Map[GV] = GEP;
1424       }
1425     }
1426     assert(Map.size() == LDSVarsToTransform.size());
1427     return {SGV, std::move(Map)};
1428   }
1429 
1430   template <typename PredicateTy>
1431   static void replaceLDSVariablesWithStruct(
1432       Module &M, DenseSet<GlobalVariable *> const &LDSVarsToTransformArg,
1433       const LDSVariableReplacement &Replacement, PredicateTy Predicate) {
1434     LLVMContext &Ctx = M.getContext();
1435     const DataLayout &DL = M.getDataLayout();
1436 
1437     // A hack... we need to insert the aliasing info in a predictable order for
1438     // lit tests. Would like to have them in a stable order already, ideally the
1439     // same order they get allocated, which might mean an ordered set container
1440     auto LDSVarsToTransform = sortByName(std::vector<GlobalVariable *>(
1441         LDSVarsToTransformArg.begin(), LDSVarsToTransformArg.end()));
1442 
1443     // Create alias.scope and their lists. Each field in the new structure
1444     // does not alias with all other fields.
1445     SmallVector<MDNode *> AliasScopes;
1446     SmallVector<Metadata *> NoAliasList;
1447     const size_t NumberVars = LDSVarsToTransform.size();
1448     if (NumberVars > 1) {
1449       MDBuilder MDB(Ctx);
1450       AliasScopes.reserve(NumberVars);
1451       MDNode *Domain = MDB.createAnonymousAliasScopeDomain();
1452       for (size_t I = 0; I < NumberVars; I++) {
1453         MDNode *Scope = MDB.createAnonymousAliasScope(Domain);
1454         AliasScopes.push_back(Scope);
1455       }
1456       NoAliasList.append(&AliasScopes[1], AliasScopes.end());
1457     }
1458 
1459     // Replace uses of ith variable with a constantexpr to the corresponding
1460     // field of the instance that will be allocated by AMDGPUMachineFunction
1461     for (size_t I = 0; I < NumberVars; I++) {
1462       GlobalVariable *GV = LDSVarsToTransform[I];
1463       Constant *GEP = Replacement.LDSVarsToConstantGEP.at(GV);
1464 
1465       GV->replaceUsesWithIf(GEP, Predicate);
1466 
1467       APInt APOff(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
1468       GEP->stripAndAccumulateInBoundsConstantOffsets(DL, APOff);
1469       uint64_t Offset = APOff.getZExtValue();
1470 
1471       Align A =
1472           commonAlignment(Replacement.SGV->getAlign().valueOrOne(), Offset);
1473 
1474       if (I)
1475         NoAliasList[I - 1] = AliasScopes[I - 1];
1476       MDNode *NoAlias =
1477           NoAliasList.empty() ? nullptr : MDNode::get(Ctx, NoAliasList);
1478       MDNode *AliasScope =
1479           AliasScopes.empty() ? nullptr : MDNode::get(Ctx, {AliasScopes[I]});
1480 
1481       refineUsesAlignmentAndAA(GEP, A, DL, AliasScope, NoAlias);
1482     }
1483   }
1484 
1485   static void refineUsesAlignmentAndAA(Value *Ptr, Align A,
1486                                        const DataLayout &DL, MDNode *AliasScope,
1487                                        MDNode *NoAlias, unsigned MaxDepth = 5) {
1488     if (!MaxDepth || (A == 1 && !AliasScope))
1489       return;
1490 
1491     for (User *U : Ptr->users()) {
1492       if (auto *I = dyn_cast<Instruction>(U)) {
1493         if (AliasScope && I->mayReadOrWriteMemory()) {
1494           MDNode *AS = I->getMetadata(LLVMContext::MD_alias_scope);
1495           AS = (AS ? MDNode::getMostGenericAliasScope(AS, AliasScope)
1496                    : AliasScope);
1497           I->setMetadata(LLVMContext::MD_alias_scope, AS);
1498 
1499           MDNode *NA = I->getMetadata(LLVMContext::MD_noalias);
1500           NA = (NA ? MDNode::intersect(NA, NoAlias) : NoAlias);
1501           I->setMetadata(LLVMContext::MD_noalias, NA);
1502         }
1503       }
1504 
1505       if (auto *LI = dyn_cast<LoadInst>(U)) {
1506         LI->setAlignment(std::max(A, LI->getAlign()));
1507         continue;
1508       }
1509       if (auto *SI = dyn_cast<StoreInst>(U)) {
1510         if (SI->getPointerOperand() == Ptr)
1511           SI->setAlignment(std::max(A, SI->getAlign()));
1512         continue;
1513       }
1514       if (auto *AI = dyn_cast<AtomicRMWInst>(U)) {
1515         // None of atomicrmw operations can work on pointers, but let's
1516         // check it anyway in case it will or we will process ConstantExpr.
1517         if (AI->getPointerOperand() == Ptr)
1518           AI->setAlignment(std::max(A, AI->getAlign()));
1519         continue;
1520       }
1521       if (auto *AI = dyn_cast<AtomicCmpXchgInst>(U)) {
1522         if (AI->getPointerOperand() == Ptr)
1523           AI->setAlignment(std::max(A, AI->getAlign()));
1524         continue;
1525       }
1526       if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
1527         unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
1528         APInt Off(BitWidth, 0);
1529         if (GEP->getPointerOperand() == Ptr) {
1530           Align GA;
1531           if (GEP->accumulateConstantOffset(DL, Off))
1532             GA = commonAlignment(A, Off.getLimitedValue());
1533           refineUsesAlignmentAndAA(GEP, GA, DL, AliasScope, NoAlias,
1534                                    MaxDepth - 1);
1535         }
1536         continue;
1537       }
1538       if (auto *I = dyn_cast<Instruction>(U)) {
1539         if (I->getOpcode() == Instruction::BitCast ||
1540             I->getOpcode() == Instruction::AddrSpaceCast)
1541           refineUsesAlignmentAndAA(I, A, DL, AliasScope, NoAlias, MaxDepth - 1);
1542       }
1543     }
1544   }
1545 };
1546 
1547 } // namespace
1548 char AMDGPULowerModuleLDS::ID = 0;
1549 
1550 char &llvm::AMDGPULowerModuleLDSID = AMDGPULowerModuleLDS::ID;
1551 
1552 INITIALIZE_PASS(AMDGPULowerModuleLDS, DEBUG_TYPE,
1553                 "Lower uses of LDS variables from non-kernel functions", false,
1554                 false)
1555 
1556 ModulePass *llvm::createAMDGPULowerModuleLDSPass() {
1557   return new AMDGPULowerModuleLDS();
1558 }
1559 
1560 PreservedAnalyses AMDGPULowerModuleLDSPass::run(Module &M,
1561                                                 ModuleAnalysisManager &) {
1562   return AMDGPULowerModuleLDS().runOnModule(M) ? PreservedAnalyses::none()
1563                                                : PreservedAnalyses::all();
1564 }
1565