blob: 33ecb5bf9bdf7d2ad73726edf0d9cf3bbd65ac52 [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 Andersond13db2c2010-07-21 22:09:45 +0000138INITIALIZE_PASS(SROA, "scalarrepl",
139 "Scalar Replacement of Aggregates", false, false);
Dan Gohman844731a2008-05-13 00:00:25 +0000140
Brian Gaeked0fde302003-11-11 22:41:34 +0000141// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000142FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
143 return new SROA(Threshold);
144}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000145
146
Chris Lattner4cc576b2010-04-16 00:24:57 +0000147//===----------------------------------------------------------------------===//
148// Convert To Scalar Optimization.
149//===----------------------------------------------------------------------===//
150
151namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000152/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
153/// optimization, which scans the uses of an alloca and determines if it can
154/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000155class ConvertToScalarInfo {
156 /// AllocaSize - The size of the alloca being considered.
157 unsigned AllocaSize;
158 const TargetData &TD;
159
Chris Lattnera0bada72010-04-16 02:32:17 +0000160 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000161 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000162 bool IsNotTrivial;
Chris Lattnera001b662010-04-16 00:38:19 +0000163
164 /// VectorTy - This tracks the type that we should promote the vector to if
165 /// it is possible to turn it into a vector. This starts out null, and if it
166 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000167 const Type *VectorTy;
Chris Lattnera001b662010-04-16 00:38:19 +0000168
169 /// HadAVector - True if there is at least one vector access to the alloca.
170 /// We don't want to turn random arrays into vectors and use vector element
171 /// insert/extract, but if there are element accesses to something that is
172 /// also declared as a vector, we do want to promote to a vector.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000173 bool HadAVector;
174
175public:
176 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
177 : AllocaSize(Size), TD(td) {
178 IsNotTrivial = false;
179 VectorTy = 0;
180 HadAVector = false;
181 }
182
Chris Lattnera001b662010-04-16 00:38:19 +0000183 AllocaInst *TryConvert(AllocaInst *AI);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000184
185private:
186 bool CanConvertToScalar(Value *V, uint64_t Offset);
187 void MergeInType(const Type *In, uint64_t Offset);
188 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
189
190 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
191 uint64_t Offset, IRBuilder<> &Builder);
192 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
193 uint64_t Offset, IRBuilder<> &Builder);
194};
195} // end anonymous namespace.
196
Chris Lattner91abace2010-09-01 05:14:33 +0000197
198/// IsVerbotenVectorType - Return true if this is a vector type ScalarRepl isn't
199/// allowed to form. We do this to avoid MMX types, which is a complete hack,
200/// but is required until the backend is fixed.
Chris Lattner72eaa0e2010-09-01 23:09:27 +0000201static bool IsVerbotenVectorType(const VectorType *VTy, const Instruction *I) {
202 StringRef Triple(I->getParent()->getParent()->getParent()->getTargetTriple());
203 if (!Triple.startswith("i386") &&
204 !Triple.startswith("x86_64"))
205 return false;
206
Chris Lattner91abace2010-09-01 05:14:33 +0000207 // Reject all the MMX vector types.
208 switch (VTy->getNumElements()) {
209 default: return false;
210 case 1: return VTy->getElementType()->isIntegerTy(64);
211 case 2: return VTy->getElementType()->isIntegerTy(32);
212 case 4: return VTy->getElementType()->isIntegerTy(16);
213 case 8: return VTy->getElementType()->isIntegerTy(8);
214 }
215}
216
217
Chris Lattnera001b662010-04-16 00:38:19 +0000218/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
219/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
220/// alloca if possible or null if not.
221AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
222 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
223 // out.
224 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
225 return 0;
226
227 // If we were able to find a vector type that can handle this with
228 // insert/extract elements, and if there was at least one use that had
229 // a vector type, promote this to a vector. We don't want to promote
230 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
231 // we just get a lot of insert/extracts. If at least one vector is
232 // involved, then we probably really do have a union of vector/array.
233 const Type *NewTy;
Chris Lattner91abace2010-09-01 05:14:33 +0000234 if (VectorTy && VectorTy->isVectorTy() && HadAVector &&
Chris Lattner72eaa0e2010-09-01 23:09:27 +0000235 !IsVerbotenVectorType(cast<VectorType>(VectorTy), AI)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000236 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
237 << *VectorTy << '\n');
238 NewTy = VectorTy; // Use the vector type.
239 } else {
240 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
241 // Create and insert the integer alloca.
242 NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
243 }
244 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
245 ConvertUsesToScalar(AI, NewAI, 0);
246 return NewAI;
247}
248
249/// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
250/// so far at the offset specified by Offset (which is specified in bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000251///
252/// There are two cases we handle here:
253/// 1) A union of vector types of the same size and potentially its elements.
254/// Here we turn element accesses into insert/extract element operations.
255/// This promotes a <4 x float> with a store of float to the third element
256/// into a <4 x float> that uses insert element.
257/// 2) A fully general blob of memory, which we turn into some (potentially
258/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000259/// and stores would mutate the memory. We mark this by setting VectorTy
260/// to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000261void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000262 // If we already decided to turn this into a blob of integer memory, there is
263 // nothing to be done.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000264 if (VectorTy && VectorTy->isVoidTy())
265 return;
266
267 // If this could be contributing to a vector, analyze it.
268
269 // If the In type is a vector that is the same size as the alloca, see if it
270 // matches the existing VecTy.
271 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000272 // Remember if we saw a vector type.
273 HadAVector = true;
274
Chris Lattner4cc576b2010-04-16 00:24:57 +0000275 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
276 // If we're storing/loading a vector of the right size, allow it as a
277 // vector. If this the first vector we see, remember the type so that
Chris Lattnera001b662010-04-16 00:38:19 +0000278 // we know the element size. If this is a subsequent access, ignore it
279 // even if it is a differing type but the same size. Worst case we can
280 // bitcast the resultant vectors.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000281 if (VectorTy == 0)
282 VectorTy = VInTy;
283 return;
284 }
285 } else if (In->isFloatTy() || In->isDoubleTy() ||
286 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
287 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
288 // If we're accessing something that could be an element of a vector, see
289 // if the implied vector agrees with what we already have and if Offset is
290 // compatible with it.
291 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
292 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
293 (VectorTy == 0 ||
294 cast<VectorType>(VectorTy)->getElementType()
295 ->getPrimitiveSizeInBits()/8 == EltSize)) {
296 if (VectorTy == 0)
297 VectorTy = VectorType::get(In, AllocaSize/EltSize);
298 return;
299 }
300 }
301
302 // Otherwise, we have a case that we can't handle with an optimized vector
303 // form. We can still turn this into a large integer.
304 VectorTy = Type::getVoidTy(In->getContext());
305}
306
307/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
308/// its accesses to a single vector type, return true and set VecTy to
309/// the new type. If we could convert the alloca into a single promotable
310/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
311/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
312/// is the current offset from the base of the alloca being analyzed.
313///
314/// If we see at least one access to the value that is as a vector type, set the
315/// SawVec flag.
316bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
317 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
318 Instruction *User = cast<Instruction>(*UI);
319
320 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
321 // Don't break volatile loads.
322 if (LI->isVolatile())
323 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000324 // Don't touch MMX operations.
325 if (LI->getType()->isX86_MMXTy())
326 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000327 MergeInType(LI->getType(), Offset);
328 continue;
329 }
330
331 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
332 // Storing the pointer, not into the value?
333 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000334 // Don't touch MMX operations.
335 if (SI->getOperand(0)->getType()->isX86_MMXTy())
336 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000337 MergeInType(SI->getOperand(0)->getType(), Offset);
338 continue;
339 }
340
341 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000342 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000343 if (!CanConvertToScalar(BCI, Offset))
344 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000345 continue;
346 }
347
348 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
349 // If this is a GEP with a variable indices, we can't handle it.
350 if (!GEP->hasAllConstantIndices())
351 return false;
352
353 // Compute the offset that this GEP adds to the pointer.
354 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
355 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
356 &Indices[0], Indices.size());
357 // See if all uses can be converted.
358 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
359 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000360 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000361 continue;
362 }
363
364 // If this is a constant sized memset of a constant value (e.g. 0) we can
365 // handle it.
366 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
367 // Store of constant value and constant size.
Chris Lattnera001b662010-04-16 00:38:19 +0000368 if (!isa<ConstantInt>(MSI->getValue()) ||
369 !isa<ConstantInt>(MSI->getLength()))
370 return false;
371 IsNotTrivial = true; // Can't be mem2reg'd.
372 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000373 }
374
375 // If this is a memcpy or memmove into or out of the whole allocation, we
376 // can handle it like a load or store of the scalar type.
377 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000378 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
379 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
380 return false;
381
382 IsNotTrivial = true; // Can't be mem2reg'd.
383 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000384 }
385
386 // Otherwise, we cannot handle this!
387 return false;
388 }
389
390 return true;
391}
392
393/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
394/// directly. This happens when we are converting an "integer union" to a
395/// single integer scalar, or when we are converting a "vector union" to a
396/// vector with insert/extractelement instructions.
397///
398/// Offset is an offset from the original alloca, in bits that need to be
399/// shifted to the right. By the end of this, there should be no uses of Ptr.
400void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
401 uint64_t Offset) {
402 while (!Ptr->use_empty()) {
403 Instruction *User = cast<Instruction>(Ptr->use_back());
404
405 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
406 ConvertUsesToScalar(CI, NewAI, Offset);
407 CI->eraseFromParent();
408 continue;
409 }
410
411 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
412 // Compute the offset that this GEP adds to the pointer.
413 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
414 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
415 &Indices[0], Indices.size());
416 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
417 GEP->eraseFromParent();
418 continue;
419 }
420
421 IRBuilder<> Builder(User->getParent(), User);
422
423 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
424 // The load is a bit extract from NewAI shifted right by Offset bits.
425 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
426 Value *NewLoadVal
427 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
428 LI->replaceAllUsesWith(NewLoadVal);
429 LI->eraseFromParent();
430 continue;
431 }
432
433 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
434 assert(SI->getOperand(0) != Ptr && "Consistency error!");
435 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
436 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
437 Builder);
438 Builder.CreateStore(New, NewAI);
439 SI->eraseFromParent();
440
441 // If the load we just inserted is now dead, then the inserted store
442 // overwrote the entire thing.
443 if (Old->use_empty())
444 Old->eraseFromParent();
445 continue;
446 }
447
448 // If this is a constant sized memset of a constant value (e.g. 0) we can
449 // transform it into a store of the expanded constant value.
450 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
451 assert(MSI->getRawDest() == Ptr && "Consistency error!");
452 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
453 if (NumBytes != 0) {
454 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
455
456 // Compute the value replicated the right number of times.
457 APInt APVal(NumBytes*8, Val);
458
459 // Splat the value if non-zero.
460 if (Val)
461 for (unsigned i = 1; i != NumBytes; ++i)
462 APVal |= APVal << 8;
463
464 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
465 Value *New = ConvertScalar_InsertValue(
466 ConstantInt::get(User->getContext(), APVal),
467 Old, Offset, Builder);
468 Builder.CreateStore(New, NewAI);
469
470 // If the load we just inserted is now dead, then the memset overwrote
471 // the entire thing.
472 if (Old->use_empty())
473 Old->eraseFromParent();
474 }
475 MSI->eraseFromParent();
476 continue;
477 }
478
479 // If this is a memcpy or memmove into or out of the whole allocation, we
480 // can handle it like a load or store of the scalar type.
481 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
482 assert(Offset == 0 && "must be store to start of alloca");
483
484 // If the source and destination are both to the same alloca, then this is
485 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
486 // as appropriate.
487 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject(0));
488
489 if (MTI->getSource()->getUnderlyingObject(0) != OrigAI) {
490 // Dest must be OrigAI, change this to be a load from the original
491 // pointer (bitcasted), then a store to our new alloca.
492 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
493 Value *SrcPtr = MTI->getSource();
494 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
495
496 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
497 SrcVal->setAlignment(MTI->getAlignment());
498 Builder.CreateStore(SrcVal, NewAI);
499 } else if (MTI->getDest()->getUnderlyingObject(0) != OrigAI) {
500 // Src must be OrigAI, change this to be a load from NewAI then a store
501 // through the original dest pointer (bitcasted).
502 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
503 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
504
505 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
506 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
507 NewStore->setAlignment(MTI->getAlignment());
508 } else {
509 // Noop transfer. Src == Dst
510 }
511
512 MTI->eraseFromParent();
513 continue;
514 }
515
516 llvm_unreachable("Unsupported operation!");
517 }
518}
519
520/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
521/// or vector value FromVal, extracting the bits from the offset specified by
522/// Offset. This returns the value, which is of type ToType.
523///
524/// This happens when we are converting an "integer union" to a single
525/// integer scalar, or when we are converting a "vector union" to a vector with
526/// insert/extractelement instructions.
527///
528/// Offset is an offset from the original alloca, in bits that need to be
529/// shifted to the right.
530Value *ConvertToScalarInfo::
531ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
532 uint64_t Offset, IRBuilder<> &Builder) {
533 // If the load is of the whole new alloca, no conversion is needed.
534 if (FromVal->getType() == ToType && Offset == 0)
535 return FromVal;
536
537 // If the result alloca is a vector type, this is either an element
538 // access or a bitcast to another vector type of the same size.
539 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
540 if (ToType->isVectorTy())
541 return Builder.CreateBitCast(FromVal, ToType, "tmp");
542
543 // Otherwise it must be an element access.
544 unsigned Elt = 0;
545 if (Offset) {
546 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
547 Elt = Offset/EltSize;
548 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
549 }
550 // Return the element extracted out of it.
551 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
552 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
553 if (V->getType() != ToType)
554 V = Builder.CreateBitCast(V, ToType, "tmp");
555 return V;
556 }
557
558 // If ToType is a first class aggregate, extract out each of the pieces and
559 // use insertvalue's to form the FCA.
560 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
561 const StructLayout &Layout = *TD.getStructLayout(ST);
562 Value *Res = UndefValue::get(ST);
563 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
564 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
565 Offset+Layout.getElementOffsetInBits(i),
566 Builder);
567 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
568 }
569 return Res;
570 }
571
572 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
573 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
574 Value *Res = UndefValue::get(AT);
575 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
576 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
577 Offset+i*EltSize, Builder);
578 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
579 }
580 return Res;
581 }
582
583 // Otherwise, this must be a union that was converted to an integer value.
584 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
585
586 // If this is a big-endian system and the load is narrower than the
587 // full alloca type, we need to do a shift to get the right bits.
588 int ShAmt = 0;
589 if (TD.isBigEndian()) {
590 // On big-endian machines, the lowest bit is stored at the bit offset
591 // from the pointer given by getTypeStoreSizeInBits. This matters for
592 // integers with a bitwidth that is not a multiple of 8.
593 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
594 TD.getTypeStoreSizeInBits(ToType) - Offset;
595 } else {
596 ShAmt = Offset;
597 }
598
599 // Note: we support negative bitwidths (with shl) which are not defined.
600 // We do this to support (f.e.) loads off the end of a structure where
601 // only some bits are used.
602 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
603 FromVal = Builder.CreateLShr(FromVal,
604 ConstantInt::get(FromVal->getType(),
605 ShAmt), "tmp");
606 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
607 FromVal = Builder.CreateShl(FromVal,
608 ConstantInt::get(FromVal->getType(),
609 -ShAmt), "tmp");
610
611 // Finally, unconditionally truncate the integer to the right width.
612 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
613 if (LIBitWidth < NTy->getBitWidth())
614 FromVal =
615 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
616 LIBitWidth), "tmp");
617 else if (LIBitWidth > NTy->getBitWidth())
618 FromVal =
619 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
620 LIBitWidth), "tmp");
621
622 // If the result is an integer, this is a trunc or bitcast.
623 if (ToType->isIntegerTy()) {
624 // Should be done.
625 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
626 // Just do a bitcast, we know the sizes match up.
627 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
628 } else {
629 // Otherwise must be a pointer.
630 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
631 }
632 assert(FromVal->getType() == ToType && "Didn't convert right?");
633 return FromVal;
634}
635
636/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
637/// or vector value "Old" at the offset specified by Offset.
638///
639/// This happens when we are converting an "integer union" to a
640/// single integer scalar, or when we are converting a "vector union" to a
641/// vector with insert/extractelement instructions.
642///
643/// Offset is an offset from the original alloca, in bits that need to be
644/// shifted to the right.
645Value *ConvertToScalarInfo::
646ConvertScalar_InsertValue(Value *SV, Value *Old,
647 uint64_t Offset, IRBuilder<> &Builder) {
648 // Convert the stored type to the actual type, shift it left to insert
649 // then 'or' into place.
650 const Type *AllocaType = Old->getType();
651 LLVMContext &Context = Old->getContext();
652
653 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
654 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
655 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
656
657 // Changing the whole vector with memset or with an access of a different
658 // vector type?
659 if (ValSize == VecSize)
660 return Builder.CreateBitCast(SV, AllocaType, "tmp");
661
662 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
663
664 // Must be an element insertion.
665 unsigned Elt = Offset/EltSize;
666
667 if (SV->getType() != VTy->getElementType())
668 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
669
670 SV = Builder.CreateInsertElement(Old, SV,
671 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
672 "tmp");
673 return SV;
674 }
675
676 // If SV is a first-class aggregate value, insert each value recursively.
677 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
678 const StructLayout &Layout = *TD.getStructLayout(ST);
679 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
680 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
681 Old = ConvertScalar_InsertValue(Elt, Old,
682 Offset+Layout.getElementOffsetInBits(i),
683 Builder);
684 }
685 return Old;
686 }
687
688 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
689 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
690 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
691 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
692 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
693 }
694 return Old;
695 }
696
697 // If SV is a float, convert it to the appropriate integer type.
698 // If it is a pointer, do the same.
699 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
700 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
701 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
702 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
703 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
704 SV = Builder.CreateBitCast(SV,
705 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
706 else if (SV->getType()->isPointerTy())
707 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
708
709 // Zero extend or truncate the value if needed.
710 if (SV->getType() != AllocaType) {
711 if (SV->getType()->getPrimitiveSizeInBits() <
712 AllocaType->getPrimitiveSizeInBits())
713 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
714 else {
715 // Truncation may be needed if storing more than the alloca can hold
716 // (undefined behavior).
717 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
718 SrcWidth = DestWidth;
719 SrcStoreWidth = DestStoreWidth;
720 }
721 }
722
723 // If this is a big-endian system and the store is narrower than the
724 // full alloca type, we need to do a shift to get the right bits.
725 int ShAmt = 0;
726 if (TD.isBigEndian()) {
727 // On big-endian machines, the lowest bit is stored at the bit offset
728 // from the pointer given by getTypeStoreSizeInBits. This matters for
729 // integers with a bitwidth that is not a multiple of 8.
730 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
731 } else {
732 ShAmt = Offset;
733 }
734
735 // Note: we support negative bitwidths (with shr) which are not defined.
736 // We do this to support (f.e.) stores off the end of a structure where
737 // only some bits in the structure are set.
738 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
739 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
740 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
741 ShAmt), "tmp");
742 Mask <<= ShAmt;
743 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
744 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
745 -ShAmt), "tmp");
746 Mask = Mask.lshr(-ShAmt);
747 }
748
749 // Mask out the bits we are about to insert from the old value, and or
750 // in the new bits.
751 if (SrcWidth != DestWidth) {
752 assert(DestWidth > SrcWidth);
753 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
754 SV = Builder.CreateOr(Old, SV, "ins");
755 }
756 return SV;
757}
758
759
760//===----------------------------------------------------------------------===//
761// SRoA Driver
762//===----------------------------------------------------------------------===//
763
764
Chris Lattnered7b41e2003-05-27 15:45:27 +0000765bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000766 TD = getAnalysisIfAvailable<TargetData>();
767
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000768 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000769
770 // FIXME: ScalarRepl currently depends on TargetData more than it
771 // theoretically needs to. It should be refactored in order to support
772 // target-independent IR. Until this is done, just skip the actual
773 // scalar-replacement portion of this pass.
774 if (!TD) return Changed;
775
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000776 while (1) {
777 bool LocalChange = performScalarRepl(F);
778 if (!LocalChange) break; // No need to repromote if no scalarrepl
779 Changed = true;
780 LocalChange = performPromotion(F);
781 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
782 }
Chris Lattner38aec322003-09-11 16:45:55 +0000783
784 return Changed;
785}
786
787
788bool SROA::performPromotion(Function &F) {
789 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000790 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000791 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000792
Chris Lattner02a3be02003-09-20 14:39:18 +0000793 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000794
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000795 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000796
Chris Lattner38aec322003-09-11 16:45:55 +0000797 while (1) {
798 Allocas.clear();
799
800 // Find allocas that are safe to promote, by looking at all instructions in
801 // the entry node
802 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
803 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000804 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000805 Allocas.push_back(AI);
806
807 if (Allocas.empty()) break;
808
Nick Lewyckyce2c51b2009-11-23 03:50:44 +0000809 PromoteMemToReg(Allocas, DT, DF);
Chris Lattner38aec322003-09-11 16:45:55 +0000810 NumPromoted += Allocas.size();
811 Changed = true;
812 }
813
814 return Changed;
815}
816
Chris Lattner4cc576b2010-04-16 00:24:57 +0000817
Bob Wilson3992feb2010-02-03 17:23:56 +0000818/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
819/// SROA. It must be a struct or array type with a small number of elements.
820static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
821 const Type *T = AI->getAllocatedType();
822 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +0000823 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +0000824 return ST->getNumElements() <= 32;
825 // Arrays are much less likely to be safe for SROA; only consider
826 // them if they are very small.
827 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
828 return AT->getNumElements() <= 8;
829 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +0000830}
831
Chris Lattnerc4472072010-04-15 23:50:26 +0000832
Chris Lattner38aec322003-09-11 16:45:55 +0000833// performScalarRepl - This algorithm is a simple worklist driven algorithm,
834// which runs on all of the malloc/alloca instructions in the function, removing
835// them if they are only used by getelementptr instructions.
836//
837bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000838 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000839
Chris Lattner31d80102010-04-15 21:59:20 +0000840 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +0000841 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000842 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000843 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000844 WorkList.push_back(A);
845
846 // Process the worklist
847 bool Changed = false;
848 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000849 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000850 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000851
Chris Lattneradd2bd72006-12-22 23:14:42 +0000852 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
853 // with unused elements.
854 if (AI->use_empty()) {
855 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +0000856 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +0000857 continue;
858 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000859
860 // If this alloca is impossible for us to promote, reject it early.
861 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
862 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000863
864 // Check to see if this allocation is only modified by a memcpy/memmove from
865 // a constant global. If this is the case, we can change all users to use
866 // the constant global instead. This is commonly produced by the CFE by
867 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
868 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +0000869 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +0000870 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
871 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +0000872 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +0000873 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000874 TheCopy->eraseFromParent(); // Don't mutate the global.
875 AI->eraseFromParent();
876 ++NumGlobals;
877 Changed = true;
878 continue;
879 }
Chris Lattner15c82772009-02-02 20:44:45 +0000880
Chris Lattner7809ecd2009-02-03 01:30:09 +0000881 // Check to see if we can perform the core SROA transformation. We cannot
882 // transform the allocation instruction if it is an array allocation
883 // (allocations OF arrays are ok though), and an allocation of a scalar
884 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000885 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000886
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000887 // Do not promote [0 x %struct].
888 if (AllocaSize == 0) continue;
Chris Lattner31d80102010-04-15 21:59:20 +0000889
890 // Do not promote any struct whose size is too big.
891 if (AllocaSize > SRThreshold) continue;
892
Bob Wilson3992feb2010-02-03 17:23:56 +0000893 // If the alloca looks like a good candidate for scalar replacement, and if
894 // all its users can be transformed, then split up the aggregate into its
895 // separate elements.
896 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
897 DoScalarReplacement(AI, WorkList);
898 Changed = true;
899 continue;
900 }
901
Chris Lattner6e733d32009-01-28 20:16:43 +0000902 // If we can turn this aggregate value (potentially with casts) into a
903 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000904 // IsNotTrivial tracks whether this is something that mem2reg could have
905 // promoted itself. If so, we don't want to transform it needlessly. Note
906 // that we can't just check based on the type: the alloca may be of an i32
907 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +0000908 if (AllocaInst *NewAI =
909 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000910 NewAI->takeName(AI);
911 AI->eraseFromParent();
912 ++NumConverted;
913 Changed = true;
914 continue;
Chris Lattner593375d2010-04-16 00:20:00 +0000915 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000916
Chris Lattner7809ecd2009-02-03 01:30:09 +0000917 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000918 }
919
920 return Changed;
921}
Chris Lattner5e062a12003-05-30 04:15:41 +0000922
Chris Lattnera10b29b2007-04-25 05:02:56 +0000923/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
924/// predicate, do SROA now.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000925void SROA::DoScalarReplacement(AllocaInst *AI,
926 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +0000927 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +0000928 SmallVector<AllocaInst*, 32> ElementAllocas;
929 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
930 ElementAllocas.reserve(ST->getNumContainedTypes());
931 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000932 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +0000933 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000934 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000935 ElementAllocas.push_back(NA);
936 WorkList.push_back(NA); // Add to worklist for recursive processing
937 }
938 } else {
939 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
940 ElementAllocas.reserve(AT->getNumElements());
941 const Type *ElTy = AT->getElementType();
942 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000943 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000944 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000945 ElementAllocas.push_back(NA);
946 WorkList.push_back(NA); // Add to worklist for recursive processing
947 }
948 }
949
Bob Wilsonb742def2009-12-18 20:14:40 +0000950 // Now that we have created the new alloca instructions, rewrite all the
951 // uses of the old alloca.
952 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +0000953
Bob Wilsonb742def2009-12-18 20:14:40 +0000954 // Now erase any instructions that were made dead while rewriting the alloca.
955 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +0000956 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +0000957
Dan Gohmanfe601042010-06-22 15:08:57 +0000958 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +0000959}
Chris Lattnera59adc42009-12-14 05:11:02 +0000960
Bob Wilsonb742def2009-12-18 20:14:40 +0000961/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
962/// recursively including all their operands that become trivially dead.
963void SROA::DeleteDeadInstructions() {
964 while (!DeadInsts.empty()) {
965 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +0000966
Bob Wilsonb742def2009-12-18 20:14:40 +0000967 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
968 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
969 // Zero out the operand and see if it becomes trivially dead.
970 // (But, don't add allocas to the dead instruction list -- they are
971 // already on the worklist and will be deleted separately.)
972 *OI = 0;
973 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
974 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +0000975 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000976
977 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +0000978 }
Chris Lattnera59adc42009-12-14 05:11:02 +0000979}
Bob Wilsonb742def2009-12-18 20:14:40 +0000980
Bob Wilsonb742def2009-12-18 20:14:40 +0000981/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
982/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000983/// the Info parameter. Offset indicates the position within AI that is
984/// referenced by this instruction.
Bob Wilsonb742def2009-12-18 20:14:40 +0000985void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000986 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000987 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
988 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000989
Bob Wilsonb742def2009-12-18 20:14:40 +0000990 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000991 isSafeForScalarRepl(BC, AI, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000992 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000993 uint64_t GEPOffset = Offset;
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000994 isSafeGEP(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000995 if (!Info.isUnsafe)
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000996 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +0000997 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000998 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
999 if (Length)
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001000 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
Gabor Greifa6aac4c2010-07-16 09:38:02 +00001001 UI.getOperandNo() == 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001002 else
1003 MarkUnsafe(Info);
1004 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1005 if (!LI->isVolatile()) {
1006 const Type *LIType = LI->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001007 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
Bob Wilsonb742def2009-12-18 20:14:40 +00001008 LIType, false, Info);
1009 } else
1010 MarkUnsafe(Info);
1011 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1012 // Store is ok if storing INTO the pointer, not storing the pointer
1013 if (!SI->isVolatile() && SI->getOperand(0) != I) {
1014 const Type *SIType = SI->getOperand(0)->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001015 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
Bob Wilsonb742def2009-12-18 20:14:40 +00001016 SIType, true, Info);
1017 } else
1018 MarkUnsafe(Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001019 } else {
1020 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
1021 MarkUnsafe(Info);
1022 }
1023 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001024 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001025}
Bob Wilson39c88a62009-12-17 18:34:24 +00001026
Bob Wilsonb742def2009-12-18 20:14:40 +00001027/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1028/// replacement. It is safe when all the indices are constant, in-bounds
1029/// references, and when the resulting offset corresponds to an element within
1030/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001031/// return, Offset is adjusted as specified by the GEP indices.
Bob Wilsonb742def2009-12-18 20:14:40 +00001032void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001033 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001034 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1035 if (GEPIt == E)
1036 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001037
Chris Lattner88e6dc82008-08-23 05:21:06 +00001038 // Walk through the GEP type indices, checking the types that this indexes
1039 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001040 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001041 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001042 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001043 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001044
Bob Wilsonb742def2009-12-18 20:14:40 +00001045 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1046 if (!IdxVal)
1047 return MarkUnsafe(Info);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001048 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001049
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001050 // Compute the offset due to this GEP and check if the alloca has a
1051 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001052 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1053 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1054 &Indices[0], Indices.size());
Bob Wilsonb742def2009-12-18 20:14:40 +00001055 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
1056 MarkUnsafe(Info);
Chris Lattner5e062a12003-05-30 04:15:41 +00001057}
1058
Bob Wilsonb742def2009-12-18 20:14:40 +00001059/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1060/// alloca or has an offset and size that corresponds to a component element
1061/// within it. The offset checked here may have been formed from a GEP with a
1062/// pointer bitcasted to a different type.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001063void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001064 const Type *MemOpType, bool isStore,
1065 AllocaInfo &Info) {
1066 // Check if this is a load/store of the entire alloca.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001067 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001068 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
1069 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
1070 // (which are essentially the same as the MemIntrinsics, especially with
1071 // regard to copying padding between elements), or references using the
1072 // aggregate type of the alloca.
Duncan Sands1df98592010-02-16 11:11:14 +00001073 if (!MemOpType || MemOpType->isIntegerTy() || UsesAggregateType) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001074 if (!UsesAggregateType) {
1075 if (isStore)
1076 Info.isMemCpyDst = true;
1077 else
1078 Info.isMemCpySrc = true;
1079 }
1080 return;
1081 }
1082 }
1083 // Check if the offset/size correspond to a component within the alloca type.
1084 const Type *T = AI->getAllocatedType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001085 if (TypeHasComponent(T, Offset, MemSize))
Bob Wilsonb742def2009-12-18 20:14:40 +00001086 return;
1087
1088 return MarkUnsafe(Info);
1089}
1090
1091/// TypeHasComponent - Return true if T has a component type with the
1092/// specified offset and size. If Size is zero, do not check the size.
1093bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1094 const Type *EltTy;
1095 uint64_t EltSize;
1096 if (const StructType *ST = dyn_cast<StructType>(T)) {
1097 const StructLayout *Layout = TD->getStructLayout(ST);
1098 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1099 EltTy = ST->getContainedType(EltIdx);
1100 EltSize = TD->getTypeAllocSize(EltTy);
1101 Offset -= Layout->getElementOffset(EltIdx);
1102 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1103 EltTy = AT->getElementType();
1104 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001105 if (Offset >= AT->getNumElements() * EltSize)
1106 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001107 Offset %= EltSize;
1108 } else {
1109 return false;
1110 }
1111 if (Offset == 0 && (Size == 0 || EltSize == Size))
1112 return true;
1113 // Check if the component spans multiple elements.
1114 if (Offset + Size > EltSize)
1115 return false;
1116 return TypeHasComponent(EltTy, Offset, Size);
1117}
1118
1119/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1120/// the instruction I, which references it, to use the separate elements.
1121/// Offset indicates the position within AI that is referenced by this
1122/// instruction.
1123void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1124 SmallVector<AllocaInst*, 32> &NewElts) {
1125 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1126 Instruction *User = cast<Instruction>(*UI);
1127
1128 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1129 RewriteBitCast(BC, AI, Offset, NewElts);
1130 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1131 RewriteGEP(GEPI, AI, Offset, NewElts);
1132 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1133 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1134 uint64_t MemSize = Length->getZExtValue();
1135 if (Offset == 0 &&
1136 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1137 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001138 // Otherwise the intrinsic can only touch a single element and the
1139 // address operand will be updated, so nothing else needs to be done.
Bob Wilsonb742def2009-12-18 20:14:40 +00001140 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1141 const Type *LIType = LI->getType();
1142 if (LIType == AI->getAllocatedType()) {
1143 // Replace:
1144 // %res = load { i32, i32 }* %alloc
1145 // with:
1146 // %load.0 = load i32* %alloc.0
1147 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1148 // %load.1 = load i32* %alloc.1
1149 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1150 // (Also works for arrays instead of structs)
1151 Value *Insert = UndefValue::get(LIType);
1152 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1153 Value *Load = new LoadInst(NewElts[i], "load", LI);
1154 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1155 }
1156 LI->replaceAllUsesWith(Insert);
1157 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001158 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001159 TD->getTypeAllocSize(LIType) ==
1160 TD->getTypeAllocSize(AI->getAllocatedType())) {
1161 // If this is a load of the entire alloca to an integer, rewrite it.
1162 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1163 }
1164 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1165 Value *Val = SI->getOperand(0);
1166 const Type *SIType = Val->getType();
1167 if (SIType == AI->getAllocatedType()) {
1168 // Replace:
1169 // store { i32, i32 } %val, { i32, i32 }* %alloc
1170 // with:
1171 // %val.0 = extractvalue { i32, i32 } %val, 0
1172 // store i32 %val.0, i32* %alloc.0
1173 // %val.1 = extractvalue { i32, i32 } %val, 1
1174 // store i32 %val.1, i32* %alloc.1
1175 // (Also works for arrays instead of structs)
1176 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1177 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1178 new StoreInst(Extract, NewElts[i], SI);
1179 }
1180 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001181 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001182 TD->getTypeAllocSize(SIType) ==
1183 TD->getTypeAllocSize(AI->getAllocatedType())) {
1184 // If this is a store of the entire alloca from an integer, rewrite it.
1185 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1186 }
1187 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001188 }
1189}
1190
Bob Wilsonb742def2009-12-18 20:14:40 +00001191/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1192/// and recursively continue updating all of its uses.
1193void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1194 SmallVector<AllocaInst*, 32> &NewElts) {
1195 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1196 if (BC->getOperand(0) != AI)
1197 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001198
Bob Wilsonb742def2009-12-18 20:14:40 +00001199 // The bitcast references the original alloca. Replace its uses with
1200 // references to the first new element alloca.
1201 Instruction *Val = NewElts[0];
1202 if (Val->getType() != BC->getDestTy()) {
1203 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1204 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001205 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001206 BC->replaceAllUsesWith(Val);
1207 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001208}
1209
Bob Wilsonb742def2009-12-18 20:14:40 +00001210/// FindElementAndOffset - Return the index of the element containing Offset
1211/// within the specified type, which must be either a struct or an array.
1212/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001213/// element. IdxTy is set to the type of the index result to be used in a
1214/// GEP instruction.
1215uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1216 const Type *&IdxTy) {
1217 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001218 if (const StructType *ST = dyn_cast<StructType>(T)) {
1219 const StructLayout *Layout = TD->getStructLayout(ST);
1220 Idx = Layout->getElementContainingOffset(Offset);
1221 T = ST->getContainedType(Idx);
1222 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001223 IdxTy = Type::getInt32Ty(T->getContext());
1224 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001225 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001226 const ArrayType *AT = cast<ArrayType>(T);
1227 T = AT->getElementType();
1228 uint64_t EltSize = TD->getTypeAllocSize(T);
1229 Idx = Offset / EltSize;
1230 Offset -= Idx * EltSize;
1231 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001232 return Idx;
1233}
1234
1235/// RewriteGEP - Check if this GEP instruction moves the pointer across
1236/// elements of the alloca that are being split apart, and if so, rewrite
1237/// the GEP to be relative to the new element.
1238void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1239 SmallVector<AllocaInst*, 32> &NewElts) {
1240 uint64_t OldOffset = Offset;
1241 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1242 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1243 &Indices[0], Indices.size());
1244
1245 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1246
1247 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00001248 const Type *IdxTy;
1249 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001250 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001251 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001252
1253 T = AI->getAllocatedType();
1254 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001255 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001256
1257 // If this GEP does not move the pointer across elements of the alloca
1258 // being split, then it does not needs to be rewritten.
1259 if (Idx == OldIdx)
1260 return;
1261
1262 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1263 SmallVector<Value*, 8> NewArgs;
1264 NewArgs.push_back(Constant::getNullValue(i32Ty));
1265 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001266 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1267 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00001268 }
1269 Instruction *Val = NewElts[Idx];
1270 if (NewArgs.size() > 1) {
1271 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1272 NewArgs.end(), "", GEPI);
1273 Val->takeName(GEPI);
1274 }
1275 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001276 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001277 GEPI->replaceAllUsesWith(Val);
1278 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001279}
1280
1281/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1282/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00001283void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001284 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00001285 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001286 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00001287 // appropriate type. The "Other" pointer is the pointer that goes to memory
1288 // that doesn't have anything to do with the alloca that we are promoting. For
1289 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00001290 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001291 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00001292 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00001293 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00001294 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001295 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00001296 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00001297 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001298 }
1299 }
Bob Wilson78c50b82009-12-08 18:22:03 +00001300
Chris Lattnerd93afec2009-01-07 07:18:45 +00001301 // If there is an other pointer, we want to convert it to the same pointer
1302 // type as AI has, so we can GEP through it safely.
1303 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00001304 unsigned AddrSpace =
1305 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00001306
1307 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
1308 // optimization, but it's also required to detect the corner case where
1309 // both pointer operands are referencing the same memory, and where
1310 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
1311 // function is only called for mem intrinsics that access the whole
1312 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00001313 OtherPtr = OtherPtr->stripPointerCasts();
1314
Bob Wilsona756b1d2010-01-19 04:32:48 +00001315 // Copying the alloca to itself is a no-op: just delete it.
1316 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1317 // This code will run twice for a no-op memcpy -- once for each operand.
1318 // Put only one reference to MI on the DeadInsts list.
1319 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1320 E = DeadInsts.end(); I != E; ++I)
1321 if (*I == MI) return;
1322 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001323 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00001324 }
Chris Lattner372dda82007-03-05 07:52:57 +00001325
Chris Lattnerd93afec2009-01-07 07:18:45 +00001326 // If the pointer is not the right type, insert a bitcast to the right
1327 // type.
Chris Lattner0238f8c2010-07-08 00:27:05 +00001328 const Type *NewTy =
1329 PointerType::get(AI->getType()->getElementType(), AddrSpace);
1330
1331 if (OtherPtr->getType() != NewTy)
1332 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001333 }
1334
1335 // Process each element of the aggregate.
Gabor Greifa9b23132010-04-20 13:13:04 +00001336 Value *TheFn = MI->getCalledValue();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001337 const Type *BytePtrTy = MI->getRawDest()->getType();
Bob Wilsonb742def2009-12-18 20:14:40 +00001338 bool SROADest = MI->getRawDest() == Inst;
Chris Lattnerd93afec2009-01-07 07:18:45 +00001339
Owen Anderson1d0be152009-08-13 21:58:54 +00001340 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00001341
1342 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1343 // If this is a memcpy/memmove, emit a GEP of the other element address.
1344 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001345 unsigned OtherEltAlign = MemAlignment;
1346
Bob Wilsona756b1d2010-01-19 04:32:48 +00001347 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001348 Value *Idx[2] = { Zero,
1349 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00001350 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001351 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00001352 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00001353 uint64_t EltOffset;
1354 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001355 const Type *OtherTy = OtherPtrTy->getElementType();
1356 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001357 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1358 } else {
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001359 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001360 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001361 }
1362
1363 // The alignment of the other pointer is the guaranteed alignment of the
1364 // element, which is affected by both the known alignment of the whole
1365 // mem intrinsic and the alignment of the element. If the alignment of
1366 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1367 // known alignment is just 4 bytes.
1368 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00001369 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001370
1371 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00001372 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001373
1374 // If we got down to a scalar, insert a load or store as appropriate.
1375 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001376 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001377 if (SROADest) {
1378 // From Other to Alloca.
1379 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1380 new StoreInst(Elt, EltPtr, MI);
1381 } else {
1382 // From Alloca to Other.
1383 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1384 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1385 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001386 continue;
1387 }
1388 assert(isa<MemSetInst>(MI));
1389
1390 // If the stored element is zero (common case), just store a null
1391 // constant.
1392 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001393 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001394 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001395 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00001396 } else {
1397 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00001398 const Type *ValTy = EltTy->getScalarType();
1399
Chris Lattnerd93afec2009-01-07 07:18:45 +00001400 // Construct an integer with the right value.
1401 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1402 APInt OneVal(EltSize, CI->getZExtValue());
1403 APInt TotalVal(OneVal);
1404 // Set each byte.
1405 for (unsigned i = 0; 8*i < EltSize; ++i) {
1406 TotalVal = TotalVal.shl(8);
1407 TotalVal |= OneVal;
1408 }
1409
1410 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001411 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001412 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001413 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001414 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001415 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001416 assert(StoreVal->getType() == ValTy && "Type mismatch!");
1417
1418 // If the requested value was a vector constant, create it.
1419 if (EltTy != ValTy) {
1420 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1421 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +00001422 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001423 }
1424 }
1425 new StoreInst(StoreVal, EltPtr, MI);
1426 continue;
1427 }
1428 // Otherwise, if we're storing a byte variable, use a memset call for
1429 // this element.
1430 }
1431
1432 // Cast the element pointer to BytePtrTy.
1433 if (EltPtr->getType() != BytePtrTy)
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001434 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001435
1436 // Cast the other pointer (if we have one) to BytePtrTy.
Mon P Wang20adc9d2010-04-04 03:10:48 +00001437 if (OtherElt && OtherElt->getType() != BytePtrTy) {
1438 // Preserve address space of OtherElt
1439 const PointerType* OtherPTy = cast<PointerType>(OtherElt->getType());
1440 const PointerType* PTy = cast<PointerType>(BytePtrTy);
1441 if (OtherPTy->getElementType() != PTy->getElementType()) {
1442 Type *NewOtherPTy = PointerType::get(PTy->getElementType(),
1443 OtherPTy->getAddressSpace());
1444 OtherElt = new BitCastInst(OtherElt, NewOtherPTy,
1445 OtherElt->getNameStr(), MI);
1446 }
1447 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001448
Duncan Sands777d2302009-05-09 07:06:46 +00001449 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001450
1451 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001452 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001453 Value *Ops[] = {
1454 SROADest ? EltPtr : OtherElt, // Dest ptr
1455 SROADest ? OtherElt : EltPtr, // Src ptr
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001456 ConstantInt::get(MI->getArgOperand(2)->getType(), EltSize), // Size
Owen Anderson1d0be152009-08-13 21:58:54 +00001457 // Align
Mon P Wang20adc9d2010-04-04 03:10:48 +00001458 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign),
1459 MI->getVolatileCst()
Chris Lattnerd93afec2009-01-07 07:18:45 +00001460 };
Mon P Wang20adc9d2010-04-04 03:10:48 +00001461 // In case we fold the address space overloaded memcpy of A to B
1462 // with memcpy of B to C, change the function to be a memcpy of A to C.
1463 const Type *Tys[] = { Ops[0]->getType(), Ops[1]->getType(),
1464 Ops[2]->getType() };
1465 Module *M = MI->getParent()->getParent()->getParent();
1466 TheFn = Intrinsic::getDeclaration(M, MI->getIntrinsicID(), Tys, 3);
1467 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001468 } else {
1469 assert(isa<MemSetInst>(MI));
1470 Value *Ops[] = {
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001471 EltPtr, MI->getArgOperand(1), // Dest, Value,
1472 ConstantInt::get(MI->getArgOperand(2)->getType(), EltSize), // Size
Mon P Wang20adc9d2010-04-04 03:10:48 +00001473 Zero, // Align
1474 ConstantInt::get(Type::getInt1Ty(MI->getContext()), 0) // isVolatile
Chris Lattnerd93afec2009-01-07 07:18:45 +00001475 };
Mon P Wang20adc9d2010-04-04 03:10:48 +00001476 const Type *Tys[] = { Ops[0]->getType(), Ops[2]->getType() };
1477 Module *M = MI->getParent()->getParent()->getParent();
1478 TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys, 2);
1479 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001480 }
Chris Lattner372dda82007-03-05 07:52:57 +00001481 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001482 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00001483}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001484
Bob Wilson39fdd692009-12-04 21:57:37 +00001485/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001486/// overwrites the entire allocation. Extract out the pieces of the stored
1487/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001488void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001489 SmallVector<AllocaInst*, 32> &NewElts){
1490 // Extract each element out of the integer according to its structure offset
1491 // and store the element value to the individual alloca.
1492 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00001493 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001494 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001495
Eli Friedman41b33f42009-06-01 09:14:32 +00001496 // Handle tail padding by extending the operand
1497 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001498 SrcVal = new ZExtInst(SrcVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001499 IntegerType::get(SI->getContext(), AllocaSizeBits),
1500 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001501
David Greene504c7d82010-01-05 01:27:09 +00001502 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00001503 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001504
1505 // There are two forms here: AI could be an array or struct. Both cases
1506 // have different ways to compute the element offset.
1507 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1508 const StructLayout *Layout = TD->getStructLayout(EltSTy);
1509
1510 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1511 // Get the number of bits to shift SrcVal to get the value.
1512 const Type *FieldTy = EltSTy->getElementType(i);
1513 uint64_t Shift = Layout->getElementOffsetInBits(i);
1514
1515 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00001516 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001517
1518 Value *EltVal = SrcVal;
1519 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001520 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001521 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1522 "sroa.store.elt", SI);
1523 }
1524
1525 // Truncate down to an integer of the right size.
1526 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +00001527
1528 // Ignore zero sized fields like {}, they obviously contain no data.
1529 if (FieldSizeBits == 0) continue;
1530
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001531 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001532 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001533 IntegerType::get(SI->getContext(), FieldSizeBits),
1534 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001535 Value *DestField = NewElts[i];
1536 if (EltVal->getType() == FieldTy) {
1537 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00001538 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001539 // Bitcast to the right element type (for fp/vector values).
1540 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
1541 } else {
1542 // Otherwise, bitcast the dest pointer (for aggregates).
1543 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001544 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001545 "", SI);
1546 }
1547 new StoreInst(EltVal, DestField, SI);
1548 }
1549
1550 } else {
1551 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1552 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001553 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001554 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1555
1556 uint64_t Shift;
1557
1558 if (TD->isBigEndian())
1559 Shift = AllocaSizeBits-ElementOffset;
1560 else
1561 Shift = 0;
1562
1563 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00001564 // Ignore zero sized fields like {}, they obviously contain no data.
1565 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001566
1567 Value *EltVal = SrcVal;
1568 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001569 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001570 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1571 "sroa.store.elt", SI);
1572 }
1573
1574 // Truncate down to an integer of the right size.
1575 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001576 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001577 IntegerType::get(SI->getContext(),
1578 ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001579 Value *DestField = NewElts[i];
1580 if (EltVal->getType() == ArrayEltTy) {
1581 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001582 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001583 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001584 // Bitcast to the right element type (for fp/vector values).
1585 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1586 } else {
1587 // Otherwise, bitcast the dest pointer (for aggregates).
1588 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001589 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001590 "", SI);
1591 }
1592 new StoreInst(EltVal, DestField, SI);
1593
1594 if (TD->isBigEndian())
1595 Shift -= ElementOffset;
1596 else
1597 Shift += ElementOffset;
1598 }
1599 }
1600
Bob Wilsonb742def2009-12-18 20:14:40 +00001601 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001602}
1603
Bob Wilson39fdd692009-12-04 21:57:37 +00001604/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001605/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001606void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001607 SmallVector<AllocaInst*, 32> &NewElts) {
1608 // Extract each element out of the NewElts according to its structure offset
1609 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00001610 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001611 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001612
David Greene504c7d82010-01-05 01:27:09 +00001613 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00001614 << '\n');
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001615
1616 // There are two forms here: AI could be an array or struct. Both cases
1617 // have different ways to compute the element offset.
1618 const StructLayout *Layout = 0;
1619 uint64_t ArrayEltBitOffset = 0;
1620 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1621 Layout = TD->getStructLayout(EltSTy);
1622 } else {
1623 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001624 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001625 }
Owen Andersone922c022009-07-22 00:24:57 +00001626
Owen Andersone922c022009-07-22 00:24:57 +00001627 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001628 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001629
1630 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1631 // Load the value from the alloca. If the NewElt is an aggregate, cast
1632 // the pointer to an integer of the same size before doing the load.
1633 Value *SrcField = NewElts[i];
1634 const Type *FieldTy =
1635 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001636 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1637
1638 // Ignore zero sized fields like {}, they obviously contain no data.
1639 if (FieldSizeBits == 0) continue;
1640
Owen Anderson1d0be152009-08-13 21:58:54 +00001641 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1642 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00001643 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1644 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001645 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001646 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001647 "", LI);
1648 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1649
1650 // If SrcField is a fp or vector of the right size but that isn't an
1651 // integer type, bitcast to an integer so we can shift it.
1652 if (SrcField->getType() != FieldIntTy)
1653 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1654
1655 // Zero extend the field to be the same size as the final alloca so that
1656 // we can shift and insert it.
1657 if (SrcField->getType() != ResultVal->getType())
1658 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1659
1660 // Determine the number of bits to shift SrcField.
1661 uint64_t Shift;
1662 if (Layout) // Struct case.
1663 Shift = Layout->getElementOffsetInBits(i);
1664 else // Array case.
1665 Shift = i*ArrayEltBitOffset;
1666
1667 if (TD->isBigEndian())
1668 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1669
1670 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001671 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001672 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1673 }
1674
Chris Lattner14952472010-06-27 07:58:26 +00001675 // Don't create an 'or x, 0' on the first iteration.
1676 if (!isa<Constant>(ResultVal) ||
1677 !cast<Constant>(ResultVal)->isNullValue())
1678 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1679 else
1680 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001681 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001682
1683 // Handle tail padding by truncating the result
1684 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1685 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1686
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001687 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00001688 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001689}
1690
Duncan Sands3cb36502007-11-04 14:43:57 +00001691/// HasPadding - Return true if the specified type has any structure or
1692/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001693static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner91abace2010-09-01 05:14:33 +00001694 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
1695 return HasPadding(ATy->getElementType(), TD);
1696
1697 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
1698 return HasPadding(VTy->getElementType(), TD);
1699
Chris Lattner39a1c042007-05-30 06:11:23 +00001700 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1701 const StructLayout *SL = TD.getStructLayout(STy);
1702 unsigned PrevFieldBitOffset = 0;
1703 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001704 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1705
Chris Lattner39a1c042007-05-30 06:11:23 +00001706 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001707 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001708 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001709
Chris Lattner39a1c042007-05-30 06:11:23 +00001710 // Check to see if there is any padding between this element and the
1711 // previous one.
1712 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001713 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001714 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1715 if (PrevFieldEnd < FieldBitOffset)
1716 return true;
1717 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001718
Chris Lattner39a1c042007-05-30 06:11:23 +00001719 PrevFieldBitOffset = FieldBitOffset;
1720 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001721
Chris Lattner39a1c042007-05-30 06:11:23 +00001722 // Check for tail padding.
1723 if (unsigned EltCount = STy->getNumElements()) {
1724 unsigned PrevFieldEnd = PrevFieldBitOffset +
1725 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001726 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001727 return true;
1728 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001729 }
Chris Lattner91abace2010-09-01 05:14:33 +00001730
Duncan Sands777d2302009-05-09 07:06:46 +00001731 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001732}
Chris Lattner372dda82007-03-05 07:52:57 +00001733
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001734/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1735/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1736/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001737bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001738 // Loop over the use list of the alloca. We can only transform it if all of
1739 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001740 AllocaInfo Info;
1741
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001742 isSafeForScalarRepl(AI, AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001743 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00001744 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001745 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001746 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001747
1748 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1749 // source and destination, we have to be careful. In particular, the memcpy
1750 // could be moving around elements that live in structure padding of the LLVM
1751 // types, but may actually be used. In these cases, we refuse to promote the
1752 // struct.
1753 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001754 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001755 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00001756
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001757 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00001758}
Chris Lattnera1888942005-12-12 07:19:13 +00001759
Chris Lattner800de312008-02-29 07:03:13 +00001760
Chris Lattner79b3bd32007-04-25 06:40:51 +00001761
1762/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1763/// some part of a constant global variable. This intentionally only accepts
1764/// constant expressions because we don't can't rewrite arbitrary instructions.
1765static bool PointsToConstantGlobal(Value *V) {
1766 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1767 return GV->isConstant();
1768 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1769 if (CE->getOpcode() == Instruction::BitCast ||
1770 CE->getOpcode() == Instruction::GetElementPtr)
1771 return PointsToConstantGlobal(CE->getOperand(0));
1772 return false;
1773}
1774
1775/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1776/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1777/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1778/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1779/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1780/// the alloca, and if the source pointer is a pointer to a constant global, we
1781/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00001782static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00001783 bool isOffset) {
1784 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00001785 User *U = cast<Instruction>(*UI);
1786
1787 if (LoadInst *LI = dyn_cast<LoadInst>(U))
Chris Lattner6e733d32009-01-28 20:16:43 +00001788 // Ignore non-volatile loads, they are always ok.
1789 if (!LI->isVolatile())
1790 continue;
1791
Gabor Greif8a8a4352010-04-06 19:32:30 +00001792 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001793 // If uses of the bitcast are ok, we are ok.
1794 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1795 return false;
1796 continue;
1797 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00001798 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001799 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1800 // doesn't, it does.
1801 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1802 isOffset || !GEP->hasAllZeroIndices()))
1803 return false;
1804 continue;
1805 }
1806
1807 // If this is isn't our memcpy/memmove, reject it as something we can't
1808 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00001809 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
1810 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00001811 return false;
1812
1813 // If we already have seen a copy, reject the second one.
1814 if (TheCopy) return false;
1815
1816 // If the pointer has been offset from the start of the alloca, we can't
1817 // safely handle this.
1818 if (isOffset) return false;
1819
1820 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00001821 if (UI.getOperandNo() != 0) return false;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001822
Chris Lattner79b3bd32007-04-25 06:40:51 +00001823 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00001824 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001825 return false;
1826
1827 // Otherwise, the transform is safe. Remember the copy instruction.
1828 TheCopy = MI;
1829 }
1830 return true;
1831}
1832
1833/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1834/// modified by a copy from a constant global. If we can prove this, we can
1835/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00001836MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1837 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001838 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1839 return TheCopy;
1840 return 0;
1841}