blob: 0731d514d8dea7f8b6c607246976f31283e4f758 [file] [log] [blame]
Chris Lattnered7b41e2003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnered7b41e2003-05-27 15:45:27 +00009//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation. This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
Chris Lattner38aec322003-09-11 16:45:55 +000013// each member (if possible). Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17// often interact, especially for C++ programs. As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
Chris Lattnered7b41e2003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
Chris Lattner0e5f4992006-12-19 21:40:18 +000022#define DEBUG_TYPE "scalarrepl"
Chris Lattnered7b41e2003-05-27 15:45:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattner38aec322003-09-11 16:45:55 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnered7b41e2003-05-27 15:45:27 +000026#include "llvm/Function.h"
Chris Lattner79b3bd32007-04-25 06:40:51 +000027#include "llvm/GlobalVariable.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000028#include "llvm/Instructions.h"
Chris Lattner372dda82007-03-05 07:52:57 +000029#include "llvm/IntrinsicInst.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Chris Lattner372dda82007-03-05 07:52:57 +000031#include "llvm/Pass.h"
Chris Lattner38aec322003-09-11 16:45:55 +000032#include "llvm/Analysis/Dominators.h"
33#include "llvm/Target/TargetData.h"
34#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000035#include "llvm/Transforms/Utils/Local.h"
Chris Lattner95255282006-06-28 23:17:24 +000036#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000037#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000038#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000039#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000040#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000041#include "llvm/Support/raw_ostream.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000042#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000043#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000044using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000045
Chris Lattner0e5f4992006-12-19 21:40:18 +000046STATISTIC(NumReplaced, "Number of allocas broken up");
47STATISTIC(NumPromoted, "Number of allocas promoted");
48STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000049STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000050
Chris Lattner0e5f4992006-12-19 21:40:18 +000051namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000052 struct SROA : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000053 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000054 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Devang Patelff366852007-07-09 21:19:23 +000055 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000056 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000057 else
58 SRThreshold = T;
59 }
Devang Patel794fd752007-05-01 21:15:47 +000060
Chris Lattnered7b41e2003-05-27 15:45:27 +000061 bool runOnFunction(Function &F);
62
Chris Lattner38aec322003-09-11 16:45:55 +000063 bool performScalarRepl(Function &F);
64 bool performPromotion(Function &F);
65
Chris Lattnera15854c2003-08-31 00:45:13 +000066 // getAnalysisUsage - This pass does not require any passes, but we know it
67 // will not alter the CFG, so say so.
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel326821e2007-06-07 21:57:03 +000069 AU.addRequired<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +000070 AU.addRequired<DominanceFrontier>();
Chris Lattnera15854c2003-08-31 00:45:13 +000071 AU.setPreservesCFG();
72 }
73
Chris Lattnered7b41e2003-05-27 15:45:27 +000074 private:
Chris Lattner56c38522009-01-07 06:34:28 +000075 TargetData *TD;
76
Bob Wilsonb742def2009-12-18 20:14:40 +000077 /// DeadInsts - Keep track of instructions we have made dead, so that
78 /// we can remove them after we are done working.
79 SmallVector<Value*, 32> DeadInsts;
80
Chris Lattner39a1c042007-05-30 06:11:23 +000081 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
82 /// information about the uses. All these fields are initialized to false
83 /// and set to true when something is learned.
84 struct AllocaInfo {
85 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
86 bool isUnsafe : 1;
87
Chris Lattner39a1c042007-05-30 06:11:23 +000088 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
89 bool isMemCpySrc : 1;
90
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000091 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000092 bool isMemCpyDst : 1;
93
94 AllocaInfo()
Victor Hernandez6c146ee2010-01-21 23:05:53 +000095 : isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +000096 };
97
Devang Patelff366852007-07-09 21:19:23 +000098 unsigned SRThreshold;
99
Chris Lattner39a1c042007-05-30 06:11:23 +0000100 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
101
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000102 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000103
Bob Wilsonb742def2009-12-18 20:14:40 +0000104 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000105 AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000106 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000107 AllocaInfo &Info);
108 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
109 const Type *MemOpType, bool isStore, AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000110 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000111 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
112 const Type *&IdxTy);
Chris Lattner39a1c042007-05-30 06:11:23 +0000113
Victor Hernandez7b929da2009-10-23 21:09:37 +0000114 void DoScalarReplacement(AllocaInst *AI,
115 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000116 void DeleteDeadInstructions();
Victor Hernandez7b929da2009-10-23 21:09:37 +0000117 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocaInst *Base);
Chris Lattnera1888942005-12-12 07:19:13 +0000118
Bob Wilsonb742def2009-12-18 20:14:40 +0000119 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
120 SmallVector<AllocaInst*, 32> &NewElts);
121 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
122 SmallVector<AllocaInst*, 32> &NewElts);
123 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
124 SmallVector<AllocaInst*, 32> &NewElts);
125 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000126 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000127 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000128 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000129 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000130 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000131 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000132
Chris Lattner31d80102010-04-15 21:59:20 +0000133 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000134 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000135}
136
Dan Gohman844731a2008-05-13 00:00:25 +0000137char SROA::ID = 0;
138static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
139
Brian Gaeked0fde302003-11-11 22:41:34 +0000140// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000141FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
142 return new SROA(Threshold);
143}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000144
145
Chris Lattner4cc576b2010-04-16 00:24:57 +0000146//===----------------------------------------------------------------------===//
147// Convert To Scalar Optimization.
148//===----------------------------------------------------------------------===//
149
150namespace {
151/// ConvertToScalarInfo - This struct is used by CanConvertToScalar
152class ConvertToScalarInfo {
153 /// AllocaSize - The size of the alloca being considered.
154 unsigned AllocaSize;
155 const TargetData &TD;
156
157 bool IsNotTrivial;
158 const Type *VectorTy;
159 bool HadAVector;
160
161public:
162 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
163 : AllocaSize(Size), TD(td) {
164 IsNotTrivial = false;
165 VectorTy = 0;
166 HadAVector = false;
167 }
168
169 AllocaInst *TryConvert(AllocaInst *AI) {
170 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
171 // out.
172 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
173 // FIXME: In the trivial case, just use mem2reg.
174 return 0;
175
176 // If we were able to find a vector type that can handle this with
177 // insert/extract elements, and if there was at least one use that had
178 // a vector type, promote this to a vector. We don't want to promote
179 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
180 // we just get a lot of insert/extracts. If at least one vector is
181 // involved, then we probably really do have a union of vector/array.
182 const Type *NewTy;
183 if (VectorTy && VectorTy->isVectorTy() && HadAVector) {
184 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
185 << *VectorTy << '\n');
186 NewTy = VectorTy; // Use the vector type.
187 } else {
188 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
189 // Create and insert the integer alloca.
190 NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
191 }
192 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
193 ConvertUsesToScalar(AI, NewAI, 0);
194 return NewAI;
195 }
196
197private:
198 bool CanConvertToScalar(Value *V, uint64_t Offset);
199 void MergeInType(const Type *In, uint64_t Offset);
200 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
201
202 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
203 uint64_t Offset, IRBuilder<> &Builder);
204 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
205 uint64_t Offset, IRBuilder<> &Builder);
206};
207} // end anonymous namespace.
208
209/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
210/// the offset specified by Offset (which is specified in bytes).
211///
212/// There are two cases we handle here:
213/// 1) A union of vector types of the same size and potentially its elements.
214/// Here we turn element accesses into insert/extract element operations.
215/// This promotes a <4 x float> with a store of float to the third element
216/// into a <4 x float> that uses insert element.
217/// 2) A fully general blob of memory, which we turn into some (potentially
218/// large) integer type with extract and insert operations where the loads
219/// and stores would mutate the memory.
220void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
221 // Remember if we saw a vector type.
222 HadAVector |= In->isVectorTy();
223
224 if (VectorTy && VectorTy->isVoidTy())
225 return;
226
227 // If this could be contributing to a vector, analyze it.
228
229 // If the In type is a vector that is the same size as the alloca, see if it
230 // matches the existing VecTy.
231 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
232 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
233 // If we're storing/loading a vector of the right size, allow it as a
234 // vector. If this the first vector we see, remember the type so that
235 // we know the element size.
236 if (VectorTy == 0)
237 VectorTy = VInTy;
238 return;
239 }
240 } else if (In->isFloatTy() || In->isDoubleTy() ||
241 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
242 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
243 // If we're accessing something that could be an element of a vector, see
244 // if the implied vector agrees with what we already have and if Offset is
245 // compatible with it.
246 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
247 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
248 (VectorTy == 0 ||
249 cast<VectorType>(VectorTy)->getElementType()
250 ->getPrimitiveSizeInBits()/8 == EltSize)) {
251 if (VectorTy == 0)
252 VectorTy = VectorType::get(In, AllocaSize/EltSize);
253 return;
254 }
255 }
256
257 // Otherwise, we have a case that we can't handle with an optimized vector
258 // form. We can still turn this into a large integer.
259 VectorTy = Type::getVoidTy(In->getContext());
260}
261
262/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
263/// its accesses to a single vector type, return true and set VecTy to
264/// the new type. If we could convert the alloca into a single promotable
265/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
266/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
267/// is the current offset from the base of the alloca being analyzed.
268///
269/// If we see at least one access to the value that is as a vector type, set the
270/// SawVec flag.
271bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
272 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
273 Instruction *User = cast<Instruction>(*UI);
274
275 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
276 // Don't break volatile loads.
277 if (LI->isVolatile())
278 return false;
279 MergeInType(LI->getType(), Offset);
280 continue;
281 }
282
283 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
284 // Storing the pointer, not into the value?
285 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
286 MergeInType(SI->getOperand(0)->getType(), Offset);
287 continue;
288 }
289
290 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
291 if (!CanConvertToScalar(BCI, Offset))
292 return false;
293 IsNotTrivial = true;
294 continue;
295 }
296
297 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
298 // If this is a GEP with a variable indices, we can't handle it.
299 if (!GEP->hasAllConstantIndices())
300 return false;
301
302 // Compute the offset that this GEP adds to the pointer.
303 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
304 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
305 &Indices[0], Indices.size());
306 // See if all uses can be converted.
307 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
308 return false;
309 IsNotTrivial = true;
310 continue;
311 }
312
313 // If this is a constant sized memset of a constant value (e.g. 0) we can
314 // handle it.
315 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
316 // Store of constant value and constant size.
317 if (isa<ConstantInt>(MSI->getValue()) &&
318 isa<ConstantInt>(MSI->getLength())) {
319 IsNotTrivial = true;
320 continue;
321 }
322 }
323
324 // If this is a memcpy or memmove into or out of the whole allocation, we
325 // can handle it like a load or store of the scalar type.
326 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
327 if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
328 if (Len->getZExtValue() == AllocaSize && Offset == 0) {
329 IsNotTrivial = true;
330 continue;
331 }
332 }
333
334 // Otherwise, we cannot handle this!
335 return false;
336 }
337
338 return true;
339}
340
341/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
342/// directly. This happens when we are converting an "integer union" to a
343/// single integer scalar, or when we are converting a "vector union" to a
344/// vector with insert/extractelement instructions.
345///
346/// Offset is an offset from the original alloca, in bits that need to be
347/// shifted to the right. By the end of this, there should be no uses of Ptr.
348void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
349 uint64_t Offset) {
350 while (!Ptr->use_empty()) {
351 Instruction *User = cast<Instruction>(Ptr->use_back());
352
353 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
354 ConvertUsesToScalar(CI, NewAI, Offset);
355 CI->eraseFromParent();
356 continue;
357 }
358
359 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
360 // Compute the offset that this GEP adds to the pointer.
361 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
362 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
363 &Indices[0], Indices.size());
364 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
365 GEP->eraseFromParent();
366 continue;
367 }
368
369 IRBuilder<> Builder(User->getParent(), User);
370
371 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
372 // The load is a bit extract from NewAI shifted right by Offset bits.
373 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
374 Value *NewLoadVal
375 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
376 LI->replaceAllUsesWith(NewLoadVal);
377 LI->eraseFromParent();
378 continue;
379 }
380
381 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
382 assert(SI->getOperand(0) != Ptr && "Consistency error!");
383 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
384 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
385 Builder);
386 Builder.CreateStore(New, NewAI);
387 SI->eraseFromParent();
388
389 // If the load we just inserted is now dead, then the inserted store
390 // overwrote the entire thing.
391 if (Old->use_empty())
392 Old->eraseFromParent();
393 continue;
394 }
395
396 // If this is a constant sized memset of a constant value (e.g. 0) we can
397 // transform it into a store of the expanded constant value.
398 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
399 assert(MSI->getRawDest() == Ptr && "Consistency error!");
400 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
401 if (NumBytes != 0) {
402 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
403
404 // Compute the value replicated the right number of times.
405 APInt APVal(NumBytes*8, Val);
406
407 // Splat the value if non-zero.
408 if (Val)
409 for (unsigned i = 1; i != NumBytes; ++i)
410 APVal |= APVal << 8;
411
412 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
413 Value *New = ConvertScalar_InsertValue(
414 ConstantInt::get(User->getContext(), APVal),
415 Old, Offset, Builder);
416 Builder.CreateStore(New, NewAI);
417
418 // If the load we just inserted is now dead, then the memset overwrote
419 // the entire thing.
420 if (Old->use_empty())
421 Old->eraseFromParent();
422 }
423 MSI->eraseFromParent();
424 continue;
425 }
426
427 // If this is a memcpy or memmove into or out of the whole allocation, we
428 // can handle it like a load or store of the scalar type.
429 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
430 assert(Offset == 0 && "must be store to start of alloca");
431
432 // If the source and destination are both to the same alloca, then this is
433 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
434 // as appropriate.
435 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject(0));
436
437 if (MTI->getSource()->getUnderlyingObject(0) != OrigAI) {
438 // Dest must be OrigAI, change this to be a load from the original
439 // pointer (bitcasted), then a store to our new alloca.
440 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
441 Value *SrcPtr = MTI->getSource();
442 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
443
444 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
445 SrcVal->setAlignment(MTI->getAlignment());
446 Builder.CreateStore(SrcVal, NewAI);
447 } else if (MTI->getDest()->getUnderlyingObject(0) != OrigAI) {
448 // Src must be OrigAI, change this to be a load from NewAI then a store
449 // through the original dest pointer (bitcasted).
450 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
451 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
452
453 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
454 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
455 NewStore->setAlignment(MTI->getAlignment());
456 } else {
457 // Noop transfer. Src == Dst
458 }
459
460 MTI->eraseFromParent();
461 continue;
462 }
463
464 llvm_unreachable("Unsupported operation!");
465 }
466}
467
468/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
469/// or vector value FromVal, extracting the bits from the offset specified by
470/// Offset. This returns the value, which is of type ToType.
471///
472/// This happens when we are converting an "integer union" to a single
473/// integer scalar, or when we are converting a "vector union" to a vector with
474/// insert/extractelement instructions.
475///
476/// Offset is an offset from the original alloca, in bits that need to be
477/// shifted to the right.
478Value *ConvertToScalarInfo::
479ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
480 uint64_t Offset, IRBuilder<> &Builder) {
481 // If the load is of the whole new alloca, no conversion is needed.
482 if (FromVal->getType() == ToType && Offset == 0)
483 return FromVal;
484
485 // If the result alloca is a vector type, this is either an element
486 // access or a bitcast to another vector type of the same size.
487 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
488 if (ToType->isVectorTy())
489 return Builder.CreateBitCast(FromVal, ToType, "tmp");
490
491 // Otherwise it must be an element access.
492 unsigned Elt = 0;
493 if (Offset) {
494 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
495 Elt = Offset/EltSize;
496 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
497 }
498 // Return the element extracted out of it.
499 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
500 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
501 if (V->getType() != ToType)
502 V = Builder.CreateBitCast(V, ToType, "tmp");
503 return V;
504 }
505
506 // If ToType is a first class aggregate, extract out each of the pieces and
507 // use insertvalue's to form the FCA.
508 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
509 const StructLayout &Layout = *TD.getStructLayout(ST);
510 Value *Res = UndefValue::get(ST);
511 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
512 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
513 Offset+Layout.getElementOffsetInBits(i),
514 Builder);
515 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
516 }
517 return Res;
518 }
519
520 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
521 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
522 Value *Res = UndefValue::get(AT);
523 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
524 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
525 Offset+i*EltSize, Builder);
526 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
527 }
528 return Res;
529 }
530
531 // Otherwise, this must be a union that was converted to an integer value.
532 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
533
534 // If this is a big-endian system and the load is narrower than the
535 // full alloca type, we need to do a shift to get the right bits.
536 int ShAmt = 0;
537 if (TD.isBigEndian()) {
538 // On big-endian machines, the lowest bit is stored at the bit offset
539 // from the pointer given by getTypeStoreSizeInBits. This matters for
540 // integers with a bitwidth that is not a multiple of 8.
541 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
542 TD.getTypeStoreSizeInBits(ToType) - Offset;
543 } else {
544 ShAmt = Offset;
545 }
546
547 // Note: we support negative bitwidths (with shl) which are not defined.
548 // We do this to support (f.e.) loads off the end of a structure where
549 // only some bits are used.
550 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
551 FromVal = Builder.CreateLShr(FromVal,
552 ConstantInt::get(FromVal->getType(),
553 ShAmt), "tmp");
554 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
555 FromVal = Builder.CreateShl(FromVal,
556 ConstantInt::get(FromVal->getType(),
557 -ShAmt), "tmp");
558
559 // Finally, unconditionally truncate the integer to the right width.
560 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
561 if (LIBitWidth < NTy->getBitWidth())
562 FromVal =
563 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
564 LIBitWidth), "tmp");
565 else if (LIBitWidth > NTy->getBitWidth())
566 FromVal =
567 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
568 LIBitWidth), "tmp");
569
570 // If the result is an integer, this is a trunc or bitcast.
571 if (ToType->isIntegerTy()) {
572 // Should be done.
573 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
574 // Just do a bitcast, we know the sizes match up.
575 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
576 } else {
577 // Otherwise must be a pointer.
578 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
579 }
580 assert(FromVal->getType() == ToType && "Didn't convert right?");
581 return FromVal;
582}
583
584/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
585/// or vector value "Old" at the offset specified by Offset.
586///
587/// This happens when we are converting an "integer union" to a
588/// single integer scalar, or when we are converting a "vector union" to a
589/// vector with insert/extractelement instructions.
590///
591/// Offset is an offset from the original alloca, in bits that need to be
592/// shifted to the right.
593Value *ConvertToScalarInfo::
594ConvertScalar_InsertValue(Value *SV, Value *Old,
595 uint64_t Offset, IRBuilder<> &Builder) {
596 // Convert the stored type to the actual type, shift it left to insert
597 // then 'or' into place.
598 const Type *AllocaType = Old->getType();
599 LLVMContext &Context = Old->getContext();
600
601 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
602 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
603 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
604
605 // Changing the whole vector with memset or with an access of a different
606 // vector type?
607 if (ValSize == VecSize)
608 return Builder.CreateBitCast(SV, AllocaType, "tmp");
609
610 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
611
612 // Must be an element insertion.
613 unsigned Elt = Offset/EltSize;
614
615 if (SV->getType() != VTy->getElementType())
616 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
617
618 SV = Builder.CreateInsertElement(Old, SV,
619 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
620 "tmp");
621 return SV;
622 }
623
624 // If SV is a first-class aggregate value, insert each value recursively.
625 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
626 const StructLayout &Layout = *TD.getStructLayout(ST);
627 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
628 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
629 Old = ConvertScalar_InsertValue(Elt, Old,
630 Offset+Layout.getElementOffsetInBits(i),
631 Builder);
632 }
633 return Old;
634 }
635
636 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
637 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
638 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
639 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
640 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
641 }
642 return Old;
643 }
644
645 // If SV is a float, convert it to the appropriate integer type.
646 // If it is a pointer, do the same.
647 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
648 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
649 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
650 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
651 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
652 SV = Builder.CreateBitCast(SV,
653 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
654 else if (SV->getType()->isPointerTy())
655 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
656
657 // Zero extend or truncate the value if needed.
658 if (SV->getType() != AllocaType) {
659 if (SV->getType()->getPrimitiveSizeInBits() <
660 AllocaType->getPrimitiveSizeInBits())
661 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
662 else {
663 // Truncation may be needed if storing more than the alloca can hold
664 // (undefined behavior).
665 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
666 SrcWidth = DestWidth;
667 SrcStoreWidth = DestStoreWidth;
668 }
669 }
670
671 // If this is a big-endian system and the store is narrower than the
672 // full alloca type, we need to do a shift to get the right bits.
673 int ShAmt = 0;
674 if (TD.isBigEndian()) {
675 // On big-endian machines, the lowest bit is stored at the bit offset
676 // from the pointer given by getTypeStoreSizeInBits. This matters for
677 // integers with a bitwidth that is not a multiple of 8.
678 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
679 } else {
680 ShAmt = Offset;
681 }
682
683 // Note: we support negative bitwidths (with shr) which are not defined.
684 // We do this to support (f.e.) stores off the end of a structure where
685 // only some bits in the structure are set.
686 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
687 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
688 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
689 ShAmt), "tmp");
690 Mask <<= ShAmt;
691 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
692 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
693 -ShAmt), "tmp");
694 Mask = Mask.lshr(-ShAmt);
695 }
696
697 // Mask out the bits we are about to insert from the old value, and or
698 // in the new bits.
699 if (SrcWidth != DestWidth) {
700 assert(DestWidth > SrcWidth);
701 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
702 SV = Builder.CreateOr(Old, SV, "ins");
703 }
704 return SV;
705}
706
707
708//===----------------------------------------------------------------------===//
709// SRoA Driver
710//===----------------------------------------------------------------------===//
711
712
Chris Lattnered7b41e2003-05-27 15:45:27 +0000713bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000714 TD = getAnalysisIfAvailable<TargetData>();
715
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000716 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000717
718 // FIXME: ScalarRepl currently depends on TargetData more than it
719 // theoretically needs to. It should be refactored in order to support
720 // target-independent IR. Until this is done, just skip the actual
721 // scalar-replacement portion of this pass.
722 if (!TD) return Changed;
723
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000724 while (1) {
725 bool LocalChange = performScalarRepl(F);
726 if (!LocalChange) break; // No need to repromote if no scalarrepl
727 Changed = true;
728 LocalChange = performPromotion(F);
729 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
730 }
Chris Lattner38aec322003-09-11 16:45:55 +0000731
732 return Changed;
733}
734
735
736bool SROA::performPromotion(Function &F) {
737 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000738 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000739 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000740
Chris Lattner02a3be02003-09-20 14:39:18 +0000741 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000742
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000743 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000744
Chris Lattner38aec322003-09-11 16:45:55 +0000745 while (1) {
746 Allocas.clear();
747
748 // Find allocas that are safe to promote, by looking at all instructions in
749 // the entry node
750 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
751 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000752 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000753 Allocas.push_back(AI);
754
755 if (Allocas.empty()) break;
756
Nick Lewyckyce2c51b2009-11-23 03:50:44 +0000757 PromoteMemToReg(Allocas, DT, DF);
Chris Lattner38aec322003-09-11 16:45:55 +0000758 NumPromoted += Allocas.size();
759 Changed = true;
760 }
761
762 return Changed;
763}
764
Chris Lattner4cc576b2010-04-16 00:24:57 +0000765
Bob Wilson3992feb2010-02-03 17:23:56 +0000766/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
767/// SROA. It must be a struct or array type with a small number of elements.
768static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
769 const Type *T = AI->getAllocatedType();
770 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +0000771 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +0000772 return ST->getNumElements() <= 32;
773 // Arrays are much less likely to be safe for SROA; only consider
774 // them if they are very small.
775 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
776 return AT->getNumElements() <= 8;
777 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +0000778}
779
Chris Lattnerc4472072010-04-15 23:50:26 +0000780
Chris Lattner38aec322003-09-11 16:45:55 +0000781// performScalarRepl - This algorithm is a simple worklist driven algorithm,
782// which runs on all of the malloc/alloca instructions in the function, removing
783// them if they are only used by getelementptr instructions.
784//
785bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000786 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000787
Chris Lattner31d80102010-04-15 21:59:20 +0000788 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +0000789 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000790 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000791 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000792 WorkList.push_back(A);
793
794 // Process the worklist
795 bool Changed = false;
796 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000797 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000798 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000799
Chris Lattneradd2bd72006-12-22 23:14:42 +0000800 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
801 // with unused elements.
802 if (AI->use_empty()) {
803 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +0000804 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +0000805 continue;
806 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000807
808 // If this alloca is impossible for us to promote, reject it early.
809 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
810 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000811
812 // Check to see if this allocation is only modified by a memcpy/memmove from
813 // a constant global. If this is the case, we can change all users to use
814 // the constant global instead. This is commonly produced by the CFE by
815 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
816 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +0000817 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +0000818 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
819 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +0000820 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +0000821 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000822 TheCopy->eraseFromParent(); // Don't mutate the global.
823 AI->eraseFromParent();
824 ++NumGlobals;
825 Changed = true;
826 continue;
827 }
Chris Lattner15c82772009-02-02 20:44:45 +0000828
Chris Lattner7809ecd2009-02-03 01:30:09 +0000829 // Check to see if we can perform the core SROA transformation. We cannot
830 // transform the allocation instruction if it is an array allocation
831 // (allocations OF arrays are ok though), and an allocation of a scalar
832 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000833 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000834
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000835 // Do not promote [0 x %struct].
836 if (AllocaSize == 0) continue;
Chris Lattner31d80102010-04-15 21:59:20 +0000837
838 // Do not promote any struct whose size is too big.
839 if (AllocaSize > SRThreshold) continue;
840
Bob Wilson3992feb2010-02-03 17:23:56 +0000841 // If the alloca looks like a good candidate for scalar replacement, and if
842 // all its users can be transformed, then split up the aggregate into its
843 // separate elements.
844 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
845 DoScalarReplacement(AI, WorkList);
846 Changed = true;
847 continue;
848 }
849
Chris Lattner6e733d32009-01-28 20:16:43 +0000850 // If we can turn this aggregate value (potentially with casts) into a
851 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000852 // IsNotTrivial tracks whether this is something that mem2reg could have
853 // promoted itself. If so, we don't want to transform it needlessly. Note
854 // that we can't just check based on the type: the alloca may be of an i32
855 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +0000856 if (AllocaInst *NewAI =
857 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000858 NewAI->takeName(AI);
859 AI->eraseFromParent();
860 ++NumConverted;
861 Changed = true;
862 continue;
Chris Lattner593375d2010-04-16 00:20:00 +0000863 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000864
Chris Lattner7809ecd2009-02-03 01:30:09 +0000865 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000866 }
867
868 return Changed;
869}
Chris Lattner5e062a12003-05-30 04:15:41 +0000870
Chris Lattnera10b29b2007-04-25 05:02:56 +0000871/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
872/// predicate, do SROA now.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000873void SROA::DoScalarReplacement(AllocaInst *AI,
874 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +0000875 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +0000876 SmallVector<AllocaInst*, 32> ElementAllocas;
877 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
878 ElementAllocas.reserve(ST->getNumContainedTypes());
879 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000880 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +0000881 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000882 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000883 ElementAllocas.push_back(NA);
884 WorkList.push_back(NA); // Add to worklist for recursive processing
885 }
886 } else {
887 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
888 ElementAllocas.reserve(AT->getNumElements());
889 const Type *ElTy = AT->getElementType();
890 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000891 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000892 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000893 ElementAllocas.push_back(NA);
894 WorkList.push_back(NA); // Add to worklist for recursive processing
895 }
896 }
897
Bob Wilsonb742def2009-12-18 20:14:40 +0000898 // Now that we have created the new alloca instructions, rewrite all the
899 // uses of the old alloca.
900 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +0000901
Bob Wilsonb742def2009-12-18 20:14:40 +0000902 // Now erase any instructions that were made dead while rewriting the alloca.
903 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +0000904 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +0000905
Chris Lattnera10b29b2007-04-25 05:02:56 +0000906 NumReplaced++;
907}
Chris Lattnera59adc42009-12-14 05:11:02 +0000908
Bob Wilsonb742def2009-12-18 20:14:40 +0000909/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
910/// recursively including all their operands that become trivially dead.
911void SROA::DeleteDeadInstructions() {
912 while (!DeadInsts.empty()) {
913 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +0000914
Bob Wilsonb742def2009-12-18 20:14:40 +0000915 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
916 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
917 // Zero out the operand and see if it becomes trivially dead.
918 // (But, don't add allocas to the dead instruction list -- they are
919 // already on the worklist and will be deleted separately.)
920 *OI = 0;
921 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
922 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +0000923 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000924
925 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +0000926 }
Chris Lattnera59adc42009-12-14 05:11:02 +0000927}
Bob Wilsonb742def2009-12-18 20:14:40 +0000928
Bob Wilsonb742def2009-12-18 20:14:40 +0000929/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
930/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000931/// the Info parameter. Offset indicates the position within AI that is
932/// referenced by this instruction.
Bob Wilsonb742def2009-12-18 20:14:40 +0000933void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000934 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000935 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
936 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000937
Bob Wilsonb742def2009-12-18 20:14:40 +0000938 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000939 isSafeForScalarRepl(BC, AI, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000940 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000941 uint64_t GEPOffset = Offset;
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000942 isSafeGEP(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000943 if (!Info.isUnsafe)
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000944 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
Gabor Greif2ff961f2010-04-15 20:51:13 +0000945 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000946 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
947 if (Length)
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000948 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
Gabor Greif2ff961f2010-04-15 20:51:13 +0000949 UI.getOperandNo() == 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000950 else
951 MarkUnsafe(Info);
952 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
953 if (!LI->isVolatile()) {
954 const Type *LIType = LI->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000955 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
Bob Wilsonb742def2009-12-18 20:14:40 +0000956 LIType, false, Info);
957 } else
958 MarkUnsafe(Info);
959 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
960 // Store is ok if storing INTO the pointer, not storing the pointer
961 if (!SI->isVolatile() && SI->getOperand(0) != I) {
962 const Type *SIType = SI->getOperand(0)->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000963 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
Bob Wilsonb742def2009-12-18 20:14:40 +0000964 SIType, true, Info);
965 } else
966 MarkUnsafe(Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000967 } else {
968 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
969 MarkUnsafe(Info);
970 }
971 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000972 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000973}
Bob Wilson39c88a62009-12-17 18:34:24 +0000974
Bob Wilsonb742def2009-12-18 20:14:40 +0000975/// isSafeGEP - Check if a GEP instruction can be handled for scalar
976/// replacement. It is safe when all the indices are constant, in-bounds
977/// references, and when the resulting offset corresponds to an element within
978/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000979/// return, Offset is adjusted as specified by the GEP indices.
Bob Wilsonb742def2009-12-18 20:14:40 +0000980void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000981 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000982 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
983 if (GEPIt == E)
984 return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000985
Chris Lattner88e6dc82008-08-23 05:21:06 +0000986 // Walk through the GEP type indices, checking the types that this indexes
987 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +0000988 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +0000989 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +0000990 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +0000991 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000992
Bob Wilsonb742def2009-12-18 20:14:40 +0000993 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
994 if (!IdxVal)
995 return MarkUnsafe(Info);
Chris Lattner88e6dc82008-08-23 05:21:06 +0000996 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000997
Bob Wilsonf27a4cd2009-12-22 06:57:14 +0000998 // Compute the offset due to this GEP and check if the alloca has a
999 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001000 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1001 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1002 &Indices[0], Indices.size());
Bob Wilsonb742def2009-12-18 20:14:40 +00001003 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
1004 MarkUnsafe(Info);
Chris Lattner5e062a12003-05-30 04:15:41 +00001005}
1006
Bob Wilsonb742def2009-12-18 20:14:40 +00001007/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1008/// alloca or has an offset and size that corresponds to a component element
1009/// within it. The offset checked here may have been formed from a GEP with a
1010/// pointer bitcasted to a different type.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001011void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001012 const Type *MemOpType, bool isStore,
1013 AllocaInfo &Info) {
1014 // Check if this is a load/store of the entire alloca.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001015 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001016 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
1017 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
1018 // (which are essentially the same as the MemIntrinsics, especially with
1019 // regard to copying padding between elements), or references using the
1020 // aggregate type of the alloca.
Duncan Sands1df98592010-02-16 11:11:14 +00001021 if (!MemOpType || MemOpType->isIntegerTy() || UsesAggregateType) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001022 if (!UsesAggregateType) {
1023 if (isStore)
1024 Info.isMemCpyDst = true;
1025 else
1026 Info.isMemCpySrc = true;
1027 }
1028 return;
1029 }
1030 }
1031 // Check if the offset/size correspond to a component within the alloca type.
1032 const Type *T = AI->getAllocatedType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001033 if (TypeHasComponent(T, Offset, MemSize))
Bob Wilsonb742def2009-12-18 20:14:40 +00001034 return;
1035
1036 return MarkUnsafe(Info);
1037}
1038
1039/// TypeHasComponent - Return true if T has a component type with the
1040/// specified offset and size. If Size is zero, do not check the size.
1041bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1042 const Type *EltTy;
1043 uint64_t EltSize;
1044 if (const StructType *ST = dyn_cast<StructType>(T)) {
1045 const StructLayout *Layout = TD->getStructLayout(ST);
1046 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1047 EltTy = ST->getContainedType(EltIdx);
1048 EltSize = TD->getTypeAllocSize(EltTy);
1049 Offset -= Layout->getElementOffset(EltIdx);
1050 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1051 EltTy = AT->getElementType();
1052 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001053 if (Offset >= AT->getNumElements() * EltSize)
1054 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001055 Offset %= EltSize;
1056 } else {
1057 return false;
1058 }
1059 if (Offset == 0 && (Size == 0 || EltSize == Size))
1060 return true;
1061 // Check if the component spans multiple elements.
1062 if (Offset + Size > EltSize)
1063 return false;
1064 return TypeHasComponent(EltTy, Offset, Size);
1065}
1066
1067/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1068/// the instruction I, which references it, to use the separate elements.
1069/// Offset indicates the position within AI that is referenced by this
1070/// instruction.
1071void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1072 SmallVector<AllocaInst*, 32> &NewElts) {
1073 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1074 Instruction *User = cast<Instruction>(*UI);
1075
1076 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1077 RewriteBitCast(BC, AI, Offset, NewElts);
1078 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1079 RewriteGEP(GEPI, AI, Offset, NewElts);
1080 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1081 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1082 uint64_t MemSize = Length->getZExtValue();
1083 if (Offset == 0 &&
1084 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1085 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001086 // Otherwise the intrinsic can only touch a single element and the
1087 // address operand will be updated, so nothing else needs to be done.
Bob Wilsonb742def2009-12-18 20:14:40 +00001088 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1089 const Type *LIType = LI->getType();
1090 if (LIType == AI->getAllocatedType()) {
1091 // Replace:
1092 // %res = load { i32, i32 }* %alloc
1093 // with:
1094 // %load.0 = load i32* %alloc.0
1095 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1096 // %load.1 = load i32* %alloc.1
1097 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1098 // (Also works for arrays instead of structs)
1099 Value *Insert = UndefValue::get(LIType);
1100 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1101 Value *Load = new LoadInst(NewElts[i], "load", LI);
1102 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1103 }
1104 LI->replaceAllUsesWith(Insert);
1105 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001106 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001107 TD->getTypeAllocSize(LIType) ==
1108 TD->getTypeAllocSize(AI->getAllocatedType())) {
1109 // If this is a load of the entire alloca to an integer, rewrite it.
1110 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1111 }
1112 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1113 Value *Val = SI->getOperand(0);
1114 const Type *SIType = Val->getType();
1115 if (SIType == AI->getAllocatedType()) {
1116 // Replace:
1117 // store { i32, i32 } %val, { i32, i32 }* %alloc
1118 // with:
1119 // %val.0 = extractvalue { i32, i32 } %val, 0
1120 // store i32 %val.0, i32* %alloc.0
1121 // %val.1 = extractvalue { i32, i32 } %val, 1
1122 // store i32 %val.1, i32* %alloc.1
1123 // (Also works for arrays instead of structs)
1124 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1125 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1126 new StoreInst(Extract, NewElts[i], SI);
1127 }
1128 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001129 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001130 TD->getTypeAllocSize(SIType) ==
1131 TD->getTypeAllocSize(AI->getAllocatedType())) {
1132 // If this is a store of the entire alloca from an integer, rewrite it.
1133 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1134 }
1135 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001136 }
1137}
1138
Bob Wilsonb742def2009-12-18 20:14:40 +00001139/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1140/// and recursively continue updating all of its uses.
1141void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1142 SmallVector<AllocaInst*, 32> &NewElts) {
1143 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1144 if (BC->getOperand(0) != AI)
1145 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001146
Bob Wilsonb742def2009-12-18 20:14:40 +00001147 // The bitcast references the original alloca. Replace its uses with
1148 // references to the first new element alloca.
1149 Instruction *Val = NewElts[0];
1150 if (Val->getType() != BC->getDestTy()) {
1151 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1152 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001153 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001154 BC->replaceAllUsesWith(Val);
1155 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001156}
1157
Bob Wilsonb742def2009-12-18 20:14:40 +00001158/// FindElementAndOffset - Return the index of the element containing Offset
1159/// within the specified type, which must be either a struct or an array.
1160/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001161/// element. IdxTy is set to the type of the index result to be used in a
1162/// GEP instruction.
1163uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1164 const Type *&IdxTy) {
1165 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001166 if (const StructType *ST = dyn_cast<StructType>(T)) {
1167 const StructLayout *Layout = TD->getStructLayout(ST);
1168 Idx = Layout->getElementContainingOffset(Offset);
1169 T = ST->getContainedType(Idx);
1170 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001171 IdxTy = Type::getInt32Ty(T->getContext());
1172 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001173 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001174 const ArrayType *AT = cast<ArrayType>(T);
1175 T = AT->getElementType();
1176 uint64_t EltSize = TD->getTypeAllocSize(T);
1177 Idx = Offset / EltSize;
1178 Offset -= Idx * EltSize;
1179 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001180 return Idx;
1181}
1182
1183/// RewriteGEP - Check if this GEP instruction moves the pointer across
1184/// elements of the alloca that are being split apart, and if so, rewrite
1185/// the GEP to be relative to the new element.
1186void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1187 SmallVector<AllocaInst*, 32> &NewElts) {
1188 uint64_t OldOffset = Offset;
1189 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1190 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1191 &Indices[0], Indices.size());
1192
1193 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1194
1195 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00001196 const Type *IdxTy;
1197 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001198 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001199 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001200
1201 T = AI->getAllocatedType();
1202 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001203 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001204
1205 // If this GEP does not move the pointer across elements of the alloca
1206 // being split, then it does not needs to be rewritten.
1207 if (Idx == OldIdx)
1208 return;
1209
1210 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1211 SmallVector<Value*, 8> NewArgs;
1212 NewArgs.push_back(Constant::getNullValue(i32Ty));
1213 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001214 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1215 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00001216 }
1217 Instruction *Val = NewElts[Idx];
1218 if (NewArgs.size() > 1) {
1219 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1220 NewArgs.end(), "", GEPI);
1221 Val->takeName(GEPI);
1222 }
1223 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001224 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001225 GEPI->replaceAllUsesWith(Val);
1226 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001227}
1228
1229/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1230/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00001231void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001232 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00001233 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001234 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00001235 // appropriate type. The "Other" pointer is the pointer that goes to memory
1236 // that doesn't have anything to do with the alloca that we are promoting. For
1237 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00001238 Value *OtherPtr = 0;
Owen Andersone922c022009-07-22 00:24:57 +00001239 LLVMContext &Context = MI->getContext();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001240 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00001241 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00001242 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00001243 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001244 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00001245 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00001246 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001247 }
1248 }
Bob Wilson78c50b82009-12-08 18:22:03 +00001249
Chris Lattnerd93afec2009-01-07 07:18:45 +00001250 // If there is an other pointer, we want to convert it to the same pointer
1251 // type as AI has, so we can GEP through it safely.
1252 if (OtherPtr) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001253
1254 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
1255 // optimization, but it's also required to detect the corner case where
1256 // both pointer operands are referencing the same memory, and where
1257 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
1258 // function is only called for mem intrinsics that access the whole
1259 // aggregate, so non-zero GEPs are not an issue here.)
1260 while (1) {
1261 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr)) {
1262 OtherPtr = BC->getOperand(0);
1263 continue;
1264 }
1265 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr)) {
1266 // All zero GEPs are effectively bitcasts.
1267 if (GEP->hasAllZeroIndices()) {
1268 OtherPtr = GEP->getOperand(0);
1269 continue;
1270 }
1271 }
1272 break;
1273 }
Bob Wilsona756b1d2010-01-19 04:32:48 +00001274 // Copying the alloca to itself is a no-op: just delete it.
1275 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1276 // This code will run twice for a no-op memcpy -- once for each operand.
1277 // Put only one reference to MI on the DeadInsts list.
1278 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1279 E = DeadInsts.end(); I != E; ++I)
1280 if (*I == MI) return;
1281 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001282 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00001283 }
Chris Lattner372dda82007-03-05 07:52:57 +00001284
Chris Lattnerd93afec2009-01-07 07:18:45 +00001285 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
1286 if (BCE->getOpcode() == Instruction::BitCast)
1287 OtherPtr = BCE->getOperand(0);
1288
1289 // If the pointer is not the right type, insert a bitcast to the right
1290 // type.
1291 if (OtherPtr->getType() != AI->getType())
1292 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
1293 MI);
1294 }
1295
1296 // Process each element of the aggregate.
Gabor Greif2ff961f2010-04-15 20:51:13 +00001297 Value *TheFn = MI->getCalledValue();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001298 const Type *BytePtrTy = MI->getRawDest()->getType();
Bob Wilsonb742def2009-12-18 20:14:40 +00001299 bool SROADest = MI->getRawDest() == Inst;
Chris Lattnerd93afec2009-01-07 07:18:45 +00001300
Owen Anderson1d0be152009-08-13 21:58:54 +00001301 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00001302
1303 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1304 // If this is a memcpy/memmove, emit a GEP of the other element address.
1305 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001306 unsigned OtherEltAlign = MemAlignment;
1307
Bob Wilsona756b1d2010-01-19 04:32:48 +00001308 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001309 Value *Idx[2] = { Zero,
1310 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00001311 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001312 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00001313 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00001314 uint64_t EltOffset;
1315 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
1316 if (const StructType *ST =
1317 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
1318 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1319 } else {
1320 const Type *EltTy =
1321 cast<SequentialType>(OtherPtr->getType())->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001322 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001323 }
1324
1325 // The alignment of the other pointer is the guaranteed alignment of the
1326 // element, which is affected by both the known alignment of the whole
1327 // mem intrinsic and the alignment of the element. If the alignment of
1328 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1329 // known alignment is just 4 bytes.
1330 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00001331 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001332
1333 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00001334 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001335
1336 // If we got down to a scalar, insert a load or store as appropriate.
1337 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001338 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001339 if (SROADest) {
1340 // From Other to Alloca.
1341 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1342 new StoreInst(Elt, EltPtr, MI);
1343 } else {
1344 // From Alloca to Other.
1345 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1346 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1347 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001348 continue;
1349 }
1350 assert(isa<MemSetInst>(MI));
1351
1352 // If the stored element is zero (common case), just store a null
1353 // constant.
1354 Constant *StoreVal;
Gabor Greif2ff961f2010-04-15 20:51:13 +00001355 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001356 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001357 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00001358 } else {
1359 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00001360 const Type *ValTy = EltTy->getScalarType();
1361
Chris Lattnerd93afec2009-01-07 07:18:45 +00001362 // Construct an integer with the right value.
1363 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1364 APInt OneVal(EltSize, CI->getZExtValue());
1365 APInt TotalVal(OneVal);
1366 // Set each byte.
1367 for (unsigned i = 0; 8*i < EltSize; ++i) {
1368 TotalVal = TotalVal.shl(8);
1369 TotalVal |= OneVal;
1370 }
1371
1372 // Convert the integer value to the appropriate type.
Owen Andersoneed707b2009-07-24 23:12:02 +00001373 StoreVal = ConstantInt::get(Context, TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001374 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001375 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001376 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001377 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001378 assert(StoreVal->getType() == ValTy && "Type mismatch!");
1379
1380 // If the requested value was a vector constant, create it.
1381 if (EltTy != ValTy) {
1382 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1383 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +00001384 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001385 }
1386 }
1387 new StoreInst(StoreVal, EltPtr, MI);
1388 continue;
1389 }
1390 // Otherwise, if we're storing a byte variable, use a memset call for
1391 // this element.
1392 }
1393
1394 // Cast the element pointer to BytePtrTy.
1395 if (EltPtr->getType() != BytePtrTy)
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001396 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001397
1398 // Cast the other pointer (if we have one) to BytePtrTy.
Mon P Wang20adc9d2010-04-04 03:10:48 +00001399 if (OtherElt && OtherElt->getType() != BytePtrTy) {
1400 // Preserve address space of OtherElt
1401 const PointerType* OtherPTy = cast<PointerType>(OtherElt->getType());
1402 const PointerType* PTy = cast<PointerType>(BytePtrTy);
1403 if (OtherPTy->getElementType() != PTy->getElementType()) {
1404 Type *NewOtherPTy = PointerType::get(PTy->getElementType(),
1405 OtherPTy->getAddressSpace());
1406 OtherElt = new BitCastInst(OtherElt, NewOtherPTy,
1407 OtherElt->getNameStr(), MI);
1408 }
1409 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001410
Duncan Sands777d2302009-05-09 07:06:46 +00001411 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001412
1413 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001414 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001415 Value *Ops[] = {
1416 SROADest ? EltPtr : OtherElt, // Dest ptr
1417 SROADest ? OtherElt : EltPtr, // Src ptr
Gabor Greif2ff961f2010-04-15 20:51:13 +00001418 ConstantInt::get(MI->getOperand(2)->getType(), EltSize), // Size
Owen Anderson1d0be152009-08-13 21:58:54 +00001419 // Align
Mon P Wang20adc9d2010-04-04 03:10:48 +00001420 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign),
1421 MI->getVolatileCst()
Chris Lattnerd93afec2009-01-07 07:18:45 +00001422 };
Mon P Wang20adc9d2010-04-04 03:10:48 +00001423 // In case we fold the address space overloaded memcpy of A to B
1424 // with memcpy of B to C, change the function to be a memcpy of A to C.
1425 const Type *Tys[] = { Ops[0]->getType(), Ops[1]->getType(),
1426 Ops[2]->getType() };
1427 Module *M = MI->getParent()->getParent()->getParent();
1428 TheFn = Intrinsic::getDeclaration(M, MI->getIntrinsicID(), Tys, 3);
1429 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001430 } else {
1431 assert(isa<MemSetInst>(MI));
1432 Value *Ops[] = {
Gabor Greif2ff961f2010-04-15 20:51:13 +00001433 EltPtr, MI->getOperand(1), // Dest, Value,
1434 ConstantInt::get(MI->getOperand(2)->getType(), EltSize), // Size
Mon P Wang20adc9d2010-04-04 03:10:48 +00001435 Zero, // Align
1436 ConstantInt::get(Type::getInt1Ty(MI->getContext()), 0) // isVolatile
Chris Lattnerd93afec2009-01-07 07:18:45 +00001437 };
Mon P Wang20adc9d2010-04-04 03:10:48 +00001438 const Type *Tys[] = { Ops[0]->getType(), Ops[2]->getType() };
1439 Module *M = MI->getParent()->getParent()->getParent();
1440 TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys, 2);
1441 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001442 }
Chris Lattner372dda82007-03-05 07:52:57 +00001443 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001444 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00001445}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001446
Bob Wilson39fdd692009-12-04 21:57:37 +00001447/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001448/// overwrites the entire allocation. Extract out the pieces of the stored
1449/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001450void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001451 SmallVector<AllocaInst*, 32> &NewElts){
1452 // Extract each element out of the integer according to its structure offset
1453 // and store the element value to the individual alloca.
1454 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00001455 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001456 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001457
Eli Friedman41b33f42009-06-01 09:14:32 +00001458 // Handle tail padding by extending the operand
1459 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001460 SrcVal = new ZExtInst(SrcVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001461 IntegerType::get(SI->getContext(), AllocaSizeBits),
1462 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001463
David Greene504c7d82010-01-05 01:27:09 +00001464 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00001465 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001466
1467 // There are two forms here: AI could be an array or struct. Both cases
1468 // have different ways to compute the element offset.
1469 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1470 const StructLayout *Layout = TD->getStructLayout(EltSTy);
1471
1472 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1473 // Get the number of bits to shift SrcVal to get the value.
1474 const Type *FieldTy = EltSTy->getElementType(i);
1475 uint64_t Shift = Layout->getElementOffsetInBits(i);
1476
1477 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00001478 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001479
1480 Value *EltVal = SrcVal;
1481 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001482 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001483 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1484 "sroa.store.elt", SI);
1485 }
1486
1487 // Truncate down to an integer of the right size.
1488 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +00001489
1490 // Ignore zero sized fields like {}, they obviously contain no data.
1491 if (FieldSizeBits == 0) continue;
1492
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001493 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001494 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001495 IntegerType::get(SI->getContext(), FieldSizeBits),
1496 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001497 Value *DestField = NewElts[i];
1498 if (EltVal->getType() == FieldTy) {
1499 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00001500 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001501 // Bitcast to the right element type (for fp/vector values).
1502 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
1503 } else {
1504 // Otherwise, bitcast the dest pointer (for aggregates).
1505 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001506 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001507 "", SI);
1508 }
1509 new StoreInst(EltVal, DestField, SI);
1510 }
1511
1512 } else {
1513 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1514 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001515 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001516 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1517
1518 uint64_t Shift;
1519
1520 if (TD->isBigEndian())
1521 Shift = AllocaSizeBits-ElementOffset;
1522 else
1523 Shift = 0;
1524
1525 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00001526 // Ignore zero sized fields like {}, they obviously contain no data.
1527 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001528
1529 Value *EltVal = SrcVal;
1530 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001531 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001532 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1533 "sroa.store.elt", SI);
1534 }
1535
1536 // Truncate down to an integer of the right size.
1537 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001538 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001539 IntegerType::get(SI->getContext(),
1540 ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001541 Value *DestField = NewElts[i];
1542 if (EltVal->getType() == ArrayEltTy) {
1543 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001544 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001545 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001546 // Bitcast to the right element type (for fp/vector values).
1547 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1548 } else {
1549 // Otherwise, bitcast the dest pointer (for aggregates).
1550 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001551 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001552 "", SI);
1553 }
1554 new StoreInst(EltVal, DestField, SI);
1555
1556 if (TD->isBigEndian())
1557 Shift -= ElementOffset;
1558 else
1559 Shift += ElementOffset;
1560 }
1561 }
1562
Bob Wilsonb742def2009-12-18 20:14:40 +00001563 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001564}
1565
Bob Wilson39fdd692009-12-04 21:57:37 +00001566/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001567/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001568void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001569 SmallVector<AllocaInst*, 32> &NewElts) {
1570 // Extract each element out of the NewElts according to its structure offset
1571 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00001572 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001573 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001574
David Greene504c7d82010-01-05 01:27:09 +00001575 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00001576 << '\n');
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001577
1578 // There are two forms here: AI could be an array or struct. Both cases
1579 // have different ways to compute the element offset.
1580 const StructLayout *Layout = 0;
1581 uint64_t ArrayEltBitOffset = 0;
1582 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1583 Layout = TD->getStructLayout(EltSTy);
1584 } else {
1585 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001586 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001587 }
Owen Andersone922c022009-07-22 00:24:57 +00001588
Owen Andersone922c022009-07-22 00:24:57 +00001589 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001590 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001591
1592 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1593 // Load the value from the alloca. If the NewElt is an aggregate, cast
1594 // the pointer to an integer of the same size before doing the load.
1595 Value *SrcField = NewElts[i];
1596 const Type *FieldTy =
1597 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001598 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1599
1600 // Ignore zero sized fields like {}, they obviously contain no data.
1601 if (FieldSizeBits == 0) continue;
1602
Owen Anderson1d0be152009-08-13 21:58:54 +00001603 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1604 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00001605 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1606 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001607 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001608 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001609 "", LI);
1610 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1611
1612 // If SrcField is a fp or vector of the right size but that isn't an
1613 // integer type, bitcast to an integer so we can shift it.
1614 if (SrcField->getType() != FieldIntTy)
1615 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1616
1617 // Zero extend the field to be the same size as the final alloca so that
1618 // we can shift and insert it.
1619 if (SrcField->getType() != ResultVal->getType())
1620 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1621
1622 // Determine the number of bits to shift SrcField.
1623 uint64_t Shift;
1624 if (Layout) // Struct case.
1625 Shift = Layout->getElementOffsetInBits(i);
1626 else // Array case.
1627 Shift = i*ArrayEltBitOffset;
1628
1629 if (TD->isBigEndian())
1630 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1631
1632 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001633 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001634 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1635 }
1636
1637 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1638 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001639
1640 // Handle tail padding by truncating the result
1641 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1642 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1643
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001644 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00001645 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001646}
1647
Duncan Sands3cb36502007-11-04 14:43:57 +00001648/// HasPadding - Return true if the specified type has any structure or
1649/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001650static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001651 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1652 const StructLayout *SL = TD.getStructLayout(STy);
1653 unsigned PrevFieldBitOffset = 0;
1654 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001655 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1656
Chris Lattner39a1c042007-05-30 06:11:23 +00001657 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001658 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001659 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001660
Chris Lattner39a1c042007-05-30 06:11:23 +00001661 // Check to see if there is any padding between this element and the
1662 // previous one.
1663 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001664 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001665 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1666 if (PrevFieldEnd < FieldBitOffset)
1667 return true;
1668 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001669
Chris Lattner39a1c042007-05-30 06:11:23 +00001670 PrevFieldBitOffset = FieldBitOffset;
1671 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001672
Chris Lattner39a1c042007-05-30 06:11:23 +00001673 // Check for tail padding.
1674 if (unsigned EltCount = STy->getNumElements()) {
1675 unsigned PrevFieldEnd = PrevFieldBitOffset +
1676 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001677 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001678 return true;
1679 }
1680
1681 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001682 return HasPadding(ATy->getElementType(), TD);
Duncan Sands3cb36502007-11-04 14:43:57 +00001683 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001684 return HasPadding(VTy->getElementType(), TD);
Chris Lattner39a1c042007-05-30 06:11:23 +00001685 }
Duncan Sands777d2302009-05-09 07:06:46 +00001686 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001687}
Chris Lattner372dda82007-03-05 07:52:57 +00001688
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001689/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1690/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1691/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001692bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001693 // Loop over the use list of the alloca. We can only transform it if all of
1694 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001695 AllocaInfo Info;
1696
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001697 isSafeForScalarRepl(AI, AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001698 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00001699 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001700 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001701 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001702
1703 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1704 // source and destination, we have to be careful. In particular, the memcpy
1705 // could be moving around elements that live in structure padding of the LLVM
1706 // types, but may actually be used. In these cases, we refuse to promote the
1707 // struct.
1708 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001709 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001710 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00001711
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001712 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00001713}
Chris Lattnera1888942005-12-12 07:19:13 +00001714
Chris Lattner800de312008-02-29 07:03:13 +00001715
Chris Lattner79b3bd32007-04-25 06:40:51 +00001716
1717/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1718/// some part of a constant global variable. This intentionally only accepts
1719/// constant expressions because we don't can't rewrite arbitrary instructions.
1720static bool PointsToConstantGlobal(Value *V) {
1721 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1722 return GV->isConstant();
1723 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1724 if (CE->getOpcode() == Instruction::BitCast ||
1725 CE->getOpcode() == Instruction::GetElementPtr)
1726 return PointsToConstantGlobal(CE->getOperand(0));
1727 return false;
1728}
1729
1730/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1731/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1732/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1733/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1734/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1735/// the alloca, and if the source pointer is a pointer to a constant global, we
1736/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00001737static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00001738 bool isOffset) {
1739 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00001740 User *U = cast<Instruction>(*UI);
1741
1742 if (LoadInst *LI = dyn_cast<LoadInst>(U))
Chris Lattner6e733d32009-01-28 20:16:43 +00001743 // Ignore non-volatile loads, they are always ok.
1744 if (!LI->isVolatile())
1745 continue;
1746
Gabor Greif8a8a4352010-04-06 19:32:30 +00001747 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001748 // If uses of the bitcast are ok, we are ok.
1749 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1750 return false;
1751 continue;
1752 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00001753 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001754 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1755 // doesn't, it does.
1756 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1757 isOffset || !GEP->hasAllZeroIndices()))
1758 return false;
1759 continue;
1760 }
1761
1762 // If this is isn't our memcpy/memmove, reject it as something we can't
1763 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00001764 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
1765 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00001766 return false;
1767
1768 // If we already have seen a copy, reject the second one.
1769 if (TheCopy) return false;
1770
1771 // If the pointer has been offset from the start of the alloca, we can't
1772 // safely handle this.
1773 if (isOffset) return false;
1774
1775 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greif2ff961f2010-04-15 20:51:13 +00001776 if (UI.getOperandNo() != 0) return false;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001777
Chris Lattner79b3bd32007-04-25 06:40:51 +00001778 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00001779 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001780 return false;
1781
1782 // Otherwise, the transform is safe. Remember the copy instruction.
1783 TheCopy = MI;
1784 }
1785 return true;
1786}
1787
1788/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1789/// modified by a copy from a constant global. If we can prove this, we can
1790/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00001791MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1792 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001793 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1794 return TheCopy;
1795 return 0;
1796}