blob: bb7fa6bcb0e5a4d5f518a64009f68d2d8d9833c3 [file] [log] [blame]
Tom Stellard880a80a2014-06-17 16:53:14 +00001//===-- AMDGPUPromoteAlloca.cpp - Promote Allocas -------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass eliminates allocas by either converting them into vectors or
11// by migrating them to local address space.
12//
13//===----------------------------------------------------------------------===//
14
15#include "AMDGPU.h"
16#include "AMDGPUSubtarget.h"
17#include "llvm/Analysis/ValueTracking.h"
18#include "llvm/IR/IRBuilder.h"
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +000019#include "llvm/IR/IntrinsicInst.h"
Matt Arsenaulte0132462016-01-30 05:19:45 +000020#include "llvm/IR/MDBuilder.h"
Tom Stellard880a80a2014-06-17 16:53:14 +000021#include "llvm/Support/Debug.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000022#include "llvm/Support/raw_ostream.h"
Tom Stellard880a80a2014-06-17 16:53:14 +000023
24#define DEBUG_TYPE "amdgpu-promote-alloca"
25
26using namespace llvm;
27
28namespace {
29
Matt Arsenaulte0132462016-01-30 05:19:45 +000030// FIXME: This can create globals so should be a module pass.
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +000031class AMDGPUPromoteAlloca : public FunctionPass {
Matt Arsenaulte0132462016-01-30 05:19:45 +000032private:
33 const TargetMachine *TM;
Tom Stellard880a80a2014-06-17 16:53:14 +000034 Module *Mod;
Matt Arsenaulta61cb482016-05-12 01:58:58 +000035 const DataLayout *DL;
Matt Arsenaulte0132462016-01-30 05:19:45 +000036 MDNode *MaxWorkGroupSizeRange;
37
38 // FIXME: This should be per-kernel.
Matt Arsenault8a028bf2016-05-16 21:19:59 +000039 uint32_t LocalMemLimit;
40 uint32_t CurrentLocalMemUsage;
Tom Stellard880a80a2014-06-17 16:53:14 +000041
Matt Arsenaulte0132462016-01-30 05:19:45 +000042 bool IsAMDGCN;
43 bool IsAMDHSA;
44
45 std::pair<Value *, Value *> getLocalSizeYZ(IRBuilder<> &Builder);
46 Value *getWorkitemID(IRBuilder<> &Builder, unsigned N);
47
Matt Arsenaulta61cb482016-05-12 01:58:58 +000048 /// BaseAlloca is the alloca root the search started from.
49 /// Val may be that alloca or a recursive user of it.
50 bool collectUsesWithPtrTypes(Value *BaseAlloca,
51 Value *Val,
52 std::vector<Value*> &WorkList) const;
53
54 /// Val is a derived pointer from Alloca. OpIdx0/OpIdx1 are the operand
55 /// indices to an instruction with 2 pointer inputs (e.g. select, icmp).
56 /// Returns true if both operands are derived from the same alloca. Val should
57 /// be the same value as one of the input operands of UseInst.
58 bool binaryOpIsDerivedFromSameAlloca(Value *Alloca, Value *Val,
59 Instruction *UseInst,
60 int OpIdx0, int OpIdx1) const;
61
Tom Stellard880a80a2014-06-17 16:53:14 +000062public:
Matt Arsenaulte0132462016-01-30 05:19:45 +000063 static char ID;
64
65 AMDGPUPromoteAlloca(const TargetMachine *TM_ = nullptr) :
66 FunctionPass(ID),
67 TM(TM_),
68 Mod(nullptr),
Matt Arsenaulta61cb482016-05-12 01:58:58 +000069 DL(nullptr),
Matt Arsenaulte0132462016-01-30 05:19:45 +000070 MaxWorkGroupSizeRange(nullptr),
Matt Arsenault8a028bf2016-05-16 21:19:59 +000071 LocalMemLimit(0),
72 CurrentLocalMemUsage(0),
Matt Arsenaulte0132462016-01-30 05:19:45 +000073 IsAMDGCN(false),
74 IsAMDHSA(false) { }
75
Benjamin Kramer8c90fd72014-09-03 11:41:21 +000076 bool doInitialization(Module &M) override;
77 bool runOnFunction(Function &F) override;
Matt Arsenaulte0132462016-01-30 05:19:45 +000078
79 const char *getPassName() const override {
80 return "AMDGPU Promote Alloca";
81 }
82
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +000083 void handleAlloca(AllocaInst &I);
Matt Arsenaulta61cb482016-05-12 01:58:58 +000084
85 void getAnalysisUsage(AnalysisUsage &AU) const override {
86 AU.setPreservesCFG();
87 FunctionPass::getAnalysisUsage(AU);
88 }
Tom Stellard880a80a2014-06-17 16:53:14 +000089};
90
91} // End anonymous namespace
92
93char AMDGPUPromoteAlloca::ID = 0;
94
Matt Arsenaulte0132462016-01-30 05:19:45 +000095INITIALIZE_TM_PASS(AMDGPUPromoteAlloca, DEBUG_TYPE,
96 "AMDGPU promote alloca to vector or LDS", false, false)
97
98char &llvm::AMDGPUPromoteAllocaID = AMDGPUPromoteAlloca::ID;
99
100
Tom Stellard880a80a2014-06-17 16:53:14 +0000101bool AMDGPUPromoteAlloca::doInitialization(Module &M) {
Matt Arsenaulte0132462016-01-30 05:19:45 +0000102 if (!TM)
103 return false;
104
Tom Stellard880a80a2014-06-17 16:53:14 +0000105 Mod = &M;
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000106 DL = &Mod->getDataLayout();
Matt Arsenaulte0132462016-01-30 05:19:45 +0000107
108 // The maximum workitem id.
109 //
110 // FIXME: Should get as subtarget property. Usually runtime enforced max is
111 // 256.
112 MDBuilder MDB(Mod->getContext());
113 MaxWorkGroupSizeRange = MDB.createRange(APInt(32, 0), APInt(32, 2048));
114
115 const Triple &TT = TM->getTargetTriple();
116
117 IsAMDGCN = TT.getArch() == Triple::amdgcn;
118 IsAMDHSA = TT.getOS() == Triple::AMDHSA;
119
Tom Stellard880a80a2014-06-17 16:53:14 +0000120 return false;
121}
122
123bool AMDGPUPromoteAlloca::runOnFunction(Function &F) {
Andrew Kaylor7de74af2016-04-25 22:23:44 +0000124 if (!TM || skipFunction(F))
Matt Arsenaulte0132462016-01-30 05:19:45 +0000125 return false;
126
Matt Arsenault03d85842016-06-27 20:32:13 +0000127 const AMDGPUSubtarget &ST = TM->getSubtarget<AMDGPUSubtarget>(F);
128 if (!ST.isPromoteAllocaEnabled())
129 return false;
130
Craig Toppere3dcce92015-08-01 22:20:21 +0000131 FunctionType *FTy = F.getFunctionType();
Tom Stellard880a80a2014-06-17 16:53:14 +0000132
133 // If the function has any arguments in the local address space, then it's
134 // possible these arguments require the entire local memory space, so
135 // we cannot use local memory in the pass.
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000136 for (Type *ParamTy : FTy->params()) {
137 PointerType *PtrTy = dyn_cast<PointerType>(ParamTy);
138 if (PtrTy && PtrTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000139 LocalMemLimit = 0;
140 DEBUG(dbgs() << "Function has local memory argument. Promoting to "
Tom Stellard880a80a2014-06-17 16:53:14 +0000141 "local memory disabled.\n");
Matt Arsenaulte5737f72016-02-02 19:18:57 +0000142 return false;
Tom Stellard880a80a2014-06-17 16:53:14 +0000143 }
144 }
145
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000146 LocalMemLimit = ST.getLocalMemorySize();
147 if (LocalMemLimit == 0)
Matt Arsenaulte5737f72016-02-02 19:18:57 +0000148 return false;
149
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000150 const DataLayout &DL = Mod->getDataLayout();
151
Matt Arsenaulte5737f72016-02-02 19:18:57 +0000152 // Check how much local memory is being used by global objects
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000153 CurrentLocalMemUsage = 0;
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000154 for (GlobalVariable &GV : Mod->globals()) {
155 if (GV.getType()->getAddressSpace() != AMDGPUAS::LOCAL_ADDRESS)
Matt Arsenaulte5737f72016-02-02 19:18:57 +0000156 continue;
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000157
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000158 for (const User *U : GV.users()) {
159 const Instruction *Use = dyn_cast<Instruction>(U);
Matt Arsenaulte5737f72016-02-02 19:18:57 +0000160 if (!Use)
Tom Stellard880a80a2014-06-17 16:53:14 +0000161 continue;
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000162
Matt Arsenault0547b012016-04-27 21:05:08 +0000163 if (Use->getParent()->getParent() == &F) {
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000164 unsigned Align = GV.getAlignment();
165 if (Align == 0)
166 Align = DL.getABITypeAlignment(GV.getValueType());
167
168 // FIXME: Try to account for padding here. The padding is currently
169 // determined from the inverse order of uses in the function. I'm not
170 // sure if the use list order is in any way connected to this, so the
171 // total reported size is likely incorrect.
172 uint64_t AllocSize = DL.getTypeAllocSize(GV.getValueType());
173 CurrentLocalMemUsage = alignTo(CurrentLocalMemUsage, Align);
174 CurrentLocalMemUsage += AllocSize;
Matt Arsenault0547b012016-04-27 21:05:08 +0000175 break;
176 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000177 }
178 }
179
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000180 unsigned MaxOccupancy = ST.getOccupancyWithLocalMemSize(CurrentLocalMemUsage);
181
182 // Restrict local memory usage so that we don't drastically reduce occupancy,
183 // unless it is already significantly reduced.
184
185 // TODO: Have some sort of hint or other heuristics to guess occupancy based
186 // on other factors..
187 unsigned OccupancyHint
188 = AMDGPU::getIntegerAttribute(F, "amdgpu-max-waves-per-eu", 0);
189 if (OccupancyHint == 0)
190 OccupancyHint = 7;
191
192 // Clamp to max value.
193 OccupancyHint = std::min(OccupancyHint, ST.getMaxWavesPerCU());
194
195 // Check the hint but ignore it if it's obviously wrong from the existing LDS
196 // usage.
197 MaxOccupancy = std::min(OccupancyHint, MaxOccupancy);
198
199
200 // Round up to the next tier of usage.
201 unsigned MaxSizeWithWaveCount
202 = ST.getMaxLocalMemSizeWithWaveCount(MaxOccupancy);
203
204 // Program is possibly broken by using more local mem than available.
205 if (CurrentLocalMemUsage > MaxSizeWithWaveCount)
206 return false;
207
208 LocalMemLimit = MaxSizeWithWaveCount;
209
210 DEBUG(
211 dbgs() << F.getName() << " uses " << CurrentLocalMemUsage << " bytes of LDS\n"
212 << " Rounding size to " << MaxSizeWithWaveCount
213 << " with a maximum occupancy of " << MaxOccupancy << '\n'
214 << " and " << (LocalMemLimit - CurrentLocalMemUsage)
215 << " available for promotion\n"
216 );
Tom Stellard880a80a2014-06-17 16:53:14 +0000217
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +0000218 BasicBlock &EntryBB = *F.begin();
219 for (auto I = EntryBB.begin(), E = EntryBB.end(); I != E; ) {
220 AllocaInst *AI = dyn_cast<AllocaInst>(I);
221
222 ++I;
223 if (AI)
224 handleAlloca(*AI);
225 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000226
Matt Arsenaulte5737f72016-02-02 19:18:57 +0000227 return true;
Tom Stellard880a80a2014-06-17 16:53:14 +0000228}
229
Matt Arsenaulte0132462016-01-30 05:19:45 +0000230std::pair<Value *, Value *>
231AMDGPUPromoteAlloca::getLocalSizeYZ(IRBuilder<> &Builder) {
232 if (!IsAMDHSA) {
233 Function *LocalSizeYFn
234 = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_y);
235 Function *LocalSizeZFn
236 = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_z);
237
238 CallInst *LocalSizeY = Builder.CreateCall(LocalSizeYFn, {});
239 CallInst *LocalSizeZ = Builder.CreateCall(LocalSizeZFn, {});
240
241 LocalSizeY->setMetadata(LLVMContext::MD_range, MaxWorkGroupSizeRange);
242 LocalSizeZ->setMetadata(LLVMContext::MD_range, MaxWorkGroupSizeRange);
243
244 return std::make_pair(LocalSizeY, LocalSizeZ);
245 }
246
247 // We must read the size out of the dispatch pointer.
248 assert(IsAMDGCN);
249
250 // We are indexing into this struct, and want to extract the workgroup_size_*
251 // fields.
252 //
253 // typedef struct hsa_kernel_dispatch_packet_s {
254 // uint16_t header;
255 // uint16_t setup;
256 // uint16_t workgroup_size_x ;
257 // uint16_t workgroup_size_y;
258 // uint16_t workgroup_size_z;
259 // uint16_t reserved0;
260 // uint32_t grid_size_x ;
261 // uint32_t grid_size_y ;
262 // uint32_t grid_size_z;
263 //
264 // uint32_t private_segment_size;
265 // uint32_t group_segment_size;
266 // uint64_t kernel_object;
267 //
268 // #ifdef HSA_LARGE_MODEL
269 // void *kernarg_address;
270 // #elif defined HSA_LITTLE_ENDIAN
271 // void *kernarg_address;
272 // uint32_t reserved1;
273 // #else
274 // uint32_t reserved1;
275 // void *kernarg_address;
276 // #endif
277 // uint64_t reserved2;
278 // hsa_signal_t completion_signal; // uint64_t wrapper
279 // } hsa_kernel_dispatch_packet_t
280 //
281 Function *DispatchPtrFn
282 = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_dispatch_ptr);
283
284 CallInst *DispatchPtr = Builder.CreateCall(DispatchPtrFn, {});
285 DispatchPtr->addAttribute(AttributeSet::ReturnIndex, Attribute::NoAlias);
286 DispatchPtr->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
287
288 // Size of the dispatch packet struct.
289 DispatchPtr->addDereferenceableAttr(AttributeSet::ReturnIndex, 64);
290
291 Type *I32Ty = Type::getInt32Ty(Mod->getContext());
292 Value *CastDispatchPtr = Builder.CreateBitCast(
293 DispatchPtr, PointerType::get(I32Ty, AMDGPUAS::CONSTANT_ADDRESS));
294
295 // We could do a single 64-bit load here, but it's likely that the basic
296 // 32-bit and extract sequence is already present, and it is probably easier
297 // to CSE this. The loads should be mergable later anyway.
298 Value *GEPXY = Builder.CreateConstInBoundsGEP1_64(CastDispatchPtr, 1);
299 LoadInst *LoadXY = Builder.CreateAlignedLoad(GEPXY, 4);
300
301 Value *GEPZU = Builder.CreateConstInBoundsGEP1_64(CastDispatchPtr, 2);
302 LoadInst *LoadZU = Builder.CreateAlignedLoad(GEPZU, 4);
303
304 MDNode *MD = llvm::MDNode::get(Mod->getContext(), None);
305 LoadXY->setMetadata(LLVMContext::MD_invariant_load, MD);
306 LoadZU->setMetadata(LLVMContext::MD_invariant_load, MD);
307 LoadZU->setMetadata(LLVMContext::MD_range, MaxWorkGroupSizeRange);
308
309 // Extract y component. Upper half of LoadZU should be zero already.
310 Value *Y = Builder.CreateLShr(LoadXY, 16);
311
312 return std::make_pair(Y, LoadZU);
313}
314
315Value *AMDGPUPromoteAlloca::getWorkitemID(IRBuilder<> &Builder, unsigned N) {
316 Intrinsic::ID IntrID = Intrinsic::ID::not_intrinsic;
317
318 switch (N) {
319 case 0:
320 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_x
321 : Intrinsic::r600_read_tidig_x;
322 break;
323 case 1:
324 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_y
325 : Intrinsic::r600_read_tidig_y;
326 break;
327
328 case 2:
329 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_z
330 : Intrinsic::r600_read_tidig_z;
331 break;
332 default:
333 llvm_unreachable("invalid dimension");
334 }
335
336 Function *WorkitemIdFn = Intrinsic::getDeclaration(Mod, IntrID);
337 CallInst *CI = Builder.CreateCall(WorkitemIdFn);
338 CI->setMetadata(LLVMContext::MD_range, MaxWorkGroupSizeRange);
339
340 return CI;
341}
342
Craig Toppere3dcce92015-08-01 22:20:21 +0000343static VectorType *arrayTypeToVecType(Type *ArrayTy) {
Tom Stellard880a80a2014-06-17 16:53:14 +0000344 return VectorType::get(ArrayTy->getArrayElementType(),
345 ArrayTy->getArrayNumElements());
346}
347
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +0000348static Value *
349calculateVectorIndex(Value *Ptr,
350 const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
Tom Stellard880a80a2014-06-17 16:53:14 +0000351 GetElementPtrInst *GEP = cast<GetElementPtrInst>(Ptr);
352
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +0000353 auto I = GEPIdx.find(GEP);
354 return I == GEPIdx.end() ? nullptr : I->second;
Tom Stellard880a80a2014-06-17 16:53:14 +0000355}
356
357static Value* GEPToVectorIndex(GetElementPtrInst *GEP) {
358 // FIXME we only support simple cases
359 if (GEP->getNumOperands() != 3)
Matt Arsenaultefb24542016-07-18 18:34:53 +0000360 return nullptr;
Tom Stellard880a80a2014-06-17 16:53:14 +0000361
362 ConstantInt *I0 = dyn_cast<ConstantInt>(GEP->getOperand(1));
363 if (!I0 || !I0->isZero())
Matt Arsenaultefb24542016-07-18 18:34:53 +0000364 return nullptr;
Tom Stellard880a80a2014-06-17 16:53:14 +0000365
366 return GEP->getOperand(2);
367}
368
Matt Arsenault642d2e72014-06-27 16:52:49 +0000369// Not an instruction handled below to turn into a vector.
370//
371// TODO: Check isTriviallyVectorizable for calls and handle other
372// instructions.
Matt Arsenault7227cc12015-07-28 18:47:00 +0000373static bool canVectorizeInst(Instruction *Inst, User *User) {
Matt Arsenault642d2e72014-06-27 16:52:49 +0000374 switch (Inst->getOpcode()) {
375 case Instruction::Load:
Matt Arsenault642d2e72014-06-27 16:52:49 +0000376 case Instruction::BitCast:
377 case Instruction::AddrSpaceCast:
378 return true;
Matt Arsenault7227cc12015-07-28 18:47:00 +0000379 case Instruction::Store: {
380 // Must be the stored pointer operand, not a stored value.
381 StoreInst *SI = cast<StoreInst>(Inst);
382 return SI->getPointerOperand() == User;
383 }
Matt Arsenault642d2e72014-06-27 16:52:49 +0000384 default:
385 return false;
386 }
387}
388
Tom Stellard880a80a2014-06-17 16:53:14 +0000389static bool tryPromoteAllocaToVector(AllocaInst *Alloca) {
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000390 ArrayType *AllocaTy = dyn_cast<ArrayType>(Alloca->getAllocatedType());
Tom Stellard880a80a2014-06-17 16:53:14 +0000391
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000392 DEBUG(dbgs() << "Alloca candidate for vectorization\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000393
394 // FIXME: There is no reason why we can't support larger arrays, we
395 // are just being conservative for now.
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000396 if (!AllocaTy ||
397 AllocaTy->getElementType()->isVectorTy() ||
Matt Arsenaultefb24542016-07-18 18:34:53 +0000398 AllocaTy->getNumElements() > 4 ||
399 AllocaTy->getNumElements() < 2) {
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000400 DEBUG(dbgs() << " Cannot convert type to vector\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000401 return false;
402 }
403
404 std::map<GetElementPtrInst*, Value*> GEPVectorIdx;
405 std::vector<Value*> WorkList;
406 for (User *AllocaUser : Alloca->users()) {
407 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(AllocaUser);
408 if (!GEP) {
Matt Arsenault7227cc12015-07-28 18:47:00 +0000409 if (!canVectorizeInst(cast<Instruction>(AllocaUser), Alloca))
Matt Arsenault642d2e72014-06-27 16:52:49 +0000410 return false;
411
Tom Stellard880a80a2014-06-17 16:53:14 +0000412 WorkList.push_back(AllocaUser);
413 continue;
414 }
415
416 Value *Index = GEPToVectorIndex(GEP);
417
418 // If we can't compute a vector index from this GEP, then we can't
419 // promote this alloca to vector.
420 if (!Index) {
Matt Arsenault6f62cf82014-06-27 02:36:59 +0000421 DEBUG(dbgs() << " Cannot compute vector index for GEP " << *GEP << '\n');
Tom Stellard880a80a2014-06-17 16:53:14 +0000422 return false;
423 }
424
425 GEPVectorIdx[GEP] = Index;
426 for (User *GEPUser : AllocaUser->users()) {
Matt Arsenault7227cc12015-07-28 18:47:00 +0000427 if (!canVectorizeInst(cast<Instruction>(GEPUser), AllocaUser))
Matt Arsenault642d2e72014-06-27 16:52:49 +0000428 return false;
429
Tom Stellard880a80a2014-06-17 16:53:14 +0000430 WorkList.push_back(GEPUser);
431 }
432 }
433
434 VectorType *VectorTy = arrayTypeToVecType(AllocaTy);
435
Matt Arsenault6f62cf82014-06-27 02:36:59 +0000436 DEBUG(dbgs() << " Converting alloca to vector "
437 << *AllocaTy << " -> " << *VectorTy << '\n');
Tom Stellard880a80a2014-06-17 16:53:14 +0000438
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000439 for (Value *V : WorkList) {
440 Instruction *Inst = cast<Instruction>(V);
Tom Stellard880a80a2014-06-17 16:53:14 +0000441 IRBuilder<> Builder(Inst);
442 switch (Inst->getOpcode()) {
443 case Instruction::Load: {
Matt Arsenaultefb24542016-07-18 18:34:53 +0000444 Type *VecPtrTy = VectorTy->getPointerTo(AMDGPUAS::PRIVATE_ADDRESS);
Tom Stellard880a80a2014-06-17 16:53:14 +0000445 Value *Ptr = Inst->getOperand(0);
446 Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
Matt Arsenaultefb24542016-07-18 18:34:53 +0000447
448 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
Tom Stellard880a80a2014-06-17 16:53:14 +0000449 Value *VecValue = Builder.CreateLoad(BitCast);
450 Value *ExtractElement = Builder.CreateExtractElement(VecValue, Index);
451 Inst->replaceAllUsesWith(ExtractElement);
452 Inst->eraseFromParent();
453 break;
454 }
455 case Instruction::Store: {
Matt Arsenaultefb24542016-07-18 18:34:53 +0000456 Type *VecPtrTy = VectorTy->getPointerTo(AMDGPUAS::PRIVATE_ADDRESS);
457
Tom Stellard880a80a2014-06-17 16:53:14 +0000458 Value *Ptr = Inst->getOperand(1);
459 Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
Matt Arsenaultefb24542016-07-18 18:34:53 +0000460 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
Tom Stellard880a80a2014-06-17 16:53:14 +0000461 Value *VecValue = Builder.CreateLoad(BitCast);
462 Value *NewVecValue = Builder.CreateInsertElement(VecValue,
463 Inst->getOperand(0),
464 Index);
465 Builder.CreateStore(NewVecValue, BitCast);
466 Inst->eraseFromParent();
467 break;
468 }
469 case Instruction::BitCast:
Matt Arsenault642d2e72014-06-27 16:52:49 +0000470 case Instruction::AddrSpaceCast:
Tom Stellard880a80a2014-06-17 16:53:14 +0000471 break;
472
473 default:
Matt Arsenault642d2e72014-06-27 16:52:49 +0000474 llvm_unreachable("Inconsistency in instructions promotable to vector");
Tom Stellard880a80a2014-06-17 16:53:14 +0000475 }
476 }
477 return true;
478}
479
Matt Arsenaultad134842016-02-02 19:18:53 +0000480static bool isCallPromotable(CallInst *CI) {
Matt Arsenaultad134842016-02-02 19:18:53 +0000481 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
482 if (!II)
483 return false;
484
485 switch (II->getIntrinsicID()) {
486 case Intrinsic::memcpy:
Matt Arsenault7e747f12016-02-02 20:28:10 +0000487 case Intrinsic::memmove:
Matt Arsenaultad134842016-02-02 19:18:53 +0000488 case Intrinsic::memset:
489 case Intrinsic::lifetime_start:
490 case Intrinsic::lifetime_end:
491 case Intrinsic::invariant_start:
492 case Intrinsic::invariant_end:
493 case Intrinsic::invariant_group_barrier:
Matt Arsenault7e747f12016-02-02 20:28:10 +0000494 case Intrinsic::objectsize:
Matt Arsenaultad134842016-02-02 19:18:53 +0000495 return true;
496 default:
497 return false;
498 }
499}
500
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000501bool AMDGPUPromoteAlloca::binaryOpIsDerivedFromSameAlloca(Value *BaseAlloca,
502 Value *Val,
503 Instruction *Inst,
504 int OpIdx0,
505 int OpIdx1) const {
506 // Figure out which operand is the one we might not be promoting.
507 Value *OtherOp = Inst->getOperand(OpIdx0);
508 if (Val == OtherOp)
509 OtherOp = Inst->getOperand(OpIdx1);
510
Matt Arsenault891fccc2016-05-18 15:57:21 +0000511 if (isa<ConstantPointerNull>(OtherOp))
512 return true;
513
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000514 Value *OtherObj = GetUnderlyingObject(OtherOp, *DL);
515 if (!isa<AllocaInst>(OtherObj))
516 return false;
517
518 // TODO: We should be able to replace undefs with the right pointer type.
519
520 // TODO: If we know the other base object is another promotable
521 // alloca, not necessarily this alloca, we can do this. The
522 // important part is both must have the same address space at
523 // the end.
524 if (OtherObj != BaseAlloca) {
525 DEBUG(dbgs() << "Found a binary instruction with another alloca object\n");
526 return false;
527 }
528
529 return true;
530}
531
532bool AMDGPUPromoteAlloca::collectUsesWithPtrTypes(
533 Value *BaseAlloca,
534 Value *Val,
535 std::vector<Value*> &WorkList) const {
536
Tom Stellard880a80a2014-06-17 16:53:14 +0000537 for (User *User : Val->users()) {
Matt Arsenaultad134842016-02-02 19:18:53 +0000538 if (std::find(WorkList.begin(), WorkList.end(), User) != WorkList.end())
Tom Stellard880a80a2014-06-17 16:53:14 +0000539 continue;
Matt Arsenaultad134842016-02-02 19:18:53 +0000540
Matt Arsenaultfdcd39a2015-07-28 18:29:14 +0000541 if (CallInst *CI = dyn_cast<CallInst>(User)) {
Matt Arsenaultad134842016-02-02 19:18:53 +0000542 if (!isCallPromotable(CI))
Matt Arsenaultfdcd39a2015-07-28 18:29:14 +0000543 return false;
544
Tom Stellard880a80a2014-06-17 16:53:14 +0000545 WorkList.push_back(User);
546 continue;
547 }
Tom Stellard5b2927f2014-10-31 20:52:04 +0000548
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000549 Instruction *UseInst = cast<Instruction>(User);
550 if (UseInst->getOpcode() == Instruction::PtrToInt)
Tom Stellard5b2927f2014-10-31 20:52:04 +0000551 return false;
552
Matt Arsenault210b7cf2016-07-18 19:00:07 +0000553 if (LoadInst *LI = dyn_cast<LoadInst>(UseInst)) {
Matt Arsenaultc438ef52016-05-18 23:20:24 +0000554 if (LI->isVolatile())
555 return false;
556
557 continue;
558 }
559
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000560 if (StoreInst *SI = dyn_cast<StoreInst>(UseInst)) {
Matt Arsenault0a30e452016-03-23 23:17:29 +0000561 if (SI->isVolatile())
562 return false;
563
Matt Arsenault7227cc12015-07-28 18:47:00 +0000564 // Reject if the stored value is not the pointer operand.
565 if (SI->getPointerOperand() != Val)
566 return false;
Matt Arsenault210b7cf2016-07-18 19:00:07 +0000567 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UseInst)) {
Matt Arsenault0a30e452016-03-23 23:17:29 +0000568 if (RMW->isVolatile())
569 return false;
Matt Arsenault210b7cf2016-07-18 19:00:07 +0000570 } else if (AtomicCmpXchgInst *CAS = dyn_cast<AtomicCmpXchgInst>(UseInst)) {
Matt Arsenault0a30e452016-03-23 23:17:29 +0000571 if (CAS->isVolatile())
572 return false;
Matt Arsenault7227cc12015-07-28 18:47:00 +0000573 }
574
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000575 // Only promote a select if we know that the other select operand
576 // is from another pointer that will also be promoted.
577 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
578 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, ICmp, 0, 1))
579 return false;
Matt Arsenault891fccc2016-05-18 15:57:21 +0000580
581 // May need to rewrite constant operands.
582 WorkList.push_back(ICmp);
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000583 }
584
Tom Stellard880a80a2014-06-17 16:53:14 +0000585 if (!User->getType()->isPointerTy())
586 continue;
Tom Stellard5b2927f2014-10-31 20:52:04 +0000587
Matt Arsenaultde420812016-02-02 21:16:12 +0000588 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UseInst)) {
589 // Be conservative if an address could be computed outside the bounds of
590 // the alloca.
591 if (!GEP->isInBounds())
592 return false;
593 }
594
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000595 // Only promote a select if we know that the other select operand is from
596 // another pointer that will also be promoted.
597 if (SelectInst *SI = dyn_cast<SelectInst>(UseInst)) {
598 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, SI, 1, 2))
599 return false;
600 }
601
602 // Repeat for phis.
603 if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
604 // TODO: Handle more complex cases. We should be able to replace loops
605 // over arrays.
606 switch (Phi->getNumIncomingValues()) {
607 case 1:
608 break;
609 case 2:
610 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, Phi, 0, 1))
611 return false;
612 break;
613 default:
614 return false;
615 }
616 }
617
Tom Stellard880a80a2014-06-17 16:53:14 +0000618 WorkList.push_back(User);
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000619 if (!collectUsesWithPtrTypes(BaseAlloca, User, WorkList))
Matt Arsenaultad134842016-02-02 19:18:53 +0000620 return false;
Tom Stellard880a80a2014-06-17 16:53:14 +0000621 }
Matt Arsenaultad134842016-02-02 19:18:53 +0000622
623 return true;
Tom Stellard880a80a2014-06-17 16:53:14 +0000624}
625
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000626// FIXME: Should try to pick the most likely to be profitable allocas first.
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +0000627void AMDGPUPromoteAlloca::handleAlloca(AllocaInst &I) {
Matt Arsenaultc5fce692016-04-28 18:38:48 +0000628 // Array allocations are probably not worth handling, since an allocation of
629 // the array type is the canonical form.
630 if (!I.isStaticAlloca() || I.isArrayAllocation())
Matt Arsenault19c54882015-08-26 18:37:13 +0000631 return;
632
Tom Stellard880a80a2014-06-17 16:53:14 +0000633 IRBuilder<> Builder(&I);
634
635 // First try to replace the alloca with a vector
636 Type *AllocaTy = I.getAllocatedType();
637
Matt Arsenault6f62cf82014-06-27 02:36:59 +0000638 DEBUG(dbgs() << "Trying to promote " << I << '\n');
Tom Stellard880a80a2014-06-17 16:53:14 +0000639
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000640 if (tryPromoteAllocaToVector(&I)) {
641 DEBUG(dbgs() << " alloca is not a candidate for vectorization.\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000642 return;
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000643 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000644
Tom Stellard79a1fd72016-04-14 16:27:07 +0000645 const Function &ContainingFunction = *I.getParent()->getParent();
646
Nicolai Haehnlebef1ceb2016-07-18 09:02:47 +0000647 // Don't promote the alloca to LDS for shader calling conventions as the work
648 // item ID intrinsics are not supported for these calling conventions.
649 // Furthermore not all LDS is available for some of the stages.
650 if (AMDGPU::isShader(ContainingFunction.getCallingConv()))
651 return;
652
Tom Stellard79a1fd72016-04-14 16:27:07 +0000653 // FIXME: We should also try to get this value from the reqd_work_group_size
654 // function attribute if it is available.
655 unsigned WorkGroupSize = AMDGPU::getMaximumWorkGroupSize(ContainingFunction);
656
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000657 const DataLayout &DL = Mod->getDataLayout();
Tom Stellard880a80a2014-06-17 16:53:14 +0000658
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000659 unsigned Align = I.getAlignment();
660 if (Align == 0)
661 Align = DL.getABITypeAlignment(I.getAllocatedType());
662
663 // FIXME: This computed padding is likely wrong since it depends on inverse
664 // usage order.
665 //
666 // FIXME: It is also possible that if we're allowed to use all of the memory
667 // could could end up using more than the maximum due to alignment padding.
668
669 uint32_t NewSize = alignTo(CurrentLocalMemUsage, Align);
670 uint32_t AllocSize = WorkGroupSize * DL.getTypeAllocSize(AllocaTy);
671 NewSize += AllocSize;
672
673 if (NewSize > LocalMemLimit) {
674 DEBUG(dbgs() << " " << AllocSize
675 << " bytes of local memory not available to promote\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000676 return;
677 }
678
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000679 CurrentLocalMemUsage = NewSize;
680
Tom Stellard5b2927f2014-10-31 20:52:04 +0000681 std::vector<Value*> WorkList;
682
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000683 if (!collectUsesWithPtrTypes(&I, &I, WorkList)) {
Tom Stellard5b2927f2014-10-31 20:52:04 +0000684 DEBUG(dbgs() << " Do not know how to convert all uses\n");
685 return;
686 }
687
Tom Stellard880a80a2014-06-17 16:53:14 +0000688 DEBUG(dbgs() << "Promoting alloca to local memory\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000689
Matt Arsenaultcf84e262016-02-05 19:47:23 +0000690 Function *F = I.getParent()->getParent();
691
Tom Stellard79a1fd72016-04-14 16:27:07 +0000692 Type *GVTy = ArrayType::get(I.getAllocatedType(), WorkGroupSize);
Tom Stellard880a80a2014-06-17 16:53:14 +0000693 GlobalVariable *GV = new GlobalVariable(
Matt Arsenaultcf84e262016-02-05 19:47:23 +0000694 *Mod, GVTy, false, GlobalValue::InternalLinkage,
695 UndefValue::get(GVTy),
696 Twine(F->getName()) + Twine('.') + I.getName(),
697 nullptr,
698 GlobalVariable::NotThreadLocal,
699 AMDGPUAS::LOCAL_ADDRESS);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000700 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Matt Arsenaultcf84e262016-02-05 19:47:23 +0000701 GV->setAlignment(I.getAlignment());
Tom Stellard880a80a2014-06-17 16:53:14 +0000702
Matt Arsenaulte0132462016-01-30 05:19:45 +0000703 Value *TCntY, *TCntZ;
Tom Stellard880a80a2014-06-17 16:53:14 +0000704
Matt Arsenaulte0132462016-01-30 05:19:45 +0000705 std::tie(TCntY, TCntZ) = getLocalSizeYZ(Builder);
706 Value *TIdX = getWorkitemID(Builder, 0);
707 Value *TIdY = getWorkitemID(Builder, 1);
708 Value *TIdZ = getWorkitemID(Builder, 2);
Tom Stellard880a80a2014-06-17 16:53:14 +0000709
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000710 Value *Tmp0 = Builder.CreateMul(TCntY, TCntZ, "", true, true);
Tom Stellard880a80a2014-06-17 16:53:14 +0000711 Tmp0 = Builder.CreateMul(Tmp0, TIdX);
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000712 Value *Tmp1 = Builder.CreateMul(TIdY, TCntZ, "", true, true);
Tom Stellard880a80a2014-06-17 16:53:14 +0000713 Value *TID = Builder.CreateAdd(Tmp0, Tmp1);
714 TID = Builder.CreateAdd(TID, TIdZ);
715
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000716 Value *Indices[] = {
717 Constant::getNullValue(Type::getInt32Ty(Mod->getContext())),
718 TID
719 };
Tom Stellard880a80a2014-06-17 16:53:14 +0000720
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000721 Value *Offset = Builder.CreateInBoundsGEP(GVTy, GV, Indices);
Tom Stellard880a80a2014-06-17 16:53:14 +0000722 I.mutateType(Offset->getType());
723 I.replaceAllUsesWith(Offset);
724 I.eraseFromParent();
725
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000726 for (Value *V : WorkList) {
Tom Stellard880a80a2014-06-17 16:53:14 +0000727 CallInst *Call = dyn_cast<CallInst>(V);
728 if (!Call) {
Matt Arsenault891fccc2016-05-18 15:57:21 +0000729 if (ICmpInst *CI = dyn_cast<ICmpInst>(V)) {
730 Value *Src0 = CI->getOperand(0);
731 Type *EltTy = Src0->getType()->getPointerElementType();
732 PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
733
734 if (isa<ConstantPointerNull>(CI->getOperand(0)))
735 CI->setOperand(0, ConstantPointerNull::get(NewTy));
736
737 if (isa<ConstantPointerNull>(CI->getOperand(1)))
738 CI->setOperand(1, ConstantPointerNull::get(NewTy));
739
740 continue;
741 }
Matt Arsenault65f67e42014-09-15 15:41:44 +0000742
743 // The operand's value should be corrected on its own.
744 if (isa<AddrSpaceCastInst>(V))
745 continue;
746
Matt Arsenault891fccc2016-05-18 15:57:21 +0000747 Type *EltTy = V->getType()->getPointerElementType();
748 PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
749
Matt Arsenault65f67e42014-09-15 15:41:44 +0000750 // FIXME: It doesn't really make sense to try to do this for all
751 // instructions.
Tom Stellard880a80a2014-06-17 16:53:14 +0000752 V->mutateType(NewTy);
Matt Arsenault891fccc2016-05-18 15:57:21 +0000753
754 // Adjust the types of any constant operands.
755 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
756 if (isa<ConstantPointerNull>(SI->getOperand(1)))
757 SI->setOperand(1, ConstantPointerNull::get(NewTy));
758
759 if (isa<ConstantPointerNull>(SI->getOperand(2)))
760 SI->setOperand(2, ConstantPointerNull::get(NewTy));
761 } else if (PHINode *Phi = dyn_cast<PHINode>(V)) {
762 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
763 if (isa<ConstantPointerNull>(Phi->getIncomingValue(I)))
764 Phi->setIncomingValue(I, ConstantPointerNull::get(NewTy));
765 }
766 }
767
Tom Stellard880a80a2014-06-17 16:53:14 +0000768 continue;
769 }
770
Matt Arsenault2e08e182016-07-18 18:34:48 +0000771 IntrinsicInst *Intr = cast<IntrinsicInst>(Call);
Tom Stellard880a80a2014-06-17 16:53:14 +0000772 Builder.SetInsertPoint(Intr);
773 switch (Intr->getIntrinsicID()) {
774 case Intrinsic::lifetime_start:
775 case Intrinsic::lifetime_end:
776 // These intrinsics are for address space 0 only
777 Intr->eraseFromParent();
778 continue;
779 case Intrinsic::memcpy: {
780 MemCpyInst *MemCpy = cast<MemCpyInst>(Intr);
781 Builder.CreateMemCpy(MemCpy->getRawDest(), MemCpy->getRawSource(),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000782 MemCpy->getLength(), MemCpy->getAlignment(),
783 MemCpy->isVolatile());
Tom Stellard880a80a2014-06-17 16:53:14 +0000784 Intr->eraseFromParent();
785 continue;
786 }
Matt Arsenault7e747f12016-02-02 20:28:10 +0000787 case Intrinsic::memmove: {
788 MemMoveInst *MemMove = cast<MemMoveInst>(Intr);
789 Builder.CreateMemMove(MemMove->getRawDest(), MemMove->getRawSource(),
790 MemMove->getLength(), MemMove->getAlignment(),
791 MemMove->isVolatile());
792 Intr->eraseFromParent();
793 continue;
794 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000795 case Intrinsic::memset: {
796 MemSetInst *MemSet = cast<MemSetInst>(Intr);
797 Builder.CreateMemSet(MemSet->getRawDest(), MemSet->getValue(),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000798 MemSet->getLength(), MemSet->getAlignment(),
Tom Stellard880a80a2014-06-17 16:53:14 +0000799 MemSet->isVolatile());
800 Intr->eraseFromParent();
801 continue;
802 }
Matt Arsenault0b783ef02016-01-22 19:47:54 +0000803 case Intrinsic::invariant_start:
804 case Intrinsic::invariant_end:
805 case Intrinsic::invariant_group_barrier:
806 Intr->eraseFromParent();
807 // FIXME: I think the invariant marker should still theoretically apply,
808 // but the intrinsics need to be changed to accept pointers with any
809 // address space.
810 continue;
Matt Arsenault7e747f12016-02-02 20:28:10 +0000811 case Intrinsic::objectsize: {
812 Value *Src = Intr->getOperand(0);
813 Type *SrcTy = Src->getType()->getPointerElementType();
814 Function *ObjectSize = Intrinsic::getDeclaration(Mod,
815 Intrinsic::objectsize,
816 { Intr->getType(), PointerType::get(SrcTy, AMDGPUAS::LOCAL_ADDRESS) }
817 );
818
819 CallInst *NewCall
820 = Builder.CreateCall(ObjectSize, { Src, Intr->getOperand(1) });
821 Intr->replaceAllUsesWith(NewCall);
822 Intr->eraseFromParent();
823 continue;
824 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000825 default:
826 Intr->dump();
827 llvm_unreachable("Don't know how to promote alloca intrinsic use.");
828 }
829 }
830}
831
Matt Arsenaulte0132462016-01-30 05:19:45 +0000832FunctionPass *llvm::createAMDGPUPromoteAlloca(const TargetMachine *TM) {
833 return new AMDGPUPromoteAlloca(TM);
Tom Stellard880a80a2014-06-17 16:53:14 +0000834}