blob: 27e49160a839c4a76f33be8c8bf0b1dfcb1c3952 [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 Lattner72eaa0e2010-09-01 23:09:27 +000031#include "llvm/Module.h"
Chris Lattner372dda82007-03-05 07:52:57 +000032#include "llvm/Pass.h"
Chris Lattner38aec322003-09-11 16:45:55 +000033#include "llvm/Analysis/Dominators.h"
34#include "llvm/Target/TargetData.h"
35#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000036#include "llvm/Transforms/Utils/Local.h"
Chris Lattner95255282006-06-28 23:17:24 +000037#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000038#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000039#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000040#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000041#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000042#include "llvm/Support/raw_ostream.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000043#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000044#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000045using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000046
Chris Lattner0e5f4992006-12-19 21:40:18 +000047STATISTIC(NumReplaced, "Number of allocas broken up");
48STATISTIC(NumPromoted, "Number of allocas promoted");
49STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000050STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000051
Chris Lattner0e5f4992006-12-19 21:40:18 +000052namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000053 struct SROA : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000054 static char ID; // Pass identification, replacement for typeid
Owen Anderson90c579d2010-08-06 18:33:48 +000055 explicit SROA(signed T = -1) : FunctionPass(ID) {
Devang Patelff366852007-07-09 21:19:23 +000056 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000057 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000058 else
59 SRThreshold = T;
60 }
Devang Patel794fd752007-05-01 21:15:47 +000061
Chris Lattnered7b41e2003-05-27 15:45:27 +000062 bool runOnFunction(Function &F);
63
Chris Lattner38aec322003-09-11 16:45:55 +000064 bool performScalarRepl(Function &F);
65 bool performPromotion(Function &F);
66
Chris Lattnera15854c2003-08-31 00:45:13 +000067 // getAnalysisUsage - This pass does not require any passes, but we know it
68 // will not alter the CFG, so say so.
69 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel326821e2007-06-07 21:57:03 +000070 AU.addRequired<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +000071 AU.addRequired<DominanceFrontier>();
Chris Lattnera15854c2003-08-31 00:45:13 +000072 AU.setPreservesCFG();
73 }
74
Chris Lattnered7b41e2003-05-27 15:45:27 +000075 private:
Chris Lattner56c38522009-01-07 06:34:28 +000076 TargetData *TD;
77
Bob Wilsonb742def2009-12-18 20:14:40 +000078 /// DeadInsts - Keep track of instructions we have made dead, so that
79 /// we can remove them after we are done working.
80 SmallVector<Value*, 32> DeadInsts;
81
Chris Lattner39a1c042007-05-30 06:11:23 +000082 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
83 /// information about the uses. All these fields are initialized to false
84 /// and set to true when something is learned.
85 struct AllocaInfo {
86 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
87 bool isUnsafe : 1;
88
Chris Lattner39a1c042007-05-30 06:11:23 +000089 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
90 bool isMemCpySrc : 1;
91
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000092 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000093 bool isMemCpyDst : 1;
94
95 AllocaInfo()
Victor Hernandez6c146ee2010-01-21 23:05:53 +000096 : isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +000097 };
98
Devang Patelff366852007-07-09 21:19:23 +000099 unsigned SRThreshold;
100
Chris Lattner39a1c042007-05-30 06:11:23 +0000101 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
102
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000103 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000104
Bob Wilsonb742def2009-12-18 20:14:40 +0000105 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000106 AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000107 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000108 AllocaInfo &Info);
109 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
110 const Type *MemOpType, bool isStore, AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000111 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000112 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
113 const Type *&IdxTy);
Chris Lattner39a1c042007-05-30 06:11:23 +0000114
Victor Hernandez7b929da2009-10-23 21:09:37 +0000115 void DoScalarReplacement(AllocaInst *AI,
116 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000117 void DeleteDeadInstructions();
Chris Lattner3126f1c2010-08-18 02:37:06 +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;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000138INITIALIZE_PASS_BEGIN(SROA, "scalarrepl",
139 "Scalar Replacement of Aggregates", false, false)
140INITIALIZE_PASS_DEPENDENCY(DominatorTree)
141INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
142INITIALIZE_PASS_END(SROA, "scalarrepl",
Owen Andersonce665bd2010-10-07 22:25:06 +0000143 "Scalar Replacement of Aggregates", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000144
Brian Gaeked0fde302003-11-11 22:41:34 +0000145// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000146FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
147 return new SROA(Threshold);
148}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000149
150
Chris Lattner4cc576b2010-04-16 00:24:57 +0000151//===----------------------------------------------------------------------===//
152// Convert To Scalar Optimization.
153//===----------------------------------------------------------------------===//
154
155namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000156/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
157/// optimization, which scans the uses of an alloca and determines if it can
158/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000159class ConvertToScalarInfo {
160 /// AllocaSize - The size of the alloca being considered.
161 unsigned AllocaSize;
162 const TargetData &TD;
163
Chris Lattnera0bada72010-04-16 02:32:17 +0000164 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000165 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000166 bool IsNotTrivial;
Chris Lattnera001b662010-04-16 00:38:19 +0000167
168 /// VectorTy - This tracks the type that we should promote the vector to if
169 /// it is possible to turn it into a vector. This starts out null, and if it
170 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000171 const Type *VectorTy;
Chris Lattnera001b662010-04-16 00:38:19 +0000172
173 /// HadAVector - True if there is at least one vector access to the alloca.
174 /// We don't want to turn random arrays into vectors and use vector element
175 /// insert/extract, but if there are element accesses to something that is
176 /// also declared as a vector, we do want to promote to a vector.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000177 bool HadAVector;
178
179public:
180 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
181 : AllocaSize(Size), TD(td) {
182 IsNotTrivial = false;
183 VectorTy = 0;
184 HadAVector = false;
185 }
186
Chris Lattnera001b662010-04-16 00:38:19 +0000187 AllocaInst *TryConvert(AllocaInst *AI);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000188
189private:
190 bool CanConvertToScalar(Value *V, uint64_t Offset);
191 void MergeInType(const Type *In, uint64_t Offset);
192 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
193
194 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
195 uint64_t Offset, IRBuilder<> &Builder);
196 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
197 uint64_t Offset, IRBuilder<> &Builder);
198};
199} // end anonymous namespace.
200
Chris Lattner91abace2010-09-01 05:14:33 +0000201
202/// IsVerbotenVectorType - Return true if this is a vector type ScalarRepl isn't
203/// allowed to form. We do this to avoid MMX types, which is a complete hack,
204/// but is required until the backend is fixed.
Chris Lattner72eaa0e2010-09-01 23:09:27 +0000205static bool IsVerbotenVectorType(const VectorType *VTy, const Instruction *I) {
206 StringRef Triple(I->getParent()->getParent()->getParent()->getTargetTriple());
207 if (!Triple.startswith("i386") &&
208 !Triple.startswith("x86_64"))
209 return false;
210
Chris Lattner91abace2010-09-01 05:14:33 +0000211 // Reject all the MMX vector types.
212 switch (VTy->getNumElements()) {
213 default: return false;
214 case 1: return VTy->getElementType()->isIntegerTy(64);
215 case 2: return VTy->getElementType()->isIntegerTy(32);
216 case 4: return VTy->getElementType()->isIntegerTy(16);
217 case 8: return VTy->getElementType()->isIntegerTy(8);
218 }
219}
220
221
Chris Lattnera001b662010-04-16 00:38:19 +0000222/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
223/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
224/// alloca if possible or null if not.
225AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
226 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
227 // out.
228 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
229 return 0;
230
231 // If we were able to find a vector type that can handle this with
232 // insert/extract elements, and if there was at least one use that had
233 // a vector type, promote this to a vector. We don't want to promote
234 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
235 // we just get a lot of insert/extracts. If at least one vector is
236 // involved, then we probably really do have a union of vector/array.
237 const Type *NewTy;
Chris Lattner91abace2010-09-01 05:14:33 +0000238 if (VectorTy && VectorTy->isVectorTy() && HadAVector &&
Chris Lattner72eaa0e2010-09-01 23:09:27 +0000239 !IsVerbotenVectorType(cast<VectorType>(VectorTy), AI)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000240 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
241 << *VectorTy << '\n');
242 NewTy = VectorTy; // Use the vector type.
243 } else {
244 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
245 // Create and insert the integer alloca.
246 NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
247 }
248 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
249 ConvertUsesToScalar(AI, NewAI, 0);
250 return NewAI;
251}
252
253/// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
254/// so far at the offset specified by Offset (which is specified in bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000255///
256/// There are two cases we handle here:
257/// 1) A union of vector types of the same size and potentially its elements.
258/// Here we turn element accesses into insert/extract element operations.
259/// This promotes a <4 x float> with a store of float to the third element
260/// into a <4 x float> that uses insert element.
261/// 2) A fully general blob of memory, which we turn into some (potentially
262/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000263/// and stores would mutate the memory. We mark this by setting VectorTy
264/// to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000265void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000266 // If we already decided to turn this into a blob of integer memory, there is
267 // nothing to be done.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000268 if (VectorTy && VectorTy->isVoidTy())
269 return;
270
271 // If this could be contributing to a vector, analyze it.
272
273 // If the In type is a vector that is the same size as the alloca, see if it
274 // matches the existing VecTy.
275 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000276 // Remember if we saw a vector type.
277 HadAVector = true;
278
Chris Lattner4cc576b2010-04-16 00:24:57 +0000279 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
280 // If we're storing/loading a vector of the right size, allow it as a
281 // vector. If this the first vector we see, remember the type so that
Chris Lattnera001b662010-04-16 00:38:19 +0000282 // we know the element size. If this is a subsequent access, ignore it
283 // even if it is a differing type but the same size. Worst case we can
284 // bitcast the resultant vectors.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000285 if (VectorTy == 0)
286 VectorTy = VInTy;
287 return;
288 }
289 } else if (In->isFloatTy() || In->isDoubleTy() ||
290 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
291 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
292 // If we're accessing something that could be an element of a vector, see
293 // if the implied vector agrees with what we already have and if Offset is
294 // compatible with it.
295 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
296 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
297 (VectorTy == 0 ||
298 cast<VectorType>(VectorTy)->getElementType()
299 ->getPrimitiveSizeInBits()/8 == EltSize)) {
300 if (VectorTy == 0)
301 VectorTy = VectorType::get(In, AllocaSize/EltSize);
302 return;
303 }
304 }
305
306 // Otherwise, we have a case that we can't handle with an optimized vector
307 // form. We can still turn this into a large integer.
308 VectorTy = Type::getVoidTy(In->getContext());
309}
310
311/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
312/// its accesses to a single vector type, return true and set VecTy to
313/// the new type. If we could convert the alloca into a single promotable
314/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
315/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
316/// is the current offset from the base of the alloca being analyzed.
317///
318/// If we see at least one access to the value that is as a vector type, set the
319/// SawVec flag.
320bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
321 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
322 Instruction *User = cast<Instruction>(*UI);
323
324 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
325 // Don't break volatile loads.
326 if (LI->isVolatile())
327 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000328 // Don't touch MMX operations.
329 if (LI->getType()->isX86_MMXTy())
330 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000331 MergeInType(LI->getType(), Offset);
332 continue;
333 }
334
335 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
336 // Storing the pointer, not into the value?
337 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000338 // Don't touch MMX operations.
339 if (SI->getOperand(0)->getType()->isX86_MMXTy())
340 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000341 MergeInType(SI->getOperand(0)->getType(), Offset);
342 continue;
343 }
344
345 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000346 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000347 if (!CanConvertToScalar(BCI, Offset))
348 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000349 continue;
350 }
351
352 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
353 // If this is a GEP with a variable indices, we can't handle it.
354 if (!GEP->hasAllConstantIndices())
355 return false;
356
357 // Compute the offset that this GEP adds to the pointer.
358 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
359 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
360 &Indices[0], Indices.size());
361 // See if all uses can be converted.
362 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
363 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000364 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000365 continue;
366 }
367
368 // If this is a constant sized memset of a constant value (e.g. 0) we can
369 // handle it.
370 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
371 // Store of constant value and constant size.
Chris Lattnera001b662010-04-16 00:38:19 +0000372 if (!isa<ConstantInt>(MSI->getValue()) ||
373 !isa<ConstantInt>(MSI->getLength()))
374 return false;
375 IsNotTrivial = true; // Can't be mem2reg'd.
376 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000377 }
378
379 // If this is a memcpy or memmove into or out of the whole allocation, we
380 // can handle it like a load or store of the scalar type.
381 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000382 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
383 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
384 return false;
385
386 IsNotTrivial = true; // Can't be mem2reg'd.
387 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000388 }
389
390 // Otherwise, we cannot handle this!
391 return false;
392 }
393
394 return true;
395}
396
397/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
398/// directly. This happens when we are converting an "integer union" to a
399/// single integer scalar, or when we are converting a "vector union" to a
400/// vector with insert/extractelement instructions.
401///
402/// Offset is an offset from the original alloca, in bits that need to be
403/// shifted to the right. By the end of this, there should be no uses of Ptr.
404void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
405 uint64_t Offset) {
406 while (!Ptr->use_empty()) {
407 Instruction *User = cast<Instruction>(Ptr->use_back());
408
409 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
410 ConvertUsesToScalar(CI, NewAI, Offset);
411 CI->eraseFromParent();
412 continue;
413 }
414
415 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
416 // Compute the offset that this GEP adds to the pointer.
417 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
418 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
419 &Indices[0], Indices.size());
420 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
421 GEP->eraseFromParent();
422 continue;
423 }
424
425 IRBuilder<> Builder(User->getParent(), User);
426
427 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
428 // The load is a bit extract from NewAI shifted right by Offset bits.
429 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
430 Value *NewLoadVal
431 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
432 LI->replaceAllUsesWith(NewLoadVal);
433 LI->eraseFromParent();
434 continue;
435 }
436
437 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
438 assert(SI->getOperand(0) != Ptr && "Consistency error!");
439 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
440 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
441 Builder);
442 Builder.CreateStore(New, NewAI);
443 SI->eraseFromParent();
444
445 // If the load we just inserted is now dead, then the inserted store
446 // overwrote the entire thing.
447 if (Old->use_empty())
448 Old->eraseFromParent();
449 continue;
450 }
451
452 // If this is a constant sized memset of a constant value (e.g. 0) we can
453 // transform it into a store of the expanded constant value.
454 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
455 assert(MSI->getRawDest() == Ptr && "Consistency error!");
456 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
457 if (NumBytes != 0) {
458 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
459
460 // Compute the value replicated the right number of times.
461 APInt APVal(NumBytes*8, Val);
462
463 // Splat the value if non-zero.
464 if (Val)
465 for (unsigned i = 1; i != NumBytes; ++i)
466 APVal |= APVal << 8;
467
468 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
469 Value *New = ConvertScalar_InsertValue(
470 ConstantInt::get(User->getContext(), APVal),
471 Old, Offset, Builder);
472 Builder.CreateStore(New, NewAI);
473
474 // If the load we just inserted is now dead, then the memset overwrote
475 // the entire thing.
476 if (Old->use_empty())
477 Old->eraseFromParent();
478 }
479 MSI->eraseFromParent();
480 continue;
481 }
482
483 // If this is a memcpy or memmove into or out of the whole allocation, we
484 // can handle it like a load or store of the scalar type.
485 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
486 assert(Offset == 0 && "must be store to start of alloca");
487
488 // If the source and destination are both to the same alloca, then this is
489 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
490 // as appropriate.
491 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject(0));
492
493 if (MTI->getSource()->getUnderlyingObject(0) != OrigAI) {
494 // Dest must be OrigAI, change this to be a load from the original
495 // pointer (bitcasted), then a store to our new alloca.
496 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
497 Value *SrcPtr = MTI->getSource();
498 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
499
500 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
501 SrcVal->setAlignment(MTI->getAlignment());
502 Builder.CreateStore(SrcVal, NewAI);
503 } else if (MTI->getDest()->getUnderlyingObject(0) != OrigAI) {
504 // Src must be OrigAI, change this to be a load from NewAI then a store
505 // through the original dest pointer (bitcasted).
506 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
507 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
508
509 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
510 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
511 NewStore->setAlignment(MTI->getAlignment());
512 } else {
513 // Noop transfer. Src == Dst
514 }
515
516 MTI->eraseFromParent();
517 continue;
518 }
519
520 llvm_unreachable("Unsupported operation!");
521 }
522}
523
524/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
525/// or vector value FromVal, extracting the bits from the offset specified by
526/// Offset. This returns the value, which is of type ToType.
527///
528/// This happens when we are converting an "integer union" to a single
529/// integer scalar, or when we are converting a "vector union" to a vector with
530/// insert/extractelement instructions.
531///
532/// Offset is an offset from the original alloca, in bits that need to be
533/// shifted to the right.
534Value *ConvertToScalarInfo::
535ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
536 uint64_t Offset, IRBuilder<> &Builder) {
537 // If the load is of the whole new alloca, no conversion is needed.
538 if (FromVal->getType() == ToType && Offset == 0)
539 return FromVal;
540
541 // If the result alloca is a vector type, this is either an element
542 // access or a bitcast to another vector type of the same size.
543 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
544 if (ToType->isVectorTy())
545 return Builder.CreateBitCast(FromVal, ToType, "tmp");
546
547 // Otherwise it must be an element access.
548 unsigned Elt = 0;
549 if (Offset) {
550 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
551 Elt = Offset/EltSize;
552 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
553 }
554 // Return the element extracted out of it.
555 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
556 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
557 if (V->getType() != ToType)
558 V = Builder.CreateBitCast(V, ToType, "tmp");
559 return V;
560 }
561
562 // If ToType is a first class aggregate, extract out each of the pieces and
563 // use insertvalue's to form the FCA.
564 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
565 const StructLayout &Layout = *TD.getStructLayout(ST);
566 Value *Res = UndefValue::get(ST);
567 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
568 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
569 Offset+Layout.getElementOffsetInBits(i),
570 Builder);
571 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
572 }
573 return Res;
574 }
575
576 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
577 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
578 Value *Res = UndefValue::get(AT);
579 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
580 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
581 Offset+i*EltSize, Builder);
582 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
583 }
584 return Res;
585 }
586
587 // Otherwise, this must be a union that was converted to an integer value.
588 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
589
590 // If this is a big-endian system and the load is narrower than the
591 // full alloca type, we need to do a shift to get the right bits.
592 int ShAmt = 0;
593 if (TD.isBigEndian()) {
594 // On big-endian machines, the lowest bit is stored at the bit offset
595 // from the pointer given by getTypeStoreSizeInBits. This matters for
596 // integers with a bitwidth that is not a multiple of 8.
597 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
598 TD.getTypeStoreSizeInBits(ToType) - Offset;
599 } else {
600 ShAmt = Offset;
601 }
602
603 // Note: we support negative bitwidths (with shl) which are not defined.
604 // We do this to support (f.e.) loads off the end of a structure where
605 // only some bits are used.
606 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
607 FromVal = Builder.CreateLShr(FromVal,
608 ConstantInt::get(FromVal->getType(),
609 ShAmt), "tmp");
610 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
611 FromVal = Builder.CreateShl(FromVal,
612 ConstantInt::get(FromVal->getType(),
613 -ShAmt), "tmp");
614
615 // Finally, unconditionally truncate the integer to the right width.
616 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
617 if (LIBitWidth < NTy->getBitWidth())
618 FromVal =
619 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
620 LIBitWidth), "tmp");
621 else if (LIBitWidth > NTy->getBitWidth())
622 FromVal =
623 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
624 LIBitWidth), "tmp");
625
626 // If the result is an integer, this is a trunc or bitcast.
627 if (ToType->isIntegerTy()) {
628 // Should be done.
629 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
630 // Just do a bitcast, we know the sizes match up.
631 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
632 } else {
633 // Otherwise must be a pointer.
634 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
635 }
636 assert(FromVal->getType() == ToType && "Didn't convert right?");
637 return FromVal;
638}
639
640/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
641/// or vector value "Old" at the offset specified by Offset.
642///
643/// This happens when we are converting an "integer union" to a
644/// single integer scalar, or when we are converting a "vector union" to a
645/// vector with insert/extractelement instructions.
646///
647/// Offset is an offset from the original alloca, in bits that need to be
648/// shifted to the right.
649Value *ConvertToScalarInfo::
650ConvertScalar_InsertValue(Value *SV, Value *Old,
651 uint64_t Offset, IRBuilder<> &Builder) {
652 // Convert the stored type to the actual type, shift it left to insert
653 // then 'or' into place.
654 const Type *AllocaType = Old->getType();
655 LLVMContext &Context = Old->getContext();
656
657 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
658 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
659 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
660
661 // Changing the whole vector with memset or with an access of a different
662 // vector type?
663 if (ValSize == VecSize)
664 return Builder.CreateBitCast(SV, AllocaType, "tmp");
665
666 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
667
668 // Must be an element insertion.
669 unsigned Elt = Offset/EltSize;
670
671 if (SV->getType() != VTy->getElementType())
672 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
673
674 SV = Builder.CreateInsertElement(Old, SV,
675 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
676 "tmp");
677 return SV;
678 }
679
680 // If SV is a first-class aggregate value, insert each value recursively.
681 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
682 const StructLayout &Layout = *TD.getStructLayout(ST);
683 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
684 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
685 Old = ConvertScalar_InsertValue(Elt, Old,
686 Offset+Layout.getElementOffsetInBits(i),
687 Builder);
688 }
689 return Old;
690 }
691
692 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
693 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
694 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
695 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
696 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
697 }
698 return Old;
699 }
700
701 // If SV is a float, convert it to the appropriate integer type.
702 // If it is a pointer, do the same.
703 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
704 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
705 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
706 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
707 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
708 SV = Builder.CreateBitCast(SV,
709 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
710 else if (SV->getType()->isPointerTy())
711 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
712
713 // Zero extend or truncate the value if needed.
714 if (SV->getType() != AllocaType) {
715 if (SV->getType()->getPrimitiveSizeInBits() <
716 AllocaType->getPrimitiveSizeInBits())
717 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
718 else {
719 // Truncation may be needed if storing more than the alloca can hold
720 // (undefined behavior).
721 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
722 SrcWidth = DestWidth;
723 SrcStoreWidth = DestStoreWidth;
724 }
725 }
726
727 // If this is a big-endian system and the store is narrower than the
728 // full alloca type, we need to do a shift to get the right bits.
729 int ShAmt = 0;
730 if (TD.isBigEndian()) {
731 // On big-endian machines, the lowest bit is stored at the bit offset
732 // from the pointer given by getTypeStoreSizeInBits. This matters for
733 // integers with a bitwidth that is not a multiple of 8.
734 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
735 } else {
736 ShAmt = Offset;
737 }
738
739 // Note: we support negative bitwidths (with shr) which are not defined.
740 // We do this to support (f.e.) stores off the end of a structure where
741 // only some bits in the structure are set.
742 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
743 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
744 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
745 ShAmt), "tmp");
746 Mask <<= ShAmt;
747 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
748 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
749 -ShAmt), "tmp");
750 Mask = Mask.lshr(-ShAmt);
751 }
752
753 // Mask out the bits we are about to insert from the old value, and or
754 // in the new bits.
755 if (SrcWidth != DestWidth) {
756 assert(DestWidth > SrcWidth);
757 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
758 SV = Builder.CreateOr(Old, SV, "ins");
759 }
760 return SV;
761}
762
763
764//===----------------------------------------------------------------------===//
765// SRoA Driver
766//===----------------------------------------------------------------------===//
767
768
Chris Lattnered7b41e2003-05-27 15:45:27 +0000769bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000770 TD = getAnalysisIfAvailable<TargetData>();
771
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000772 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000773
774 // FIXME: ScalarRepl currently depends on TargetData more than it
775 // theoretically needs to. It should be refactored in order to support
776 // target-independent IR. Until this is done, just skip the actual
777 // scalar-replacement portion of this pass.
778 if (!TD) return Changed;
779
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000780 while (1) {
781 bool LocalChange = performScalarRepl(F);
782 if (!LocalChange) break; // No need to repromote if no scalarrepl
783 Changed = true;
784 LocalChange = performPromotion(F);
785 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
786 }
Chris Lattner38aec322003-09-11 16:45:55 +0000787
788 return Changed;
789}
790
791
792bool SROA::performPromotion(Function &F) {
793 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000794 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000795 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000796
Chris Lattner02a3be02003-09-20 14:39:18 +0000797 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000798
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000799 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000800
Chris Lattner38aec322003-09-11 16:45:55 +0000801 while (1) {
802 Allocas.clear();
803
804 // Find allocas that are safe to promote, by looking at all instructions in
805 // the entry node
806 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
807 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000808 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000809 Allocas.push_back(AI);
810
811 if (Allocas.empty()) break;
812
Nick Lewyckyce2c51b2009-11-23 03:50:44 +0000813 PromoteMemToReg(Allocas, DT, DF);
Chris Lattner38aec322003-09-11 16:45:55 +0000814 NumPromoted += Allocas.size();
815 Changed = true;
816 }
817
818 return Changed;
819}
820
Chris Lattner4cc576b2010-04-16 00:24:57 +0000821
Bob Wilson3992feb2010-02-03 17:23:56 +0000822/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
823/// SROA. It must be a struct or array type with a small number of elements.
824static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
825 const Type *T = AI->getAllocatedType();
826 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +0000827 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +0000828 return ST->getNumElements() <= 32;
829 // Arrays are much less likely to be safe for SROA; only consider
830 // them if they are very small.
831 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
832 return AT->getNumElements() <= 8;
833 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +0000834}
835
Chris Lattnerc4472072010-04-15 23:50:26 +0000836
Chris Lattner38aec322003-09-11 16:45:55 +0000837// performScalarRepl - This algorithm is a simple worklist driven algorithm,
838// which runs on all of the malloc/alloca instructions in the function, removing
839// them if they are only used by getelementptr instructions.
840//
841bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000842 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000843
Chris Lattner31d80102010-04-15 21:59:20 +0000844 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +0000845 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000846 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000847 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000848 WorkList.push_back(A);
849
850 // Process the worklist
851 bool Changed = false;
852 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000853 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000854 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000855
Chris Lattneradd2bd72006-12-22 23:14:42 +0000856 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
857 // with unused elements.
858 if (AI->use_empty()) {
859 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +0000860 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +0000861 continue;
862 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000863
864 // If this alloca is impossible for us to promote, reject it early.
865 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
866 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000867
868 // Check to see if this allocation is only modified by a memcpy/memmove from
869 // a constant global. If this is the case, we can change all users to use
870 // the constant global instead. This is commonly produced by the CFE by
871 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
872 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +0000873 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +0000874 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
875 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +0000876 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +0000877 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000878 TheCopy->eraseFromParent(); // Don't mutate the global.
879 AI->eraseFromParent();
880 ++NumGlobals;
881 Changed = true;
882 continue;
883 }
Chris Lattner15c82772009-02-02 20:44:45 +0000884
Chris Lattner7809ecd2009-02-03 01:30:09 +0000885 // Check to see if we can perform the core SROA transformation. We cannot
886 // transform the allocation instruction if it is an array allocation
887 // (allocations OF arrays are ok though), and an allocation of a scalar
888 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000889 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000890
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000891 // Do not promote [0 x %struct].
892 if (AllocaSize == 0) continue;
Chris Lattner31d80102010-04-15 21:59:20 +0000893
894 // Do not promote any struct whose size is too big.
895 if (AllocaSize > SRThreshold) continue;
896
Bob Wilson3992feb2010-02-03 17:23:56 +0000897 // If the alloca looks like a good candidate for scalar replacement, and if
898 // all its users can be transformed, then split up the aggregate into its
899 // separate elements.
900 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
901 DoScalarReplacement(AI, WorkList);
902 Changed = true;
903 continue;
904 }
905
Chris Lattner6e733d32009-01-28 20:16:43 +0000906 // If we can turn this aggregate value (potentially with casts) into a
907 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000908 // IsNotTrivial tracks whether this is something that mem2reg could have
909 // promoted itself. If so, we don't want to transform it needlessly. Note
910 // that we can't just check based on the type: the alloca may be of an i32
911 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +0000912 if (AllocaInst *NewAI =
913 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000914 NewAI->takeName(AI);
915 AI->eraseFromParent();
916 ++NumConverted;
917 Changed = true;
918 continue;
Chris Lattner593375d2010-04-16 00:20:00 +0000919 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000920
Chris Lattner7809ecd2009-02-03 01:30:09 +0000921 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000922 }
923
924 return Changed;
925}
Chris Lattner5e062a12003-05-30 04:15:41 +0000926
Chris Lattnera10b29b2007-04-25 05:02:56 +0000927/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
928/// predicate, do SROA now.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000929void SROA::DoScalarReplacement(AllocaInst *AI,
930 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +0000931 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +0000932 SmallVector<AllocaInst*, 32> ElementAllocas;
933 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
934 ElementAllocas.reserve(ST->getNumContainedTypes());
935 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000936 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +0000937 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000938 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000939 ElementAllocas.push_back(NA);
940 WorkList.push_back(NA); // Add to worklist for recursive processing
941 }
942 } else {
943 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
944 ElementAllocas.reserve(AT->getNumElements());
945 const Type *ElTy = AT->getElementType();
946 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000947 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000948 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000949 ElementAllocas.push_back(NA);
950 WorkList.push_back(NA); // Add to worklist for recursive processing
951 }
952 }
953
Bob Wilsonb742def2009-12-18 20:14:40 +0000954 // Now that we have created the new alloca instructions, rewrite all the
955 // uses of the old alloca.
956 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +0000957
Bob Wilsonb742def2009-12-18 20:14:40 +0000958 // Now erase any instructions that were made dead while rewriting the alloca.
959 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +0000960 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +0000961
Dan Gohmanfe601042010-06-22 15:08:57 +0000962 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +0000963}
Chris Lattnera59adc42009-12-14 05:11:02 +0000964
Bob Wilsonb742def2009-12-18 20:14:40 +0000965/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
966/// recursively including all their operands that become trivially dead.
967void SROA::DeleteDeadInstructions() {
968 while (!DeadInsts.empty()) {
969 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +0000970
Bob Wilsonb742def2009-12-18 20:14:40 +0000971 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
972 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
973 // Zero out the operand and see if it becomes trivially dead.
974 // (But, don't add allocas to the dead instruction list -- they are
975 // already on the worklist and will be deleted separately.)
976 *OI = 0;
977 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
978 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +0000979 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000980
981 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +0000982 }
Chris Lattnera59adc42009-12-14 05:11:02 +0000983}
Bob Wilsonb742def2009-12-18 20:14:40 +0000984
Bob Wilsonb742def2009-12-18 20:14:40 +0000985/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
986/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000987/// the Info parameter. Offset indicates the position within AI that is
988/// referenced by this instruction.
Bob Wilsonb742def2009-12-18 20:14:40 +0000989void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000990 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000991 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
992 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000993
Bob Wilsonb742def2009-12-18 20:14:40 +0000994 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000995 isSafeForScalarRepl(BC, AI, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000996 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000997 uint64_t GEPOffset = Offset;
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000998 isSafeGEP(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000999 if (!Info.isUnsafe)
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001000 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001001 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001002 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1003 if (Length)
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001004 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
Gabor Greifa6aac4c2010-07-16 09:38:02 +00001005 UI.getOperandNo() == 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001006 else
1007 MarkUnsafe(Info);
1008 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1009 if (!LI->isVolatile()) {
1010 const Type *LIType = LI->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001011 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
Bob Wilsonb742def2009-12-18 20:14:40 +00001012 LIType, false, Info);
1013 } else
1014 MarkUnsafe(Info);
1015 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1016 // Store is ok if storing INTO the pointer, not storing the pointer
1017 if (!SI->isVolatile() && SI->getOperand(0) != I) {
1018 const Type *SIType = SI->getOperand(0)->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001019 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
Bob Wilsonb742def2009-12-18 20:14:40 +00001020 SIType, true, Info);
1021 } else
1022 MarkUnsafe(Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001023 } else {
1024 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
1025 MarkUnsafe(Info);
1026 }
1027 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001028 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001029}
Bob Wilson39c88a62009-12-17 18:34:24 +00001030
Bob Wilsonb742def2009-12-18 20:14:40 +00001031/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1032/// replacement. It is safe when all the indices are constant, in-bounds
1033/// references, and when the resulting offset corresponds to an element within
1034/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001035/// return, Offset is adjusted as specified by the GEP indices.
Bob Wilsonb742def2009-12-18 20:14:40 +00001036void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001037 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001038 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1039 if (GEPIt == E)
1040 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001041
Chris Lattner88e6dc82008-08-23 05:21:06 +00001042 // Walk through the GEP type indices, checking the types that this indexes
1043 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001044 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001045 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001046 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001047 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001048
Bob Wilsonb742def2009-12-18 20:14:40 +00001049 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1050 if (!IdxVal)
1051 return MarkUnsafe(Info);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001052 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001053
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001054 // Compute the offset due to this GEP and check if the alloca has a
1055 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001056 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1057 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1058 &Indices[0], Indices.size());
Bob Wilsonb742def2009-12-18 20:14:40 +00001059 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
1060 MarkUnsafe(Info);
Chris Lattner5e062a12003-05-30 04:15:41 +00001061}
1062
Bob Wilsonb742def2009-12-18 20:14:40 +00001063/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1064/// alloca or has an offset and size that corresponds to a component element
1065/// within it. The offset checked here may have been formed from a GEP with a
1066/// pointer bitcasted to a different type.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001067void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001068 const Type *MemOpType, bool isStore,
1069 AllocaInfo &Info) {
1070 // Check if this is a load/store of the entire alloca.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001071 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001072 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
1073 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
1074 // (which are essentially the same as the MemIntrinsics, especially with
1075 // regard to copying padding between elements), or references using the
1076 // aggregate type of the alloca.
Duncan Sands1df98592010-02-16 11:11:14 +00001077 if (!MemOpType || MemOpType->isIntegerTy() || UsesAggregateType) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001078 if (!UsesAggregateType) {
1079 if (isStore)
1080 Info.isMemCpyDst = true;
1081 else
1082 Info.isMemCpySrc = true;
1083 }
1084 return;
1085 }
1086 }
1087 // Check if the offset/size correspond to a component within the alloca type.
1088 const Type *T = AI->getAllocatedType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001089 if (TypeHasComponent(T, Offset, MemSize))
Bob Wilsonb742def2009-12-18 20:14:40 +00001090 return;
1091
1092 return MarkUnsafe(Info);
1093}
1094
1095/// TypeHasComponent - Return true if T has a component type with the
1096/// specified offset and size. If Size is zero, do not check the size.
1097bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1098 const Type *EltTy;
1099 uint64_t EltSize;
1100 if (const StructType *ST = dyn_cast<StructType>(T)) {
1101 const StructLayout *Layout = TD->getStructLayout(ST);
1102 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1103 EltTy = ST->getContainedType(EltIdx);
1104 EltSize = TD->getTypeAllocSize(EltTy);
1105 Offset -= Layout->getElementOffset(EltIdx);
1106 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1107 EltTy = AT->getElementType();
1108 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001109 if (Offset >= AT->getNumElements() * EltSize)
1110 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001111 Offset %= EltSize;
1112 } else {
1113 return false;
1114 }
1115 if (Offset == 0 && (Size == 0 || EltSize == Size))
1116 return true;
1117 // Check if the component spans multiple elements.
1118 if (Offset + Size > EltSize)
1119 return false;
1120 return TypeHasComponent(EltTy, Offset, Size);
1121}
1122
1123/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1124/// the instruction I, which references it, to use the separate elements.
1125/// Offset indicates the position within AI that is referenced by this
1126/// instruction.
1127void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1128 SmallVector<AllocaInst*, 32> &NewElts) {
1129 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1130 Instruction *User = cast<Instruction>(*UI);
1131
1132 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1133 RewriteBitCast(BC, AI, Offset, NewElts);
1134 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1135 RewriteGEP(GEPI, AI, Offset, NewElts);
1136 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1137 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1138 uint64_t MemSize = Length->getZExtValue();
1139 if (Offset == 0 &&
1140 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1141 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001142 // Otherwise the intrinsic can only touch a single element and the
1143 // address operand will be updated, so nothing else needs to be done.
Bob Wilsonb742def2009-12-18 20:14:40 +00001144 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1145 const Type *LIType = LI->getType();
1146 if (LIType == AI->getAllocatedType()) {
1147 // Replace:
1148 // %res = load { i32, i32 }* %alloc
1149 // with:
1150 // %load.0 = load i32* %alloc.0
1151 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1152 // %load.1 = load i32* %alloc.1
1153 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1154 // (Also works for arrays instead of structs)
1155 Value *Insert = UndefValue::get(LIType);
1156 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1157 Value *Load = new LoadInst(NewElts[i], "load", LI);
1158 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1159 }
1160 LI->replaceAllUsesWith(Insert);
1161 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001162 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001163 TD->getTypeAllocSize(LIType) ==
1164 TD->getTypeAllocSize(AI->getAllocatedType())) {
1165 // If this is a load of the entire alloca to an integer, rewrite it.
1166 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1167 }
1168 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1169 Value *Val = SI->getOperand(0);
1170 const Type *SIType = Val->getType();
1171 if (SIType == AI->getAllocatedType()) {
1172 // Replace:
1173 // store { i32, i32 } %val, { i32, i32 }* %alloc
1174 // with:
1175 // %val.0 = extractvalue { i32, i32 } %val, 0
1176 // store i32 %val.0, i32* %alloc.0
1177 // %val.1 = extractvalue { i32, i32 } %val, 1
1178 // store i32 %val.1, i32* %alloc.1
1179 // (Also works for arrays instead of structs)
1180 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1181 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1182 new StoreInst(Extract, NewElts[i], SI);
1183 }
1184 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001185 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001186 TD->getTypeAllocSize(SIType) ==
1187 TD->getTypeAllocSize(AI->getAllocatedType())) {
1188 // If this is a store of the entire alloca from an integer, rewrite it.
1189 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1190 }
1191 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001192 }
1193}
1194
Bob Wilsonb742def2009-12-18 20:14:40 +00001195/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1196/// and recursively continue updating all of its uses.
1197void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1198 SmallVector<AllocaInst*, 32> &NewElts) {
1199 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1200 if (BC->getOperand(0) != AI)
1201 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001202
Bob Wilsonb742def2009-12-18 20:14:40 +00001203 // The bitcast references the original alloca. Replace its uses with
1204 // references to the first new element alloca.
1205 Instruction *Val = NewElts[0];
1206 if (Val->getType() != BC->getDestTy()) {
1207 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1208 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001209 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001210 BC->replaceAllUsesWith(Val);
1211 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001212}
1213
Bob Wilsonb742def2009-12-18 20:14:40 +00001214/// FindElementAndOffset - Return the index of the element containing Offset
1215/// within the specified type, which must be either a struct or an array.
1216/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001217/// element. IdxTy is set to the type of the index result to be used in a
1218/// GEP instruction.
1219uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1220 const Type *&IdxTy) {
1221 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001222 if (const StructType *ST = dyn_cast<StructType>(T)) {
1223 const StructLayout *Layout = TD->getStructLayout(ST);
1224 Idx = Layout->getElementContainingOffset(Offset);
1225 T = ST->getContainedType(Idx);
1226 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001227 IdxTy = Type::getInt32Ty(T->getContext());
1228 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001229 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001230 const ArrayType *AT = cast<ArrayType>(T);
1231 T = AT->getElementType();
1232 uint64_t EltSize = TD->getTypeAllocSize(T);
1233 Idx = Offset / EltSize;
1234 Offset -= Idx * EltSize;
1235 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001236 return Idx;
1237}
1238
1239/// RewriteGEP - Check if this GEP instruction moves the pointer across
1240/// elements of the alloca that are being split apart, and if so, rewrite
1241/// the GEP to be relative to the new element.
1242void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1243 SmallVector<AllocaInst*, 32> &NewElts) {
1244 uint64_t OldOffset = Offset;
1245 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1246 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1247 &Indices[0], Indices.size());
1248
1249 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1250
1251 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00001252 const Type *IdxTy;
1253 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001254 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001255 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001256
1257 T = AI->getAllocatedType();
1258 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001259 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001260
1261 // If this GEP does not move the pointer across elements of the alloca
1262 // being split, then it does not needs to be rewritten.
1263 if (Idx == OldIdx)
1264 return;
1265
1266 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1267 SmallVector<Value*, 8> NewArgs;
1268 NewArgs.push_back(Constant::getNullValue(i32Ty));
1269 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001270 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1271 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00001272 }
1273 Instruction *Val = NewElts[Idx];
1274 if (NewArgs.size() > 1) {
1275 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1276 NewArgs.end(), "", GEPI);
1277 Val->takeName(GEPI);
1278 }
1279 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001280 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001281 GEPI->replaceAllUsesWith(Val);
1282 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001283}
1284
1285/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1286/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00001287void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001288 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00001289 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001290 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00001291 // appropriate type. The "Other" pointer is the pointer that goes to memory
1292 // that doesn't have anything to do with the alloca that we are promoting. For
1293 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00001294 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001295 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00001296 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00001297 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00001298 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001299 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00001300 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00001301 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001302 }
1303 }
Bob Wilson78c50b82009-12-08 18:22:03 +00001304
Chris Lattnerd93afec2009-01-07 07:18:45 +00001305 // If there is an other pointer, we want to convert it to the same pointer
1306 // type as AI has, so we can GEP through it safely.
1307 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00001308 unsigned AddrSpace =
1309 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00001310
1311 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
1312 // optimization, but it's also required to detect the corner case where
1313 // both pointer operands are referencing the same memory, and where
1314 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
1315 // function is only called for mem intrinsics that access the whole
1316 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00001317 OtherPtr = OtherPtr->stripPointerCasts();
1318
Bob Wilsona756b1d2010-01-19 04:32:48 +00001319 // Copying the alloca to itself is a no-op: just delete it.
1320 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1321 // This code will run twice for a no-op memcpy -- once for each operand.
1322 // Put only one reference to MI on the DeadInsts list.
1323 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1324 E = DeadInsts.end(); I != E; ++I)
1325 if (*I == MI) return;
1326 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001327 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00001328 }
Chris Lattner372dda82007-03-05 07:52:57 +00001329
Chris Lattnerd93afec2009-01-07 07:18:45 +00001330 // If the pointer is not the right type, insert a bitcast to the right
1331 // type.
Chris Lattner0238f8c2010-07-08 00:27:05 +00001332 const Type *NewTy =
1333 PointerType::get(AI->getType()->getElementType(), AddrSpace);
1334
1335 if (OtherPtr->getType() != NewTy)
1336 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001337 }
1338
1339 // Process each element of the aggregate.
Gabor Greifa9b23132010-04-20 13:13:04 +00001340 Value *TheFn = MI->getCalledValue();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001341 const Type *BytePtrTy = MI->getRawDest()->getType();
Bob Wilsonb742def2009-12-18 20:14:40 +00001342 bool SROADest = MI->getRawDest() == Inst;
Chris Lattnerd93afec2009-01-07 07:18:45 +00001343
Owen Anderson1d0be152009-08-13 21:58:54 +00001344 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00001345
1346 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1347 // If this is a memcpy/memmove, emit a GEP of the other element address.
1348 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001349 unsigned OtherEltAlign = MemAlignment;
1350
Bob Wilsona756b1d2010-01-19 04:32:48 +00001351 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001352 Value *Idx[2] = { Zero,
1353 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00001354 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001355 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00001356 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00001357 uint64_t EltOffset;
1358 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001359 const Type *OtherTy = OtherPtrTy->getElementType();
1360 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001361 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1362 } else {
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001363 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001364 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001365 }
1366
1367 // The alignment of the other pointer is the guaranteed alignment of the
1368 // element, which is affected by both the known alignment of the whole
1369 // mem intrinsic and the alignment of the element. If the alignment of
1370 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1371 // known alignment is just 4 bytes.
1372 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00001373 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001374
1375 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00001376 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001377
1378 // If we got down to a scalar, insert a load or store as appropriate.
1379 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001380 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001381 if (SROADest) {
1382 // From Other to Alloca.
1383 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1384 new StoreInst(Elt, EltPtr, MI);
1385 } else {
1386 // From Alloca to Other.
1387 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1388 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1389 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001390 continue;
1391 }
1392 assert(isa<MemSetInst>(MI));
1393
1394 // If the stored element is zero (common case), just store a null
1395 // constant.
1396 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001397 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001398 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001399 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00001400 } else {
1401 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00001402 const Type *ValTy = EltTy->getScalarType();
1403
Chris Lattnerd93afec2009-01-07 07:18:45 +00001404 // Construct an integer with the right value.
1405 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1406 APInt OneVal(EltSize, CI->getZExtValue());
1407 APInt TotalVal(OneVal);
1408 // Set each byte.
1409 for (unsigned i = 0; 8*i < EltSize; ++i) {
1410 TotalVal = TotalVal.shl(8);
1411 TotalVal |= OneVal;
1412 }
1413
1414 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001415 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001416 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001417 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001418 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001419 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001420 assert(StoreVal->getType() == ValTy && "Type mismatch!");
1421
1422 // If the requested value was a vector constant, create it.
1423 if (EltTy != ValTy) {
1424 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1425 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +00001426 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001427 }
1428 }
1429 new StoreInst(StoreVal, EltPtr, MI);
1430 continue;
1431 }
1432 // Otherwise, if we're storing a byte variable, use a memset call for
1433 // this element.
1434 }
1435
1436 // Cast the element pointer to BytePtrTy.
1437 if (EltPtr->getType() != BytePtrTy)
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001438 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001439
1440 // Cast the other pointer (if we have one) to BytePtrTy.
Mon P Wang20adc9d2010-04-04 03:10:48 +00001441 if (OtherElt && OtherElt->getType() != BytePtrTy) {
1442 // Preserve address space of OtherElt
1443 const PointerType* OtherPTy = cast<PointerType>(OtherElt->getType());
1444 const PointerType* PTy = cast<PointerType>(BytePtrTy);
1445 if (OtherPTy->getElementType() != PTy->getElementType()) {
1446 Type *NewOtherPTy = PointerType::get(PTy->getElementType(),
1447 OtherPTy->getAddressSpace());
1448 OtherElt = new BitCastInst(OtherElt, NewOtherPTy,
1449 OtherElt->getNameStr(), MI);
1450 }
1451 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001452
Duncan Sands777d2302009-05-09 07:06:46 +00001453 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001454
1455 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001456 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001457 Value *Ops[] = {
1458 SROADest ? EltPtr : OtherElt, // Dest ptr
1459 SROADest ? OtherElt : EltPtr, // Src ptr
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001460 ConstantInt::get(MI->getArgOperand(2)->getType(), EltSize), // Size
Owen Anderson1d0be152009-08-13 21:58:54 +00001461 // Align
Mon P Wang20adc9d2010-04-04 03:10:48 +00001462 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign),
1463 MI->getVolatileCst()
Chris Lattnerd93afec2009-01-07 07:18:45 +00001464 };
Mon P Wang20adc9d2010-04-04 03:10:48 +00001465 // In case we fold the address space overloaded memcpy of A to B
1466 // with memcpy of B to C, change the function to be a memcpy of A to C.
1467 const Type *Tys[] = { Ops[0]->getType(), Ops[1]->getType(),
1468 Ops[2]->getType() };
1469 Module *M = MI->getParent()->getParent()->getParent();
1470 TheFn = Intrinsic::getDeclaration(M, MI->getIntrinsicID(), Tys, 3);
1471 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001472 } else {
1473 assert(isa<MemSetInst>(MI));
1474 Value *Ops[] = {
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001475 EltPtr, MI->getArgOperand(1), // Dest, Value,
1476 ConstantInt::get(MI->getArgOperand(2)->getType(), EltSize), // Size
Mon P Wang20adc9d2010-04-04 03:10:48 +00001477 Zero, // Align
1478 ConstantInt::get(Type::getInt1Ty(MI->getContext()), 0) // isVolatile
Chris Lattnerd93afec2009-01-07 07:18:45 +00001479 };
Mon P Wang20adc9d2010-04-04 03:10:48 +00001480 const Type *Tys[] = { Ops[0]->getType(), Ops[2]->getType() };
1481 Module *M = MI->getParent()->getParent()->getParent();
1482 TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys, 2);
1483 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001484 }
Chris Lattner372dda82007-03-05 07:52:57 +00001485 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001486 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00001487}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001488
Bob Wilson39fdd692009-12-04 21:57:37 +00001489/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001490/// overwrites the entire allocation. Extract out the pieces of the stored
1491/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001492void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001493 SmallVector<AllocaInst*, 32> &NewElts){
1494 // Extract each element out of the integer according to its structure offset
1495 // and store the element value to the individual alloca.
1496 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00001497 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001498 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001499
Eli Friedman41b33f42009-06-01 09:14:32 +00001500 // Handle tail padding by extending the operand
1501 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001502 SrcVal = new ZExtInst(SrcVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001503 IntegerType::get(SI->getContext(), AllocaSizeBits),
1504 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001505
David Greene504c7d82010-01-05 01:27:09 +00001506 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00001507 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001508
1509 // There are two forms here: AI could be an array or struct. Both cases
1510 // have different ways to compute the element offset.
1511 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1512 const StructLayout *Layout = TD->getStructLayout(EltSTy);
1513
1514 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1515 // Get the number of bits to shift SrcVal to get the value.
1516 const Type *FieldTy = EltSTy->getElementType(i);
1517 uint64_t Shift = Layout->getElementOffsetInBits(i);
1518
1519 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00001520 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001521
1522 Value *EltVal = SrcVal;
1523 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001524 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001525 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1526 "sroa.store.elt", SI);
1527 }
1528
1529 // Truncate down to an integer of the right size.
1530 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +00001531
1532 // Ignore zero sized fields like {}, they obviously contain no data.
1533 if (FieldSizeBits == 0) continue;
1534
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001535 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001536 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001537 IntegerType::get(SI->getContext(), FieldSizeBits),
1538 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001539 Value *DestField = NewElts[i];
1540 if (EltVal->getType() == FieldTy) {
1541 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00001542 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001543 // Bitcast to the right element type (for fp/vector values).
1544 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
1545 } else {
1546 // Otherwise, bitcast the dest pointer (for aggregates).
1547 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001548 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001549 "", SI);
1550 }
1551 new StoreInst(EltVal, DestField, SI);
1552 }
1553
1554 } else {
1555 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1556 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001557 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001558 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1559
1560 uint64_t Shift;
1561
1562 if (TD->isBigEndian())
1563 Shift = AllocaSizeBits-ElementOffset;
1564 else
1565 Shift = 0;
1566
1567 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00001568 // Ignore zero sized fields like {}, they obviously contain no data.
1569 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001570
1571 Value *EltVal = SrcVal;
1572 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001573 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001574 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1575 "sroa.store.elt", SI);
1576 }
1577
1578 // Truncate down to an integer of the right size.
1579 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001580 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001581 IntegerType::get(SI->getContext(),
1582 ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001583 Value *DestField = NewElts[i];
1584 if (EltVal->getType() == ArrayEltTy) {
1585 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001586 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001587 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001588 // Bitcast to the right element type (for fp/vector values).
1589 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1590 } else {
1591 // Otherwise, bitcast the dest pointer (for aggregates).
1592 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001593 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001594 "", SI);
1595 }
1596 new StoreInst(EltVal, DestField, SI);
1597
1598 if (TD->isBigEndian())
1599 Shift -= ElementOffset;
1600 else
1601 Shift += ElementOffset;
1602 }
1603 }
1604
Bob Wilsonb742def2009-12-18 20:14:40 +00001605 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001606}
1607
Bob Wilson39fdd692009-12-04 21:57:37 +00001608/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001609/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001610void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001611 SmallVector<AllocaInst*, 32> &NewElts) {
1612 // Extract each element out of the NewElts according to its structure offset
1613 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00001614 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001615 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001616
David Greene504c7d82010-01-05 01:27:09 +00001617 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00001618 << '\n');
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001619
1620 // There are two forms here: AI could be an array or struct. Both cases
1621 // have different ways to compute the element offset.
1622 const StructLayout *Layout = 0;
1623 uint64_t ArrayEltBitOffset = 0;
1624 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1625 Layout = TD->getStructLayout(EltSTy);
1626 } else {
1627 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001628 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001629 }
Owen Andersone922c022009-07-22 00:24:57 +00001630
Owen Andersone922c022009-07-22 00:24:57 +00001631 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001632 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001633
1634 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1635 // Load the value from the alloca. If the NewElt is an aggregate, cast
1636 // the pointer to an integer of the same size before doing the load.
1637 Value *SrcField = NewElts[i];
1638 const Type *FieldTy =
1639 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001640 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1641
1642 // Ignore zero sized fields like {}, they obviously contain no data.
1643 if (FieldSizeBits == 0) continue;
1644
Owen Anderson1d0be152009-08-13 21:58:54 +00001645 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1646 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00001647 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1648 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001649 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001650 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001651 "", LI);
1652 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1653
1654 // If SrcField is a fp or vector of the right size but that isn't an
1655 // integer type, bitcast to an integer so we can shift it.
1656 if (SrcField->getType() != FieldIntTy)
1657 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1658
1659 // Zero extend the field to be the same size as the final alloca so that
1660 // we can shift and insert it.
1661 if (SrcField->getType() != ResultVal->getType())
1662 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1663
1664 // Determine the number of bits to shift SrcField.
1665 uint64_t Shift;
1666 if (Layout) // Struct case.
1667 Shift = Layout->getElementOffsetInBits(i);
1668 else // Array case.
1669 Shift = i*ArrayEltBitOffset;
1670
1671 if (TD->isBigEndian())
1672 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1673
1674 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001675 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001676 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1677 }
1678
Chris Lattner14952472010-06-27 07:58:26 +00001679 // Don't create an 'or x, 0' on the first iteration.
1680 if (!isa<Constant>(ResultVal) ||
1681 !cast<Constant>(ResultVal)->isNullValue())
1682 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1683 else
1684 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001685 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001686
1687 // Handle tail padding by truncating the result
1688 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1689 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1690
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001691 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00001692 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001693}
1694
Duncan Sands3cb36502007-11-04 14:43:57 +00001695/// HasPadding - Return true if the specified type has any structure or
1696/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001697static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner91abace2010-09-01 05:14:33 +00001698 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
1699 return HasPadding(ATy->getElementType(), TD);
1700
1701 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
1702 return HasPadding(VTy->getElementType(), TD);
1703
Chris Lattner39a1c042007-05-30 06:11:23 +00001704 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1705 const StructLayout *SL = TD.getStructLayout(STy);
1706 unsigned PrevFieldBitOffset = 0;
1707 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001708 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1709
Chris Lattner39a1c042007-05-30 06:11:23 +00001710 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001711 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001712 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001713
Chris Lattner39a1c042007-05-30 06:11:23 +00001714 // Check to see if there is any padding between this element and the
1715 // previous one.
1716 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001717 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001718 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1719 if (PrevFieldEnd < FieldBitOffset)
1720 return true;
1721 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001722
Chris Lattner39a1c042007-05-30 06:11:23 +00001723 PrevFieldBitOffset = FieldBitOffset;
1724 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001725
Chris Lattner39a1c042007-05-30 06:11:23 +00001726 // Check for tail padding.
1727 if (unsigned EltCount = STy->getNumElements()) {
1728 unsigned PrevFieldEnd = PrevFieldBitOffset +
1729 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001730 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001731 return true;
1732 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001733 }
Chris Lattner91abace2010-09-01 05:14:33 +00001734
Duncan Sands777d2302009-05-09 07:06:46 +00001735 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001736}
Chris Lattner372dda82007-03-05 07:52:57 +00001737
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001738/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1739/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1740/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001741bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001742 // Loop over the use list of the alloca. We can only transform it if all of
1743 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001744 AllocaInfo Info;
1745
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001746 isSafeForScalarRepl(AI, AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001747 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00001748 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001749 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001750 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001751
1752 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1753 // source and destination, we have to be careful. In particular, the memcpy
1754 // could be moving around elements that live in structure padding of the LLVM
1755 // types, but may actually be used. In these cases, we refuse to promote the
1756 // struct.
1757 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001758 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001759 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00001760
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001761 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00001762}
Chris Lattnera1888942005-12-12 07:19:13 +00001763
Chris Lattner800de312008-02-29 07:03:13 +00001764
Chris Lattner79b3bd32007-04-25 06:40:51 +00001765
1766/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1767/// some part of a constant global variable. This intentionally only accepts
1768/// constant expressions because we don't can't rewrite arbitrary instructions.
1769static bool PointsToConstantGlobal(Value *V) {
1770 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1771 return GV->isConstant();
1772 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1773 if (CE->getOpcode() == Instruction::BitCast ||
1774 CE->getOpcode() == Instruction::GetElementPtr)
1775 return PointsToConstantGlobal(CE->getOperand(0));
1776 return false;
1777}
1778
1779/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1780/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1781/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1782/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1783/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1784/// the alloca, and if the source pointer is a pointer to a constant global, we
1785/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00001786static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00001787 bool isOffset) {
1788 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00001789 User *U = cast<Instruction>(*UI);
1790
1791 if (LoadInst *LI = dyn_cast<LoadInst>(U))
Chris Lattner6e733d32009-01-28 20:16:43 +00001792 // Ignore non-volatile loads, they are always ok.
1793 if (!LI->isVolatile())
1794 continue;
1795
Gabor Greif8a8a4352010-04-06 19:32:30 +00001796 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001797 // If uses of the bitcast are ok, we are ok.
1798 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1799 return false;
1800 continue;
1801 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00001802 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001803 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1804 // doesn't, it does.
1805 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1806 isOffset || !GEP->hasAllZeroIndices()))
1807 return false;
1808 continue;
1809 }
1810
1811 // If this is isn't our memcpy/memmove, reject it as something we can't
1812 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00001813 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
1814 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00001815 return false;
1816
1817 // If we already have seen a copy, reject the second one.
1818 if (TheCopy) return false;
1819
1820 // If the pointer has been offset from the start of the alloca, we can't
1821 // safely handle this.
1822 if (isOffset) return false;
1823
1824 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00001825 if (UI.getOperandNo() != 0) return false;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001826
Chris Lattner79b3bd32007-04-25 06:40:51 +00001827 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00001828 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001829 return false;
1830
1831 // Otherwise, the transform is safe. Remember the copy instruction.
1832 TheCopy = MI;
1833 }
1834 return true;
1835}
1836
1837/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1838/// modified by a copy from a constant global. If we can prove this, we can
1839/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00001840MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1841 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001842 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1843 return TheCopy;
1844 return 0;
1845}