blob: e644ccf1383dc49d0bfa83f8ce5f9657f60a00f3 [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 Lattner9fc5cdf2011-01-02 22:09:33 +000033#include "llvm/Analysis/DominanceFrontier.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000034#include "llvm/Analysis/ValueTracking.h"
Chris Lattner38aec322003-09-11 16:45:55 +000035#include "llvm/Target/TargetData.h"
36#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000037#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere0a1a5b2011-01-14 07:50:47 +000038#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattnera9be1df2010-11-18 06:26:49 +000039#include "llvm/Support/CallSite.h"
Chris Lattner95255282006-06-28 23:17:24 +000040#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000041#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000042#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000043#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000044#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000045#include "llvm/Support/raw_ostream.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000046#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000047#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000048using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000049
Chris Lattner0e5f4992006-12-19 21:40:18 +000050STATISTIC(NumReplaced, "Number of allocas broken up");
51STATISTIC(NumPromoted, "Number of allocas promoted");
52STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000053STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000054
Chris Lattnere0a1a5b2011-01-14 07:50:47 +000055enum {
56 UsePromoteMemToReg = 1
57};
58
Chris Lattner0e5f4992006-12-19 21:40:18 +000059namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000060 struct SROA : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000061 static char ID; // Pass identification, replacement for typeid
Owen Anderson90c579d2010-08-06 18:33:48 +000062 explicit SROA(signed T = -1) : FunctionPass(ID) {
Owen Anderson081c34b2010-10-19 17:21:58 +000063 initializeSROAPass(*PassRegistry::getPassRegistry());
Devang Patelff366852007-07-09 21:19:23 +000064 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000065 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000066 else
67 SRThreshold = T;
68 }
Devang Patel794fd752007-05-01 21:15:47 +000069
Chris Lattnered7b41e2003-05-27 15:45:27 +000070 bool runOnFunction(Function &F);
71
Chris Lattner38aec322003-09-11 16:45:55 +000072 bool performScalarRepl(Function &F);
73 bool performPromotion(Function &F);
74
Chris Lattnera15854c2003-08-31 00:45:13 +000075 // getAnalysisUsage - This pass does not require any passes, but we know it
76 // will not alter the CFG, so say so.
77 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnere0a1a5b2011-01-14 07:50:47 +000078 if (UsePromoteMemToReg) {
79 AU.addRequired<DominatorTree>();
80 AU.addRequired<DominanceFrontier>();
81 }
Chris Lattnera15854c2003-08-31 00:45:13 +000082 AU.setPreservesCFG();
83 }
84
Chris Lattnered7b41e2003-05-27 15:45:27 +000085 private:
Chris Lattner56c38522009-01-07 06:34:28 +000086 TargetData *TD;
Bob Wilson69743022011-01-13 20:59:44 +000087
Bob Wilsonb742def2009-12-18 20:14:40 +000088 /// DeadInsts - Keep track of instructions we have made dead, so that
89 /// we can remove them after we are done working.
90 SmallVector<Value*, 32> DeadInsts;
91
Chris Lattner39a1c042007-05-30 06:11:23 +000092 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
93 /// information about the uses. All these fields are initialized to false
94 /// and set to true when something is learned.
95 struct AllocaInfo {
96 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
97 bool isUnsafe : 1;
Bob Wilson69743022011-01-13 20:59:44 +000098
Chris Lattner39a1c042007-05-30 06:11:23 +000099 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
100 bool isMemCpySrc : 1;
101
Zhou Sheng33b0b8d2007-07-06 06:01:16 +0000102 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +0000103 bool isMemCpyDst : 1;
104
105 AllocaInfo()
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000106 : isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +0000107 };
Bob Wilson69743022011-01-13 20:59:44 +0000108
Devang Patelff366852007-07-09 21:19:23 +0000109 unsigned SRThreshold;
110
Chris Lattner39a1c042007-05-30 06:11:23 +0000111 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
112
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000113 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000114
Bob Wilsonb742def2009-12-18 20:14:40 +0000115 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000116 AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000117 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000118 AllocaInfo &Info);
119 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
120 const Type *MemOpType, bool isStore, AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000121 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000122 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
123 const Type *&IdxTy);
Bob Wilson69743022011-01-13 20:59:44 +0000124
125 void DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000126 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000127 void DeleteDeadInstructions();
Bob Wilson69743022011-01-13 20:59:44 +0000128
Bob Wilsonb742def2009-12-18 20:14:40 +0000129 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
130 SmallVector<AllocaInst*, 32> &NewElts);
131 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
132 SmallVector<AllocaInst*, 32> &NewElts);
133 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
134 SmallVector<AllocaInst*, 32> &NewElts);
135 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000136 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000137 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000138 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000139 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000140 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000141 SmallVector<AllocaInst*, 32> &NewElts);
Bob Wilson69743022011-01-13 20:59:44 +0000142
Chris Lattner31d80102010-04-15 21:59:20 +0000143 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000144 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000145}
146
Dan Gohman844731a2008-05-13 00:00:25 +0000147char SROA::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000148INITIALIZE_PASS_BEGIN(SROA, "scalarrepl",
149 "Scalar Replacement of Aggregates", false, false)
150INITIALIZE_PASS_DEPENDENCY(DominatorTree)
151INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
152INITIALIZE_PASS_END(SROA, "scalarrepl",
Owen Andersonce665bd2010-10-07 22:25:06 +0000153 "Scalar Replacement of Aggregates", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000154
Brian Gaeked0fde302003-11-11 22:41:34 +0000155// Public interface to the ScalarReplAggregates pass
Bob Wilson69743022011-01-13 20:59:44 +0000156FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
Devang Patelff366852007-07-09 21:19:23 +0000157 return new SROA(Threshold);
158}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000159
160
Chris Lattner4cc576b2010-04-16 00:24:57 +0000161//===----------------------------------------------------------------------===//
162// Convert To Scalar Optimization.
163//===----------------------------------------------------------------------===//
164
165namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000166/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
167/// optimization, which scans the uses of an alloca and determines if it can
168/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000169class ConvertToScalarInfo {
170 /// AllocaSize - The size of the alloca being considered.
171 unsigned AllocaSize;
172 const TargetData &TD;
Bob Wilson69743022011-01-13 20:59:44 +0000173
Chris Lattnera0bada72010-04-16 02:32:17 +0000174 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000175 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000176 bool IsNotTrivial;
Bob Wilson69743022011-01-13 20:59:44 +0000177
Chris Lattnera001b662010-04-16 00:38:19 +0000178 /// VectorTy - This tracks the type that we should promote the vector to if
179 /// it is possible to turn it into a vector. This starts out null, and if it
180 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000181 const Type *VectorTy;
Bob Wilson69743022011-01-13 20:59:44 +0000182
Chris Lattnera001b662010-04-16 00:38:19 +0000183 /// HadAVector - True if there is at least one vector access to the alloca.
184 /// We don't want to turn random arrays into vectors and use vector element
185 /// insert/extract, but if there are element accesses to something that is
186 /// also declared as a vector, we do want to promote to a vector.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000187 bool HadAVector;
188
189public:
190 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
191 : AllocaSize(Size), TD(td) {
192 IsNotTrivial = false;
193 VectorTy = 0;
194 HadAVector = false;
195 }
Bob Wilson69743022011-01-13 20:59:44 +0000196
Chris Lattnera001b662010-04-16 00:38:19 +0000197 AllocaInst *TryConvert(AllocaInst *AI);
Bob Wilson69743022011-01-13 20:59:44 +0000198
Chris Lattner4cc576b2010-04-16 00:24:57 +0000199private:
200 bool CanConvertToScalar(Value *V, uint64_t Offset);
201 void MergeInType(const Type *In, uint64_t Offset);
202 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Bob Wilson69743022011-01-13 20:59:44 +0000203
Chris Lattner4cc576b2010-04-16 00:24:57 +0000204 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
205 uint64_t Offset, IRBuilder<> &Builder);
206 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
207 uint64_t Offset, IRBuilder<> &Builder);
208};
209} // end anonymous namespace.
210
Chris Lattner91abace2010-09-01 05:14:33 +0000211
212/// IsVerbotenVectorType - Return true if this is a vector type ScalarRepl isn't
213/// allowed to form. We do this to avoid MMX types, which is a complete hack,
214/// but is required until the backend is fixed.
Chris Lattner72eaa0e2010-09-01 23:09:27 +0000215static bool IsVerbotenVectorType(const VectorType *VTy, const Instruction *I) {
216 StringRef Triple(I->getParent()->getParent()->getParent()->getTargetTriple());
217 if (!Triple.startswith("i386") &&
218 !Triple.startswith("x86_64"))
219 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000220
Chris Lattner91abace2010-09-01 05:14:33 +0000221 // Reject all the MMX vector types.
222 switch (VTy->getNumElements()) {
223 default: return false;
224 case 1: return VTy->getElementType()->isIntegerTy(64);
225 case 2: return VTy->getElementType()->isIntegerTy(32);
226 case 4: return VTy->getElementType()->isIntegerTy(16);
227 case 8: return VTy->getElementType()->isIntegerTy(8);
228 }
229}
230
231
Chris Lattnera001b662010-04-16 00:38:19 +0000232/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
233/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
234/// alloca if possible or null if not.
235AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
236 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
237 // out.
238 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
239 return 0;
Bob Wilson69743022011-01-13 20:59:44 +0000240
Chris Lattnera001b662010-04-16 00:38:19 +0000241 // If we were able to find a vector type that can handle this with
242 // insert/extract elements, and if there was at least one use that had
243 // a vector type, promote this to a vector. We don't want to promote
244 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
245 // we just get a lot of insert/extracts. If at least one vector is
246 // involved, then we probably really do have a union of vector/array.
247 const Type *NewTy;
Chris Lattner91abace2010-09-01 05:14:33 +0000248 if (VectorTy && VectorTy->isVectorTy() && HadAVector &&
Chris Lattner72eaa0e2010-09-01 23:09:27 +0000249 !IsVerbotenVectorType(cast<VectorType>(VectorTy), AI)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000250 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
251 << *VectorTy << '\n');
252 NewTy = VectorTy; // Use the vector type.
253 } else {
254 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
255 // Create and insert the integer alloca.
256 NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
257 }
258 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
259 ConvertUsesToScalar(AI, NewAI, 0);
260 return NewAI;
261}
262
263/// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
264/// so far at the offset specified by Offset (which is specified in bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000265///
266/// There are two cases we handle here:
267/// 1) A union of vector types of the same size and potentially its elements.
268/// Here we turn element accesses into insert/extract element operations.
269/// This promotes a <4 x float> with a store of float to the third element
270/// into a <4 x float> that uses insert element.
271/// 2) A fully general blob of memory, which we turn into some (potentially
272/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000273/// and stores would mutate the memory. We mark this by setting VectorTy
274/// to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000275void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000276 // If we already decided to turn this into a blob of integer memory, there is
277 // nothing to be done.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000278 if (VectorTy && VectorTy->isVoidTy())
279 return;
Bob Wilson69743022011-01-13 20:59:44 +0000280
Chris Lattner4cc576b2010-04-16 00:24:57 +0000281 // If this could be contributing to a vector, analyze it.
282
283 // If the In type is a vector that is the same size as the alloca, see if it
284 // matches the existing VecTy.
285 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000286 // Remember if we saw a vector type.
287 HadAVector = true;
Bob Wilson69743022011-01-13 20:59:44 +0000288
Chris Lattner4cc576b2010-04-16 00:24:57 +0000289 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
290 // If we're storing/loading a vector of the right size, allow it as a
291 // vector. If this the first vector we see, remember the type so that
Chris Lattnera001b662010-04-16 00:38:19 +0000292 // we know the element size. If this is a subsequent access, ignore it
293 // even if it is a differing type but the same size. Worst case we can
294 // bitcast the resultant vectors.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000295 if (VectorTy == 0)
296 VectorTy = VInTy;
297 return;
298 }
299 } else if (In->isFloatTy() || In->isDoubleTy() ||
300 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
301 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
302 // If we're accessing something that could be an element of a vector, see
303 // if the implied vector agrees with what we already have and if Offset is
304 // compatible with it.
305 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
306 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Bob Wilson69743022011-01-13 20:59:44 +0000307 (VectorTy == 0 ||
Chris Lattner4cc576b2010-04-16 00:24:57 +0000308 cast<VectorType>(VectorTy)->getElementType()
309 ->getPrimitiveSizeInBits()/8 == EltSize)) {
310 if (VectorTy == 0)
311 VectorTy = VectorType::get(In, AllocaSize/EltSize);
312 return;
313 }
314 }
Bob Wilson69743022011-01-13 20:59:44 +0000315
Chris Lattner4cc576b2010-04-16 00:24:57 +0000316 // Otherwise, we have a case that we can't handle with an optimized vector
317 // form. We can still turn this into a large integer.
318 VectorTy = Type::getVoidTy(In->getContext());
319}
320
321/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
322/// its accesses to a single vector type, return true and set VecTy to
323/// the new type. If we could convert the alloca into a single promotable
324/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
325/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
326/// is the current offset from the base of the alloca being analyzed.
327///
328/// If we see at least one access to the value that is as a vector type, set the
329/// SawVec flag.
330bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
331 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
332 Instruction *User = cast<Instruction>(*UI);
Bob Wilson69743022011-01-13 20:59:44 +0000333
Chris Lattner4cc576b2010-04-16 00:24:57 +0000334 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
335 // Don't break volatile loads.
336 if (LI->isVolatile())
337 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000338 // Don't touch MMX operations.
339 if (LI->getType()->isX86_MMXTy())
340 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000341 MergeInType(LI->getType(), Offset);
342 continue;
343 }
Bob Wilson69743022011-01-13 20:59:44 +0000344
Chris Lattner4cc576b2010-04-16 00:24:57 +0000345 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
346 // Storing the pointer, not into the value?
347 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000348 // Don't touch MMX operations.
349 if (SI->getOperand(0)->getType()->isX86_MMXTy())
350 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000351 MergeInType(SI->getOperand(0)->getType(), Offset);
352 continue;
353 }
Bob Wilson69743022011-01-13 20:59:44 +0000354
Chris Lattner4cc576b2010-04-16 00:24:57 +0000355 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000356 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000357 if (!CanConvertToScalar(BCI, Offset))
358 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000359 continue;
360 }
361
362 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
363 // If this is a GEP with a variable indices, we can't handle it.
364 if (!GEP->hasAllConstantIndices())
365 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000366
Chris Lattner4cc576b2010-04-16 00:24:57 +0000367 // Compute the offset that this GEP adds to the pointer.
368 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
369 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
370 &Indices[0], Indices.size());
371 // See if all uses can be converted.
372 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
373 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000374 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000375 continue;
376 }
377
378 // If this is a constant sized memset of a constant value (e.g. 0) we can
379 // handle it.
380 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
381 // Store of constant value and constant size.
Chris Lattnera001b662010-04-16 00:38:19 +0000382 if (!isa<ConstantInt>(MSI->getValue()) ||
383 !isa<ConstantInt>(MSI->getLength()))
384 return false;
385 IsNotTrivial = true; // Can't be mem2reg'd.
386 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000387 }
388
389 // If this is a memcpy or memmove into or out of the whole allocation, we
390 // can handle it like a load or store of the scalar type.
391 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000392 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
393 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
394 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000395
Chris Lattnera001b662010-04-16 00:38:19 +0000396 IsNotTrivial = true; // Can't be mem2reg'd.
397 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000398 }
Bob Wilson69743022011-01-13 20:59:44 +0000399
Chris Lattner4cc576b2010-04-16 00:24:57 +0000400 // Otherwise, we cannot handle this!
401 return false;
402 }
Bob Wilson69743022011-01-13 20:59:44 +0000403
Chris Lattner4cc576b2010-04-16 00:24:57 +0000404 return true;
405}
406
407/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
408/// directly. This happens when we are converting an "integer union" to a
409/// single integer scalar, or when we are converting a "vector union" to a
410/// vector with insert/extractelement instructions.
411///
412/// Offset is an offset from the original alloca, in bits that need to be
413/// shifted to the right. By the end of this, there should be no uses of Ptr.
414void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
415 uint64_t Offset) {
416 while (!Ptr->use_empty()) {
417 Instruction *User = cast<Instruction>(Ptr->use_back());
418
419 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
420 ConvertUsesToScalar(CI, NewAI, Offset);
421 CI->eraseFromParent();
422 continue;
423 }
424
425 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
426 // Compute the offset that this GEP adds to the pointer.
427 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
428 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
429 &Indices[0], Indices.size());
430 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
431 GEP->eraseFromParent();
432 continue;
433 }
Bob Wilson69743022011-01-13 20:59:44 +0000434
Chris Lattner61db1f52010-12-26 22:57:41 +0000435 IRBuilder<> Builder(User);
Bob Wilson69743022011-01-13 20:59:44 +0000436
Chris Lattner4cc576b2010-04-16 00:24:57 +0000437 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
438 // The load is a bit extract from NewAI shifted right by Offset bits.
439 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
440 Value *NewLoadVal
441 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
442 LI->replaceAllUsesWith(NewLoadVal);
443 LI->eraseFromParent();
444 continue;
445 }
Bob Wilson69743022011-01-13 20:59:44 +0000446
Chris Lattner4cc576b2010-04-16 00:24:57 +0000447 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
448 assert(SI->getOperand(0) != Ptr && "Consistency error!");
449 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
450 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
451 Builder);
452 Builder.CreateStore(New, NewAI);
453 SI->eraseFromParent();
Bob Wilson69743022011-01-13 20:59:44 +0000454
Chris Lattner4cc576b2010-04-16 00:24:57 +0000455 // If the load we just inserted is now dead, then the inserted store
456 // overwrote the entire thing.
457 if (Old->use_empty())
458 Old->eraseFromParent();
459 continue;
460 }
Bob Wilson69743022011-01-13 20:59:44 +0000461
Chris Lattner4cc576b2010-04-16 00:24:57 +0000462 // If this is a constant sized memset of a constant value (e.g. 0) we can
463 // transform it into a store of the expanded constant value.
464 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
465 assert(MSI->getRawDest() == Ptr && "Consistency error!");
466 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
467 if (NumBytes != 0) {
468 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson69743022011-01-13 20:59:44 +0000469
Chris Lattner4cc576b2010-04-16 00:24:57 +0000470 // Compute the value replicated the right number of times.
471 APInt APVal(NumBytes*8, Val);
472
473 // Splat the value if non-zero.
474 if (Val)
475 for (unsigned i = 1; i != NumBytes; ++i)
476 APVal |= APVal << 8;
Bob Wilson69743022011-01-13 20:59:44 +0000477
Chris Lattner4cc576b2010-04-16 00:24:57 +0000478 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
479 Value *New = ConvertScalar_InsertValue(
480 ConstantInt::get(User->getContext(), APVal),
481 Old, Offset, Builder);
482 Builder.CreateStore(New, NewAI);
Bob Wilson69743022011-01-13 20:59:44 +0000483
Chris Lattner4cc576b2010-04-16 00:24:57 +0000484 // If the load we just inserted is now dead, then the memset overwrote
485 // the entire thing.
486 if (Old->use_empty())
Bob Wilson69743022011-01-13 20:59:44 +0000487 Old->eraseFromParent();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000488 }
489 MSI->eraseFromParent();
490 continue;
491 }
492
493 // If this is a memcpy or memmove into or out of the whole allocation, we
494 // can handle it like a load or store of the scalar type.
495 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
496 assert(Offset == 0 && "must be store to start of alloca");
Bob Wilson69743022011-01-13 20:59:44 +0000497
Chris Lattner4cc576b2010-04-16 00:24:57 +0000498 // If the source and destination are both to the same alloca, then this is
499 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
500 // as appropriate.
Dan Gohman5034dd32010-12-15 20:02:24 +0000501 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, 0));
Bob Wilson69743022011-01-13 20:59:44 +0000502
Dan Gohman5034dd32010-12-15 20:02:24 +0000503 if (GetUnderlyingObject(MTI->getSource(), 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000504 // Dest must be OrigAI, change this to be a load from the original
505 // pointer (bitcasted), then a store to our new alloca.
506 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
507 Value *SrcPtr = MTI->getSource();
Mon P Wange90a6332010-12-23 01:41:32 +0000508 const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
509 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
510 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
511 AIPTy = PointerType::get(AIPTy->getElementType(),
512 SPTy->getAddressSpace());
513 }
514 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
515
Chris Lattner4cc576b2010-04-16 00:24:57 +0000516 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
517 SrcVal->setAlignment(MTI->getAlignment());
518 Builder.CreateStore(SrcVal, NewAI);
Dan Gohman5034dd32010-12-15 20:02:24 +0000519 } else if (GetUnderlyingObject(MTI->getDest(), 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000520 // Src must be OrigAI, change this to be a load from NewAI then a store
521 // through the original dest pointer (bitcasted).
522 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
523 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
524
Mon P Wange90a6332010-12-23 01:41:32 +0000525 const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
526 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
527 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
528 AIPTy = PointerType::get(AIPTy->getElementType(),
529 DPTy->getAddressSpace());
530 }
531 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
532
Chris Lattner4cc576b2010-04-16 00:24:57 +0000533 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
534 NewStore->setAlignment(MTI->getAlignment());
535 } else {
536 // Noop transfer. Src == Dst
537 }
538
539 MTI->eraseFromParent();
540 continue;
541 }
Bob Wilson69743022011-01-13 20:59:44 +0000542
Chris Lattner4cc576b2010-04-16 00:24:57 +0000543 llvm_unreachable("Unsupported operation!");
544 }
545}
546
547/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
548/// or vector value FromVal, extracting the bits from the offset specified by
549/// Offset. This returns the value, which is of type ToType.
550///
551/// This happens when we are converting an "integer union" to a single
552/// integer scalar, or when we are converting a "vector union" to a vector with
553/// insert/extractelement instructions.
554///
555/// Offset is an offset from the original alloca, in bits that need to be
556/// shifted to the right.
557Value *ConvertToScalarInfo::
558ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
559 uint64_t Offset, IRBuilder<> &Builder) {
560 // If the load is of the whole new alloca, no conversion is needed.
561 if (FromVal->getType() == ToType && Offset == 0)
562 return FromVal;
563
564 // If the result alloca is a vector type, this is either an element
565 // access or a bitcast to another vector type of the same size.
566 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
567 if (ToType->isVectorTy())
568 return Builder.CreateBitCast(FromVal, ToType, "tmp");
569
570 // Otherwise it must be an element access.
571 unsigned Elt = 0;
572 if (Offset) {
573 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
574 Elt = Offset/EltSize;
575 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
576 }
577 // Return the element extracted out of it.
578 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
579 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
580 if (V->getType() != ToType)
581 V = Builder.CreateBitCast(V, ToType, "tmp");
582 return V;
583 }
Bob Wilson69743022011-01-13 20:59:44 +0000584
Chris Lattner4cc576b2010-04-16 00:24:57 +0000585 // If ToType is a first class aggregate, extract out each of the pieces and
586 // use insertvalue's to form the FCA.
587 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
588 const StructLayout &Layout = *TD.getStructLayout(ST);
589 Value *Res = UndefValue::get(ST);
590 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
591 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
592 Offset+Layout.getElementOffsetInBits(i),
593 Builder);
594 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
595 }
596 return Res;
597 }
Bob Wilson69743022011-01-13 20:59:44 +0000598
Chris Lattner4cc576b2010-04-16 00:24:57 +0000599 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
600 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
601 Value *Res = UndefValue::get(AT);
602 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
603 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
604 Offset+i*EltSize, Builder);
605 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
606 }
607 return Res;
608 }
609
610 // Otherwise, this must be a union that was converted to an integer value.
611 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
612
613 // If this is a big-endian system and the load is narrower than the
614 // full alloca type, we need to do a shift to get the right bits.
615 int ShAmt = 0;
616 if (TD.isBigEndian()) {
617 // On big-endian machines, the lowest bit is stored at the bit offset
618 // from the pointer given by getTypeStoreSizeInBits. This matters for
619 // integers with a bitwidth that is not a multiple of 8.
620 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
621 TD.getTypeStoreSizeInBits(ToType) - Offset;
622 } else {
623 ShAmt = Offset;
624 }
625
626 // Note: we support negative bitwidths (with shl) which are not defined.
627 // We do this to support (f.e.) loads off the end of a structure where
628 // only some bits are used.
629 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
630 FromVal = Builder.CreateLShr(FromVal,
631 ConstantInt::get(FromVal->getType(),
632 ShAmt), "tmp");
633 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson69743022011-01-13 20:59:44 +0000634 FromVal = Builder.CreateShl(FromVal,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000635 ConstantInt::get(FromVal->getType(),
636 -ShAmt), "tmp");
637
638 // Finally, unconditionally truncate the integer to the right width.
639 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
640 if (LIBitWidth < NTy->getBitWidth())
641 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000642 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000643 LIBitWidth), "tmp");
644 else if (LIBitWidth > NTy->getBitWidth())
645 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000646 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000647 LIBitWidth), "tmp");
648
649 // If the result is an integer, this is a trunc or bitcast.
650 if (ToType->isIntegerTy()) {
651 // Should be done.
652 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
653 // Just do a bitcast, we know the sizes match up.
654 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
655 } else {
656 // Otherwise must be a pointer.
657 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
658 }
659 assert(FromVal->getType() == ToType && "Didn't convert right?");
660 return FromVal;
661}
662
663/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
664/// or vector value "Old" at the offset specified by Offset.
665///
666/// This happens when we are converting an "integer union" to a
667/// single integer scalar, or when we are converting a "vector union" to a
668/// vector with insert/extractelement instructions.
669///
670/// Offset is an offset from the original alloca, in bits that need to be
671/// shifted to the right.
672Value *ConvertToScalarInfo::
673ConvertScalar_InsertValue(Value *SV, Value *Old,
674 uint64_t Offset, IRBuilder<> &Builder) {
675 // Convert the stored type to the actual type, shift it left to insert
676 // then 'or' into place.
677 const Type *AllocaType = Old->getType();
678 LLVMContext &Context = Old->getContext();
679
680 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
681 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
682 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
Bob Wilson69743022011-01-13 20:59:44 +0000683
Chris Lattner4cc576b2010-04-16 00:24:57 +0000684 // Changing the whole vector with memset or with an access of a different
685 // vector type?
686 if (ValSize == VecSize)
687 return Builder.CreateBitCast(SV, AllocaType, "tmp");
688
689 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
690
691 // Must be an element insertion.
692 unsigned Elt = Offset/EltSize;
Bob Wilson69743022011-01-13 20:59:44 +0000693
Chris Lattner4cc576b2010-04-16 00:24:57 +0000694 if (SV->getType() != VTy->getElementType())
695 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000696
697 SV = Builder.CreateInsertElement(Old, SV,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000698 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
699 "tmp");
700 return SV;
701 }
Bob Wilson69743022011-01-13 20:59:44 +0000702
Chris Lattner4cc576b2010-04-16 00:24:57 +0000703 // If SV is a first-class aggregate value, insert each value recursively.
704 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
705 const StructLayout &Layout = *TD.getStructLayout(ST);
706 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
707 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000708 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000709 Offset+Layout.getElementOffsetInBits(i),
710 Builder);
711 }
712 return Old;
713 }
Bob Wilson69743022011-01-13 20:59:44 +0000714
Chris Lattner4cc576b2010-04-16 00:24:57 +0000715 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
716 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
717 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
718 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
719 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
720 }
721 return Old;
722 }
723
724 // If SV is a float, convert it to the appropriate integer type.
725 // If it is a pointer, do the same.
726 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
727 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
728 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
729 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
730 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
731 SV = Builder.CreateBitCast(SV,
732 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
733 else if (SV->getType()->isPointerTy())
734 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
735
736 // Zero extend or truncate the value if needed.
737 if (SV->getType() != AllocaType) {
738 if (SV->getType()->getPrimitiveSizeInBits() <
739 AllocaType->getPrimitiveSizeInBits())
740 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
741 else {
742 // Truncation may be needed if storing more than the alloca can hold
743 // (undefined behavior).
744 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
745 SrcWidth = DestWidth;
746 SrcStoreWidth = DestStoreWidth;
747 }
748 }
749
750 // If this is a big-endian system and the store is narrower than the
751 // full alloca type, we need to do a shift to get the right bits.
752 int ShAmt = 0;
753 if (TD.isBigEndian()) {
754 // On big-endian machines, the lowest bit is stored at the bit offset
755 // from the pointer given by getTypeStoreSizeInBits. This matters for
756 // integers with a bitwidth that is not a multiple of 8.
757 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
758 } else {
759 ShAmt = Offset;
760 }
761
762 // Note: we support negative bitwidths (with shr) which are not defined.
763 // We do this to support (f.e.) stores off the end of a structure where
764 // only some bits in the structure are set.
765 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
766 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
767 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
768 ShAmt), "tmp");
769 Mask <<= ShAmt;
770 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
771 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
772 -ShAmt), "tmp");
773 Mask = Mask.lshr(-ShAmt);
774 }
775
776 // Mask out the bits we are about to insert from the old value, and or
777 // in the new bits.
778 if (SrcWidth != DestWidth) {
779 assert(DestWidth > SrcWidth);
780 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
781 SV = Builder.CreateOr(Old, SV, "ins");
782 }
783 return SV;
784}
785
786
787//===----------------------------------------------------------------------===//
788// SRoA Driver
789//===----------------------------------------------------------------------===//
790
791
Chris Lattnered7b41e2003-05-27 15:45:27 +0000792bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000793 TD = getAnalysisIfAvailable<TargetData>();
794
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000795 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000796
797 // FIXME: ScalarRepl currently depends on TargetData more than it
798 // theoretically needs to. It should be refactored in order to support
799 // target-independent IR. Until this is done, just skip the actual
800 // scalar-replacement portion of this pass.
801 if (!TD) return Changed;
802
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000803 while (1) {
804 bool LocalChange = performScalarRepl(F);
805 if (!LocalChange) break; // No need to repromote if no scalarrepl
806 Changed = true;
807 LocalChange = performPromotion(F);
808 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
809 }
Chris Lattner38aec322003-09-11 16:45:55 +0000810
811 return Changed;
812}
813
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000814/// PromoteAlloca - Promote an alloca to registers, using SSAUpdater.
815static void PromoteAlloca(AllocaInst *AI, SSAUpdater &SSA) {
816 SSA.Initialize(AI->getType()->getElementType(), AI->getName());
817
818 // First step: bucket up uses of the alloca by the block they occur in.
819 // This is important because we have to handle multiple defs/uses in a block
820 // ourselves: SSAUpdater is purely for cross-block references.
821 // FIXME: Want a TinyVector<Instruction*> since there is often 0/1 element.
822 DenseMap<BasicBlock*, std::vector<Instruction*> > UsesByBlock;
823
824 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
825 UI != E; ++UI) {
826 Instruction *User = cast<Instruction>(*UI);
827 UsesByBlock[User->getParent()].push_back(User);
828 }
829
830 // Okay, now we can iterate over all the blocks in the function with uses,
831 // processing them. Keep track of which loads are loading a live-in value.
832 // Walk the uses in the use-list order to be determinstic.
833 SmallVector<LoadInst*, 32> LiveInLoads;
834 DenseMap<Value*, Value*> ReplacedLoads;
835
836 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
837 UI != E; ++UI) {
838 Instruction *User = cast<Instruction>(*UI);
839 BasicBlock *BB = User->getParent();
840 std::vector<Instruction*> &BlockUses = UsesByBlock[BB];
841
842 // If this block has already been processed, ignore this repeat use.
843 if (BlockUses.empty()) continue;
844
845 // Okay, this is the first use in the block. If this block just has a
846 // single user in it, we can rewrite it trivially.
847 if (BlockUses.size() == 1) {
848 // If it is a store, it is a trivial def of the value in the block.
849 if (StoreInst *SI = dyn_cast<StoreInst>(User))
850 SSA.AddAvailableValue(BB, SI->getOperand(0));
851 else
852 // Otherwise it is a load, queue it to rewrite as a live-in load.
853 LiveInLoads.push_back(cast<LoadInst>(User));
854 BlockUses.clear();
855 continue;
856 }
857
858 // Otherwise, check to see if this block is all loads.
859 bool HasStore = false;
860 for (unsigned i = 0, e = BlockUses.size(); i != e; ++i) {
861 if (isa<StoreInst>(BlockUses[i])) {
862 HasStore = true;
863 break;
864 }
865 }
866
867 // If so, we can queue them all as live in loads. We don't have an
868 // efficient way to tell which on is first in the block and don't want to
869 // scan large blocks, so just add all loads as live ins.
870 if (!HasStore) {
871 for (unsigned i = 0, e = BlockUses.size(); i != e; ++i)
872 LiveInLoads.push_back(cast<LoadInst>(BlockUses[i]));
873 BlockUses.clear();
874 continue;
875 }
876
877 // Otherwise, we have mixed loads and stores (or just a bunch of stores).
878 // Since SSAUpdater is purely for cross-block values, we need to determine
879 // the order of these instructions in the block. If the first use in the
880 // block is a load, then it uses the live in value. The last store defines
881 // the live out value. We handle this by doing a linear scan of the block.
882 Value *StoredValue = 0;
883 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
884 if (LoadInst *L = dyn_cast<LoadInst>(II)) {
885 // If this is a load from an unrelated pointer, ignore it.
886 if (L->getOperand(0) != AI) continue;
887
888 // If we haven't seen a store yet, this is a live in use, otherwise
889 // use the stored value.
890 if (StoredValue) {
891 L->replaceAllUsesWith(StoredValue);
892 ReplacedLoads[L] = StoredValue;
893 } else {
894 LiveInLoads.push_back(L);
895 }
896 continue;
897 }
898
899 if (StoreInst *S = dyn_cast<StoreInst>(II)) {
900 // If this is a store to an unrelated pointer, ignore it.
901 if (S->getPointerOperand() != AI) continue;
902
903 // Remember that this is the active value in the block.
904 StoredValue = S->getOperand(0);
905 }
906 }
907
908 // The last stored value that happened is the live-out for the block.
909 assert(StoredValue && "Already checked that there is a store in block");
910 SSA.AddAvailableValue(BB, StoredValue);
911 BlockUses.clear();
912 }
913
914 // Okay, now we rewrite all loads that use live-in values in the loop,
915 // inserting PHI nodes as necessary.
916 for (unsigned i = 0, e = LiveInLoads.size(); i != e; ++i) {
917 LoadInst *ALoad = LiveInLoads[i];
918 Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent());
919 ALoad->replaceAllUsesWith(NewVal);
920 ReplacedLoads[ALoad] = NewVal;
921 }
922
923 // Now that everything is rewritten, delete the old instructions from the
924 // function. They should all be dead now.
925 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E; ) {
926 Instruction *User = cast<Instruction>(*UI++);
927
928 // If this is a load that still has uses, then the load must have been added
929 // as a live value in the SSAUpdate data structure for a block (e.g. because
930 // the loaded value was stored later). In this case, we need to recursively
931 // propagate the updates until we get to the real value.
932 if (!User->use_empty()) {
933 Value *NewVal = ReplacedLoads[User];
934 assert(NewVal && "not a replaced load?");
935
936 // Propagate down to the ultimate replacee. The intermediately loads
937 // could theoretically already have been deleted, so we don't want to
938 // dereference the Value*'s.
939 DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal);
940 while (RLI != ReplacedLoads.end()) {
941 NewVal = RLI->second;
942 RLI = ReplacedLoads.find(NewVal);
943 }
944
945 User->replaceAllUsesWith(NewVal);
946 }
947
948 User->eraseFromParent();
949 }
950}
951
Chris Lattner38aec322003-09-11 16:45:55 +0000952
953bool SROA::performPromotion(Function &F) {
954 std::vector<AllocaInst*> Allocas;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000955 DominatorTree *DT = 0;
956 DominanceFrontier *DF = 0;
957 if (UsePromoteMemToReg) {
958 DT = &getAnalysis<DominatorTree>();
959 DF = &getAnalysis<DominanceFrontier>();
960 }
Chris Lattner38aec322003-09-11 16:45:55 +0000961
Chris Lattner02a3be02003-09-20 14:39:18 +0000962 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000963
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000964 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000965
Chris Lattner38aec322003-09-11 16:45:55 +0000966 while (1) {
967 Allocas.clear();
968
969 // Find allocas that are safe to promote, by looking at all instructions in
970 // the entry node
971 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
972 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000973 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000974 Allocas.push_back(AI);
975
976 if (Allocas.empty()) break;
977
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000978 if (UsePromoteMemToReg)
979 PromoteMemToReg(Allocas, *DT, *DF);
980 else {
981 SSAUpdater SSA;
982 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
983 PromoteAlloca(Allocas[i], SSA);
984 Allocas[i]->eraseFromParent();
985 }
986 }
Chris Lattner38aec322003-09-11 16:45:55 +0000987 NumPromoted += Allocas.size();
988 Changed = true;
989 }
990
991 return Changed;
992}
993
Chris Lattner4cc576b2010-04-16 00:24:57 +0000994
Bob Wilson3992feb2010-02-03 17:23:56 +0000995/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
996/// SROA. It must be a struct or array type with a small number of elements.
997static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
998 const Type *T = AI->getAllocatedType();
999 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +00001000 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +00001001 return ST->getNumElements() <= 32;
1002 // Arrays are much less likely to be safe for SROA; only consider
1003 // them if they are very small.
1004 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1005 return AT->getNumElements() <= 8;
1006 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +00001007}
1008
Chris Lattnerc4472072010-04-15 23:50:26 +00001009
Chris Lattner38aec322003-09-11 16:45:55 +00001010// performScalarRepl - This algorithm is a simple worklist driven algorithm,
1011// which runs on all of the malloc/alloca instructions in the function, removing
1012// them if they are only used by getelementptr instructions.
1013//
1014bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001015 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +00001016
Chris Lattner31d80102010-04-15 21:59:20 +00001017 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +00001018 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001019 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +00001020 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +00001021 WorkList.push_back(A);
1022
1023 // Process the worklist
1024 bool Changed = false;
1025 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001026 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001027 WorkList.pop_back();
Bob Wilson69743022011-01-13 20:59:44 +00001028
Chris Lattneradd2bd72006-12-22 23:14:42 +00001029 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1030 // with unused elements.
1031 if (AI->use_empty()) {
1032 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +00001033 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +00001034 continue;
1035 }
Chris Lattner7809ecd2009-02-03 01:30:09 +00001036
1037 // If this alloca is impossible for us to promote, reject it early.
1038 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1039 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001040
Chris Lattner79b3bd32007-04-25 06:40:51 +00001041 // Check to see if this allocation is only modified by a memcpy/memmove from
1042 // a constant global. If this is the case, we can change all users to use
1043 // the constant global instead. This is commonly produced by the CFE by
1044 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1045 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +00001046 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +00001047 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
1048 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +00001049 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001050 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +00001051 TheCopy->eraseFromParent(); // Don't mutate the global.
1052 AI->eraseFromParent();
1053 ++NumGlobals;
1054 Changed = true;
1055 continue;
1056 }
Bob Wilson69743022011-01-13 20:59:44 +00001057
Chris Lattner7809ecd2009-02-03 01:30:09 +00001058 // Check to see if we can perform the core SROA transformation. We cannot
1059 // transform the allocation instruction if it is an array allocation
1060 // (allocations OF arrays are ok though), and an allocation of a scalar
1061 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +00001062 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +00001063
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +00001064 // Do not promote [0 x %struct].
1065 if (AllocaSize == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001066
Chris Lattner31d80102010-04-15 21:59:20 +00001067 // Do not promote any struct whose size is too big.
1068 if (AllocaSize > SRThreshold) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001069
Bob Wilson3992feb2010-02-03 17:23:56 +00001070 // If the alloca looks like a good candidate for scalar replacement, and if
1071 // all its users can be transformed, then split up the aggregate into its
1072 // separate elements.
1073 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1074 DoScalarReplacement(AI, WorkList);
1075 Changed = true;
1076 continue;
1077 }
1078
Chris Lattner6e733d32009-01-28 20:16:43 +00001079 // If we can turn this aggregate value (potentially with casts) into a
1080 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001081 // IsNotTrivial tracks whether this is something that mem2reg could have
1082 // promoted itself. If so, we don't want to transform it needlessly. Note
1083 // that we can't just check based on the type: the alloca may be of an i32
1084 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +00001085 if (AllocaInst *NewAI =
1086 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001087 NewAI->takeName(AI);
1088 AI->eraseFromParent();
1089 ++NumConverted;
1090 Changed = true;
1091 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001092 }
1093
Chris Lattner7809ecd2009-02-03 01:30:09 +00001094 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +00001095 }
1096
1097 return Changed;
1098}
Chris Lattner5e062a12003-05-30 04:15:41 +00001099
Chris Lattnera10b29b2007-04-25 05:02:56 +00001100/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1101/// predicate, do SROA now.
Bob Wilson69743022011-01-13 20:59:44 +00001102void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001103 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +00001104 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +00001105 SmallVector<AllocaInst*, 32> ElementAllocas;
1106 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1107 ElementAllocas.reserve(ST->getNumContainedTypes());
1108 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Bob Wilson69743022011-01-13 20:59:44 +00001109 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +00001110 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001111 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001112 ElementAllocas.push_back(NA);
1113 WorkList.push_back(NA); // Add to worklist for recursive processing
1114 }
1115 } else {
1116 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1117 ElementAllocas.reserve(AT->getNumElements());
1118 const Type *ElTy = AT->getElementType();
1119 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +00001120 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001121 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001122 ElementAllocas.push_back(NA);
1123 WorkList.push_back(NA); // Add to worklist for recursive processing
1124 }
1125 }
1126
Bob Wilsonb742def2009-12-18 20:14:40 +00001127 // Now that we have created the new alloca instructions, rewrite all the
1128 // uses of the old alloca.
1129 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +00001130
Bob Wilsonb742def2009-12-18 20:14:40 +00001131 // Now erase any instructions that were made dead while rewriting the alloca.
1132 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +00001133 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +00001134
Dan Gohmanfe601042010-06-22 15:08:57 +00001135 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +00001136}
Chris Lattnera59adc42009-12-14 05:11:02 +00001137
Bob Wilsonb742def2009-12-18 20:14:40 +00001138/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1139/// recursively including all their operands that become trivially dead.
1140void SROA::DeleteDeadInstructions() {
1141 while (!DeadInsts.empty()) {
1142 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +00001143
Bob Wilsonb742def2009-12-18 20:14:40 +00001144 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1145 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1146 // Zero out the operand and see if it becomes trivially dead.
1147 // (But, don't add allocas to the dead instruction list -- they are
1148 // already on the worklist and will be deleted separately.)
1149 *OI = 0;
1150 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1151 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +00001152 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001153
1154 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +00001155 }
Chris Lattnera59adc42009-12-14 05:11:02 +00001156}
Bob Wilson69743022011-01-13 20:59:44 +00001157
Bob Wilsonb742def2009-12-18 20:14:40 +00001158/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1159/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001160/// the Info parameter. Offset indicates the position within AI that is
1161/// referenced by this instruction.
Bob Wilsonb742def2009-12-18 20:14:40 +00001162void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001163 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001164 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1165 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +00001166
Bob Wilsonb742def2009-12-18 20:14:40 +00001167 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001168 isSafeForScalarRepl(BC, AI, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001169 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001170 uint64_t GEPOffset = Offset;
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001171 isSafeGEP(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001172 if (!Info.isUnsafe)
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001173 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001174 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001175 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1176 if (Length)
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001177 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
Gabor Greifa6aac4c2010-07-16 09:38:02 +00001178 UI.getOperandNo() == 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001179 else
1180 MarkUnsafe(Info);
1181 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1182 if (!LI->isVolatile()) {
1183 const Type *LIType = LI->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001184 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
Bob Wilsonb742def2009-12-18 20:14:40 +00001185 LIType, false, Info);
1186 } else
1187 MarkUnsafe(Info);
1188 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1189 // Store is ok if storing INTO the pointer, not storing the pointer
1190 if (!SI->isVolatile() && SI->getOperand(0) != I) {
1191 const Type *SIType = SI->getOperand(0)->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001192 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
Bob Wilsonb742def2009-12-18 20:14:40 +00001193 SIType, true, Info);
1194 } else
1195 MarkUnsafe(Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001196 } else {
1197 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
1198 MarkUnsafe(Info);
1199 }
1200 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001201 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001202}
Bob Wilson39c88a62009-12-17 18:34:24 +00001203
Bob Wilsonb742def2009-12-18 20:14:40 +00001204/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1205/// replacement. It is safe when all the indices are constant, in-bounds
1206/// references, and when the resulting offset corresponds to an element within
1207/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001208/// return, Offset is adjusted as specified by the GEP indices.
Bob Wilsonb742def2009-12-18 20:14:40 +00001209void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001210 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001211 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1212 if (GEPIt == E)
1213 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001214
Chris Lattner88e6dc82008-08-23 05:21:06 +00001215 // Walk through the GEP type indices, checking the types that this indexes
1216 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001217 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001218 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001219 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001220 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001221
Bob Wilsonb742def2009-12-18 20:14:40 +00001222 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1223 if (!IdxVal)
1224 return MarkUnsafe(Info);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001225 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001226
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001227 // Compute the offset due to this GEP and check if the alloca has a
1228 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001229 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1230 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1231 &Indices[0], Indices.size());
Bob Wilsonb742def2009-12-18 20:14:40 +00001232 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
1233 MarkUnsafe(Info);
Chris Lattner5e062a12003-05-30 04:15:41 +00001234}
1235
Bob Wilson704d1342011-01-13 17:45:11 +00001236/// isHomogeneousAggregate - Check if type T is a struct or array containing
1237/// elements of the same type (which is always true for arrays). If so,
1238/// return true with NumElts and EltTy set to the number of elements and the
1239/// element type, respectively.
1240static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1241 const Type *&EltTy) {
1242 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1243 NumElts = AT->getNumElements();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001244 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
Bob Wilson704d1342011-01-13 17:45:11 +00001245 return true;
1246 }
1247 if (const StructType *ST = dyn_cast<StructType>(T)) {
1248 NumElts = ST->getNumContainedTypes();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001249 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
Bob Wilson704d1342011-01-13 17:45:11 +00001250 for (unsigned n = 1; n < NumElts; ++n) {
1251 if (ST->getContainedType(n) != EltTy)
1252 return false;
1253 }
1254 return true;
1255 }
1256 return false;
1257}
1258
1259/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1260/// "homogeneous" aggregates with the same element type and number of elements.
1261static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1262 if (T1 == T2)
1263 return true;
1264
1265 unsigned NumElts1, NumElts2;
1266 const Type *EltTy1, *EltTy2;
1267 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1268 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1269 NumElts1 == NumElts2 &&
1270 EltTy1 == EltTy2)
1271 return true;
1272
1273 return false;
1274}
1275
Bob Wilsonb742def2009-12-18 20:14:40 +00001276/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1277/// alloca or has an offset and size that corresponds to a component element
1278/// within it. The offset checked here may have been formed from a GEP with a
1279/// pointer bitcasted to a different type.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001280void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001281 const Type *MemOpType, bool isStore,
1282 AllocaInfo &Info) {
1283 // Check if this is a load/store of the entire alloca.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001284 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilson704d1342011-01-13 17:45:11 +00001285 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1286 // loads/stores (which are essentially the same as the MemIntrinsics with
1287 // regard to copying padding between elements). But, if an alloca is
1288 // flagged as both a source and destination of such operations, we'll need
1289 // to check later for padding between elements.
1290 if (!MemOpType || MemOpType->isIntegerTy()) {
1291 if (isStore)
1292 Info.isMemCpyDst = true;
1293 else
1294 Info.isMemCpySrc = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001295 return;
1296 }
Bob Wilson704d1342011-01-13 17:45:11 +00001297 // This is also safe for references using a type that is compatible with
1298 // the type of the alloca, so that loads/stores can be rewritten using
1299 // insertvalue/extractvalue.
1300 if (isCompatibleAggregate(MemOpType, AI->getAllocatedType()))
1301 return;
Bob Wilsonb742def2009-12-18 20:14:40 +00001302 }
1303 // Check if the offset/size correspond to a component within the alloca type.
1304 const Type *T = AI->getAllocatedType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001305 if (TypeHasComponent(T, Offset, MemSize))
Bob Wilsonb742def2009-12-18 20:14:40 +00001306 return;
1307
1308 return MarkUnsafe(Info);
1309}
1310
1311/// TypeHasComponent - Return true if T has a component type with the
1312/// specified offset and size. If Size is zero, do not check the size.
1313bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1314 const Type *EltTy;
1315 uint64_t EltSize;
1316 if (const StructType *ST = dyn_cast<StructType>(T)) {
1317 const StructLayout *Layout = TD->getStructLayout(ST);
1318 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1319 EltTy = ST->getContainedType(EltIdx);
1320 EltSize = TD->getTypeAllocSize(EltTy);
1321 Offset -= Layout->getElementOffset(EltIdx);
1322 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1323 EltTy = AT->getElementType();
1324 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001325 if (Offset >= AT->getNumElements() * EltSize)
1326 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001327 Offset %= EltSize;
1328 } else {
1329 return false;
1330 }
1331 if (Offset == 0 && (Size == 0 || EltSize == Size))
1332 return true;
1333 // Check if the component spans multiple elements.
1334 if (Offset + Size > EltSize)
1335 return false;
1336 return TypeHasComponent(EltTy, Offset, Size);
1337}
1338
1339/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1340/// the instruction I, which references it, to use the separate elements.
1341/// Offset indicates the position within AI that is referenced by this
1342/// instruction.
1343void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1344 SmallVector<AllocaInst*, 32> &NewElts) {
1345 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1346 Instruction *User = cast<Instruction>(*UI);
1347
1348 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1349 RewriteBitCast(BC, AI, Offset, NewElts);
1350 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1351 RewriteGEP(GEPI, AI, Offset, NewElts);
1352 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1353 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1354 uint64_t MemSize = Length->getZExtValue();
1355 if (Offset == 0 &&
1356 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1357 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001358 // Otherwise the intrinsic can only touch a single element and the
1359 // address operand will be updated, so nothing else needs to be done.
Bob Wilsonb742def2009-12-18 20:14:40 +00001360 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1361 const Type *LIType = LI->getType();
Bob Wilson704d1342011-01-13 17:45:11 +00001362 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001363 // Replace:
1364 // %res = load { i32, i32 }* %alloc
1365 // with:
1366 // %load.0 = load i32* %alloc.0
1367 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1368 // %load.1 = load i32* %alloc.1
1369 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1370 // (Also works for arrays instead of structs)
1371 Value *Insert = UndefValue::get(LIType);
1372 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1373 Value *Load = new LoadInst(NewElts[i], "load", LI);
1374 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1375 }
1376 LI->replaceAllUsesWith(Insert);
1377 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001378 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001379 TD->getTypeAllocSize(LIType) ==
1380 TD->getTypeAllocSize(AI->getAllocatedType())) {
1381 // If this is a load of the entire alloca to an integer, rewrite it.
1382 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1383 }
1384 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1385 Value *Val = SI->getOperand(0);
1386 const Type *SIType = Val->getType();
Bob Wilson704d1342011-01-13 17:45:11 +00001387 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001388 // Replace:
1389 // store { i32, i32 } %val, { i32, i32 }* %alloc
1390 // with:
1391 // %val.0 = extractvalue { i32, i32 } %val, 0
1392 // store i32 %val.0, i32* %alloc.0
1393 // %val.1 = extractvalue { i32, i32 } %val, 1
1394 // store i32 %val.1, i32* %alloc.1
1395 // (Also works for arrays instead of structs)
1396 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1397 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1398 new StoreInst(Extract, NewElts[i], SI);
1399 }
1400 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001401 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001402 TD->getTypeAllocSize(SIType) ==
1403 TD->getTypeAllocSize(AI->getAllocatedType())) {
1404 // If this is a store of the entire alloca from an integer, rewrite it.
1405 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1406 }
1407 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001408 }
1409}
1410
Bob Wilsonb742def2009-12-18 20:14:40 +00001411/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1412/// and recursively continue updating all of its uses.
1413void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1414 SmallVector<AllocaInst*, 32> &NewElts) {
1415 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1416 if (BC->getOperand(0) != AI)
1417 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001418
Bob Wilsonb742def2009-12-18 20:14:40 +00001419 // The bitcast references the original alloca. Replace its uses with
1420 // references to the first new element alloca.
1421 Instruction *Val = NewElts[0];
1422 if (Val->getType() != BC->getDestTy()) {
1423 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1424 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001425 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001426 BC->replaceAllUsesWith(Val);
1427 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001428}
1429
Bob Wilsonb742def2009-12-18 20:14:40 +00001430/// FindElementAndOffset - Return the index of the element containing Offset
1431/// within the specified type, which must be either a struct or an array.
1432/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001433/// element. IdxTy is set to the type of the index result to be used in a
1434/// GEP instruction.
1435uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1436 const Type *&IdxTy) {
1437 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001438 if (const StructType *ST = dyn_cast<StructType>(T)) {
1439 const StructLayout *Layout = TD->getStructLayout(ST);
1440 Idx = Layout->getElementContainingOffset(Offset);
1441 T = ST->getContainedType(Idx);
1442 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001443 IdxTy = Type::getInt32Ty(T->getContext());
1444 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001445 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001446 const ArrayType *AT = cast<ArrayType>(T);
1447 T = AT->getElementType();
1448 uint64_t EltSize = TD->getTypeAllocSize(T);
1449 Idx = Offset / EltSize;
1450 Offset -= Idx * EltSize;
1451 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001452 return Idx;
1453}
1454
1455/// RewriteGEP - Check if this GEP instruction moves the pointer across
1456/// elements of the alloca that are being split apart, and if so, rewrite
1457/// the GEP to be relative to the new element.
1458void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1459 SmallVector<AllocaInst*, 32> &NewElts) {
1460 uint64_t OldOffset = Offset;
1461 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1462 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1463 &Indices[0], Indices.size());
1464
1465 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1466
1467 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00001468 const Type *IdxTy;
1469 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001470 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001471 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001472
1473 T = AI->getAllocatedType();
1474 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001475 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001476
1477 // If this GEP does not move the pointer across elements of the alloca
1478 // being split, then it does not needs to be rewritten.
1479 if (Idx == OldIdx)
1480 return;
1481
1482 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1483 SmallVector<Value*, 8> NewArgs;
1484 NewArgs.push_back(Constant::getNullValue(i32Ty));
1485 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001486 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1487 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00001488 }
1489 Instruction *Val = NewElts[Idx];
1490 if (NewArgs.size() > 1) {
1491 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1492 NewArgs.end(), "", GEPI);
1493 Val->takeName(GEPI);
1494 }
1495 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001496 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001497 GEPI->replaceAllUsesWith(Val);
1498 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001499}
1500
1501/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1502/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00001503void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001504 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00001505 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001506 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00001507 // appropriate type. The "Other" pointer is the pointer that goes to memory
1508 // that doesn't have anything to do with the alloca that we are promoting. For
1509 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00001510 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001511 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00001512 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00001513 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00001514 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001515 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00001516 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00001517 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001518 }
1519 }
Bob Wilson78c50b82009-12-08 18:22:03 +00001520
Chris Lattnerd93afec2009-01-07 07:18:45 +00001521 // If there is an other pointer, we want to convert it to the same pointer
1522 // type as AI has, so we can GEP through it safely.
1523 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00001524 unsigned AddrSpace =
1525 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00001526
1527 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
1528 // optimization, but it's also required to detect the corner case where
1529 // both pointer operands are referencing the same memory, and where
1530 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
1531 // function is only called for mem intrinsics that access the whole
1532 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00001533 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson69743022011-01-13 20:59:44 +00001534
Bob Wilsona756b1d2010-01-19 04:32:48 +00001535 // Copying the alloca to itself is a no-op: just delete it.
1536 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1537 // This code will run twice for a no-op memcpy -- once for each operand.
1538 // Put only one reference to MI on the DeadInsts list.
1539 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1540 E = DeadInsts.end(); I != E; ++I)
1541 if (*I == MI) return;
1542 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001543 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00001544 }
Bob Wilson69743022011-01-13 20:59:44 +00001545
Chris Lattnerd93afec2009-01-07 07:18:45 +00001546 // If the pointer is not the right type, insert a bitcast to the right
1547 // type.
Chris Lattner0238f8c2010-07-08 00:27:05 +00001548 const Type *NewTy =
1549 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson69743022011-01-13 20:59:44 +00001550
Chris Lattner0238f8c2010-07-08 00:27:05 +00001551 if (OtherPtr->getType() != NewTy)
1552 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001553 }
Bob Wilson69743022011-01-13 20:59:44 +00001554
Chris Lattnerd93afec2009-01-07 07:18:45 +00001555 // Process each element of the aggregate.
Bob Wilsonb742def2009-12-18 20:14:40 +00001556 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson69743022011-01-13 20:59:44 +00001557
Owen Anderson1d0be152009-08-13 21:58:54 +00001558 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00001559
1560 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1561 // If this is a memcpy/memmove, emit a GEP of the other element address.
1562 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001563 unsigned OtherEltAlign = MemAlignment;
Bob Wilson69743022011-01-13 20:59:44 +00001564
Bob Wilsona756b1d2010-01-19 04:32:48 +00001565 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001566 Value *Idx[2] = { Zero,
1567 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00001568 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001569 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00001570 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00001571 uint64_t EltOffset;
1572 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001573 const Type *OtherTy = OtherPtrTy->getElementType();
1574 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001575 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1576 } else {
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001577 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001578 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001579 }
Bob Wilson69743022011-01-13 20:59:44 +00001580
Chris Lattner1541e0f2009-03-04 19:20:50 +00001581 // The alignment of the other pointer is the guaranteed alignment of the
1582 // element, which is affected by both the known alignment of the whole
1583 // mem intrinsic and the alignment of the element. If the alignment of
1584 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1585 // known alignment is just 4 bytes.
1586 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00001587 }
Bob Wilson69743022011-01-13 20:59:44 +00001588
Chris Lattnerd93afec2009-01-07 07:18:45 +00001589 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00001590 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson69743022011-01-13 20:59:44 +00001591
Chris Lattnerd93afec2009-01-07 07:18:45 +00001592 // If we got down to a scalar, insert a load or store as appropriate.
1593 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001594 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001595 if (SROADest) {
1596 // From Other to Alloca.
1597 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1598 new StoreInst(Elt, EltPtr, MI);
1599 } else {
1600 // From Alloca to Other.
1601 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1602 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1603 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001604 continue;
1605 }
1606 assert(isa<MemSetInst>(MI));
Bob Wilson69743022011-01-13 20:59:44 +00001607
Chris Lattnerd93afec2009-01-07 07:18:45 +00001608 // If the stored element is zero (common case), just store a null
1609 // constant.
1610 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001611 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001612 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001613 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00001614 } else {
1615 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00001616 const Type *ValTy = EltTy->getScalarType();
1617
Chris Lattnerd93afec2009-01-07 07:18:45 +00001618 // Construct an integer with the right value.
1619 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1620 APInt OneVal(EltSize, CI->getZExtValue());
1621 APInt TotalVal(OneVal);
1622 // Set each byte.
1623 for (unsigned i = 0; 8*i < EltSize; ++i) {
1624 TotalVal = TotalVal.shl(8);
1625 TotalVal |= OneVal;
1626 }
Bob Wilson69743022011-01-13 20:59:44 +00001627
Chris Lattnerd93afec2009-01-07 07:18:45 +00001628 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001629 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001630 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001631 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001632 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001633 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001634 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson69743022011-01-13 20:59:44 +00001635
Chris Lattnerd93afec2009-01-07 07:18:45 +00001636 // If the requested value was a vector constant, create it.
1637 if (EltTy != ValTy) {
1638 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1639 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +00001640 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001641 }
1642 }
1643 new StoreInst(StoreVal, EltPtr, MI);
1644 continue;
1645 }
1646 // Otherwise, if we're storing a byte variable, use a memset call for
1647 // this element.
1648 }
Bob Wilson69743022011-01-13 20:59:44 +00001649
Duncan Sands777d2302009-05-09 07:06:46 +00001650 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001651
Chris Lattner61db1f52010-12-26 22:57:41 +00001652 IRBuilder<> Builder(MI);
Bob Wilson69743022011-01-13 20:59:44 +00001653
Chris Lattnerd93afec2009-01-07 07:18:45 +00001654 // Finally, insert the meminst for this element.
Chris Lattner61db1f52010-12-26 22:57:41 +00001655 if (isa<MemSetInst>(MI)) {
1656 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
1657 MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00001658 } else {
Chris Lattner61db1f52010-12-26 22:57:41 +00001659 assert(isa<MemTransferInst>(MI));
1660 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
1661 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson69743022011-01-13 20:59:44 +00001662
Chris Lattner61db1f52010-12-26 22:57:41 +00001663 if (isa<MemCpyInst>(MI))
1664 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
1665 else
1666 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00001667 }
Chris Lattner372dda82007-03-05 07:52:57 +00001668 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001669 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00001670}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001671
Bob Wilson39fdd692009-12-04 21:57:37 +00001672/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001673/// overwrites the entire allocation. Extract out the pieces of the stored
1674/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001675void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001676 SmallVector<AllocaInst*, 32> &NewElts){
1677 // Extract each element out of the integer according to its structure offset
1678 // and store the element value to the individual alloca.
1679 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00001680 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001681 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001682
Eli Friedman41b33f42009-06-01 09:14:32 +00001683 // Handle tail padding by extending the operand
1684 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001685 SrcVal = new ZExtInst(SrcVal,
Bob Wilson69743022011-01-13 20:59:44 +00001686 IntegerType::get(SI->getContext(), AllocaSizeBits),
Owen Anderson1d0be152009-08-13 21:58:54 +00001687 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001688
David Greene504c7d82010-01-05 01:27:09 +00001689 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00001690 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001691
1692 // There are two forms here: AI could be an array or struct. Both cases
1693 // have different ways to compute the element offset.
1694 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1695 const StructLayout *Layout = TD->getStructLayout(EltSTy);
Bob Wilson69743022011-01-13 20:59:44 +00001696
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001697 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1698 // Get the number of bits to shift SrcVal to get the value.
1699 const Type *FieldTy = EltSTy->getElementType(i);
1700 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson69743022011-01-13 20:59:44 +00001701
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001702 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00001703 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00001704
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001705 Value *EltVal = SrcVal;
1706 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001707 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001708 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1709 "sroa.store.elt", SI);
1710 }
Bob Wilson69743022011-01-13 20:59:44 +00001711
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001712 // Truncate down to an integer of the right size.
1713 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00001714
Chris Lattner583dd602009-01-09 18:18:43 +00001715 // Ignore zero sized fields like {}, they obviously contain no data.
1716 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001717
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001718 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001719 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001720 IntegerType::get(SI->getContext(), FieldSizeBits),
1721 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001722 Value *DestField = NewElts[i];
1723 if (EltVal->getType() == FieldTy) {
1724 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00001725 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001726 // Bitcast to the right element type (for fp/vector values).
1727 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
1728 } else {
1729 // Otherwise, bitcast the dest pointer (for aggregates).
1730 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001731 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001732 "", SI);
1733 }
1734 new StoreInst(EltVal, DestField, SI);
1735 }
Bob Wilson69743022011-01-13 20:59:44 +00001736
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001737 } else {
1738 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1739 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001740 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001741 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1742
1743 uint64_t Shift;
Bob Wilson69743022011-01-13 20:59:44 +00001744
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001745 if (TD->isBigEndian())
1746 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00001747 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001748 Shift = 0;
Bob Wilson69743022011-01-13 20:59:44 +00001749
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001750 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00001751 // Ignore zero sized fields like {}, they obviously contain no data.
1752 if (ElementSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001753
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001754 Value *EltVal = SrcVal;
1755 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001756 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001757 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1758 "sroa.store.elt", SI);
1759 }
Bob Wilson69743022011-01-13 20:59:44 +00001760
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001761 // Truncate down to an integer of the right size.
1762 if (ElementSizeBits != AllocaSizeBits)
Bob Wilson69743022011-01-13 20:59:44 +00001763 EltVal = new TruncInst(EltVal,
1764 IntegerType::get(SI->getContext(),
1765 ElementSizeBits), "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001766 Value *DestField = NewElts[i];
1767 if (EltVal->getType() == ArrayEltTy) {
1768 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001769 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001770 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001771 // Bitcast to the right element type (for fp/vector values).
1772 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1773 } else {
1774 // Otherwise, bitcast the dest pointer (for aggregates).
1775 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001776 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001777 "", SI);
1778 }
1779 new StoreInst(EltVal, DestField, SI);
Bob Wilson69743022011-01-13 20:59:44 +00001780
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001781 if (TD->isBigEndian())
1782 Shift -= ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00001783 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001784 Shift += ElementOffset;
1785 }
1786 }
Bob Wilson69743022011-01-13 20:59:44 +00001787
Bob Wilsonb742def2009-12-18 20:14:40 +00001788 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001789}
1790
Bob Wilson39fdd692009-12-04 21:57:37 +00001791/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001792/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001793void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001794 SmallVector<AllocaInst*, 32> &NewElts) {
1795 // Extract each element out of the NewElts according to its structure offset
1796 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00001797 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001798 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001799
David Greene504c7d82010-01-05 01:27:09 +00001800 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00001801 << '\n');
Bob Wilson69743022011-01-13 20:59:44 +00001802
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001803 // There are two forms here: AI could be an array or struct. Both cases
1804 // have different ways to compute the element offset.
1805 const StructLayout *Layout = 0;
1806 uint64_t ArrayEltBitOffset = 0;
1807 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1808 Layout = TD->getStructLayout(EltSTy);
1809 } else {
1810 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001811 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001812 }
1813
1814 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001815 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson69743022011-01-13 20:59:44 +00001816
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001817 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1818 // Load the value from the alloca. If the NewElt is an aggregate, cast
1819 // the pointer to an integer of the same size before doing the load.
1820 Value *SrcField = NewElts[i];
1821 const Type *FieldTy =
1822 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001823 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00001824
Chris Lattner583dd602009-01-09 18:18:43 +00001825 // Ignore zero sized fields like {}, they obviously contain no data.
1826 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001827
1828 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +00001829 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00001830 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1831 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001832 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001833 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001834 "", LI);
1835 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1836
1837 // If SrcField is a fp or vector of the right size but that isn't an
1838 // integer type, bitcast to an integer so we can shift it.
1839 if (SrcField->getType() != FieldIntTy)
1840 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1841
1842 // Zero extend the field to be the same size as the final alloca so that
1843 // we can shift and insert it.
1844 if (SrcField->getType() != ResultVal->getType())
1845 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson69743022011-01-13 20:59:44 +00001846
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001847 // Determine the number of bits to shift SrcField.
1848 uint64_t Shift;
1849 if (Layout) // Struct case.
1850 Shift = Layout->getElementOffsetInBits(i);
1851 else // Array case.
1852 Shift = i*ArrayEltBitOffset;
Bob Wilson69743022011-01-13 20:59:44 +00001853
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001854 if (TD->isBigEndian())
1855 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson69743022011-01-13 20:59:44 +00001856
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001857 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001858 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001859 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1860 }
1861
Chris Lattner14952472010-06-27 07:58:26 +00001862 // Don't create an 'or x, 0' on the first iteration.
1863 if (!isa<Constant>(ResultVal) ||
1864 !cast<Constant>(ResultVal)->isNullValue())
1865 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1866 else
1867 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001868 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001869
1870 // Handle tail padding by truncating the result
1871 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1872 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1873
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001874 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00001875 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001876}
1877
Duncan Sands3cb36502007-11-04 14:43:57 +00001878/// HasPadding - Return true if the specified type has any structure or
Bob Wilson694a10e2011-01-13 17:45:08 +00001879/// alignment padding in between the elements that would be split apart
1880/// by SROA; return false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001881static bool HasPadding(const Type *Ty, const TargetData &TD) {
Bob Wilson694a10e2011-01-13 17:45:08 +00001882 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1883 Ty = ATy->getElementType();
1884 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001885 }
Bob Wilson694a10e2011-01-13 17:45:08 +00001886
1887 // SROA currently handles only Arrays and Structs.
1888 const StructType *STy = cast<StructType>(Ty);
1889 const StructLayout *SL = TD.getStructLayout(STy);
1890 unsigned PrevFieldBitOffset = 0;
1891 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1892 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1893
1894 // Check to see if there is any padding between this element and the
1895 // previous one.
1896 if (i) {
1897 unsigned PrevFieldEnd =
1898 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1899 if (PrevFieldEnd < FieldBitOffset)
1900 return true;
1901 }
1902 PrevFieldBitOffset = FieldBitOffset;
1903 }
1904 // Check for tail padding.
1905 if (unsigned EltCount = STy->getNumElements()) {
1906 unsigned PrevFieldEnd = PrevFieldBitOffset +
1907 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1908 if (PrevFieldEnd < SL->getSizeInBits())
1909 return true;
1910 }
1911 return false;
Chris Lattner39a1c042007-05-30 06:11:23 +00001912}
Chris Lattner372dda82007-03-05 07:52:57 +00001913
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001914/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1915/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1916/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001917bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001918 // Loop over the use list of the alloca. We can only transform it if all of
1919 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001920 AllocaInfo Info;
Bob Wilson69743022011-01-13 20:59:44 +00001921
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001922 isSafeForScalarRepl(AI, AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001923 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00001924 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001925 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001926 }
Bob Wilson69743022011-01-13 20:59:44 +00001927
Chris Lattner39a1c042007-05-30 06:11:23 +00001928 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1929 // source and destination, we have to be careful. In particular, the memcpy
1930 // could be moving around elements that live in structure padding of the LLVM
1931 // types, but may actually be used. In these cases, we refuse to promote the
1932 // struct.
1933 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001934 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001935 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00001936
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001937 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00001938}
Chris Lattnera1888942005-12-12 07:19:13 +00001939
Chris Lattner800de312008-02-29 07:03:13 +00001940
Chris Lattner79b3bd32007-04-25 06:40:51 +00001941
1942/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1943/// some part of a constant global variable. This intentionally only accepts
1944/// constant expressions because we don't can't rewrite arbitrary instructions.
1945static bool PointsToConstantGlobal(Value *V) {
1946 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1947 return GV->isConstant();
1948 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Bob Wilson69743022011-01-13 20:59:44 +00001949 if (CE->getOpcode() == Instruction::BitCast ||
Chris Lattner79b3bd32007-04-25 06:40:51 +00001950 CE->getOpcode() == Instruction::GetElementPtr)
1951 return PointsToConstantGlobal(CE->getOperand(0));
1952 return false;
1953}
1954
1955/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1956/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1957/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1958/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1959/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
Nick Lewycky081f8002010-11-24 22:04:20 +00001960/// the alloca, and if the source pointer is a pointer to a constant global, we
Chris Lattner79b3bd32007-04-25 06:40:51 +00001961/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00001962static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00001963 bool isOffset) {
1964 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00001965 User *U = cast<Instruction>(*UI);
1966
Chris Lattner2e618492010-11-18 06:20:47 +00001967 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00001968 // Ignore non-volatile loads, they are always ok.
Chris Lattner2e618492010-11-18 06:20:47 +00001969 if (LI->isVolatile()) return false;
1970 continue;
1971 }
Bob Wilson69743022011-01-13 20:59:44 +00001972
Gabor Greif8a8a4352010-04-06 19:32:30 +00001973 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001974 // If uses of the bitcast are ok, we are ok.
1975 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1976 return false;
1977 continue;
1978 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00001979 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001980 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1981 // doesn't, it does.
1982 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1983 isOffset || !GEP->hasAllZeroIndices()))
1984 return false;
1985 continue;
1986 }
Bob Wilson69743022011-01-13 20:59:44 +00001987
Chris Lattner62480652010-11-18 06:41:51 +00001988 if (CallSite CS = U) {
1989 // If this is a readonly/readnone call site, then we know it is just a
1990 // load and we can ignore it.
Chris Lattnera9be1df2010-11-18 06:26:49 +00001991 if (CS.onlyReadsMemory())
1992 continue;
Nick Lewycky081f8002010-11-24 22:04:20 +00001993
1994 // If this is the function being called then we treat it like a load and
1995 // ignore it.
1996 if (CS.isCallee(UI))
1997 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001998
Chris Lattner62480652010-11-18 06:41:51 +00001999 // If this is being passed as a byval argument, the caller is making a
2000 // copy, so it is only a read of the alloca.
2001 unsigned ArgNo = CS.getArgumentNo(UI);
2002 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
2003 continue;
2004 }
Bob Wilson69743022011-01-13 20:59:44 +00002005
Chris Lattner79b3bd32007-04-25 06:40:51 +00002006 // If this is isn't our memcpy/memmove, reject it as something we can't
2007 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00002008 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2009 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00002010 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002011
Chris Lattner2e618492010-11-18 06:20:47 +00002012 // If the transfer is using the alloca as a source of the transfer, then
Chris Lattner2e29ebd2010-11-18 07:32:33 +00002013 // ignore it since it is a load (unless the transfer is volatile).
Chris Lattner2e618492010-11-18 06:20:47 +00002014 if (UI.getOperandNo() == 1) {
2015 if (MI->isVolatile()) return false;
2016 continue;
2017 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00002018
2019 // If we already have seen a copy, reject the second one.
2020 if (TheCopy) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002021
Chris Lattner79b3bd32007-04-25 06:40:51 +00002022 // If the pointer has been offset from the start of the alloca, we can't
2023 // safely handle this.
2024 if (isOffset) return false;
2025
2026 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00002027 if (UI.getOperandNo() != 0) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002028
Chris Lattner79b3bd32007-04-25 06:40:51 +00002029 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00002030 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002031 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002032
Chris Lattner79b3bd32007-04-25 06:40:51 +00002033 // Otherwise, the transform is safe. Remember the copy instruction.
2034 TheCopy = MI;
2035 }
2036 return true;
2037}
2038
2039/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2040/// modified by a copy from a constant global. If we can prove this, we can
2041/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00002042MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
2043 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00002044 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
2045 return TheCopy;
2046 return 0;
2047}