xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPromoteAlloca.cpp (revision 8bcb0991864975618c09697b1aca10683346d9f0)
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"
150b57cec5SDimitry Andric #include "AMDGPUSubtarget.h"
160b57cec5SDimitry Andric #include "Utils/AMDGPUBaseInfo.h"
170b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
180b57cec5SDimitry Andric #include "llvm/ADT/None.h"
190b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
200b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
210b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
220b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/CaptureTracking.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
260b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
270b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
280b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
290b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
300b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
310b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
320b57cec5SDimitry Andric #include "llvm/IR/Function.h"
330b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
340b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
350b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
360b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
370b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
380b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
390b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
400b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
410b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
420b57cec5SDimitry Andric #include "llvm/IR/Module.h"
430b57cec5SDimitry Andric #include "llvm/IR/Type.h"
440b57cec5SDimitry Andric #include "llvm/IR/User.h"
450b57cec5SDimitry Andric #include "llvm/IR/Value.h"
460b57cec5SDimitry Andric #include "llvm/Pass.h"
470b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
480b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
490b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
500b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
510b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
520b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
530b57cec5SDimitry Andric #include <algorithm>
540b57cec5SDimitry Andric #include <cassert>
550b57cec5SDimitry Andric #include <cstdint>
560b57cec5SDimitry Andric #include <map>
570b57cec5SDimitry Andric #include <tuple>
580b57cec5SDimitry Andric #include <utility>
590b57cec5SDimitry Andric #include <vector>
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric #define DEBUG_TYPE "amdgpu-promote-alloca"
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric using namespace llvm;
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric namespace {
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric static cl::opt<bool> DisablePromoteAllocaToVector(
680b57cec5SDimitry Andric   "disable-promote-alloca-to-vector",
690b57cec5SDimitry Andric   cl::desc("Disable promote alloca to vector"),
700b57cec5SDimitry Andric   cl::init(false));
710b57cec5SDimitry Andric 
720b57cec5SDimitry Andric static cl::opt<bool> DisablePromoteAllocaToLDS(
730b57cec5SDimitry Andric   "disable-promote-alloca-to-lds",
740b57cec5SDimitry Andric   cl::desc("Disable promote alloca to LDS"),
750b57cec5SDimitry Andric   cl::init(false));
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric // FIXME: This can create globals so should be a module pass.
780b57cec5SDimitry Andric class AMDGPUPromoteAlloca : public FunctionPass {
790b57cec5SDimitry Andric private:
800b57cec5SDimitry Andric   const TargetMachine *TM;
810b57cec5SDimitry Andric   Module *Mod = nullptr;
820b57cec5SDimitry Andric   const DataLayout *DL = nullptr;
830b57cec5SDimitry Andric 
840b57cec5SDimitry Andric   // FIXME: This should be per-kernel.
850b57cec5SDimitry Andric   uint32_t LocalMemLimit = 0;
860b57cec5SDimitry Andric   uint32_t CurrentLocalMemUsage = 0;
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric   bool IsAMDGCN = false;
890b57cec5SDimitry Andric   bool IsAMDHSA = false;
900b57cec5SDimitry Andric 
910b57cec5SDimitry Andric   std::pair<Value *, Value *> getLocalSizeYZ(IRBuilder<> &Builder);
920b57cec5SDimitry Andric   Value *getWorkitemID(IRBuilder<> &Builder, unsigned N);
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric   /// BaseAlloca is the alloca root the search started from.
950b57cec5SDimitry Andric   /// Val may be that alloca or a recursive user of it.
960b57cec5SDimitry Andric   bool collectUsesWithPtrTypes(Value *BaseAlloca,
970b57cec5SDimitry Andric                                Value *Val,
980b57cec5SDimitry Andric                                std::vector<Value*> &WorkList) const;
990b57cec5SDimitry Andric 
1000b57cec5SDimitry Andric   /// Val is a derived pointer from Alloca. OpIdx0/OpIdx1 are the operand
1010b57cec5SDimitry Andric   /// indices to an instruction with 2 pointer inputs (e.g. select, icmp).
1020b57cec5SDimitry Andric   /// Returns true if both operands are derived from the same alloca. Val should
1030b57cec5SDimitry Andric   /// be the same value as one of the input operands of UseInst.
1040b57cec5SDimitry Andric   bool binaryOpIsDerivedFromSameAlloca(Value *Alloca, Value *Val,
1050b57cec5SDimitry Andric                                        Instruction *UseInst,
1060b57cec5SDimitry Andric                                        int OpIdx0, int OpIdx1) const;
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric   /// Check whether we have enough local memory for promotion.
1090b57cec5SDimitry Andric   bool hasSufficientLocalMem(const Function &F);
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric public:
1120b57cec5SDimitry Andric   static char ID;
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric   AMDGPUPromoteAlloca() : FunctionPass(ID) {}
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric   bool doInitialization(Module &M) override;
1170b57cec5SDimitry Andric   bool runOnFunction(Function &F) override;
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric   StringRef getPassName() const override { return "AMDGPU Promote Alloca"; }
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric   bool handleAlloca(AllocaInst &I, bool SufficientLDS);
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
1240b57cec5SDimitry Andric     AU.setPreservesCFG();
1250b57cec5SDimitry Andric     FunctionPass::getAnalysisUsage(AU);
1260b57cec5SDimitry Andric   }
1270b57cec5SDimitry Andric };
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric } // end anonymous namespace
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric char AMDGPUPromoteAlloca::ID = 0;
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric INITIALIZE_PASS(AMDGPUPromoteAlloca, DEBUG_TYPE,
1340b57cec5SDimitry Andric                 "AMDGPU promote alloca to vector or LDS", false, false)
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric char &llvm::AMDGPUPromoteAllocaID = AMDGPUPromoteAlloca::ID;
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric bool AMDGPUPromoteAlloca::doInitialization(Module &M) {
1390b57cec5SDimitry Andric   Mod = &M;
1400b57cec5SDimitry Andric   DL = &Mod->getDataLayout();
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric   return false;
1430b57cec5SDimitry Andric }
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric bool AMDGPUPromoteAlloca::runOnFunction(Function &F) {
1460b57cec5SDimitry Andric   if (skipFunction(F))
1470b57cec5SDimitry Andric     return false;
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric   if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>())
1500b57cec5SDimitry Andric     TM = &TPC->getTM<TargetMachine>();
1510b57cec5SDimitry Andric   else
1520b57cec5SDimitry Andric     return false;
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric   const Triple &TT = TM->getTargetTriple();
1550b57cec5SDimitry Andric   IsAMDGCN = TT.getArch() == Triple::amdgcn;
1560b57cec5SDimitry Andric   IsAMDHSA = TT.getOS() == Triple::AMDHSA;
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(*TM, F);
1590b57cec5SDimitry Andric   if (!ST.isPromoteAllocaEnabled())
1600b57cec5SDimitry Andric     return false;
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric   bool SufficientLDS = hasSufficientLocalMem(F);
1630b57cec5SDimitry Andric   bool Changed = false;
1640b57cec5SDimitry Andric   BasicBlock &EntryBB = *F.begin();
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric   SmallVector<AllocaInst *, 16> Allocas;
1670b57cec5SDimitry Andric   for (Instruction &I : EntryBB) {
1680b57cec5SDimitry Andric     if (AllocaInst *AI = dyn_cast<AllocaInst>(&I))
1690b57cec5SDimitry Andric       Allocas.push_back(AI);
1700b57cec5SDimitry Andric   }
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric   for (AllocaInst *AI : Allocas) {
1730b57cec5SDimitry Andric     if (handleAlloca(*AI, SufficientLDS))
1740b57cec5SDimitry Andric       Changed = true;
1750b57cec5SDimitry Andric   }
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric   return Changed;
1780b57cec5SDimitry Andric }
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric std::pair<Value *, Value *>
1810b57cec5SDimitry Andric AMDGPUPromoteAlloca::getLocalSizeYZ(IRBuilder<> &Builder) {
1820b57cec5SDimitry Andric   const Function &F = *Builder.GetInsertBlock()->getParent();
1830b57cec5SDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(*TM, F);
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric   if (!IsAMDHSA) {
1860b57cec5SDimitry Andric     Function *LocalSizeYFn
1870b57cec5SDimitry Andric       = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_y);
1880b57cec5SDimitry Andric     Function *LocalSizeZFn
1890b57cec5SDimitry Andric       = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_z);
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric     CallInst *LocalSizeY = Builder.CreateCall(LocalSizeYFn, {});
1920b57cec5SDimitry Andric     CallInst *LocalSizeZ = Builder.CreateCall(LocalSizeZFn, {});
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric     ST.makeLIDRangeMetadata(LocalSizeY);
1950b57cec5SDimitry Andric     ST.makeLIDRangeMetadata(LocalSizeZ);
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric     return std::make_pair(LocalSizeY, LocalSizeZ);
1980b57cec5SDimitry Andric   }
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric   // We must read the size out of the dispatch pointer.
2010b57cec5SDimitry Andric   assert(IsAMDGCN);
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric   // We are indexing into this struct, and want to extract the workgroup_size_*
2040b57cec5SDimitry Andric   // fields.
2050b57cec5SDimitry Andric   //
2060b57cec5SDimitry Andric   //   typedef struct hsa_kernel_dispatch_packet_s {
2070b57cec5SDimitry Andric   //     uint16_t header;
2080b57cec5SDimitry Andric   //     uint16_t setup;
2090b57cec5SDimitry Andric   //     uint16_t workgroup_size_x ;
2100b57cec5SDimitry Andric   //     uint16_t workgroup_size_y;
2110b57cec5SDimitry Andric   //     uint16_t workgroup_size_z;
2120b57cec5SDimitry Andric   //     uint16_t reserved0;
2130b57cec5SDimitry Andric   //     uint32_t grid_size_x ;
2140b57cec5SDimitry Andric   //     uint32_t grid_size_y ;
2150b57cec5SDimitry Andric   //     uint32_t grid_size_z;
2160b57cec5SDimitry Andric   //
2170b57cec5SDimitry Andric   //     uint32_t private_segment_size;
2180b57cec5SDimitry Andric   //     uint32_t group_segment_size;
2190b57cec5SDimitry Andric   //     uint64_t kernel_object;
2200b57cec5SDimitry Andric   //
2210b57cec5SDimitry Andric   // #ifdef HSA_LARGE_MODEL
2220b57cec5SDimitry Andric   //     void *kernarg_address;
2230b57cec5SDimitry Andric   // #elif defined HSA_LITTLE_ENDIAN
2240b57cec5SDimitry Andric   //     void *kernarg_address;
2250b57cec5SDimitry Andric   //     uint32_t reserved1;
2260b57cec5SDimitry Andric   // #else
2270b57cec5SDimitry Andric   //     uint32_t reserved1;
2280b57cec5SDimitry Andric   //     void *kernarg_address;
2290b57cec5SDimitry Andric   // #endif
2300b57cec5SDimitry Andric   //     uint64_t reserved2;
2310b57cec5SDimitry Andric   //     hsa_signal_t completion_signal; // uint64_t wrapper
2320b57cec5SDimitry Andric   //   } hsa_kernel_dispatch_packet_t
2330b57cec5SDimitry Andric   //
2340b57cec5SDimitry Andric   Function *DispatchPtrFn
2350b57cec5SDimitry Andric     = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_dispatch_ptr);
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric   CallInst *DispatchPtr = Builder.CreateCall(DispatchPtrFn, {});
2380b57cec5SDimitry Andric   DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
2390b57cec5SDimitry Andric   DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
2400b57cec5SDimitry Andric 
2410b57cec5SDimitry Andric   // Size of the dispatch packet struct.
2420b57cec5SDimitry Andric   DispatchPtr->addDereferenceableAttr(AttributeList::ReturnIndex, 64);
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric   Type *I32Ty = Type::getInt32Ty(Mod->getContext());
2450b57cec5SDimitry Andric   Value *CastDispatchPtr = Builder.CreateBitCast(
2460b57cec5SDimitry Andric     DispatchPtr, PointerType::get(I32Ty, AMDGPUAS::CONSTANT_ADDRESS));
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric   // We could do a single 64-bit load here, but it's likely that the basic
2490b57cec5SDimitry Andric   // 32-bit and extract sequence is already present, and it is probably easier
2500b57cec5SDimitry Andric   // to CSE this. The loads should be mergable later anyway.
2510b57cec5SDimitry Andric   Value *GEPXY = Builder.CreateConstInBoundsGEP1_64(I32Ty, CastDispatchPtr, 1);
2520b57cec5SDimitry Andric   LoadInst *LoadXY = Builder.CreateAlignedLoad(I32Ty, GEPXY, 4);
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric   Value *GEPZU = Builder.CreateConstInBoundsGEP1_64(I32Ty, CastDispatchPtr, 2);
2550b57cec5SDimitry Andric   LoadInst *LoadZU = Builder.CreateAlignedLoad(I32Ty, GEPZU, 4);
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric   MDNode *MD = MDNode::get(Mod->getContext(), None);
2580b57cec5SDimitry Andric   LoadXY->setMetadata(LLVMContext::MD_invariant_load, MD);
2590b57cec5SDimitry Andric   LoadZU->setMetadata(LLVMContext::MD_invariant_load, MD);
2600b57cec5SDimitry Andric   ST.makeLIDRangeMetadata(LoadZU);
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric   // Extract y component. Upper half of LoadZU should be zero already.
2630b57cec5SDimitry Andric   Value *Y = Builder.CreateLShr(LoadXY, 16);
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   return std::make_pair(Y, LoadZU);
2660b57cec5SDimitry Andric }
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric Value *AMDGPUPromoteAlloca::getWorkitemID(IRBuilder<> &Builder, unsigned N) {
2690b57cec5SDimitry Andric   const AMDGPUSubtarget &ST =
2700b57cec5SDimitry Andric       AMDGPUSubtarget::get(*TM, *Builder.GetInsertBlock()->getParent());
2710b57cec5SDimitry Andric   Intrinsic::ID IntrID = Intrinsic::ID::not_intrinsic;
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric   switch (N) {
2740b57cec5SDimitry Andric   case 0:
2750b57cec5SDimitry Andric     IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_x
2760b57cec5SDimitry Andric       : Intrinsic::r600_read_tidig_x;
2770b57cec5SDimitry Andric     break;
2780b57cec5SDimitry Andric   case 1:
2790b57cec5SDimitry Andric     IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_y
2800b57cec5SDimitry Andric       : Intrinsic::r600_read_tidig_y;
2810b57cec5SDimitry Andric     break;
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric   case 2:
2840b57cec5SDimitry Andric     IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_z
2850b57cec5SDimitry Andric       : Intrinsic::r600_read_tidig_z;
2860b57cec5SDimitry Andric     break;
2870b57cec5SDimitry Andric   default:
2880b57cec5SDimitry Andric     llvm_unreachable("invalid dimension");
2890b57cec5SDimitry Andric   }
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric   Function *WorkitemIdFn = Intrinsic::getDeclaration(Mod, IntrID);
2920b57cec5SDimitry Andric   CallInst *CI = Builder.CreateCall(WorkitemIdFn);
2930b57cec5SDimitry Andric   ST.makeLIDRangeMetadata(CI);
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric   return CI;
2960b57cec5SDimitry Andric }
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric static VectorType *arrayTypeToVecType(ArrayType *ArrayTy) {
2990b57cec5SDimitry Andric   return VectorType::get(ArrayTy->getElementType(),
3000b57cec5SDimitry Andric                          ArrayTy->getNumElements());
3010b57cec5SDimitry Andric }
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric static Value *
3040b57cec5SDimitry Andric calculateVectorIndex(Value *Ptr,
3050b57cec5SDimitry Andric                      const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
3060b57cec5SDimitry Andric   GetElementPtrInst *GEP = cast<GetElementPtrInst>(Ptr);
3070b57cec5SDimitry Andric 
3080b57cec5SDimitry Andric   auto I = GEPIdx.find(GEP);
3090b57cec5SDimitry Andric   return I == GEPIdx.end() ? nullptr : I->second;
3100b57cec5SDimitry Andric }
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric static Value* GEPToVectorIndex(GetElementPtrInst *GEP) {
3130b57cec5SDimitry Andric   // FIXME we only support simple cases
3140b57cec5SDimitry Andric   if (GEP->getNumOperands() != 3)
3150b57cec5SDimitry Andric     return nullptr;
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric   ConstantInt *I0 = dyn_cast<ConstantInt>(GEP->getOperand(1));
3180b57cec5SDimitry Andric   if (!I0 || !I0->isZero())
3190b57cec5SDimitry Andric     return nullptr;
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric   return GEP->getOperand(2);
3220b57cec5SDimitry Andric }
3230b57cec5SDimitry Andric 
3240b57cec5SDimitry Andric // Not an instruction handled below to turn into a vector.
3250b57cec5SDimitry Andric //
3260b57cec5SDimitry Andric // TODO: Check isTriviallyVectorizable for calls and handle other
3270b57cec5SDimitry Andric // instructions.
3280b57cec5SDimitry Andric static bool canVectorizeInst(Instruction *Inst, User *User) {
3290b57cec5SDimitry Andric   switch (Inst->getOpcode()) {
3300b57cec5SDimitry Andric   case Instruction::Load: {
3310b57cec5SDimitry Andric     // Currently only handle the case where the Pointer Operand is a GEP.
3320b57cec5SDimitry Andric     // Also we could not vectorize volatile or atomic loads.
3330b57cec5SDimitry Andric     LoadInst *LI = cast<LoadInst>(Inst);
3340b57cec5SDimitry Andric     if (isa<AllocaInst>(User) &&
3350b57cec5SDimitry Andric         LI->getPointerOperandType() == User->getType() &&
3360b57cec5SDimitry Andric         isa<VectorType>(LI->getType()))
3370b57cec5SDimitry Andric       return true;
3380b57cec5SDimitry Andric     return isa<GetElementPtrInst>(LI->getPointerOperand()) && LI->isSimple();
3390b57cec5SDimitry Andric   }
3400b57cec5SDimitry Andric   case Instruction::BitCast:
3410b57cec5SDimitry Andric     return true;
3420b57cec5SDimitry Andric   case Instruction::Store: {
3430b57cec5SDimitry Andric     // Must be the stored pointer operand, not a stored value, plus
3440b57cec5SDimitry Andric     // since it should be canonical form, the User should be a GEP.
3450b57cec5SDimitry Andric     // Also we could not vectorize volatile or atomic stores.
3460b57cec5SDimitry Andric     StoreInst *SI = cast<StoreInst>(Inst);
3470b57cec5SDimitry Andric     if (isa<AllocaInst>(User) &&
3480b57cec5SDimitry Andric         SI->getPointerOperandType() == User->getType() &&
3490b57cec5SDimitry Andric         isa<VectorType>(SI->getValueOperand()->getType()))
3500b57cec5SDimitry Andric       return true;
3510b57cec5SDimitry Andric     return (SI->getPointerOperand() == User) && isa<GetElementPtrInst>(User) && SI->isSimple();
3520b57cec5SDimitry Andric   }
3530b57cec5SDimitry Andric   default:
3540b57cec5SDimitry Andric     return false;
3550b57cec5SDimitry Andric   }
3560b57cec5SDimitry Andric }
3570b57cec5SDimitry Andric 
3580b57cec5SDimitry Andric static bool tryPromoteAllocaToVector(AllocaInst *Alloca) {
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric   if (DisablePromoteAllocaToVector) {
3610b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Promotion alloca to vector is disabled\n");
3620b57cec5SDimitry Andric     return false;
3630b57cec5SDimitry Andric   }
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric   Type *AT = Alloca->getAllocatedType();
3660b57cec5SDimitry Andric   SequentialType *AllocaTy = dyn_cast<SequentialType>(AT);
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Alloca candidate for vectorization\n");
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric   // FIXME: There is no reason why we can't support larger arrays, we
3710b57cec5SDimitry Andric   // are just being conservative for now.
3720b57cec5SDimitry Andric   // FIXME: We also reject alloca's of the form [ 2 x [ 2 x i32 ]] or equivalent. Potentially these
3730b57cec5SDimitry Andric   // could also be promoted but we don't currently handle this case
3740b57cec5SDimitry Andric   if (!AllocaTy ||
3750b57cec5SDimitry Andric       AllocaTy->getNumElements() > 16 ||
3760b57cec5SDimitry Andric       AllocaTy->getNumElements() < 2 ||
3770b57cec5SDimitry Andric       !VectorType::isValidElementType(AllocaTy->getElementType())) {
3780b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Cannot convert type to vector\n");
3790b57cec5SDimitry Andric     return false;
3800b57cec5SDimitry Andric   }
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric   std::map<GetElementPtrInst*, Value*> GEPVectorIdx;
3830b57cec5SDimitry Andric   std::vector<Value*> WorkList;
3840b57cec5SDimitry Andric   for (User *AllocaUser : Alloca->users()) {
3850b57cec5SDimitry Andric     GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(AllocaUser);
3860b57cec5SDimitry Andric     if (!GEP) {
3870b57cec5SDimitry Andric       if (!canVectorizeInst(cast<Instruction>(AllocaUser), Alloca))
3880b57cec5SDimitry Andric         return false;
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric       WorkList.push_back(AllocaUser);
3910b57cec5SDimitry Andric       continue;
3920b57cec5SDimitry Andric     }
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric     Value *Index = GEPToVectorIndex(GEP);
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric     // If we can't compute a vector index from this GEP, then we can't
3970b57cec5SDimitry Andric     // promote this alloca to vector.
3980b57cec5SDimitry Andric     if (!Index) {
3990b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  Cannot compute vector index for GEP " << *GEP
4000b57cec5SDimitry Andric                         << '\n');
4010b57cec5SDimitry Andric       return false;
4020b57cec5SDimitry Andric     }
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric     GEPVectorIdx[GEP] = Index;
4050b57cec5SDimitry Andric     for (User *GEPUser : AllocaUser->users()) {
4060b57cec5SDimitry Andric       if (!canVectorizeInst(cast<Instruction>(GEPUser), AllocaUser))
4070b57cec5SDimitry Andric         return false;
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric       WorkList.push_back(GEPUser);
4100b57cec5SDimitry Andric     }
4110b57cec5SDimitry Andric   }
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric   VectorType *VectorTy = dyn_cast<VectorType>(AllocaTy);
4140b57cec5SDimitry Andric   if (!VectorTy)
4150b57cec5SDimitry Andric     VectorTy = arrayTypeToVecType(cast<ArrayType>(AllocaTy));
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Converting alloca to vector " << *AllocaTy << " -> "
4180b57cec5SDimitry Andric                     << *VectorTy << '\n');
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric   for (Value *V : WorkList) {
4210b57cec5SDimitry Andric     Instruction *Inst = cast<Instruction>(V);
4220b57cec5SDimitry Andric     IRBuilder<> Builder(Inst);
4230b57cec5SDimitry Andric     switch (Inst->getOpcode()) {
4240b57cec5SDimitry Andric     case Instruction::Load: {
4250b57cec5SDimitry Andric       if (Inst->getType() == AT)
4260b57cec5SDimitry Andric         break;
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric       Type *VecPtrTy = VectorTy->getPointerTo(AMDGPUAS::PRIVATE_ADDRESS);
4290b57cec5SDimitry Andric       Value *Ptr = cast<LoadInst>(Inst)->getPointerOperand();
4300b57cec5SDimitry Andric       Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric       Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
4330b57cec5SDimitry Andric       Value *VecValue = Builder.CreateLoad(VectorTy, BitCast);
4340b57cec5SDimitry Andric       Value *ExtractElement = Builder.CreateExtractElement(VecValue, Index);
4350b57cec5SDimitry Andric       Inst->replaceAllUsesWith(ExtractElement);
4360b57cec5SDimitry Andric       Inst->eraseFromParent();
4370b57cec5SDimitry Andric       break;
4380b57cec5SDimitry Andric     }
4390b57cec5SDimitry Andric     case Instruction::Store: {
4400b57cec5SDimitry Andric       StoreInst *SI = cast<StoreInst>(Inst);
4410b57cec5SDimitry Andric       if (SI->getValueOperand()->getType() == AT)
4420b57cec5SDimitry Andric         break;
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric       Type *VecPtrTy = VectorTy->getPointerTo(AMDGPUAS::PRIVATE_ADDRESS);
4450b57cec5SDimitry Andric       Value *Ptr = SI->getPointerOperand();
4460b57cec5SDimitry Andric       Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
4470b57cec5SDimitry Andric       Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
4480b57cec5SDimitry Andric       Value *VecValue = Builder.CreateLoad(VectorTy, BitCast);
4490b57cec5SDimitry Andric       Value *NewVecValue = Builder.CreateInsertElement(VecValue,
4500b57cec5SDimitry Andric                                                        SI->getValueOperand(),
4510b57cec5SDimitry Andric                                                        Index);
4520b57cec5SDimitry Andric       Builder.CreateStore(NewVecValue, BitCast);
4530b57cec5SDimitry Andric       Inst->eraseFromParent();
4540b57cec5SDimitry Andric       break;
4550b57cec5SDimitry Andric     }
4560b57cec5SDimitry Andric     case Instruction::BitCast:
4570b57cec5SDimitry Andric     case Instruction::AddrSpaceCast:
4580b57cec5SDimitry Andric       break;
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric     default:
4610b57cec5SDimitry Andric       llvm_unreachable("Inconsistency in instructions promotable to vector");
4620b57cec5SDimitry Andric     }
4630b57cec5SDimitry Andric   }
4640b57cec5SDimitry Andric   return true;
4650b57cec5SDimitry Andric }
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric static bool isCallPromotable(CallInst *CI) {
4680b57cec5SDimitry Andric   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
4690b57cec5SDimitry Andric   if (!II)
4700b57cec5SDimitry Andric     return false;
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric   switch (II->getIntrinsicID()) {
4730b57cec5SDimitry Andric   case Intrinsic::memcpy:
4740b57cec5SDimitry Andric   case Intrinsic::memmove:
4750b57cec5SDimitry Andric   case Intrinsic::memset:
4760b57cec5SDimitry Andric   case Intrinsic::lifetime_start:
4770b57cec5SDimitry Andric   case Intrinsic::lifetime_end:
4780b57cec5SDimitry Andric   case Intrinsic::invariant_start:
4790b57cec5SDimitry Andric   case Intrinsic::invariant_end:
4800b57cec5SDimitry Andric   case Intrinsic::launder_invariant_group:
4810b57cec5SDimitry Andric   case Intrinsic::strip_invariant_group:
4820b57cec5SDimitry Andric   case Intrinsic::objectsize:
4830b57cec5SDimitry Andric     return true;
4840b57cec5SDimitry Andric   default:
4850b57cec5SDimitry Andric     return false;
4860b57cec5SDimitry Andric   }
4870b57cec5SDimitry Andric }
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric bool AMDGPUPromoteAlloca::binaryOpIsDerivedFromSameAlloca(Value *BaseAlloca,
4900b57cec5SDimitry Andric                                                           Value *Val,
4910b57cec5SDimitry Andric                                                           Instruction *Inst,
4920b57cec5SDimitry Andric                                                           int OpIdx0,
4930b57cec5SDimitry Andric                                                           int OpIdx1) const {
4940b57cec5SDimitry Andric   // Figure out which operand is the one we might not be promoting.
4950b57cec5SDimitry Andric   Value *OtherOp = Inst->getOperand(OpIdx0);
4960b57cec5SDimitry Andric   if (Val == OtherOp)
4970b57cec5SDimitry Andric     OtherOp = Inst->getOperand(OpIdx1);
4980b57cec5SDimitry Andric 
4990b57cec5SDimitry Andric   if (isa<ConstantPointerNull>(OtherOp))
5000b57cec5SDimitry Andric     return true;
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric   Value *OtherObj = GetUnderlyingObject(OtherOp, *DL);
5030b57cec5SDimitry Andric   if (!isa<AllocaInst>(OtherObj))
5040b57cec5SDimitry Andric     return false;
5050b57cec5SDimitry Andric 
5060b57cec5SDimitry Andric   // TODO: We should be able to replace undefs with the right pointer type.
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric   // TODO: If we know the other base object is another promotable
5090b57cec5SDimitry Andric   // alloca, not necessarily this alloca, we can do this. The
5100b57cec5SDimitry Andric   // important part is both must have the same address space at
5110b57cec5SDimitry Andric   // the end.
5120b57cec5SDimitry Andric   if (OtherObj != BaseAlloca) {
5130b57cec5SDimitry Andric     LLVM_DEBUG(
5140b57cec5SDimitry Andric         dbgs() << "Found a binary instruction with another alloca object\n");
5150b57cec5SDimitry Andric     return false;
5160b57cec5SDimitry Andric   }
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   return true;
5190b57cec5SDimitry Andric }
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric bool AMDGPUPromoteAlloca::collectUsesWithPtrTypes(
5220b57cec5SDimitry Andric   Value *BaseAlloca,
5230b57cec5SDimitry Andric   Value *Val,
5240b57cec5SDimitry Andric   std::vector<Value*> &WorkList) const {
5250b57cec5SDimitry Andric 
5260b57cec5SDimitry Andric   for (User *User : Val->users()) {
5270b57cec5SDimitry Andric     if (is_contained(WorkList, User))
5280b57cec5SDimitry Andric       continue;
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric     if (CallInst *CI = dyn_cast<CallInst>(User)) {
5310b57cec5SDimitry Andric       if (!isCallPromotable(CI))
5320b57cec5SDimitry Andric         return false;
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric       WorkList.push_back(User);
5350b57cec5SDimitry Andric       continue;
5360b57cec5SDimitry Andric     }
5370b57cec5SDimitry Andric 
5380b57cec5SDimitry Andric     Instruction *UseInst = cast<Instruction>(User);
5390b57cec5SDimitry Andric     if (UseInst->getOpcode() == Instruction::PtrToInt)
5400b57cec5SDimitry Andric       return false;
5410b57cec5SDimitry Andric 
5420b57cec5SDimitry Andric     if (LoadInst *LI = dyn_cast<LoadInst>(UseInst)) {
5430b57cec5SDimitry Andric       if (LI->isVolatile())
5440b57cec5SDimitry Andric         return false;
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric       continue;
5470b57cec5SDimitry Andric     }
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric     if (StoreInst *SI = dyn_cast<StoreInst>(UseInst)) {
5500b57cec5SDimitry Andric       if (SI->isVolatile())
5510b57cec5SDimitry Andric         return false;
5520b57cec5SDimitry Andric 
5530b57cec5SDimitry Andric       // Reject if the stored value is not the pointer operand.
5540b57cec5SDimitry Andric       if (SI->getPointerOperand() != Val)
5550b57cec5SDimitry Andric         return false;
5560b57cec5SDimitry Andric     } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UseInst)) {
5570b57cec5SDimitry Andric       if (RMW->isVolatile())
5580b57cec5SDimitry Andric         return false;
5590b57cec5SDimitry Andric     } else if (AtomicCmpXchgInst *CAS = dyn_cast<AtomicCmpXchgInst>(UseInst)) {
5600b57cec5SDimitry Andric       if (CAS->isVolatile())
5610b57cec5SDimitry Andric         return false;
5620b57cec5SDimitry Andric     }
5630b57cec5SDimitry Andric 
5640b57cec5SDimitry Andric     // Only promote a select if we know that the other select operand
5650b57cec5SDimitry Andric     // is from another pointer that will also be promoted.
5660b57cec5SDimitry Andric     if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
5670b57cec5SDimitry Andric       if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, ICmp, 0, 1))
5680b57cec5SDimitry Andric         return false;
5690b57cec5SDimitry Andric 
5700b57cec5SDimitry Andric       // May need to rewrite constant operands.
5710b57cec5SDimitry Andric       WorkList.push_back(ICmp);
5720b57cec5SDimitry Andric     }
5730b57cec5SDimitry Andric 
5740b57cec5SDimitry Andric     if (UseInst->getOpcode() == Instruction::AddrSpaceCast) {
5750b57cec5SDimitry Andric       // Give up if the pointer may be captured.
5760b57cec5SDimitry Andric       if (PointerMayBeCaptured(UseInst, true, true))
5770b57cec5SDimitry Andric         return false;
5780b57cec5SDimitry Andric       // Don't collect the users of this.
5790b57cec5SDimitry Andric       WorkList.push_back(User);
5800b57cec5SDimitry Andric       continue;
5810b57cec5SDimitry Andric     }
5820b57cec5SDimitry Andric 
5830b57cec5SDimitry Andric     if (!User->getType()->isPointerTy())
5840b57cec5SDimitry Andric       continue;
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UseInst)) {
5870b57cec5SDimitry Andric       // Be conservative if an address could be computed outside the bounds of
5880b57cec5SDimitry Andric       // the alloca.
5890b57cec5SDimitry Andric       if (!GEP->isInBounds())
5900b57cec5SDimitry Andric         return false;
5910b57cec5SDimitry Andric     }
5920b57cec5SDimitry Andric 
5930b57cec5SDimitry Andric     // Only promote a select if we know that the other select operand is from
5940b57cec5SDimitry Andric     // another pointer that will also be promoted.
5950b57cec5SDimitry Andric     if (SelectInst *SI = dyn_cast<SelectInst>(UseInst)) {
5960b57cec5SDimitry Andric       if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, SI, 1, 2))
5970b57cec5SDimitry Andric         return false;
5980b57cec5SDimitry Andric     }
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric     // Repeat for phis.
6010b57cec5SDimitry Andric     if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
6020b57cec5SDimitry Andric       // TODO: Handle more complex cases. We should be able to replace loops
6030b57cec5SDimitry Andric       // over arrays.
6040b57cec5SDimitry Andric       switch (Phi->getNumIncomingValues()) {
6050b57cec5SDimitry Andric       case 1:
6060b57cec5SDimitry Andric         break;
6070b57cec5SDimitry Andric       case 2:
6080b57cec5SDimitry Andric         if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, Phi, 0, 1))
6090b57cec5SDimitry Andric           return false;
6100b57cec5SDimitry Andric         break;
6110b57cec5SDimitry Andric       default:
6120b57cec5SDimitry Andric         return false;
6130b57cec5SDimitry Andric       }
6140b57cec5SDimitry Andric     }
6150b57cec5SDimitry Andric 
6160b57cec5SDimitry Andric     WorkList.push_back(User);
6170b57cec5SDimitry Andric     if (!collectUsesWithPtrTypes(BaseAlloca, User, WorkList))
6180b57cec5SDimitry Andric       return false;
6190b57cec5SDimitry Andric   }
6200b57cec5SDimitry Andric 
6210b57cec5SDimitry Andric   return true;
6220b57cec5SDimitry Andric }
6230b57cec5SDimitry Andric 
6240b57cec5SDimitry Andric bool AMDGPUPromoteAlloca::hasSufficientLocalMem(const Function &F) {
6250b57cec5SDimitry Andric 
6260b57cec5SDimitry Andric   FunctionType *FTy = F.getFunctionType();
6270b57cec5SDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(*TM, F);
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric   // If the function has any arguments in the local address space, then it's
6300b57cec5SDimitry Andric   // possible these arguments require the entire local memory space, so
6310b57cec5SDimitry Andric   // we cannot use local memory in the pass.
6320b57cec5SDimitry Andric   for (Type *ParamTy : FTy->params()) {
6330b57cec5SDimitry Andric     PointerType *PtrTy = dyn_cast<PointerType>(ParamTy);
6340b57cec5SDimitry Andric     if (PtrTy && PtrTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
6350b57cec5SDimitry Andric       LocalMemLimit = 0;
6360b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Function has local memory argument. Promoting to "
6370b57cec5SDimitry Andric                            "local memory disabled.\n");
6380b57cec5SDimitry Andric       return false;
6390b57cec5SDimitry Andric     }
6400b57cec5SDimitry Andric   }
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric   LocalMemLimit = ST.getLocalMemorySize();
6430b57cec5SDimitry Andric   if (LocalMemLimit == 0)
6440b57cec5SDimitry Andric     return false;
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric   const DataLayout &DL = Mod->getDataLayout();
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric   // Check how much local memory is being used by global objects
6490b57cec5SDimitry Andric   CurrentLocalMemUsage = 0;
6500b57cec5SDimitry Andric   for (GlobalVariable &GV : Mod->globals()) {
6510b57cec5SDimitry Andric     if (GV.getType()->getAddressSpace() != AMDGPUAS::LOCAL_ADDRESS)
6520b57cec5SDimitry Andric       continue;
6530b57cec5SDimitry Andric 
6540b57cec5SDimitry Andric     for (const User *U : GV.users()) {
6550b57cec5SDimitry Andric       const Instruction *Use = dyn_cast<Instruction>(U);
6560b57cec5SDimitry Andric       if (!Use)
6570b57cec5SDimitry Andric         continue;
6580b57cec5SDimitry Andric 
6590b57cec5SDimitry Andric       if (Use->getParent()->getParent() == &F) {
6600b57cec5SDimitry Andric         unsigned Align = GV.getAlignment();
6610b57cec5SDimitry Andric         if (Align == 0)
6620b57cec5SDimitry Andric           Align = DL.getABITypeAlignment(GV.getValueType());
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric         // FIXME: Try to account for padding here. The padding is currently
6650b57cec5SDimitry Andric         // determined from the inverse order of uses in the function. I'm not
6660b57cec5SDimitry Andric         // sure if the use list order is in any way connected to this, so the
6670b57cec5SDimitry Andric         // total reported size is likely incorrect.
6680b57cec5SDimitry Andric         uint64_t AllocSize = DL.getTypeAllocSize(GV.getValueType());
6690b57cec5SDimitry Andric         CurrentLocalMemUsage = alignTo(CurrentLocalMemUsage, Align);
6700b57cec5SDimitry Andric         CurrentLocalMemUsage += AllocSize;
6710b57cec5SDimitry Andric         break;
6720b57cec5SDimitry Andric       }
6730b57cec5SDimitry Andric     }
6740b57cec5SDimitry Andric   }
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric   unsigned MaxOccupancy = ST.getOccupancyWithLocalMemSize(CurrentLocalMemUsage,
6770b57cec5SDimitry Andric                                                           F);
6780b57cec5SDimitry Andric 
6790b57cec5SDimitry Andric   // Restrict local memory usage so that we don't drastically reduce occupancy,
6800b57cec5SDimitry Andric   // unless it is already significantly reduced.
6810b57cec5SDimitry Andric 
6820b57cec5SDimitry Andric   // TODO: Have some sort of hint or other heuristics to guess occupancy based
6830b57cec5SDimitry Andric   // on other factors..
6840b57cec5SDimitry Andric   unsigned OccupancyHint = ST.getWavesPerEU(F).second;
6850b57cec5SDimitry Andric   if (OccupancyHint == 0)
6860b57cec5SDimitry Andric     OccupancyHint = 7;
6870b57cec5SDimitry Andric 
6880b57cec5SDimitry Andric   // Clamp to max value.
6890b57cec5SDimitry Andric   OccupancyHint = std::min(OccupancyHint, ST.getMaxWavesPerEU());
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric   // Check the hint but ignore it if it's obviously wrong from the existing LDS
6920b57cec5SDimitry Andric   // usage.
6930b57cec5SDimitry Andric   MaxOccupancy = std::min(OccupancyHint, MaxOccupancy);
6940b57cec5SDimitry Andric 
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric   // Round up to the next tier of usage.
6970b57cec5SDimitry Andric   unsigned MaxSizeWithWaveCount
6980b57cec5SDimitry Andric     = ST.getMaxLocalMemSizeWithWaveCount(MaxOccupancy, F);
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric   // Program is possibly broken by using more local mem than available.
7010b57cec5SDimitry Andric   if (CurrentLocalMemUsage > MaxSizeWithWaveCount)
7020b57cec5SDimitry Andric     return false;
7030b57cec5SDimitry Andric 
7040b57cec5SDimitry Andric   LocalMemLimit = MaxSizeWithWaveCount;
7050b57cec5SDimitry Andric 
7060b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << F.getName() << " uses " << CurrentLocalMemUsage
7070b57cec5SDimitry Andric                     << " bytes of LDS\n"
7080b57cec5SDimitry Andric                     << "  Rounding size to " << MaxSizeWithWaveCount
7090b57cec5SDimitry Andric                     << " with a maximum occupancy of " << MaxOccupancy << '\n'
7100b57cec5SDimitry Andric                     << " and " << (LocalMemLimit - CurrentLocalMemUsage)
7110b57cec5SDimitry Andric                     << " available for promotion\n");
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric   return true;
7140b57cec5SDimitry Andric }
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric // FIXME: Should try to pick the most likely to be profitable allocas first.
7170b57cec5SDimitry Andric bool AMDGPUPromoteAlloca::handleAlloca(AllocaInst &I, bool SufficientLDS) {
7180b57cec5SDimitry Andric   // Array allocations are probably not worth handling, since an allocation of
7190b57cec5SDimitry Andric   // the array type is the canonical form.
7200b57cec5SDimitry Andric   if (!I.isStaticAlloca() || I.isArrayAllocation())
7210b57cec5SDimitry Andric     return false;
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric   IRBuilder<> Builder(&I);
7240b57cec5SDimitry Andric 
7250b57cec5SDimitry Andric   // First try to replace the alloca with a vector
7260b57cec5SDimitry Andric   Type *AllocaTy = I.getAllocatedType();
7270b57cec5SDimitry Andric 
7280b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Trying to promote " << I << '\n');
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric   if (tryPromoteAllocaToVector(&I))
7310b57cec5SDimitry Andric     return true; // Promoted to vector.
7320b57cec5SDimitry Andric 
7330b57cec5SDimitry Andric   if (DisablePromoteAllocaToLDS)
7340b57cec5SDimitry Andric     return false;
7350b57cec5SDimitry Andric 
7360b57cec5SDimitry Andric   const Function &ContainingFunction = *I.getParent()->getParent();
7370b57cec5SDimitry Andric   CallingConv::ID CC = ContainingFunction.getCallingConv();
7380b57cec5SDimitry Andric 
7390b57cec5SDimitry Andric   // Don't promote the alloca to LDS for shader calling conventions as the work
7400b57cec5SDimitry Andric   // item ID intrinsics are not supported for these calling conventions.
7410b57cec5SDimitry Andric   // Furthermore not all LDS is available for some of the stages.
7420b57cec5SDimitry Andric   switch (CC) {
7430b57cec5SDimitry Andric   case CallingConv::AMDGPU_KERNEL:
7440b57cec5SDimitry Andric   case CallingConv::SPIR_KERNEL:
7450b57cec5SDimitry Andric     break;
7460b57cec5SDimitry Andric   default:
7470b57cec5SDimitry Andric     LLVM_DEBUG(
7480b57cec5SDimitry Andric         dbgs()
7490b57cec5SDimitry Andric         << " promote alloca to LDS not supported with calling convention.\n");
7500b57cec5SDimitry Andric     return false;
7510b57cec5SDimitry Andric   }
7520b57cec5SDimitry Andric 
7530b57cec5SDimitry Andric   // Not likely to have sufficient local memory for promotion.
7540b57cec5SDimitry Andric   if (!SufficientLDS)
7550b57cec5SDimitry Andric     return false;
7560b57cec5SDimitry Andric 
7570b57cec5SDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(*TM, ContainingFunction);
7580b57cec5SDimitry Andric   unsigned WorkGroupSize = ST.getFlatWorkGroupSizes(ContainingFunction).second;
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric   const DataLayout &DL = Mod->getDataLayout();
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric   unsigned Align = I.getAlignment();
7630b57cec5SDimitry Andric   if (Align == 0)
7640b57cec5SDimitry Andric     Align = DL.getABITypeAlignment(I.getAllocatedType());
7650b57cec5SDimitry Andric 
7660b57cec5SDimitry Andric   // FIXME: This computed padding is likely wrong since it depends on inverse
7670b57cec5SDimitry Andric   // usage order.
7680b57cec5SDimitry Andric   //
7690b57cec5SDimitry Andric   // FIXME: It is also possible that if we're allowed to use all of the memory
7700b57cec5SDimitry Andric   // could could end up using more than the maximum due to alignment padding.
7710b57cec5SDimitry Andric 
7720b57cec5SDimitry Andric   uint32_t NewSize = alignTo(CurrentLocalMemUsage, Align);
7730b57cec5SDimitry Andric   uint32_t AllocSize = WorkGroupSize * DL.getTypeAllocSize(AllocaTy);
7740b57cec5SDimitry Andric   NewSize += AllocSize;
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric   if (NewSize > LocalMemLimit) {
7770b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  " << AllocSize
7780b57cec5SDimitry Andric                       << " bytes of local memory not available to promote\n");
7790b57cec5SDimitry Andric     return false;
7800b57cec5SDimitry Andric   }
7810b57cec5SDimitry Andric 
7820b57cec5SDimitry Andric   CurrentLocalMemUsage = NewSize;
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric   std::vector<Value*> WorkList;
7850b57cec5SDimitry Andric 
7860b57cec5SDimitry Andric   if (!collectUsesWithPtrTypes(&I, &I, WorkList)) {
7870b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " Do not know how to convert all uses\n");
7880b57cec5SDimitry Andric     return false;
7890b57cec5SDimitry Andric   }
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Promoting alloca to local memory\n");
7920b57cec5SDimitry Andric 
7930b57cec5SDimitry Andric   Function *F = I.getParent()->getParent();
7940b57cec5SDimitry Andric 
7950b57cec5SDimitry Andric   Type *GVTy = ArrayType::get(I.getAllocatedType(), WorkGroupSize);
7960b57cec5SDimitry Andric   GlobalVariable *GV = new GlobalVariable(
7970b57cec5SDimitry Andric       *Mod, GVTy, false, GlobalValue::InternalLinkage,
7980b57cec5SDimitry Andric       UndefValue::get(GVTy),
7990b57cec5SDimitry Andric       Twine(F->getName()) + Twine('.') + I.getName(),
8000b57cec5SDimitry Andric       nullptr,
8010b57cec5SDimitry Andric       GlobalVariable::NotThreadLocal,
8020b57cec5SDimitry Andric       AMDGPUAS::LOCAL_ADDRESS);
8030b57cec5SDimitry Andric   GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
804*8bcb0991SDimitry Andric   GV->setAlignment(MaybeAlign(I.getAlignment()));
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric   Value *TCntY, *TCntZ;
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric   std::tie(TCntY, TCntZ) = getLocalSizeYZ(Builder);
8090b57cec5SDimitry Andric   Value *TIdX = getWorkitemID(Builder, 0);
8100b57cec5SDimitry Andric   Value *TIdY = getWorkitemID(Builder, 1);
8110b57cec5SDimitry Andric   Value *TIdZ = getWorkitemID(Builder, 2);
8120b57cec5SDimitry Andric 
8130b57cec5SDimitry Andric   Value *Tmp0 = Builder.CreateMul(TCntY, TCntZ, "", true, true);
8140b57cec5SDimitry Andric   Tmp0 = Builder.CreateMul(Tmp0, TIdX);
8150b57cec5SDimitry Andric   Value *Tmp1 = Builder.CreateMul(TIdY, TCntZ, "", true, true);
8160b57cec5SDimitry Andric   Value *TID = Builder.CreateAdd(Tmp0, Tmp1);
8170b57cec5SDimitry Andric   TID = Builder.CreateAdd(TID, TIdZ);
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric   Value *Indices[] = {
8200b57cec5SDimitry Andric     Constant::getNullValue(Type::getInt32Ty(Mod->getContext())),
8210b57cec5SDimitry Andric     TID
8220b57cec5SDimitry Andric   };
8230b57cec5SDimitry Andric 
8240b57cec5SDimitry Andric   Value *Offset = Builder.CreateInBoundsGEP(GVTy, GV, Indices);
8250b57cec5SDimitry Andric   I.mutateType(Offset->getType());
8260b57cec5SDimitry Andric   I.replaceAllUsesWith(Offset);
8270b57cec5SDimitry Andric   I.eraseFromParent();
8280b57cec5SDimitry Andric 
8290b57cec5SDimitry Andric   for (Value *V : WorkList) {
8300b57cec5SDimitry Andric     CallInst *Call = dyn_cast<CallInst>(V);
8310b57cec5SDimitry Andric     if (!Call) {
8320b57cec5SDimitry Andric       if (ICmpInst *CI = dyn_cast<ICmpInst>(V)) {
8330b57cec5SDimitry Andric         Value *Src0 = CI->getOperand(0);
8340b57cec5SDimitry Andric         Type *EltTy = Src0->getType()->getPointerElementType();
8350b57cec5SDimitry Andric         PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric         if (isa<ConstantPointerNull>(CI->getOperand(0)))
8380b57cec5SDimitry Andric           CI->setOperand(0, ConstantPointerNull::get(NewTy));
8390b57cec5SDimitry Andric 
8400b57cec5SDimitry Andric         if (isa<ConstantPointerNull>(CI->getOperand(1)))
8410b57cec5SDimitry Andric           CI->setOperand(1, ConstantPointerNull::get(NewTy));
8420b57cec5SDimitry Andric 
8430b57cec5SDimitry Andric         continue;
8440b57cec5SDimitry Andric       }
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric       // The operand's value should be corrected on its own and we don't want to
8470b57cec5SDimitry Andric       // touch the users.
8480b57cec5SDimitry Andric       if (isa<AddrSpaceCastInst>(V))
8490b57cec5SDimitry Andric         continue;
8500b57cec5SDimitry Andric 
8510b57cec5SDimitry Andric       Type *EltTy = V->getType()->getPointerElementType();
8520b57cec5SDimitry Andric       PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
8530b57cec5SDimitry Andric 
8540b57cec5SDimitry Andric       // FIXME: It doesn't really make sense to try to do this for all
8550b57cec5SDimitry Andric       // instructions.
8560b57cec5SDimitry Andric       V->mutateType(NewTy);
8570b57cec5SDimitry Andric 
8580b57cec5SDimitry Andric       // Adjust the types of any constant operands.
8590b57cec5SDimitry Andric       if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
8600b57cec5SDimitry Andric         if (isa<ConstantPointerNull>(SI->getOperand(1)))
8610b57cec5SDimitry Andric           SI->setOperand(1, ConstantPointerNull::get(NewTy));
8620b57cec5SDimitry Andric 
8630b57cec5SDimitry Andric         if (isa<ConstantPointerNull>(SI->getOperand(2)))
8640b57cec5SDimitry Andric           SI->setOperand(2, ConstantPointerNull::get(NewTy));
8650b57cec5SDimitry Andric       } else if (PHINode *Phi = dyn_cast<PHINode>(V)) {
8660b57cec5SDimitry Andric         for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
8670b57cec5SDimitry Andric           if (isa<ConstantPointerNull>(Phi->getIncomingValue(I)))
8680b57cec5SDimitry Andric             Phi->setIncomingValue(I, ConstantPointerNull::get(NewTy));
8690b57cec5SDimitry Andric         }
8700b57cec5SDimitry Andric       }
8710b57cec5SDimitry Andric 
8720b57cec5SDimitry Andric       continue;
8730b57cec5SDimitry Andric     }
8740b57cec5SDimitry Andric 
8750b57cec5SDimitry Andric     IntrinsicInst *Intr = cast<IntrinsicInst>(Call);
8760b57cec5SDimitry Andric     Builder.SetInsertPoint(Intr);
8770b57cec5SDimitry Andric     switch (Intr->getIntrinsicID()) {
8780b57cec5SDimitry Andric     case Intrinsic::lifetime_start:
8790b57cec5SDimitry Andric     case Intrinsic::lifetime_end:
8800b57cec5SDimitry Andric       // These intrinsics are for address space 0 only
8810b57cec5SDimitry Andric       Intr->eraseFromParent();
8820b57cec5SDimitry Andric       continue;
8830b57cec5SDimitry Andric     case Intrinsic::memcpy: {
8840b57cec5SDimitry Andric       MemCpyInst *MemCpy = cast<MemCpyInst>(Intr);
8850b57cec5SDimitry Andric       Builder.CreateMemCpy(MemCpy->getRawDest(), MemCpy->getDestAlignment(),
8860b57cec5SDimitry Andric                            MemCpy->getRawSource(), MemCpy->getSourceAlignment(),
8870b57cec5SDimitry Andric                            MemCpy->getLength(), MemCpy->isVolatile());
8880b57cec5SDimitry Andric       Intr->eraseFromParent();
8890b57cec5SDimitry Andric       continue;
8900b57cec5SDimitry Andric     }
8910b57cec5SDimitry Andric     case Intrinsic::memmove: {
8920b57cec5SDimitry Andric       MemMoveInst *MemMove = cast<MemMoveInst>(Intr);
8930b57cec5SDimitry Andric       Builder.CreateMemMove(MemMove->getRawDest(), MemMove->getDestAlignment(),
8940b57cec5SDimitry Andric                             MemMove->getRawSource(), MemMove->getSourceAlignment(),
8950b57cec5SDimitry Andric                             MemMove->getLength(), MemMove->isVolatile());
8960b57cec5SDimitry Andric       Intr->eraseFromParent();
8970b57cec5SDimitry Andric       continue;
8980b57cec5SDimitry Andric     }
8990b57cec5SDimitry Andric     case Intrinsic::memset: {
9000b57cec5SDimitry Andric       MemSetInst *MemSet = cast<MemSetInst>(Intr);
9010b57cec5SDimitry Andric       Builder.CreateMemSet(MemSet->getRawDest(), MemSet->getValue(),
9020b57cec5SDimitry Andric                            MemSet->getLength(), MemSet->getDestAlignment(),
9030b57cec5SDimitry Andric                            MemSet->isVolatile());
9040b57cec5SDimitry Andric       Intr->eraseFromParent();
9050b57cec5SDimitry Andric       continue;
9060b57cec5SDimitry Andric     }
9070b57cec5SDimitry Andric     case Intrinsic::invariant_start:
9080b57cec5SDimitry Andric     case Intrinsic::invariant_end:
9090b57cec5SDimitry Andric     case Intrinsic::launder_invariant_group:
9100b57cec5SDimitry Andric     case Intrinsic::strip_invariant_group:
9110b57cec5SDimitry Andric       Intr->eraseFromParent();
9120b57cec5SDimitry Andric       // FIXME: I think the invariant marker should still theoretically apply,
9130b57cec5SDimitry Andric       // but the intrinsics need to be changed to accept pointers with any
9140b57cec5SDimitry Andric       // address space.
9150b57cec5SDimitry Andric       continue;
9160b57cec5SDimitry Andric     case Intrinsic::objectsize: {
9170b57cec5SDimitry Andric       Value *Src = Intr->getOperand(0);
9180b57cec5SDimitry Andric       Type *SrcTy = Src->getType()->getPointerElementType();
9190b57cec5SDimitry Andric       Function *ObjectSize = Intrinsic::getDeclaration(Mod,
9200b57cec5SDimitry Andric         Intrinsic::objectsize,
9210b57cec5SDimitry Andric         { Intr->getType(), PointerType::get(SrcTy, AMDGPUAS::LOCAL_ADDRESS) }
9220b57cec5SDimitry Andric       );
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric       CallInst *NewCall = Builder.CreateCall(
9250b57cec5SDimitry Andric           ObjectSize,
9260b57cec5SDimitry Andric           {Src, Intr->getOperand(1), Intr->getOperand(2), Intr->getOperand(3)});
9270b57cec5SDimitry Andric       Intr->replaceAllUsesWith(NewCall);
9280b57cec5SDimitry Andric       Intr->eraseFromParent();
9290b57cec5SDimitry Andric       continue;
9300b57cec5SDimitry Andric     }
9310b57cec5SDimitry Andric     default:
9320b57cec5SDimitry Andric       Intr->print(errs());
9330b57cec5SDimitry Andric       llvm_unreachable("Don't know how to promote alloca intrinsic use.");
9340b57cec5SDimitry Andric     }
9350b57cec5SDimitry Andric   }
9360b57cec5SDimitry Andric   return true;
9370b57cec5SDimitry Andric }
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric FunctionPass *llvm::createAMDGPUPromoteAlloca() {
9400b57cec5SDimitry Andric   return new AMDGPUPromoteAlloca();
9410b57cec5SDimitry Andric }
942