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