blob: ffe34831623ea8fa74f76d2da06783f51df7e237 [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"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000017#include "Utils/AMDGPUBaseInfo.h"
18#include "llvm/ADT/APInt.h"
19#include "llvm/ADT/None.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Triple.h"
23#include "llvm/ADT/Twine.h"
Changpeng Fangc85abbd2017-01-24 19:06:28 +000024#include "llvm/Analysis/CaptureTracking.h"
Tom Stellard880a80a2014-06-17 16:53:14 +000025#include "llvm/Analysis/ValueTracking.h"
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +000026#include "llvm/CodeGen/TargetPassConfig.h"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000027#include "llvm/IR/Attributes.h"
28#include "llvm/IR/BasicBlock.h"
29#include "llvm/IR/Constant.h"
30#include "llvm/IR/Constants.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/DerivedTypes.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/GlobalValue.h"
35#include "llvm/IR/GlobalVariable.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000036#include "llvm/IR/IRBuilder.h"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000037#include "llvm/IR/Instruction.h"
38#include "llvm/IR/Instructions.h"
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +000039#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000040#include "llvm/IR/Intrinsics.h"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000041#include "llvm/IR/LLVMContext.h"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000042#include "llvm/IR/Metadata.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/Type.h"
45#include "llvm/IR/User.h"
46#include "llvm/IR/Value.h"
47#include "llvm/Pass.h"
48#include "llvm/Support/Casting.h"
Tom Stellard880a80a2014-06-17 16:53:14 +000049#include "llvm/Support/Debug.h"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000050#include "llvm/Support/ErrorHandling.h"
51#include "llvm/Support/MathExtras.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000052#include "llvm/Support/raw_ostream.h"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000053#include "llvm/Target/TargetMachine.h"
54#include <algorithm>
55#include <cassert>
56#include <cstdint>
57#include <map>
58#include <tuple>
59#include <utility>
60#include <vector>
Tom Stellard880a80a2014-06-17 16:53:14 +000061
62#define DEBUG_TYPE "amdgpu-promote-alloca"
63
64using namespace llvm;
65
66namespace {
67
Changpeng Fangba920592018-02-16 19:14:17 +000068static cl::opt<bool> DisablePromoteAllocaToVector(
69 "disable-promote-alloca-to-vector",
70 cl::desc("Disable promote alloca to vector"),
71 cl::init(false));
72
Matt Arsenaulte0132462016-01-30 05:19:45 +000073// FIXME: This can create globals so should be a module pass.
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +000074class AMDGPUPromoteAlloca : public FunctionPass {
Matt Arsenaulte0132462016-01-30 05:19:45 +000075private:
76 const TargetMachine *TM;
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000077 Module *Mod = nullptr;
78 const DataLayout *DL = nullptr;
Yaxun Liu1a14bfa2017-03-27 14:04:01 +000079 AMDGPUAS AS;
Matt Arsenaulte0132462016-01-30 05:19:45 +000080
81 // FIXME: This should be per-kernel.
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000082 uint32_t LocalMemLimit = 0;
83 uint32_t CurrentLocalMemUsage = 0;
Tom Stellard880a80a2014-06-17 16:53:14 +000084
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000085 bool IsAMDGCN = false;
86 bool IsAMDHSA = false;
Matt Arsenaulte0132462016-01-30 05:19:45 +000087
88 std::pair<Value *, Value *> getLocalSizeYZ(IRBuilder<> &Builder);
89 Value *getWorkitemID(IRBuilder<> &Builder, unsigned N);
90
Matt Arsenaulta61cb482016-05-12 01:58:58 +000091 /// BaseAlloca is the alloca root the search started from.
92 /// Val may be that alloca or a recursive user of it.
93 bool collectUsesWithPtrTypes(Value *BaseAlloca,
94 Value *Val,
95 std::vector<Value*> &WorkList) const;
96
97 /// Val is a derived pointer from Alloca. OpIdx0/OpIdx1 are the operand
98 /// indices to an instruction with 2 pointer inputs (e.g. select, icmp).
99 /// Returns true if both operands are derived from the same alloca. Val should
100 /// be the same value as one of the input operands of UseInst.
101 bool binaryOpIsDerivedFromSameAlloca(Value *Alloca, Value *Val,
102 Instruction *UseInst,
103 int OpIdx0, int OpIdx1) const;
104
Changpeng Fang1dbace12017-05-23 20:25:41 +0000105 /// Check whether we have enough local memory for promotion.
106 bool hasSufficientLocalMem(const Function &F);
107
Tom Stellard880a80a2014-06-17 16:53:14 +0000108public:
Matt Arsenaulte0132462016-01-30 05:19:45 +0000109 static char ID;
110
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000111 AMDGPUPromoteAlloca() : FunctionPass(ID) {}
Matt Arsenaulte0132462016-01-30 05:19:45 +0000112
Benjamin Kramer8c90fd72014-09-03 11:41:21 +0000113 bool doInitialization(Module &M) override;
114 bool runOnFunction(Function &F) override;
Matt Arsenaulte0132462016-01-30 05:19:45 +0000115
Mehdi Amini117296c2016-10-01 02:56:57 +0000116 StringRef getPassName() const override { return "AMDGPU Promote Alloca"; }
Matt Arsenaulte0132462016-01-30 05:19:45 +0000117
Changpeng Fang1dbace12017-05-23 20:25:41 +0000118 bool handleAlloca(AllocaInst &I, bool SufficientLDS);
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000119
120 void getAnalysisUsage(AnalysisUsage &AU) const override {
121 AU.setPreservesCFG();
122 FunctionPass::getAnalysisUsage(AU);
123 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000124};
125
Eugene Zelenko734bb7b2017-01-20 17:52:16 +0000126} // end anonymous namespace
Tom Stellard880a80a2014-06-17 16:53:14 +0000127
128char AMDGPUPromoteAlloca::ID = 0;
129
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000130INITIALIZE_PASS(AMDGPUPromoteAlloca, DEBUG_TYPE,
131 "AMDGPU promote alloca to vector or LDS", false, false)
Matt Arsenaulte0132462016-01-30 05:19:45 +0000132
133char &llvm::AMDGPUPromoteAllocaID = AMDGPUPromoteAlloca::ID;
134
Tom Stellard880a80a2014-06-17 16:53:14 +0000135bool AMDGPUPromoteAlloca::doInitialization(Module &M) {
136 Mod = &M;
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000137 DL = &Mod->getDataLayout();
Matt Arsenaulte0132462016-01-30 05:19:45 +0000138
Tom Stellard880a80a2014-06-17 16:53:14 +0000139 return false;
140}
141
142bool AMDGPUPromoteAlloca::runOnFunction(Function &F) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000143 if (skipFunction(F))
Matt Arsenaulte0132462016-01-30 05:19:45 +0000144 return false;
145
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000146 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>())
147 TM = &TPC->getTM<TargetMachine>();
148 else
149 return false;
150
151 const Triple &TT = TM->getTargetTriple();
152 IsAMDGCN = TT.getArch() == Triple::amdgcn;
153 IsAMDHSA = TT.getOS() == Triple::AMDHSA;
154
Tom Stellardc5a154d2018-06-28 23:47:12 +0000155 const AMDGPUCommonSubtarget &ST = AMDGPUCommonSubtarget::get(*TM, F);
Matt Arsenault03d85842016-06-27 20:32:13 +0000156 if (!ST.isPromoteAllocaEnabled())
157 return false;
Changpeng Fang1dbace12017-05-23 20:25:41 +0000158
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000159 AS = AMDGPU::getAMDGPUAS(*F.getParent());
Matt Arsenault03d85842016-06-27 20:32:13 +0000160
Changpeng Fang1dbace12017-05-23 20:25:41 +0000161 bool SufficientLDS = hasSufficientLocalMem(F);
162 bool Changed = false;
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +0000163 BasicBlock &EntryBB = *F.begin();
164 for (auto I = EntryBB.begin(), E = EntryBB.end(); I != E; ) {
165 AllocaInst *AI = dyn_cast<AllocaInst>(I);
166
167 ++I;
168 if (AI)
Changpeng Fang1dbace12017-05-23 20:25:41 +0000169 Changed |= handleAlloca(*AI, SufficientLDS);
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +0000170 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000171
Changpeng Fang1dbace12017-05-23 20:25:41 +0000172 return Changed;
Tom Stellard880a80a2014-06-17 16:53:14 +0000173}
174
Matt Arsenaulte0132462016-01-30 05:19:45 +0000175std::pair<Value *, Value *>
176AMDGPUPromoteAlloca::getLocalSizeYZ(IRBuilder<> &Builder) {
Tom Stellardc5a154d2018-06-28 23:47:12 +0000177 const Function &F = *Builder.GetInsertBlock()->getParent();
178 const AMDGPUCommonSubtarget &ST = AMDGPUCommonSubtarget::get(*TM, F);
Stanislav Mekhanoshinc90347d2017-04-12 20:48:56 +0000179
Matt Arsenaulte0132462016-01-30 05:19:45 +0000180 if (!IsAMDHSA) {
181 Function *LocalSizeYFn
182 = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_y);
183 Function *LocalSizeZFn
184 = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_z);
185
186 CallInst *LocalSizeY = Builder.CreateCall(LocalSizeYFn, {});
187 CallInst *LocalSizeZ = Builder.CreateCall(LocalSizeZFn, {});
188
Stanislav Mekhanoshinc90347d2017-04-12 20:48:56 +0000189 ST.makeLIDRangeMetadata(LocalSizeY);
190 ST.makeLIDRangeMetadata(LocalSizeZ);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000191
192 return std::make_pair(LocalSizeY, LocalSizeZ);
193 }
194
195 // We must read the size out of the dispatch pointer.
196 assert(IsAMDGCN);
197
198 // We are indexing into this struct, and want to extract the workgroup_size_*
199 // fields.
200 //
201 // typedef struct hsa_kernel_dispatch_packet_s {
202 // uint16_t header;
203 // uint16_t setup;
204 // uint16_t workgroup_size_x ;
205 // uint16_t workgroup_size_y;
206 // uint16_t workgroup_size_z;
207 // uint16_t reserved0;
208 // uint32_t grid_size_x ;
209 // uint32_t grid_size_y ;
210 // uint32_t grid_size_z;
211 //
212 // uint32_t private_segment_size;
213 // uint32_t group_segment_size;
214 // uint64_t kernel_object;
215 //
216 // #ifdef HSA_LARGE_MODEL
217 // void *kernarg_address;
218 // #elif defined HSA_LITTLE_ENDIAN
219 // void *kernarg_address;
220 // uint32_t reserved1;
221 // #else
222 // uint32_t reserved1;
223 // void *kernarg_address;
224 // #endif
225 // uint64_t reserved2;
226 // hsa_signal_t completion_signal; // uint64_t wrapper
227 // } hsa_kernel_dispatch_packet_t
228 //
229 Function *DispatchPtrFn
230 = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_dispatch_ptr);
231
232 CallInst *DispatchPtr = Builder.CreateCall(DispatchPtrFn, {});
Reid Klecknerb5180542017-03-21 16:57:19 +0000233 DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
234 DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000235
236 // Size of the dispatch packet struct.
Reid Klecknerb5180542017-03-21 16:57:19 +0000237 DispatchPtr->addDereferenceableAttr(AttributeList::ReturnIndex, 64);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000238
239 Type *I32Ty = Type::getInt32Ty(Mod->getContext());
240 Value *CastDispatchPtr = Builder.CreateBitCast(
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000241 DispatchPtr, PointerType::get(I32Ty, AS.CONSTANT_ADDRESS));
Matt Arsenaulte0132462016-01-30 05:19:45 +0000242
243 // We could do a single 64-bit load here, but it's likely that the basic
244 // 32-bit and extract sequence is already present, and it is probably easier
245 // to CSE this. The loads should be mergable later anyway.
246 Value *GEPXY = Builder.CreateConstInBoundsGEP1_64(CastDispatchPtr, 1);
247 LoadInst *LoadXY = Builder.CreateAlignedLoad(GEPXY, 4);
248
249 Value *GEPZU = Builder.CreateConstInBoundsGEP1_64(CastDispatchPtr, 2);
250 LoadInst *LoadZU = Builder.CreateAlignedLoad(GEPZU, 4);
251
Eugene Zelenko734bb7b2017-01-20 17:52:16 +0000252 MDNode *MD = MDNode::get(Mod->getContext(), None);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000253 LoadXY->setMetadata(LLVMContext::MD_invariant_load, MD);
254 LoadZU->setMetadata(LLVMContext::MD_invariant_load, MD);
Stanislav Mekhanoshinc90347d2017-04-12 20:48:56 +0000255 ST.makeLIDRangeMetadata(LoadZU);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000256
257 // Extract y component. Upper half of LoadZU should be zero already.
258 Value *Y = Builder.CreateLShr(LoadXY, 16);
259
260 return std::make_pair(Y, LoadZU);
261}
262
263Value *AMDGPUPromoteAlloca::getWorkitemID(IRBuilder<> &Builder, unsigned N) {
Tom Stellardc5a154d2018-06-28 23:47:12 +0000264 const AMDGPUCommonSubtarget &ST =
265 AMDGPUCommonSubtarget::get(*TM, *Builder.GetInsertBlock()->getParent());
Matt Arsenaulte0132462016-01-30 05:19:45 +0000266 Intrinsic::ID IntrID = Intrinsic::ID::not_intrinsic;
267
268 switch (N) {
269 case 0:
270 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_x
271 : Intrinsic::r600_read_tidig_x;
272 break;
273 case 1:
274 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_y
275 : Intrinsic::r600_read_tidig_y;
276 break;
277
278 case 2:
279 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_z
280 : Intrinsic::r600_read_tidig_z;
281 break;
282 default:
283 llvm_unreachable("invalid dimension");
284 }
285
286 Function *WorkitemIdFn = Intrinsic::getDeclaration(Mod, IntrID);
287 CallInst *CI = Builder.CreateCall(WorkitemIdFn);
Stanislav Mekhanoshinc90347d2017-04-12 20:48:56 +0000288 ST.makeLIDRangeMetadata(CI);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000289
290 return CI;
291}
292
Matt Arsenault37ab4cf2017-09-14 18:02:29 +0000293static VectorType *arrayTypeToVecType(ArrayType *ArrayTy) {
294 return VectorType::get(ArrayTy->getElementType(),
295 ArrayTy->getNumElements());
Tom Stellard880a80a2014-06-17 16:53:14 +0000296}
297
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +0000298static Value *
299calculateVectorIndex(Value *Ptr,
300 const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
Tom Stellard880a80a2014-06-17 16:53:14 +0000301 GetElementPtrInst *GEP = cast<GetElementPtrInst>(Ptr);
302
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +0000303 auto I = GEPIdx.find(GEP);
304 return I == GEPIdx.end() ? nullptr : I->second;
Tom Stellard880a80a2014-06-17 16:53:14 +0000305}
306
307static Value* GEPToVectorIndex(GetElementPtrInst *GEP) {
308 // FIXME we only support simple cases
309 if (GEP->getNumOperands() != 3)
Matt Arsenaultefb24542016-07-18 18:34:53 +0000310 return nullptr;
Tom Stellard880a80a2014-06-17 16:53:14 +0000311
312 ConstantInt *I0 = dyn_cast<ConstantInt>(GEP->getOperand(1));
313 if (!I0 || !I0->isZero())
Matt Arsenaultefb24542016-07-18 18:34:53 +0000314 return nullptr;
Tom Stellard880a80a2014-06-17 16:53:14 +0000315
316 return GEP->getOperand(2);
317}
318
Matt Arsenault642d2e72014-06-27 16:52:49 +0000319// Not an instruction handled below to turn into a vector.
320//
321// TODO: Check isTriviallyVectorizable for calls and handle other
322// instructions.
Matt Arsenault7227cc12015-07-28 18:47:00 +0000323static bool canVectorizeInst(Instruction *Inst, User *User) {
Matt Arsenault642d2e72014-06-27 16:52:49 +0000324 switch (Inst->getOpcode()) {
Changpeng Fang161e8c39af2017-05-12 20:31:12 +0000325 case Instruction::Load: {
Changpeng Fang860d4602018-05-17 21:49:44 +0000326 // Currently only handle the case where the Pointer Operand is a GEP.
327 // Also we could not vectorize volatile or atomic loads.
Changpeng Fang161e8c39af2017-05-12 20:31:12 +0000328 LoadInst *LI = cast<LoadInst>(Inst);
Changpeng Fang860d4602018-05-17 21:49:44 +0000329 return isa<GetElementPtrInst>(LI->getPointerOperand()) && LI->isSimple();
Changpeng Fang161e8c39af2017-05-12 20:31:12 +0000330 }
Matt Arsenault642d2e72014-06-27 16:52:49 +0000331 case Instruction::BitCast:
Matt Arsenault642d2e72014-06-27 16:52:49 +0000332 return true;
Matt Arsenault7227cc12015-07-28 18:47:00 +0000333 case Instruction::Store: {
David Stuttard82618ba2017-06-09 14:16:22 +0000334 // Must be the stored pointer operand, not a stored value, plus
335 // since it should be canonical form, the User should be a GEP.
Changpeng Fang860d4602018-05-17 21:49:44 +0000336 // Also we could not vectorize volatile or atomic stores.
Matt Arsenault7227cc12015-07-28 18:47:00 +0000337 StoreInst *SI = cast<StoreInst>(Inst);
Changpeng Fang860d4602018-05-17 21:49:44 +0000338 return (SI->getPointerOperand() == User) && isa<GetElementPtrInst>(User) && SI->isSimple();
Matt Arsenault7227cc12015-07-28 18:47:00 +0000339 }
Matt Arsenault642d2e72014-06-27 16:52:49 +0000340 default:
341 return false;
342 }
343}
344
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000345static bool tryPromoteAllocaToVector(AllocaInst *Alloca, AMDGPUAS AS) {
Changpeng Fangba920592018-02-16 19:14:17 +0000346
347 if (DisablePromoteAllocaToVector) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000348 LLVM_DEBUG(dbgs() << " Promotion alloca to vector is disabled\n");
Changpeng Fangba920592018-02-16 19:14:17 +0000349 return false;
350 }
351
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000352 ArrayType *AllocaTy = dyn_cast<ArrayType>(Alloca->getAllocatedType());
Tom Stellard880a80a2014-06-17 16:53:14 +0000353
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000354 LLVM_DEBUG(dbgs() << "Alloca candidate for vectorization\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000355
356 // FIXME: There is no reason why we can't support larger arrays, we
357 // are just being conservative for now.
David Stuttard82618ba2017-06-09 14:16:22 +0000358 // FIXME: We also reject alloca's of the form [ 2 x [ 2 x i32 ]] or equivalent. Potentially these
359 // could also be promoted but we don't currently handle this case
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000360 if (!AllocaTy ||
Changpeng Fangba920592018-02-16 19:14:17 +0000361 AllocaTy->getNumElements() > 16 ||
Matt Arsenault37ab4cf2017-09-14 18:02:29 +0000362 AllocaTy->getNumElements() < 2 ||
363 !VectorType::isValidElementType(AllocaTy->getElementType())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000364 LLVM_DEBUG(dbgs() << " Cannot convert type to vector\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000365 return false;
366 }
367
368 std::map<GetElementPtrInst*, Value*> GEPVectorIdx;
369 std::vector<Value*> WorkList;
370 for (User *AllocaUser : Alloca->users()) {
371 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(AllocaUser);
372 if (!GEP) {
Matt Arsenault7227cc12015-07-28 18:47:00 +0000373 if (!canVectorizeInst(cast<Instruction>(AllocaUser), Alloca))
Matt Arsenault642d2e72014-06-27 16:52:49 +0000374 return false;
375
Tom Stellard880a80a2014-06-17 16:53:14 +0000376 WorkList.push_back(AllocaUser);
377 continue;
378 }
379
380 Value *Index = GEPToVectorIndex(GEP);
381
382 // If we can't compute a vector index from this GEP, then we can't
383 // promote this alloca to vector.
384 if (!Index) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000385 LLVM_DEBUG(dbgs() << " Cannot compute vector index for GEP " << *GEP
386 << '\n');
Tom Stellard880a80a2014-06-17 16:53:14 +0000387 return false;
388 }
389
390 GEPVectorIdx[GEP] = Index;
391 for (User *GEPUser : AllocaUser->users()) {
Matt Arsenault7227cc12015-07-28 18:47:00 +0000392 if (!canVectorizeInst(cast<Instruction>(GEPUser), AllocaUser))
Matt Arsenault642d2e72014-06-27 16:52:49 +0000393 return false;
394
Tom Stellard880a80a2014-06-17 16:53:14 +0000395 WorkList.push_back(GEPUser);
396 }
397 }
398
399 VectorType *VectorTy = arrayTypeToVecType(AllocaTy);
400
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000401 LLVM_DEBUG(dbgs() << " Converting alloca to vector " << *AllocaTy << " -> "
402 << *VectorTy << '\n');
Tom Stellard880a80a2014-06-17 16:53:14 +0000403
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000404 for (Value *V : WorkList) {
405 Instruction *Inst = cast<Instruction>(V);
Tom Stellard880a80a2014-06-17 16:53:14 +0000406 IRBuilder<> Builder(Inst);
407 switch (Inst->getOpcode()) {
408 case Instruction::Load: {
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000409 Type *VecPtrTy = VectorTy->getPointerTo(AS.PRIVATE_ADDRESS);
David Stuttard82618ba2017-06-09 14:16:22 +0000410 Value *Ptr = cast<LoadInst>(Inst)->getPointerOperand();
Tom Stellard880a80a2014-06-17 16:53:14 +0000411 Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
Matt Arsenaultefb24542016-07-18 18:34:53 +0000412
413 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
Tom Stellard880a80a2014-06-17 16:53:14 +0000414 Value *VecValue = Builder.CreateLoad(BitCast);
415 Value *ExtractElement = Builder.CreateExtractElement(VecValue, Index);
416 Inst->replaceAllUsesWith(ExtractElement);
417 Inst->eraseFromParent();
418 break;
419 }
420 case Instruction::Store: {
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000421 Type *VecPtrTy = VectorTy->getPointerTo(AS.PRIVATE_ADDRESS);
Matt Arsenaultefb24542016-07-18 18:34:53 +0000422
David Stuttard82618ba2017-06-09 14:16:22 +0000423 StoreInst *SI = cast<StoreInst>(Inst);
424 Value *Ptr = SI->getPointerOperand();
Tom Stellard880a80a2014-06-17 16:53:14 +0000425 Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
Matt Arsenaultefb24542016-07-18 18:34:53 +0000426 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
Tom Stellard880a80a2014-06-17 16:53:14 +0000427 Value *VecValue = Builder.CreateLoad(BitCast);
428 Value *NewVecValue = Builder.CreateInsertElement(VecValue,
David Stuttard82618ba2017-06-09 14:16:22 +0000429 SI->getValueOperand(),
Tom Stellard880a80a2014-06-17 16:53:14 +0000430 Index);
431 Builder.CreateStore(NewVecValue, BitCast);
432 Inst->eraseFromParent();
433 break;
434 }
435 case Instruction::BitCast:
Matt Arsenault642d2e72014-06-27 16:52:49 +0000436 case Instruction::AddrSpaceCast:
Tom Stellard880a80a2014-06-17 16:53:14 +0000437 break;
438
439 default:
Matt Arsenault642d2e72014-06-27 16:52:49 +0000440 llvm_unreachable("Inconsistency in instructions promotable to vector");
Tom Stellard880a80a2014-06-17 16:53:14 +0000441 }
442 }
443 return true;
444}
445
Matt Arsenaultad134842016-02-02 19:18:53 +0000446static bool isCallPromotable(CallInst *CI) {
Matt Arsenaultad134842016-02-02 19:18:53 +0000447 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
448 if (!II)
449 return false;
450
451 switch (II->getIntrinsicID()) {
452 case Intrinsic::memcpy:
Matt Arsenault7e747f12016-02-02 20:28:10 +0000453 case Intrinsic::memmove:
Matt Arsenaultad134842016-02-02 19:18:53 +0000454 case Intrinsic::memset:
455 case Intrinsic::lifetime_start:
456 case Intrinsic::lifetime_end:
457 case Intrinsic::invariant_start:
458 case Intrinsic::invariant_end:
Piotr Padlewski5dde8092018-05-03 11:03:01 +0000459 case Intrinsic::launder_invariant_group:
Matt Arsenault7e747f12016-02-02 20:28:10 +0000460 case Intrinsic::objectsize:
Matt Arsenaultad134842016-02-02 19:18:53 +0000461 return true;
462 default:
463 return false;
464 }
465}
466
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000467bool AMDGPUPromoteAlloca::binaryOpIsDerivedFromSameAlloca(Value *BaseAlloca,
468 Value *Val,
469 Instruction *Inst,
470 int OpIdx0,
471 int OpIdx1) const {
472 // Figure out which operand is the one we might not be promoting.
473 Value *OtherOp = Inst->getOperand(OpIdx0);
474 if (Val == OtherOp)
475 OtherOp = Inst->getOperand(OpIdx1);
476
Matt Arsenault891fccc2016-05-18 15:57:21 +0000477 if (isa<ConstantPointerNull>(OtherOp))
478 return true;
479
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000480 Value *OtherObj = GetUnderlyingObject(OtherOp, *DL);
481 if (!isa<AllocaInst>(OtherObj))
482 return false;
483
484 // TODO: We should be able to replace undefs with the right pointer type.
485
486 // TODO: If we know the other base object is another promotable
487 // alloca, not necessarily this alloca, we can do this. The
488 // important part is both must have the same address space at
489 // the end.
490 if (OtherObj != BaseAlloca) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000491 LLVM_DEBUG(
492 dbgs() << "Found a binary instruction with another alloca object\n");
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000493 return false;
494 }
495
496 return true;
497}
498
499bool AMDGPUPromoteAlloca::collectUsesWithPtrTypes(
500 Value *BaseAlloca,
501 Value *Val,
502 std::vector<Value*> &WorkList) const {
503
Tom Stellard880a80a2014-06-17 16:53:14 +0000504 for (User *User : Val->users()) {
David Majnemer0d955d02016-08-11 22:21:41 +0000505 if (is_contained(WorkList, User))
Tom Stellard880a80a2014-06-17 16:53:14 +0000506 continue;
Matt Arsenaultad134842016-02-02 19:18:53 +0000507
Matt Arsenaultfdcd39a2015-07-28 18:29:14 +0000508 if (CallInst *CI = dyn_cast<CallInst>(User)) {
Matt Arsenaultad134842016-02-02 19:18:53 +0000509 if (!isCallPromotable(CI))
Matt Arsenaultfdcd39a2015-07-28 18:29:14 +0000510 return false;
511
Tom Stellard880a80a2014-06-17 16:53:14 +0000512 WorkList.push_back(User);
513 continue;
514 }
Tom Stellard5b2927f2014-10-31 20:52:04 +0000515
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000516 Instruction *UseInst = cast<Instruction>(User);
517 if (UseInst->getOpcode() == Instruction::PtrToInt)
Tom Stellard5b2927f2014-10-31 20:52:04 +0000518 return false;
519
Matt Arsenault210b7cf2016-07-18 19:00:07 +0000520 if (LoadInst *LI = dyn_cast<LoadInst>(UseInst)) {
Matt Arsenaultc438ef52016-05-18 23:20:24 +0000521 if (LI->isVolatile())
522 return false;
523
524 continue;
525 }
526
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000527 if (StoreInst *SI = dyn_cast<StoreInst>(UseInst)) {
Matt Arsenault0a30e452016-03-23 23:17:29 +0000528 if (SI->isVolatile())
529 return false;
530
Matt Arsenault7227cc12015-07-28 18:47:00 +0000531 // Reject if the stored value is not the pointer operand.
532 if (SI->getPointerOperand() != Val)
533 return false;
Matt Arsenault210b7cf2016-07-18 19:00:07 +0000534 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UseInst)) {
Matt Arsenault0a30e452016-03-23 23:17:29 +0000535 if (RMW->isVolatile())
536 return false;
Matt Arsenault210b7cf2016-07-18 19:00:07 +0000537 } else if (AtomicCmpXchgInst *CAS = dyn_cast<AtomicCmpXchgInst>(UseInst)) {
Matt Arsenault0a30e452016-03-23 23:17:29 +0000538 if (CAS->isVolatile())
539 return false;
Matt Arsenault7227cc12015-07-28 18:47:00 +0000540 }
541
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000542 // Only promote a select if we know that the other select operand
543 // is from another pointer that will also be promoted.
544 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
545 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, ICmp, 0, 1))
546 return false;
Matt Arsenault891fccc2016-05-18 15:57:21 +0000547
548 // May need to rewrite constant operands.
549 WorkList.push_back(ICmp);
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000550 }
551
Matt Arsenault2402b952016-12-10 00:52:50 +0000552 if (UseInst->getOpcode() == Instruction::AddrSpaceCast) {
Changpeng Fangc85abbd2017-01-24 19:06:28 +0000553 // Give up if the pointer may be captured.
554 if (PointerMayBeCaptured(UseInst, true, true))
555 return false;
Matt Arsenault2402b952016-12-10 00:52:50 +0000556 // Don't collect the users of this.
557 WorkList.push_back(User);
558 continue;
559 }
560
Tom Stellard880a80a2014-06-17 16:53:14 +0000561 if (!User->getType()->isPointerTy())
562 continue;
Tom Stellard5b2927f2014-10-31 20:52:04 +0000563
Matt Arsenaultde420812016-02-02 21:16:12 +0000564 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UseInst)) {
565 // Be conservative if an address could be computed outside the bounds of
566 // the alloca.
567 if (!GEP->isInBounds())
568 return false;
569 }
570
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000571 // Only promote a select if we know that the other select operand is from
572 // another pointer that will also be promoted.
573 if (SelectInst *SI = dyn_cast<SelectInst>(UseInst)) {
574 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, SI, 1, 2))
575 return false;
576 }
577
578 // Repeat for phis.
579 if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
580 // TODO: Handle more complex cases. We should be able to replace loops
581 // over arrays.
582 switch (Phi->getNumIncomingValues()) {
583 case 1:
584 break;
585 case 2:
586 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, Phi, 0, 1))
587 return false;
588 break;
589 default:
590 return false;
591 }
592 }
593
Tom Stellard880a80a2014-06-17 16:53:14 +0000594 WorkList.push_back(User);
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000595 if (!collectUsesWithPtrTypes(BaseAlloca, User, WorkList))
Matt Arsenaultad134842016-02-02 19:18:53 +0000596 return false;
Tom Stellard880a80a2014-06-17 16:53:14 +0000597 }
Matt Arsenaultad134842016-02-02 19:18:53 +0000598
599 return true;
Tom Stellard880a80a2014-06-17 16:53:14 +0000600}
601
Changpeng Fang1dbace12017-05-23 20:25:41 +0000602bool AMDGPUPromoteAlloca::hasSufficientLocalMem(const Function &F) {
603
604 FunctionType *FTy = F.getFunctionType();
Tom Stellardc5a154d2018-06-28 23:47:12 +0000605 const AMDGPUCommonSubtarget &ST = AMDGPUCommonSubtarget::get(*TM, F);
Changpeng Fang1dbace12017-05-23 20:25:41 +0000606
607 // If the function has any arguments in the local address space, then it's
608 // possible these arguments require the entire local memory space, so
609 // we cannot use local memory in the pass.
610 for (Type *ParamTy : FTy->params()) {
611 PointerType *PtrTy = dyn_cast<PointerType>(ParamTy);
612 if (PtrTy && PtrTy->getAddressSpace() == AS.LOCAL_ADDRESS) {
613 LocalMemLimit = 0;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000614 LLVM_DEBUG(dbgs() << "Function has local memory argument. Promoting to "
615 "local memory disabled.\n");
Changpeng Fang1dbace12017-05-23 20:25:41 +0000616 return false;
617 }
618 }
619
620 LocalMemLimit = ST.getLocalMemorySize();
621 if (LocalMemLimit == 0)
622 return false;
623
624 const DataLayout &DL = Mod->getDataLayout();
625
626 // Check how much local memory is being used by global objects
627 CurrentLocalMemUsage = 0;
628 for (GlobalVariable &GV : Mod->globals()) {
629 if (GV.getType()->getAddressSpace() != AS.LOCAL_ADDRESS)
630 continue;
631
632 for (const User *U : GV.users()) {
633 const Instruction *Use = dyn_cast<Instruction>(U);
634 if (!Use)
635 continue;
636
637 if (Use->getParent()->getParent() == &F) {
638 unsigned Align = GV.getAlignment();
639 if (Align == 0)
640 Align = DL.getABITypeAlignment(GV.getValueType());
641
642 // FIXME: Try to account for padding here. The padding is currently
643 // determined from the inverse order of uses in the function. I'm not
644 // sure if the use list order is in any way connected to this, so the
645 // total reported size is likely incorrect.
646 uint64_t AllocSize = DL.getTypeAllocSize(GV.getValueType());
647 CurrentLocalMemUsage = alignTo(CurrentLocalMemUsage, Align);
648 CurrentLocalMemUsage += AllocSize;
649 break;
650 }
651 }
652 }
653
654 unsigned MaxOccupancy = ST.getOccupancyWithLocalMemSize(CurrentLocalMemUsage,
655 F);
656
657 // Restrict local memory usage so that we don't drastically reduce occupancy,
658 // unless it is already significantly reduced.
659
660 // TODO: Have some sort of hint or other heuristics to guess occupancy based
661 // on other factors..
662 unsigned OccupancyHint = ST.getWavesPerEU(F).second;
663 if (OccupancyHint == 0)
664 OccupancyHint = 7;
665
666 // Clamp to max value.
667 OccupancyHint = std::min(OccupancyHint, ST.getMaxWavesPerEU());
668
669 // Check the hint but ignore it if it's obviously wrong from the existing LDS
670 // usage.
671 MaxOccupancy = std::min(OccupancyHint, MaxOccupancy);
672
673
674 // Round up to the next tier of usage.
675 unsigned MaxSizeWithWaveCount
676 = ST.getMaxLocalMemSizeWithWaveCount(MaxOccupancy, F);
677
678 // Program is possibly broken by using more local mem than available.
679 if (CurrentLocalMemUsage > MaxSizeWithWaveCount)
680 return false;
681
682 LocalMemLimit = MaxSizeWithWaveCount;
683
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000684 LLVM_DEBUG(dbgs() << F.getName() << " uses " << CurrentLocalMemUsage
685 << " bytes of LDS\n"
686 << " Rounding size to " << MaxSizeWithWaveCount
687 << " with a maximum occupancy of " << MaxOccupancy << '\n'
688 << " and " << (LocalMemLimit - CurrentLocalMemUsage)
689 << " available for promotion\n");
Changpeng Fang1dbace12017-05-23 20:25:41 +0000690
691 return true;
692}
693
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000694// FIXME: Should try to pick the most likely to be profitable allocas first.
Changpeng Fang1dbace12017-05-23 20:25:41 +0000695bool AMDGPUPromoteAlloca::handleAlloca(AllocaInst &I, bool SufficientLDS) {
Matt Arsenaultc5fce692016-04-28 18:38:48 +0000696 // Array allocations are probably not worth handling, since an allocation of
697 // the array type is the canonical form.
698 if (!I.isStaticAlloca() || I.isArrayAllocation())
Changpeng Fang1dbace12017-05-23 20:25:41 +0000699 return false;
Matt Arsenault19c54882015-08-26 18:37:13 +0000700
Tom Stellard880a80a2014-06-17 16:53:14 +0000701 IRBuilder<> Builder(&I);
702
703 // First try to replace the alloca with a vector
704 Type *AllocaTy = I.getAllocatedType();
705
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000706 LLVM_DEBUG(dbgs() << "Trying to promote " << I << '\n');
Tom Stellard880a80a2014-06-17 16:53:14 +0000707
Changpeng Fang1dbace12017-05-23 20:25:41 +0000708 if (tryPromoteAllocaToVector(&I, AS))
709 return true; // Promoted to vector.
Tom Stellard880a80a2014-06-17 16:53:14 +0000710
Tom Stellard79a1fd72016-04-14 16:27:07 +0000711 const Function &ContainingFunction = *I.getParent()->getParent();
Matt Arsenault5c806182017-05-02 18:33:18 +0000712 CallingConv::ID CC = ContainingFunction.getCallingConv();
Tom Stellard79a1fd72016-04-14 16:27:07 +0000713
Nicolai Haehnlebef1ceb2016-07-18 09:02:47 +0000714 // Don't promote the alloca to LDS for shader calling conventions as the work
715 // item ID intrinsics are not supported for these calling conventions.
716 // Furthermore not all LDS is available for some of the stages.
Matt Arsenault5c806182017-05-02 18:33:18 +0000717 switch (CC) {
718 case CallingConv::AMDGPU_KERNEL:
719 case CallingConv::SPIR_KERNEL:
720 break;
721 default:
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000722 LLVM_DEBUG(
723 dbgs()
724 << " promote alloca to LDS not supported with calling convention.\n");
Changpeng Fang1dbace12017-05-23 20:25:41 +0000725 return false;
Matt Arsenault5c806182017-05-02 18:33:18 +0000726 }
Nicolai Haehnlebef1ceb2016-07-18 09:02:47 +0000727
Changpeng Fang1dbace12017-05-23 20:25:41 +0000728 // Not likely to have sufficient local memory for promotion.
729 if (!SufficientLDS)
730 return false;
731
Tom Stellardc5a154d2018-06-28 23:47:12 +0000732 const AMDGPUCommonSubtarget &ST = AMDGPUCommonSubtarget::get(*TM, ContainingFunction);
Konstantin Zhuravlyov1d650262016-09-06 20:22:28 +0000733 unsigned WorkGroupSize = ST.getFlatWorkGroupSizes(ContainingFunction).second;
Tom Stellard79a1fd72016-04-14 16:27:07 +0000734
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000735 const DataLayout &DL = Mod->getDataLayout();
Tom Stellard880a80a2014-06-17 16:53:14 +0000736
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000737 unsigned Align = I.getAlignment();
738 if (Align == 0)
739 Align = DL.getABITypeAlignment(I.getAllocatedType());
740
741 // FIXME: This computed padding is likely wrong since it depends on inverse
742 // usage order.
743 //
744 // FIXME: It is also possible that if we're allowed to use all of the memory
745 // could could end up using more than the maximum due to alignment padding.
746
747 uint32_t NewSize = alignTo(CurrentLocalMemUsage, Align);
748 uint32_t AllocSize = WorkGroupSize * DL.getTypeAllocSize(AllocaTy);
749 NewSize += AllocSize;
750
751 if (NewSize > LocalMemLimit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000752 LLVM_DEBUG(dbgs() << " " << AllocSize
753 << " bytes of local memory not available to promote\n");
Changpeng Fang1dbace12017-05-23 20:25:41 +0000754 return false;
Tom Stellard880a80a2014-06-17 16:53:14 +0000755 }
756
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000757 CurrentLocalMemUsage = NewSize;
758
Tom Stellard5b2927f2014-10-31 20:52:04 +0000759 std::vector<Value*> WorkList;
760
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000761 if (!collectUsesWithPtrTypes(&I, &I, WorkList)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000762 LLVM_DEBUG(dbgs() << " Do not know how to convert all uses\n");
Changpeng Fang1dbace12017-05-23 20:25:41 +0000763 return false;
Tom Stellard5b2927f2014-10-31 20:52:04 +0000764 }
765
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000766 LLVM_DEBUG(dbgs() << "Promoting alloca to local memory\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000767
Matt Arsenaultcf84e262016-02-05 19:47:23 +0000768 Function *F = I.getParent()->getParent();
769
Tom Stellard79a1fd72016-04-14 16:27:07 +0000770 Type *GVTy = ArrayType::get(I.getAllocatedType(), WorkGroupSize);
Tom Stellard880a80a2014-06-17 16:53:14 +0000771 GlobalVariable *GV = new GlobalVariable(
Matt Arsenaultcf84e262016-02-05 19:47:23 +0000772 *Mod, GVTy, false, GlobalValue::InternalLinkage,
773 UndefValue::get(GVTy),
774 Twine(F->getName()) + Twine('.') + I.getName(),
775 nullptr,
776 GlobalVariable::NotThreadLocal,
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000777 AS.LOCAL_ADDRESS);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000778 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Matt Arsenaultcf84e262016-02-05 19:47:23 +0000779 GV->setAlignment(I.getAlignment());
Tom Stellard880a80a2014-06-17 16:53:14 +0000780
Matt Arsenaulte0132462016-01-30 05:19:45 +0000781 Value *TCntY, *TCntZ;
Tom Stellard880a80a2014-06-17 16:53:14 +0000782
Matt Arsenaulte0132462016-01-30 05:19:45 +0000783 std::tie(TCntY, TCntZ) = getLocalSizeYZ(Builder);
784 Value *TIdX = getWorkitemID(Builder, 0);
785 Value *TIdY = getWorkitemID(Builder, 1);
786 Value *TIdZ = getWorkitemID(Builder, 2);
Tom Stellard880a80a2014-06-17 16:53:14 +0000787
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000788 Value *Tmp0 = Builder.CreateMul(TCntY, TCntZ, "", true, true);
Tom Stellard880a80a2014-06-17 16:53:14 +0000789 Tmp0 = Builder.CreateMul(Tmp0, TIdX);
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000790 Value *Tmp1 = Builder.CreateMul(TIdY, TCntZ, "", true, true);
Tom Stellard880a80a2014-06-17 16:53:14 +0000791 Value *TID = Builder.CreateAdd(Tmp0, Tmp1);
792 TID = Builder.CreateAdd(TID, TIdZ);
793
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000794 Value *Indices[] = {
795 Constant::getNullValue(Type::getInt32Ty(Mod->getContext())),
796 TID
797 };
Tom Stellard880a80a2014-06-17 16:53:14 +0000798
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000799 Value *Offset = Builder.CreateInBoundsGEP(GVTy, GV, Indices);
Tom Stellard880a80a2014-06-17 16:53:14 +0000800 I.mutateType(Offset->getType());
801 I.replaceAllUsesWith(Offset);
802 I.eraseFromParent();
803
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000804 for (Value *V : WorkList) {
Tom Stellard880a80a2014-06-17 16:53:14 +0000805 CallInst *Call = dyn_cast<CallInst>(V);
806 if (!Call) {
Matt Arsenault891fccc2016-05-18 15:57:21 +0000807 if (ICmpInst *CI = dyn_cast<ICmpInst>(V)) {
808 Value *Src0 = CI->getOperand(0);
809 Type *EltTy = Src0->getType()->getPointerElementType();
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000810 PointerType *NewTy = PointerType::get(EltTy, AS.LOCAL_ADDRESS);
Matt Arsenault891fccc2016-05-18 15:57:21 +0000811
812 if (isa<ConstantPointerNull>(CI->getOperand(0)))
813 CI->setOperand(0, ConstantPointerNull::get(NewTy));
814
815 if (isa<ConstantPointerNull>(CI->getOperand(1)))
816 CI->setOperand(1, ConstantPointerNull::get(NewTy));
817
818 continue;
819 }
Matt Arsenault65f67e42014-09-15 15:41:44 +0000820
Matt Arsenault2402b952016-12-10 00:52:50 +0000821 // The operand's value should be corrected on its own and we don't want to
822 // touch the users.
Matt Arsenault65f67e42014-09-15 15:41:44 +0000823 if (isa<AddrSpaceCastInst>(V))
824 continue;
825
Matt Arsenault891fccc2016-05-18 15:57:21 +0000826 Type *EltTy = V->getType()->getPointerElementType();
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000827 PointerType *NewTy = PointerType::get(EltTy, AS.LOCAL_ADDRESS);
Matt Arsenault891fccc2016-05-18 15:57:21 +0000828
Matt Arsenault65f67e42014-09-15 15:41:44 +0000829 // FIXME: It doesn't really make sense to try to do this for all
830 // instructions.
Tom Stellard880a80a2014-06-17 16:53:14 +0000831 V->mutateType(NewTy);
Matt Arsenault891fccc2016-05-18 15:57:21 +0000832
833 // Adjust the types of any constant operands.
834 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
835 if (isa<ConstantPointerNull>(SI->getOperand(1)))
836 SI->setOperand(1, ConstantPointerNull::get(NewTy));
837
838 if (isa<ConstantPointerNull>(SI->getOperand(2)))
839 SI->setOperand(2, ConstantPointerNull::get(NewTy));
840 } else if (PHINode *Phi = dyn_cast<PHINode>(V)) {
841 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
842 if (isa<ConstantPointerNull>(Phi->getIncomingValue(I)))
843 Phi->setIncomingValue(I, ConstantPointerNull::get(NewTy));
844 }
845 }
846
Tom Stellard880a80a2014-06-17 16:53:14 +0000847 continue;
848 }
849
Matt Arsenault2e08e182016-07-18 18:34:48 +0000850 IntrinsicInst *Intr = cast<IntrinsicInst>(Call);
Tom Stellard880a80a2014-06-17 16:53:14 +0000851 Builder.SetInsertPoint(Intr);
852 switch (Intr->getIntrinsicID()) {
853 case Intrinsic::lifetime_start:
854 case Intrinsic::lifetime_end:
855 // These intrinsics are for address space 0 only
856 Intr->eraseFromParent();
857 continue;
858 case Intrinsic::memcpy: {
859 MemCpyInst *MemCpy = cast<MemCpyInst>(Intr);
Daniel Neilsona60f4622018-02-09 21:56:15 +0000860 Builder.CreateMemCpy(MemCpy->getRawDest(), MemCpy->getDestAlignment(),
861 MemCpy->getRawSource(), MemCpy->getSourceAlignment(),
862 MemCpy->getLength(), MemCpy->isVolatile());
Tom Stellard880a80a2014-06-17 16:53:14 +0000863 Intr->eraseFromParent();
864 continue;
865 }
Matt Arsenault7e747f12016-02-02 20:28:10 +0000866 case Intrinsic::memmove: {
867 MemMoveInst *MemMove = cast<MemMoveInst>(Intr);
Daniel Neilsona60f4622018-02-09 21:56:15 +0000868 Builder.CreateMemMove(MemMove->getRawDest(), MemMove->getDestAlignment(),
869 MemMove->getRawSource(), MemMove->getSourceAlignment(),
870 MemMove->getLength(), MemMove->isVolatile());
Matt Arsenault7e747f12016-02-02 20:28:10 +0000871 Intr->eraseFromParent();
872 continue;
873 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000874 case Intrinsic::memset: {
875 MemSetInst *MemSet = cast<MemSetInst>(Intr);
876 Builder.CreateMemSet(MemSet->getRawDest(), MemSet->getValue(),
Daniel Neilsona60f4622018-02-09 21:56:15 +0000877 MemSet->getLength(), MemSet->getDestAlignment(),
Tom Stellard880a80a2014-06-17 16:53:14 +0000878 MemSet->isVolatile());
879 Intr->eraseFromParent();
880 continue;
881 }
Matt Arsenault0b783ef02016-01-22 19:47:54 +0000882 case Intrinsic::invariant_start:
883 case Intrinsic::invariant_end:
Piotr Padlewski5dde8092018-05-03 11:03:01 +0000884 case Intrinsic::launder_invariant_group:
Matt Arsenault0b783ef02016-01-22 19:47:54 +0000885 Intr->eraseFromParent();
886 // FIXME: I think the invariant marker should still theoretically apply,
887 // but the intrinsics need to be changed to accept pointers with any
888 // address space.
889 continue;
Matt Arsenault7e747f12016-02-02 20:28:10 +0000890 case Intrinsic::objectsize: {
891 Value *Src = Intr->getOperand(0);
892 Type *SrcTy = Src->getType()->getPointerElementType();
893 Function *ObjectSize = Intrinsic::getDeclaration(Mod,
894 Intrinsic::objectsize,
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000895 { Intr->getType(), PointerType::get(SrcTy, AS.LOCAL_ADDRESS) }
Matt Arsenault7e747f12016-02-02 20:28:10 +0000896 );
897
George Burgess IV56c7e882017-03-21 20:08:59 +0000898 CallInst *NewCall = Builder.CreateCall(
899 ObjectSize, {Src, Intr->getOperand(1), Intr->getOperand(2)});
Matt Arsenault7e747f12016-02-02 20:28:10 +0000900 Intr->replaceAllUsesWith(NewCall);
901 Intr->eraseFromParent();
902 continue;
903 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000904 default:
Matthias Braun8c209aa2017-01-28 02:02:38 +0000905 Intr->print(errs());
Tom Stellard880a80a2014-06-17 16:53:14 +0000906 llvm_unreachable("Don't know how to promote alloca intrinsic use.");
907 }
908 }
Changpeng Fang1dbace12017-05-23 20:25:41 +0000909 return true;
Tom Stellard880a80a2014-06-17 16:53:14 +0000910}
911
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000912FunctionPass *llvm::createAMDGPUPromoteAlloca() {
913 return new AMDGPUPromoteAlloca();
Tom Stellard880a80a2014-06-17 16:53:14 +0000914}