LCOV - code coverage report
Current view: top level - lib/Target/AMDGPU - AMDGPUPromoteAlloca.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 290 298 97.3 %
Date: 2018-02-23 05:02:05 Functions: 19 21 90.5 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13