blob: f4e379b3f55823a504f0cd676cccdd440d5659dd [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 Lattnerc4472072010-04-15 23:50:26 +000052 struct ConvertToScalarInfo;
53
Chris Lattner3e8b6632009-09-02 06:11:42 +000054 struct SROA : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000055 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000056 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Devang Patelff366852007-07-09 21:19:23 +000057 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000058 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000059 else
60 SRThreshold = T;
61 }
Devang Patel794fd752007-05-01 21:15:47 +000062
Chris Lattnered7b41e2003-05-27 15:45:27 +000063 bool runOnFunction(Function &F);
64
Chris Lattner38aec322003-09-11 16:45:55 +000065 bool performScalarRepl(Function &F);
66 bool performPromotion(Function &F);
67
Chris Lattnera15854c2003-08-31 00:45:13 +000068 // getAnalysisUsage - This pass does not require any passes, but we know it
69 // will not alter the CFG, so say so.
70 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel326821e2007-06-07 21:57:03 +000071 AU.addRequired<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +000072 AU.addRequired<DominanceFrontier>();
Chris Lattnera15854c2003-08-31 00:45:13 +000073 AU.setPreservesCFG();
74 }
75
Chris Lattnered7b41e2003-05-27 15:45:27 +000076 private:
Chris Lattner56c38522009-01-07 06:34:28 +000077 TargetData *TD;
78
Bob Wilsonb742def2009-12-18 20:14:40 +000079 /// DeadInsts - Keep track of instructions we have made dead, so that
80 /// we can remove them after we are done working.
81 SmallVector<Value*, 32> DeadInsts;
82
Chris Lattner39a1c042007-05-30 06:11:23 +000083 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
84 /// information about the uses. All these fields are initialized to false
85 /// and set to true when something is learned.
86 struct AllocaInfo {
87 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
88 bool isUnsafe : 1;
89
Chris Lattner39a1c042007-05-30 06:11:23 +000090 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
91 bool isMemCpySrc : 1;
92
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000093 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000094 bool isMemCpyDst : 1;
95
96 AllocaInfo()
Victor Hernandez6c146ee2010-01-21 23:05:53 +000097 : isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +000098 };
99
Devang Patelff366852007-07-09 21:19:23 +0000100 unsigned SRThreshold;
101
Chris Lattner39a1c042007-05-30 06:11:23 +0000102 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
103
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000104 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000105
Bob Wilsonb742def2009-12-18 20:14:40 +0000106 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000107 AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000108 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000109 AllocaInfo &Info);
110 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
111 const Type *MemOpType, bool isStore, AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000112 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000113 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
114 const Type *&IdxTy);
Chris Lattner39a1c042007-05-30 06:11:23 +0000115
Victor Hernandez7b929da2009-10-23 21:09:37 +0000116 void DoScalarReplacement(AllocaInst *AI,
117 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000118 void DeleteDeadInstructions();
Victor Hernandez7b929da2009-10-23 21:09:37 +0000119 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocaInst *Base);
Chris Lattnera1888942005-12-12 07:19:13 +0000120
Bob Wilsonb742def2009-12-18 20:14:40 +0000121 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
122 SmallVector<AllocaInst*, 32> &NewElts);
123 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
124 SmallVector<AllocaInst*, 32> &NewElts);
125 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
126 SmallVector<AllocaInst*, 32> &NewElts);
127 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000128 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000129 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000130 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000131 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000132 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000133 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000134
Chris Lattnerc4472072010-04-15 23:50:26 +0000135 bool CanConvertToScalar(Value *V, ConvertToScalarInfo &ConvertInfo,
136 uint64_t Offset);
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000137 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Chris Lattner6e011152009-02-03 21:01:03 +0000138 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
Chris Lattner9bc67da2009-02-03 19:45:44 +0000139 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +0000140 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Chris Lattner65a65022009-02-03 19:41:50 +0000141 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner31d80102010-04-15 21:59:20 +0000142 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000143 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000144}
145
Dan Gohman844731a2008-05-13 00:00:25 +0000146char SROA::ID = 0;
147static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
148
Brian Gaeked0fde302003-11-11 22:41:34 +0000149// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000150FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
151 return new SROA(Threshold);
152}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000153
154
Chris Lattnered7b41e2003-05-27 15:45:27 +0000155bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000156 TD = getAnalysisIfAvailable<TargetData>();
157
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000158 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000159
160 // FIXME: ScalarRepl currently depends on TargetData more than it
161 // theoretically needs to. It should be refactored in order to support
162 // target-independent IR. Until this is done, just skip the actual
163 // scalar-replacement portion of this pass.
164 if (!TD) return Changed;
165
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000166 while (1) {
167 bool LocalChange = performScalarRepl(F);
168 if (!LocalChange) break; // No need to repromote if no scalarrepl
169 Changed = true;
170 LocalChange = performPromotion(F);
171 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
172 }
Chris Lattner38aec322003-09-11 16:45:55 +0000173
174 return Changed;
175}
176
177
178bool SROA::performPromotion(Function &F) {
179 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000180 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000181 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000182
Chris Lattner02a3be02003-09-20 14:39:18 +0000183 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000184
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000185 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000186
Chris Lattner38aec322003-09-11 16:45:55 +0000187 while (1) {
188 Allocas.clear();
189
190 // Find allocas that are safe to promote, by looking at all instructions in
191 // the entry node
192 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
193 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000194 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000195 Allocas.push_back(AI);
196
197 if (Allocas.empty()) break;
198
Nick Lewyckyce2c51b2009-11-23 03:50:44 +0000199 PromoteMemToReg(Allocas, DT, DF);
Chris Lattner38aec322003-09-11 16:45:55 +0000200 NumPromoted += Allocas.size();
201 Changed = true;
202 }
203
204 return Changed;
205}
206
Bob Wilson3992feb2010-02-03 17:23:56 +0000207/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
208/// SROA. It must be a struct or array type with a small number of elements.
209static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
210 const Type *T = AI->getAllocatedType();
211 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +0000212 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +0000213 return ST->getNumElements() <= 32;
214 // Arrays are much less likely to be safe for SROA; only consider
215 // them if they are very small.
216 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
217 return AT->getNumElements() <= 8;
218 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +0000219}
220
Chris Lattnerc4472072010-04-15 23:50:26 +0000221namespace {
222struct ConvertToScalarInfo {
223 /// AllocaSize - The size of the alloca being considered.
224 unsigned AllocaSize;
225
226 bool IsNotTrivial;
227 const Type *VectorTy;
228 bool HadAVector;
229
230 explicit ConvertToScalarInfo(unsigned Size) : AllocaSize(Size) {
231 IsNotTrivial = false;
232 VectorTy = 0;
233 HadAVector = false;
234 }
235
236 bool shouldConvertToVector() const {
237 return VectorTy && VectorTy->isVectorTy() && HadAVector;
238 }
239};
240} // end anonymous namespace.
241
242
243
Chris Lattner38aec322003-09-11 16:45:55 +0000244// performScalarRepl - This algorithm is a simple worklist driven algorithm,
245// which runs on all of the malloc/alloca instructions in the function, removing
246// them if they are only used by getelementptr instructions.
247//
248bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000249 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000250
Chris Lattner31d80102010-04-15 21:59:20 +0000251 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +0000252 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000253 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000254 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000255 WorkList.push_back(A);
256
257 // Process the worklist
258 bool Changed = false;
259 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000260 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000261 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000262
Chris Lattneradd2bd72006-12-22 23:14:42 +0000263 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
264 // with unused elements.
265 if (AI->use_empty()) {
266 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +0000267 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +0000268 continue;
269 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000270
271 // If this alloca is impossible for us to promote, reject it early.
272 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
273 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000274
275 // Check to see if this allocation is only modified by a memcpy/memmove from
276 // a constant global. If this is the case, we can change all users to use
277 // the constant global instead. This is commonly produced by the CFE by
278 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
279 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +0000280 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +0000281 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
282 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +0000283 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +0000284 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000285 TheCopy->eraseFromParent(); // Don't mutate the global.
286 AI->eraseFromParent();
287 ++NumGlobals;
288 Changed = true;
289 continue;
290 }
Chris Lattner15c82772009-02-02 20:44:45 +0000291
Chris Lattner7809ecd2009-02-03 01:30:09 +0000292 // Check to see if we can perform the core SROA transformation. We cannot
293 // transform the allocation instruction if it is an array allocation
294 // (allocations OF arrays are ok though), and an allocation of a scalar
295 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000296 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000297
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000298 // Do not promote [0 x %struct].
299 if (AllocaSize == 0) continue;
Chris Lattner31d80102010-04-15 21:59:20 +0000300
301 // Do not promote any struct whose size is too big.
302 if (AllocaSize > SRThreshold) continue;
303
Bob Wilson3992feb2010-02-03 17:23:56 +0000304 // If the alloca looks like a good candidate for scalar replacement, and if
305 // all its users can be transformed, then split up the aggregate into its
306 // separate elements.
307 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
308 DoScalarReplacement(AI, WorkList);
309 Changed = true;
310 continue;
311 }
312
Chris Lattner6e733d32009-01-28 20:16:43 +0000313 // If we can turn this aggregate value (potentially with casts) into a
314 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000315 // IsNotTrivial tracks whether this is something that mem2reg could have
316 // promoted itself. If so, we don't want to transform it needlessly. Note
317 // that we can't just check based on the type: the alloca may be of an i32
318 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattnerc4472072010-04-15 23:50:26 +0000319 ConvertToScalarInfo ConvertInfo((unsigned)AllocaSize);
320 if (CanConvertToScalar(AI, ConvertInfo, 0) && ConvertInfo.IsNotTrivial) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000321 AllocaInst *NewAI;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000322 // If we were able to find a vector type that can handle this with
323 // insert/extract elements, and if there was at least one use that had
324 // a vector type, promote this to a vector. We don't want to promote
325 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
326 // we just get a lot of insert/extracts. If at least one vector is
327 // involved, then we probably really do have a union of vector/array.
Chris Lattnerc4472072010-04-15 23:50:26 +0000328 if (ConvertInfo.shouldConvertToVector()) {
David Greene504c7d82010-01-05 01:27:09 +0000329 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
Chris Lattnerc4472072010-04-15 23:50:26 +0000330 << *ConvertInfo.VectorTy << '\n');
Chris Lattner15c82772009-02-02 20:44:45 +0000331
Chris Lattner7809ecd2009-02-03 01:30:09 +0000332 // Create and insert the vector alloca.
Chris Lattnerc4472072010-04-15 23:50:26 +0000333 NewAI = new AllocaInst(ConvertInfo.VectorTy, 0, "",
334 AI->getParent()->begin());
Chris Lattner15c82772009-02-02 20:44:45 +0000335 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000336 } else {
David Greene504c7d82010-01-05 01:27:09 +0000337 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
Chris Lattner7809ecd2009-02-03 01:30:09 +0000338
339 // Create and insert the integer alloca.
Owen Anderson1d0be152009-08-13 21:58:54 +0000340 const Type *NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
Owen Anderson50dead02009-07-15 23:53:25 +0000341 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
Chris Lattner7809ecd2009-02-03 01:30:09 +0000342 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner6e733d32009-01-28 20:16:43 +0000343 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000344 NewAI->takeName(AI);
345 AI->eraseFromParent();
346 ++NumConverted;
347 Changed = true;
348 continue;
349 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000350
Chris Lattner7809ecd2009-02-03 01:30:09 +0000351 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000352 }
353
354 return Changed;
355}
Chris Lattner5e062a12003-05-30 04:15:41 +0000356
Chris Lattnera10b29b2007-04-25 05:02:56 +0000357/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
358/// predicate, do SROA now.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000359void SROA::DoScalarReplacement(AllocaInst *AI,
360 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +0000361 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +0000362 SmallVector<AllocaInst*, 32> ElementAllocas;
363 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
364 ElementAllocas.reserve(ST->getNumContainedTypes());
365 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000366 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +0000367 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000368 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000369 ElementAllocas.push_back(NA);
370 WorkList.push_back(NA); // Add to worklist for recursive processing
371 }
372 } else {
373 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
374 ElementAllocas.reserve(AT->getNumElements());
375 const Type *ElTy = AT->getElementType();
376 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000377 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000378 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000379 ElementAllocas.push_back(NA);
380 WorkList.push_back(NA); // Add to worklist for recursive processing
381 }
382 }
383
Bob Wilsonb742def2009-12-18 20:14:40 +0000384 // Now that we have created the new alloca instructions, rewrite all the
385 // uses of the old alloca.
386 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +0000387
Bob Wilsonb742def2009-12-18 20:14:40 +0000388 // Now erase any instructions that were made dead while rewriting the alloca.
389 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +0000390 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +0000391
Chris Lattnera10b29b2007-04-25 05:02:56 +0000392 NumReplaced++;
393}
Chris Lattnera59adc42009-12-14 05:11:02 +0000394
Bob Wilsonb742def2009-12-18 20:14:40 +0000395/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
396/// recursively including all their operands that become trivially dead.
397void SROA::DeleteDeadInstructions() {
398 while (!DeadInsts.empty()) {
399 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +0000400
Bob Wilsonb742def2009-12-18 20:14:40 +0000401 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
402 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
403 // Zero out the operand and see if it becomes trivially dead.
404 // (But, don't add allocas to the dead instruction list -- they are
405 // already on the worklist and will be deleted separately.)
406 *OI = 0;
407 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
408 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +0000409 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000410
411 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +0000412 }
Chris Lattnera59adc42009-12-14 05:11:02 +0000413}
Bob Wilsonb742def2009-12-18 20:14:40 +0000414
Bob Wilsonb742def2009-12-18 20:14:40 +0000415/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
416/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000417/// the Info parameter. Offset indicates the position within AI that is
418/// referenced by this instruction.
Bob Wilsonb742def2009-12-18 20:14:40 +0000419void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000420 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000421 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
422 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000423
Bob Wilsonb742def2009-12-18 20:14:40 +0000424 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000425 isSafeForScalarRepl(BC, AI, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000426 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000427 uint64_t GEPOffset = Offset;
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000428 isSafeGEP(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000429 if (!Info.isUnsafe)
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000430 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
Gabor Greif2ff961f2010-04-15 20:51:13 +0000431 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000432 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
433 if (Length)
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000434 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
Gabor Greif2ff961f2010-04-15 20:51:13 +0000435 UI.getOperandNo() == 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000436 else
437 MarkUnsafe(Info);
438 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
439 if (!LI->isVolatile()) {
440 const Type *LIType = LI->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000441 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
Bob Wilsonb742def2009-12-18 20:14:40 +0000442 LIType, false, Info);
443 } else
444 MarkUnsafe(Info);
445 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
446 // Store is ok if storing INTO the pointer, not storing the pointer
447 if (!SI->isVolatile() && SI->getOperand(0) != I) {
448 const Type *SIType = SI->getOperand(0)->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000449 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
Bob Wilsonb742def2009-12-18 20:14:40 +0000450 SIType, true, Info);
451 } else
452 MarkUnsafe(Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000453 } else {
454 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
455 MarkUnsafe(Info);
456 }
457 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000458 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000459}
Bob Wilson39c88a62009-12-17 18:34:24 +0000460
Bob Wilsonb742def2009-12-18 20:14:40 +0000461/// isSafeGEP - Check if a GEP instruction can be handled for scalar
462/// replacement. It is safe when all the indices are constant, in-bounds
463/// references, and when the resulting offset corresponds to an element within
464/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000465/// return, Offset is adjusted as specified by the GEP indices.
Bob Wilsonb742def2009-12-18 20:14:40 +0000466void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000467 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000468 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
469 if (GEPIt == E)
470 return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000471
Chris Lattner88e6dc82008-08-23 05:21:06 +0000472 // Walk through the GEP type indices, checking the types that this indexes
473 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +0000474 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +0000475 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +0000476 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +0000477 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000478
Bob Wilsonb742def2009-12-18 20:14:40 +0000479 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
480 if (!IdxVal)
481 return MarkUnsafe(Info);
Chris Lattner88e6dc82008-08-23 05:21:06 +0000482 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000483
Bob Wilsonf27a4cd2009-12-22 06:57:14 +0000484 // Compute the offset due to this GEP and check if the alloca has a
485 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000486 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
487 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
488 &Indices[0], Indices.size());
Bob Wilsonb742def2009-12-18 20:14:40 +0000489 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
490 MarkUnsafe(Info);
Chris Lattner5e062a12003-05-30 04:15:41 +0000491}
492
Bob Wilsonb742def2009-12-18 20:14:40 +0000493/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
494/// alloca or has an offset and size that corresponds to a component element
495/// within it. The offset checked here may have been formed from a GEP with a
496/// pointer bitcasted to a different type.
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000497void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +0000498 const Type *MemOpType, bool isStore,
499 AllocaInfo &Info) {
500 // Check if this is a load/store of the entire alloca.
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000501 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000502 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
503 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
504 // (which are essentially the same as the MemIntrinsics, especially with
505 // regard to copying padding between elements), or references using the
506 // aggregate type of the alloca.
Duncan Sands1df98592010-02-16 11:11:14 +0000507 if (!MemOpType || MemOpType->isIntegerTy() || UsesAggregateType) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000508 if (!UsesAggregateType) {
509 if (isStore)
510 Info.isMemCpyDst = true;
511 else
512 Info.isMemCpySrc = true;
513 }
514 return;
515 }
516 }
517 // Check if the offset/size correspond to a component within the alloca type.
518 const Type *T = AI->getAllocatedType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000519 if (TypeHasComponent(T, Offset, MemSize))
Bob Wilsonb742def2009-12-18 20:14:40 +0000520 return;
521
522 return MarkUnsafe(Info);
523}
524
525/// TypeHasComponent - Return true if T has a component type with the
526/// specified offset and size. If Size is zero, do not check the size.
527bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
528 const Type *EltTy;
529 uint64_t EltSize;
530 if (const StructType *ST = dyn_cast<StructType>(T)) {
531 const StructLayout *Layout = TD->getStructLayout(ST);
532 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
533 EltTy = ST->getContainedType(EltIdx);
534 EltSize = TD->getTypeAllocSize(EltTy);
535 Offset -= Layout->getElementOffset(EltIdx);
536 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
537 EltTy = AT->getElementType();
538 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +0000539 if (Offset >= AT->getNumElements() * EltSize)
540 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +0000541 Offset %= EltSize;
542 } else {
543 return false;
544 }
545 if (Offset == 0 && (Size == 0 || EltSize == Size))
546 return true;
547 // Check if the component spans multiple elements.
548 if (Offset + Size > EltSize)
549 return false;
550 return TypeHasComponent(EltTy, Offset, Size);
551}
552
553/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
554/// the instruction I, which references it, to use the separate elements.
555/// Offset indicates the position within AI that is referenced by this
556/// instruction.
557void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
558 SmallVector<AllocaInst*, 32> &NewElts) {
559 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
560 Instruction *User = cast<Instruction>(*UI);
561
562 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
563 RewriteBitCast(BC, AI, Offset, NewElts);
564 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
565 RewriteGEP(GEPI, AI, Offset, NewElts);
566 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
567 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
568 uint64_t MemSize = Length->getZExtValue();
569 if (Offset == 0 &&
570 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
571 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +0000572 // Otherwise the intrinsic can only touch a single element and the
573 // address operand will be updated, so nothing else needs to be done.
Bob Wilsonb742def2009-12-18 20:14:40 +0000574 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
575 const Type *LIType = LI->getType();
576 if (LIType == AI->getAllocatedType()) {
577 // Replace:
578 // %res = load { i32, i32 }* %alloc
579 // with:
580 // %load.0 = load i32* %alloc.0
581 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
582 // %load.1 = load i32* %alloc.1
583 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
584 // (Also works for arrays instead of structs)
585 Value *Insert = UndefValue::get(LIType);
586 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
587 Value *Load = new LoadInst(NewElts[i], "load", LI);
588 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
589 }
590 LI->replaceAllUsesWith(Insert);
591 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +0000592 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +0000593 TD->getTypeAllocSize(LIType) ==
594 TD->getTypeAllocSize(AI->getAllocatedType())) {
595 // If this is a load of the entire alloca to an integer, rewrite it.
596 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
597 }
598 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
599 Value *Val = SI->getOperand(0);
600 const Type *SIType = Val->getType();
601 if (SIType == AI->getAllocatedType()) {
602 // Replace:
603 // store { i32, i32 } %val, { i32, i32 }* %alloc
604 // with:
605 // %val.0 = extractvalue { i32, i32 } %val, 0
606 // store i32 %val.0, i32* %alloc.0
607 // %val.1 = extractvalue { i32, i32 } %val, 1
608 // store i32 %val.1, i32* %alloc.1
609 // (Also works for arrays instead of structs)
610 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
611 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
612 new StoreInst(Extract, NewElts[i], SI);
613 }
614 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +0000615 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +0000616 TD->getTypeAllocSize(SIType) ==
617 TD->getTypeAllocSize(AI->getAllocatedType())) {
618 // If this is a store of the entire alloca from an integer, rewrite it.
619 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
620 }
621 }
Bob Wilson39c88a62009-12-17 18:34:24 +0000622 }
623}
624
Bob Wilsonb742def2009-12-18 20:14:40 +0000625/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
626/// and recursively continue updating all of its uses.
627void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
628 SmallVector<AllocaInst*, 32> &NewElts) {
629 RewriteForScalarRepl(BC, AI, Offset, NewElts);
630 if (BC->getOperand(0) != AI)
631 return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000632
Bob Wilsonb742def2009-12-18 20:14:40 +0000633 // The bitcast references the original alloca. Replace its uses with
634 // references to the first new element alloca.
635 Instruction *Val = NewElts[0];
636 if (Val->getType() != BC->getDestTy()) {
637 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
638 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +0000639 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000640 BC->replaceAllUsesWith(Val);
641 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +0000642}
643
Bob Wilsonb742def2009-12-18 20:14:40 +0000644/// FindElementAndOffset - Return the index of the element containing Offset
645/// within the specified type, which must be either a struct or an array.
646/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +0000647/// element. IdxTy is set to the type of the index result to be used in a
648/// GEP instruction.
649uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
650 const Type *&IdxTy) {
651 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +0000652 if (const StructType *ST = dyn_cast<StructType>(T)) {
653 const StructLayout *Layout = TD->getStructLayout(ST);
654 Idx = Layout->getElementContainingOffset(Offset);
655 T = ST->getContainedType(Idx);
656 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +0000657 IdxTy = Type::getInt32Ty(T->getContext());
658 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +0000659 }
Bob Wilsone88728d2009-12-19 06:53:17 +0000660 const ArrayType *AT = cast<ArrayType>(T);
661 T = AT->getElementType();
662 uint64_t EltSize = TD->getTypeAllocSize(T);
663 Idx = Offset / EltSize;
664 Offset -= Idx * EltSize;
665 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +0000666 return Idx;
667}
668
669/// RewriteGEP - Check if this GEP instruction moves the pointer across
670/// elements of the alloca that are being split apart, and if so, rewrite
671/// the GEP to be relative to the new element.
672void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
673 SmallVector<AllocaInst*, 32> &NewElts) {
674 uint64_t OldOffset = Offset;
675 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
676 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
677 &Indices[0], Indices.size());
678
679 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
680
681 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +0000682 const Type *IdxTy;
683 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +0000684 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +0000685 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +0000686
687 T = AI->getAllocatedType();
688 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +0000689 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +0000690
691 // If this GEP does not move the pointer across elements of the alloca
692 // being split, then it does not needs to be rewritten.
693 if (Idx == OldIdx)
694 return;
695
696 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
697 SmallVector<Value*, 8> NewArgs;
698 NewArgs.push_back(Constant::getNullValue(i32Ty));
699 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +0000700 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
701 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +0000702 }
703 Instruction *Val = NewElts[Idx];
704 if (NewArgs.size() > 1) {
705 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
706 NewArgs.end(), "", GEPI);
707 Val->takeName(GEPI);
708 }
709 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +0000710 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +0000711 GEPI->replaceAllUsesWith(Val);
712 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000713}
714
715/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
716/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +0000717void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000718 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000719 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000720 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +0000721 // appropriate type. The "Other" pointer is the pointer that goes to memory
722 // that doesn't have anything to do with the alloca that we are promoting. For
723 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000724 Value *OtherPtr = 0;
Owen Andersone922c022009-07-22 00:24:57 +0000725 LLVMContext &Context = MI->getContext();
Chris Lattnerdfe964c2009-03-08 03:59:00 +0000726 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +0000727 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +0000728 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +0000729 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000730 else {
Bob Wilsonb742def2009-12-18 20:14:40 +0000731 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +0000732 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000733 }
734 }
Bob Wilson78c50b82009-12-08 18:22:03 +0000735
Chris Lattnerd93afec2009-01-07 07:18:45 +0000736 // If there is an other pointer, we want to convert it to the same pointer
737 // type as AI has, so we can GEP through it safely.
738 if (OtherPtr) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000739
740 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
741 // optimization, but it's also required to detect the corner case where
742 // both pointer operands are referencing the same memory, and where
743 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
744 // function is only called for mem intrinsics that access the whole
745 // aggregate, so non-zero GEPs are not an issue here.)
746 while (1) {
747 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr)) {
748 OtherPtr = BC->getOperand(0);
749 continue;
750 }
751 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr)) {
752 // All zero GEPs are effectively bitcasts.
753 if (GEP->hasAllZeroIndices()) {
754 OtherPtr = GEP->getOperand(0);
755 continue;
756 }
757 }
758 break;
759 }
Bob Wilsona756b1d2010-01-19 04:32:48 +0000760 // Copying the alloca to itself is a no-op: just delete it.
761 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
762 // This code will run twice for a no-op memcpy -- once for each operand.
763 // Put only one reference to MI on the DeadInsts list.
764 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
765 E = DeadInsts.end(); I != E; ++I)
766 if (*I == MI) return;
767 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +0000768 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +0000769 }
Chris Lattner372dda82007-03-05 07:52:57 +0000770
Chris Lattnerd93afec2009-01-07 07:18:45 +0000771 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
772 if (BCE->getOpcode() == Instruction::BitCast)
773 OtherPtr = BCE->getOperand(0);
774
775 // If the pointer is not the right type, insert a bitcast to the right
776 // type.
777 if (OtherPtr->getType() != AI->getType())
778 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
779 MI);
780 }
781
782 // Process each element of the aggregate.
Gabor Greif2ff961f2010-04-15 20:51:13 +0000783 Value *TheFn = MI->getCalledValue();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000784 const Type *BytePtrTy = MI->getRawDest()->getType();
Bob Wilsonb742def2009-12-18 20:14:40 +0000785 bool SROADest = MI->getRawDest() == Inst;
Chris Lattnerd93afec2009-01-07 07:18:45 +0000786
Owen Anderson1d0be152009-08-13 21:58:54 +0000787 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +0000788
789 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
790 // If this is a memcpy/memmove, emit a GEP of the other element address.
791 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000792 unsigned OtherEltAlign = MemAlignment;
793
Bob Wilsona756b1d2010-01-19 04:32:48 +0000794 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000795 Value *Idx[2] = { Zero,
796 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +0000797 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +0000798 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +0000799 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +0000800 uint64_t EltOffset;
801 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
802 if (const StructType *ST =
803 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
804 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
805 } else {
806 const Type *EltTy =
807 cast<SequentialType>(OtherPtr->getType())->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000808 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000809 }
810
811 // The alignment of the other pointer is the guaranteed alignment of the
812 // element, which is affected by both the known alignment of the whole
813 // mem intrinsic and the alignment of the element. If the alignment of
814 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
815 // known alignment is just 4 bytes.
816 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000817 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000818
819 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +0000820 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000821
822 // If we got down to a scalar, insert a load or store as appropriate.
823 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000824 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +0000825 if (SROADest) {
826 // From Other to Alloca.
827 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
828 new StoreInst(Elt, EltPtr, MI);
829 } else {
830 // From Alloca to Other.
831 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
832 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
833 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000834 continue;
835 }
836 assert(isa<MemSetInst>(MI));
837
838 // If the stored element is zero (common case), just store a null
839 // constant.
840 Constant *StoreVal;
Gabor Greif2ff961f2010-04-15 20:51:13 +0000841 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000842 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000843 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +0000844 } else {
845 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +0000846 const Type *ValTy = EltTy->getScalarType();
847
Chris Lattnerd93afec2009-01-07 07:18:45 +0000848 // Construct an integer with the right value.
849 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
850 APInt OneVal(EltSize, CI->getZExtValue());
851 APInt TotalVal(OneVal);
852 // Set each byte.
853 for (unsigned i = 0; 8*i < EltSize; ++i) {
854 TotalVal = TotalVal.shl(8);
855 TotalVal |= OneVal;
856 }
857
858 // Convert the integer value to the appropriate type.
Owen Andersoneed707b2009-07-24 23:12:02 +0000859 StoreVal = ConstantInt::get(Context, TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +0000860 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000861 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000862 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000863 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000864 assert(StoreVal->getType() == ValTy && "Type mismatch!");
865
866 // If the requested value was a vector constant, create it.
867 if (EltTy != ValTy) {
868 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
869 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +0000870 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000871 }
872 }
873 new StoreInst(StoreVal, EltPtr, MI);
874 continue;
875 }
876 // Otherwise, if we're storing a byte variable, use a memset call for
877 // this element.
878 }
879
880 // Cast the element pointer to BytePtrTy.
881 if (EltPtr->getType() != BytePtrTy)
Benjamin Kramer2d64ca02010-01-27 19:46:52 +0000882 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000883
884 // Cast the other pointer (if we have one) to BytePtrTy.
Mon P Wang20adc9d2010-04-04 03:10:48 +0000885 if (OtherElt && OtherElt->getType() != BytePtrTy) {
886 // Preserve address space of OtherElt
887 const PointerType* OtherPTy = cast<PointerType>(OtherElt->getType());
888 const PointerType* PTy = cast<PointerType>(BytePtrTy);
889 if (OtherPTy->getElementType() != PTy->getElementType()) {
890 Type *NewOtherPTy = PointerType::get(PTy->getElementType(),
891 OtherPTy->getAddressSpace());
892 OtherElt = new BitCastInst(OtherElt, NewOtherPTy,
893 OtherElt->getNameStr(), MI);
894 }
895 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000896
Duncan Sands777d2302009-05-09 07:06:46 +0000897 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000898
899 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000900 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000901 Value *Ops[] = {
902 SROADest ? EltPtr : OtherElt, // Dest ptr
903 SROADest ? OtherElt : EltPtr, // Src ptr
Gabor Greif2ff961f2010-04-15 20:51:13 +0000904 ConstantInt::get(MI->getOperand(2)->getType(), EltSize), // Size
Owen Anderson1d0be152009-08-13 21:58:54 +0000905 // Align
Mon P Wang20adc9d2010-04-04 03:10:48 +0000906 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign),
907 MI->getVolatileCst()
Chris Lattnerd93afec2009-01-07 07:18:45 +0000908 };
Mon P Wang20adc9d2010-04-04 03:10:48 +0000909 // In case we fold the address space overloaded memcpy of A to B
910 // with memcpy of B to C, change the function to be a memcpy of A to C.
911 const Type *Tys[] = { Ops[0]->getType(), Ops[1]->getType(),
912 Ops[2]->getType() };
913 Module *M = MI->getParent()->getParent()->getParent();
914 TheFn = Intrinsic::getDeclaration(M, MI->getIntrinsicID(), Tys, 3);
915 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000916 } else {
917 assert(isa<MemSetInst>(MI));
918 Value *Ops[] = {
Gabor Greif2ff961f2010-04-15 20:51:13 +0000919 EltPtr, MI->getOperand(1), // Dest, Value,
920 ConstantInt::get(MI->getOperand(2)->getType(), EltSize), // Size
Mon P Wang20adc9d2010-04-04 03:10:48 +0000921 Zero, // Align
922 ConstantInt::get(Type::getInt1Ty(MI->getContext()), 0) // isVolatile
Chris Lattnerd93afec2009-01-07 07:18:45 +0000923 };
Mon P Wang20adc9d2010-04-04 03:10:48 +0000924 const Type *Tys[] = { Ops[0]->getType(), Ops[2]->getType() };
925 Module *M = MI->getParent()->getParent()->getParent();
926 TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys, 2);
927 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000928 }
Chris Lattner372dda82007-03-05 07:52:57 +0000929 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000930 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +0000931}
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000932
Bob Wilson39fdd692009-12-04 21:57:37 +0000933/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000934/// overwrites the entire allocation. Extract out the pieces of the stored
935/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000936void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000937 SmallVector<AllocaInst*, 32> &NewElts){
938 // Extract each element out of the integer according to its structure offset
939 // and store the element value to the individual alloca.
940 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +0000941 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +0000942 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000943
Eli Friedman41b33f42009-06-01 09:14:32 +0000944 // Handle tail padding by extending the operand
945 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000946 SrcVal = new ZExtInst(SrcVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000947 IntegerType::get(SI->getContext(), AllocaSizeBits),
948 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000949
David Greene504c7d82010-01-05 01:27:09 +0000950 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +0000951 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000952
953 // There are two forms here: AI could be an array or struct. Both cases
954 // have different ways to compute the element offset.
955 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
956 const StructLayout *Layout = TD->getStructLayout(EltSTy);
957
958 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
959 // Get the number of bits to shift SrcVal to get the value.
960 const Type *FieldTy = EltSTy->getElementType(i);
961 uint64_t Shift = Layout->getElementOffsetInBits(i);
962
963 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +0000964 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000965
966 Value *EltVal = SrcVal;
967 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000968 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000969 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
970 "sroa.store.elt", SI);
971 }
972
973 // Truncate down to an integer of the right size.
974 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +0000975
976 // Ignore zero sized fields like {}, they obviously contain no data.
977 if (FieldSizeBits == 0) continue;
978
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000979 if (FieldSizeBits != 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(), FieldSizeBits),
982 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000983 Value *DestField = NewElts[i];
984 if (EltVal->getType() == FieldTy) {
985 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +0000986 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000987 // Bitcast to the right element type (for fp/vector values).
988 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
989 } else {
990 // Otherwise, bitcast the dest pointer (for aggregates).
991 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +0000992 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000993 "", SI);
994 }
995 new StoreInst(EltVal, DestField, SI);
996 }
997
998 } else {
999 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1000 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001001 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001002 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1003
1004 uint64_t Shift;
1005
1006 if (TD->isBigEndian())
1007 Shift = AllocaSizeBits-ElementOffset;
1008 else
1009 Shift = 0;
1010
1011 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00001012 // Ignore zero sized fields like {}, they obviously contain no data.
1013 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001014
1015 Value *EltVal = SrcVal;
1016 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001017 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001018 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1019 "sroa.store.elt", SI);
1020 }
1021
1022 // Truncate down to an integer of the right size.
1023 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001024 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001025 IntegerType::get(SI->getContext(),
1026 ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001027 Value *DestField = NewElts[i];
1028 if (EltVal->getType() == ArrayEltTy) {
1029 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001030 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001031 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001032 // Bitcast to the right element type (for fp/vector values).
1033 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1034 } else {
1035 // Otherwise, bitcast the dest pointer (for aggregates).
1036 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001037 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001038 "", SI);
1039 }
1040 new StoreInst(EltVal, DestField, SI);
1041
1042 if (TD->isBigEndian())
1043 Shift -= ElementOffset;
1044 else
1045 Shift += ElementOffset;
1046 }
1047 }
1048
Bob Wilsonb742def2009-12-18 20:14:40 +00001049 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001050}
1051
Bob Wilson39fdd692009-12-04 21:57:37 +00001052/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001053/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001054void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001055 SmallVector<AllocaInst*, 32> &NewElts) {
1056 // Extract each element out of the NewElts according to its structure offset
1057 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00001058 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001059 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001060
David Greene504c7d82010-01-05 01:27:09 +00001061 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00001062 << '\n');
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001063
1064 // There are two forms here: AI could be an array or struct. Both cases
1065 // have different ways to compute the element offset.
1066 const StructLayout *Layout = 0;
1067 uint64_t ArrayEltBitOffset = 0;
1068 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1069 Layout = TD->getStructLayout(EltSTy);
1070 } else {
1071 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001072 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001073 }
Owen Andersone922c022009-07-22 00:24:57 +00001074
Owen Andersone922c022009-07-22 00:24:57 +00001075 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001076 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001077
1078 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1079 // Load the value from the alloca. If the NewElt is an aggregate, cast
1080 // the pointer to an integer of the same size before doing the load.
1081 Value *SrcField = NewElts[i];
1082 const Type *FieldTy =
1083 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001084 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1085
1086 // Ignore zero sized fields like {}, they obviously contain no data.
1087 if (FieldSizeBits == 0) continue;
1088
Owen Anderson1d0be152009-08-13 21:58:54 +00001089 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1090 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00001091 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1092 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001093 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001094 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001095 "", LI);
1096 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1097
1098 // If SrcField is a fp or vector of the right size but that isn't an
1099 // integer type, bitcast to an integer so we can shift it.
1100 if (SrcField->getType() != FieldIntTy)
1101 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1102
1103 // Zero extend the field to be the same size as the final alloca so that
1104 // we can shift and insert it.
1105 if (SrcField->getType() != ResultVal->getType())
1106 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1107
1108 // Determine the number of bits to shift SrcField.
1109 uint64_t Shift;
1110 if (Layout) // Struct case.
1111 Shift = Layout->getElementOffsetInBits(i);
1112 else // Array case.
1113 Shift = i*ArrayEltBitOffset;
1114
1115 if (TD->isBigEndian())
1116 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1117
1118 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001119 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001120 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1121 }
1122
1123 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1124 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001125
1126 // Handle tail padding by truncating the result
1127 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1128 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1129
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001130 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00001131 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001132}
1133
Duncan Sands3cb36502007-11-04 14:43:57 +00001134/// HasPadding - Return true if the specified type has any structure or
1135/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001136static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001137 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1138 const StructLayout *SL = TD.getStructLayout(STy);
1139 unsigned PrevFieldBitOffset = 0;
1140 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001141 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1142
Chris Lattner39a1c042007-05-30 06:11:23 +00001143 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001144 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001145 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001146
Chris Lattner39a1c042007-05-30 06:11:23 +00001147 // Check to see if there is any padding between this element and the
1148 // previous one.
1149 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001150 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001151 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1152 if (PrevFieldEnd < FieldBitOffset)
1153 return true;
1154 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001155
Chris Lattner39a1c042007-05-30 06:11:23 +00001156 PrevFieldBitOffset = FieldBitOffset;
1157 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001158
Chris Lattner39a1c042007-05-30 06:11:23 +00001159 // Check for tail padding.
1160 if (unsigned EltCount = STy->getNumElements()) {
1161 unsigned PrevFieldEnd = PrevFieldBitOffset +
1162 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001163 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001164 return true;
1165 }
1166
1167 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001168 return HasPadding(ATy->getElementType(), TD);
Duncan Sands3cb36502007-11-04 14:43:57 +00001169 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001170 return HasPadding(VTy->getElementType(), TD);
Chris Lattner39a1c042007-05-30 06:11:23 +00001171 }
Duncan Sands777d2302009-05-09 07:06:46 +00001172 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001173}
Chris Lattner372dda82007-03-05 07:52:57 +00001174
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001175/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1176/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1177/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001178bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001179 // Loop over the use list of the alloca. We can only transform it if all of
1180 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001181 AllocaInfo Info;
1182
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001183 isSafeForScalarRepl(AI, AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001184 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00001185 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001186 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001187 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001188
1189 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1190 // source and destination, we have to be careful. In particular, the memcpy
1191 // could be moving around elements that live in structure padding of the LLVM
1192 // types, but may actually be used. In these cases, we refuse to promote the
1193 // struct.
1194 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001195 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001196 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00001197
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001198 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00001199}
Chris Lattnera1888942005-12-12 07:19:13 +00001200
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001201/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1202/// the offset specified by Offset (which is specified in bytes).
Chris Lattnerde6df882006-04-14 21:42:41 +00001203///
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001204/// There are two cases we handle here:
1205/// 1) A union of vector types of the same size and potentially its elements.
Chris Lattnerd22dbdf2006-12-15 07:32:38 +00001206/// Here we turn element accesses into insert/extract element operations.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001207/// This promotes a <4 x float> with a store of float to the third element
1208/// into a <4 x float> that uses insert element.
1209/// 2) A fully general blob of memory, which we turn into some (potentially
1210/// large) integer type with extract and insert operations where the loads
1211/// and stores would mutate the memory.
Chris Lattnerc4472072010-04-15 23:50:26 +00001212static void MergeInType(const Type *In, uint64_t Offset,
1213 ConvertToScalarInfo &ConvertInfo, const TargetData &TD){
1214 // Remember if we saw a vector type.
1215 ConvertInfo.HadAVector |= In->isVectorTy();
1216
1217 if (ConvertInfo.VectorTy && ConvertInfo.VectorTy->isVoidTy())
1218 return;
1219
Chris Lattner7809ecd2009-02-03 01:30:09 +00001220 // If this could be contributing to a vector, analyze it.
Chris Lattner996d7a92009-02-02 18:02:59 +00001221
Chris Lattnerc4472072010-04-15 23:50:26 +00001222 // If the In type is a vector that is the same size as the alloca, see if it
1223 // matches the existing VecTy.
1224 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1225 if (VInTy->getBitWidth()/8 == ConvertInfo.AllocaSize && Offset == 0) {
1226 // If we're storing/loading a vector of the right size, allow it as a
1227 // vector. If this the first vector we see, remember the type so that
1228 // we know the element size.
1229 if (ConvertInfo.VectorTy == 0)
1230 ConvertInfo.VectorTy = VInTy;
1231 return;
1232 }
1233 } else if (In->isFloatTy() || In->isDoubleTy() ||
1234 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
1235 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1236 // If we're accessing something that could be an element of a vector, see
1237 // if the implied vector agrees with what we already have and if Offset is
1238 // compatible with it.
1239 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1240 if (Offset % EltSize == 0 &&
1241 ConvertInfo.AllocaSize % EltSize == 0 &&
1242 (ConvertInfo.VectorTy == 0 ||
1243 cast<VectorType>(ConvertInfo.VectorTy)->getElementType()
1244 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1245 if (ConvertInfo.VectorTy == 0)
1246 ConvertInfo.VectorTy = VectorType::get(In,
1247 ConvertInfo.AllocaSize/EltSize);
1248 return;
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001249 }
1250 }
1251
Chris Lattner7809ecd2009-02-03 01:30:09 +00001252 // Otherwise, we have a case that we can't handle with an optimized vector
1253 // form. We can still turn this into a large integer.
Chris Lattnerc4472072010-04-15 23:50:26 +00001254 ConvertInfo.VectorTy = Type::getVoidTy(In->getContext());
Chris Lattnera1888942005-12-12 07:19:13 +00001255}
1256
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001257/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
Bob Wilsonefc58e72009-12-09 18:05:27 +00001258/// its accesses to a single vector type, return true and set VecTy to
Chris Lattner7809ecd2009-02-03 01:30:09 +00001259/// the new type. If we could convert the alloca into a single promotable
1260/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1261/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1262/// is the current offset from the base of the alloca being analyzed.
Chris Lattnera1888942005-12-12 07:19:13 +00001263///
Chris Lattner1a3257b2009-02-03 18:15:05 +00001264/// If we see at least one access to the value that is as a vector type, set the
1265/// SawVec flag.
Chris Lattnerc4472072010-04-15 23:50:26 +00001266bool SROA::CanConvertToScalar(Value *V, ConvertToScalarInfo &ConvertInfo,
1267 uint64_t Offset) {
Chris Lattnera1888942005-12-12 07:19:13 +00001268 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1269 Instruction *User = cast<Instruction>(*UI);
1270
1271 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001272 // Don't break volatile loads.
Chris Lattner6e733d32009-01-28 20:16:43 +00001273 if (LI->isVolatile())
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001274 return false;
Chris Lattnerc4472072010-04-15 23:50:26 +00001275 MergeInType(LI->getType(), Offset, ConvertInfo, *TD);
Chris Lattnercf321862009-01-07 06:39:58 +00001276 continue;
1277 }
1278
1279 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001280 // Storing the pointer, not into the value?
Chris Lattnerc4472072010-04-15 23:50:26 +00001281 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
1282 MergeInType(SI->getOperand(0)->getType(), Offset, ConvertInfo, *TD);
Chris Lattnercf321862009-01-07 06:39:58 +00001283 continue;
1284 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001285
1286 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerc4472072010-04-15 23:50:26 +00001287 if (!CanConvertToScalar(BCI, ConvertInfo, Offset))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001288 return false;
Chris Lattnerc4472072010-04-15 23:50:26 +00001289 ConvertInfo.IsNotTrivial = true;
Chris Lattnercf321862009-01-07 06:39:58 +00001290 continue;
1291 }
1292
1293 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001294 // If this is a GEP with a variable indices, we can't handle it.
1295 if (!GEP->hasAllConstantIndices())
1296 return false;
Chris Lattnercf321862009-01-07 06:39:58 +00001297
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001298 // Compute the offset that this GEP adds to the pointer.
1299 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Bob Wilsonb742def2009-12-18 20:14:40 +00001300 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001301 &Indices[0], Indices.size());
1302 // See if all uses can be converted.
Chris Lattnerc4472072010-04-15 23:50:26 +00001303 if (!CanConvertToScalar(GEP, ConvertInfo, Offset+GEPOffset))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001304 return false;
Chris Lattnerc4472072010-04-15 23:50:26 +00001305 ConvertInfo.IsNotTrivial = true;
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001306 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001307 }
Chris Lattner3ce5e882009-03-08 03:37:16 +00001308
Chris Lattner3d730f72009-02-03 02:01:43 +00001309 // If this is a constant sized memset of a constant value (e.g. 0) we can
1310 // handle it.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001311 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1312 // Store of constant value and constant size.
1313 if (isa<ConstantInt>(MSI->getValue()) &&
1314 isa<ConstantInt>(MSI->getLength())) {
Chris Lattnerc4472072010-04-15 23:50:26 +00001315 ConvertInfo.IsNotTrivial = true;
Chris Lattner3ce5e882009-03-08 03:37:16 +00001316 continue;
1317 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001318 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001319
1320 // If this is a memcpy or memmove into or out of the whole allocation, we
1321 // can handle it like a load or store of the scalar type.
1322 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1323 if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
Chris Lattnerc4472072010-04-15 23:50:26 +00001324 if (Len->getZExtValue() == ConvertInfo.AllocaSize && Offset == 0) {
1325 ConvertInfo.IsNotTrivial = true;
Chris Lattnerc5704872009-03-08 04:04:21 +00001326 continue;
1327 }
1328 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001329
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001330 // Otherwise, we cannot handle this!
1331 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001332 }
1333
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001334 return true;
Chris Lattnera1888942005-12-12 07:19:13 +00001335}
1336
Chris Lattnera1888942005-12-12 07:19:13 +00001337/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattnerde6df882006-04-14 21:42:41 +00001338/// directly. This happens when we are converting an "integer union" to a
1339/// single integer scalar, or when we are converting a "vector union" to a
1340/// vector with insert/extractelement instructions.
1341///
1342/// Offset is an offset from the original alloca, in bits that need to be
1343/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001344void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
Chris Lattnera1888942005-12-12 07:19:13 +00001345 while (!Ptr->use_empty()) {
1346 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001347
Chris Lattnercf321862009-01-07 06:39:58 +00001348 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb10e0da2008-01-30 00:39:15 +00001349 ConvertUsesToScalar(CI, NewAI, Offset);
Chris Lattnera1888942005-12-12 07:19:13 +00001350 CI->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001351 continue;
1352 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001353
Chris Lattnercf321862009-01-07 06:39:58 +00001354 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001355 // Compute the offset that this GEP adds to the pointer.
1356 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Bob Wilsonb742def2009-12-18 20:14:40 +00001357 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001358 &Indices[0], Indices.size());
1359 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Chris Lattnera1888942005-12-12 07:19:13 +00001360 GEP->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001361 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001362 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001363
Chris Lattner9bc67da2009-02-03 19:45:44 +00001364 IRBuilder<> Builder(User->getParent(), User);
1365
1366 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner6e011152009-02-03 21:01:03 +00001367 // The load is a bit extract from NewAI shifted right by Offset bits.
1368 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1369 Value *NewLoadVal
1370 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1371 LI->replaceAllUsesWith(NewLoadVal);
Chris Lattner9bc67da2009-02-03 19:45:44 +00001372 LI->eraseFromParent();
1373 continue;
1374 }
1375
1376 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1377 assert(SI->getOperand(0) != Ptr && "Consistency error!");
Chris Lattneraadadb32009-12-22 19:33:28 +00001378 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
Chris Lattner9bc67da2009-02-03 19:45:44 +00001379 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1380 Builder);
1381 Builder.CreateStore(New, NewAI);
1382 SI->eraseFromParent();
Chris Lattneraadadb32009-12-22 19:33:28 +00001383
1384 // If the load we just inserted is now dead, then the inserted store
1385 // overwrote the entire thing.
1386 if (Old->use_empty())
1387 Old->eraseFromParent();
Chris Lattner9bc67da2009-02-03 19:45:44 +00001388 continue;
1389 }
1390
Chris Lattner3d730f72009-02-03 02:01:43 +00001391 // If this is a constant sized memset of a constant value (e.g. 0) we can
1392 // transform it into a store of the expanded constant value.
1393 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1394 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1395 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Chris Lattner33e24ad2009-04-21 16:52:12 +00001396 if (NumBytes != 0) {
1397 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1398
1399 // Compute the value replicated the right number of times.
1400 APInt APVal(NumBytes*8, Val);
Chris Lattner3d730f72009-02-03 02:01:43 +00001401
Chris Lattner33e24ad2009-04-21 16:52:12 +00001402 // Splat the value if non-zero.
1403 if (Val)
1404 for (unsigned i = 1; i != NumBytes; ++i)
1405 APVal |= APVal << 8;
Benjamin Kramere6f32942009-11-29 21:17:48 +00001406
Chris Lattneraadadb32009-12-22 19:33:28 +00001407 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
Owen Andersone922c022009-07-22 00:24:57 +00001408 Value *New = ConvertScalar_InsertValue(
Owen Andersoneed707b2009-07-24 23:12:02 +00001409 ConstantInt::get(User->getContext(), APVal),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001410 Old, Offset, Builder);
Chris Lattner33e24ad2009-04-21 16:52:12 +00001411 Builder.CreateStore(New, NewAI);
Chris Lattneraadadb32009-12-22 19:33:28 +00001412
1413 // If the load we just inserted is now dead, then the memset overwrote
1414 // the entire thing.
1415 if (Old->use_empty())
1416 Old->eraseFromParent();
Chris Lattner33e24ad2009-04-21 16:52:12 +00001417 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001418 MSI->eraseFromParent();
1419 continue;
1420 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001421
1422 // If this is a memcpy or memmove into or out of the whole allocation, we
1423 // can handle it like a load or store of the scalar type.
1424 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1425 assert(Offset == 0 && "must be store to start of alloca");
1426
1427 // If the source and destination are both to the same alloca, then this is
1428 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
1429 // as appropriate.
Bob Wilson03274292010-01-25 18:26:54 +00001430 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject(0));
Chris Lattnerc5704872009-03-08 04:04:21 +00001431
Bob Wilson03274292010-01-25 18:26:54 +00001432 if (MTI->getSource()->getUnderlyingObject(0) != OrigAI) {
Chris Lattnerc5704872009-03-08 04:04:21 +00001433 // Dest must be OrigAI, change this to be a load from the original
1434 // pointer (bitcasted), then a store to our new alloca.
1435 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1436 Value *SrcPtr = MTI->getSource();
1437 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1438
1439 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1440 SrcVal->setAlignment(MTI->getAlignment());
1441 Builder.CreateStore(SrcVal, NewAI);
Bob Wilson03274292010-01-25 18:26:54 +00001442 } else if (MTI->getDest()->getUnderlyingObject(0) != OrigAI) {
Chris Lattnerc5704872009-03-08 04:04:21 +00001443 // Src must be OrigAI, change this to be a load from NewAI then a store
1444 // through the original dest pointer (bitcasted).
1445 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1446 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1447
1448 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1449 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1450 NewStore->setAlignment(MTI->getAlignment());
1451 } else {
1452 // Noop transfer. Src == Dst
1453 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001454
1455 MTI->eraseFromParent();
1456 continue;
1457 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001458
Torok Edwinc23197a2009-07-14 16:55:14 +00001459 llvm_unreachable("Unsupported operation!");
Chris Lattnera1888942005-12-12 07:19:13 +00001460 }
1461}
Chris Lattner79b3bd32007-04-25 06:40:51 +00001462
Chris Lattner6e011152009-02-03 21:01:03 +00001463/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1464/// or vector value FromVal, extracting the bits from the offset specified by
1465/// Offset. This returns the value, which is of type ToType.
1466///
1467/// This happens when we are converting an "integer union" to a single
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001468/// integer scalar, or when we are converting a "vector union" to a vector with
1469/// insert/extractelement instructions.
Chris Lattner800de312008-02-29 07:03:13 +00001470///
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001471/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner6e011152009-02-03 21:01:03 +00001472/// shifted to the right.
1473Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1474 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001475 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattner6e011152009-02-03 21:01:03 +00001476 if (FromVal->getType() == ToType && Offset == 0)
1477 return FromVal;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001478
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001479 // If the result alloca is a vector type, this is either an element
1480 // access or a bitcast to another vector type of the same size.
Chris Lattner6e011152009-02-03 21:01:03 +00001481 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
Duncan Sands1df98592010-02-16 11:11:14 +00001482 if (ToType->isVectorTy())
Chris Lattner6e011152009-02-03 21:01:03 +00001483 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001484
1485 // Otherwise it must be an element access.
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001486 unsigned Elt = 0;
1487 if (Offset) {
Duncan Sands777d2302009-05-09 07:06:46 +00001488 unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001489 Elt = Offset/EltSize;
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001490 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner800de312008-02-29 07:03:13 +00001491 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001492 // Return the element extracted out of it.
Owen Anderson1d0be152009-08-13 21:58:54 +00001493 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
1494 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
Chris Lattner6e011152009-02-03 21:01:03 +00001495 if (V->getType() != ToType)
1496 V = Builder.CreateBitCast(V, ToType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001497 return V;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001498 }
Chris Lattner1aa70562009-02-03 21:08:45 +00001499
1500 // If ToType is a first class aggregate, extract out each of the pieces and
1501 // use insertvalue's to form the FCA.
1502 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1503 const StructLayout &Layout = *TD->getStructLayout(ST);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001504 Value *Res = UndefValue::get(ST);
Chris Lattner1aa70562009-02-03 21:08:45 +00001505 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1506 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
Chris Lattnere991ced2009-02-06 04:34:07 +00001507 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner1aa70562009-02-03 21:08:45 +00001508 Builder);
1509 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1510 }
1511 return Res;
1512 }
1513
1514 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001515 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001516 Value *Res = UndefValue::get(AT);
Chris Lattner1aa70562009-02-03 21:08:45 +00001517 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1518 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1519 Offset+i*EltSize, Builder);
1520 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1521 }
1522 return Res;
1523 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001524
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001525 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattner6e011152009-02-03 21:01:03 +00001526 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001527
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001528 // If this is a big-endian system and the load is narrower than the
1529 // full alloca type, we need to do a shift to get the right bits.
1530 int ShAmt = 0;
Chris Lattner56c38522009-01-07 06:34:28 +00001531 if (TD->isBigEndian()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001532 // On big-endian machines, the lowest bit is stored at the bit offset
1533 // from the pointer given by getTypeStoreSizeInBits. This matters for
1534 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner56c38522009-01-07 06:34:28 +00001535 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
Chris Lattner6e011152009-02-03 21:01:03 +00001536 TD->getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001537 } else {
1538 ShAmt = Offset;
1539 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001540
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001541 // Note: we support negative bitwidths (with shl) which are not defined.
1542 // We do this to support (f.e.) loads off the end of a structure where
1543 // only some bits are used.
1544 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001545 FromVal = Builder.CreateLShr(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001546 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001547 ShAmt), "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001548 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001549 FromVal = Builder.CreateShl(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001550 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001551 -ShAmt), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001552
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001553 // Finally, unconditionally truncate the integer to the right width.
Chris Lattner6e011152009-02-03 21:01:03 +00001554 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001555 if (LIBitWidth < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001556 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001557 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
1558 LIBitWidth), "tmp");
Chris Lattner55a683d2009-02-03 07:08:57 +00001559 else if (LIBitWidth > NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001560 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001561 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
1562 LIBitWidth), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001563
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001564 // If the result is an integer, this is a trunc or bitcast.
Duncan Sands1df98592010-02-16 11:11:14 +00001565 if (ToType->isIntegerTy()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001566 // Should be done.
Duncan Sands1df98592010-02-16 11:11:14 +00001567 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001568 // Just do a bitcast, we know the sizes match up.
Chris Lattner6e011152009-02-03 21:01:03 +00001569 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001570 } else {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001571 // Otherwise must be a pointer.
Chris Lattner6e011152009-02-03 21:01:03 +00001572 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001573 }
Chris Lattner6e011152009-02-03 21:01:03 +00001574 assert(FromVal->getType() == ToType && "Didn't convert right?");
1575 return FromVal;
Chris Lattner800de312008-02-29 07:03:13 +00001576}
1577
Chris Lattner9b872db2009-02-03 19:30:11 +00001578/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1579/// or vector value "Old" at the offset specified by Offset.
1580///
1581/// This happens when we are converting an "integer union" to a
Chris Lattner800de312008-02-29 07:03:13 +00001582/// single integer scalar, or when we are converting a "vector union" to a
1583/// vector with insert/extractelement instructions.
1584///
1585/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner9b872db2009-02-03 19:30:11 +00001586/// shifted to the right.
1587Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
Chris Lattner65a65022009-02-03 19:41:50 +00001588 uint64_t Offset, IRBuilder<> &Builder) {
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001589
Chris Lattner800de312008-02-29 07:03:13 +00001590 // Convert the stored type to the actual type, shift it left to insert
1591 // then 'or' into place.
Chris Lattner9b872db2009-02-03 19:30:11 +00001592 const Type *AllocaType = Old->getType();
Owen Andersone922c022009-07-22 00:24:57 +00001593 LLVMContext &Context = Old->getContext();
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001594
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001595 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001596 uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1597 uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
Chris Lattner29e64172009-03-08 04:17:04 +00001598
1599 // Changing the whole vector with memset or with an access of a different
1600 // vector type?
1601 if (ValSize == VecSize)
1602 return Builder.CreateBitCast(SV, AllocaType, "tmp");
1603
Duncan Sands777d2302009-05-09 07:06:46 +00001604 uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner29e64172009-03-08 04:17:04 +00001605
1606 // Must be an element insertion.
1607 unsigned Elt = Offset/EltSize;
1608
1609 if (SV->getType() != VTy->getElementType())
1610 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1611
1612 SV = Builder.CreateInsertElement(Old, SV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001613 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
Chris Lattner29e64172009-03-08 04:17:04 +00001614 "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001615 return SV;
1616 }
Chris Lattner9b872db2009-02-03 19:30:11 +00001617
1618 // If SV is a first-class aggregate value, insert each value recursively.
1619 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1620 const StructLayout &Layout = *TD->getStructLayout(ST);
1621 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001622 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Chris Lattner9b872db2009-02-03 19:30:11 +00001623 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattnere991ced2009-02-06 04:34:07 +00001624 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner65a65022009-02-03 19:41:50 +00001625 Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001626 }
1627 return Old;
1628 }
1629
1630 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Duncan Sands777d2302009-05-09 07:06:46 +00001631 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner9b872db2009-02-03 19:30:11 +00001632 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001633 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1634 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001635 }
1636 return Old;
1637 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001638
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001639 // If SV is a float, convert it to the appropriate integer type.
Chris Lattner9b872db2009-02-03 19:30:11 +00001640 // If it is a pointer, do the same.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001641 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1642 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1643 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1644 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
Duncan Sands1df98592010-02-16 11:11:14 +00001645 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001646 SV = Builder.CreateBitCast(SV,
1647 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
Duncan Sands1df98592010-02-16 11:11:14 +00001648 else if (SV->getType()->isPointerTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001649 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(SV->getContext()), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001650
Chris Lattner7809ecd2009-02-03 01:30:09 +00001651 // Zero extend or truncate the value if needed.
1652 if (SV->getType() != AllocaType) {
1653 if (SV->getType()->getPrimitiveSizeInBits() <
1654 AllocaType->getPrimitiveSizeInBits())
Chris Lattner65a65022009-02-03 19:41:50 +00001655 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001656 else {
1657 // Truncation may be needed if storing more than the alloca can hold
1658 // (undefined behavior).
Chris Lattner65a65022009-02-03 19:41:50 +00001659 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001660 SrcWidth = DestWidth;
1661 SrcStoreWidth = DestStoreWidth;
1662 }
1663 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001664
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001665 // If this is a big-endian system and the store is narrower than the
1666 // full alloca type, we need to do a shift to get the right bits.
1667 int ShAmt = 0;
1668 if (TD->isBigEndian()) {
1669 // On big-endian machines, the lowest bit is stored at the bit offset
1670 // from the pointer given by getTypeStoreSizeInBits. This matters for
1671 // integers with a bitwidth that is not a multiple of 8.
1672 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner800de312008-02-29 07:03:13 +00001673 } else {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001674 ShAmt = Offset;
1675 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001676
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001677 // Note: we support negative bitwidths (with shr) which are not defined.
1678 // We do this to support (f.e.) stores off the end of a structure where
1679 // only some bits in the structure are set.
1680 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1681 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001682 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001683 ShAmt), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001684 Mask <<= ShAmt;
1685 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001686 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001687 -ShAmt), "tmp");
Duncan Sands0e7c46b2009-02-02 09:53:14 +00001688 Mask = Mask.lshr(-ShAmt);
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001689 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001690
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001691 // Mask out the bits we are about to insert from the old value, and or
1692 // in the new bits.
1693 if (SrcWidth != DestWidth) {
1694 assert(DestWidth > SrcWidth);
Owen Andersoneed707b2009-07-24 23:12:02 +00001695 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
Chris Lattner65a65022009-02-03 19:41:50 +00001696 SV = Builder.CreateOr(Old, SV, "ins");
Chris Lattner800de312008-02-29 07:03:13 +00001697 }
1698 return SV;
1699}
1700
1701
Chris Lattner79b3bd32007-04-25 06:40:51 +00001702
1703/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1704/// some part of a constant global variable. This intentionally only accepts
1705/// constant expressions because we don't can't rewrite arbitrary instructions.
1706static bool PointsToConstantGlobal(Value *V) {
1707 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1708 return GV->isConstant();
1709 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1710 if (CE->getOpcode() == Instruction::BitCast ||
1711 CE->getOpcode() == Instruction::GetElementPtr)
1712 return PointsToConstantGlobal(CE->getOperand(0));
1713 return false;
1714}
1715
1716/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1717/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1718/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1719/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1720/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1721/// the alloca, and if the source pointer is a pointer to a constant global, we
1722/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00001723static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00001724 bool isOffset) {
1725 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00001726 User *U = cast<Instruction>(*UI);
1727
1728 if (LoadInst *LI = dyn_cast<LoadInst>(U))
Chris Lattner6e733d32009-01-28 20:16:43 +00001729 // Ignore non-volatile loads, they are always ok.
1730 if (!LI->isVolatile())
1731 continue;
1732
Gabor Greif8a8a4352010-04-06 19:32:30 +00001733 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001734 // If uses of the bitcast are ok, we are ok.
1735 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1736 return false;
1737 continue;
1738 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00001739 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001740 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1741 // doesn't, it does.
1742 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1743 isOffset || !GEP->hasAllZeroIndices()))
1744 return false;
1745 continue;
1746 }
1747
1748 // If this is isn't our memcpy/memmove, reject it as something we can't
1749 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00001750 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
1751 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00001752 return false;
1753
1754 // If we already have seen a copy, reject the second one.
1755 if (TheCopy) return false;
1756
1757 // If the pointer has been offset from the start of the alloca, we can't
1758 // safely handle this.
1759 if (isOffset) return false;
1760
1761 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greif2ff961f2010-04-15 20:51:13 +00001762 if (UI.getOperandNo() != 0) return false;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001763
Chris Lattner79b3bd32007-04-25 06:40:51 +00001764 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00001765 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001766 return false;
1767
1768 // Otherwise, the transform is safe. Remember the copy instruction.
1769 TheCopy = MI;
1770 }
1771 return true;
1772}
1773
1774/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1775/// modified by a copy from a constant global. If we can prove this, we can
1776/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00001777MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1778 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001779 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1780 return TheCopy;
1781 return 0;
1782}