blob: de02cafb37d1b7fcdabaec80e7685ef943d295fd [file] [log] [blame]
Chris Lattnered7b41e2003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnered7b41e2003-05-27 15:45:27 +00009//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation. This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
Chris Lattner38aec322003-09-11 16:45:55 +000013// each member (if possible). Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17// often interact, especially for C++ programs. As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
Chris Lattnered7b41e2003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
Chris Lattner0e5f4992006-12-19 21:40:18 +000022#define DEBUG_TYPE "scalarrepl"
Chris Lattnered7b41e2003-05-27 15:45:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattner38aec322003-09-11 16:45:55 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnered7b41e2003-05-27 15:45:27 +000026#include "llvm/Function.h"
Chris Lattner79b3bd32007-04-25 06:40:51 +000027#include "llvm/GlobalVariable.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000028#include "llvm/Instructions.h"
Chris Lattner372dda82007-03-05 07:52:57 +000029#include "llvm/IntrinsicInst.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Chris Lattner372dda82007-03-05 07:52:57 +000031#include "llvm/Pass.h"
Chris Lattner38aec322003-09-11 16:45:55 +000032#include "llvm/Analysis/Dominators.h"
33#include "llvm/Target/TargetData.h"
34#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000035#include "llvm/Transforms/Utils/Local.h"
Chris Lattner95255282006-06-28 23:17:24 +000036#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000037#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000038#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000039#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000040#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000041#include "llvm/Support/raw_ostream.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000042#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000043#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000044using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000045
Chris Lattner0e5f4992006-12-19 21:40:18 +000046STATISTIC(NumReplaced, "Number of allocas broken up");
47STATISTIC(NumPromoted, "Number of allocas promoted");
48STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000049STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000050
Chris Lattner0e5f4992006-12-19 21:40:18 +000051namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000052 struct SROA : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000053 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000054 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Devang Patelff366852007-07-09 21:19:23 +000055 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000056 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000057 else
58 SRThreshold = T;
59 }
Devang Patel794fd752007-05-01 21:15:47 +000060
Chris Lattnered7b41e2003-05-27 15:45:27 +000061 bool runOnFunction(Function &F);
62
Chris Lattner38aec322003-09-11 16:45:55 +000063 bool performScalarRepl(Function &F);
64 bool performPromotion(Function &F);
65
Chris Lattnera15854c2003-08-31 00:45:13 +000066 // getAnalysisUsage - This pass does not require any passes, but we know it
67 // will not alter the CFG, so say so.
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel326821e2007-06-07 21:57:03 +000069 AU.addRequired<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +000070 AU.addRequired<DominanceFrontier>();
Chris Lattnera15854c2003-08-31 00:45:13 +000071 AU.setPreservesCFG();
72 }
73
Chris Lattnered7b41e2003-05-27 15:45:27 +000074 private:
Chris Lattner56c38522009-01-07 06:34:28 +000075 TargetData *TD;
76
Bob Wilsonb742def2009-12-18 20:14:40 +000077 /// DeadInsts - Keep track of instructions we have made dead, so that
78 /// we can remove them after we are done working.
79 SmallVector<Value*, 32> DeadInsts;
80
Chris Lattner39a1c042007-05-30 06:11:23 +000081 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
82 /// information about the uses. All these fields are initialized to false
83 /// and set to true when something is learned.
84 struct AllocaInfo {
85 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
86 bool isUnsafe : 1;
87
Chris Lattner39a1c042007-05-30 06:11:23 +000088 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
89 bool isMemCpySrc : 1;
90
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000091 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000092 bool isMemCpyDst : 1;
93
94 AllocaInfo()
Victor Hernandez6c146ee2010-01-21 23:05:53 +000095 : isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +000096 };
97
Devang Patelff366852007-07-09 21:19:23 +000098 unsigned SRThreshold;
99
Chris Lattner39a1c042007-05-30 06:11:23 +0000100 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
101
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000102 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000103
Bob Wilsonb742def2009-12-18 20:14:40 +0000104 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000105 AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000106 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000107 AllocaInfo &Info);
108 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
109 const Type *MemOpType, bool isStore, AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000110 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000111 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
112 const Type *&IdxTy);
Chris Lattner39a1c042007-05-30 06:11:23 +0000113
Victor Hernandez7b929da2009-10-23 21:09:37 +0000114 void DoScalarReplacement(AllocaInst *AI,
115 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000116 void DeleteDeadInstructions();
Victor Hernandez7b929da2009-10-23 21:09:37 +0000117 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocaInst *Base);
Chris Lattnera1888942005-12-12 07:19:13 +0000118
Bob Wilsonb742def2009-12-18 20:14:40 +0000119 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
120 SmallVector<AllocaInst*, 32> &NewElts);
121 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
122 SmallVector<AllocaInst*, 32> &NewElts);
123 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
124 SmallVector<AllocaInst*, 32> &NewElts);
125 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000126 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000127 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000128 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000129 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000130 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000131 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000132
Chris Lattner7809ecd2009-02-03 01:30:09 +0000133 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
Chris Lattner1a3257b2009-02-03 18:15:05 +0000134 bool &SawVec, uint64_t Offset, unsigned AllocaSize);
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000135 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Chris Lattner6e011152009-02-03 21:01:03 +0000136 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
Chris Lattner9bc67da2009-02-03 19:45:44 +0000137 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +0000138 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Chris Lattner65a65022009-02-03 19:41:50 +0000139 uint64_t Offset, IRBuilder<> &Builder);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000140 static Instruction *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000141 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000142}
143
Dan Gohman844731a2008-05-13 00:00:25 +0000144char SROA::ID = 0;
145static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
146
Brian Gaeked0fde302003-11-11 22:41:34 +0000147// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000148FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
149 return new SROA(Threshold);
150}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000151
152
Chris Lattnered7b41e2003-05-27 15:45:27 +0000153bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000154 TD = getAnalysisIfAvailable<TargetData>();
155
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000156 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000157
158 // FIXME: ScalarRepl currently depends on TargetData more than it
159 // theoretically needs to. It should be refactored in order to support
160 // target-independent IR. Until this is done, just skip the actual
161 // scalar-replacement portion of this pass.
162 if (!TD) return Changed;
163
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000164 while (1) {
165 bool LocalChange = performScalarRepl(F);
166 if (!LocalChange) break; // No need to repromote if no scalarrepl
167 Changed = true;
168 LocalChange = performPromotion(F);
169 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
170 }
Chris Lattner38aec322003-09-11 16:45:55 +0000171
172 return Changed;
173}
174
175
176bool SROA::performPromotion(Function &F) {
177 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000178 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000179 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000180
Chris Lattner02a3be02003-09-20 14:39:18 +0000181 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000182
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000183 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000184
Chris Lattner38aec322003-09-11 16:45:55 +0000185 while (1) {
186 Allocas.clear();
187
188 // Find allocas that are safe to promote, by looking at all instructions in
189 // the entry node
190 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
191 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000192 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000193 Allocas.push_back(AI);
194
195 if (Allocas.empty()) break;
196
Nick Lewyckyce2c51b2009-11-23 03:50:44 +0000197 PromoteMemToReg(Allocas, DT, DF);
Chris Lattner38aec322003-09-11 16:45:55 +0000198 NumPromoted += Allocas.size();
199 Changed = true;
200 }
201
202 return Changed;
203}
204
Chris Lattner963a97f2008-06-22 17:46:21 +0000205/// getNumSAElements - Return the number of elements in the specific struct or
206/// array.
207static uint64_t getNumSAElements(const Type *T) {
208 if (const StructType *ST = dyn_cast<StructType>(T))
209 return ST->getNumElements();
210 return cast<ArrayType>(T)->getNumElements();
211}
212
Chris Lattner38aec322003-09-11 16:45:55 +0000213// performScalarRepl - This algorithm is a simple worklist driven algorithm,
214// which runs on all of the malloc/alloca instructions in the function, removing
215// them if they are only used by getelementptr instructions.
216//
217bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000218 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000219
220 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner02a3be02003-09-20 14:39:18 +0000221 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000222 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000223 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000224 WorkList.push_back(A);
225
226 // Process the worklist
227 bool Changed = false;
228 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000229 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000230 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000231
Chris Lattneradd2bd72006-12-22 23:14:42 +0000232 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
233 // with unused elements.
234 if (AI->use_empty()) {
235 AI->eraseFromParent();
236 continue;
237 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000238
239 // If this alloca is impossible for us to promote, reject it early.
240 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
241 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000242
243 // Check to see if this allocation is only modified by a memcpy/memmove from
244 // a constant global. If this is the case, we can change all users to use
245 // the constant global instead. This is commonly produced by the CFE by
246 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
247 // is only subsequently read.
248 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +0000249 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
250 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner79b3bd32007-04-25 06:40:51 +0000251 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000252 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000253 TheCopy->eraseFromParent(); // Don't mutate the global.
254 AI->eraseFromParent();
255 ++NumGlobals;
256 Changed = true;
257 continue;
258 }
Chris Lattner15c82772009-02-02 20:44:45 +0000259
Chris Lattner7809ecd2009-02-03 01:30:09 +0000260 // Check to see if we can perform the core SROA transformation. We cannot
261 // transform the allocation instruction if it is an array allocation
262 // (allocations OF arrays are ok though), and an allocation of a scalar
263 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000264 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000265
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000266 // Do not promote [0 x %struct].
267 if (AllocaSize == 0) continue;
268
Bill Wendling5a377cb2009-03-03 12:12:58 +0000269 // Do not promote any struct whose size is too big.
Bill Wendling3aaf5d92009-03-03 19:18:49 +0000270 if (AllocaSize > SRThreshold) continue;
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000271
Chris Lattner7809ecd2009-02-03 01:30:09 +0000272 if ((isa<StructType>(AI->getAllocatedType()) ||
273 isa<ArrayType>(AI->getAllocatedType())) &&
Chris Lattner7809ecd2009-02-03 01:30:09 +0000274 // Do not promote any struct into more than "32" separate vars.
Evan Cheng67fca632009-03-06 00:56:43 +0000275 getNumSAElements(AI->getAllocatedType()) <= SRThreshold/4) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000276 // Check that all of the users of the allocation are capable of being
277 // transformed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000278 if (isSafeAllocaToScalarRepl(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000279 DoScalarReplacement(AI, WorkList);
280 Changed = true;
281 continue;
282 }
283 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000284
285 // If we can turn this aggregate value (potentially with casts) into a
286 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000287 // IsNotTrivial tracks whether this is something that mem2reg could have
288 // promoted itself. If so, we don't want to transform it needlessly. Note
289 // that we can't just check based on the type: the alloca may be of an i32
290 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner6e733d32009-01-28 20:16:43 +0000291 bool IsNotTrivial = false;
Chris Lattner7809ecd2009-02-03 01:30:09 +0000292 const Type *VectorTy = 0;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000293 bool HadAVector = false;
294 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
Chris Lattner0ff83ab2009-03-04 19:22:30 +0000295 0, unsigned(AllocaSize)) && IsNotTrivial) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000296 AllocaInst *NewAI;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000297 // If we were able to find a vector type that can handle this with
298 // insert/extract elements, and if there was at least one use that had
299 // a vector type, promote this to a vector. We don't want to promote
300 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
301 // we just get a lot of insert/extracts. If at least one vector is
302 // involved, then we probably really do have a union of vector/array.
303 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
David Greene504c7d82010-01-05 01:27:09 +0000304 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
Chris Lattnerbdff5482009-08-23 04:37:46 +0000305 << *VectorTy << '\n');
Chris Lattner15c82772009-02-02 20:44:45 +0000306
Chris Lattner7809ecd2009-02-03 01:30:09 +0000307 // Create and insert the vector alloca.
Owen Anderson50dead02009-07-15 23:53:25 +0000308 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
Chris Lattner15c82772009-02-02 20:44:45 +0000309 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000310 } else {
David Greene504c7d82010-01-05 01:27:09 +0000311 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
Chris Lattner7809ecd2009-02-03 01:30:09 +0000312
313 // Create and insert the integer alloca.
Owen Anderson1d0be152009-08-13 21:58:54 +0000314 const Type *NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
Owen Anderson50dead02009-07-15 23:53:25 +0000315 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
Chris Lattner7809ecd2009-02-03 01:30:09 +0000316 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner6e733d32009-01-28 20:16:43 +0000317 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000318 NewAI->takeName(AI);
319 AI->eraseFromParent();
320 ++NumConverted;
321 Changed = true;
322 continue;
323 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000324
Chris Lattner7809ecd2009-02-03 01:30:09 +0000325 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000326 }
327
328 return Changed;
329}
Chris Lattner5e062a12003-05-30 04:15:41 +0000330
Chris Lattnera10b29b2007-04-25 05:02:56 +0000331/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
332/// predicate, do SROA now.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000333void SROA::DoScalarReplacement(AllocaInst *AI,
334 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +0000335 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +0000336 SmallVector<AllocaInst*, 32> ElementAllocas;
337 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
338 ElementAllocas.reserve(ST->getNumContainedTypes());
339 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000340 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +0000341 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000342 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000343 ElementAllocas.push_back(NA);
344 WorkList.push_back(NA); // Add to worklist for recursive processing
345 }
346 } else {
347 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
348 ElementAllocas.reserve(AT->getNumElements());
349 const Type *ElTy = AT->getElementType();
350 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000351 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000352 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000353 ElementAllocas.push_back(NA);
354 WorkList.push_back(NA); // Add to worklist for recursive processing
355 }
356 }
357
Bob Wilsonb742def2009-12-18 20:14:40 +0000358 // Now that we have created the new alloca instructions, rewrite all the
359 // uses of the old alloca.
360 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +0000361
Bob Wilsonb742def2009-12-18 20:14:40 +0000362 // Now erase any instructions that were made dead while rewriting the alloca.
363 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +0000364 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +0000365
Chris Lattnera10b29b2007-04-25 05:02:56 +0000366 NumReplaced++;
367}
Chris Lattnera59adc42009-12-14 05:11:02 +0000368
Bob Wilsonb742def2009-12-18 20:14:40 +0000369/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
370/// recursively including all their operands that become trivially dead.
371void SROA::DeleteDeadInstructions() {
372 while (!DeadInsts.empty()) {
373 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +0000374
Bob Wilsonb742def2009-12-18 20:14:40 +0000375 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
376 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
377 // Zero out the operand and see if it becomes trivially dead.
378 // (But, don't add allocas to the dead instruction list -- they are
379 // already on the worklist and will be deleted separately.)
380 *OI = 0;
381 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
382 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +0000383 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000384
385 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +0000386 }
Chris Lattnera59adc42009-12-14 05:11:02 +0000387}
Bob Wilsonb742def2009-12-18 20:14:40 +0000388
Bob Wilsonb742def2009-12-18 20:14:40 +0000389/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
390/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000391/// the Info parameter. Offset indicates the position within AI that is
392/// referenced by this instruction.
Bob Wilsonb742def2009-12-18 20:14:40 +0000393void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000394 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000395 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
396 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000397
Bob Wilsonb742def2009-12-18 20:14:40 +0000398 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000399 isSafeForScalarRepl(BC, AI, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000400 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000401 uint64_t GEPOffset = Offset;
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000402 isSafeGEP(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000403 if (!Info.isUnsafe)
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000404 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000405 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
406 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
407 if (Length)
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000408 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
Bob Wilsonb742def2009-12-18 20:14:40 +0000409 UI.getOperandNo() == 1, Info);
410 else
411 MarkUnsafe(Info);
412 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
413 if (!LI->isVolatile()) {
414 const Type *LIType = LI->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000415 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
Bob Wilsonb742def2009-12-18 20:14:40 +0000416 LIType, false, Info);
417 } else
418 MarkUnsafe(Info);
419 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
420 // Store is ok if storing INTO the pointer, not storing the pointer
421 if (!SI->isVolatile() && SI->getOperand(0) != I) {
422 const Type *SIType = SI->getOperand(0)->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000423 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
Bob Wilsonb742def2009-12-18 20:14:40 +0000424 SIType, true, Info);
425 } else
426 MarkUnsafe(Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000427 } else {
428 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
429 MarkUnsafe(Info);
430 }
431 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000432 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000433}
Bob Wilson39c88a62009-12-17 18:34:24 +0000434
Bob Wilsonb742def2009-12-18 20:14:40 +0000435/// isSafeGEP - Check if a GEP instruction can be handled for scalar
436/// replacement. It is safe when all the indices are constant, in-bounds
437/// references, and when the resulting offset corresponds to an element within
438/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000439/// return, Offset is adjusted as specified by the GEP indices.
Bob Wilsonb742def2009-12-18 20:14:40 +0000440void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000441 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000442 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
443 if (GEPIt == E)
444 return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000445
Chris Lattner88e6dc82008-08-23 05:21:06 +0000446 // Walk through the GEP type indices, checking the types that this indexes
447 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +0000448 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +0000449 // Ignore struct elements, no extra checking needed for these.
Bob Wilsonb742def2009-12-18 20:14:40 +0000450 if (isa<StructType>(*GEPIt))
Chris Lattner88e6dc82008-08-23 05:21:06 +0000451 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000452
Bob Wilsonb742def2009-12-18 20:14:40 +0000453 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
454 if (!IdxVal)
455 return MarkUnsafe(Info);
Chris Lattner88e6dc82008-08-23 05:21:06 +0000456 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000457
Bob Wilsonf27a4cd2009-12-22 06:57:14 +0000458 // Compute the offset due to this GEP and check if the alloca has a
459 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000460 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
461 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
462 &Indices[0], Indices.size());
Bob Wilsonb742def2009-12-18 20:14:40 +0000463 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
464 MarkUnsafe(Info);
Chris Lattner5e062a12003-05-30 04:15:41 +0000465}
466
Bob Wilsonb742def2009-12-18 20:14:40 +0000467/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
468/// alloca or has an offset and size that corresponds to a component element
469/// within it. The offset checked here may have been formed from a GEP with a
470/// pointer bitcasted to a different type.
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000471void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +0000472 const Type *MemOpType, bool isStore,
473 AllocaInfo &Info) {
474 // Check if this is a load/store of the entire alloca.
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000475 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000476 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
477 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
478 // (which are essentially the same as the MemIntrinsics, especially with
479 // regard to copying padding between elements), or references using the
480 // aggregate type of the alloca.
481 if (!MemOpType || isa<IntegerType>(MemOpType) || UsesAggregateType) {
482 if (!UsesAggregateType) {
483 if (isStore)
484 Info.isMemCpyDst = true;
485 else
486 Info.isMemCpySrc = true;
487 }
488 return;
489 }
490 }
491 // Check if the offset/size correspond to a component within the alloca type.
492 const Type *T = AI->getAllocatedType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000493 if (TypeHasComponent(T, Offset, MemSize))
Bob Wilsonb742def2009-12-18 20:14:40 +0000494 return;
495
496 return MarkUnsafe(Info);
497}
498
499/// TypeHasComponent - Return true if T has a component type with the
500/// specified offset and size. If Size is zero, do not check the size.
501bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
502 const Type *EltTy;
503 uint64_t EltSize;
504 if (const StructType *ST = dyn_cast<StructType>(T)) {
505 const StructLayout *Layout = TD->getStructLayout(ST);
506 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
507 EltTy = ST->getContainedType(EltIdx);
508 EltSize = TD->getTypeAllocSize(EltTy);
509 Offset -= Layout->getElementOffset(EltIdx);
510 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
511 EltTy = AT->getElementType();
512 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +0000513 if (Offset >= AT->getNumElements() * EltSize)
514 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +0000515 Offset %= EltSize;
516 } else {
517 return false;
518 }
519 if (Offset == 0 && (Size == 0 || EltSize == Size))
520 return true;
521 // Check if the component spans multiple elements.
522 if (Offset + Size > EltSize)
523 return false;
524 return TypeHasComponent(EltTy, Offset, Size);
525}
526
527/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
528/// the instruction I, which references it, to use the separate elements.
529/// Offset indicates the position within AI that is referenced by this
530/// instruction.
531void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
532 SmallVector<AllocaInst*, 32> &NewElts) {
533 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
534 Instruction *User = cast<Instruction>(*UI);
535
536 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
537 RewriteBitCast(BC, AI, Offset, NewElts);
538 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
539 RewriteGEP(GEPI, AI, Offset, NewElts);
540 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
541 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
542 uint64_t MemSize = Length->getZExtValue();
543 if (Offset == 0 &&
544 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
545 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +0000546 // Otherwise the intrinsic can only touch a single element and the
547 // address operand will be updated, so nothing else needs to be done.
Bob Wilsonb742def2009-12-18 20:14:40 +0000548 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
549 const Type *LIType = LI->getType();
550 if (LIType == AI->getAllocatedType()) {
551 // Replace:
552 // %res = load { i32, i32 }* %alloc
553 // with:
554 // %load.0 = load i32* %alloc.0
555 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
556 // %load.1 = load i32* %alloc.1
557 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
558 // (Also works for arrays instead of structs)
559 Value *Insert = UndefValue::get(LIType);
560 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
561 Value *Load = new LoadInst(NewElts[i], "load", LI);
562 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
563 }
564 LI->replaceAllUsesWith(Insert);
565 DeadInsts.push_back(LI);
566 } else if (isa<IntegerType>(LIType) &&
567 TD->getTypeAllocSize(LIType) ==
568 TD->getTypeAllocSize(AI->getAllocatedType())) {
569 // If this is a load of the entire alloca to an integer, rewrite it.
570 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
571 }
572 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
573 Value *Val = SI->getOperand(0);
574 const Type *SIType = Val->getType();
575 if (SIType == AI->getAllocatedType()) {
576 // Replace:
577 // store { i32, i32 } %val, { i32, i32 }* %alloc
578 // with:
579 // %val.0 = extractvalue { i32, i32 } %val, 0
580 // store i32 %val.0, i32* %alloc.0
581 // %val.1 = extractvalue { i32, i32 } %val, 1
582 // store i32 %val.1, i32* %alloc.1
583 // (Also works for arrays instead of structs)
584 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
585 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
586 new StoreInst(Extract, NewElts[i], SI);
587 }
588 DeadInsts.push_back(SI);
589 } else if (isa<IntegerType>(SIType) &&
590 TD->getTypeAllocSize(SIType) ==
591 TD->getTypeAllocSize(AI->getAllocatedType())) {
592 // If this is a store of the entire alloca from an integer, rewrite it.
593 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
594 }
595 }
Bob Wilson39c88a62009-12-17 18:34:24 +0000596 }
597}
598
Bob Wilsonb742def2009-12-18 20:14:40 +0000599/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
600/// and recursively continue updating all of its uses.
601void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
602 SmallVector<AllocaInst*, 32> &NewElts) {
603 RewriteForScalarRepl(BC, AI, Offset, NewElts);
604 if (BC->getOperand(0) != AI)
605 return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000606
Bob Wilsonb742def2009-12-18 20:14:40 +0000607 // The bitcast references the original alloca. Replace its uses with
608 // references to the first new element alloca.
609 Instruction *Val = NewElts[0];
610 if (Val->getType() != BC->getDestTy()) {
611 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
612 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +0000613 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000614 BC->replaceAllUsesWith(Val);
615 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +0000616}
617
Bob Wilsonb742def2009-12-18 20:14:40 +0000618/// FindElementAndOffset - Return the index of the element containing Offset
619/// within the specified type, which must be either a struct or an array.
620/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +0000621/// element. IdxTy is set to the type of the index result to be used in a
622/// GEP instruction.
623uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
624 const Type *&IdxTy) {
625 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +0000626 if (const StructType *ST = dyn_cast<StructType>(T)) {
627 const StructLayout *Layout = TD->getStructLayout(ST);
628 Idx = Layout->getElementContainingOffset(Offset);
629 T = ST->getContainedType(Idx);
630 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +0000631 IdxTy = Type::getInt32Ty(T->getContext());
632 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +0000633 }
Bob Wilsone88728d2009-12-19 06:53:17 +0000634 const ArrayType *AT = cast<ArrayType>(T);
635 T = AT->getElementType();
636 uint64_t EltSize = TD->getTypeAllocSize(T);
637 Idx = Offset / EltSize;
638 Offset -= Idx * EltSize;
639 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +0000640 return Idx;
641}
642
643/// RewriteGEP - Check if this GEP instruction moves the pointer across
644/// elements of the alloca that are being split apart, and if so, rewrite
645/// the GEP to be relative to the new element.
646void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
647 SmallVector<AllocaInst*, 32> &NewElts) {
648 uint64_t OldOffset = Offset;
649 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
650 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
651 &Indices[0], Indices.size());
652
653 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
654
655 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +0000656 const Type *IdxTy;
657 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +0000658 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +0000659 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +0000660
661 T = AI->getAllocatedType();
662 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +0000663 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +0000664
665 // If this GEP does not move the pointer across elements of the alloca
666 // being split, then it does not needs to be rewritten.
667 if (Idx == OldIdx)
668 return;
669
670 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
671 SmallVector<Value*, 8> NewArgs;
672 NewArgs.push_back(Constant::getNullValue(i32Ty));
673 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +0000674 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
675 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +0000676 }
677 Instruction *Val = NewElts[Idx];
678 if (NewArgs.size() > 1) {
679 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
680 NewArgs.end(), "", GEPI);
681 Val->takeName(GEPI);
682 }
683 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +0000684 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +0000685 GEPI->replaceAllUsesWith(Val);
686 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000687}
688
689/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
690/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +0000691void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000692 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000693 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000694 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +0000695 // appropriate type. The "Other" pointer is the pointer that goes to memory
696 // that doesn't have anything to do with the alloca that we are promoting. For
697 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000698 Value *OtherPtr = 0;
Owen Andersone922c022009-07-22 00:24:57 +0000699 LLVMContext &Context = MI->getContext();
Chris Lattnerdfe964c2009-03-08 03:59:00 +0000700 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +0000701 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +0000702 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +0000703 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000704 else {
Bob Wilsonb742def2009-12-18 20:14:40 +0000705 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +0000706 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000707 }
708 }
Bob Wilson78c50b82009-12-08 18:22:03 +0000709
Chris Lattnerd93afec2009-01-07 07:18:45 +0000710 // If there is an other pointer, we want to convert it to the same pointer
711 // type as AI has, so we can GEP through it safely.
712 if (OtherPtr) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000713
714 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
715 // optimization, but it's also required to detect the corner case where
716 // both pointer operands are referencing the same memory, and where
717 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
718 // function is only called for mem intrinsics that access the whole
719 // aggregate, so non-zero GEPs are not an issue here.)
720 while (1) {
721 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr)) {
722 OtherPtr = BC->getOperand(0);
723 continue;
724 }
725 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr)) {
726 // All zero GEPs are effectively bitcasts.
727 if (GEP->hasAllZeroIndices()) {
728 OtherPtr = GEP->getOperand(0);
729 continue;
730 }
731 }
732 break;
733 }
Bob Wilsona756b1d2010-01-19 04:32:48 +0000734 // Copying the alloca to itself is a no-op: just delete it.
735 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
736 // This code will run twice for a no-op memcpy -- once for each operand.
737 // Put only one reference to MI on the DeadInsts list.
738 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
739 E = DeadInsts.end(); I != E; ++I)
740 if (*I == MI) return;
741 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +0000742 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +0000743 }
Chris Lattner372dda82007-03-05 07:52:57 +0000744
Chris Lattnerd93afec2009-01-07 07:18:45 +0000745 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
746 if (BCE->getOpcode() == Instruction::BitCast)
747 OtherPtr = BCE->getOperand(0);
748
749 // If the pointer is not the right type, insert a bitcast to the right
750 // type.
751 if (OtherPtr->getType() != AI->getType())
752 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
753 MI);
754 }
755
756 // Process each element of the aggregate.
757 Value *TheFn = MI->getOperand(0);
758 const Type *BytePtrTy = MI->getRawDest()->getType();
Bob Wilsonb742def2009-12-18 20:14:40 +0000759 bool SROADest = MI->getRawDest() == Inst;
Chris Lattnerd93afec2009-01-07 07:18:45 +0000760
Owen Anderson1d0be152009-08-13 21:58:54 +0000761 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +0000762
763 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
764 // If this is a memcpy/memmove, emit a GEP of the other element address.
765 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000766 unsigned OtherEltAlign = MemAlignment;
767
Bob Wilsona756b1d2010-01-19 04:32:48 +0000768 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000769 Value *Idx[2] = { Zero,
770 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +0000771 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +0000772 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +0000773 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +0000774 uint64_t EltOffset;
775 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
776 if (const StructType *ST =
777 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
778 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
779 } else {
780 const Type *EltTy =
781 cast<SequentialType>(OtherPtr->getType())->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000782 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000783 }
784
785 // The alignment of the other pointer is the guaranteed alignment of the
786 // element, which is affected by both the known alignment of the whole
787 // mem intrinsic and the alignment of the element. If the alignment of
788 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
789 // known alignment is just 4 bytes.
790 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000791 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000792
793 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +0000794 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000795
796 // If we got down to a scalar, insert a load or store as appropriate.
797 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000798 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +0000799 if (SROADest) {
800 // From Other to Alloca.
801 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
802 new StoreInst(Elt, EltPtr, MI);
803 } else {
804 // From Alloca to Other.
805 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
806 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
807 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000808 continue;
809 }
810 assert(isa<MemSetInst>(MI));
811
812 // If the stored element is zero (common case), just store a null
813 // constant.
814 Constant *StoreVal;
815 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
816 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000817 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +0000818 } else {
819 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +0000820 const Type *ValTy = EltTy->getScalarType();
821
Chris Lattnerd93afec2009-01-07 07:18:45 +0000822 // Construct an integer with the right value.
823 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
824 APInt OneVal(EltSize, CI->getZExtValue());
825 APInt TotalVal(OneVal);
826 // Set each byte.
827 for (unsigned i = 0; 8*i < EltSize; ++i) {
828 TotalVal = TotalVal.shl(8);
829 TotalVal |= OneVal;
830 }
831
832 // Convert the integer value to the appropriate type.
Owen Andersoneed707b2009-07-24 23:12:02 +0000833 StoreVal = ConstantInt::get(Context, TotalVal);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000834 if (isa<PointerType>(ValTy))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000835 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000836 else if (ValTy->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000837 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000838 assert(StoreVal->getType() == ValTy && "Type mismatch!");
839
840 // If the requested value was a vector constant, create it.
841 if (EltTy != ValTy) {
842 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
843 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +0000844 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000845 }
846 }
847 new StoreInst(StoreVal, EltPtr, MI);
848 continue;
849 }
850 // Otherwise, if we're storing a byte variable, use a memset call for
851 // this element.
852 }
853
854 // Cast the element pointer to BytePtrTy.
855 if (EltPtr->getType() != BytePtrTy)
Benjamin Kramer2d64ca02010-01-27 19:46:52 +0000856 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000857
858 // Cast the other pointer (if we have one) to BytePtrTy.
859 if (OtherElt && OtherElt->getType() != BytePtrTy)
Benjamin Kramer2d64ca02010-01-27 19:46:52 +0000860 OtherElt = new BitCastInst(OtherElt, BytePtrTy, OtherElt->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000861
Duncan Sands777d2302009-05-09 07:06:46 +0000862 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000863
864 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000865 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000866 Value *Ops[] = {
867 SROADest ? EltPtr : OtherElt, // Dest ptr
868 SROADest ? OtherElt : EltPtr, // Src ptr
Owen Andersoneed707b2009-07-24 23:12:02 +0000869 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Owen Anderson1d0be152009-08-13 21:58:54 +0000870 // Align
871 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign)
Chris Lattnerd93afec2009-01-07 07:18:45 +0000872 };
873 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
874 } else {
875 assert(isa<MemSetInst>(MI));
876 Value *Ops[] = {
877 EltPtr, MI->getOperand(2), // Dest, Value,
Owen Andersoneed707b2009-07-24 23:12:02 +0000878 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Chris Lattnerd93afec2009-01-07 07:18:45 +0000879 Zero // Align
880 };
881 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
882 }
Chris Lattner372dda82007-03-05 07:52:57 +0000883 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000884 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +0000885}
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000886
Bob Wilson39fdd692009-12-04 21:57:37 +0000887/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000888/// overwrites the entire allocation. Extract out the pieces of the stored
889/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000890void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000891 SmallVector<AllocaInst*, 32> &NewElts){
892 // Extract each element out of the integer according to its structure offset
893 // and store the element value to the individual alloca.
894 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +0000895 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +0000896 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000897
Eli Friedman41b33f42009-06-01 09:14:32 +0000898 // Handle tail padding by extending the operand
899 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000900 SrcVal = new ZExtInst(SrcVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000901 IntegerType::get(SI->getContext(), AllocaSizeBits),
902 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000903
David Greene504c7d82010-01-05 01:27:09 +0000904 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +0000905 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000906
907 // There are two forms here: AI could be an array or struct. Both cases
908 // have different ways to compute the element offset.
909 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
910 const StructLayout *Layout = TD->getStructLayout(EltSTy);
911
912 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
913 // Get the number of bits to shift SrcVal to get the value.
914 const Type *FieldTy = EltSTy->getElementType(i);
915 uint64_t Shift = Layout->getElementOffsetInBits(i);
916
917 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +0000918 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000919
920 Value *EltVal = SrcVal;
921 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000922 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000923 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
924 "sroa.store.elt", SI);
925 }
926
927 // Truncate down to an integer of the right size.
928 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +0000929
930 // Ignore zero sized fields like {}, they obviously contain no data.
931 if (FieldSizeBits == 0) continue;
932
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000933 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000934 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000935 IntegerType::get(SI->getContext(), FieldSizeBits),
936 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000937 Value *DestField = NewElts[i];
938 if (EltVal->getType() == FieldTy) {
939 // Storing to an integer field of this size, just do it.
940 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
941 // Bitcast to the right element type (for fp/vector values).
942 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
943 } else {
944 // Otherwise, bitcast the dest pointer (for aggregates).
945 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +0000946 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000947 "", SI);
948 }
949 new StoreInst(EltVal, DestField, SI);
950 }
951
952 } else {
953 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
954 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000955 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000956 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
957
958 uint64_t Shift;
959
960 if (TD->isBigEndian())
961 Shift = AllocaSizeBits-ElementOffset;
962 else
963 Shift = 0;
964
965 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +0000966 // Ignore zero sized fields like {}, they obviously contain no data.
967 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000968
969 Value *EltVal = SrcVal;
970 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000971 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000972 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
973 "sroa.store.elt", SI);
974 }
975
976 // Truncate down to an integer of the right size.
977 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000978 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000979 IntegerType::get(SI->getContext(),
980 ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000981 Value *DestField = NewElts[i];
982 if (EltVal->getType() == ArrayEltTy) {
983 // Storing to an integer field of this size, just do it.
984 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
985 // Bitcast to the right element type (for fp/vector values).
986 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
987 } else {
988 // Otherwise, bitcast the dest pointer (for aggregates).
989 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +0000990 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000991 "", SI);
992 }
993 new StoreInst(EltVal, DestField, SI);
994
995 if (TD->isBigEndian())
996 Shift -= ElementOffset;
997 else
998 Shift += ElementOffset;
999 }
1000 }
1001
Bob Wilsonb742def2009-12-18 20:14:40 +00001002 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001003}
1004
Bob Wilson39fdd692009-12-04 21:57:37 +00001005/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001006/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001007void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001008 SmallVector<AllocaInst*, 32> &NewElts) {
1009 // Extract each element out of the NewElts according to its structure offset
1010 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00001011 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001012 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001013
David Greene504c7d82010-01-05 01:27:09 +00001014 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00001015 << '\n');
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001016
1017 // There are two forms here: AI could be an array or struct. Both cases
1018 // have different ways to compute the element offset.
1019 const StructLayout *Layout = 0;
1020 uint64_t ArrayEltBitOffset = 0;
1021 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1022 Layout = TD->getStructLayout(EltSTy);
1023 } else {
1024 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001025 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001026 }
Owen Andersone922c022009-07-22 00:24:57 +00001027
Owen Andersone922c022009-07-22 00:24:57 +00001028 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001029 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001030
1031 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1032 // Load the value from the alloca. If the NewElt is an aggregate, cast
1033 // the pointer to an integer of the same size before doing the load.
1034 Value *SrcField = NewElts[i];
1035 const Type *FieldTy =
1036 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001037 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1038
1039 // Ignore zero sized fields like {}, they obviously contain no data.
1040 if (FieldSizeBits == 0) continue;
1041
Owen Anderson1d0be152009-08-13 21:58:54 +00001042 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1043 FieldSizeBits);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001044 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1045 !isa<VectorType>(FieldTy))
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001046 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001047 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001048 "", LI);
1049 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1050
1051 // If SrcField is a fp or vector of the right size but that isn't an
1052 // integer type, bitcast to an integer so we can shift it.
1053 if (SrcField->getType() != FieldIntTy)
1054 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1055
1056 // Zero extend the field to be the same size as the final alloca so that
1057 // we can shift and insert it.
1058 if (SrcField->getType() != ResultVal->getType())
1059 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1060
1061 // Determine the number of bits to shift SrcField.
1062 uint64_t Shift;
1063 if (Layout) // Struct case.
1064 Shift = Layout->getElementOffsetInBits(i);
1065 else // Array case.
1066 Shift = i*ArrayEltBitOffset;
1067
1068 if (TD->isBigEndian())
1069 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1070
1071 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001072 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001073 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1074 }
1075
1076 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1077 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001078
1079 // Handle tail padding by truncating the result
1080 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1081 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1082
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001083 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00001084 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001085}
1086
Duncan Sands3cb36502007-11-04 14:43:57 +00001087/// HasPadding - Return true if the specified type has any structure or
1088/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001089static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001090 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1091 const StructLayout *SL = TD.getStructLayout(STy);
1092 unsigned PrevFieldBitOffset = 0;
1093 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001094 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1095
Chris Lattner39a1c042007-05-30 06:11:23 +00001096 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001097 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001098 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001099
Chris Lattner39a1c042007-05-30 06:11:23 +00001100 // Check to see if there is any padding between this element and the
1101 // previous one.
1102 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001103 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001104 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1105 if (PrevFieldEnd < FieldBitOffset)
1106 return true;
1107 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001108
Chris Lattner39a1c042007-05-30 06:11:23 +00001109 PrevFieldBitOffset = FieldBitOffset;
1110 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001111
Chris Lattner39a1c042007-05-30 06:11:23 +00001112 // Check for tail padding.
1113 if (unsigned EltCount = STy->getNumElements()) {
1114 unsigned PrevFieldEnd = PrevFieldBitOffset +
1115 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001116 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001117 return true;
1118 }
1119
1120 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001121 return HasPadding(ATy->getElementType(), TD);
Duncan Sands3cb36502007-11-04 14:43:57 +00001122 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001123 return HasPadding(VTy->getElementType(), TD);
Chris Lattner39a1c042007-05-30 06:11:23 +00001124 }
Duncan Sands777d2302009-05-09 07:06:46 +00001125 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001126}
Chris Lattner372dda82007-03-05 07:52:57 +00001127
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001128/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1129/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1130/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001131bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001132 // Loop over the use list of the alloca. We can only transform it if all of
1133 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001134 AllocaInfo Info;
1135
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001136 isSafeForScalarRepl(AI, AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001137 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00001138 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001139 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001140 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001141
1142 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1143 // source and destination, we have to be careful. In particular, the memcpy
1144 // could be moving around elements that live in structure padding of the LLVM
1145 // types, but may actually be used. In these cases, we refuse to promote the
1146 // struct.
1147 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001148 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001149 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00001150
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001151 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00001152}
Chris Lattnera1888942005-12-12 07:19:13 +00001153
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001154/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1155/// the offset specified by Offset (which is specified in bytes).
Chris Lattnerde6df882006-04-14 21:42:41 +00001156///
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001157/// There are two cases we handle here:
1158/// 1) A union of vector types of the same size and potentially its elements.
Chris Lattnerd22dbdf2006-12-15 07:32:38 +00001159/// Here we turn element accesses into insert/extract element operations.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001160/// This promotes a <4 x float> with a store of float to the third element
1161/// into a <4 x float> that uses insert element.
1162/// 2) A fully general blob of memory, which we turn into some (potentially
1163/// large) integer type with extract and insert operations where the loads
1164/// and stores would mutate the memory.
Chris Lattner7809ecd2009-02-03 01:30:09 +00001165static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001166 unsigned AllocaSize, const TargetData &TD,
Owen Andersone922c022009-07-22 00:24:57 +00001167 LLVMContext &Context) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001168 // If this could be contributing to a vector, analyze it.
Owen Anderson1d0be152009-08-13 21:58:54 +00001169 if (VecTy != Type::getVoidTy(Context)) { // either null or a vector type.
Chris Lattner996d7a92009-02-02 18:02:59 +00001170
Chris Lattner7809ecd2009-02-03 01:30:09 +00001171 // If the In type is a vector that is the same size as the alloca, see if it
1172 // matches the existing VecTy.
1173 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1174 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1175 // If we're storing/loading a vector of the right size, allow it as a
1176 // vector. If this the first vector we see, remember the type so that
1177 // we know the element size.
1178 if (VecTy == 0)
1179 VecTy = VInTy;
1180 return;
1181 }
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001182 } else if (In->isFloatTy() || In->isDoubleTy() ||
Chris Lattner7809ecd2009-02-03 01:30:09 +00001183 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1184 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1185 // If we're accessing something that could be an element of a vector, see
1186 // if the implied vector agrees with what we already have and if Offset is
1187 // compatible with it.
1188 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1189 if (Offset % EltSize == 0 &&
1190 AllocaSize % EltSize == 0 &&
1191 (VecTy == 0 ||
1192 cast<VectorType>(VecTy)->getElementType()
1193 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1194 if (VecTy == 0)
Owen Andersondebcb012009-07-29 22:17:13 +00001195 VecTy = VectorType::get(In, AllocaSize/EltSize);
Chris Lattner7809ecd2009-02-03 01:30:09 +00001196 return;
1197 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001198 }
1199 }
1200
Chris Lattner7809ecd2009-02-03 01:30:09 +00001201 // Otherwise, we have a case that we can't handle with an optimized vector
1202 // form. We can still turn this into a large integer.
Owen Anderson1d0be152009-08-13 21:58:54 +00001203 VecTy = Type::getVoidTy(Context);
Chris Lattnera1888942005-12-12 07:19:13 +00001204}
1205
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001206/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
Bob Wilsonefc58e72009-12-09 18:05:27 +00001207/// its accesses to a single vector type, return true and set VecTy to
Chris Lattner7809ecd2009-02-03 01:30:09 +00001208/// the new type. If we could convert the alloca into a single promotable
1209/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1210/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1211/// is the current offset from the base of the alloca being analyzed.
Chris Lattnera1888942005-12-12 07:19:13 +00001212///
Chris Lattner1a3257b2009-02-03 18:15:05 +00001213/// If we see at least one access to the value that is as a vector type, set the
1214/// SawVec flag.
Chris Lattner1a3257b2009-02-03 18:15:05 +00001215bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1216 bool &SawVec, uint64_t Offset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001217 unsigned AllocaSize) {
Chris Lattnera1888942005-12-12 07:19:13 +00001218 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1219 Instruction *User = cast<Instruction>(*UI);
1220
1221 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001222 // Don't break volatile loads.
Chris Lattner6e733d32009-01-28 20:16:43 +00001223 if (LI->isVolatile())
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001224 return false;
Owen Andersone922c022009-07-22 00:24:57 +00001225 MergeInType(LI->getType(), Offset, VecTy,
1226 AllocaSize, *TD, V->getContext());
Chris Lattner1a3257b2009-02-03 18:15:05 +00001227 SawVec |= isa<VectorType>(LI->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001228 continue;
1229 }
1230
1231 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001232 // Storing the pointer, not into the value?
Chris Lattner6e733d32009-01-28 20:16:43 +00001233 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001234 MergeInType(SI->getOperand(0)->getType(), Offset,
Owen Andersone922c022009-07-22 00:24:57 +00001235 VecTy, AllocaSize, *TD, V->getContext());
Chris Lattner1a3257b2009-02-03 18:15:05 +00001236 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001237 continue;
1238 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001239
1240 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattner1a3257b2009-02-03 18:15:05 +00001241 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1242 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001243 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001244 IsNotTrivial = true;
Chris Lattnercf321862009-01-07 06:39:58 +00001245 continue;
1246 }
1247
1248 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001249 // If this is a GEP with a variable indices, we can't handle it.
1250 if (!GEP->hasAllConstantIndices())
1251 return false;
Chris Lattnercf321862009-01-07 06:39:58 +00001252
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001253 // Compute the offset that this GEP adds to the pointer.
1254 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Bob Wilsonb742def2009-12-18 20:14:40 +00001255 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001256 &Indices[0], Indices.size());
1257 // See if all uses can be converted.
Chris Lattner1a3257b2009-02-03 18:15:05 +00001258 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001259 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001260 return false;
1261 IsNotTrivial = true;
1262 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001263 }
Chris Lattner3ce5e882009-03-08 03:37:16 +00001264
Chris Lattner3d730f72009-02-03 02:01:43 +00001265 // If this is a constant sized memset of a constant value (e.g. 0) we can
1266 // handle it.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001267 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1268 // Store of constant value and constant size.
1269 if (isa<ConstantInt>(MSI->getValue()) &&
1270 isa<ConstantInt>(MSI->getLength())) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001271 IsNotTrivial = true;
1272 continue;
1273 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001274 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001275
1276 // If this is a memcpy or memmove into or out of the whole allocation, we
1277 // can handle it like a load or store of the scalar type.
1278 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1279 if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
1280 if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1281 IsNotTrivial = true;
1282 continue;
1283 }
1284 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001285
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001286 // Otherwise, we cannot handle this!
1287 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001288 }
1289
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001290 return true;
Chris Lattnera1888942005-12-12 07:19:13 +00001291}
1292
Chris Lattnera1888942005-12-12 07:19:13 +00001293/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattnerde6df882006-04-14 21:42:41 +00001294/// directly. This happens when we are converting an "integer union" to a
1295/// single integer scalar, or when we are converting a "vector union" to a
1296/// vector with insert/extractelement instructions.
1297///
1298/// Offset is an offset from the original alloca, in bits that need to be
1299/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001300void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
Chris Lattnera1888942005-12-12 07:19:13 +00001301 while (!Ptr->use_empty()) {
1302 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001303
Chris Lattnercf321862009-01-07 06:39:58 +00001304 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb10e0da2008-01-30 00:39:15 +00001305 ConvertUsesToScalar(CI, NewAI, Offset);
Chris Lattnera1888942005-12-12 07:19:13 +00001306 CI->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001307 continue;
1308 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001309
Chris Lattnercf321862009-01-07 06:39:58 +00001310 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001311 // Compute the offset that this GEP adds to the pointer.
1312 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Bob Wilsonb742def2009-12-18 20:14:40 +00001313 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001314 &Indices[0], Indices.size());
1315 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Chris Lattnera1888942005-12-12 07:19:13 +00001316 GEP->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001317 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001318 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001319
Chris Lattner9bc67da2009-02-03 19:45:44 +00001320 IRBuilder<> Builder(User->getParent(), User);
1321
1322 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner6e011152009-02-03 21:01:03 +00001323 // The load is a bit extract from NewAI shifted right by Offset bits.
1324 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1325 Value *NewLoadVal
1326 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1327 LI->replaceAllUsesWith(NewLoadVal);
Chris Lattner9bc67da2009-02-03 19:45:44 +00001328 LI->eraseFromParent();
1329 continue;
1330 }
1331
1332 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1333 assert(SI->getOperand(0) != Ptr && "Consistency error!");
Chris Lattneraadadb32009-12-22 19:33:28 +00001334 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
Chris Lattner9bc67da2009-02-03 19:45:44 +00001335 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1336 Builder);
1337 Builder.CreateStore(New, NewAI);
1338 SI->eraseFromParent();
Chris Lattneraadadb32009-12-22 19:33:28 +00001339
1340 // If the load we just inserted is now dead, then the inserted store
1341 // overwrote the entire thing.
1342 if (Old->use_empty())
1343 Old->eraseFromParent();
Chris Lattner9bc67da2009-02-03 19:45:44 +00001344 continue;
1345 }
1346
Chris Lattner3d730f72009-02-03 02:01:43 +00001347 // If this is a constant sized memset of a constant value (e.g. 0) we can
1348 // transform it into a store of the expanded constant value.
1349 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1350 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1351 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Chris Lattner33e24ad2009-04-21 16:52:12 +00001352 if (NumBytes != 0) {
1353 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1354
1355 // Compute the value replicated the right number of times.
1356 APInt APVal(NumBytes*8, Val);
Chris Lattner3d730f72009-02-03 02:01:43 +00001357
Chris Lattner33e24ad2009-04-21 16:52:12 +00001358 // Splat the value if non-zero.
1359 if (Val)
1360 for (unsigned i = 1; i != NumBytes; ++i)
1361 APVal |= APVal << 8;
Benjamin Kramere6f32942009-11-29 21:17:48 +00001362
Chris Lattneraadadb32009-12-22 19:33:28 +00001363 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
Owen Andersone922c022009-07-22 00:24:57 +00001364 Value *New = ConvertScalar_InsertValue(
Owen Andersoneed707b2009-07-24 23:12:02 +00001365 ConstantInt::get(User->getContext(), APVal),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001366 Old, Offset, Builder);
Chris Lattner33e24ad2009-04-21 16:52:12 +00001367 Builder.CreateStore(New, NewAI);
Chris Lattneraadadb32009-12-22 19:33:28 +00001368
1369 // If the load we just inserted is now dead, then the memset overwrote
1370 // the entire thing.
1371 if (Old->use_empty())
1372 Old->eraseFromParent();
Chris Lattner33e24ad2009-04-21 16:52:12 +00001373 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001374 MSI->eraseFromParent();
1375 continue;
1376 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001377
1378 // If this is a memcpy or memmove into or out of the whole allocation, we
1379 // can handle it like a load or store of the scalar type.
1380 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1381 assert(Offset == 0 && "must be store to start of alloca");
1382
1383 // If the source and destination are both to the same alloca, then this is
1384 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
1385 // as appropriate.
Bob Wilson03274292010-01-25 18:26:54 +00001386 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject(0));
Chris Lattnerc5704872009-03-08 04:04:21 +00001387
Bob Wilson03274292010-01-25 18:26:54 +00001388 if (MTI->getSource()->getUnderlyingObject(0) != OrigAI) {
Chris Lattnerc5704872009-03-08 04:04:21 +00001389 // Dest must be OrigAI, change this to be a load from the original
1390 // pointer (bitcasted), then a store to our new alloca.
1391 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1392 Value *SrcPtr = MTI->getSource();
1393 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1394
1395 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1396 SrcVal->setAlignment(MTI->getAlignment());
1397 Builder.CreateStore(SrcVal, NewAI);
Bob Wilson03274292010-01-25 18:26:54 +00001398 } else if (MTI->getDest()->getUnderlyingObject(0) != OrigAI) {
Chris Lattnerc5704872009-03-08 04:04:21 +00001399 // Src must be OrigAI, change this to be a load from NewAI then a store
1400 // through the original dest pointer (bitcasted).
1401 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1402 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1403
1404 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1405 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1406 NewStore->setAlignment(MTI->getAlignment());
1407 } else {
1408 // Noop transfer. Src == Dst
1409 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001410
1411 MTI->eraseFromParent();
1412 continue;
1413 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001414
Torok Edwinc23197a2009-07-14 16:55:14 +00001415 llvm_unreachable("Unsupported operation!");
Chris Lattnera1888942005-12-12 07:19:13 +00001416 }
1417}
Chris Lattner79b3bd32007-04-25 06:40:51 +00001418
Chris Lattner6e011152009-02-03 21:01:03 +00001419/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1420/// or vector value FromVal, extracting the bits from the offset specified by
1421/// Offset. This returns the value, which is of type ToType.
1422///
1423/// This happens when we are converting an "integer union" to a single
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001424/// integer scalar, or when we are converting a "vector union" to a vector with
1425/// insert/extractelement instructions.
Chris Lattner800de312008-02-29 07:03:13 +00001426///
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001427/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner6e011152009-02-03 21:01:03 +00001428/// shifted to the right.
1429Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1430 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001431 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattner6e011152009-02-03 21:01:03 +00001432 if (FromVal->getType() == ToType && Offset == 0)
1433 return FromVal;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001434
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001435 // If the result alloca is a vector type, this is either an element
1436 // access or a bitcast to another vector type of the same size.
Chris Lattner6e011152009-02-03 21:01:03 +00001437 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1438 if (isa<VectorType>(ToType))
1439 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001440
1441 // Otherwise it must be an element access.
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001442 unsigned Elt = 0;
1443 if (Offset) {
Duncan Sands777d2302009-05-09 07:06:46 +00001444 unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001445 Elt = Offset/EltSize;
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001446 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner800de312008-02-29 07:03:13 +00001447 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001448 // Return the element extracted out of it.
Owen Anderson1d0be152009-08-13 21:58:54 +00001449 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
1450 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
Chris Lattner6e011152009-02-03 21:01:03 +00001451 if (V->getType() != ToType)
1452 V = Builder.CreateBitCast(V, ToType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001453 return V;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001454 }
Chris Lattner1aa70562009-02-03 21:08:45 +00001455
1456 // If ToType is a first class aggregate, extract out each of the pieces and
1457 // use insertvalue's to form the FCA.
1458 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1459 const StructLayout &Layout = *TD->getStructLayout(ST);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001460 Value *Res = UndefValue::get(ST);
Chris Lattner1aa70562009-02-03 21:08:45 +00001461 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1462 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
Chris Lattnere991ced2009-02-06 04:34:07 +00001463 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner1aa70562009-02-03 21:08:45 +00001464 Builder);
1465 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1466 }
1467 return Res;
1468 }
1469
1470 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001471 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001472 Value *Res = UndefValue::get(AT);
Chris Lattner1aa70562009-02-03 21:08:45 +00001473 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1474 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1475 Offset+i*EltSize, Builder);
1476 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1477 }
1478 return Res;
1479 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001480
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001481 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattner6e011152009-02-03 21:01:03 +00001482 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001483
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001484 // If this is a big-endian system and the load is narrower than the
1485 // full alloca type, we need to do a shift to get the right bits.
1486 int ShAmt = 0;
Chris Lattner56c38522009-01-07 06:34:28 +00001487 if (TD->isBigEndian()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001488 // On big-endian machines, the lowest bit is stored at the bit offset
1489 // from the pointer given by getTypeStoreSizeInBits. This matters for
1490 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner56c38522009-01-07 06:34:28 +00001491 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
Chris Lattner6e011152009-02-03 21:01:03 +00001492 TD->getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001493 } else {
1494 ShAmt = Offset;
1495 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001496
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001497 // Note: we support negative bitwidths (with shl) which are not defined.
1498 // We do this to support (f.e.) loads off the end of a structure where
1499 // only some bits are used.
1500 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001501 FromVal = Builder.CreateLShr(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001502 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001503 ShAmt), "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001504 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001505 FromVal = Builder.CreateShl(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001506 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001507 -ShAmt), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001508
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001509 // Finally, unconditionally truncate the integer to the right width.
Chris Lattner6e011152009-02-03 21:01:03 +00001510 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001511 if (LIBitWidth < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001512 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001513 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
1514 LIBitWidth), "tmp");
Chris Lattner55a683d2009-02-03 07:08:57 +00001515 else if (LIBitWidth > NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001516 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001517 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
1518 LIBitWidth), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001519
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001520 // If the result is an integer, this is a trunc or bitcast.
Chris Lattner6e011152009-02-03 21:01:03 +00001521 if (isa<IntegerType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001522 // Should be done.
Chris Lattner6e011152009-02-03 21:01:03 +00001523 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001524 // Just do a bitcast, we know the sizes match up.
Chris Lattner6e011152009-02-03 21:01:03 +00001525 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001526 } else {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001527 // Otherwise must be a pointer.
Chris Lattner6e011152009-02-03 21:01:03 +00001528 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001529 }
Chris Lattner6e011152009-02-03 21:01:03 +00001530 assert(FromVal->getType() == ToType && "Didn't convert right?");
1531 return FromVal;
Chris Lattner800de312008-02-29 07:03:13 +00001532}
1533
Chris Lattner9b872db2009-02-03 19:30:11 +00001534/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1535/// or vector value "Old" at the offset specified by Offset.
1536///
1537/// This happens when we are converting an "integer union" to a
Chris Lattner800de312008-02-29 07:03:13 +00001538/// single integer scalar, or when we are converting a "vector union" to a
1539/// vector with insert/extractelement instructions.
1540///
1541/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner9b872db2009-02-03 19:30:11 +00001542/// shifted to the right.
1543Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
Chris Lattner65a65022009-02-03 19:41:50 +00001544 uint64_t Offset, IRBuilder<> &Builder) {
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001545
Chris Lattner800de312008-02-29 07:03:13 +00001546 // Convert the stored type to the actual type, shift it left to insert
1547 // then 'or' into place.
Chris Lattner9b872db2009-02-03 19:30:11 +00001548 const Type *AllocaType = Old->getType();
Owen Andersone922c022009-07-22 00:24:57 +00001549 LLVMContext &Context = Old->getContext();
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001550
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001551 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001552 uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1553 uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
Chris Lattner29e64172009-03-08 04:17:04 +00001554
1555 // Changing the whole vector with memset or with an access of a different
1556 // vector type?
1557 if (ValSize == VecSize)
1558 return Builder.CreateBitCast(SV, AllocaType, "tmp");
1559
Duncan Sands777d2302009-05-09 07:06:46 +00001560 uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner29e64172009-03-08 04:17:04 +00001561
1562 // Must be an element insertion.
1563 unsigned Elt = Offset/EltSize;
1564
1565 if (SV->getType() != VTy->getElementType())
1566 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1567
1568 SV = Builder.CreateInsertElement(Old, SV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001569 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
Chris Lattner29e64172009-03-08 04:17:04 +00001570 "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001571 return SV;
1572 }
Chris Lattner9b872db2009-02-03 19:30:11 +00001573
1574 // If SV is a first-class aggregate value, insert each value recursively.
1575 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1576 const StructLayout &Layout = *TD->getStructLayout(ST);
1577 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001578 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Chris Lattner9b872db2009-02-03 19:30:11 +00001579 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattnere991ced2009-02-06 04:34:07 +00001580 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner65a65022009-02-03 19:41:50 +00001581 Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001582 }
1583 return Old;
1584 }
1585
1586 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Duncan Sands777d2302009-05-09 07:06:46 +00001587 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner9b872db2009-02-03 19:30:11 +00001588 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001589 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1590 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001591 }
1592 return Old;
1593 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001594
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001595 // If SV is a float, convert it to the appropriate integer type.
Chris Lattner9b872db2009-02-03 19:30:11 +00001596 // If it is a pointer, do the same.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001597 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1598 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1599 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1600 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1601 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
Owen Anderson1d0be152009-08-13 21:58:54 +00001602 SV = Builder.CreateBitCast(SV,
1603 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001604 else if (isa<PointerType>(SV->getType()))
Owen Anderson1d0be152009-08-13 21:58:54 +00001605 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(SV->getContext()), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001606
Chris Lattner7809ecd2009-02-03 01:30:09 +00001607 // Zero extend or truncate the value if needed.
1608 if (SV->getType() != AllocaType) {
1609 if (SV->getType()->getPrimitiveSizeInBits() <
1610 AllocaType->getPrimitiveSizeInBits())
Chris Lattner65a65022009-02-03 19:41:50 +00001611 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001612 else {
1613 // Truncation may be needed if storing more than the alloca can hold
1614 // (undefined behavior).
Chris Lattner65a65022009-02-03 19:41:50 +00001615 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001616 SrcWidth = DestWidth;
1617 SrcStoreWidth = DestStoreWidth;
1618 }
1619 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001620
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001621 // If this is a big-endian system and the store is narrower than the
1622 // full alloca type, we need to do a shift to get the right bits.
1623 int ShAmt = 0;
1624 if (TD->isBigEndian()) {
1625 // On big-endian machines, the lowest bit is stored at the bit offset
1626 // from the pointer given by getTypeStoreSizeInBits. This matters for
1627 // integers with a bitwidth that is not a multiple of 8.
1628 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner800de312008-02-29 07:03:13 +00001629 } else {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001630 ShAmt = Offset;
1631 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001632
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001633 // Note: we support negative bitwidths (with shr) which are not defined.
1634 // We do this to support (f.e.) stores off the end of a structure where
1635 // only some bits in the structure are set.
1636 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1637 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001638 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001639 ShAmt), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001640 Mask <<= ShAmt;
1641 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001642 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001643 -ShAmt), "tmp");
Duncan Sands0e7c46b2009-02-02 09:53:14 +00001644 Mask = Mask.lshr(-ShAmt);
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001645 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001646
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001647 // Mask out the bits we are about to insert from the old value, and or
1648 // in the new bits.
1649 if (SrcWidth != DestWidth) {
1650 assert(DestWidth > SrcWidth);
Owen Andersoneed707b2009-07-24 23:12:02 +00001651 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
Chris Lattner65a65022009-02-03 19:41:50 +00001652 SV = Builder.CreateOr(Old, SV, "ins");
Chris Lattner800de312008-02-29 07:03:13 +00001653 }
1654 return SV;
1655}
1656
1657
Chris Lattner79b3bd32007-04-25 06:40:51 +00001658
1659/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1660/// some part of a constant global variable. This intentionally only accepts
1661/// constant expressions because we don't can't rewrite arbitrary instructions.
1662static bool PointsToConstantGlobal(Value *V) {
1663 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1664 return GV->isConstant();
1665 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1666 if (CE->getOpcode() == Instruction::BitCast ||
1667 CE->getOpcode() == Instruction::GetElementPtr)
1668 return PointsToConstantGlobal(CE->getOperand(0));
1669 return false;
1670}
1671
1672/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1673/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1674/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1675/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1676/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1677/// the alloca, and if the source pointer is a pointer to a constant global, we
1678/// can optimize this.
1679static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1680 bool isOffset) {
1681 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Chris Lattner6e733d32009-01-28 20:16:43 +00001682 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1683 // Ignore non-volatile loads, they are always ok.
1684 if (!LI->isVolatile())
1685 continue;
1686
Chris Lattner79b3bd32007-04-25 06:40:51 +00001687 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1688 // If uses of the bitcast are ok, we are ok.
1689 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1690 return false;
1691 continue;
1692 }
1693 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1694 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1695 // doesn't, it does.
1696 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1697 isOffset || !GEP->hasAllZeroIndices()))
1698 return false;
1699 continue;
1700 }
1701
1702 // If this is isn't our memcpy/memmove, reject it as something we can't
1703 // handle.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001704 if (!isa<MemTransferInst>(*UI))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001705 return false;
1706
1707 // If we already have seen a copy, reject the second one.
1708 if (TheCopy) return false;
1709
1710 // If the pointer has been offset from the start of the alloca, we can't
1711 // safely handle this.
1712 if (isOffset) return false;
1713
1714 // If the memintrinsic isn't using the alloca as the dest, reject it.
1715 if (UI.getOperandNo() != 1) return false;
1716
1717 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1718
1719 // If the source of the memcpy/move is not a constant global, reject it.
1720 if (!PointsToConstantGlobal(MI->getOperand(2)))
1721 return false;
1722
1723 // Otherwise, the transform is safe. Remember the copy instruction.
1724 TheCopy = MI;
1725 }
1726 return true;
1727}
1728
1729/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1730/// modified by a copy from a constant global. If we can prove this, we can
1731/// replace any uses of the alloca with uses of the global directly.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001732Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001733 Instruction *TheCopy = 0;
1734 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1735 return TheCopy;
1736 return 0;
1737}