blob: bbe6270655845ca2fee421dff1775ea02996c0fb [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
Bob Wilson3992feb2010-02-03 17:23:56 +0000205/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
206/// SROA. It must be a struct or array type with a small number of elements.
207static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
208 const Type *T = AI->getAllocatedType();
209 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +0000210 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +0000211 return ST->getNumElements() <= 32;
212 // Arrays are much less likely to be safe for SROA; only consider
213 // them if they are very small.
214 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
215 return AT->getNumElements() <= 8;
216 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +0000217}
218
Chris Lattner38aec322003-09-11 16:45:55 +0000219// performScalarRepl - This algorithm is a simple worklist driven algorithm,
220// which runs on all of the malloc/alloca instructions in the function, removing
221// them if they are only used by getelementptr instructions.
222//
223bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000224 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000225
226 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner02a3be02003-09-20 14:39:18 +0000227 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000228 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000229 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000230 WorkList.push_back(A);
231
232 // Process the worklist
233 bool Changed = false;
234 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000235 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000236 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000237
Chris Lattneradd2bd72006-12-22 23:14:42 +0000238 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
239 // with unused elements.
240 if (AI->use_empty()) {
241 AI->eraseFromParent();
242 continue;
243 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000244
245 // If this alloca is impossible for us to promote, reject it early.
246 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
247 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000248
249 // Check to see if this allocation is only modified by a memcpy/memmove from
250 // a constant global. If this is the case, we can change all users to use
251 // the constant global instead. This is commonly produced by the CFE by
252 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
253 // is only subsequently read.
254 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +0000255 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
256 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner79b3bd32007-04-25 06:40:51 +0000257 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000258 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000259 TheCopy->eraseFromParent(); // Don't mutate the global.
260 AI->eraseFromParent();
261 ++NumGlobals;
262 Changed = true;
263 continue;
264 }
Chris Lattner15c82772009-02-02 20:44:45 +0000265
Chris Lattner7809ecd2009-02-03 01:30:09 +0000266 // Check to see if we can perform the core SROA transformation. We cannot
267 // transform the allocation instruction if it is an array allocation
268 // (allocations OF arrays are ok though), and an allocation of a scalar
269 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000270 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000271
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000272 // Do not promote [0 x %struct].
273 if (AllocaSize == 0) continue;
274
Bob Wilson3992feb2010-02-03 17:23:56 +0000275 // If the alloca looks like a good candidate for scalar replacement, and if
276 // all its users can be transformed, then split up the aggregate into its
277 // separate elements.
278 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
279 DoScalarReplacement(AI, WorkList);
280 Changed = true;
281 continue;
282 }
283
Bill Wendling5a377cb2009-03-03 12:12:58 +0000284 // Do not promote any struct whose size is too big.
Bill Wendling3aaf5d92009-03-03 19:18:49 +0000285 if (AllocaSize > SRThreshold) continue;
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000286
Chris Lattner6e733d32009-01-28 20:16:43 +0000287 // If we can turn this aggregate value (potentially with casts) into a
288 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000289 // IsNotTrivial tracks whether this is something that mem2reg could have
290 // promoted itself. If so, we don't want to transform it needlessly. Note
291 // that we can't just check based on the type: the alloca may be of an i32
292 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner6e733d32009-01-28 20:16:43 +0000293 bool IsNotTrivial = false;
Chris Lattner7809ecd2009-02-03 01:30:09 +0000294 const Type *VectorTy = 0;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000295 bool HadAVector = false;
296 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
Chris Lattner0ff83ab2009-03-04 19:22:30 +0000297 0, unsigned(AllocaSize)) && IsNotTrivial) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000298 AllocaInst *NewAI;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000299 // If we were able to find a vector type that can handle this with
300 // insert/extract elements, and if there was at least one use that had
301 // a vector type, promote this to a vector. We don't want to promote
302 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
303 // we just get a lot of insert/extracts. If at least one vector is
304 // involved, then we probably really do have a union of vector/array.
Duncan Sands1df98592010-02-16 11:11:14 +0000305 if (VectorTy && VectorTy->isVectorTy() && HadAVector) {
David Greene504c7d82010-01-05 01:27:09 +0000306 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
Chris Lattnerbdff5482009-08-23 04:37:46 +0000307 << *VectorTy << '\n');
Chris Lattner15c82772009-02-02 20:44:45 +0000308
Chris Lattner7809ecd2009-02-03 01:30:09 +0000309 // Create and insert the vector alloca.
Owen Anderson50dead02009-07-15 23:53:25 +0000310 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
Chris Lattner15c82772009-02-02 20:44:45 +0000311 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000312 } else {
David Greene504c7d82010-01-05 01:27:09 +0000313 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
Chris Lattner7809ecd2009-02-03 01:30:09 +0000314
315 // Create and insert the integer alloca.
Owen Anderson1d0be152009-08-13 21:58:54 +0000316 const Type *NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
Owen Anderson50dead02009-07-15 23:53:25 +0000317 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
Chris Lattner7809ecd2009-02-03 01:30:09 +0000318 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner6e733d32009-01-28 20:16:43 +0000319 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000320 NewAI->takeName(AI);
321 AI->eraseFromParent();
322 ++NumConverted;
323 Changed = true;
324 continue;
325 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000326
Chris Lattner7809ecd2009-02-03 01:30:09 +0000327 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000328 }
329
330 return Changed;
331}
Chris Lattner5e062a12003-05-30 04:15:41 +0000332
Chris Lattnera10b29b2007-04-25 05:02:56 +0000333/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
334/// predicate, do SROA now.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000335void SROA::DoScalarReplacement(AllocaInst *AI,
336 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +0000337 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +0000338 SmallVector<AllocaInst*, 32> ElementAllocas;
339 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
340 ElementAllocas.reserve(ST->getNumContainedTypes());
341 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000342 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +0000343 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000344 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000345 ElementAllocas.push_back(NA);
346 WorkList.push_back(NA); // Add to worklist for recursive processing
347 }
348 } else {
349 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
350 ElementAllocas.reserve(AT->getNumElements());
351 const Type *ElTy = AT->getElementType();
352 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000353 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000354 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000355 ElementAllocas.push_back(NA);
356 WorkList.push_back(NA); // Add to worklist for recursive processing
357 }
358 }
359
Bob Wilsonb742def2009-12-18 20:14:40 +0000360 // Now that we have created the new alloca instructions, rewrite all the
361 // uses of the old alloca.
362 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +0000363
Bob Wilsonb742def2009-12-18 20:14:40 +0000364 // Now erase any instructions that were made dead while rewriting the alloca.
365 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +0000366 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +0000367
Chris Lattnera10b29b2007-04-25 05:02:56 +0000368 NumReplaced++;
369}
Chris Lattnera59adc42009-12-14 05:11:02 +0000370
Bob Wilsonb742def2009-12-18 20:14:40 +0000371/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
372/// recursively including all their operands that become trivially dead.
373void SROA::DeleteDeadInstructions() {
374 while (!DeadInsts.empty()) {
375 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +0000376
Bob Wilsonb742def2009-12-18 20:14:40 +0000377 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
378 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
379 // Zero out the operand and see if it becomes trivially dead.
380 // (But, don't add allocas to the dead instruction list -- they are
381 // already on the worklist and will be deleted separately.)
382 *OI = 0;
383 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
384 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +0000385 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000386
387 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +0000388 }
Chris Lattnera59adc42009-12-14 05:11:02 +0000389}
Bob Wilsonb742def2009-12-18 20:14:40 +0000390
Bob Wilsonb742def2009-12-18 20:14:40 +0000391/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
392/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000393/// the Info parameter. Offset indicates the position within AI that is
394/// referenced by this instruction.
Bob Wilsonb742def2009-12-18 20:14:40 +0000395void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000396 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000397 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
398 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000399
Bob Wilsonb742def2009-12-18 20:14:40 +0000400 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000401 isSafeForScalarRepl(BC, AI, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000402 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000403 uint64_t GEPOffset = Offset;
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000404 isSafeGEP(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000405 if (!Info.isUnsafe)
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000406 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000407 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
408 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
409 if (Length)
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000410 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
Bob Wilsonb742def2009-12-18 20:14:40 +0000411 UI.getOperandNo() == 1, Info);
412 else
413 MarkUnsafe(Info);
414 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
415 if (!LI->isVolatile()) {
416 const Type *LIType = LI->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000417 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
Bob Wilsonb742def2009-12-18 20:14:40 +0000418 LIType, false, Info);
419 } else
420 MarkUnsafe(Info);
421 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
422 // Store is ok if storing INTO the pointer, not storing the pointer
423 if (!SI->isVolatile() && SI->getOperand(0) != I) {
424 const Type *SIType = SI->getOperand(0)->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000425 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
Bob Wilsonb742def2009-12-18 20:14:40 +0000426 SIType, true, Info);
427 } else
428 MarkUnsafe(Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000429 } else {
430 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
431 MarkUnsafe(Info);
432 }
433 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000434 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000435}
Bob Wilson39c88a62009-12-17 18:34:24 +0000436
Bob Wilsonb742def2009-12-18 20:14:40 +0000437/// isSafeGEP - Check if a GEP instruction can be handled for scalar
438/// replacement. It is safe when all the indices are constant, in-bounds
439/// references, and when the resulting offset corresponds to an element within
440/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000441/// return, Offset is adjusted as specified by the GEP indices.
Bob Wilsonb742def2009-12-18 20:14:40 +0000442void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000443 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000444 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
445 if (GEPIt == E)
446 return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000447
Chris Lattner88e6dc82008-08-23 05:21:06 +0000448 // Walk through the GEP type indices, checking the types that this indexes
449 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +0000450 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +0000451 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +0000452 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +0000453 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000454
Bob Wilsonb742def2009-12-18 20:14:40 +0000455 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
456 if (!IdxVal)
457 return MarkUnsafe(Info);
Chris Lattner88e6dc82008-08-23 05:21:06 +0000458 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000459
Bob Wilsonf27a4cd2009-12-22 06:57:14 +0000460 // Compute the offset due to this GEP and check if the alloca has a
461 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000462 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
463 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
464 &Indices[0], Indices.size());
Bob Wilsonb742def2009-12-18 20:14:40 +0000465 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
466 MarkUnsafe(Info);
Chris Lattner5e062a12003-05-30 04:15:41 +0000467}
468
Bob Wilsonb742def2009-12-18 20:14:40 +0000469/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
470/// alloca or has an offset and size that corresponds to a component element
471/// within it. The offset checked here may have been formed from a GEP with a
472/// pointer bitcasted to a different type.
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000473void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +0000474 const Type *MemOpType, bool isStore,
475 AllocaInfo &Info) {
476 // Check if this is a load/store of the entire alloca.
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000477 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000478 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
479 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
480 // (which are essentially the same as the MemIntrinsics, especially with
481 // regard to copying padding between elements), or references using the
482 // aggregate type of the alloca.
Duncan Sands1df98592010-02-16 11:11:14 +0000483 if (!MemOpType || MemOpType->isIntegerTy() || UsesAggregateType) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000484 if (!UsesAggregateType) {
485 if (isStore)
486 Info.isMemCpyDst = true;
487 else
488 Info.isMemCpySrc = true;
489 }
490 return;
491 }
492 }
493 // Check if the offset/size correspond to a component within the alloca type.
494 const Type *T = AI->getAllocatedType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000495 if (TypeHasComponent(T, Offset, MemSize))
Bob Wilsonb742def2009-12-18 20:14:40 +0000496 return;
497
498 return MarkUnsafe(Info);
499}
500
501/// TypeHasComponent - Return true if T has a component type with the
502/// specified offset and size. If Size is zero, do not check the size.
503bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
504 const Type *EltTy;
505 uint64_t EltSize;
506 if (const StructType *ST = dyn_cast<StructType>(T)) {
507 const StructLayout *Layout = TD->getStructLayout(ST);
508 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
509 EltTy = ST->getContainedType(EltIdx);
510 EltSize = TD->getTypeAllocSize(EltTy);
511 Offset -= Layout->getElementOffset(EltIdx);
512 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
513 EltTy = AT->getElementType();
514 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +0000515 if (Offset >= AT->getNumElements() * EltSize)
516 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +0000517 Offset %= EltSize;
518 } else {
519 return false;
520 }
521 if (Offset == 0 && (Size == 0 || EltSize == Size))
522 return true;
523 // Check if the component spans multiple elements.
524 if (Offset + Size > EltSize)
525 return false;
526 return TypeHasComponent(EltTy, Offset, Size);
527}
528
529/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
530/// the instruction I, which references it, to use the separate elements.
531/// Offset indicates the position within AI that is referenced by this
532/// instruction.
533void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
534 SmallVector<AllocaInst*, 32> &NewElts) {
535 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
536 Instruction *User = cast<Instruction>(*UI);
537
538 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
539 RewriteBitCast(BC, AI, Offset, NewElts);
540 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
541 RewriteGEP(GEPI, AI, Offset, NewElts);
542 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
543 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
544 uint64_t MemSize = Length->getZExtValue();
545 if (Offset == 0 &&
546 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
547 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +0000548 // Otherwise the intrinsic can only touch a single element and the
549 // address operand will be updated, so nothing else needs to be done.
Bob Wilsonb742def2009-12-18 20:14:40 +0000550 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
551 const Type *LIType = LI->getType();
552 if (LIType == AI->getAllocatedType()) {
553 // Replace:
554 // %res = load { i32, i32 }* %alloc
555 // with:
556 // %load.0 = load i32* %alloc.0
557 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
558 // %load.1 = load i32* %alloc.1
559 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
560 // (Also works for arrays instead of structs)
561 Value *Insert = UndefValue::get(LIType);
562 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
563 Value *Load = new LoadInst(NewElts[i], "load", LI);
564 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
565 }
566 LI->replaceAllUsesWith(Insert);
567 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +0000568 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +0000569 TD->getTypeAllocSize(LIType) ==
570 TD->getTypeAllocSize(AI->getAllocatedType())) {
571 // If this is a load of the entire alloca to an integer, rewrite it.
572 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
573 }
574 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
575 Value *Val = SI->getOperand(0);
576 const Type *SIType = Val->getType();
577 if (SIType == AI->getAllocatedType()) {
578 // Replace:
579 // store { i32, i32 } %val, { i32, i32 }* %alloc
580 // with:
581 // %val.0 = extractvalue { i32, i32 } %val, 0
582 // store i32 %val.0, i32* %alloc.0
583 // %val.1 = extractvalue { i32, i32 } %val, 1
584 // store i32 %val.1, i32* %alloc.1
585 // (Also works for arrays instead of structs)
586 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
587 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
588 new StoreInst(Extract, NewElts[i], SI);
589 }
590 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +0000591 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +0000592 TD->getTypeAllocSize(SIType) ==
593 TD->getTypeAllocSize(AI->getAllocatedType())) {
594 // If this is a store of the entire alloca from an integer, rewrite it.
595 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
596 }
597 }
Bob Wilson39c88a62009-12-17 18:34:24 +0000598 }
599}
600
Bob Wilsonb742def2009-12-18 20:14:40 +0000601/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
602/// and recursively continue updating all of its uses.
603void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
604 SmallVector<AllocaInst*, 32> &NewElts) {
605 RewriteForScalarRepl(BC, AI, Offset, NewElts);
606 if (BC->getOperand(0) != AI)
607 return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000608
Bob Wilsonb742def2009-12-18 20:14:40 +0000609 // The bitcast references the original alloca. Replace its uses with
610 // references to the first new element alloca.
611 Instruction *Val = NewElts[0];
612 if (Val->getType() != BC->getDestTy()) {
613 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
614 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +0000615 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000616 BC->replaceAllUsesWith(Val);
617 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +0000618}
619
Bob Wilsonb742def2009-12-18 20:14:40 +0000620/// FindElementAndOffset - Return the index of the element containing Offset
621/// within the specified type, which must be either a struct or an array.
622/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +0000623/// element. IdxTy is set to the type of the index result to be used in a
624/// GEP instruction.
625uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
626 const Type *&IdxTy) {
627 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +0000628 if (const StructType *ST = dyn_cast<StructType>(T)) {
629 const StructLayout *Layout = TD->getStructLayout(ST);
630 Idx = Layout->getElementContainingOffset(Offset);
631 T = ST->getContainedType(Idx);
632 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +0000633 IdxTy = Type::getInt32Ty(T->getContext());
634 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +0000635 }
Bob Wilsone88728d2009-12-19 06:53:17 +0000636 const ArrayType *AT = cast<ArrayType>(T);
637 T = AT->getElementType();
638 uint64_t EltSize = TD->getTypeAllocSize(T);
639 Idx = Offset / EltSize;
640 Offset -= Idx * EltSize;
641 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +0000642 return Idx;
643}
644
645/// RewriteGEP - Check if this GEP instruction moves the pointer across
646/// elements of the alloca that are being split apart, and if so, rewrite
647/// the GEP to be relative to the new element.
648void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
649 SmallVector<AllocaInst*, 32> &NewElts) {
650 uint64_t OldOffset = Offset;
651 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
652 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
653 &Indices[0], Indices.size());
654
655 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
656
657 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +0000658 const Type *IdxTy;
659 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +0000660 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +0000661 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +0000662
663 T = AI->getAllocatedType();
664 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +0000665 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +0000666
667 // If this GEP does not move the pointer across elements of the alloca
668 // being split, then it does not needs to be rewritten.
669 if (Idx == OldIdx)
670 return;
671
672 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
673 SmallVector<Value*, 8> NewArgs;
674 NewArgs.push_back(Constant::getNullValue(i32Ty));
675 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +0000676 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
677 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +0000678 }
679 Instruction *Val = NewElts[Idx];
680 if (NewArgs.size() > 1) {
681 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
682 NewArgs.end(), "", GEPI);
683 Val->takeName(GEPI);
684 }
685 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +0000686 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +0000687 GEPI->replaceAllUsesWith(Val);
688 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000689}
690
691/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
692/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +0000693void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000694 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000695 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000696 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +0000697 // appropriate type. The "Other" pointer is the pointer that goes to memory
698 // that doesn't have anything to do with the alloca that we are promoting. For
699 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000700 Value *OtherPtr = 0;
Owen Andersone922c022009-07-22 00:24:57 +0000701 LLVMContext &Context = MI->getContext();
Chris Lattnerdfe964c2009-03-08 03:59:00 +0000702 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +0000703 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +0000704 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +0000705 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000706 else {
Bob Wilsonb742def2009-12-18 20:14:40 +0000707 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +0000708 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000709 }
710 }
Bob Wilson78c50b82009-12-08 18:22:03 +0000711
Chris Lattnerd93afec2009-01-07 07:18:45 +0000712 // If there is an other pointer, we want to convert it to the same pointer
713 // type as AI has, so we can GEP through it safely.
714 if (OtherPtr) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000715
716 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
717 // optimization, but it's also required to detect the corner case where
718 // both pointer operands are referencing the same memory, and where
719 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
720 // function is only called for mem intrinsics that access the whole
721 // aggregate, so non-zero GEPs are not an issue here.)
722 while (1) {
723 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr)) {
724 OtherPtr = BC->getOperand(0);
725 continue;
726 }
727 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr)) {
728 // All zero GEPs are effectively bitcasts.
729 if (GEP->hasAllZeroIndices()) {
730 OtherPtr = GEP->getOperand(0);
731 continue;
732 }
733 }
734 break;
735 }
Bob Wilsona756b1d2010-01-19 04:32:48 +0000736 // Copying the alloca to itself is a no-op: just delete it.
737 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
738 // This code will run twice for a no-op memcpy -- once for each operand.
739 // Put only one reference to MI on the DeadInsts list.
740 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
741 E = DeadInsts.end(); I != E; ++I)
742 if (*I == MI) return;
743 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +0000744 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +0000745 }
Chris Lattner372dda82007-03-05 07:52:57 +0000746
Chris Lattnerd93afec2009-01-07 07:18:45 +0000747 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
748 if (BCE->getOpcode() == Instruction::BitCast)
749 OtherPtr = BCE->getOperand(0);
750
751 // If the pointer is not the right type, insert a bitcast to the right
752 // type.
753 if (OtherPtr->getType() != AI->getType())
754 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
755 MI);
756 }
757
758 // Process each element of the aggregate.
759 Value *TheFn = MI->getOperand(0);
760 const Type *BytePtrTy = MI->getRawDest()->getType();
Bob Wilsonb742def2009-12-18 20:14:40 +0000761 bool SROADest = MI->getRawDest() == Inst;
Chris Lattnerd93afec2009-01-07 07:18:45 +0000762
Owen Anderson1d0be152009-08-13 21:58:54 +0000763 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +0000764
765 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
766 // If this is a memcpy/memmove, emit a GEP of the other element address.
767 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000768 unsigned OtherEltAlign = MemAlignment;
769
Bob Wilsona756b1d2010-01-19 04:32:48 +0000770 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000771 Value *Idx[2] = { Zero,
772 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +0000773 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +0000774 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +0000775 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +0000776 uint64_t EltOffset;
777 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
778 if (const StructType *ST =
779 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
780 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
781 } else {
782 const Type *EltTy =
783 cast<SequentialType>(OtherPtr->getType())->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000784 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000785 }
786
787 // The alignment of the other pointer is the guaranteed alignment of the
788 // element, which is affected by both the known alignment of the whole
789 // mem intrinsic and the alignment of the element. If the alignment of
790 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
791 // known alignment is just 4 bytes.
792 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000793 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000794
795 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +0000796 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000797
798 // If we got down to a scalar, insert a load or store as appropriate.
799 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000800 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +0000801 if (SROADest) {
802 // From Other to Alloca.
803 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
804 new StoreInst(Elt, EltPtr, MI);
805 } else {
806 // From Alloca to Other.
807 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
808 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
809 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000810 continue;
811 }
812 assert(isa<MemSetInst>(MI));
813
814 // If the stored element is zero (common case), just store a null
815 // constant.
816 Constant *StoreVal;
817 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
818 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000819 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +0000820 } else {
821 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +0000822 const Type *ValTy = EltTy->getScalarType();
823
Chris Lattnerd93afec2009-01-07 07:18:45 +0000824 // Construct an integer with the right value.
825 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
826 APInt OneVal(EltSize, CI->getZExtValue());
827 APInt TotalVal(OneVal);
828 // Set each byte.
829 for (unsigned i = 0; 8*i < EltSize; ++i) {
830 TotalVal = TotalVal.shl(8);
831 TotalVal |= OneVal;
832 }
833
834 // Convert the integer value to the appropriate type.
Owen Andersoneed707b2009-07-24 23:12:02 +0000835 StoreVal = ConstantInt::get(Context, TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +0000836 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000837 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000838 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000839 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000840 assert(StoreVal->getType() == ValTy && "Type mismatch!");
841
842 // If the requested value was a vector constant, create it.
843 if (EltTy != ValTy) {
844 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
845 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +0000846 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000847 }
848 }
849 new StoreInst(StoreVal, EltPtr, MI);
850 continue;
851 }
852 // Otherwise, if we're storing a byte variable, use a memset call for
853 // this element.
854 }
855
856 // Cast the element pointer to BytePtrTy.
857 if (EltPtr->getType() != BytePtrTy)
Benjamin Kramer2d64ca02010-01-27 19:46:52 +0000858 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000859
860 // Cast the other pointer (if we have one) to BytePtrTy.
861 if (OtherElt && OtherElt->getType() != BytePtrTy)
Benjamin Kramer2d64ca02010-01-27 19:46:52 +0000862 OtherElt = new BitCastInst(OtherElt, BytePtrTy, OtherElt->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000863
Duncan Sands777d2302009-05-09 07:06:46 +0000864 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000865
866 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000867 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000868 Value *Ops[] = {
869 SROADest ? EltPtr : OtherElt, // Dest ptr
870 SROADest ? OtherElt : EltPtr, // Src ptr
Owen Andersoneed707b2009-07-24 23:12:02 +0000871 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Owen Anderson1d0be152009-08-13 21:58:54 +0000872 // Align
873 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign)
Chris Lattnerd93afec2009-01-07 07:18:45 +0000874 };
875 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
876 } else {
877 assert(isa<MemSetInst>(MI));
878 Value *Ops[] = {
879 EltPtr, MI->getOperand(2), // Dest, Value,
Owen Andersoneed707b2009-07-24 23:12:02 +0000880 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Chris Lattnerd93afec2009-01-07 07:18:45 +0000881 Zero // Align
882 };
883 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
884 }
Chris Lattner372dda82007-03-05 07:52:57 +0000885 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000886 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +0000887}
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000888
Bob Wilson39fdd692009-12-04 21:57:37 +0000889/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000890/// overwrites the entire allocation. Extract out the pieces of the stored
891/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000892void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000893 SmallVector<AllocaInst*, 32> &NewElts){
894 // Extract each element out of the integer according to its structure offset
895 // and store the element value to the individual alloca.
896 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +0000897 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +0000898 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000899
Eli Friedman41b33f42009-06-01 09:14:32 +0000900 // Handle tail padding by extending the operand
901 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000902 SrcVal = new ZExtInst(SrcVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000903 IntegerType::get(SI->getContext(), AllocaSizeBits),
904 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000905
David Greene504c7d82010-01-05 01:27:09 +0000906 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +0000907 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000908
909 // There are two forms here: AI could be an array or struct. Both cases
910 // have different ways to compute the element offset.
911 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
912 const StructLayout *Layout = TD->getStructLayout(EltSTy);
913
914 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
915 // Get the number of bits to shift SrcVal to get the value.
916 const Type *FieldTy = EltSTy->getElementType(i);
917 uint64_t Shift = Layout->getElementOffsetInBits(i);
918
919 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +0000920 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000921
922 Value *EltVal = SrcVal;
923 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000924 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000925 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
926 "sroa.store.elt", SI);
927 }
928
929 // Truncate down to an integer of the right size.
930 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +0000931
932 // Ignore zero sized fields like {}, they obviously contain no data.
933 if (FieldSizeBits == 0) continue;
934
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000935 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000936 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000937 IntegerType::get(SI->getContext(), FieldSizeBits),
938 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000939 Value *DestField = NewElts[i];
940 if (EltVal->getType() == FieldTy) {
941 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +0000942 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000943 // Bitcast to the right element type (for fp/vector values).
944 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
945 } else {
946 // Otherwise, bitcast the dest pointer (for aggregates).
947 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +0000948 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000949 "", SI);
950 }
951 new StoreInst(EltVal, DestField, SI);
952 }
953
954 } else {
955 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
956 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000957 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000958 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
959
960 uint64_t Shift;
961
962 if (TD->isBigEndian())
963 Shift = AllocaSizeBits-ElementOffset;
964 else
965 Shift = 0;
966
967 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +0000968 // Ignore zero sized fields like {}, they obviously contain no data.
969 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000970
971 Value *EltVal = SrcVal;
972 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000973 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000974 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
975 "sroa.store.elt", SI);
976 }
977
978 // Truncate down to an integer of the right size.
979 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000980 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000981 IntegerType::get(SI->getContext(),
982 ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000983 Value *DestField = NewElts[i];
984 if (EltVal->getType() == ArrayEltTy) {
985 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000986 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000987 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000988 // Bitcast to the right element type (for fp/vector values).
989 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
990 } else {
991 // Otherwise, bitcast the dest pointer (for aggregates).
992 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +0000993 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000994 "", SI);
995 }
996 new StoreInst(EltVal, DestField, SI);
997
998 if (TD->isBigEndian())
999 Shift -= ElementOffset;
1000 else
1001 Shift += ElementOffset;
1002 }
1003 }
1004
Bob Wilsonb742def2009-12-18 20:14:40 +00001005 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001006}
1007
Bob Wilson39fdd692009-12-04 21:57:37 +00001008/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001009/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001010void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001011 SmallVector<AllocaInst*, 32> &NewElts) {
1012 // Extract each element out of the NewElts according to its structure offset
1013 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00001014 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001015 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001016
David Greene504c7d82010-01-05 01:27:09 +00001017 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00001018 << '\n');
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001019
1020 // There are two forms here: AI could be an array or struct. Both cases
1021 // have different ways to compute the element offset.
1022 const StructLayout *Layout = 0;
1023 uint64_t ArrayEltBitOffset = 0;
1024 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1025 Layout = TD->getStructLayout(EltSTy);
1026 } else {
1027 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001028 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001029 }
Owen Andersone922c022009-07-22 00:24:57 +00001030
Owen Andersone922c022009-07-22 00:24:57 +00001031 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001032 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001033
1034 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1035 // Load the value from the alloca. If the NewElt is an aggregate, cast
1036 // the pointer to an integer of the same size before doing the load.
1037 Value *SrcField = NewElts[i];
1038 const Type *FieldTy =
1039 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001040 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1041
1042 // Ignore zero sized fields like {}, they obviously contain no data.
1043 if (FieldSizeBits == 0) continue;
1044
Owen Anderson1d0be152009-08-13 21:58:54 +00001045 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1046 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00001047 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1048 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001049 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001050 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001051 "", LI);
1052 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1053
1054 // If SrcField is a fp or vector of the right size but that isn't an
1055 // integer type, bitcast to an integer so we can shift it.
1056 if (SrcField->getType() != FieldIntTy)
1057 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1058
1059 // Zero extend the field to be the same size as the final alloca so that
1060 // we can shift and insert it.
1061 if (SrcField->getType() != ResultVal->getType())
1062 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1063
1064 // Determine the number of bits to shift SrcField.
1065 uint64_t Shift;
1066 if (Layout) // Struct case.
1067 Shift = Layout->getElementOffsetInBits(i);
1068 else // Array case.
1069 Shift = i*ArrayEltBitOffset;
1070
1071 if (TD->isBigEndian())
1072 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1073
1074 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001075 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001076 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1077 }
1078
1079 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1080 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001081
1082 // Handle tail padding by truncating the result
1083 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1084 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1085
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001086 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00001087 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001088}
1089
Duncan Sands3cb36502007-11-04 14:43:57 +00001090/// HasPadding - Return true if the specified type has any structure or
1091/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001092static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001093 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1094 const StructLayout *SL = TD.getStructLayout(STy);
1095 unsigned PrevFieldBitOffset = 0;
1096 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001097 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1098
Chris Lattner39a1c042007-05-30 06:11:23 +00001099 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001100 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001101 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001102
Chris Lattner39a1c042007-05-30 06:11:23 +00001103 // Check to see if there is any padding between this element and the
1104 // previous one.
1105 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001106 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001107 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1108 if (PrevFieldEnd < FieldBitOffset)
1109 return true;
1110 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001111
Chris Lattner39a1c042007-05-30 06:11:23 +00001112 PrevFieldBitOffset = FieldBitOffset;
1113 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001114
Chris Lattner39a1c042007-05-30 06:11:23 +00001115 // Check for tail padding.
1116 if (unsigned EltCount = STy->getNumElements()) {
1117 unsigned PrevFieldEnd = PrevFieldBitOffset +
1118 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001119 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001120 return true;
1121 }
1122
1123 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001124 return HasPadding(ATy->getElementType(), TD);
Duncan Sands3cb36502007-11-04 14:43:57 +00001125 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001126 return HasPadding(VTy->getElementType(), TD);
Chris Lattner39a1c042007-05-30 06:11:23 +00001127 }
Duncan Sands777d2302009-05-09 07:06:46 +00001128 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001129}
Chris Lattner372dda82007-03-05 07:52:57 +00001130
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001131/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1132/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1133/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001134bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001135 // Loop over the use list of the alloca. We can only transform it if all of
1136 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001137 AllocaInfo Info;
1138
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001139 isSafeForScalarRepl(AI, AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001140 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00001141 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001142 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001143 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001144
1145 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1146 // source and destination, we have to be careful. In particular, the memcpy
1147 // could be moving around elements that live in structure padding of the LLVM
1148 // types, but may actually be used. In these cases, we refuse to promote the
1149 // struct.
1150 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001151 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001152 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00001153
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001154 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00001155}
Chris Lattnera1888942005-12-12 07:19:13 +00001156
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001157/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1158/// the offset specified by Offset (which is specified in bytes).
Chris Lattnerde6df882006-04-14 21:42:41 +00001159///
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001160/// There are two cases we handle here:
1161/// 1) A union of vector types of the same size and potentially its elements.
Chris Lattnerd22dbdf2006-12-15 07:32:38 +00001162/// Here we turn element accesses into insert/extract element operations.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001163/// This promotes a <4 x float> with a store of float to the third element
1164/// into a <4 x float> that uses insert element.
1165/// 2) A fully general blob of memory, which we turn into some (potentially
1166/// large) integer type with extract and insert operations where the loads
1167/// and stores would mutate the memory.
Chris Lattner7809ecd2009-02-03 01:30:09 +00001168static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001169 unsigned AllocaSize, const TargetData &TD,
Owen Andersone922c022009-07-22 00:24:57 +00001170 LLVMContext &Context) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001171 // If this could be contributing to a vector, analyze it.
Owen Anderson1d0be152009-08-13 21:58:54 +00001172 if (VecTy != Type::getVoidTy(Context)) { // either null or a vector type.
Chris Lattner996d7a92009-02-02 18:02:59 +00001173
Chris Lattner7809ecd2009-02-03 01:30:09 +00001174 // If the In type is a vector that is the same size as the alloca, see if it
1175 // matches the existing VecTy.
1176 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1177 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1178 // If we're storing/loading a vector of the right size, allow it as a
1179 // vector. If this the first vector we see, remember the type so that
1180 // we know the element size.
1181 if (VecTy == 0)
1182 VecTy = VInTy;
1183 return;
1184 }
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001185 } else if (In->isFloatTy() || In->isDoubleTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001186 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
Chris Lattner7809ecd2009-02-03 01:30:09 +00001187 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1188 // If we're accessing something that could be an element of a vector, see
1189 // if the implied vector agrees with what we already have and if Offset is
1190 // compatible with it.
1191 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1192 if (Offset % EltSize == 0 &&
1193 AllocaSize % EltSize == 0 &&
1194 (VecTy == 0 ||
1195 cast<VectorType>(VecTy)->getElementType()
1196 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1197 if (VecTy == 0)
Owen Andersondebcb012009-07-29 22:17:13 +00001198 VecTy = VectorType::get(In, AllocaSize/EltSize);
Chris Lattner7809ecd2009-02-03 01:30:09 +00001199 return;
1200 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001201 }
1202 }
1203
Chris Lattner7809ecd2009-02-03 01:30:09 +00001204 // Otherwise, we have a case that we can't handle with an optimized vector
1205 // form. We can still turn this into a large integer.
Owen Anderson1d0be152009-08-13 21:58:54 +00001206 VecTy = Type::getVoidTy(Context);
Chris Lattnera1888942005-12-12 07:19:13 +00001207}
1208
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001209/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
Bob Wilsonefc58e72009-12-09 18:05:27 +00001210/// its accesses to a single vector type, return true and set VecTy to
Chris Lattner7809ecd2009-02-03 01:30:09 +00001211/// the new type. If we could convert the alloca into a single promotable
1212/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1213/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1214/// is the current offset from the base of the alloca being analyzed.
Chris Lattnera1888942005-12-12 07:19:13 +00001215///
Chris Lattner1a3257b2009-02-03 18:15:05 +00001216/// If we see at least one access to the value that is as a vector type, set the
1217/// SawVec flag.
Chris Lattner1a3257b2009-02-03 18:15:05 +00001218bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1219 bool &SawVec, uint64_t Offset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001220 unsigned AllocaSize) {
Chris Lattnera1888942005-12-12 07:19:13 +00001221 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1222 Instruction *User = cast<Instruction>(*UI);
1223
1224 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001225 // Don't break volatile loads.
Chris Lattner6e733d32009-01-28 20:16:43 +00001226 if (LI->isVolatile())
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001227 return false;
Owen Andersone922c022009-07-22 00:24:57 +00001228 MergeInType(LI->getType(), Offset, VecTy,
1229 AllocaSize, *TD, V->getContext());
Duncan Sands1df98592010-02-16 11:11:14 +00001230 SawVec |= LI->getType()->isVectorTy();
Chris Lattnercf321862009-01-07 06:39:58 +00001231 continue;
1232 }
1233
1234 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001235 // Storing the pointer, not into the value?
Chris Lattner6e733d32009-01-28 20:16:43 +00001236 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001237 MergeInType(SI->getOperand(0)->getType(), Offset,
Owen Andersone922c022009-07-22 00:24:57 +00001238 VecTy, AllocaSize, *TD, V->getContext());
Duncan Sands1df98592010-02-16 11:11:14 +00001239 SawVec |= SI->getOperand(0)->getType()->isVectorTy();
Chris Lattnercf321862009-01-07 06:39:58 +00001240 continue;
1241 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001242
1243 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattner1a3257b2009-02-03 18:15:05 +00001244 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1245 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001246 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001247 IsNotTrivial = true;
Chris Lattnercf321862009-01-07 06:39:58 +00001248 continue;
1249 }
1250
1251 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001252 // If this is a GEP with a variable indices, we can't handle it.
1253 if (!GEP->hasAllConstantIndices())
1254 return false;
Chris Lattnercf321862009-01-07 06:39:58 +00001255
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001256 // Compute the offset that this GEP adds to the pointer.
1257 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Bob Wilsonb742def2009-12-18 20:14:40 +00001258 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001259 &Indices[0], Indices.size());
1260 // See if all uses can be converted.
Chris Lattner1a3257b2009-02-03 18:15:05 +00001261 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001262 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001263 return false;
1264 IsNotTrivial = true;
1265 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001266 }
Chris Lattner3ce5e882009-03-08 03:37:16 +00001267
Chris Lattner3d730f72009-02-03 02:01:43 +00001268 // If this is a constant sized memset of a constant value (e.g. 0) we can
1269 // handle it.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001270 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1271 // Store of constant value and constant size.
1272 if (isa<ConstantInt>(MSI->getValue()) &&
1273 isa<ConstantInt>(MSI->getLength())) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001274 IsNotTrivial = true;
1275 continue;
1276 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001277 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001278
1279 // If this is a memcpy or memmove into or out of the whole allocation, we
1280 // can handle it like a load or store of the scalar type.
1281 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1282 if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
1283 if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1284 IsNotTrivial = true;
1285 continue;
1286 }
1287 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001288
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001289 // Otherwise, we cannot handle this!
1290 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001291 }
1292
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001293 return true;
Chris Lattnera1888942005-12-12 07:19:13 +00001294}
1295
Chris Lattnera1888942005-12-12 07:19:13 +00001296/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattnerde6df882006-04-14 21:42:41 +00001297/// directly. This happens when we are converting an "integer union" to a
1298/// single integer scalar, or when we are converting a "vector union" to a
1299/// vector with insert/extractelement instructions.
1300///
1301/// Offset is an offset from the original alloca, in bits that need to be
1302/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001303void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
Chris Lattnera1888942005-12-12 07:19:13 +00001304 while (!Ptr->use_empty()) {
1305 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001306
Chris Lattnercf321862009-01-07 06:39:58 +00001307 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb10e0da2008-01-30 00:39:15 +00001308 ConvertUsesToScalar(CI, NewAI, Offset);
Chris Lattnera1888942005-12-12 07:19:13 +00001309 CI->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001310 continue;
1311 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001312
Chris Lattnercf321862009-01-07 06:39:58 +00001313 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001314 // Compute the offset that this GEP adds to the pointer.
1315 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Bob Wilsonb742def2009-12-18 20:14:40 +00001316 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001317 &Indices[0], Indices.size());
1318 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Chris Lattnera1888942005-12-12 07:19:13 +00001319 GEP->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001320 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001321 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001322
Chris Lattner9bc67da2009-02-03 19:45:44 +00001323 IRBuilder<> Builder(User->getParent(), User);
1324
1325 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner6e011152009-02-03 21:01:03 +00001326 // The load is a bit extract from NewAI shifted right by Offset bits.
1327 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1328 Value *NewLoadVal
1329 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1330 LI->replaceAllUsesWith(NewLoadVal);
Chris Lattner9bc67da2009-02-03 19:45:44 +00001331 LI->eraseFromParent();
1332 continue;
1333 }
1334
1335 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1336 assert(SI->getOperand(0) != Ptr && "Consistency error!");
Chris Lattneraadadb32009-12-22 19:33:28 +00001337 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
Chris Lattner9bc67da2009-02-03 19:45:44 +00001338 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1339 Builder);
1340 Builder.CreateStore(New, NewAI);
1341 SI->eraseFromParent();
Chris Lattneraadadb32009-12-22 19:33:28 +00001342
1343 // If the load we just inserted is now dead, then the inserted store
1344 // overwrote the entire thing.
1345 if (Old->use_empty())
1346 Old->eraseFromParent();
Chris Lattner9bc67da2009-02-03 19:45:44 +00001347 continue;
1348 }
1349
Chris Lattner3d730f72009-02-03 02:01:43 +00001350 // If this is a constant sized memset of a constant value (e.g. 0) we can
1351 // transform it into a store of the expanded constant value.
1352 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1353 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1354 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Chris Lattner33e24ad2009-04-21 16:52:12 +00001355 if (NumBytes != 0) {
1356 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1357
1358 // Compute the value replicated the right number of times.
1359 APInt APVal(NumBytes*8, Val);
Chris Lattner3d730f72009-02-03 02:01:43 +00001360
Chris Lattner33e24ad2009-04-21 16:52:12 +00001361 // Splat the value if non-zero.
1362 if (Val)
1363 for (unsigned i = 1; i != NumBytes; ++i)
1364 APVal |= APVal << 8;
Benjamin Kramere6f32942009-11-29 21:17:48 +00001365
Chris Lattneraadadb32009-12-22 19:33:28 +00001366 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
Owen Andersone922c022009-07-22 00:24:57 +00001367 Value *New = ConvertScalar_InsertValue(
Owen Andersoneed707b2009-07-24 23:12:02 +00001368 ConstantInt::get(User->getContext(), APVal),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001369 Old, Offset, Builder);
Chris Lattner33e24ad2009-04-21 16:52:12 +00001370 Builder.CreateStore(New, NewAI);
Chris Lattneraadadb32009-12-22 19:33:28 +00001371
1372 // If the load we just inserted is now dead, then the memset overwrote
1373 // the entire thing.
1374 if (Old->use_empty())
1375 Old->eraseFromParent();
Chris Lattner33e24ad2009-04-21 16:52:12 +00001376 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001377 MSI->eraseFromParent();
1378 continue;
1379 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001380
1381 // If this is a memcpy or memmove into or out of the whole allocation, we
1382 // can handle it like a load or store of the scalar type.
1383 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1384 assert(Offset == 0 && "must be store to start of alloca");
1385
1386 // If the source and destination are both to the same alloca, then this is
1387 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
1388 // as appropriate.
Bob Wilson03274292010-01-25 18:26:54 +00001389 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject(0));
Chris Lattnerc5704872009-03-08 04:04:21 +00001390
Bob Wilson03274292010-01-25 18:26:54 +00001391 if (MTI->getSource()->getUnderlyingObject(0) != OrigAI) {
Chris Lattnerc5704872009-03-08 04:04:21 +00001392 // Dest must be OrigAI, change this to be a load from the original
1393 // pointer (bitcasted), then a store to our new alloca.
1394 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1395 Value *SrcPtr = MTI->getSource();
1396 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1397
1398 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1399 SrcVal->setAlignment(MTI->getAlignment());
1400 Builder.CreateStore(SrcVal, NewAI);
Bob Wilson03274292010-01-25 18:26:54 +00001401 } else if (MTI->getDest()->getUnderlyingObject(0) != OrigAI) {
Chris Lattnerc5704872009-03-08 04:04:21 +00001402 // Src must be OrigAI, change this to be a load from NewAI then a store
1403 // through the original dest pointer (bitcasted).
1404 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1405 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1406
1407 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1408 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1409 NewStore->setAlignment(MTI->getAlignment());
1410 } else {
1411 // Noop transfer. Src == Dst
1412 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001413
1414 MTI->eraseFromParent();
1415 continue;
1416 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001417
Torok Edwinc23197a2009-07-14 16:55:14 +00001418 llvm_unreachable("Unsupported operation!");
Chris Lattnera1888942005-12-12 07:19:13 +00001419 }
1420}
Chris Lattner79b3bd32007-04-25 06:40:51 +00001421
Chris Lattner6e011152009-02-03 21:01:03 +00001422/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1423/// or vector value FromVal, extracting the bits from the offset specified by
1424/// Offset. This returns the value, which is of type ToType.
1425///
1426/// This happens when we are converting an "integer union" to a single
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001427/// integer scalar, or when we are converting a "vector union" to a vector with
1428/// insert/extractelement instructions.
Chris Lattner800de312008-02-29 07:03:13 +00001429///
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001430/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner6e011152009-02-03 21:01:03 +00001431/// shifted to the right.
1432Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1433 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001434 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattner6e011152009-02-03 21:01:03 +00001435 if (FromVal->getType() == ToType && Offset == 0)
1436 return FromVal;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001437
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001438 // If the result alloca is a vector type, this is either an element
1439 // access or a bitcast to another vector type of the same size.
Chris Lattner6e011152009-02-03 21:01:03 +00001440 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
Duncan Sands1df98592010-02-16 11:11:14 +00001441 if (ToType->isVectorTy())
Chris Lattner6e011152009-02-03 21:01:03 +00001442 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001443
1444 // Otherwise it must be an element access.
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001445 unsigned Elt = 0;
1446 if (Offset) {
Duncan Sands777d2302009-05-09 07:06:46 +00001447 unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001448 Elt = Offset/EltSize;
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001449 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner800de312008-02-29 07:03:13 +00001450 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001451 // Return the element extracted out of it.
Owen Anderson1d0be152009-08-13 21:58:54 +00001452 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
1453 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
Chris Lattner6e011152009-02-03 21:01:03 +00001454 if (V->getType() != ToType)
1455 V = Builder.CreateBitCast(V, ToType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001456 return V;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001457 }
Chris Lattner1aa70562009-02-03 21:08:45 +00001458
1459 // If ToType is a first class aggregate, extract out each of the pieces and
1460 // use insertvalue's to form the FCA.
1461 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1462 const StructLayout &Layout = *TD->getStructLayout(ST);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001463 Value *Res = UndefValue::get(ST);
Chris Lattner1aa70562009-02-03 21:08:45 +00001464 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1465 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
Chris Lattnere991ced2009-02-06 04:34:07 +00001466 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner1aa70562009-02-03 21:08:45 +00001467 Builder);
1468 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1469 }
1470 return Res;
1471 }
1472
1473 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001474 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001475 Value *Res = UndefValue::get(AT);
Chris Lattner1aa70562009-02-03 21:08:45 +00001476 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1477 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1478 Offset+i*EltSize, Builder);
1479 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1480 }
1481 return Res;
1482 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001483
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001484 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattner6e011152009-02-03 21:01:03 +00001485 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001486
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001487 // If this is a big-endian system and the load is narrower than the
1488 // full alloca type, we need to do a shift to get the right bits.
1489 int ShAmt = 0;
Chris Lattner56c38522009-01-07 06:34:28 +00001490 if (TD->isBigEndian()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001491 // On big-endian machines, the lowest bit is stored at the bit offset
1492 // from the pointer given by getTypeStoreSizeInBits. This matters for
1493 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner56c38522009-01-07 06:34:28 +00001494 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
Chris Lattner6e011152009-02-03 21:01:03 +00001495 TD->getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001496 } else {
1497 ShAmt = Offset;
1498 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001499
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001500 // Note: we support negative bitwidths (with shl) which are not defined.
1501 // We do this to support (f.e.) loads off the end of a structure where
1502 // only some bits are used.
1503 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001504 FromVal = Builder.CreateLShr(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001505 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001506 ShAmt), "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001507 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001508 FromVal = Builder.CreateShl(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001509 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001510 -ShAmt), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001511
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001512 // Finally, unconditionally truncate the integer to the right width.
Chris Lattner6e011152009-02-03 21:01:03 +00001513 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001514 if (LIBitWidth < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001515 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001516 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
1517 LIBitWidth), "tmp");
Chris Lattner55a683d2009-02-03 07:08:57 +00001518 else if (LIBitWidth > NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001519 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001520 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
1521 LIBitWidth), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001522
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001523 // If the result is an integer, this is a trunc or bitcast.
Duncan Sands1df98592010-02-16 11:11:14 +00001524 if (ToType->isIntegerTy()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001525 // Should be done.
Duncan Sands1df98592010-02-16 11:11:14 +00001526 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001527 // Just do a bitcast, we know the sizes match up.
Chris Lattner6e011152009-02-03 21:01:03 +00001528 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001529 } else {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001530 // Otherwise must be a pointer.
Chris Lattner6e011152009-02-03 21:01:03 +00001531 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001532 }
Chris Lattner6e011152009-02-03 21:01:03 +00001533 assert(FromVal->getType() == ToType && "Didn't convert right?");
1534 return FromVal;
Chris Lattner800de312008-02-29 07:03:13 +00001535}
1536
Chris Lattner9b872db2009-02-03 19:30:11 +00001537/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1538/// or vector value "Old" at the offset specified by Offset.
1539///
1540/// This happens when we are converting an "integer union" to a
Chris Lattner800de312008-02-29 07:03:13 +00001541/// single integer scalar, or when we are converting a "vector union" to a
1542/// vector with insert/extractelement instructions.
1543///
1544/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner9b872db2009-02-03 19:30:11 +00001545/// shifted to the right.
1546Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
Chris Lattner65a65022009-02-03 19:41:50 +00001547 uint64_t Offset, IRBuilder<> &Builder) {
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001548
Chris Lattner800de312008-02-29 07:03:13 +00001549 // Convert the stored type to the actual type, shift it left to insert
1550 // then 'or' into place.
Chris Lattner9b872db2009-02-03 19:30:11 +00001551 const Type *AllocaType = Old->getType();
Owen Andersone922c022009-07-22 00:24:57 +00001552 LLVMContext &Context = Old->getContext();
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001553
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001554 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001555 uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1556 uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
Chris Lattner29e64172009-03-08 04:17:04 +00001557
1558 // Changing the whole vector with memset or with an access of a different
1559 // vector type?
1560 if (ValSize == VecSize)
1561 return Builder.CreateBitCast(SV, AllocaType, "tmp");
1562
Duncan Sands777d2302009-05-09 07:06:46 +00001563 uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner29e64172009-03-08 04:17:04 +00001564
1565 // Must be an element insertion.
1566 unsigned Elt = Offset/EltSize;
1567
1568 if (SV->getType() != VTy->getElementType())
1569 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1570
1571 SV = Builder.CreateInsertElement(Old, SV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001572 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
Chris Lattner29e64172009-03-08 04:17:04 +00001573 "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001574 return SV;
1575 }
Chris Lattner9b872db2009-02-03 19:30:11 +00001576
1577 // If SV is a first-class aggregate value, insert each value recursively.
1578 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1579 const StructLayout &Layout = *TD->getStructLayout(ST);
1580 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001581 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Chris Lattner9b872db2009-02-03 19:30:11 +00001582 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattnere991ced2009-02-06 04:34:07 +00001583 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner65a65022009-02-03 19:41:50 +00001584 Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001585 }
1586 return Old;
1587 }
1588
1589 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Duncan Sands777d2302009-05-09 07:06:46 +00001590 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner9b872db2009-02-03 19:30:11 +00001591 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001592 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1593 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001594 }
1595 return Old;
1596 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001597
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001598 // If SV is a float, convert it to the appropriate integer type.
Chris Lattner9b872db2009-02-03 19:30:11 +00001599 // If it is a pointer, do the same.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001600 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1601 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1602 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1603 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
Duncan Sands1df98592010-02-16 11:11:14 +00001604 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001605 SV = Builder.CreateBitCast(SV,
1606 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
Duncan Sands1df98592010-02-16 11:11:14 +00001607 else if (SV->getType()->isPointerTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001608 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(SV->getContext()), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001609
Chris Lattner7809ecd2009-02-03 01:30:09 +00001610 // Zero extend or truncate the value if needed.
1611 if (SV->getType() != AllocaType) {
1612 if (SV->getType()->getPrimitiveSizeInBits() <
1613 AllocaType->getPrimitiveSizeInBits())
Chris Lattner65a65022009-02-03 19:41:50 +00001614 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001615 else {
1616 // Truncation may be needed if storing more than the alloca can hold
1617 // (undefined behavior).
Chris Lattner65a65022009-02-03 19:41:50 +00001618 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001619 SrcWidth = DestWidth;
1620 SrcStoreWidth = DestStoreWidth;
1621 }
1622 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001623
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001624 // If this is a big-endian system and the store is narrower than the
1625 // full alloca type, we need to do a shift to get the right bits.
1626 int ShAmt = 0;
1627 if (TD->isBigEndian()) {
1628 // On big-endian machines, the lowest bit is stored at the bit offset
1629 // from the pointer given by getTypeStoreSizeInBits. This matters for
1630 // integers with a bitwidth that is not a multiple of 8.
1631 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner800de312008-02-29 07:03:13 +00001632 } else {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001633 ShAmt = Offset;
1634 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001635
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001636 // Note: we support negative bitwidths (with shr) which are not defined.
1637 // We do this to support (f.e.) stores off the end of a structure where
1638 // only some bits in the structure are set.
1639 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1640 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001641 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001642 ShAmt), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001643 Mask <<= ShAmt;
1644 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001645 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001646 -ShAmt), "tmp");
Duncan Sands0e7c46b2009-02-02 09:53:14 +00001647 Mask = Mask.lshr(-ShAmt);
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001648 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001649
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001650 // Mask out the bits we are about to insert from the old value, and or
1651 // in the new bits.
1652 if (SrcWidth != DestWidth) {
1653 assert(DestWidth > SrcWidth);
Owen Andersoneed707b2009-07-24 23:12:02 +00001654 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
Chris Lattner65a65022009-02-03 19:41:50 +00001655 SV = Builder.CreateOr(Old, SV, "ins");
Chris Lattner800de312008-02-29 07:03:13 +00001656 }
1657 return SV;
1658}
1659
1660
Chris Lattner79b3bd32007-04-25 06:40:51 +00001661
1662/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1663/// some part of a constant global variable. This intentionally only accepts
1664/// constant expressions because we don't can't rewrite arbitrary instructions.
1665static bool PointsToConstantGlobal(Value *V) {
1666 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1667 return GV->isConstant();
1668 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1669 if (CE->getOpcode() == Instruction::BitCast ||
1670 CE->getOpcode() == Instruction::GetElementPtr)
1671 return PointsToConstantGlobal(CE->getOperand(0));
1672 return false;
1673}
1674
1675/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1676/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1677/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1678/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1679/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1680/// the alloca, and if the source pointer is a pointer to a constant global, we
1681/// can optimize this.
1682static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1683 bool isOffset) {
1684 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Chris Lattner6e733d32009-01-28 20:16:43 +00001685 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1686 // Ignore non-volatile loads, they are always ok.
1687 if (!LI->isVolatile())
1688 continue;
1689
Chris Lattner79b3bd32007-04-25 06:40:51 +00001690 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1691 // If uses of the bitcast are ok, we are ok.
1692 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1693 return false;
1694 continue;
1695 }
1696 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1697 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1698 // doesn't, it does.
1699 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1700 isOffset || !GEP->hasAllZeroIndices()))
1701 return false;
1702 continue;
1703 }
1704
1705 // If this is isn't our memcpy/memmove, reject it as something we can't
1706 // handle.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001707 if (!isa<MemTransferInst>(*UI))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001708 return false;
1709
1710 // If we already have seen a copy, reject the second one.
1711 if (TheCopy) return false;
1712
1713 // If the pointer has been offset from the start of the alloca, we can't
1714 // safely handle this.
1715 if (isOffset) return false;
1716
1717 // If the memintrinsic isn't using the alloca as the dest, reject it.
1718 if (UI.getOperandNo() != 1) return false;
1719
1720 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1721
1722 // If the source of the memcpy/move is not a constant global, reject it.
1723 if (!PointsToConstantGlobal(MI->getOperand(2)))
1724 return false;
1725
1726 // Otherwise, the transform is safe. Remember the copy instruction.
1727 TheCopy = MI;
1728 }
1729 return true;
1730}
1731
1732/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1733/// modified by a copy from a constant global. If we can prove this, we can
1734/// replace any uses of the alloca with uses of the global directly.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001735Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001736 Instruction *TheCopy = 0;
1737 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1738 return TheCopy;
1739 return 0;
1740}