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