1 //===-- AMDGPUPromoteAlloca.cpp - Promote Allocas -------------------------===//
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 allocas by either converting them into vectors or
10 // by migrating them to local address space.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AMDGPU.h"
15 #include "AMDGPUSubtarget.h"
16 #include "Utils/AMDGPUBaseInfo.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Analysis/CaptureTracking.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/CodeGen/TargetPassConfig.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/Constant.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GlobalValue.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/Instruction.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Intrinsics.h"
40 #include "llvm/IR/IntrinsicsAMDGPU.h"
41 #include "llvm/IR/IntrinsicsR600.h"
42 #include "llvm/IR/LLVMContext.h"
43 #include "llvm/IR/Metadata.h"
44 #include "llvm/IR/Module.h"
45 #include "llvm/IR/Type.h"
46 #include "llvm/IR/User.h"
47 #include "llvm/IR/Value.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetMachine.h"
55 #include <algorithm>
56 #include <cassert>
57 #include <cstdint>
58 #include <map>
59 #include <tuple>
60 #include <utility>
61 #include <vector>
62 
63 #define DEBUG_TYPE "amdgpu-promote-alloca"
64 
65 using namespace llvm;
66 
67 namespace {
68 
69 static cl::opt<bool> DisablePromoteAllocaToVector(
70   "disable-promote-alloca-to-vector",
71   cl::desc("Disable promote alloca to vector"),
72   cl::init(false));
73 
74 static cl::opt<bool> DisablePromoteAllocaToLDS(
75   "disable-promote-alloca-to-lds",
76   cl::desc("Disable promote alloca to LDS"),
77   cl::init(false));
78 
79 // FIXME: This can create globals so should be a module pass.
80 class AMDGPUPromoteAlloca : public FunctionPass {
81 private:
82   const TargetMachine *TM;
83   Module *Mod = nullptr;
84   const DataLayout *DL = nullptr;
85 
86   // FIXME: This should be per-kernel.
87   uint32_t LocalMemLimit = 0;
88   uint32_t CurrentLocalMemUsage = 0;
89 
90   bool IsAMDGCN = false;
91   bool IsAMDHSA = false;
92 
93   std::pair<Value *, Value *> getLocalSizeYZ(IRBuilder<> &Builder);
94   Value *getWorkitemID(IRBuilder<> &Builder, unsigned N);
95 
96   /// BaseAlloca is the alloca root the search started from.
97   /// Val may be that alloca or a recursive user of it.
98   bool collectUsesWithPtrTypes(Value *BaseAlloca,
99                                Value *Val,
100                                std::vector<Value*> &WorkList) const;
101 
102   /// Val is a derived pointer from Alloca. OpIdx0/OpIdx1 are the operand
103   /// indices to an instruction with 2 pointer inputs (e.g. select, icmp).
104   /// Returns true if both operands are derived from the same alloca. Val should
105   /// be the same value as one of the input operands of UseInst.
106   bool binaryOpIsDerivedFromSameAlloca(Value *Alloca, Value *Val,
107                                        Instruction *UseInst,
108                                        int OpIdx0, int OpIdx1) const;
109 
110   /// Check whether we have enough local memory for promotion.
111   bool hasSufficientLocalMem(const Function &F);
112 
113 public:
114   static char ID;
115 
116   AMDGPUPromoteAlloca() : FunctionPass(ID) {}
117 
118   bool doInitialization(Module &M) override;
119   bool runOnFunction(Function &F) override;
120 
121   StringRef getPassName() const override { return "AMDGPU Promote Alloca"; }
122 
123   bool handleAlloca(AllocaInst &I, bool SufficientLDS);
124 
125   void getAnalysisUsage(AnalysisUsage &AU) const override {
126     AU.setPreservesCFG();
127     FunctionPass::getAnalysisUsage(AU);
128   }
129 };
130 
131 } // end anonymous namespace
132 
133 char AMDGPUPromoteAlloca::ID = 0;
134 
135 INITIALIZE_PASS(AMDGPUPromoteAlloca, DEBUG_TYPE,
136                 "AMDGPU promote alloca to vector or LDS", false, false)
137 
138 char &llvm::AMDGPUPromoteAllocaID = AMDGPUPromoteAlloca::ID;
139 
140 bool AMDGPUPromoteAlloca::doInitialization(Module &M) {
141   Mod = &M;
142   DL = &Mod->getDataLayout();
143 
144   return false;
145 }
146 
147 bool AMDGPUPromoteAlloca::runOnFunction(Function &F) {
148   if (skipFunction(F))
149     return false;
150 
151   if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>())
152     TM = &TPC->getTM<TargetMachine>();
153   else
154     return false;
155 
156   const Triple &TT = TM->getTargetTriple();
157   IsAMDGCN = TT.getArch() == Triple::amdgcn;
158   IsAMDHSA = TT.getOS() == Triple::AMDHSA;
159 
160   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(*TM, F);
161   if (!ST.isPromoteAllocaEnabled())
162     return false;
163 
164   bool SufficientLDS = hasSufficientLocalMem(F);
165   bool Changed = false;
166   BasicBlock &EntryBB = *F.begin();
167 
168   SmallVector<AllocaInst *, 16> Allocas;
169   for (Instruction &I : EntryBB) {
170     if (AllocaInst *AI = dyn_cast<AllocaInst>(&I))
171       Allocas.push_back(AI);
172   }
173 
174   for (AllocaInst *AI : Allocas) {
175     if (handleAlloca(*AI, SufficientLDS))
176       Changed = true;
177   }
178 
179   return Changed;
180 }
181 
182 std::pair<Value *, Value *>
183 AMDGPUPromoteAlloca::getLocalSizeYZ(IRBuilder<> &Builder) {
184   const Function &F = *Builder.GetInsertBlock()->getParent();
185   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(*TM, F);
186 
187   if (!IsAMDHSA) {
188     Function *LocalSizeYFn
189       = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_y);
190     Function *LocalSizeZFn
191       = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_z);
192 
193     CallInst *LocalSizeY = Builder.CreateCall(LocalSizeYFn, {});
194     CallInst *LocalSizeZ = Builder.CreateCall(LocalSizeZFn, {});
195 
196     ST.makeLIDRangeMetadata(LocalSizeY);
197     ST.makeLIDRangeMetadata(LocalSizeZ);
198 
199     return std::make_pair(LocalSizeY, LocalSizeZ);
200   }
201 
202   // We must read the size out of the dispatch pointer.
203   assert(IsAMDGCN);
204 
205   // We are indexing into this struct, and want to extract the workgroup_size_*
206   // fields.
207   //
208   //   typedef struct hsa_kernel_dispatch_packet_s {
209   //     uint16_t header;
210   //     uint16_t setup;
211   //     uint16_t workgroup_size_x ;
212   //     uint16_t workgroup_size_y;
213   //     uint16_t workgroup_size_z;
214   //     uint16_t reserved0;
215   //     uint32_t grid_size_x ;
216   //     uint32_t grid_size_y ;
217   //     uint32_t grid_size_z;
218   //
219   //     uint32_t private_segment_size;
220   //     uint32_t group_segment_size;
221   //     uint64_t kernel_object;
222   //
223   // #ifdef HSA_LARGE_MODEL
224   //     void *kernarg_address;
225   // #elif defined HSA_LITTLE_ENDIAN
226   //     void *kernarg_address;
227   //     uint32_t reserved1;
228   // #else
229   //     uint32_t reserved1;
230   //     void *kernarg_address;
231   // #endif
232   //     uint64_t reserved2;
233   //     hsa_signal_t completion_signal; // uint64_t wrapper
234   //   } hsa_kernel_dispatch_packet_t
235   //
236   Function *DispatchPtrFn
237     = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_dispatch_ptr);
238 
239   CallInst *DispatchPtr = Builder.CreateCall(DispatchPtrFn, {});
240   DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
241   DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
242 
243   // Size of the dispatch packet struct.
244   DispatchPtr->addDereferenceableAttr(AttributeList::ReturnIndex, 64);
245 
246   Type *I32Ty = Type::getInt32Ty(Mod->getContext());
247   Value *CastDispatchPtr = Builder.CreateBitCast(
248     DispatchPtr, PointerType::get(I32Ty, AMDGPUAS::CONSTANT_ADDRESS));
249 
250   // We could do a single 64-bit load here, but it's likely that the basic
251   // 32-bit and extract sequence is already present, and it is probably easier
252   // to CSE this. The loads should be mergable later anyway.
253   Value *GEPXY = Builder.CreateConstInBoundsGEP1_64(I32Ty, CastDispatchPtr, 1);
254   LoadInst *LoadXY = Builder.CreateAlignedLoad(I32Ty, GEPXY, Align(4));
255 
256   Value *GEPZU = Builder.CreateConstInBoundsGEP1_64(I32Ty, CastDispatchPtr, 2);
257   LoadInst *LoadZU = Builder.CreateAlignedLoad(I32Ty, GEPZU, Align(4));
258 
259   MDNode *MD = MDNode::get(Mod->getContext(), None);
260   LoadXY->setMetadata(LLVMContext::MD_invariant_load, MD);
261   LoadZU->setMetadata(LLVMContext::MD_invariant_load, MD);
262   ST.makeLIDRangeMetadata(LoadZU);
263 
264   // Extract y component. Upper half of LoadZU should be zero already.
265   Value *Y = Builder.CreateLShr(LoadXY, 16);
266 
267   return std::make_pair(Y, LoadZU);
268 }
269 
270 Value *AMDGPUPromoteAlloca::getWorkitemID(IRBuilder<> &Builder, unsigned N) {
271   const AMDGPUSubtarget &ST =
272       AMDGPUSubtarget::get(*TM, *Builder.GetInsertBlock()->getParent());
273   Intrinsic::ID IntrID = Intrinsic::not_intrinsic;
274 
275   switch (N) {
276   case 0:
277     IntrID = IsAMDGCN ? (Intrinsic::ID)Intrinsic::amdgcn_workitem_id_x
278                       : (Intrinsic::ID)Intrinsic::r600_read_tidig_x;
279     break;
280   case 1:
281     IntrID = IsAMDGCN ? (Intrinsic::ID)Intrinsic::amdgcn_workitem_id_y
282                       : (Intrinsic::ID)Intrinsic::r600_read_tidig_y;
283     break;
284 
285   case 2:
286     IntrID = IsAMDGCN ? (Intrinsic::ID)Intrinsic::amdgcn_workitem_id_z
287                       : (Intrinsic::ID)Intrinsic::r600_read_tidig_z;
288     break;
289   default:
290     llvm_unreachable("invalid dimension");
291   }
292 
293   Function *WorkitemIdFn = Intrinsic::getDeclaration(Mod, IntrID);
294   CallInst *CI = Builder.CreateCall(WorkitemIdFn);
295   ST.makeLIDRangeMetadata(CI);
296 
297   return CI;
298 }
299 
300 static VectorType *arrayTypeToVecType(ArrayType *ArrayTy) {
301   return VectorType::get(ArrayTy->getElementType(),
302                          ArrayTy->getNumElements());
303 }
304 
305 static Value *
306 calculateVectorIndex(Value *Ptr,
307                      const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
308   GetElementPtrInst *GEP = cast<GetElementPtrInst>(Ptr);
309 
310   auto I = GEPIdx.find(GEP);
311   return I == GEPIdx.end() ? nullptr : I->second;
312 }
313 
314 static Value* GEPToVectorIndex(GetElementPtrInst *GEP) {
315   // FIXME we only support simple cases
316   if (GEP->getNumOperands() != 3)
317     return nullptr;
318 
319   ConstantInt *I0 = dyn_cast<ConstantInt>(GEP->getOperand(1));
320   if (!I0 || !I0->isZero())
321     return nullptr;
322 
323   return GEP->getOperand(2);
324 }
325 
326 // Not an instruction handled below to turn into a vector.
327 //
328 // TODO: Check isTriviallyVectorizable for calls and handle other
329 // instructions.
330 static bool canVectorizeInst(Instruction *Inst, User *User) {
331   switch (Inst->getOpcode()) {
332   case Instruction::Load: {
333     // Currently only handle the case where the Pointer Operand is a GEP.
334     // Also we could not vectorize volatile or atomic loads.
335     LoadInst *LI = cast<LoadInst>(Inst);
336     if (isa<AllocaInst>(User) &&
337         LI->getPointerOperandType() == User->getType() &&
338         isa<VectorType>(LI->getType()))
339       return true;
340     return isa<GetElementPtrInst>(LI->getPointerOperand()) && LI->isSimple();
341   }
342   case Instruction::BitCast:
343     return true;
344   case Instruction::Store: {
345     // Must be the stored pointer operand, not a stored value, plus
346     // since it should be canonical form, the User should be a GEP.
347     // Also we could not vectorize volatile or atomic stores.
348     StoreInst *SI = cast<StoreInst>(Inst);
349     if (isa<AllocaInst>(User) &&
350         SI->getPointerOperandType() == User->getType() &&
351         isa<VectorType>(SI->getValueOperand()->getType()))
352       return true;
353     return (SI->getPointerOperand() == User) && isa<GetElementPtrInst>(User) && SI->isSimple();
354   }
355   default:
356     return false;
357   }
358 }
359 
360 static bool tryPromoteAllocaToVector(AllocaInst *Alloca) {
361 
362   if (DisablePromoteAllocaToVector) {
363     LLVM_DEBUG(dbgs() << "  Promotion alloca to vector is disabled\n");
364     return false;
365   }
366 
367   Type *AllocaTy = Alloca->getAllocatedType();
368   VectorType *VectorTy = dyn_cast<VectorType>(AllocaTy);
369   if (auto *ArrayTy = dyn_cast<ArrayType>(AllocaTy)) {
370     if (VectorType::isValidElementType(ArrayTy->getElementType()) &&
371         ArrayTy->getNumElements() > 0)
372       VectorTy = arrayTypeToVecType(ArrayTy);
373   }
374 
375   LLVM_DEBUG(dbgs() << "Alloca candidate for vectorization\n");
376 
377   // FIXME: There is no reason why we can't support larger arrays, we
378   // are just being conservative for now.
379   // FIXME: We also reject alloca's of the form [ 2 x [ 2 x i32 ]] or equivalent. Potentially these
380   // could also be promoted but we don't currently handle this case
381   if (!VectorTy || VectorTy->getNumElements() > 16 ||
382       VectorTy->getNumElements() < 2) {
383     LLVM_DEBUG(dbgs() << "  Cannot convert type to vector\n");
384     return false;
385   }
386 
387   std::map<GetElementPtrInst*, Value*> GEPVectorIdx;
388   std::vector<Value*> WorkList;
389   for (User *AllocaUser : Alloca->users()) {
390     GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(AllocaUser);
391     if (!GEP) {
392       if (!canVectorizeInst(cast<Instruction>(AllocaUser), Alloca))
393         return false;
394 
395       WorkList.push_back(AllocaUser);
396       continue;
397     }
398 
399     Value *Index = GEPToVectorIndex(GEP);
400 
401     // If we can't compute a vector index from this GEP, then we can't
402     // promote this alloca to vector.
403     if (!Index) {
404       LLVM_DEBUG(dbgs() << "  Cannot compute vector index for GEP " << *GEP
405                         << '\n');
406       return false;
407     }
408 
409     GEPVectorIdx[GEP] = Index;
410     for (User *GEPUser : AllocaUser->users()) {
411       if (!canVectorizeInst(cast<Instruction>(GEPUser), AllocaUser))
412         return false;
413 
414       WorkList.push_back(GEPUser);
415     }
416   }
417 
418   LLVM_DEBUG(dbgs() << "  Converting alloca to vector " << *AllocaTy << " -> "
419                     << *VectorTy << '\n');
420 
421   for (Value *V : WorkList) {
422     Instruction *Inst = cast<Instruction>(V);
423     IRBuilder<> Builder(Inst);
424     switch (Inst->getOpcode()) {
425     case Instruction::Load: {
426       if (Inst->getType() == AllocaTy)
427         break;
428 
429       Type *VecPtrTy = VectorTy->getPointerTo(AMDGPUAS::PRIVATE_ADDRESS);
430       Value *Ptr = cast<LoadInst>(Inst)->getPointerOperand();
431       Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
432 
433       Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
434       Value *VecValue = Builder.CreateLoad(VectorTy, BitCast);
435       Value *ExtractElement = Builder.CreateExtractElement(VecValue, Index);
436       Inst->replaceAllUsesWith(ExtractElement);
437       Inst->eraseFromParent();
438       break;
439     }
440     case Instruction::Store: {
441       StoreInst *SI = cast<StoreInst>(Inst);
442       if (SI->getValueOperand()->getType() == AllocaTy)
443         break;
444 
445       Type *VecPtrTy = VectorTy->getPointerTo(AMDGPUAS::PRIVATE_ADDRESS);
446       Value *Ptr = SI->getPointerOperand();
447       Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
448       Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
449       Value *VecValue = Builder.CreateLoad(VectorTy, BitCast);
450       Value *NewVecValue = Builder.CreateInsertElement(VecValue,
451                                                        SI->getValueOperand(),
452                                                        Index);
453       Builder.CreateStore(NewVecValue, BitCast);
454       Inst->eraseFromParent();
455       break;
456     }
457     case Instruction::BitCast:
458     case Instruction::AddrSpaceCast:
459       break;
460 
461     default:
462       llvm_unreachable("Inconsistency in instructions promotable to vector");
463     }
464   }
465   return true;
466 }
467 
468 static bool isCallPromotable(CallInst *CI) {
469   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
470   if (!II)
471     return false;
472 
473   switch (II->getIntrinsicID()) {
474   case Intrinsic::memcpy:
475   case Intrinsic::memmove:
476   case Intrinsic::memset:
477   case Intrinsic::lifetime_start:
478   case Intrinsic::lifetime_end:
479   case Intrinsic::invariant_start:
480   case Intrinsic::invariant_end:
481   case Intrinsic::launder_invariant_group:
482   case Intrinsic::strip_invariant_group:
483   case Intrinsic::objectsize:
484     return true;
485   default:
486     return false;
487   }
488 }
489 
490 bool AMDGPUPromoteAlloca::binaryOpIsDerivedFromSameAlloca(Value *BaseAlloca,
491                                                           Value *Val,
492                                                           Instruction *Inst,
493                                                           int OpIdx0,
494                                                           int OpIdx1) const {
495   // Figure out which operand is the one we might not be promoting.
496   Value *OtherOp = Inst->getOperand(OpIdx0);
497   if (Val == OtherOp)
498     OtherOp = Inst->getOperand(OpIdx1);
499 
500   if (isa<ConstantPointerNull>(OtherOp))
501     return true;
502 
503   Value *OtherObj = GetUnderlyingObject(OtherOp, *DL);
504   if (!isa<AllocaInst>(OtherObj))
505     return false;
506 
507   // TODO: We should be able to replace undefs with the right pointer type.
508 
509   // TODO: If we know the other base object is another promotable
510   // alloca, not necessarily this alloca, we can do this. The
511   // important part is both must have the same address space at
512   // the end.
513   if (OtherObj != BaseAlloca) {
514     LLVM_DEBUG(
515         dbgs() << "Found a binary instruction with another alloca object\n");
516     return false;
517   }
518 
519   return true;
520 }
521 
522 bool AMDGPUPromoteAlloca::collectUsesWithPtrTypes(
523   Value *BaseAlloca,
524   Value *Val,
525   std::vector<Value*> &WorkList) const {
526 
527   for (User *User : Val->users()) {
528     if (is_contained(WorkList, User))
529       continue;
530 
531     if (CallInst *CI = dyn_cast<CallInst>(User)) {
532       if (!isCallPromotable(CI))
533         return false;
534 
535       WorkList.push_back(User);
536       continue;
537     }
538 
539     Instruction *UseInst = cast<Instruction>(User);
540     if (UseInst->getOpcode() == Instruction::PtrToInt)
541       return false;
542 
543     if (LoadInst *LI = dyn_cast<LoadInst>(UseInst)) {
544       if (LI->isVolatile())
545         return false;
546 
547       continue;
548     }
549 
550     if (StoreInst *SI = dyn_cast<StoreInst>(UseInst)) {
551       if (SI->isVolatile())
552         return false;
553 
554       // Reject if the stored value is not the pointer operand.
555       if (SI->getPointerOperand() != Val)
556         return false;
557     } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UseInst)) {
558       if (RMW->isVolatile())
559         return false;
560     } else if (AtomicCmpXchgInst *CAS = dyn_cast<AtomicCmpXchgInst>(UseInst)) {
561       if (CAS->isVolatile())
562         return false;
563     }
564 
565     // Only promote a select if we know that the other select operand
566     // is from another pointer that will also be promoted.
567     if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
568       if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, ICmp, 0, 1))
569         return false;
570 
571       // May need to rewrite constant operands.
572       WorkList.push_back(ICmp);
573     }
574 
575     if (UseInst->getOpcode() == Instruction::AddrSpaceCast) {
576       // Give up if the pointer may be captured.
577       if (PointerMayBeCaptured(UseInst, true, true))
578         return false;
579       // Don't collect the users of this.
580       WorkList.push_back(User);
581       continue;
582     }
583 
584     if (!User->getType()->isPointerTy())
585       continue;
586 
587     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UseInst)) {
588       // Be conservative if an address could be computed outside the bounds of
589       // the alloca.
590       if (!GEP->isInBounds())
591         return false;
592     }
593 
594     // Only promote a select if we know that the other select operand is from
595     // another pointer that will also be promoted.
596     if (SelectInst *SI = dyn_cast<SelectInst>(UseInst)) {
597       if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, SI, 1, 2))
598         return false;
599     }
600 
601     // Repeat for phis.
602     if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
603       // TODO: Handle more complex cases. We should be able to replace loops
604       // over arrays.
605       switch (Phi->getNumIncomingValues()) {
606       case 1:
607         break;
608       case 2:
609         if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, Phi, 0, 1))
610           return false;
611         break;
612       default:
613         return false;
614       }
615     }
616 
617     WorkList.push_back(User);
618     if (!collectUsesWithPtrTypes(BaseAlloca, User, WorkList))
619       return false;
620   }
621 
622   return true;
623 }
624 
625 bool AMDGPUPromoteAlloca::hasSufficientLocalMem(const Function &F) {
626 
627   FunctionType *FTy = F.getFunctionType();
628   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(*TM, F);
629 
630   // If the function has any arguments in the local address space, then it's
631   // possible these arguments require the entire local memory space, so
632   // we cannot use local memory in the pass.
633   for (Type *ParamTy : FTy->params()) {
634     PointerType *PtrTy = dyn_cast<PointerType>(ParamTy);
635     if (PtrTy && PtrTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
636       LocalMemLimit = 0;
637       LLVM_DEBUG(dbgs() << "Function has local memory argument. Promoting to "
638                            "local memory disabled.\n");
639       return false;
640     }
641   }
642 
643   LocalMemLimit = ST.getLocalMemorySize();
644   if (LocalMemLimit == 0)
645     return false;
646 
647   const DataLayout &DL = Mod->getDataLayout();
648 
649   // Check how much local memory is being used by global objects
650   CurrentLocalMemUsage = 0;
651   for (GlobalVariable &GV : Mod->globals()) {
652     if (GV.getAddressSpace() != AMDGPUAS::LOCAL_ADDRESS)
653       continue;
654 
655     for (const User *U : GV.users()) {
656       const Instruction *Use = dyn_cast<Instruction>(U);
657       if (!Use)
658         continue;
659 
660       if (Use->getParent()->getParent() == &F) {
661         unsigned Align = GV.getAlignment();
662         if (Align == 0)
663           Align = DL.getABITypeAlignment(GV.getValueType());
664 
665         // FIXME: Try to account for padding here. The padding is currently
666         // determined from the inverse order of uses in the function. I'm not
667         // sure if the use list order is in any way connected to this, so the
668         // total reported size is likely incorrect.
669         uint64_t AllocSize = DL.getTypeAllocSize(GV.getValueType());
670         CurrentLocalMemUsage = alignTo(CurrentLocalMemUsage, Align);
671         CurrentLocalMemUsage += AllocSize;
672         break;
673       }
674     }
675   }
676 
677   unsigned MaxOccupancy = ST.getOccupancyWithLocalMemSize(CurrentLocalMemUsage,
678                                                           F);
679 
680   // Restrict local memory usage so that we don't drastically reduce occupancy,
681   // unless it is already significantly reduced.
682 
683   // TODO: Have some sort of hint or other heuristics to guess occupancy based
684   // on other factors..
685   unsigned OccupancyHint = ST.getWavesPerEU(F).second;
686   if (OccupancyHint == 0)
687     OccupancyHint = 7;
688 
689   // Clamp to max value.
690   OccupancyHint = std::min(OccupancyHint, ST.getMaxWavesPerEU());
691 
692   // Check the hint but ignore it if it's obviously wrong from the existing LDS
693   // usage.
694   MaxOccupancy = std::min(OccupancyHint, MaxOccupancy);
695 
696 
697   // Round up to the next tier of usage.
698   unsigned MaxSizeWithWaveCount
699     = ST.getMaxLocalMemSizeWithWaveCount(MaxOccupancy, F);
700 
701   // Program is possibly broken by using more local mem than available.
702   if (CurrentLocalMemUsage > MaxSizeWithWaveCount)
703     return false;
704 
705   LocalMemLimit = MaxSizeWithWaveCount;
706 
707   LLVM_DEBUG(dbgs() << F.getName() << " uses " << CurrentLocalMemUsage
708                     << " bytes of LDS\n"
709                     << "  Rounding size to " << MaxSizeWithWaveCount
710                     << " with a maximum occupancy of " << MaxOccupancy << '\n'
711                     << " and " << (LocalMemLimit - CurrentLocalMemUsage)
712                     << " available for promotion\n");
713 
714   return true;
715 }
716 
717 // FIXME: Should try to pick the most likely to be profitable allocas first.
718 bool AMDGPUPromoteAlloca::handleAlloca(AllocaInst &I, bool SufficientLDS) {
719   // Array allocations are probably not worth handling, since an allocation of
720   // the array type is the canonical form.
721   if (!I.isStaticAlloca() || I.isArrayAllocation())
722     return false;
723 
724   IRBuilder<> Builder(&I);
725 
726   // First try to replace the alloca with a vector
727   Type *AllocaTy = I.getAllocatedType();
728 
729   LLVM_DEBUG(dbgs() << "Trying to promote " << I << '\n');
730 
731   if (tryPromoteAllocaToVector(&I))
732     return true; // Promoted to vector.
733 
734   if (DisablePromoteAllocaToLDS)
735     return false;
736 
737   const Function &ContainingFunction = *I.getParent()->getParent();
738   CallingConv::ID CC = ContainingFunction.getCallingConv();
739 
740   // Don't promote the alloca to LDS for shader calling conventions as the work
741   // item ID intrinsics are not supported for these calling conventions.
742   // Furthermore not all LDS is available for some of the stages.
743   switch (CC) {
744   case CallingConv::AMDGPU_KERNEL:
745   case CallingConv::SPIR_KERNEL:
746     break;
747   default:
748     LLVM_DEBUG(
749         dbgs()
750         << " promote alloca to LDS not supported with calling convention.\n");
751     return false;
752   }
753 
754   // Not likely to have sufficient local memory for promotion.
755   if (!SufficientLDS)
756     return false;
757 
758   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(*TM, ContainingFunction);
759   unsigned WorkGroupSize = ST.getFlatWorkGroupSizes(ContainingFunction).second;
760 
761   const DataLayout &DL = Mod->getDataLayout();
762 
763   unsigned Align = I.getAlignment();
764   if (Align == 0)
765     Align = DL.getABITypeAlignment(I.getAllocatedType());
766 
767   // FIXME: This computed padding is likely wrong since it depends on inverse
768   // usage order.
769   //
770   // FIXME: It is also possible that if we're allowed to use all of the memory
771   // could could end up using more than the maximum due to alignment padding.
772 
773   uint32_t NewSize = alignTo(CurrentLocalMemUsage, Align);
774   uint32_t AllocSize = WorkGroupSize * DL.getTypeAllocSize(AllocaTy);
775   NewSize += AllocSize;
776 
777   if (NewSize > LocalMemLimit) {
778     LLVM_DEBUG(dbgs() << "  " << AllocSize
779                       << " bytes of local memory not available to promote\n");
780     return false;
781   }
782 
783   CurrentLocalMemUsage = NewSize;
784 
785   std::vector<Value*> WorkList;
786 
787   if (!collectUsesWithPtrTypes(&I, &I, WorkList)) {
788     LLVM_DEBUG(dbgs() << " Do not know how to convert all uses\n");
789     return false;
790   }
791 
792   LLVM_DEBUG(dbgs() << "Promoting alloca to local memory\n");
793 
794   Function *F = I.getParent()->getParent();
795 
796   Type *GVTy = ArrayType::get(I.getAllocatedType(), WorkGroupSize);
797   GlobalVariable *GV = new GlobalVariable(
798       *Mod, GVTy, false, GlobalValue::InternalLinkage,
799       UndefValue::get(GVTy),
800       Twine(F->getName()) + Twine('.') + I.getName(),
801       nullptr,
802       GlobalVariable::NotThreadLocal,
803       AMDGPUAS::LOCAL_ADDRESS);
804   GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
805   GV->setAlignment(MaybeAlign(I.getAlignment()));
806 
807   Value *TCntY, *TCntZ;
808 
809   std::tie(TCntY, TCntZ) = getLocalSizeYZ(Builder);
810   Value *TIdX = getWorkitemID(Builder, 0);
811   Value *TIdY = getWorkitemID(Builder, 1);
812   Value *TIdZ = getWorkitemID(Builder, 2);
813 
814   Value *Tmp0 = Builder.CreateMul(TCntY, TCntZ, "", true, true);
815   Tmp0 = Builder.CreateMul(Tmp0, TIdX);
816   Value *Tmp1 = Builder.CreateMul(TIdY, TCntZ, "", true, true);
817   Value *TID = Builder.CreateAdd(Tmp0, Tmp1);
818   TID = Builder.CreateAdd(TID, TIdZ);
819 
820   Value *Indices[] = {
821     Constant::getNullValue(Type::getInt32Ty(Mod->getContext())),
822     TID
823   };
824 
825   Value *Offset = Builder.CreateInBoundsGEP(GVTy, GV, Indices);
826   I.mutateType(Offset->getType());
827   I.replaceAllUsesWith(Offset);
828   I.eraseFromParent();
829 
830   for (Value *V : WorkList) {
831     CallInst *Call = dyn_cast<CallInst>(V);
832     if (!Call) {
833       if (ICmpInst *CI = dyn_cast<ICmpInst>(V)) {
834         Value *Src0 = CI->getOperand(0);
835         Type *EltTy = Src0->getType()->getPointerElementType();
836         PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
837 
838         if (isa<ConstantPointerNull>(CI->getOperand(0)))
839           CI->setOperand(0, ConstantPointerNull::get(NewTy));
840 
841         if (isa<ConstantPointerNull>(CI->getOperand(1)))
842           CI->setOperand(1, ConstantPointerNull::get(NewTy));
843 
844         continue;
845       }
846 
847       // The operand's value should be corrected on its own and we don't want to
848       // touch the users.
849       if (isa<AddrSpaceCastInst>(V))
850         continue;
851 
852       Type *EltTy = V->getType()->getPointerElementType();
853       PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
854 
855       // FIXME: It doesn't really make sense to try to do this for all
856       // instructions.
857       V->mutateType(NewTy);
858 
859       // Adjust the types of any constant operands.
860       if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
861         if (isa<ConstantPointerNull>(SI->getOperand(1)))
862           SI->setOperand(1, ConstantPointerNull::get(NewTy));
863 
864         if (isa<ConstantPointerNull>(SI->getOperand(2)))
865           SI->setOperand(2, ConstantPointerNull::get(NewTy));
866       } else if (PHINode *Phi = dyn_cast<PHINode>(V)) {
867         for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
868           if (isa<ConstantPointerNull>(Phi->getIncomingValue(I)))
869             Phi->setIncomingValue(I, ConstantPointerNull::get(NewTy));
870         }
871       }
872 
873       continue;
874     }
875 
876     IntrinsicInst *Intr = cast<IntrinsicInst>(Call);
877     Builder.SetInsertPoint(Intr);
878     switch (Intr->getIntrinsicID()) {
879     case Intrinsic::lifetime_start:
880     case Intrinsic::lifetime_end:
881       // These intrinsics are for address space 0 only
882       Intr->eraseFromParent();
883       continue;
884     case Intrinsic::memcpy: {
885       MemCpyInst *MemCpy = cast<MemCpyInst>(Intr);
886       Builder.CreateMemCpy(MemCpy->getRawDest(), MemCpy->getDestAlign(),
887                            MemCpy->getRawSource(), MemCpy->getSourceAlign(),
888                            MemCpy->getLength(), MemCpy->isVolatile());
889       Intr->eraseFromParent();
890       continue;
891     }
892     case Intrinsic::memmove: {
893       MemMoveInst *MemMove = cast<MemMoveInst>(Intr);
894       Builder.CreateMemMove(MemMove->getRawDest(), MemMove->getDestAlign(),
895                             MemMove->getRawSource(), MemMove->getSourceAlign(),
896                             MemMove->getLength(), MemMove->isVolatile());
897       Intr->eraseFromParent();
898       continue;
899     }
900     case Intrinsic::memset: {
901       MemSetInst *MemSet = cast<MemSetInst>(Intr);
902       Builder.CreateMemSet(
903           MemSet->getRawDest(), MemSet->getValue(), MemSet->getLength(),
904           MaybeAlign(MemSet->getDestAlignment()), MemSet->isVolatile());
905       Intr->eraseFromParent();
906       continue;
907     }
908     case Intrinsic::invariant_start:
909     case Intrinsic::invariant_end:
910     case Intrinsic::launder_invariant_group:
911     case Intrinsic::strip_invariant_group:
912       Intr->eraseFromParent();
913       // FIXME: I think the invariant marker should still theoretically apply,
914       // but the intrinsics need to be changed to accept pointers with any
915       // address space.
916       continue;
917     case Intrinsic::objectsize: {
918       Value *Src = Intr->getOperand(0);
919       Type *SrcTy = Src->getType()->getPointerElementType();
920       Function *ObjectSize = Intrinsic::getDeclaration(Mod,
921         Intrinsic::objectsize,
922         { Intr->getType(), PointerType::get(SrcTy, AMDGPUAS::LOCAL_ADDRESS) }
923       );
924 
925       CallInst *NewCall = Builder.CreateCall(
926           ObjectSize,
927           {Src, Intr->getOperand(1), Intr->getOperand(2), Intr->getOperand(3)});
928       Intr->replaceAllUsesWith(NewCall);
929       Intr->eraseFromParent();
930       continue;
931     }
932     default:
933       Intr->print(errs());
934       llvm_unreachable("Don't know how to promote alloca intrinsic use.");
935     }
936   }
937   return true;
938 }
939 
940 FunctionPass *llvm::createAMDGPUPromoteAlloca() {
941   return new AMDGPUPromoteAlloca();
942 }
943