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 *stripBitcasts(Value *V) {
306   while (Instruction *I = dyn_cast<Instruction>(V)) {
307     if (I->getOpcode() != Instruction::BitCast)
308       break;
309     V = I->getOperand(0);
310   }
311   return V;
312 }
313 
314 static Value *
315 calculateVectorIndex(Value *Ptr,
316                      const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
317   GetElementPtrInst *GEP = cast<GetElementPtrInst>(stripBitcasts(Ptr));
318 
319   auto I = GEPIdx.find(GEP);
320   return I == GEPIdx.end() ? nullptr : I->second;
321 }
322 
323 static Value* GEPToVectorIndex(GetElementPtrInst *GEP) {
324   // FIXME we only support simple cases
325   if (GEP->getNumOperands() != 3)
326     return nullptr;
327 
328   ConstantInt *I0 = dyn_cast<ConstantInt>(GEP->getOperand(1));
329   if (!I0 || !I0->isZero())
330     return nullptr;
331 
332   return GEP->getOperand(2);
333 }
334 
335 // Not an instruction handled below to turn into a vector.
336 //
337 // TODO: Check isTriviallyVectorizable for calls and handle other
338 // instructions.
339 static bool canVectorizeInst(Instruction *Inst, User *User,
340                              const DataLayout &DL) {
341   switch (Inst->getOpcode()) {
342   case Instruction::Load: {
343     // Currently only handle the case where the Pointer Operand is a GEP.
344     // Also we could not vectorize volatile or atomic loads.
345     LoadInst *LI = cast<LoadInst>(Inst);
346     if (isa<AllocaInst>(User) &&
347         LI->getPointerOperandType() == User->getType() &&
348         isa<VectorType>(LI->getType()))
349       return true;
350 
351     Instruction *PtrInst = dyn_cast<Instruction>(LI->getPointerOperand());
352     if (!PtrInst)
353       return false;
354 
355     return (PtrInst->getOpcode() == Instruction::GetElementPtr ||
356             PtrInst->getOpcode() == Instruction::BitCast) &&
357            LI->isSimple();
358   }
359   case Instruction::BitCast:
360     return true;
361   case Instruction::Store: {
362     // Must be the stored pointer operand, not a stored value, plus
363     // since it should be canonical form, the User should be a GEP.
364     // Also we could not vectorize volatile or atomic stores.
365     StoreInst *SI = cast<StoreInst>(Inst);
366     if (isa<AllocaInst>(User) &&
367         SI->getPointerOperandType() == User->getType() &&
368         isa<VectorType>(SI->getValueOperand()->getType()))
369       return true;
370 
371     Instruction *UserInst = dyn_cast<Instruction>(User);
372     if (!UserInst)
373       return false;
374 
375     return (SI->getPointerOperand() == User) &&
376            (UserInst->getOpcode() == Instruction::GetElementPtr ||
377             UserInst->getOpcode() == Instruction::BitCast) &&
378            SI->isSimple();
379   }
380   default:
381     return false;
382   }
383 }
384 
385 static bool tryPromoteAllocaToVector(AllocaInst *Alloca, const DataLayout &DL) {
386 
387   if (DisablePromoteAllocaToVector) {
388     LLVM_DEBUG(dbgs() << "  Promotion alloca to vector is disabled\n");
389     return false;
390   }
391 
392   Type *AllocaTy = Alloca->getAllocatedType();
393   VectorType *VectorTy = dyn_cast<VectorType>(AllocaTy);
394   if (auto *ArrayTy = dyn_cast<ArrayType>(AllocaTy)) {
395     if (VectorType::isValidElementType(ArrayTy->getElementType()) &&
396         ArrayTy->getNumElements() > 0)
397       VectorTy = arrayTypeToVecType(ArrayTy);
398   }
399 
400   LLVM_DEBUG(dbgs() << "Alloca candidate for vectorization\n");
401 
402   // FIXME: There is no reason why we can't support larger arrays, we
403   // are just being conservative for now.
404   // FIXME: We also reject alloca's of the form [ 2 x [ 2 x i32 ]] or equivalent. Potentially these
405   // could also be promoted but we don't currently handle this case
406   if (!VectorTy || VectorTy->getNumElements() > 16 ||
407       VectorTy->getNumElements() < 2) {
408     LLVM_DEBUG(dbgs() << "  Cannot convert type to vector\n");
409     return false;
410   }
411 
412   std::map<GetElementPtrInst*, Value*> GEPVectorIdx;
413   std::vector<Value *> WorkList;
414   SmallVector<User *, 8> Users(Alloca->users());
415   SmallVector<User *, 8> UseUsers(Users.size(), Alloca);
416   Type *VecEltTy = VectorTy->getElementType();
417   while (!Users.empty()) {
418     User *AllocaUser = Users.pop_back_val();
419     User *UseUser = UseUsers.pop_back_val();
420     Instruction *Inst = dyn_cast<Instruction>(AllocaUser);
421 
422     GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(AllocaUser);
423     if (!GEP) {
424       if (!canVectorizeInst(Inst, UseUser, DL))
425         return false;
426 
427       if (Inst->getOpcode() == Instruction::BitCast) {
428         Type *FromTy = Inst->getOperand(0)->getType()->getPointerElementType();
429         Type *ToTy = Inst->getType()->getPointerElementType();
430         if (FromTy->isAggregateType() || ToTy->isAggregateType() ||
431             DL.getTypeSizeInBits(FromTy) != DL.getTypeSizeInBits(ToTy))
432           continue;
433 
434         for (User *CastUser : Inst->users()) {
435           if (isAssumeLikeIntrinsic(cast<Instruction>(CastUser)))
436             continue;
437           Users.push_back(CastUser);
438           UseUsers.push_back(Inst);
439         }
440 
441         continue;
442       }
443 
444       WorkList.push_back(AllocaUser);
445       continue;
446     }
447 
448     Value *Index = GEPToVectorIndex(GEP);
449 
450     // If we can't compute a vector index from this GEP, then we can't
451     // promote this alloca to vector.
452     if (!Index) {
453       LLVM_DEBUG(dbgs() << "  Cannot compute vector index for GEP " << *GEP
454                         << '\n');
455       return false;
456     }
457 
458     GEPVectorIdx[GEP] = Index;
459     Users.append(GEP->user_begin(), GEP->user_end());
460     UseUsers.append(GEP->getNumUses(), GEP);
461   }
462 
463   LLVM_DEBUG(dbgs() << "  Converting alloca to vector " << *AllocaTy << " -> "
464                     << *VectorTy << '\n');
465 
466   for (Value *V : WorkList) {
467     Instruction *Inst = cast<Instruction>(V);
468     IRBuilder<> Builder(Inst);
469     switch (Inst->getOpcode()) {
470     case Instruction::Load: {
471       if (Inst->getType() == AllocaTy)
472         break;
473 
474       Type *VecPtrTy = VectorTy->getPointerTo(AMDGPUAS::PRIVATE_ADDRESS);
475       Value *Ptr = cast<LoadInst>(Inst)->getPointerOperand();
476       Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
477 
478       Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
479       Value *VecValue = Builder.CreateLoad(VectorTy, BitCast);
480       Value *ExtractElement = Builder.CreateExtractElement(VecValue, Index);
481       if (Inst->getType() != VecEltTy)
482         ExtractElement = Builder.CreateBitCast(ExtractElement, Inst->getType());
483       Inst->replaceAllUsesWith(ExtractElement);
484       Inst->eraseFromParent();
485       break;
486     }
487     case Instruction::Store: {
488       StoreInst *SI = cast<StoreInst>(Inst);
489       if (SI->getValueOperand()->getType() == AllocaTy)
490         break;
491 
492       Type *VecPtrTy = VectorTy->getPointerTo(AMDGPUAS::PRIVATE_ADDRESS);
493       Value *Ptr = SI->getPointerOperand();
494       Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
495       Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
496       Value *VecValue = Builder.CreateLoad(VectorTy, BitCast);
497       Value *Elt = SI->getValueOperand();
498       if (Elt->getType() != VecEltTy)
499         Elt = Builder.CreateBitCast(Elt, VecEltTy);
500       Value *NewVecValue = Builder.CreateInsertElement(VecValue, Elt, Index);
501       Builder.CreateStore(NewVecValue, BitCast);
502       Inst->eraseFromParent();
503       break;
504     }
505 
506     default:
507       llvm_unreachable("Inconsistency in instructions promotable to vector");
508     }
509   }
510   return true;
511 }
512 
513 static bool isCallPromotable(CallInst *CI) {
514   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
515   if (!II)
516     return false;
517 
518   switch (II->getIntrinsicID()) {
519   case Intrinsic::memcpy:
520   case Intrinsic::memmove:
521   case Intrinsic::memset:
522   case Intrinsic::lifetime_start:
523   case Intrinsic::lifetime_end:
524   case Intrinsic::invariant_start:
525   case Intrinsic::invariant_end:
526   case Intrinsic::launder_invariant_group:
527   case Intrinsic::strip_invariant_group:
528   case Intrinsic::objectsize:
529     return true;
530   default:
531     return false;
532   }
533 }
534 
535 bool AMDGPUPromoteAlloca::binaryOpIsDerivedFromSameAlloca(Value *BaseAlloca,
536                                                           Value *Val,
537                                                           Instruction *Inst,
538                                                           int OpIdx0,
539                                                           int OpIdx1) const {
540   // Figure out which operand is the one we might not be promoting.
541   Value *OtherOp = Inst->getOperand(OpIdx0);
542   if (Val == OtherOp)
543     OtherOp = Inst->getOperand(OpIdx1);
544 
545   if (isa<ConstantPointerNull>(OtherOp))
546     return true;
547 
548   Value *OtherObj = GetUnderlyingObject(OtherOp, *DL);
549   if (!isa<AllocaInst>(OtherObj))
550     return false;
551 
552   // TODO: We should be able to replace undefs with the right pointer type.
553 
554   // TODO: If we know the other base object is another promotable
555   // alloca, not necessarily this alloca, we can do this. The
556   // important part is both must have the same address space at
557   // the end.
558   if (OtherObj != BaseAlloca) {
559     LLVM_DEBUG(
560         dbgs() << "Found a binary instruction with another alloca object\n");
561     return false;
562   }
563 
564   return true;
565 }
566 
567 bool AMDGPUPromoteAlloca::collectUsesWithPtrTypes(
568   Value *BaseAlloca,
569   Value *Val,
570   std::vector<Value*> &WorkList) const {
571 
572   for (User *User : Val->users()) {
573     if (is_contained(WorkList, User))
574       continue;
575 
576     if (CallInst *CI = dyn_cast<CallInst>(User)) {
577       if (!isCallPromotable(CI))
578         return false;
579 
580       WorkList.push_back(User);
581       continue;
582     }
583 
584     Instruction *UseInst = cast<Instruction>(User);
585     if (UseInst->getOpcode() == Instruction::PtrToInt)
586       return false;
587 
588     if (LoadInst *LI = dyn_cast<LoadInst>(UseInst)) {
589       if (LI->isVolatile())
590         return false;
591 
592       continue;
593     }
594 
595     if (StoreInst *SI = dyn_cast<StoreInst>(UseInst)) {
596       if (SI->isVolatile())
597         return false;
598 
599       // Reject if the stored value is not the pointer operand.
600       if (SI->getPointerOperand() != Val)
601         return false;
602     } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UseInst)) {
603       if (RMW->isVolatile())
604         return false;
605     } else if (AtomicCmpXchgInst *CAS = dyn_cast<AtomicCmpXchgInst>(UseInst)) {
606       if (CAS->isVolatile())
607         return false;
608     }
609 
610     // Only promote a select if we know that the other select operand
611     // is from another pointer that will also be promoted.
612     if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
613       if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, ICmp, 0, 1))
614         return false;
615 
616       // May need to rewrite constant operands.
617       WorkList.push_back(ICmp);
618     }
619 
620     if (UseInst->getOpcode() == Instruction::AddrSpaceCast) {
621       // Give up if the pointer may be captured.
622       if (PointerMayBeCaptured(UseInst, true, true))
623         return false;
624       // Don't collect the users of this.
625       WorkList.push_back(User);
626       continue;
627     }
628 
629     if (!User->getType()->isPointerTy())
630       continue;
631 
632     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UseInst)) {
633       // Be conservative if an address could be computed outside the bounds of
634       // the alloca.
635       if (!GEP->isInBounds())
636         return false;
637     }
638 
639     // Only promote a select if we know that the other select operand is from
640     // another pointer that will also be promoted.
641     if (SelectInst *SI = dyn_cast<SelectInst>(UseInst)) {
642       if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, SI, 1, 2))
643         return false;
644     }
645 
646     // Repeat for phis.
647     if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
648       // TODO: Handle more complex cases. We should be able to replace loops
649       // over arrays.
650       switch (Phi->getNumIncomingValues()) {
651       case 1:
652         break;
653       case 2:
654         if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, Phi, 0, 1))
655           return false;
656         break;
657       default:
658         return false;
659       }
660     }
661 
662     WorkList.push_back(User);
663     if (!collectUsesWithPtrTypes(BaseAlloca, User, WorkList))
664       return false;
665   }
666 
667   return true;
668 }
669 
670 bool AMDGPUPromoteAlloca::hasSufficientLocalMem(const Function &F) {
671 
672   FunctionType *FTy = F.getFunctionType();
673   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(*TM, F);
674 
675   // If the function has any arguments in the local address space, then it's
676   // possible these arguments require the entire local memory space, so
677   // we cannot use local memory in the pass.
678   for (Type *ParamTy : FTy->params()) {
679     PointerType *PtrTy = dyn_cast<PointerType>(ParamTy);
680     if (PtrTy && PtrTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
681       LocalMemLimit = 0;
682       LLVM_DEBUG(dbgs() << "Function has local memory argument. Promoting to "
683                            "local memory disabled.\n");
684       return false;
685     }
686   }
687 
688   LocalMemLimit = ST.getLocalMemorySize();
689   if (LocalMemLimit == 0)
690     return false;
691 
692   const DataLayout &DL = Mod->getDataLayout();
693 
694   // Check how much local memory is being used by global objects
695   CurrentLocalMemUsage = 0;
696   for (GlobalVariable &GV : Mod->globals()) {
697     if (GV.getAddressSpace() != AMDGPUAS::LOCAL_ADDRESS)
698       continue;
699 
700     for (const User *U : GV.users()) {
701       const Instruction *Use = dyn_cast<Instruction>(U);
702       if (!Use)
703         continue;
704 
705       if (Use->getParent()->getParent() == &F) {
706         unsigned Align = GV.getAlignment();
707         if (Align == 0)
708           Align = DL.getABITypeAlignment(GV.getValueType());
709 
710         // FIXME: Try to account for padding here. The padding is currently
711         // determined from the inverse order of uses in the function. I'm not
712         // sure if the use list order is in any way connected to this, so the
713         // total reported size is likely incorrect.
714         uint64_t AllocSize = DL.getTypeAllocSize(GV.getValueType());
715         CurrentLocalMemUsage = alignTo(CurrentLocalMemUsage, Align);
716         CurrentLocalMemUsage += AllocSize;
717         break;
718       }
719     }
720   }
721 
722   unsigned MaxOccupancy = ST.getOccupancyWithLocalMemSize(CurrentLocalMemUsage,
723                                                           F);
724 
725   // Restrict local memory usage so that we don't drastically reduce occupancy,
726   // unless it is already significantly reduced.
727 
728   // TODO: Have some sort of hint or other heuristics to guess occupancy based
729   // on other factors..
730   unsigned OccupancyHint = ST.getWavesPerEU(F).second;
731   if (OccupancyHint == 0)
732     OccupancyHint = 7;
733 
734   // Clamp to max value.
735   OccupancyHint = std::min(OccupancyHint, ST.getMaxWavesPerEU());
736 
737   // Check the hint but ignore it if it's obviously wrong from the existing LDS
738   // usage.
739   MaxOccupancy = std::min(OccupancyHint, MaxOccupancy);
740 
741 
742   // Round up to the next tier of usage.
743   unsigned MaxSizeWithWaveCount
744     = ST.getMaxLocalMemSizeWithWaveCount(MaxOccupancy, F);
745 
746   // Program is possibly broken by using more local mem than available.
747   if (CurrentLocalMemUsage > MaxSizeWithWaveCount)
748     return false;
749 
750   LocalMemLimit = MaxSizeWithWaveCount;
751 
752   LLVM_DEBUG(dbgs() << F.getName() << " uses " << CurrentLocalMemUsage
753                     << " bytes of LDS\n"
754                     << "  Rounding size to " << MaxSizeWithWaveCount
755                     << " with a maximum occupancy of " << MaxOccupancy << '\n'
756                     << " and " << (LocalMemLimit - CurrentLocalMemUsage)
757                     << " available for promotion\n");
758 
759   return true;
760 }
761 
762 // FIXME: Should try to pick the most likely to be profitable allocas first.
763 bool AMDGPUPromoteAlloca::handleAlloca(AllocaInst &I, bool SufficientLDS) {
764   // Array allocations are probably not worth handling, since an allocation of
765   // the array type is the canonical form.
766   if (!I.isStaticAlloca() || I.isArrayAllocation())
767     return false;
768 
769   const DataLayout &DL = Mod->getDataLayout();
770   IRBuilder<> Builder(&I);
771 
772   // First try to replace the alloca with a vector
773   Type *AllocaTy = I.getAllocatedType();
774 
775   LLVM_DEBUG(dbgs() << "Trying to promote " << I << '\n');
776 
777   if (tryPromoteAllocaToVector(&I, DL))
778     return true; // Promoted to vector.
779 
780   if (DisablePromoteAllocaToLDS)
781     return false;
782 
783   const Function &ContainingFunction = *I.getParent()->getParent();
784   CallingConv::ID CC = ContainingFunction.getCallingConv();
785 
786   // Don't promote the alloca to LDS for shader calling conventions as the work
787   // item ID intrinsics are not supported for these calling conventions.
788   // Furthermore not all LDS is available for some of the stages.
789   switch (CC) {
790   case CallingConv::AMDGPU_KERNEL:
791   case CallingConv::SPIR_KERNEL:
792     break;
793   default:
794     LLVM_DEBUG(
795         dbgs()
796         << " promote alloca to LDS not supported with calling convention.\n");
797     return false;
798   }
799 
800   // Not likely to have sufficient local memory for promotion.
801   if (!SufficientLDS)
802     return false;
803 
804   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(*TM, ContainingFunction);
805   unsigned WorkGroupSize = ST.getFlatWorkGroupSizes(ContainingFunction).second;
806 
807   unsigned Align = I.getAlignment();
808   if (Align == 0)
809     Align = DL.getABITypeAlignment(I.getAllocatedType());
810 
811   // FIXME: This computed padding is likely wrong since it depends on inverse
812   // usage order.
813   //
814   // FIXME: It is also possible that if we're allowed to use all of the memory
815   // could could end up using more than the maximum due to alignment padding.
816 
817   uint32_t NewSize = alignTo(CurrentLocalMemUsage, Align);
818   uint32_t AllocSize = WorkGroupSize * DL.getTypeAllocSize(AllocaTy);
819   NewSize += AllocSize;
820 
821   if (NewSize > LocalMemLimit) {
822     LLVM_DEBUG(dbgs() << "  " << AllocSize
823                       << " bytes of local memory not available to promote\n");
824     return false;
825   }
826 
827   CurrentLocalMemUsage = NewSize;
828 
829   std::vector<Value*> WorkList;
830 
831   if (!collectUsesWithPtrTypes(&I, &I, WorkList)) {
832     LLVM_DEBUG(dbgs() << " Do not know how to convert all uses\n");
833     return false;
834   }
835 
836   LLVM_DEBUG(dbgs() << "Promoting alloca to local memory\n");
837 
838   Function *F = I.getParent()->getParent();
839 
840   Type *GVTy = ArrayType::get(I.getAllocatedType(), WorkGroupSize);
841   GlobalVariable *GV = new GlobalVariable(
842       *Mod, GVTy, false, GlobalValue::InternalLinkage,
843       UndefValue::get(GVTy),
844       Twine(F->getName()) + Twine('.') + I.getName(),
845       nullptr,
846       GlobalVariable::NotThreadLocal,
847       AMDGPUAS::LOCAL_ADDRESS);
848   GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
849   GV->setAlignment(MaybeAlign(I.getAlignment()));
850 
851   Value *TCntY, *TCntZ;
852 
853   std::tie(TCntY, TCntZ) = getLocalSizeYZ(Builder);
854   Value *TIdX = getWorkitemID(Builder, 0);
855   Value *TIdY = getWorkitemID(Builder, 1);
856   Value *TIdZ = getWorkitemID(Builder, 2);
857 
858   Value *Tmp0 = Builder.CreateMul(TCntY, TCntZ, "", true, true);
859   Tmp0 = Builder.CreateMul(Tmp0, TIdX);
860   Value *Tmp1 = Builder.CreateMul(TIdY, TCntZ, "", true, true);
861   Value *TID = Builder.CreateAdd(Tmp0, Tmp1);
862   TID = Builder.CreateAdd(TID, TIdZ);
863 
864   Value *Indices[] = {
865     Constant::getNullValue(Type::getInt32Ty(Mod->getContext())),
866     TID
867   };
868 
869   Value *Offset = Builder.CreateInBoundsGEP(GVTy, GV, Indices);
870   I.mutateType(Offset->getType());
871   I.replaceAllUsesWith(Offset);
872   I.eraseFromParent();
873 
874   for (Value *V : WorkList) {
875     CallInst *Call = dyn_cast<CallInst>(V);
876     if (!Call) {
877       if (ICmpInst *CI = dyn_cast<ICmpInst>(V)) {
878         Value *Src0 = CI->getOperand(0);
879         Type *EltTy = Src0->getType()->getPointerElementType();
880         PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
881 
882         if (isa<ConstantPointerNull>(CI->getOperand(0)))
883           CI->setOperand(0, ConstantPointerNull::get(NewTy));
884 
885         if (isa<ConstantPointerNull>(CI->getOperand(1)))
886           CI->setOperand(1, ConstantPointerNull::get(NewTy));
887 
888         continue;
889       }
890 
891       // The operand's value should be corrected on its own and we don't want to
892       // touch the users.
893       if (isa<AddrSpaceCastInst>(V))
894         continue;
895 
896       Type *EltTy = V->getType()->getPointerElementType();
897       PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
898 
899       // FIXME: It doesn't really make sense to try to do this for all
900       // instructions.
901       V->mutateType(NewTy);
902 
903       // Adjust the types of any constant operands.
904       if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
905         if (isa<ConstantPointerNull>(SI->getOperand(1)))
906           SI->setOperand(1, ConstantPointerNull::get(NewTy));
907 
908         if (isa<ConstantPointerNull>(SI->getOperand(2)))
909           SI->setOperand(2, ConstantPointerNull::get(NewTy));
910       } else if (PHINode *Phi = dyn_cast<PHINode>(V)) {
911         for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
912           if (isa<ConstantPointerNull>(Phi->getIncomingValue(I)))
913             Phi->setIncomingValue(I, ConstantPointerNull::get(NewTy));
914         }
915       }
916 
917       continue;
918     }
919 
920     IntrinsicInst *Intr = cast<IntrinsicInst>(Call);
921     Builder.SetInsertPoint(Intr);
922     switch (Intr->getIntrinsicID()) {
923     case Intrinsic::lifetime_start:
924     case Intrinsic::lifetime_end:
925       // These intrinsics are for address space 0 only
926       Intr->eraseFromParent();
927       continue;
928     case Intrinsic::memcpy: {
929       MemCpyInst *MemCpy = cast<MemCpyInst>(Intr);
930       Builder.CreateMemCpy(MemCpy->getRawDest(), MemCpy->getDestAlign(),
931                            MemCpy->getRawSource(), MemCpy->getSourceAlign(),
932                            MemCpy->getLength(), MemCpy->isVolatile());
933       Intr->eraseFromParent();
934       continue;
935     }
936     case Intrinsic::memmove: {
937       MemMoveInst *MemMove = cast<MemMoveInst>(Intr);
938       Builder.CreateMemMove(MemMove->getRawDest(), MemMove->getDestAlign(),
939                             MemMove->getRawSource(), MemMove->getSourceAlign(),
940                             MemMove->getLength(), MemMove->isVolatile());
941       Intr->eraseFromParent();
942       continue;
943     }
944     case Intrinsic::memset: {
945       MemSetInst *MemSet = cast<MemSetInst>(Intr);
946       Builder.CreateMemSet(
947           MemSet->getRawDest(), MemSet->getValue(), MemSet->getLength(),
948           MaybeAlign(MemSet->getDestAlignment()), MemSet->isVolatile());
949       Intr->eraseFromParent();
950       continue;
951     }
952     case Intrinsic::invariant_start:
953     case Intrinsic::invariant_end:
954     case Intrinsic::launder_invariant_group:
955     case Intrinsic::strip_invariant_group:
956       Intr->eraseFromParent();
957       // FIXME: I think the invariant marker should still theoretically apply,
958       // but the intrinsics need to be changed to accept pointers with any
959       // address space.
960       continue;
961     case Intrinsic::objectsize: {
962       Value *Src = Intr->getOperand(0);
963       Type *SrcTy = Src->getType()->getPointerElementType();
964       Function *ObjectSize = Intrinsic::getDeclaration(Mod,
965         Intrinsic::objectsize,
966         { Intr->getType(), PointerType::get(SrcTy, AMDGPUAS::LOCAL_ADDRESS) }
967       );
968 
969       CallInst *NewCall = Builder.CreateCall(
970           ObjectSize,
971           {Src, Intr->getOperand(1), Intr->getOperand(2), Intr->getOperand(3)});
972       Intr->replaceAllUsesWith(NewCall);
973       Intr->eraseFromParent();
974       continue;
975     }
976     default:
977       Intr->print(errs());
978       llvm_unreachable("Don't know how to promote alloca intrinsic use.");
979     }
980   }
981   return true;
982 }
983 
984 FunctionPass *llvm::createAMDGPUPromoteAlloca() {
985   return new AMDGPUPromoteAlloca();
986 }
987