blob: 00fd47f6d7d6163c61f301924e2a7dd75a8610fe [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
Matt Arsenaulte0132462016-01-30 05:19:45 +000068// FIXME: This can create globals so should be a module pass.
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +000069class AMDGPUPromoteAlloca : public FunctionPass {
Matt Arsenaulte0132462016-01-30 05:19:45 +000070private:
71 const TargetMachine *TM;
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000072 Module *Mod = nullptr;
73 const DataLayout *DL = nullptr;
Yaxun Liu1a14bfa2017-03-27 14:04:01 +000074 AMDGPUAS AS;
Matt Arsenaulte0132462016-01-30 05:19:45 +000075
76 // FIXME: This should be per-kernel.
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000077 uint32_t LocalMemLimit = 0;
78 uint32_t CurrentLocalMemUsage = 0;
Tom Stellard880a80a2014-06-17 16:53:14 +000079
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000080 bool IsAMDGCN = false;
81 bool IsAMDHSA = false;
Matt Arsenaulte0132462016-01-30 05:19:45 +000082
83 std::pair<Value *, Value *> getLocalSizeYZ(IRBuilder<> &Builder);
84 Value *getWorkitemID(IRBuilder<> &Builder, unsigned N);
85
Matt Arsenaulta61cb482016-05-12 01:58:58 +000086 /// BaseAlloca is the alloca root the search started from.
87 /// Val may be that alloca or a recursive user of it.
88 bool collectUsesWithPtrTypes(Value *BaseAlloca,
89 Value *Val,
90 std::vector<Value*> &WorkList) const;
91
92 /// Val is a derived pointer from Alloca. OpIdx0/OpIdx1 are the operand
93 /// indices to an instruction with 2 pointer inputs (e.g. select, icmp).
94 /// Returns true if both operands are derived from the same alloca. Val should
95 /// be the same value as one of the input operands of UseInst.
96 bool binaryOpIsDerivedFromSameAlloca(Value *Alloca, Value *Val,
97 Instruction *UseInst,
98 int OpIdx0, int OpIdx1) const;
99
Changpeng Fang1dbace12017-05-23 20:25:41 +0000100 /// Check whether we have enough local memory for promotion.
101 bool hasSufficientLocalMem(const Function &F);
102
Tom Stellard880a80a2014-06-17 16:53:14 +0000103public:
Matt Arsenaulte0132462016-01-30 05:19:45 +0000104 static char ID;
105
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000106 AMDGPUPromoteAlloca() : FunctionPass(ID) {}
Matt Arsenaulte0132462016-01-30 05:19:45 +0000107
Benjamin Kramer8c90fd72014-09-03 11:41:21 +0000108 bool doInitialization(Module &M) override;
109 bool runOnFunction(Function &F) override;
Matt Arsenaulte0132462016-01-30 05:19:45 +0000110
Mehdi Amini117296c2016-10-01 02:56:57 +0000111 StringRef getPassName() const override { return "AMDGPU Promote Alloca"; }
Matt Arsenaulte0132462016-01-30 05:19:45 +0000112
Changpeng Fang1dbace12017-05-23 20:25:41 +0000113 bool handleAlloca(AllocaInst &I, bool SufficientLDS);
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000114
115 void getAnalysisUsage(AnalysisUsage &AU) const override {
116 AU.setPreservesCFG();
117 FunctionPass::getAnalysisUsage(AU);
118 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000119};
120
Eugene Zelenko734bb7b2017-01-20 17:52:16 +0000121} // end anonymous namespace
Tom Stellard880a80a2014-06-17 16:53:14 +0000122
123char AMDGPUPromoteAlloca::ID = 0;
124
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000125INITIALIZE_PASS(AMDGPUPromoteAlloca, DEBUG_TYPE,
126 "AMDGPU promote alloca to vector or LDS", false, false)
Matt Arsenaulte0132462016-01-30 05:19:45 +0000127
128char &llvm::AMDGPUPromoteAllocaID = AMDGPUPromoteAlloca::ID;
129
Tom Stellard880a80a2014-06-17 16:53:14 +0000130bool AMDGPUPromoteAlloca::doInitialization(Module &M) {
131 Mod = &M;
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000132 DL = &Mod->getDataLayout();
Matt Arsenaulte0132462016-01-30 05:19:45 +0000133
Tom Stellard880a80a2014-06-17 16:53:14 +0000134 return false;
135}
136
137bool AMDGPUPromoteAlloca::runOnFunction(Function &F) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000138 if (skipFunction(F))
Matt Arsenaulte0132462016-01-30 05:19:45 +0000139 return false;
140
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000141 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>())
142 TM = &TPC->getTM<TargetMachine>();
143 else
144 return false;
145
146 const Triple &TT = TM->getTargetTriple();
147 IsAMDGCN = TT.getArch() == Triple::amdgcn;
148 IsAMDHSA = TT.getOS() == Triple::AMDHSA;
149
Matt Arsenault03d85842016-06-27 20:32:13 +0000150 const AMDGPUSubtarget &ST = TM->getSubtarget<AMDGPUSubtarget>(F);
151 if (!ST.isPromoteAllocaEnabled())
152 return false;
Changpeng Fang1dbace12017-05-23 20:25:41 +0000153
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000154 AS = AMDGPU::getAMDGPUAS(*F.getParent());
Matt Arsenault03d85842016-06-27 20:32:13 +0000155
Changpeng Fang1dbace12017-05-23 20:25:41 +0000156 bool SufficientLDS = hasSufficientLocalMem(F);
157 bool Changed = false;
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +0000158 BasicBlock &EntryBB = *F.begin();
159 for (auto I = EntryBB.begin(), E = EntryBB.end(); I != E; ) {
160 AllocaInst *AI = dyn_cast<AllocaInst>(I);
161
162 ++I;
163 if (AI)
Changpeng Fang1dbace12017-05-23 20:25:41 +0000164 Changed |= handleAlloca(*AI, SufficientLDS);
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +0000165 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000166
Changpeng Fang1dbace12017-05-23 20:25:41 +0000167 return Changed;
Tom Stellard880a80a2014-06-17 16:53:14 +0000168}
169
Matt Arsenaulte0132462016-01-30 05:19:45 +0000170std::pair<Value *, Value *>
171AMDGPUPromoteAlloca::getLocalSizeYZ(IRBuilder<> &Builder) {
Stanislav Mekhanoshinc90347d2017-04-12 20:48:56 +0000172 const AMDGPUSubtarget &ST = TM->getSubtarget<AMDGPUSubtarget>(
173 *Builder.GetInsertBlock()->getParent());
174
Matt Arsenaulte0132462016-01-30 05:19:45 +0000175 if (!IsAMDHSA) {
176 Function *LocalSizeYFn
177 = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_y);
178 Function *LocalSizeZFn
179 = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_z);
180
181 CallInst *LocalSizeY = Builder.CreateCall(LocalSizeYFn, {});
182 CallInst *LocalSizeZ = Builder.CreateCall(LocalSizeZFn, {});
183
Stanislav Mekhanoshinc90347d2017-04-12 20:48:56 +0000184 ST.makeLIDRangeMetadata(LocalSizeY);
185 ST.makeLIDRangeMetadata(LocalSizeZ);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000186
187 return std::make_pair(LocalSizeY, LocalSizeZ);
188 }
189
190 // We must read the size out of the dispatch pointer.
191 assert(IsAMDGCN);
192
193 // We are indexing into this struct, and want to extract the workgroup_size_*
194 // fields.
195 //
196 // typedef struct hsa_kernel_dispatch_packet_s {
197 // uint16_t header;
198 // uint16_t setup;
199 // uint16_t workgroup_size_x ;
200 // uint16_t workgroup_size_y;
201 // uint16_t workgroup_size_z;
202 // uint16_t reserved0;
203 // uint32_t grid_size_x ;
204 // uint32_t grid_size_y ;
205 // uint32_t grid_size_z;
206 //
207 // uint32_t private_segment_size;
208 // uint32_t group_segment_size;
209 // uint64_t kernel_object;
210 //
211 // #ifdef HSA_LARGE_MODEL
212 // void *kernarg_address;
213 // #elif defined HSA_LITTLE_ENDIAN
214 // void *kernarg_address;
215 // uint32_t reserved1;
216 // #else
217 // uint32_t reserved1;
218 // void *kernarg_address;
219 // #endif
220 // uint64_t reserved2;
221 // hsa_signal_t completion_signal; // uint64_t wrapper
222 // } hsa_kernel_dispatch_packet_t
223 //
224 Function *DispatchPtrFn
225 = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_dispatch_ptr);
226
227 CallInst *DispatchPtr = Builder.CreateCall(DispatchPtrFn, {});
Reid Klecknerb5180542017-03-21 16:57:19 +0000228 DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
229 DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000230
231 // Size of the dispatch packet struct.
Reid Klecknerb5180542017-03-21 16:57:19 +0000232 DispatchPtr->addDereferenceableAttr(AttributeList::ReturnIndex, 64);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000233
234 Type *I32Ty = Type::getInt32Ty(Mod->getContext());
235 Value *CastDispatchPtr = Builder.CreateBitCast(
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000236 DispatchPtr, PointerType::get(I32Ty, AS.CONSTANT_ADDRESS));
Matt Arsenaulte0132462016-01-30 05:19:45 +0000237
238 // We could do a single 64-bit load here, but it's likely that the basic
239 // 32-bit and extract sequence is already present, and it is probably easier
240 // to CSE this. The loads should be mergable later anyway.
241 Value *GEPXY = Builder.CreateConstInBoundsGEP1_64(CastDispatchPtr, 1);
242 LoadInst *LoadXY = Builder.CreateAlignedLoad(GEPXY, 4);
243
244 Value *GEPZU = Builder.CreateConstInBoundsGEP1_64(CastDispatchPtr, 2);
245 LoadInst *LoadZU = Builder.CreateAlignedLoad(GEPZU, 4);
246
Eugene Zelenko734bb7b2017-01-20 17:52:16 +0000247 MDNode *MD = MDNode::get(Mod->getContext(), None);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000248 LoadXY->setMetadata(LLVMContext::MD_invariant_load, MD);
249 LoadZU->setMetadata(LLVMContext::MD_invariant_load, MD);
Stanislav Mekhanoshinc90347d2017-04-12 20:48:56 +0000250 ST.makeLIDRangeMetadata(LoadZU);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000251
252 // Extract y component. Upper half of LoadZU should be zero already.
253 Value *Y = Builder.CreateLShr(LoadXY, 16);
254
255 return std::make_pair(Y, LoadZU);
256}
257
258Value *AMDGPUPromoteAlloca::getWorkitemID(IRBuilder<> &Builder, unsigned N) {
Stanislav Mekhanoshinc90347d2017-04-12 20:48:56 +0000259 const AMDGPUSubtarget &ST = TM->getSubtarget<AMDGPUSubtarget>(
260 *Builder.GetInsertBlock()->getParent());
Matt Arsenaulte0132462016-01-30 05:19:45 +0000261 Intrinsic::ID IntrID = Intrinsic::ID::not_intrinsic;
262
263 switch (N) {
264 case 0:
265 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_x
266 : Intrinsic::r600_read_tidig_x;
267 break;
268 case 1:
269 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_y
270 : Intrinsic::r600_read_tidig_y;
271 break;
272
273 case 2:
274 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_z
275 : Intrinsic::r600_read_tidig_z;
276 break;
277 default:
278 llvm_unreachable("invalid dimension");
279 }
280
281 Function *WorkitemIdFn = Intrinsic::getDeclaration(Mod, IntrID);
282 CallInst *CI = Builder.CreateCall(WorkitemIdFn);
Stanislav Mekhanoshinc90347d2017-04-12 20:48:56 +0000283 ST.makeLIDRangeMetadata(CI);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000284
285 return CI;
286}
287
Craig Toppere3dcce92015-08-01 22:20:21 +0000288static VectorType *arrayTypeToVecType(Type *ArrayTy) {
Tom Stellard880a80a2014-06-17 16:53:14 +0000289 return VectorType::get(ArrayTy->getArrayElementType(),
290 ArrayTy->getArrayNumElements());
291}
292
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +0000293static Value *
294calculateVectorIndex(Value *Ptr,
295 const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
Tom Stellard880a80a2014-06-17 16:53:14 +0000296 GetElementPtrInst *GEP = cast<GetElementPtrInst>(Ptr);
297
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +0000298 auto I = GEPIdx.find(GEP);
299 return I == GEPIdx.end() ? nullptr : I->second;
Tom Stellard880a80a2014-06-17 16:53:14 +0000300}
301
302static Value* GEPToVectorIndex(GetElementPtrInst *GEP) {
303 // FIXME we only support simple cases
304 if (GEP->getNumOperands() != 3)
Matt Arsenaultefb24542016-07-18 18:34:53 +0000305 return nullptr;
Tom Stellard880a80a2014-06-17 16:53:14 +0000306
307 ConstantInt *I0 = dyn_cast<ConstantInt>(GEP->getOperand(1));
308 if (!I0 || !I0->isZero())
Matt Arsenaultefb24542016-07-18 18:34:53 +0000309 return nullptr;
Tom Stellard880a80a2014-06-17 16:53:14 +0000310
311 return GEP->getOperand(2);
312}
313
Matt Arsenault642d2e72014-06-27 16:52:49 +0000314// Not an instruction handled below to turn into a vector.
315//
316// TODO: Check isTriviallyVectorizable for calls and handle other
317// instructions.
Matt Arsenault7227cc12015-07-28 18:47:00 +0000318static bool canVectorizeInst(Instruction *Inst, User *User) {
Matt Arsenault642d2e72014-06-27 16:52:49 +0000319 switch (Inst->getOpcode()) {
Changpeng Fang161e8c39af2017-05-12 20:31:12 +0000320 case Instruction::Load: {
321 LoadInst *LI = cast<LoadInst>(Inst);
322 return !LI->isVolatile();
323 }
Matt Arsenault642d2e72014-06-27 16:52:49 +0000324 case Instruction::BitCast:
325 case Instruction::AddrSpaceCast:
326 return true;
Matt Arsenault7227cc12015-07-28 18:47:00 +0000327 case Instruction::Store: {
328 // Must be the stored pointer operand, not a stored value.
329 StoreInst *SI = cast<StoreInst>(Inst);
Changpeng Fang161e8c39af2017-05-12 20:31:12 +0000330 return (SI->getPointerOperand() == User) && !SI->isVolatile();
Matt Arsenault7227cc12015-07-28 18:47:00 +0000331 }
Matt Arsenault642d2e72014-06-27 16:52:49 +0000332 default:
333 return false;
334 }
335}
336
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000337static bool tryPromoteAllocaToVector(AllocaInst *Alloca, AMDGPUAS AS) {
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000338 ArrayType *AllocaTy = dyn_cast<ArrayType>(Alloca->getAllocatedType());
Tom Stellard880a80a2014-06-17 16:53:14 +0000339
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000340 DEBUG(dbgs() << "Alloca candidate for vectorization\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000341
342 // FIXME: There is no reason why we can't support larger arrays, we
343 // are just being conservative for now.
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000344 if (!AllocaTy ||
345 AllocaTy->getElementType()->isVectorTy() ||
Matt Arsenaultefb24542016-07-18 18:34:53 +0000346 AllocaTy->getNumElements() > 4 ||
347 AllocaTy->getNumElements() < 2) {
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000348 DEBUG(dbgs() << " Cannot convert type to vector\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000349 return false;
350 }
351
352 std::map<GetElementPtrInst*, Value*> GEPVectorIdx;
353 std::vector<Value*> WorkList;
354 for (User *AllocaUser : Alloca->users()) {
355 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(AllocaUser);
356 if (!GEP) {
Matt Arsenault7227cc12015-07-28 18:47:00 +0000357 if (!canVectorizeInst(cast<Instruction>(AllocaUser), Alloca))
Matt Arsenault642d2e72014-06-27 16:52:49 +0000358 return false;
359
Tom Stellard880a80a2014-06-17 16:53:14 +0000360 WorkList.push_back(AllocaUser);
361 continue;
362 }
363
364 Value *Index = GEPToVectorIndex(GEP);
365
366 // If we can't compute a vector index from this GEP, then we can't
367 // promote this alloca to vector.
368 if (!Index) {
Matt Arsenault6f62cf82014-06-27 02:36:59 +0000369 DEBUG(dbgs() << " Cannot compute vector index for GEP " << *GEP << '\n');
Tom Stellard880a80a2014-06-17 16:53:14 +0000370 return false;
371 }
372
373 GEPVectorIdx[GEP] = Index;
374 for (User *GEPUser : AllocaUser->users()) {
Matt Arsenault7227cc12015-07-28 18:47:00 +0000375 if (!canVectorizeInst(cast<Instruction>(GEPUser), AllocaUser))
Matt Arsenault642d2e72014-06-27 16:52:49 +0000376 return false;
377
Tom Stellard880a80a2014-06-17 16:53:14 +0000378 WorkList.push_back(GEPUser);
379 }
380 }
381
382 VectorType *VectorTy = arrayTypeToVecType(AllocaTy);
383
Matt Arsenault6f62cf82014-06-27 02:36:59 +0000384 DEBUG(dbgs() << " Converting alloca to vector "
385 << *AllocaTy << " -> " << *VectorTy << '\n');
Tom Stellard880a80a2014-06-17 16:53:14 +0000386
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000387 for (Value *V : WorkList) {
388 Instruction *Inst = cast<Instruction>(V);
Tom Stellard880a80a2014-06-17 16:53:14 +0000389 IRBuilder<> Builder(Inst);
390 switch (Inst->getOpcode()) {
391 case Instruction::Load: {
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000392 Type *VecPtrTy = VectorTy->getPointerTo(AS.PRIVATE_ADDRESS);
Tom Stellard880a80a2014-06-17 16:53:14 +0000393 Value *Ptr = Inst->getOperand(0);
394 Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
Matt Arsenaultefb24542016-07-18 18:34:53 +0000395
396 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
Tom Stellard880a80a2014-06-17 16:53:14 +0000397 Value *VecValue = Builder.CreateLoad(BitCast);
398 Value *ExtractElement = Builder.CreateExtractElement(VecValue, Index);
399 Inst->replaceAllUsesWith(ExtractElement);
400 Inst->eraseFromParent();
401 break;
402 }
403 case Instruction::Store: {
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000404 Type *VecPtrTy = VectorTy->getPointerTo(AS.PRIVATE_ADDRESS);
Matt Arsenaultefb24542016-07-18 18:34:53 +0000405
Tom Stellard880a80a2014-06-17 16:53:14 +0000406 Value *Ptr = Inst->getOperand(1);
407 Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
Matt Arsenaultefb24542016-07-18 18:34:53 +0000408 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
Tom Stellard880a80a2014-06-17 16:53:14 +0000409 Value *VecValue = Builder.CreateLoad(BitCast);
410 Value *NewVecValue = Builder.CreateInsertElement(VecValue,
411 Inst->getOperand(0),
412 Index);
413 Builder.CreateStore(NewVecValue, BitCast);
414 Inst->eraseFromParent();
415 break;
416 }
417 case Instruction::BitCast:
Matt Arsenault642d2e72014-06-27 16:52:49 +0000418 case Instruction::AddrSpaceCast:
Tom Stellard880a80a2014-06-17 16:53:14 +0000419 break;
420
421 default:
Matt Arsenault642d2e72014-06-27 16:52:49 +0000422 llvm_unreachable("Inconsistency in instructions promotable to vector");
Tom Stellard880a80a2014-06-17 16:53:14 +0000423 }
424 }
425 return true;
426}
427
Matt Arsenaultad134842016-02-02 19:18:53 +0000428static bool isCallPromotable(CallInst *CI) {
Matt Arsenaultad134842016-02-02 19:18:53 +0000429 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
430 if (!II)
431 return false;
432
433 switch (II->getIntrinsicID()) {
434 case Intrinsic::memcpy:
Matt Arsenault7e747f12016-02-02 20:28:10 +0000435 case Intrinsic::memmove:
Matt Arsenaultad134842016-02-02 19:18:53 +0000436 case Intrinsic::memset:
437 case Intrinsic::lifetime_start:
438 case Intrinsic::lifetime_end:
439 case Intrinsic::invariant_start:
440 case Intrinsic::invariant_end:
441 case Intrinsic::invariant_group_barrier:
Matt Arsenault7e747f12016-02-02 20:28:10 +0000442 case Intrinsic::objectsize:
Matt Arsenaultad134842016-02-02 19:18:53 +0000443 return true;
444 default:
445 return false;
446 }
447}
448
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000449bool AMDGPUPromoteAlloca::binaryOpIsDerivedFromSameAlloca(Value *BaseAlloca,
450 Value *Val,
451 Instruction *Inst,
452 int OpIdx0,
453 int OpIdx1) const {
454 // Figure out which operand is the one we might not be promoting.
455 Value *OtherOp = Inst->getOperand(OpIdx0);
456 if (Val == OtherOp)
457 OtherOp = Inst->getOperand(OpIdx1);
458
Matt Arsenault891fccc2016-05-18 15:57:21 +0000459 if (isa<ConstantPointerNull>(OtherOp))
460 return true;
461
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000462 Value *OtherObj = GetUnderlyingObject(OtherOp, *DL);
463 if (!isa<AllocaInst>(OtherObj))
464 return false;
465
466 // TODO: We should be able to replace undefs with the right pointer type.
467
468 // TODO: If we know the other base object is another promotable
469 // alloca, not necessarily this alloca, we can do this. The
470 // important part is both must have the same address space at
471 // the end.
472 if (OtherObj != BaseAlloca) {
473 DEBUG(dbgs() << "Found a binary instruction with another alloca object\n");
474 return false;
475 }
476
477 return true;
478}
479
480bool AMDGPUPromoteAlloca::collectUsesWithPtrTypes(
481 Value *BaseAlloca,
482 Value *Val,
483 std::vector<Value*> &WorkList) const {
484
Tom Stellard880a80a2014-06-17 16:53:14 +0000485 for (User *User : Val->users()) {
David Majnemer0d955d02016-08-11 22:21:41 +0000486 if (is_contained(WorkList, User))
Tom Stellard880a80a2014-06-17 16:53:14 +0000487 continue;
Matt Arsenaultad134842016-02-02 19:18:53 +0000488
Matt Arsenaultfdcd39a2015-07-28 18:29:14 +0000489 if (CallInst *CI = dyn_cast<CallInst>(User)) {
Matt Arsenaultad134842016-02-02 19:18:53 +0000490 if (!isCallPromotable(CI))
Matt Arsenaultfdcd39a2015-07-28 18:29:14 +0000491 return false;
492
Tom Stellard880a80a2014-06-17 16:53:14 +0000493 WorkList.push_back(User);
494 continue;
495 }
Tom Stellard5b2927f2014-10-31 20:52:04 +0000496
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000497 Instruction *UseInst = cast<Instruction>(User);
498 if (UseInst->getOpcode() == Instruction::PtrToInt)
Tom Stellard5b2927f2014-10-31 20:52:04 +0000499 return false;
500
Matt Arsenault210b7cf2016-07-18 19:00:07 +0000501 if (LoadInst *LI = dyn_cast<LoadInst>(UseInst)) {
Matt Arsenaultc438ef52016-05-18 23:20:24 +0000502 if (LI->isVolatile())
503 return false;
504
505 continue;
506 }
507
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000508 if (StoreInst *SI = dyn_cast<StoreInst>(UseInst)) {
Matt Arsenault0a30e452016-03-23 23:17:29 +0000509 if (SI->isVolatile())
510 return false;
511
Matt Arsenault7227cc12015-07-28 18:47:00 +0000512 // Reject if the stored value is not the pointer operand.
513 if (SI->getPointerOperand() != Val)
514 return false;
Matt Arsenault210b7cf2016-07-18 19:00:07 +0000515 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UseInst)) {
Matt Arsenault0a30e452016-03-23 23:17:29 +0000516 if (RMW->isVolatile())
517 return false;
Matt Arsenault210b7cf2016-07-18 19:00:07 +0000518 } else if (AtomicCmpXchgInst *CAS = dyn_cast<AtomicCmpXchgInst>(UseInst)) {
Matt Arsenault0a30e452016-03-23 23:17:29 +0000519 if (CAS->isVolatile())
520 return false;
Matt Arsenault7227cc12015-07-28 18:47:00 +0000521 }
522
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000523 // Only promote a select if we know that the other select operand
524 // is from another pointer that will also be promoted.
525 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
526 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, ICmp, 0, 1))
527 return false;
Matt Arsenault891fccc2016-05-18 15:57:21 +0000528
529 // May need to rewrite constant operands.
530 WorkList.push_back(ICmp);
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000531 }
532
Matt Arsenault2402b952016-12-10 00:52:50 +0000533 if (UseInst->getOpcode() == Instruction::AddrSpaceCast) {
Changpeng Fangc85abbd2017-01-24 19:06:28 +0000534 // Give up if the pointer may be captured.
535 if (PointerMayBeCaptured(UseInst, true, true))
536 return false;
Matt Arsenault2402b952016-12-10 00:52:50 +0000537 // Don't collect the users of this.
538 WorkList.push_back(User);
539 continue;
540 }
541
Tom Stellard880a80a2014-06-17 16:53:14 +0000542 if (!User->getType()->isPointerTy())
543 continue;
Tom Stellard5b2927f2014-10-31 20:52:04 +0000544
Matt Arsenaultde420812016-02-02 21:16:12 +0000545 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UseInst)) {
546 // Be conservative if an address could be computed outside the bounds of
547 // the alloca.
548 if (!GEP->isInBounds())
549 return false;
550 }
551
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000552 // Only promote a select if we know that the other select operand is from
553 // another pointer that will also be promoted.
554 if (SelectInst *SI = dyn_cast<SelectInst>(UseInst)) {
555 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, SI, 1, 2))
556 return false;
557 }
558
559 // Repeat for phis.
560 if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
561 // TODO: Handle more complex cases. We should be able to replace loops
562 // over arrays.
563 switch (Phi->getNumIncomingValues()) {
564 case 1:
565 break;
566 case 2:
567 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, Phi, 0, 1))
568 return false;
569 break;
570 default:
571 return false;
572 }
573 }
574
Tom Stellard880a80a2014-06-17 16:53:14 +0000575 WorkList.push_back(User);
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000576 if (!collectUsesWithPtrTypes(BaseAlloca, User, WorkList))
Matt Arsenaultad134842016-02-02 19:18:53 +0000577 return false;
Tom Stellard880a80a2014-06-17 16:53:14 +0000578 }
Matt Arsenaultad134842016-02-02 19:18:53 +0000579
580 return true;
Tom Stellard880a80a2014-06-17 16:53:14 +0000581}
582
Changpeng Fang1dbace12017-05-23 20:25:41 +0000583bool AMDGPUPromoteAlloca::hasSufficientLocalMem(const Function &F) {
584
585 FunctionType *FTy = F.getFunctionType();
586 const AMDGPUSubtarget &ST = TM->getSubtarget<AMDGPUSubtarget>(F);
587
588 // If the function has any arguments in the local address space, then it's
589 // possible these arguments require the entire local memory space, so
590 // we cannot use local memory in the pass.
591 for (Type *ParamTy : FTy->params()) {
592 PointerType *PtrTy = dyn_cast<PointerType>(ParamTy);
593 if (PtrTy && PtrTy->getAddressSpace() == AS.LOCAL_ADDRESS) {
594 LocalMemLimit = 0;
595 DEBUG(dbgs() << "Function has local memory argument. Promoting to "
596 "local memory disabled.\n");
597 return false;
598 }
599 }
600
601 LocalMemLimit = ST.getLocalMemorySize();
602 if (LocalMemLimit == 0)
603 return false;
604
605 const DataLayout &DL = Mod->getDataLayout();
606
607 // Check how much local memory is being used by global objects
608 CurrentLocalMemUsage = 0;
609 for (GlobalVariable &GV : Mod->globals()) {
610 if (GV.getType()->getAddressSpace() != AS.LOCAL_ADDRESS)
611 continue;
612
613 for (const User *U : GV.users()) {
614 const Instruction *Use = dyn_cast<Instruction>(U);
615 if (!Use)
616 continue;
617
618 if (Use->getParent()->getParent() == &F) {
619 unsigned Align = GV.getAlignment();
620 if (Align == 0)
621 Align = DL.getABITypeAlignment(GV.getValueType());
622
623 // FIXME: Try to account for padding here. The padding is currently
624 // determined from the inverse order of uses in the function. I'm not
625 // sure if the use list order is in any way connected to this, so the
626 // total reported size is likely incorrect.
627 uint64_t AllocSize = DL.getTypeAllocSize(GV.getValueType());
628 CurrentLocalMemUsage = alignTo(CurrentLocalMemUsage, Align);
629 CurrentLocalMemUsage += AllocSize;
630 break;
631 }
632 }
633 }
634
635 unsigned MaxOccupancy = ST.getOccupancyWithLocalMemSize(CurrentLocalMemUsage,
636 F);
637
638 // Restrict local memory usage so that we don't drastically reduce occupancy,
639 // unless it is already significantly reduced.
640
641 // TODO: Have some sort of hint or other heuristics to guess occupancy based
642 // on other factors..
643 unsigned OccupancyHint = ST.getWavesPerEU(F).second;
644 if (OccupancyHint == 0)
645 OccupancyHint = 7;
646
647 // Clamp to max value.
648 OccupancyHint = std::min(OccupancyHint, ST.getMaxWavesPerEU());
649
650 // Check the hint but ignore it if it's obviously wrong from the existing LDS
651 // usage.
652 MaxOccupancy = std::min(OccupancyHint, MaxOccupancy);
653
654
655 // Round up to the next tier of usage.
656 unsigned MaxSizeWithWaveCount
657 = ST.getMaxLocalMemSizeWithWaveCount(MaxOccupancy, F);
658
659 // Program is possibly broken by using more local mem than available.
660 if (CurrentLocalMemUsage > MaxSizeWithWaveCount)
661 return false;
662
663 LocalMemLimit = MaxSizeWithWaveCount;
664
665 DEBUG(
666 dbgs() << F.getName() << " uses " << CurrentLocalMemUsage << " bytes of LDS\n"
667 << " Rounding size to " << MaxSizeWithWaveCount
668 << " with a maximum occupancy of " << MaxOccupancy << '\n'
669 << " and " << (LocalMemLimit - CurrentLocalMemUsage)
670 << " available for promotion\n"
671 );
672
673 return true;
674}
675
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000676// FIXME: Should try to pick the most likely to be profitable allocas first.
Changpeng Fang1dbace12017-05-23 20:25:41 +0000677bool AMDGPUPromoteAlloca::handleAlloca(AllocaInst &I, bool SufficientLDS) {
Matt Arsenaultc5fce692016-04-28 18:38:48 +0000678 // Array allocations are probably not worth handling, since an allocation of
679 // the array type is the canonical form.
680 if (!I.isStaticAlloca() || I.isArrayAllocation())
Changpeng Fang1dbace12017-05-23 20:25:41 +0000681 return false;
Matt Arsenault19c54882015-08-26 18:37:13 +0000682
Tom Stellard880a80a2014-06-17 16:53:14 +0000683 IRBuilder<> Builder(&I);
684
685 // First try to replace the alloca with a vector
686 Type *AllocaTy = I.getAllocatedType();
687
Matt Arsenault6f62cf82014-06-27 02:36:59 +0000688 DEBUG(dbgs() << "Trying to promote " << I << '\n');
Tom Stellard880a80a2014-06-17 16:53:14 +0000689
Changpeng Fang1dbace12017-05-23 20:25:41 +0000690 if (tryPromoteAllocaToVector(&I, AS))
691 return true; // Promoted to vector.
Tom Stellard880a80a2014-06-17 16:53:14 +0000692
Tom Stellard79a1fd72016-04-14 16:27:07 +0000693 const Function &ContainingFunction = *I.getParent()->getParent();
Matt Arsenault5c806182017-05-02 18:33:18 +0000694 CallingConv::ID CC = ContainingFunction.getCallingConv();
Tom Stellard79a1fd72016-04-14 16:27:07 +0000695
Nicolai Haehnlebef1ceb2016-07-18 09:02:47 +0000696 // Don't promote the alloca to LDS for shader calling conventions as the work
697 // item ID intrinsics are not supported for these calling conventions.
698 // Furthermore not all LDS is available for some of the stages.
Matt Arsenault5c806182017-05-02 18:33:18 +0000699 switch (CC) {
700 case CallingConv::AMDGPU_KERNEL:
701 case CallingConv::SPIR_KERNEL:
702 break;
703 default:
704 DEBUG(dbgs() << " promote alloca to LDS not supported with calling convention.\n");
Changpeng Fang1dbace12017-05-23 20:25:41 +0000705 return false;
Matt Arsenault5c806182017-05-02 18:33:18 +0000706 }
Nicolai Haehnlebef1ceb2016-07-18 09:02:47 +0000707
Changpeng Fang1dbace12017-05-23 20:25:41 +0000708 // Not likely to have sufficient local memory for promotion.
709 if (!SufficientLDS)
710 return false;
711
Konstantin Zhuravlyov1d650262016-09-06 20:22:28 +0000712 const AMDGPUSubtarget &ST =
713 TM->getSubtarget<AMDGPUSubtarget>(ContainingFunction);
Konstantin Zhuravlyov1d650262016-09-06 20:22:28 +0000714 unsigned WorkGroupSize = ST.getFlatWorkGroupSizes(ContainingFunction).second;
Tom Stellard79a1fd72016-04-14 16:27:07 +0000715
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000716 const DataLayout &DL = Mod->getDataLayout();
Tom Stellard880a80a2014-06-17 16:53:14 +0000717
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000718 unsigned Align = I.getAlignment();
719 if (Align == 0)
720 Align = DL.getABITypeAlignment(I.getAllocatedType());
721
722 // FIXME: This computed padding is likely wrong since it depends on inverse
723 // usage order.
724 //
725 // FIXME: It is also possible that if we're allowed to use all of the memory
726 // could could end up using more than the maximum due to alignment padding.
727
728 uint32_t NewSize = alignTo(CurrentLocalMemUsage, Align);
729 uint32_t AllocSize = WorkGroupSize * DL.getTypeAllocSize(AllocaTy);
730 NewSize += AllocSize;
731
732 if (NewSize > LocalMemLimit) {
733 DEBUG(dbgs() << " " << AllocSize
734 << " bytes of local memory not available to promote\n");
Changpeng Fang1dbace12017-05-23 20:25:41 +0000735 return false;
Tom Stellard880a80a2014-06-17 16:53:14 +0000736 }
737
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000738 CurrentLocalMemUsage = NewSize;
739
Tom Stellard5b2927f2014-10-31 20:52:04 +0000740 std::vector<Value*> WorkList;
741
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000742 if (!collectUsesWithPtrTypes(&I, &I, WorkList)) {
Tom Stellard5b2927f2014-10-31 20:52:04 +0000743 DEBUG(dbgs() << " Do not know how to convert all uses\n");
Changpeng Fang1dbace12017-05-23 20:25:41 +0000744 return false;
Tom Stellard5b2927f2014-10-31 20:52:04 +0000745 }
746
Tom Stellard880a80a2014-06-17 16:53:14 +0000747 DEBUG(dbgs() << "Promoting alloca to local memory\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000748
Matt Arsenaultcf84e262016-02-05 19:47:23 +0000749 Function *F = I.getParent()->getParent();
750
Tom Stellard79a1fd72016-04-14 16:27:07 +0000751 Type *GVTy = ArrayType::get(I.getAllocatedType(), WorkGroupSize);
Tom Stellard880a80a2014-06-17 16:53:14 +0000752 GlobalVariable *GV = new GlobalVariable(
Matt Arsenaultcf84e262016-02-05 19:47:23 +0000753 *Mod, GVTy, false, GlobalValue::InternalLinkage,
754 UndefValue::get(GVTy),
755 Twine(F->getName()) + Twine('.') + I.getName(),
756 nullptr,
757 GlobalVariable::NotThreadLocal,
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000758 AS.LOCAL_ADDRESS);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000759 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Matt Arsenaultcf84e262016-02-05 19:47:23 +0000760 GV->setAlignment(I.getAlignment());
Tom Stellard880a80a2014-06-17 16:53:14 +0000761
Matt Arsenaulte0132462016-01-30 05:19:45 +0000762 Value *TCntY, *TCntZ;
Tom Stellard880a80a2014-06-17 16:53:14 +0000763
Matt Arsenaulte0132462016-01-30 05:19:45 +0000764 std::tie(TCntY, TCntZ) = getLocalSizeYZ(Builder);
765 Value *TIdX = getWorkitemID(Builder, 0);
766 Value *TIdY = getWorkitemID(Builder, 1);
767 Value *TIdZ = getWorkitemID(Builder, 2);
Tom Stellard880a80a2014-06-17 16:53:14 +0000768
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000769 Value *Tmp0 = Builder.CreateMul(TCntY, TCntZ, "", true, true);
Tom Stellard880a80a2014-06-17 16:53:14 +0000770 Tmp0 = Builder.CreateMul(Tmp0, TIdX);
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000771 Value *Tmp1 = Builder.CreateMul(TIdY, TCntZ, "", true, true);
Tom Stellard880a80a2014-06-17 16:53:14 +0000772 Value *TID = Builder.CreateAdd(Tmp0, Tmp1);
773 TID = Builder.CreateAdd(TID, TIdZ);
774
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000775 Value *Indices[] = {
776 Constant::getNullValue(Type::getInt32Ty(Mod->getContext())),
777 TID
778 };
Tom Stellard880a80a2014-06-17 16:53:14 +0000779
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000780 Value *Offset = Builder.CreateInBoundsGEP(GVTy, GV, Indices);
Tom Stellard880a80a2014-06-17 16:53:14 +0000781 I.mutateType(Offset->getType());
782 I.replaceAllUsesWith(Offset);
783 I.eraseFromParent();
784
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000785 for (Value *V : WorkList) {
Tom Stellard880a80a2014-06-17 16:53:14 +0000786 CallInst *Call = dyn_cast<CallInst>(V);
787 if (!Call) {
Matt Arsenault891fccc2016-05-18 15:57:21 +0000788 if (ICmpInst *CI = dyn_cast<ICmpInst>(V)) {
789 Value *Src0 = CI->getOperand(0);
790 Type *EltTy = Src0->getType()->getPointerElementType();
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000791 PointerType *NewTy = PointerType::get(EltTy, AS.LOCAL_ADDRESS);
Matt Arsenault891fccc2016-05-18 15:57:21 +0000792
793 if (isa<ConstantPointerNull>(CI->getOperand(0)))
794 CI->setOperand(0, ConstantPointerNull::get(NewTy));
795
796 if (isa<ConstantPointerNull>(CI->getOperand(1)))
797 CI->setOperand(1, ConstantPointerNull::get(NewTy));
798
799 continue;
800 }
Matt Arsenault65f67e42014-09-15 15:41:44 +0000801
Matt Arsenault2402b952016-12-10 00:52:50 +0000802 // The operand's value should be corrected on its own and we don't want to
803 // touch the users.
Matt Arsenault65f67e42014-09-15 15:41:44 +0000804 if (isa<AddrSpaceCastInst>(V))
805 continue;
806
Matt Arsenault891fccc2016-05-18 15:57:21 +0000807 Type *EltTy = V->getType()->getPointerElementType();
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000808 PointerType *NewTy = PointerType::get(EltTy, AS.LOCAL_ADDRESS);
Matt Arsenault891fccc2016-05-18 15:57:21 +0000809
Matt Arsenault65f67e42014-09-15 15:41:44 +0000810 // FIXME: It doesn't really make sense to try to do this for all
811 // instructions.
Tom Stellard880a80a2014-06-17 16:53:14 +0000812 V->mutateType(NewTy);
Matt Arsenault891fccc2016-05-18 15:57:21 +0000813
814 // Adjust the types of any constant operands.
815 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
816 if (isa<ConstantPointerNull>(SI->getOperand(1)))
817 SI->setOperand(1, ConstantPointerNull::get(NewTy));
818
819 if (isa<ConstantPointerNull>(SI->getOperand(2)))
820 SI->setOperand(2, ConstantPointerNull::get(NewTy));
821 } else if (PHINode *Phi = dyn_cast<PHINode>(V)) {
822 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
823 if (isa<ConstantPointerNull>(Phi->getIncomingValue(I)))
824 Phi->setIncomingValue(I, ConstantPointerNull::get(NewTy));
825 }
826 }
827
Tom Stellard880a80a2014-06-17 16:53:14 +0000828 continue;
829 }
830
Matt Arsenault2e08e182016-07-18 18:34:48 +0000831 IntrinsicInst *Intr = cast<IntrinsicInst>(Call);
Tom Stellard880a80a2014-06-17 16:53:14 +0000832 Builder.SetInsertPoint(Intr);
833 switch (Intr->getIntrinsicID()) {
834 case Intrinsic::lifetime_start:
835 case Intrinsic::lifetime_end:
836 // These intrinsics are for address space 0 only
837 Intr->eraseFromParent();
838 continue;
839 case Intrinsic::memcpy: {
840 MemCpyInst *MemCpy = cast<MemCpyInst>(Intr);
841 Builder.CreateMemCpy(MemCpy->getRawDest(), MemCpy->getRawSource(),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000842 MemCpy->getLength(), MemCpy->getAlignment(),
843 MemCpy->isVolatile());
Tom Stellard880a80a2014-06-17 16:53:14 +0000844 Intr->eraseFromParent();
845 continue;
846 }
Matt Arsenault7e747f12016-02-02 20:28:10 +0000847 case Intrinsic::memmove: {
848 MemMoveInst *MemMove = cast<MemMoveInst>(Intr);
849 Builder.CreateMemMove(MemMove->getRawDest(), MemMove->getRawSource(),
850 MemMove->getLength(), MemMove->getAlignment(),
851 MemMove->isVolatile());
852 Intr->eraseFromParent();
853 continue;
854 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000855 case Intrinsic::memset: {
856 MemSetInst *MemSet = cast<MemSetInst>(Intr);
857 Builder.CreateMemSet(MemSet->getRawDest(), MemSet->getValue(),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000858 MemSet->getLength(), MemSet->getAlignment(),
Tom Stellard880a80a2014-06-17 16:53:14 +0000859 MemSet->isVolatile());
860 Intr->eraseFromParent();
861 continue;
862 }
Matt Arsenault0b783ef02016-01-22 19:47:54 +0000863 case Intrinsic::invariant_start:
864 case Intrinsic::invariant_end:
865 case Intrinsic::invariant_group_barrier:
866 Intr->eraseFromParent();
867 // FIXME: I think the invariant marker should still theoretically apply,
868 // but the intrinsics need to be changed to accept pointers with any
869 // address space.
870 continue;
Matt Arsenault7e747f12016-02-02 20:28:10 +0000871 case Intrinsic::objectsize: {
872 Value *Src = Intr->getOperand(0);
873 Type *SrcTy = Src->getType()->getPointerElementType();
874 Function *ObjectSize = Intrinsic::getDeclaration(Mod,
875 Intrinsic::objectsize,
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000876 { Intr->getType(), PointerType::get(SrcTy, AS.LOCAL_ADDRESS) }
Matt Arsenault7e747f12016-02-02 20:28:10 +0000877 );
878
George Burgess IV56c7e882017-03-21 20:08:59 +0000879 CallInst *NewCall = Builder.CreateCall(
880 ObjectSize, {Src, Intr->getOperand(1), Intr->getOperand(2)});
Matt Arsenault7e747f12016-02-02 20:28:10 +0000881 Intr->replaceAllUsesWith(NewCall);
882 Intr->eraseFromParent();
883 continue;
884 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000885 default:
Matthias Braun8c209aa2017-01-28 02:02:38 +0000886 Intr->print(errs());
Tom Stellard880a80a2014-06-17 16:53:14 +0000887 llvm_unreachable("Don't know how to promote alloca intrinsic use.");
888 }
889 }
Changpeng Fang1dbace12017-05-23 20:25:41 +0000890 return true;
Tom Stellard880a80a2014-06-17 16:53:14 +0000891}
892
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000893FunctionPass *llvm::createAMDGPUPromoteAlloca() {
894 return new AMDGPUPromoteAlloca();
Tom Stellard880a80a2014-06-17 16:53:14 +0000895}