xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPromoteAlloca.cpp (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
10b57cec5SDimitry Andric //===-- AMDGPUPromoteAlloca.cpp - Promote Allocas -------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This pass eliminates allocas by either converting them into vectors or
100b57cec5SDimitry Andric // by migrating them to local address space.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "AMDGPU.h"
15*e8d8bef9SDimitry Andric #include "GCNSubtarget.h"
160b57cec5SDimitry Andric #include "llvm/Analysis/CaptureTracking.h"
170b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
180b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
190b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
20480093f4SDimitry Andric #include "llvm/IR/IntrinsicsAMDGPU.h"
21480093f4SDimitry Andric #include "llvm/IR/IntrinsicsR600.h"
220b57cec5SDimitry Andric #include "llvm/Pass.h"
230b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
240b57cec5SDimitry Andric 
250b57cec5SDimitry Andric #define DEBUG_TYPE "amdgpu-promote-alloca"
260b57cec5SDimitry Andric 
270b57cec5SDimitry Andric using namespace llvm;
280b57cec5SDimitry Andric 
290b57cec5SDimitry Andric namespace {
300b57cec5SDimitry Andric 
310b57cec5SDimitry Andric static cl::opt<bool> DisablePromoteAllocaToVector(
320b57cec5SDimitry Andric   "disable-promote-alloca-to-vector",
330b57cec5SDimitry Andric   cl::desc("Disable promote alloca to vector"),
340b57cec5SDimitry Andric   cl::init(false));
350b57cec5SDimitry Andric 
360b57cec5SDimitry Andric static cl::opt<bool> DisablePromoteAllocaToLDS(
370b57cec5SDimitry Andric   "disable-promote-alloca-to-lds",
380b57cec5SDimitry Andric   cl::desc("Disable promote alloca to LDS"),
390b57cec5SDimitry Andric   cl::init(false));
400b57cec5SDimitry Andric 
415ffd83dbSDimitry Andric static cl::opt<unsigned> PromoteAllocaToVectorLimit(
425ffd83dbSDimitry Andric   "amdgpu-promote-alloca-to-vector-limit",
435ffd83dbSDimitry Andric   cl::desc("Maximum byte size to consider promote alloca to vector"),
445ffd83dbSDimitry Andric   cl::init(0));
455ffd83dbSDimitry Andric 
460b57cec5SDimitry Andric // FIXME: This can create globals so should be a module pass.
470b57cec5SDimitry Andric class AMDGPUPromoteAlloca : public FunctionPass {
48*e8d8bef9SDimitry Andric public:
49*e8d8bef9SDimitry Andric   static char ID;
50*e8d8bef9SDimitry Andric 
51*e8d8bef9SDimitry Andric   AMDGPUPromoteAlloca() : FunctionPass(ID) {}
52*e8d8bef9SDimitry Andric 
53*e8d8bef9SDimitry Andric   bool runOnFunction(Function &F) override;
54*e8d8bef9SDimitry Andric 
55*e8d8bef9SDimitry Andric   StringRef getPassName() const override { return "AMDGPU Promote Alloca"; }
56*e8d8bef9SDimitry Andric 
57*e8d8bef9SDimitry Andric   bool handleAlloca(AllocaInst &I, bool SufficientLDS);
58*e8d8bef9SDimitry Andric 
59*e8d8bef9SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
60*e8d8bef9SDimitry Andric     AU.setPreservesCFG();
61*e8d8bef9SDimitry Andric     FunctionPass::getAnalysisUsage(AU);
62*e8d8bef9SDimitry Andric   }
63*e8d8bef9SDimitry Andric };
64*e8d8bef9SDimitry Andric 
65*e8d8bef9SDimitry Andric class AMDGPUPromoteAllocaImpl {
660b57cec5SDimitry Andric private:
67*e8d8bef9SDimitry Andric   const TargetMachine &TM;
680b57cec5SDimitry Andric   Module *Mod = nullptr;
690b57cec5SDimitry Andric   const DataLayout *DL = nullptr;
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric   // FIXME: This should be per-kernel.
720b57cec5SDimitry Andric   uint32_t LocalMemLimit = 0;
730b57cec5SDimitry Andric   uint32_t CurrentLocalMemUsage = 0;
745ffd83dbSDimitry Andric   unsigned MaxVGPRs;
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric   bool IsAMDGCN = false;
770b57cec5SDimitry Andric   bool IsAMDHSA = false;
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric   std::pair<Value *, Value *> getLocalSizeYZ(IRBuilder<> &Builder);
800b57cec5SDimitry Andric   Value *getWorkitemID(IRBuilder<> &Builder, unsigned N);
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric   /// BaseAlloca is the alloca root the search started from.
830b57cec5SDimitry Andric   /// Val may be that alloca or a recursive user of it.
840b57cec5SDimitry Andric   bool collectUsesWithPtrTypes(Value *BaseAlloca,
850b57cec5SDimitry Andric                                Value *Val,
860b57cec5SDimitry Andric                                std::vector<Value*> &WorkList) const;
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric   /// Val is a derived pointer from Alloca. OpIdx0/OpIdx1 are the operand
890b57cec5SDimitry Andric   /// indices to an instruction with 2 pointer inputs (e.g. select, icmp).
900b57cec5SDimitry Andric   /// Returns true if both operands are derived from the same alloca. Val should
910b57cec5SDimitry Andric   /// be the same value as one of the input operands of UseInst.
920b57cec5SDimitry Andric   bool binaryOpIsDerivedFromSameAlloca(Value *Alloca, Value *Val,
930b57cec5SDimitry Andric                                        Instruction *UseInst,
940b57cec5SDimitry Andric                                        int OpIdx0, int OpIdx1) const;
950b57cec5SDimitry Andric 
960b57cec5SDimitry Andric   /// Check whether we have enough local memory for promotion.
970b57cec5SDimitry Andric   bool hasSufficientLocalMem(const Function &F);
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric   bool handleAlloca(AllocaInst &I, bool SufficientLDS);
1000b57cec5SDimitry Andric 
101*e8d8bef9SDimitry Andric public:
102*e8d8bef9SDimitry Andric   AMDGPUPromoteAllocaImpl(TargetMachine &TM) : TM(TM) {}
103*e8d8bef9SDimitry Andric   bool run(Function &F);
1040b57cec5SDimitry Andric };
1050b57cec5SDimitry Andric 
1065ffd83dbSDimitry Andric class AMDGPUPromoteAllocaToVector : public FunctionPass {
1075ffd83dbSDimitry Andric public:
1085ffd83dbSDimitry Andric   static char ID;
1095ffd83dbSDimitry Andric 
1105ffd83dbSDimitry Andric   AMDGPUPromoteAllocaToVector() : FunctionPass(ID) {}
1115ffd83dbSDimitry Andric 
1125ffd83dbSDimitry Andric   bool runOnFunction(Function &F) override;
1135ffd83dbSDimitry Andric 
1145ffd83dbSDimitry Andric   StringRef getPassName() const override {
1155ffd83dbSDimitry Andric     return "AMDGPU Promote Alloca to vector";
1165ffd83dbSDimitry Andric   }
1175ffd83dbSDimitry Andric 
1185ffd83dbSDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
1195ffd83dbSDimitry Andric     AU.setPreservesCFG();
1205ffd83dbSDimitry Andric     FunctionPass::getAnalysisUsage(AU);
1215ffd83dbSDimitry Andric   }
1225ffd83dbSDimitry Andric };
1235ffd83dbSDimitry Andric 
1240b57cec5SDimitry Andric } // end anonymous namespace
1250b57cec5SDimitry Andric 
1260b57cec5SDimitry Andric char AMDGPUPromoteAlloca::ID = 0;
1275ffd83dbSDimitry Andric char AMDGPUPromoteAllocaToVector::ID = 0;
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric INITIALIZE_PASS(AMDGPUPromoteAlloca, DEBUG_TYPE,
1300b57cec5SDimitry Andric                 "AMDGPU promote alloca to vector or LDS", false, false)
1310b57cec5SDimitry Andric 
1325ffd83dbSDimitry Andric INITIALIZE_PASS(AMDGPUPromoteAllocaToVector, DEBUG_TYPE "-to-vector",
1335ffd83dbSDimitry Andric                 "AMDGPU promote alloca to vector", false, false)
1345ffd83dbSDimitry Andric 
1350b57cec5SDimitry Andric char &llvm::AMDGPUPromoteAllocaID = AMDGPUPromoteAlloca::ID;
1365ffd83dbSDimitry Andric char &llvm::AMDGPUPromoteAllocaToVectorID = AMDGPUPromoteAllocaToVector::ID;
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric bool AMDGPUPromoteAlloca::runOnFunction(Function &F) {
1390b57cec5SDimitry Andric   if (skipFunction(F))
1400b57cec5SDimitry Andric     return false;
1410b57cec5SDimitry Andric 
142*e8d8bef9SDimitry Andric   if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
143*e8d8bef9SDimitry Andric     return AMDGPUPromoteAllocaImpl(TPC->getTM<TargetMachine>()).run(F);
144*e8d8bef9SDimitry Andric   }
1450b57cec5SDimitry Andric   return false;
146*e8d8bef9SDimitry Andric }
1470b57cec5SDimitry Andric 
148*e8d8bef9SDimitry Andric PreservedAnalyses AMDGPUPromoteAllocaPass::run(Function &F,
149*e8d8bef9SDimitry Andric                                                FunctionAnalysisManager &AM) {
150*e8d8bef9SDimitry Andric   bool Changed = AMDGPUPromoteAllocaImpl(TM).run(F);
151*e8d8bef9SDimitry Andric   if (Changed) {
152*e8d8bef9SDimitry Andric     PreservedAnalyses PA;
153*e8d8bef9SDimitry Andric     PA.preserveSet<CFGAnalyses>();
154*e8d8bef9SDimitry Andric     return PA;
155*e8d8bef9SDimitry Andric   }
156*e8d8bef9SDimitry Andric   return PreservedAnalyses::all();
157*e8d8bef9SDimitry Andric }
158*e8d8bef9SDimitry Andric 
159*e8d8bef9SDimitry Andric bool AMDGPUPromoteAllocaImpl::run(Function &F) {
160*e8d8bef9SDimitry Andric   Mod = F.getParent();
161*e8d8bef9SDimitry Andric   DL = &Mod->getDataLayout();
162*e8d8bef9SDimitry Andric 
163*e8d8bef9SDimitry Andric   const Triple &TT = TM.getTargetTriple();
1640b57cec5SDimitry Andric   IsAMDGCN = TT.getArch() == Triple::amdgcn;
1650b57cec5SDimitry Andric   IsAMDHSA = TT.getOS() == Triple::AMDHSA;
1660b57cec5SDimitry Andric 
167*e8d8bef9SDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(TM, F);
1680b57cec5SDimitry Andric   if (!ST.isPromoteAllocaEnabled())
1690b57cec5SDimitry Andric     return false;
1700b57cec5SDimitry Andric 
1715ffd83dbSDimitry Andric   if (IsAMDGCN) {
172*e8d8bef9SDimitry Andric     const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(F);
1735ffd83dbSDimitry Andric     MaxVGPRs = ST.getMaxNumVGPRs(ST.getWavesPerEU(F).first);
1745ffd83dbSDimitry Andric   } else {
1755ffd83dbSDimitry Andric     MaxVGPRs = 128;
1765ffd83dbSDimitry Andric   }
1775ffd83dbSDimitry Andric 
1780b57cec5SDimitry Andric   bool SufficientLDS = hasSufficientLocalMem(F);
1790b57cec5SDimitry Andric   bool Changed = false;
1800b57cec5SDimitry Andric   BasicBlock &EntryBB = *F.begin();
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric   SmallVector<AllocaInst *, 16> Allocas;
1830b57cec5SDimitry Andric   for (Instruction &I : EntryBB) {
1840b57cec5SDimitry Andric     if (AllocaInst *AI = dyn_cast<AllocaInst>(&I))
1850b57cec5SDimitry Andric       Allocas.push_back(AI);
1860b57cec5SDimitry Andric   }
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric   for (AllocaInst *AI : Allocas) {
1890b57cec5SDimitry Andric     if (handleAlloca(*AI, SufficientLDS))
1900b57cec5SDimitry Andric       Changed = true;
1910b57cec5SDimitry Andric   }
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric   return Changed;
1940b57cec5SDimitry Andric }
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric std::pair<Value *, Value *>
197*e8d8bef9SDimitry Andric AMDGPUPromoteAllocaImpl::getLocalSizeYZ(IRBuilder<> &Builder) {
1980b57cec5SDimitry Andric   const Function &F = *Builder.GetInsertBlock()->getParent();
199*e8d8bef9SDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(TM, F);
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric   if (!IsAMDHSA) {
2020b57cec5SDimitry Andric     Function *LocalSizeYFn
2030b57cec5SDimitry Andric       = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_y);
2040b57cec5SDimitry Andric     Function *LocalSizeZFn
2050b57cec5SDimitry Andric       = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_z);
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric     CallInst *LocalSizeY = Builder.CreateCall(LocalSizeYFn, {});
2080b57cec5SDimitry Andric     CallInst *LocalSizeZ = Builder.CreateCall(LocalSizeZFn, {});
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric     ST.makeLIDRangeMetadata(LocalSizeY);
2110b57cec5SDimitry Andric     ST.makeLIDRangeMetadata(LocalSizeZ);
2120b57cec5SDimitry Andric 
2130b57cec5SDimitry Andric     return std::make_pair(LocalSizeY, LocalSizeZ);
2140b57cec5SDimitry Andric   }
2150b57cec5SDimitry Andric 
2160b57cec5SDimitry Andric   // We must read the size out of the dispatch pointer.
2170b57cec5SDimitry Andric   assert(IsAMDGCN);
2180b57cec5SDimitry Andric 
2190b57cec5SDimitry Andric   // We are indexing into this struct, and want to extract the workgroup_size_*
2200b57cec5SDimitry Andric   // fields.
2210b57cec5SDimitry Andric   //
2220b57cec5SDimitry Andric   //   typedef struct hsa_kernel_dispatch_packet_s {
2230b57cec5SDimitry Andric   //     uint16_t header;
2240b57cec5SDimitry Andric   //     uint16_t setup;
2250b57cec5SDimitry Andric   //     uint16_t workgroup_size_x ;
2260b57cec5SDimitry Andric   //     uint16_t workgroup_size_y;
2270b57cec5SDimitry Andric   //     uint16_t workgroup_size_z;
2280b57cec5SDimitry Andric   //     uint16_t reserved0;
2290b57cec5SDimitry Andric   //     uint32_t grid_size_x ;
2300b57cec5SDimitry Andric   //     uint32_t grid_size_y ;
2310b57cec5SDimitry Andric   //     uint32_t grid_size_z;
2320b57cec5SDimitry Andric   //
2330b57cec5SDimitry Andric   //     uint32_t private_segment_size;
2340b57cec5SDimitry Andric   //     uint32_t group_segment_size;
2350b57cec5SDimitry Andric   //     uint64_t kernel_object;
2360b57cec5SDimitry Andric   //
2370b57cec5SDimitry Andric   // #ifdef HSA_LARGE_MODEL
2380b57cec5SDimitry Andric   //     void *kernarg_address;
2390b57cec5SDimitry Andric   // #elif defined HSA_LITTLE_ENDIAN
2400b57cec5SDimitry Andric   //     void *kernarg_address;
2410b57cec5SDimitry Andric   //     uint32_t reserved1;
2420b57cec5SDimitry Andric   // #else
2430b57cec5SDimitry Andric   //     uint32_t reserved1;
2440b57cec5SDimitry Andric   //     void *kernarg_address;
2450b57cec5SDimitry Andric   // #endif
2460b57cec5SDimitry Andric   //     uint64_t reserved2;
2470b57cec5SDimitry Andric   //     hsa_signal_t completion_signal; // uint64_t wrapper
2480b57cec5SDimitry Andric   //   } hsa_kernel_dispatch_packet_t
2490b57cec5SDimitry Andric   //
2500b57cec5SDimitry Andric   Function *DispatchPtrFn
2510b57cec5SDimitry Andric     = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_dispatch_ptr);
2520b57cec5SDimitry Andric 
2530b57cec5SDimitry Andric   CallInst *DispatchPtr = Builder.CreateCall(DispatchPtrFn, {});
2540b57cec5SDimitry Andric   DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
2550b57cec5SDimitry Andric   DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric   // Size of the dispatch packet struct.
2580b57cec5SDimitry Andric   DispatchPtr->addDereferenceableAttr(AttributeList::ReturnIndex, 64);
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric   Type *I32Ty = Type::getInt32Ty(Mod->getContext());
2610b57cec5SDimitry Andric   Value *CastDispatchPtr = Builder.CreateBitCast(
2620b57cec5SDimitry Andric     DispatchPtr, PointerType::get(I32Ty, AMDGPUAS::CONSTANT_ADDRESS));
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric   // We could do a single 64-bit load here, but it's likely that the basic
2650b57cec5SDimitry Andric   // 32-bit and extract sequence is already present, and it is probably easier
2660b57cec5SDimitry Andric   // to CSE this. The loads should be mergable later anyway.
2670b57cec5SDimitry Andric   Value *GEPXY = Builder.CreateConstInBoundsGEP1_64(I32Ty, CastDispatchPtr, 1);
2685ffd83dbSDimitry Andric   LoadInst *LoadXY = Builder.CreateAlignedLoad(I32Ty, GEPXY, Align(4));
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric   Value *GEPZU = Builder.CreateConstInBoundsGEP1_64(I32Ty, CastDispatchPtr, 2);
2715ffd83dbSDimitry Andric   LoadInst *LoadZU = Builder.CreateAlignedLoad(I32Ty, GEPZU, Align(4));
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric   MDNode *MD = MDNode::get(Mod->getContext(), None);
2740b57cec5SDimitry Andric   LoadXY->setMetadata(LLVMContext::MD_invariant_load, MD);
2750b57cec5SDimitry Andric   LoadZU->setMetadata(LLVMContext::MD_invariant_load, MD);
2760b57cec5SDimitry Andric   ST.makeLIDRangeMetadata(LoadZU);
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric   // Extract y component. Upper half of LoadZU should be zero already.
2790b57cec5SDimitry Andric   Value *Y = Builder.CreateLShr(LoadXY, 16);
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric   return std::make_pair(Y, LoadZU);
2820b57cec5SDimitry Andric }
2830b57cec5SDimitry Andric 
284*e8d8bef9SDimitry Andric Value *AMDGPUPromoteAllocaImpl::getWorkitemID(IRBuilder<> &Builder,
285*e8d8bef9SDimitry Andric                                               unsigned N) {
2860b57cec5SDimitry Andric   const AMDGPUSubtarget &ST =
287*e8d8bef9SDimitry Andric       AMDGPUSubtarget::get(TM, *Builder.GetInsertBlock()->getParent());
288480093f4SDimitry Andric   Intrinsic::ID IntrID = Intrinsic::not_intrinsic;
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric   switch (N) {
2910b57cec5SDimitry Andric   case 0:
292480093f4SDimitry Andric     IntrID = IsAMDGCN ? (Intrinsic::ID)Intrinsic::amdgcn_workitem_id_x
293480093f4SDimitry Andric                       : (Intrinsic::ID)Intrinsic::r600_read_tidig_x;
2940b57cec5SDimitry Andric     break;
2950b57cec5SDimitry Andric   case 1:
296480093f4SDimitry Andric     IntrID = IsAMDGCN ? (Intrinsic::ID)Intrinsic::amdgcn_workitem_id_y
297480093f4SDimitry Andric                       : (Intrinsic::ID)Intrinsic::r600_read_tidig_y;
2980b57cec5SDimitry Andric     break;
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric   case 2:
301480093f4SDimitry Andric     IntrID = IsAMDGCN ? (Intrinsic::ID)Intrinsic::amdgcn_workitem_id_z
302480093f4SDimitry Andric                       : (Intrinsic::ID)Intrinsic::r600_read_tidig_z;
3030b57cec5SDimitry Andric     break;
3040b57cec5SDimitry Andric   default:
3050b57cec5SDimitry Andric     llvm_unreachable("invalid dimension");
3060b57cec5SDimitry Andric   }
3070b57cec5SDimitry Andric 
3080b57cec5SDimitry Andric   Function *WorkitemIdFn = Intrinsic::getDeclaration(Mod, IntrID);
3090b57cec5SDimitry Andric   CallInst *CI = Builder.CreateCall(WorkitemIdFn);
3100b57cec5SDimitry Andric   ST.makeLIDRangeMetadata(CI);
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric   return CI;
3130b57cec5SDimitry Andric }
3140b57cec5SDimitry Andric 
3155ffd83dbSDimitry Andric static FixedVectorType *arrayTypeToVecType(ArrayType *ArrayTy) {
3165ffd83dbSDimitry Andric   return FixedVectorType::get(ArrayTy->getElementType(),
3170b57cec5SDimitry Andric                               ArrayTy->getNumElements());
3180b57cec5SDimitry Andric }
3190b57cec5SDimitry Andric 
3205ffd83dbSDimitry Andric static Value *stripBitcasts(Value *V) {
3215ffd83dbSDimitry Andric   while (Instruction *I = dyn_cast<Instruction>(V)) {
3225ffd83dbSDimitry Andric     if (I->getOpcode() != Instruction::BitCast)
3235ffd83dbSDimitry Andric       break;
3245ffd83dbSDimitry Andric     V = I->getOperand(0);
3255ffd83dbSDimitry Andric   }
3265ffd83dbSDimitry Andric   return V;
3275ffd83dbSDimitry Andric }
3285ffd83dbSDimitry Andric 
3290b57cec5SDimitry Andric static Value *
3300b57cec5SDimitry Andric calculateVectorIndex(Value *Ptr,
3310b57cec5SDimitry Andric                      const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
3325ffd83dbSDimitry Andric   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(stripBitcasts(Ptr));
3335ffd83dbSDimitry Andric   if (!GEP)
3345ffd83dbSDimitry Andric     return nullptr;
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric   auto I = GEPIdx.find(GEP);
3370b57cec5SDimitry Andric   return I == GEPIdx.end() ? nullptr : I->second;
3380b57cec5SDimitry Andric }
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric static Value* GEPToVectorIndex(GetElementPtrInst *GEP) {
3410b57cec5SDimitry Andric   // FIXME we only support simple cases
3420b57cec5SDimitry Andric   if (GEP->getNumOperands() != 3)
3430b57cec5SDimitry Andric     return nullptr;
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric   ConstantInt *I0 = dyn_cast<ConstantInt>(GEP->getOperand(1));
3460b57cec5SDimitry Andric   if (!I0 || !I0->isZero())
3470b57cec5SDimitry Andric     return nullptr;
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric   return GEP->getOperand(2);
3500b57cec5SDimitry Andric }
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric // Not an instruction handled below to turn into a vector.
3530b57cec5SDimitry Andric //
3540b57cec5SDimitry Andric // TODO: Check isTriviallyVectorizable for calls and handle other
3550b57cec5SDimitry Andric // instructions.
3565ffd83dbSDimitry Andric static bool canVectorizeInst(Instruction *Inst, User *User,
3575ffd83dbSDimitry Andric                              const DataLayout &DL) {
3580b57cec5SDimitry Andric   switch (Inst->getOpcode()) {
3590b57cec5SDimitry Andric   case Instruction::Load: {
3600b57cec5SDimitry Andric     // Currently only handle the case where the Pointer Operand is a GEP.
3610b57cec5SDimitry Andric     // Also we could not vectorize volatile or atomic loads.
3620b57cec5SDimitry Andric     LoadInst *LI = cast<LoadInst>(Inst);
3630b57cec5SDimitry Andric     if (isa<AllocaInst>(User) &&
3640b57cec5SDimitry Andric         LI->getPointerOperandType() == User->getType() &&
3650b57cec5SDimitry Andric         isa<VectorType>(LI->getType()))
3660b57cec5SDimitry Andric       return true;
3675ffd83dbSDimitry Andric 
3685ffd83dbSDimitry Andric     Instruction *PtrInst = dyn_cast<Instruction>(LI->getPointerOperand());
3695ffd83dbSDimitry Andric     if (!PtrInst)
3705ffd83dbSDimitry Andric       return false;
3715ffd83dbSDimitry Andric 
3725ffd83dbSDimitry Andric     return (PtrInst->getOpcode() == Instruction::GetElementPtr ||
3735ffd83dbSDimitry Andric             PtrInst->getOpcode() == Instruction::BitCast) &&
3745ffd83dbSDimitry Andric            LI->isSimple();
3750b57cec5SDimitry Andric   }
3760b57cec5SDimitry Andric   case Instruction::BitCast:
3770b57cec5SDimitry Andric     return true;
3780b57cec5SDimitry Andric   case Instruction::Store: {
3790b57cec5SDimitry Andric     // Must be the stored pointer operand, not a stored value, plus
3800b57cec5SDimitry Andric     // since it should be canonical form, the User should be a GEP.
3810b57cec5SDimitry Andric     // Also we could not vectorize volatile or atomic stores.
3820b57cec5SDimitry Andric     StoreInst *SI = cast<StoreInst>(Inst);
3830b57cec5SDimitry Andric     if (isa<AllocaInst>(User) &&
3840b57cec5SDimitry Andric         SI->getPointerOperandType() == User->getType() &&
3850b57cec5SDimitry Andric         isa<VectorType>(SI->getValueOperand()->getType()))
3860b57cec5SDimitry Andric       return true;
3875ffd83dbSDimitry Andric 
3885ffd83dbSDimitry Andric     Instruction *UserInst = dyn_cast<Instruction>(User);
3895ffd83dbSDimitry Andric     if (!UserInst)
3905ffd83dbSDimitry Andric       return false;
3915ffd83dbSDimitry Andric 
3925ffd83dbSDimitry Andric     return (SI->getPointerOperand() == User) &&
3935ffd83dbSDimitry Andric            (UserInst->getOpcode() == Instruction::GetElementPtr ||
3945ffd83dbSDimitry Andric             UserInst->getOpcode() == Instruction::BitCast) &&
3955ffd83dbSDimitry Andric            SI->isSimple();
3960b57cec5SDimitry Andric   }
3970b57cec5SDimitry Andric   default:
3980b57cec5SDimitry Andric     return false;
3990b57cec5SDimitry Andric   }
4000b57cec5SDimitry Andric }
4010b57cec5SDimitry Andric 
4025ffd83dbSDimitry Andric static bool tryPromoteAllocaToVector(AllocaInst *Alloca, const DataLayout &DL,
4035ffd83dbSDimitry Andric                                      unsigned MaxVGPRs) {
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric   if (DisablePromoteAllocaToVector) {
4060b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Promotion alloca to vector is disabled\n");
4070b57cec5SDimitry Andric     return false;
4080b57cec5SDimitry Andric   }
4090b57cec5SDimitry Andric 
4105ffd83dbSDimitry Andric   Type *AllocaTy = Alloca->getAllocatedType();
4115ffd83dbSDimitry Andric   auto *VectorTy = dyn_cast<FixedVectorType>(AllocaTy);
4125ffd83dbSDimitry Andric   if (auto *ArrayTy = dyn_cast<ArrayType>(AllocaTy)) {
4135ffd83dbSDimitry Andric     if (VectorType::isValidElementType(ArrayTy->getElementType()) &&
4145ffd83dbSDimitry Andric         ArrayTy->getNumElements() > 0)
4155ffd83dbSDimitry Andric       VectorTy = arrayTypeToVecType(ArrayTy);
4165ffd83dbSDimitry Andric   }
4175ffd83dbSDimitry Andric 
4185ffd83dbSDimitry Andric   // Use up to 1/4 of available register budget for vectorization.
4195ffd83dbSDimitry Andric   unsigned Limit = PromoteAllocaToVectorLimit ? PromoteAllocaToVectorLimit * 8
4205ffd83dbSDimitry Andric                                               : (MaxVGPRs * 32);
4215ffd83dbSDimitry Andric 
4225ffd83dbSDimitry Andric   if (DL.getTypeSizeInBits(AllocaTy) * 4 > Limit) {
4235ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "  Alloca too big for vectorization with "
4245ffd83dbSDimitry Andric                       << MaxVGPRs << " registers available\n");
4255ffd83dbSDimitry Andric     return false;
4265ffd83dbSDimitry Andric   }
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Alloca candidate for vectorization\n");
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric   // FIXME: There is no reason why we can't support larger arrays, we
4310b57cec5SDimitry Andric   // are just being conservative for now.
4320b57cec5SDimitry Andric   // FIXME: We also reject alloca's of the form [ 2 x [ 2 x i32 ]] or equivalent. Potentially these
4330b57cec5SDimitry Andric   // could also be promoted but we don't currently handle this case
4345ffd83dbSDimitry Andric   if (!VectorTy || VectorTy->getNumElements() > 16 ||
4355ffd83dbSDimitry Andric       VectorTy->getNumElements() < 2) {
4360b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Cannot convert type to vector\n");
4370b57cec5SDimitry Andric     return false;
4380b57cec5SDimitry Andric   }
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric   std::map<GetElementPtrInst*, Value*> GEPVectorIdx;
4410b57cec5SDimitry Andric   std::vector<Value *> WorkList;
4425ffd83dbSDimitry Andric   SmallVector<User *, 8> Users(Alloca->users());
4435ffd83dbSDimitry Andric   SmallVector<User *, 8> UseUsers(Users.size(), Alloca);
4445ffd83dbSDimitry Andric   Type *VecEltTy = VectorTy->getElementType();
4455ffd83dbSDimitry Andric   while (!Users.empty()) {
4465ffd83dbSDimitry Andric     User *AllocaUser = Users.pop_back_val();
4475ffd83dbSDimitry Andric     User *UseUser = UseUsers.pop_back_val();
4485ffd83dbSDimitry Andric     Instruction *Inst = dyn_cast<Instruction>(AllocaUser);
4495ffd83dbSDimitry Andric 
4500b57cec5SDimitry Andric     GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(AllocaUser);
4510b57cec5SDimitry Andric     if (!GEP) {
4525ffd83dbSDimitry Andric       if (!canVectorizeInst(Inst, UseUser, DL))
4530b57cec5SDimitry Andric         return false;
4540b57cec5SDimitry Andric 
4555ffd83dbSDimitry Andric       if (Inst->getOpcode() == Instruction::BitCast) {
4565ffd83dbSDimitry Andric         Type *FromTy = Inst->getOperand(0)->getType()->getPointerElementType();
4575ffd83dbSDimitry Andric         Type *ToTy = Inst->getType()->getPointerElementType();
4585ffd83dbSDimitry Andric         if (FromTy->isAggregateType() || ToTy->isAggregateType() ||
4595ffd83dbSDimitry Andric             DL.getTypeSizeInBits(FromTy) != DL.getTypeSizeInBits(ToTy))
4605ffd83dbSDimitry Andric           continue;
4615ffd83dbSDimitry Andric 
4625ffd83dbSDimitry Andric         for (User *CastUser : Inst->users()) {
4635ffd83dbSDimitry Andric           if (isAssumeLikeIntrinsic(cast<Instruction>(CastUser)))
4645ffd83dbSDimitry Andric             continue;
4655ffd83dbSDimitry Andric           Users.push_back(CastUser);
4665ffd83dbSDimitry Andric           UseUsers.push_back(Inst);
4675ffd83dbSDimitry Andric         }
4685ffd83dbSDimitry Andric 
4695ffd83dbSDimitry Andric         continue;
4705ffd83dbSDimitry Andric       }
4715ffd83dbSDimitry Andric 
4720b57cec5SDimitry Andric       WorkList.push_back(AllocaUser);
4730b57cec5SDimitry Andric       continue;
4740b57cec5SDimitry Andric     }
4750b57cec5SDimitry Andric 
4760b57cec5SDimitry Andric     Value *Index = GEPToVectorIndex(GEP);
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric     // If we can't compute a vector index from this GEP, then we can't
4790b57cec5SDimitry Andric     // promote this alloca to vector.
4800b57cec5SDimitry Andric     if (!Index) {
4810b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  Cannot compute vector index for GEP " << *GEP
4820b57cec5SDimitry Andric                         << '\n');
4830b57cec5SDimitry Andric       return false;
4840b57cec5SDimitry Andric     }
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric     GEPVectorIdx[GEP] = Index;
4875ffd83dbSDimitry Andric     Users.append(GEP->user_begin(), GEP->user_end());
4885ffd83dbSDimitry Andric     UseUsers.append(GEP->getNumUses(), GEP);
4890b57cec5SDimitry Andric   }
4900b57cec5SDimitry Andric 
4910b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Converting alloca to vector " << *AllocaTy << " -> "
4920b57cec5SDimitry Andric                     << *VectorTy << '\n');
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric   for (Value *V : WorkList) {
4950b57cec5SDimitry Andric     Instruction *Inst = cast<Instruction>(V);
4960b57cec5SDimitry Andric     IRBuilder<> Builder(Inst);
4970b57cec5SDimitry Andric     switch (Inst->getOpcode()) {
4980b57cec5SDimitry Andric     case Instruction::Load: {
4995ffd83dbSDimitry Andric       if (Inst->getType() == AllocaTy || Inst->getType()->isVectorTy())
5005ffd83dbSDimitry Andric         break;
5015ffd83dbSDimitry Andric 
5025ffd83dbSDimitry Andric       Value *Ptr = cast<LoadInst>(Inst)->getPointerOperand();
5035ffd83dbSDimitry Andric       Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
5045ffd83dbSDimitry Andric       if (!Index)
5050b57cec5SDimitry Andric         break;
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric       Type *VecPtrTy = VectorTy->getPointerTo(AMDGPUAS::PRIVATE_ADDRESS);
5080b57cec5SDimitry Andric       Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
5090b57cec5SDimitry Andric       Value *VecValue = Builder.CreateLoad(VectorTy, BitCast);
5100b57cec5SDimitry Andric       Value *ExtractElement = Builder.CreateExtractElement(VecValue, Index);
5115ffd83dbSDimitry Andric       if (Inst->getType() != VecEltTy)
5125ffd83dbSDimitry Andric         ExtractElement = Builder.CreateBitOrPointerCast(ExtractElement, Inst->getType());
5130b57cec5SDimitry Andric       Inst->replaceAllUsesWith(ExtractElement);
5140b57cec5SDimitry Andric       Inst->eraseFromParent();
5150b57cec5SDimitry Andric       break;
5160b57cec5SDimitry Andric     }
5170b57cec5SDimitry Andric     case Instruction::Store: {
5180b57cec5SDimitry Andric       StoreInst *SI = cast<StoreInst>(Inst);
5195ffd83dbSDimitry Andric       if (SI->getValueOperand()->getType() == AllocaTy ||
5205ffd83dbSDimitry Andric           SI->getValueOperand()->getType()->isVectorTy())
5215ffd83dbSDimitry Andric         break;
5225ffd83dbSDimitry Andric 
5235ffd83dbSDimitry Andric       Value *Ptr = SI->getPointerOperand();
5245ffd83dbSDimitry Andric       Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
5255ffd83dbSDimitry Andric       if (!Index)
5260b57cec5SDimitry Andric         break;
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric       Type *VecPtrTy = VectorTy->getPointerTo(AMDGPUAS::PRIVATE_ADDRESS);
5290b57cec5SDimitry Andric       Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
5300b57cec5SDimitry Andric       Value *VecValue = Builder.CreateLoad(VectorTy, BitCast);
5315ffd83dbSDimitry Andric       Value *Elt = SI->getValueOperand();
5325ffd83dbSDimitry Andric       if (Elt->getType() != VecEltTy)
5335ffd83dbSDimitry Andric         Elt = Builder.CreateBitOrPointerCast(Elt, VecEltTy);
5345ffd83dbSDimitry Andric       Value *NewVecValue = Builder.CreateInsertElement(VecValue, Elt, Index);
5350b57cec5SDimitry Andric       Builder.CreateStore(NewVecValue, BitCast);
5360b57cec5SDimitry Andric       Inst->eraseFromParent();
5370b57cec5SDimitry Andric       break;
5380b57cec5SDimitry Andric     }
5390b57cec5SDimitry Andric 
5400b57cec5SDimitry Andric     default:
5410b57cec5SDimitry Andric       llvm_unreachable("Inconsistency in instructions promotable to vector");
5420b57cec5SDimitry Andric     }
5430b57cec5SDimitry Andric   }
5440b57cec5SDimitry Andric   return true;
5450b57cec5SDimitry Andric }
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric static bool isCallPromotable(CallInst *CI) {
5480b57cec5SDimitry Andric   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
5490b57cec5SDimitry Andric   if (!II)
5500b57cec5SDimitry Andric     return false;
5510b57cec5SDimitry Andric 
5520b57cec5SDimitry Andric   switch (II->getIntrinsicID()) {
5530b57cec5SDimitry Andric   case Intrinsic::memcpy:
5540b57cec5SDimitry Andric   case Intrinsic::memmove:
5550b57cec5SDimitry Andric   case Intrinsic::memset:
5560b57cec5SDimitry Andric   case Intrinsic::lifetime_start:
5570b57cec5SDimitry Andric   case Intrinsic::lifetime_end:
5580b57cec5SDimitry Andric   case Intrinsic::invariant_start:
5590b57cec5SDimitry Andric   case Intrinsic::invariant_end:
5600b57cec5SDimitry Andric   case Intrinsic::launder_invariant_group:
5610b57cec5SDimitry Andric   case Intrinsic::strip_invariant_group:
5620b57cec5SDimitry Andric   case Intrinsic::objectsize:
5630b57cec5SDimitry Andric     return true;
5640b57cec5SDimitry Andric   default:
5650b57cec5SDimitry Andric     return false;
5660b57cec5SDimitry Andric   }
5670b57cec5SDimitry Andric }
5680b57cec5SDimitry Andric 
569*e8d8bef9SDimitry Andric bool AMDGPUPromoteAllocaImpl::binaryOpIsDerivedFromSameAlloca(
570*e8d8bef9SDimitry Andric     Value *BaseAlloca, Value *Val, Instruction *Inst, int OpIdx0,
5710b57cec5SDimitry Andric     int OpIdx1) const {
5720b57cec5SDimitry Andric   // Figure out which operand is the one we might not be promoting.
5730b57cec5SDimitry Andric   Value *OtherOp = Inst->getOperand(OpIdx0);
5740b57cec5SDimitry Andric   if (Val == OtherOp)
5750b57cec5SDimitry Andric     OtherOp = Inst->getOperand(OpIdx1);
5760b57cec5SDimitry Andric 
5770b57cec5SDimitry Andric   if (isa<ConstantPointerNull>(OtherOp))
5780b57cec5SDimitry Andric     return true;
5790b57cec5SDimitry Andric 
580*e8d8bef9SDimitry Andric   Value *OtherObj = getUnderlyingObject(OtherOp);
5810b57cec5SDimitry Andric   if (!isa<AllocaInst>(OtherObj))
5820b57cec5SDimitry Andric     return false;
5830b57cec5SDimitry Andric 
5840b57cec5SDimitry Andric   // TODO: We should be able to replace undefs with the right pointer type.
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric   // TODO: If we know the other base object is another promotable
5870b57cec5SDimitry Andric   // alloca, not necessarily this alloca, we can do this. The
5880b57cec5SDimitry Andric   // important part is both must have the same address space at
5890b57cec5SDimitry Andric   // the end.
5900b57cec5SDimitry Andric   if (OtherObj != BaseAlloca) {
5910b57cec5SDimitry Andric     LLVM_DEBUG(
5920b57cec5SDimitry Andric         dbgs() << "Found a binary instruction with another alloca object\n");
5930b57cec5SDimitry Andric     return false;
5940b57cec5SDimitry Andric   }
5950b57cec5SDimitry Andric 
5960b57cec5SDimitry Andric   return true;
5970b57cec5SDimitry Andric }
5980b57cec5SDimitry Andric 
599*e8d8bef9SDimitry Andric bool AMDGPUPromoteAllocaImpl::collectUsesWithPtrTypes(
600*e8d8bef9SDimitry Andric     Value *BaseAlloca, Value *Val, std::vector<Value *> &WorkList) const {
6010b57cec5SDimitry Andric 
6020b57cec5SDimitry Andric   for (User *User : Val->users()) {
6030b57cec5SDimitry Andric     if (is_contained(WorkList, User))
6040b57cec5SDimitry Andric       continue;
6050b57cec5SDimitry Andric 
6060b57cec5SDimitry Andric     if (CallInst *CI = dyn_cast<CallInst>(User)) {
6070b57cec5SDimitry Andric       if (!isCallPromotable(CI))
6080b57cec5SDimitry Andric         return false;
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric       WorkList.push_back(User);
6110b57cec5SDimitry Andric       continue;
6120b57cec5SDimitry Andric     }
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric     Instruction *UseInst = cast<Instruction>(User);
6150b57cec5SDimitry Andric     if (UseInst->getOpcode() == Instruction::PtrToInt)
6160b57cec5SDimitry Andric       return false;
6170b57cec5SDimitry Andric 
6180b57cec5SDimitry Andric     if (LoadInst *LI = dyn_cast<LoadInst>(UseInst)) {
6190b57cec5SDimitry Andric       if (LI->isVolatile())
6200b57cec5SDimitry Andric         return false;
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric       continue;
6230b57cec5SDimitry Andric     }
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric     if (StoreInst *SI = dyn_cast<StoreInst>(UseInst)) {
6260b57cec5SDimitry Andric       if (SI->isVolatile())
6270b57cec5SDimitry Andric         return false;
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric       // Reject if the stored value is not the pointer operand.
6300b57cec5SDimitry Andric       if (SI->getPointerOperand() != Val)
6310b57cec5SDimitry Andric         return false;
6320b57cec5SDimitry Andric     } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UseInst)) {
6330b57cec5SDimitry Andric       if (RMW->isVolatile())
6340b57cec5SDimitry Andric         return false;
6350b57cec5SDimitry Andric     } else if (AtomicCmpXchgInst *CAS = dyn_cast<AtomicCmpXchgInst>(UseInst)) {
6360b57cec5SDimitry Andric       if (CAS->isVolatile())
6370b57cec5SDimitry Andric         return false;
6380b57cec5SDimitry Andric     }
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric     // Only promote a select if we know that the other select operand
6410b57cec5SDimitry Andric     // is from another pointer that will also be promoted.
6420b57cec5SDimitry Andric     if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
6430b57cec5SDimitry Andric       if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, ICmp, 0, 1))
6440b57cec5SDimitry Andric         return false;
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric       // May need to rewrite constant operands.
6470b57cec5SDimitry Andric       WorkList.push_back(ICmp);
6480b57cec5SDimitry Andric     }
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric     if (UseInst->getOpcode() == Instruction::AddrSpaceCast) {
6510b57cec5SDimitry Andric       // Give up if the pointer may be captured.
6520b57cec5SDimitry Andric       if (PointerMayBeCaptured(UseInst, true, true))
6530b57cec5SDimitry Andric         return false;
6540b57cec5SDimitry Andric       // Don't collect the users of this.
6550b57cec5SDimitry Andric       WorkList.push_back(User);
6560b57cec5SDimitry Andric       continue;
6570b57cec5SDimitry Andric     }
6580b57cec5SDimitry Andric 
6590b57cec5SDimitry Andric     if (!User->getType()->isPointerTy())
6600b57cec5SDimitry Andric       continue;
6610b57cec5SDimitry Andric 
6620b57cec5SDimitry Andric     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UseInst)) {
6630b57cec5SDimitry Andric       // Be conservative if an address could be computed outside the bounds of
6640b57cec5SDimitry Andric       // the alloca.
6650b57cec5SDimitry Andric       if (!GEP->isInBounds())
6660b57cec5SDimitry Andric         return false;
6670b57cec5SDimitry Andric     }
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric     // Only promote a select if we know that the other select operand is from
6700b57cec5SDimitry Andric     // another pointer that will also be promoted.
6710b57cec5SDimitry Andric     if (SelectInst *SI = dyn_cast<SelectInst>(UseInst)) {
6720b57cec5SDimitry Andric       if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, SI, 1, 2))
6730b57cec5SDimitry Andric         return false;
6740b57cec5SDimitry Andric     }
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric     // Repeat for phis.
6770b57cec5SDimitry Andric     if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
6780b57cec5SDimitry Andric       // TODO: Handle more complex cases. We should be able to replace loops
6790b57cec5SDimitry Andric       // over arrays.
6800b57cec5SDimitry Andric       switch (Phi->getNumIncomingValues()) {
6810b57cec5SDimitry Andric       case 1:
6820b57cec5SDimitry Andric         break;
6830b57cec5SDimitry Andric       case 2:
6840b57cec5SDimitry Andric         if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, Phi, 0, 1))
6850b57cec5SDimitry Andric           return false;
6860b57cec5SDimitry Andric         break;
6870b57cec5SDimitry Andric       default:
6880b57cec5SDimitry Andric         return false;
6890b57cec5SDimitry Andric       }
6900b57cec5SDimitry Andric     }
6910b57cec5SDimitry Andric 
6920b57cec5SDimitry Andric     WorkList.push_back(User);
6930b57cec5SDimitry Andric     if (!collectUsesWithPtrTypes(BaseAlloca, User, WorkList))
6940b57cec5SDimitry Andric       return false;
6950b57cec5SDimitry Andric   }
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric   return true;
6980b57cec5SDimitry Andric }
6990b57cec5SDimitry Andric 
700*e8d8bef9SDimitry Andric bool AMDGPUPromoteAllocaImpl::hasSufficientLocalMem(const Function &F) {
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric   FunctionType *FTy = F.getFunctionType();
703*e8d8bef9SDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(TM, F);
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric   // If the function has any arguments in the local address space, then it's
7060b57cec5SDimitry Andric   // possible these arguments require the entire local memory space, so
7070b57cec5SDimitry Andric   // we cannot use local memory in the pass.
7080b57cec5SDimitry Andric   for (Type *ParamTy : FTy->params()) {
7090b57cec5SDimitry Andric     PointerType *PtrTy = dyn_cast<PointerType>(ParamTy);
7100b57cec5SDimitry Andric     if (PtrTy && PtrTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
7110b57cec5SDimitry Andric       LocalMemLimit = 0;
7120b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Function has local memory argument. Promoting to "
7130b57cec5SDimitry Andric                            "local memory disabled.\n");
7140b57cec5SDimitry Andric       return false;
7150b57cec5SDimitry Andric     }
7160b57cec5SDimitry Andric   }
7170b57cec5SDimitry Andric 
7180b57cec5SDimitry Andric   LocalMemLimit = ST.getLocalMemorySize();
7190b57cec5SDimitry Andric   if (LocalMemLimit == 0)
7200b57cec5SDimitry Andric     return false;
7210b57cec5SDimitry Andric 
722*e8d8bef9SDimitry Andric   SmallVector<const Constant *, 16> Stack;
723*e8d8bef9SDimitry Andric   SmallPtrSet<const Constant *, 8> VisitedConstants;
724*e8d8bef9SDimitry Andric   SmallPtrSet<const GlobalVariable *, 8> UsedLDS;
7250b57cec5SDimitry Andric 
726*e8d8bef9SDimitry Andric   auto visitUsers = [&](const GlobalVariable *GV, const Constant *Val) -> bool {
727*e8d8bef9SDimitry Andric     for (const User *U : Val->users()) {
728*e8d8bef9SDimitry Andric       if (const Instruction *Use = dyn_cast<Instruction>(U)) {
729*e8d8bef9SDimitry Andric         if (Use->getParent()->getParent() == &F)
730*e8d8bef9SDimitry Andric           return true;
731*e8d8bef9SDimitry Andric       } else {
732*e8d8bef9SDimitry Andric         const Constant *C = cast<Constant>(U);
733*e8d8bef9SDimitry Andric         if (VisitedConstants.insert(C).second)
734*e8d8bef9SDimitry Andric           Stack.push_back(C);
735*e8d8bef9SDimitry Andric       }
736*e8d8bef9SDimitry Andric     }
737*e8d8bef9SDimitry Andric 
738*e8d8bef9SDimitry Andric     return false;
739*e8d8bef9SDimitry Andric   };
740*e8d8bef9SDimitry Andric 
7410b57cec5SDimitry Andric   for (GlobalVariable &GV : Mod->globals()) {
742480093f4SDimitry Andric     if (GV.getAddressSpace() != AMDGPUAS::LOCAL_ADDRESS)
7430b57cec5SDimitry Andric       continue;
7440b57cec5SDimitry Andric 
745*e8d8bef9SDimitry Andric     if (visitUsers(&GV, &GV)) {
746*e8d8bef9SDimitry Andric       UsedLDS.insert(&GV);
747*e8d8bef9SDimitry Andric       Stack.clear();
7480b57cec5SDimitry Andric       continue;
749*e8d8bef9SDimitry Andric     }
7500b57cec5SDimitry Andric 
751*e8d8bef9SDimitry Andric     // For any ConstantExpr uses, we need to recursively search the users until
752*e8d8bef9SDimitry Andric     // we see a function.
753*e8d8bef9SDimitry Andric     while (!Stack.empty()) {
754*e8d8bef9SDimitry Andric       const Constant *C = Stack.pop_back_val();
755*e8d8bef9SDimitry Andric       if (visitUsers(&GV, C)) {
756*e8d8bef9SDimitry Andric         UsedLDS.insert(&GV);
757*e8d8bef9SDimitry Andric         Stack.clear();
7580b57cec5SDimitry Andric         break;
7590b57cec5SDimitry Andric       }
7600b57cec5SDimitry Andric     }
7610b57cec5SDimitry Andric   }
7620b57cec5SDimitry Andric 
763*e8d8bef9SDimitry Andric   const DataLayout &DL = Mod->getDataLayout();
764*e8d8bef9SDimitry Andric   SmallVector<std::pair<uint64_t, Align>, 16> AllocatedSizes;
765*e8d8bef9SDimitry Andric   AllocatedSizes.reserve(UsedLDS.size());
766*e8d8bef9SDimitry Andric 
767*e8d8bef9SDimitry Andric   for (const GlobalVariable *GV : UsedLDS) {
768*e8d8bef9SDimitry Andric     Align Alignment =
769*e8d8bef9SDimitry Andric         DL.getValueOrABITypeAlignment(GV->getAlign(), GV->getValueType());
770*e8d8bef9SDimitry Andric     uint64_t AllocSize = DL.getTypeAllocSize(GV->getValueType());
771*e8d8bef9SDimitry Andric     AllocatedSizes.emplace_back(AllocSize, Alignment);
772*e8d8bef9SDimitry Andric   }
773*e8d8bef9SDimitry Andric 
774*e8d8bef9SDimitry Andric   // Sort to try to estimate the worst case alignment padding
775*e8d8bef9SDimitry Andric   //
776*e8d8bef9SDimitry Andric   // FIXME: We should really do something to fix the addresses to a more optimal
777*e8d8bef9SDimitry Andric   // value instead
778*e8d8bef9SDimitry Andric   llvm::sort(AllocatedSizes, [](std::pair<uint64_t, Align> LHS,
779*e8d8bef9SDimitry Andric                                 std::pair<uint64_t, Align> RHS) {
780*e8d8bef9SDimitry Andric     return LHS.second < RHS.second;
781*e8d8bef9SDimitry Andric   });
782*e8d8bef9SDimitry Andric 
783*e8d8bef9SDimitry Andric   // Check how much local memory is being used by global objects
784*e8d8bef9SDimitry Andric   CurrentLocalMemUsage = 0;
785*e8d8bef9SDimitry Andric 
786*e8d8bef9SDimitry Andric   // FIXME: Try to account for padding here. The real padding and address is
787*e8d8bef9SDimitry Andric   // currently determined from the inverse order of uses in the function when
788*e8d8bef9SDimitry Andric   // legalizing, which could also potentially change. We try to estimate the
789*e8d8bef9SDimitry Andric   // worst case here, but we probably should fix the addresses earlier.
790*e8d8bef9SDimitry Andric   for (auto Alloc : AllocatedSizes) {
791*e8d8bef9SDimitry Andric     CurrentLocalMemUsage = alignTo(CurrentLocalMemUsage, Alloc.second);
792*e8d8bef9SDimitry Andric     CurrentLocalMemUsage += Alloc.first;
793*e8d8bef9SDimitry Andric   }
794*e8d8bef9SDimitry Andric 
7950b57cec5SDimitry Andric   unsigned MaxOccupancy = ST.getOccupancyWithLocalMemSize(CurrentLocalMemUsage,
7960b57cec5SDimitry Andric                                                           F);
7970b57cec5SDimitry Andric 
7980b57cec5SDimitry Andric   // Restrict local memory usage so that we don't drastically reduce occupancy,
7990b57cec5SDimitry Andric   // unless it is already significantly reduced.
8000b57cec5SDimitry Andric 
8010b57cec5SDimitry Andric   // TODO: Have some sort of hint or other heuristics to guess occupancy based
8020b57cec5SDimitry Andric   // on other factors..
8030b57cec5SDimitry Andric   unsigned OccupancyHint = ST.getWavesPerEU(F).second;
8040b57cec5SDimitry Andric   if (OccupancyHint == 0)
8050b57cec5SDimitry Andric     OccupancyHint = 7;
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric   // Clamp to max value.
8080b57cec5SDimitry Andric   OccupancyHint = std::min(OccupancyHint, ST.getMaxWavesPerEU());
8090b57cec5SDimitry Andric 
8100b57cec5SDimitry Andric   // Check the hint but ignore it if it's obviously wrong from the existing LDS
8110b57cec5SDimitry Andric   // usage.
8120b57cec5SDimitry Andric   MaxOccupancy = std::min(OccupancyHint, MaxOccupancy);
8130b57cec5SDimitry Andric 
8140b57cec5SDimitry Andric 
8150b57cec5SDimitry Andric   // Round up to the next tier of usage.
8160b57cec5SDimitry Andric   unsigned MaxSizeWithWaveCount
8170b57cec5SDimitry Andric     = ST.getMaxLocalMemSizeWithWaveCount(MaxOccupancy, F);
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric   // Program is possibly broken by using more local mem than available.
8200b57cec5SDimitry Andric   if (CurrentLocalMemUsage > MaxSizeWithWaveCount)
8210b57cec5SDimitry Andric     return false;
8220b57cec5SDimitry Andric 
8230b57cec5SDimitry Andric   LocalMemLimit = MaxSizeWithWaveCount;
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << F.getName() << " uses " << CurrentLocalMemUsage
8260b57cec5SDimitry Andric                     << " bytes of LDS\n"
8270b57cec5SDimitry Andric                     << "  Rounding size to " << MaxSizeWithWaveCount
8280b57cec5SDimitry Andric                     << " with a maximum occupancy of " << MaxOccupancy << '\n'
8290b57cec5SDimitry Andric                     << " and " << (LocalMemLimit - CurrentLocalMemUsage)
8300b57cec5SDimitry Andric                     << " available for promotion\n");
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric   return true;
8330b57cec5SDimitry Andric }
8340b57cec5SDimitry Andric 
8350b57cec5SDimitry Andric // FIXME: Should try to pick the most likely to be profitable allocas first.
836*e8d8bef9SDimitry Andric bool AMDGPUPromoteAllocaImpl::handleAlloca(AllocaInst &I, bool SufficientLDS) {
8370b57cec5SDimitry Andric   // Array allocations are probably not worth handling, since an allocation of
8380b57cec5SDimitry Andric   // the array type is the canonical form.
8390b57cec5SDimitry Andric   if (!I.isStaticAlloca() || I.isArrayAllocation())
8400b57cec5SDimitry Andric     return false;
8410b57cec5SDimitry Andric 
8425ffd83dbSDimitry Andric   const DataLayout &DL = Mod->getDataLayout();
8430b57cec5SDimitry Andric   IRBuilder<> Builder(&I);
8440b57cec5SDimitry Andric 
8450b57cec5SDimitry Andric   // First try to replace the alloca with a vector
8460b57cec5SDimitry Andric   Type *AllocaTy = I.getAllocatedType();
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Trying to promote " << I << '\n');
8490b57cec5SDimitry Andric 
8505ffd83dbSDimitry Andric   if (tryPromoteAllocaToVector(&I, DL, MaxVGPRs))
8510b57cec5SDimitry Andric     return true; // Promoted to vector.
8520b57cec5SDimitry Andric 
8530b57cec5SDimitry Andric   if (DisablePromoteAllocaToLDS)
8540b57cec5SDimitry Andric     return false;
8550b57cec5SDimitry Andric 
8560b57cec5SDimitry Andric   const Function &ContainingFunction = *I.getParent()->getParent();
8570b57cec5SDimitry Andric   CallingConv::ID CC = ContainingFunction.getCallingConv();
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric   // Don't promote the alloca to LDS for shader calling conventions as the work
8600b57cec5SDimitry Andric   // item ID intrinsics are not supported for these calling conventions.
8610b57cec5SDimitry Andric   // Furthermore not all LDS is available for some of the stages.
8620b57cec5SDimitry Andric   switch (CC) {
8630b57cec5SDimitry Andric   case CallingConv::AMDGPU_KERNEL:
8640b57cec5SDimitry Andric   case CallingConv::SPIR_KERNEL:
8650b57cec5SDimitry Andric     break;
8660b57cec5SDimitry Andric   default:
8670b57cec5SDimitry Andric     LLVM_DEBUG(
8680b57cec5SDimitry Andric         dbgs()
8690b57cec5SDimitry Andric         << " promote alloca to LDS not supported with calling convention.\n");
8700b57cec5SDimitry Andric     return false;
8710b57cec5SDimitry Andric   }
8720b57cec5SDimitry Andric 
8730b57cec5SDimitry Andric   // Not likely to have sufficient local memory for promotion.
8740b57cec5SDimitry Andric   if (!SufficientLDS)
8750b57cec5SDimitry Andric     return false;
8760b57cec5SDimitry Andric 
877*e8d8bef9SDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(TM, ContainingFunction);
8780b57cec5SDimitry Andric   unsigned WorkGroupSize = ST.getFlatWorkGroupSizes(ContainingFunction).second;
8790b57cec5SDimitry Andric 
8805ffd83dbSDimitry Andric   Align Alignment =
8815ffd83dbSDimitry Andric       DL.getValueOrABITypeAlignment(I.getAlign(), I.getAllocatedType());
8820b57cec5SDimitry Andric 
8830b57cec5SDimitry Andric   // FIXME: This computed padding is likely wrong since it depends on inverse
8840b57cec5SDimitry Andric   // usage order.
8850b57cec5SDimitry Andric   //
8860b57cec5SDimitry Andric   // FIXME: It is also possible that if we're allowed to use all of the memory
8870b57cec5SDimitry Andric   // could could end up using more than the maximum due to alignment padding.
8880b57cec5SDimitry Andric 
8895ffd83dbSDimitry Andric   uint32_t NewSize = alignTo(CurrentLocalMemUsage, Alignment);
8900b57cec5SDimitry Andric   uint32_t AllocSize = WorkGroupSize * DL.getTypeAllocSize(AllocaTy);
8910b57cec5SDimitry Andric   NewSize += AllocSize;
8920b57cec5SDimitry Andric 
8930b57cec5SDimitry Andric   if (NewSize > LocalMemLimit) {
8940b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  " << AllocSize
8950b57cec5SDimitry Andric                       << " bytes of local memory not available to promote\n");
8960b57cec5SDimitry Andric     return false;
8970b57cec5SDimitry Andric   }
8980b57cec5SDimitry Andric 
8990b57cec5SDimitry Andric   CurrentLocalMemUsage = NewSize;
9000b57cec5SDimitry Andric 
9010b57cec5SDimitry Andric   std::vector<Value*> WorkList;
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric   if (!collectUsesWithPtrTypes(&I, &I, WorkList)) {
9040b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " Do not know how to convert all uses\n");
9050b57cec5SDimitry Andric     return false;
9060b57cec5SDimitry Andric   }
9070b57cec5SDimitry Andric 
9080b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Promoting alloca to local memory\n");
9090b57cec5SDimitry Andric 
9100b57cec5SDimitry Andric   Function *F = I.getParent()->getParent();
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric   Type *GVTy = ArrayType::get(I.getAllocatedType(), WorkGroupSize);
9130b57cec5SDimitry Andric   GlobalVariable *GV = new GlobalVariable(
9140b57cec5SDimitry Andric       *Mod, GVTy, false, GlobalValue::InternalLinkage,
9150b57cec5SDimitry Andric       UndefValue::get(GVTy),
9160b57cec5SDimitry Andric       Twine(F->getName()) + Twine('.') + I.getName(),
9170b57cec5SDimitry Andric       nullptr,
9180b57cec5SDimitry Andric       GlobalVariable::NotThreadLocal,
9190b57cec5SDimitry Andric       AMDGPUAS::LOCAL_ADDRESS);
9200b57cec5SDimitry Andric   GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
9218bcb0991SDimitry Andric   GV->setAlignment(MaybeAlign(I.getAlignment()));
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric   Value *TCntY, *TCntZ;
9240b57cec5SDimitry Andric 
9250b57cec5SDimitry Andric   std::tie(TCntY, TCntZ) = getLocalSizeYZ(Builder);
9260b57cec5SDimitry Andric   Value *TIdX = getWorkitemID(Builder, 0);
9270b57cec5SDimitry Andric   Value *TIdY = getWorkitemID(Builder, 1);
9280b57cec5SDimitry Andric   Value *TIdZ = getWorkitemID(Builder, 2);
9290b57cec5SDimitry Andric 
9300b57cec5SDimitry Andric   Value *Tmp0 = Builder.CreateMul(TCntY, TCntZ, "", true, true);
9310b57cec5SDimitry Andric   Tmp0 = Builder.CreateMul(Tmp0, TIdX);
9320b57cec5SDimitry Andric   Value *Tmp1 = Builder.CreateMul(TIdY, TCntZ, "", true, true);
9330b57cec5SDimitry Andric   Value *TID = Builder.CreateAdd(Tmp0, Tmp1);
9340b57cec5SDimitry Andric   TID = Builder.CreateAdd(TID, TIdZ);
9350b57cec5SDimitry Andric 
9360b57cec5SDimitry Andric   Value *Indices[] = {
9370b57cec5SDimitry Andric     Constant::getNullValue(Type::getInt32Ty(Mod->getContext())),
9380b57cec5SDimitry Andric     TID
9390b57cec5SDimitry Andric   };
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric   Value *Offset = Builder.CreateInBoundsGEP(GVTy, GV, Indices);
9420b57cec5SDimitry Andric   I.mutateType(Offset->getType());
9430b57cec5SDimitry Andric   I.replaceAllUsesWith(Offset);
9440b57cec5SDimitry Andric   I.eraseFromParent();
9450b57cec5SDimitry Andric 
9460b57cec5SDimitry Andric   for (Value *V : WorkList) {
9470b57cec5SDimitry Andric     CallInst *Call = dyn_cast<CallInst>(V);
9480b57cec5SDimitry Andric     if (!Call) {
9490b57cec5SDimitry Andric       if (ICmpInst *CI = dyn_cast<ICmpInst>(V)) {
9500b57cec5SDimitry Andric         Value *Src0 = CI->getOperand(0);
9510b57cec5SDimitry Andric         Type *EltTy = Src0->getType()->getPointerElementType();
9520b57cec5SDimitry Andric         PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
9530b57cec5SDimitry Andric 
9540b57cec5SDimitry Andric         if (isa<ConstantPointerNull>(CI->getOperand(0)))
9550b57cec5SDimitry Andric           CI->setOperand(0, ConstantPointerNull::get(NewTy));
9560b57cec5SDimitry Andric 
9570b57cec5SDimitry Andric         if (isa<ConstantPointerNull>(CI->getOperand(1)))
9580b57cec5SDimitry Andric           CI->setOperand(1, ConstantPointerNull::get(NewTy));
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric         continue;
9610b57cec5SDimitry Andric       }
9620b57cec5SDimitry Andric 
9630b57cec5SDimitry Andric       // The operand's value should be corrected on its own and we don't want to
9640b57cec5SDimitry Andric       // touch the users.
9650b57cec5SDimitry Andric       if (isa<AddrSpaceCastInst>(V))
9660b57cec5SDimitry Andric         continue;
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric       Type *EltTy = V->getType()->getPointerElementType();
9690b57cec5SDimitry Andric       PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
9700b57cec5SDimitry Andric 
9710b57cec5SDimitry Andric       // FIXME: It doesn't really make sense to try to do this for all
9720b57cec5SDimitry Andric       // instructions.
9730b57cec5SDimitry Andric       V->mutateType(NewTy);
9740b57cec5SDimitry Andric 
9750b57cec5SDimitry Andric       // Adjust the types of any constant operands.
9760b57cec5SDimitry Andric       if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
9770b57cec5SDimitry Andric         if (isa<ConstantPointerNull>(SI->getOperand(1)))
9780b57cec5SDimitry Andric           SI->setOperand(1, ConstantPointerNull::get(NewTy));
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric         if (isa<ConstantPointerNull>(SI->getOperand(2)))
9810b57cec5SDimitry Andric           SI->setOperand(2, ConstantPointerNull::get(NewTy));
9820b57cec5SDimitry Andric       } else if (PHINode *Phi = dyn_cast<PHINode>(V)) {
9830b57cec5SDimitry Andric         for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
9840b57cec5SDimitry Andric           if (isa<ConstantPointerNull>(Phi->getIncomingValue(I)))
9850b57cec5SDimitry Andric             Phi->setIncomingValue(I, ConstantPointerNull::get(NewTy));
9860b57cec5SDimitry Andric         }
9870b57cec5SDimitry Andric       }
9880b57cec5SDimitry Andric 
9890b57cec5SDimitry Andric       continue;
9900b57cec5SDimitry Andric     }
9910b57cec5SDimitry Andric 
9920b57cec5SDimitry Andric     IntrinsicInst *Intr = cast<IntrinsicInst>(Call);
9930b57cec5SDimitry Andric     Builder.SetInsertPoint(Intr);
9940b57cec5SDimitry Andric     switch (Intr->getIntrinsicID()) {
9950b57cec5SDimitry Andric     case Intrinsic::lifetime_start:
9960b57cec5SDimitry Andric     case Intrinsic::lifetime_end:
9970b57cec5SDimitry Andric       // These intrinsics are for address space 0 only
9980b57cec5SDimitry Andric       Intr->eraseFromParent();
9990b57cec5SDimitry Andric       continue;
10000b57cec5SDimitry Andric     case Intrinsic::memcpy: {
10010b57cec5SDimitry Andric       MemCpyInst *MemCpy = cast<MemCpyInst>(Intr);
1002480093f4SDimitry Andric       Builder.CreateMemCpy(MemCpy->getRawDest(), MemCpy->getDestAlign(),
1003480093f4SDimitry Andric                            MemCpy->getRawSource(), MemCpy->getSourceAlign(),
10040b57cec5SDimitry Andric                            MemCpy->getLength(), MemCpy->isVolatile());
10050b57cec5SDimitry Andric       Intr->eraseFromParent();
10060b57cec5SDimitry Andric       continue;
10070b57cec5SDimitry Andric     }
10080b57cec5SDimitry Andric     case Intrinsic::memmove: {
10090b57cec5SDimitry Andric       MemMoveInst *MemMove = cast<MemMoveInst>(Intr);
1010480093f4SDimitry Andric       Builder.CreateMemMove(MemMove->getRawDest(), MemMove->getDestAlign(),
1011480093f4SDimitry Andric                             MemMove->getRawSource(), MemMove->getSourceAlign(),
10120b57cec5SDimitry Andric                             MemMove->getLength(), MemMove->isVolatile());
10130b57cec5SDimitry Andric       Intr->eraseFromParent();
10140b57cec5SDimitry Andric       continue;
10150b57cec5SDimitry Andric     }
10160b57cec5SDimitry Andric     case Intrinsic::memset: {
10170b57cec5SDimitry Andric       MemSetInst *MemSet = cast<MemSetInst>(Intr);
1018480093f4SDimitry Andric       Builder.CreateMemSet(
1019480093f4SDimitry Andric           MemSet->getRawDest(), MemSet->getValue(), MemSet->getLength(),
1020480093f4SDimitry Andric           MaybeAlign(MemSet->getDestAlignment()), MemSet->isVolatile());
10210b57cec5SDimitry Andric       Intr->eraseFromParent();
10220b57cec5SDimitry Andric       continue;
10230b57cec5SDimitry Andric     }
10240b57cec5SDimitry Andric     case Intrinsic::invariant_start:
10250b57cec5SDimitry Andric     case Intrinsic::invariant_end:
10260b57cec5SDimitry Andric     case Intrinsic::launder_invariant_group:
10270b57cec5SDimitry Andric     case Intrinsic::strip_invariant_group:
10280b57cec5SDimitry Andric       Intr->eraseFromParent();
10290b57cec5SDimitry Andric       // FIXME: I think the invariant marker should still theoretically apply,
10300b57cec5SDimitry Andric       // but the intrinsics need to be changed to accept pointers with any
10310b57cec5SDimitry Andric       // address space.
10320b57cec5SDimitry Andric       continue;
10330b57cec5SDimitry Andric     case Intrinsic::objectsize: {
10340b57cec5SDimitry Andric       Value *Src = Intr->getOperand(0);
10350b57cec5SDimitry Andric       Type *SrcTy = Src->getType()->getPointerElementType();
10360b57cec5SDimitry Andric       Function *ObjectSize = Intrinsic::getDeclaration(Mod,
10370b57cec5SDimitry Andric         Intrinsic::objectsize,
10380b57cec5SDimitry Andric         { Intr->getType(), PointerType::get(SrcTy, AMDGPUAS::LOCAL_ADDRESS) }
10390b57cec5SDimitry Andric       );
10400b57cec5SDimitry Andric 
10410b57cec5SDimitry Andric       CallInst *NewCall = Builder.CreateCall(
10420b57cec5SDimitry Andric           ObjectSize,
10430b57cec5SDimitry Andric           {Src, Intr->getOperand(1), Intr->getOperand(2), Intr->getOperand(3)});
10440b57cec5SDimitry Andric       Intr->replaceAllUsesWith(NewCall);
10450b57cec5SDimitry Andric       Intr->eraseFromParent();
10460b57cec5SDimitry Andric       continue;
10470b57cec5SDimitry Andric     }
10480b57cec5SDimitry Andric     default:
10490b57cec5SDimitry Andric       Intr->print(errs());
10500b57cec5SDimitry Andric       llvm_unreachable("Don't know how to promote alloca intrinsic use.");
10510b57cec5SDimitry Andric     }
10520b57cec5SDimitry Andric   }
10530b57cec5SDimitry Andric   return true;
10540b57cec5SDimitry Andric }
10550b57cec5SDimitry Andric 
1056*e8d8bef9SDimitry Andric bool handlePromoteAllocaToVector(AllocaInst &I, unsigned MaxVGPRs) {
1057*e8d8bef9SDimitry Andric   // Array allocations are probably not worth handling, since an allocation of
1058*e8d8bef9SDimitry Andric   // the array type is the canonical form.
1059*e8d8bef9SDimitry Andric   if (!I.isStaticAlloca() || I.isArrayAllocation())
10605ffd83dbSDimitry Andric     return false;
10615ffd83dbSDimitry Andric 
1062*e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Trying to promote " << I << '\n');
1063*e8d8bef9SDimitry Andric 
1064*e8d8bef9SDimitry Andric   Module *Mod = I.getParent()->getParent()->getParent();
1065*e8d8bef9SDimitry Andric   return tryPromoteAllocaToVector(&I, Mod->getDataLayout(), MaxVGPRs);
1066*e8d8bef9SDimitry Andric }
1067*e8d8bef9SDimitry Andric 
1068*e8d8bef9SDimitry Andric bool promoteAllocasToVector(Function &F, TargetMachine &TM) {
1069*e8d8bef9SDimitry Andric   if (DisablePromoteAllocaToVector)
10705ffd83dbSDimitry Andric     return false;
10715ffd83dbSDimitry Andric 
1072*e8d8bef9SDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(TM, F);
10735ffd83dbSDimitry Andric   if (!ST.isPromoteAllocaEnabled())
10745ffd83dbSDimitry Andric     return false;
10755ffd83dbSDimitry Andric 
1076*e8d8bef9SDimitry Andric   unsigned MaxVGPRs;
1077*e8d8bef9SDimitry Andric   if (TM.getTargetTriple().getArch() == Triple::amdgcn) {
1078*e8d8bef9SDimitry Andric     const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(F);
10795ffd83dbSDimitry Andric     MaxVGPRs = ST.getMaxNumVGPRs(ST.getWavesPerEU(F).first);
10805ffd83dbSDimitry Andric   } else {
10815ffd83dbSDimitry Andric     MaxVGPRs = 128;
10825ffd83dbSDimitry Andric   }
10835ffd83dbSDimitry Andric 
10845ffd83dbSDimitry Andric   bool Changed = false;
10855ffd83dbSDimitry Andric   BasicBlock &EntryBB = *F.begin();
10865ffd83dbSDimitry Andric 
10875ffd83dbSDimitry Andric   SmallVector<AllocaInst *, 16> Allocas;
10885ffd83dbSDimitry Andric   for (Instruction &I : EntryBB) {
10895ffd83dbSDimitry Andric     if (AllocaInst *AI = dyn_cast<AllocaInst>(&I))
10905ffd83dbSDimitry Andric       Allocas.push_back(AI);
10915ffd83dbSDimitry Andric   }
10925ffd83dbSDimitry Andric 
10935ffd83dbSDimitry Andric   for (AllocaInst *AI : Allocas) {
1094*e8d8bef9SDimitry Andric     if (handlePromoteAllocaToVector(*AI, MaxVGPRs))
10955ffd83dbSDimitry Andric       Changed = true;
10965ffd83dbSDimitry Andric   }
10975ffd83dbSDimitry Andric 
10985ffd83dbSDimitry Andric   return Changed;
10995ffd83dbSDimitry Andric }
11005ffd83dbSDimitry Andric 
1101*e8d8bef9SDimitry Andric bool AMDGPUPromoteAllocaToVector::runOnFunction(Function &F) {
1102*e8d8bef9SDimitry Andric   if (skipFunction(F))
11035ffd83dbSDimitry Andric     return false;
1104*e8d8bef9SDimitry Andric   if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
1105*e8d8bef9SDimitry Andric     return promoteAllocasToVector(F, TPC->getTM<TargetMachine>());
1106*e8d8bef9SDimitry Andric   }
1107*e8d8bef9SDimitry Andric   return false;
1108*e8d8bef9SDimitry Andric }
11095ffd83dbSDimitry Andric 
1110*e8d8bef9SDimitry Andric PreservedAnalyses
1111*e8d8bef9SDimitry Andric AMDGPUPromoteAllocaToVectorPass::run(Function &F, FunctionAnalysisManager &AM) {
1112*e8d8bef9SDimitry Andric   bool Changed = promoteAllocasToVector(F, TM);
1113*e8d8bef9SDimitry Andric   if (Changed) {
1114*e8d8bef9SDimitry Andric     PreservedAnalyses PA;
1115*e8d8bef9SDimitry Andric     PA.preserveSet<CFGAnalyses>();
1116*e8d8bef9SDimitry Andric     return PA;
1117*e8d8bef9SDimitry Andric   }
1118*e8d8bef9SDimitry Andric   return PreservedAnalyses::all();
11195ffd83dbSDimitry Andric }
11205ffd83dbSDimitry Andric 
11210b57cec5SDimitry Andric FunctionPass *llvm::createAMDGPUPromoteAlloca() {
11220b57cec5SDimitry Andric   return new AMDGPUPromoteAlloca();
11230b57cec5SDimitry Andric }
11245ffd83dbSDimitry Andric 
11255ffd83dbSDimitry Andric FunctionPass *llvm::createAMDGPUPromoteAllocaToVector() {
11265ffd83dbSDimitry Andric   return new AMDGPUPromoteAllocaToVector();
11275ffd83dbSDimitry Andric }
1128