blob: f847e358d16c18060af18c64af57f42ae1d5f83b [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"
Cameron Zwarichb1686c32011-01-18 03:53:26 +000033#include "llvm/Analysis/Dominators.h"
Chris Lattnerc87c50a2011-01-23 22:04:55 +000034#include "llvm/Analysis/Loads.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000035#include "llvm/Analysis/ValueTracking.h"
Chris Lattner38aec322003-09-11 16:45:55 +000036#include "llvm/Target/TargetData.h"
37#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000038#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere0a1a5b2011-01-14 07:50:47 +000039#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattnera9be1df2010-11-18 06:26:49 +000040#include "llvm/Support/CallSite.h"
Chris Lattner95255282006-06-28 23:17:24 +000041#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000042#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000043#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000044#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000045#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000046#include "llvm/Support/raw_ostream.h"
Chris Lattnerc87c50a2011-01-23 22:04:55 +000047#include "llvm/ADT/SetVector.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000048#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000049#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000050using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000051
Chris Lattner0e5f4992006-12-19 21:40:18 +000052STATISTIC(NumReplaced, "Number of allocas broken up");
53STATISTIC(NumPromoted, "Number of allocas promoted");
Chris Lattnerc87c50a2011-01-23 22:04:55 +000054STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
Chris Lattner0e5f4992006-12-19 21:40:18 +000055STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000056STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000057
Chris Lattner0e5f4992006-12-19 21:40:18 +000058namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000059 struct SROA : public FunctionPass {
Cameron Zwarichb1686c32011-01-18 03:53:26 +000060 SROA(int T, bool hasDT, char &ID)
61 : FunctionPass(ID), HasDomTree(hasDT) {
Devang Patelff366852007-07-09 21:19:23 +000062 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000063 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000064 else
65 SRThreshold = T;
66 }
Devang Patel794fd752007-05-01 21:15:47 +000067
Chris Lattnered7b41e2003-05-27 15:45:27 +000068 bool runOnFunction(Function &F);
69
Chris Lattner38aec322003-09-11 16:45:55 +000070 bool performScalarRepl(Function &F);
71 bool performPromotion(Function &F);
72
Chris Lattnered7b41e2003-05-27 15:45:27 +000073 private:
Cameron Zwarichb1686c32011-01-18 03:53:26 +000074 bool HasDomTree;
Chris Lattner56c38522009-01-07 06:34:28 +000075 TargetData *TD;
Bob Wilson69743022011-01-13 20:59:44 +000076
Bob Wilsonb742def2009-12-18 20:14:40 +000077 /// DeadInsts - Keep track of instructions we have made dead, so that
78 /// we can remove them after we are done working.
79 SmallVector<Value*, 32> DeadInsts;
80
Chris Lattner39a1c042007-05-30 06:11:23 +000081 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
82 /// information about the uses. All these fields are initialized to false
83 /// and set to true when something is learned.
84 struct AllocaInfo {
Chris Lattner6c95d242011-01-23 07:29:29 +000085 /// The alloca to promote.
86 AllocaInst *AI;
87
Chris Lattner145c5322011-01-23 08:27:54 +000088 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
89 /// looping and avoid redundant work.
90 SmallPtrSet<PHINode*, 8> CheckedPHIs;
91
Chris Lattner39a1c042007-05-30 06:11:23 +000092 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
93 bool isUnsafe : 1;
Bob Wilson69743022011-01-13 20:59:44 +000094
Chris Lattner39a1c042007-05-30 06:11:23 +000095 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
96 bool isMemCpySrc : 1;
97
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000098 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000099 bool isMemCpyDst : 1;
100
Chris Lattner7e9b4272011-01-16 06:18:28 +0000101 /// hasSubelementAccess - This is true if a subelement of the alloca is
102 /// ever accessed, or false if the alloca is only accessed with mem
103 /// intrinsics or load/store that only access the entire alloca at once.
104 bool hasSubelementAccess : 1;
105
106 /// hasALoadOrStore - This is true if there are any loads or stores to it.
107 /// The alloca may just be accessed with memcpy, for example, which would
108 /// not set this.
109 bool hasALoadOrStore : 1;
110
Chris Lattner6c95d242011-01-23 07:29:29 +0000111 explicit AllocaInfo(AllocaInst *ai)
112 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
Chris Lattner7e9b4272011-01-16 06:18:28 +0000113 hasSubelementAccess(false), hasALoadOrStore(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +0000114 };
Bob Wilson69743022011-01-13 20:59:44 +0000115
Devang Patelff366852007-07-09 21:19:23 +0000116 unsigned SRThreshold;
117
Chris Lattnerd01a0da2011-01-23 07:05:44 +0000118 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
119 I.isUnsafe = true;
120 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
121 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000122
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000123 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000124
Chris Lattner6c95d242011-01-23 07:29:29 +0000125 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
Chris Lattner145c5322011-01-23 08:27:54 +0000126 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
127 AllocaInfo &Info);
Chris Lattner6c95d242011-01-23 07:29:29 +0000128 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
129 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattnerd01a0da2011-01-23 07:05:44 +0000130 const Type *MemOpType, bool isStore, AllocaInfo &Info,
Chris Lattner145c5322011-01-23 08:27:54 +0000131 Instruction *TheAccess, bool AllowWholeAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +0000132 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000133 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
134 const Type *&IdxTy);
Bob Wilson69743022011-01-13 20:59:44 +0000135
136 void DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000137 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000138 void DeleteDeadInstructions();
Bob Wilson69743022011-01-13 20:59:44 +0000139
Bob Wilsonb742def2009-12-18 20:14:40 +0000140 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
141 SmallVector<AllocaInst*, 32> &NewElts);
142 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
143 SmallVector<AllocaInst*, 32> &NewElts);
144 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
145 SmallVector<AllocaInst*, 32> &NewElts);
146 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000147 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000148 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000149 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000150 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000151 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000152 SmallVector<AllocaInst*, 32> &NewElts);
Bob Wilson69743022011-01-13 20:59:44 +0000153
Chris Lattner31d80102010-04-15 21:59:20 +0000154 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000155 };
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000156
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000157 // SROA_DT - SROA that uses DominatorTree.
158 struct SROA_DT : public SROA {
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000159 static char ID;
160 public:
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000161 SROA_DT(int T = -1) : SROA(T, true, ID) {
162 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000163 }
164
165 // getAnalysisUsage - This pass does not require any passes, but we know it
166 // will not alter the CFG, so say so.
167 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
168 AU.addRequired<DominatorTree>();
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000169 AU.setPreservesCFG();
170 }
171 };
172
173 // SROA_SSAUp - SROA that uses SSAUpdater.
174 struct SROA_SSAUp : public SROA {
175 static char ID;
176 public:
177 SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
178 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
179 }
180
181 // getAnalysisUsage - This pass does not require any passes, but we know it
182 // will not alter the CFG, so say so.
183 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
184 AU.setPreservesCFG();
185 }
186 };
187
Chris Lattnered7b41e2003-05-27 15:45:27 +0000188}
189
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000190char SROA_DT::ID = 0;
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000191char SROA_SSAUp::ID = 0;
192
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000193INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
194 "Scalar Replacement of Aggregates (DT)", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000195INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000196INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
197 "Scalar Replacement of Aggregates (DT)", false, false)
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000198
199INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
200 "Scalar Replacement of Aggregates (SSAUp)", false, false)
201INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
202 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000203
Brian Gaeked0fde302003-11-11 22:41:34 +0000204// Public interface to the ScalarReplAggregates pass
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000205FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000206 bool UseDomTree) {
207 if (UseDomTree)
208 return new SROA_DT(Threshold);
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000209 return new SROA_SSAUp(Threshold);
Devang Patelff366852007-07-09 21:19:23 +0000210}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000211
212
Chris Lattner4cc576b2010-04-16 00:24:57 +0000213//===----------------------------------------------------------------------===//
214// Convert To Scalar Optimization.
215//===----------------------------------------------------------------------===//
216
217namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000218/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
219/// optimization, which scans the uses of an alloca and determines if it can
220/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000221class ConvertToScalarInfo {
222 /// AllocaSize - The size of the alloca being considered.
223 unsigned AllocaSize;
224 const TargetData &TD;
Bob Wilson69743022011-01-13 20:59:44 +0000225
Chris Lattnera0bada72010-04-16 02:32:17 +0000226 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000227 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000228 bool IsNotTrivial;
Bob Wilson69743022011-01-13 20:59:44 +0000229
Chris Lattnera001b662010-04-16 00:38:19 +0000230 /// VectorTy - This tracks the type that we should promote the vector to if
231 /// it is possible to turn it into a vector. This starts out null, and if it
232 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000233 const Type *VectorTy;
Bob Wilson69743022011-01-13 20:59:44 +0000234
Chris Lattnera001b662010-04-16 00:38:19 +0000235 /// HadAVector - True if there is at least one vector access to the alloca.
236 /// We don't want to turn random arrays into vectors and use vector element
237 /// insert/extract, but if there are element accesses to something that is
238 /// also declared as a vector, we do want to promote to a vector.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000239 bool HadAVector;
240
241public:
242 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
243 : AllocaSize(Size), TD(td) {
244 IsNotTrivial = false;
245 VectorTy = 0;
246 HadAVector = false;
247 }
Bob Wilson69743022011-01-13 20:59:44 +0000248
Chris Lattnera001b662010-04-16 00:38:19 +0000249 AllocaInst *TryConvert(AllocaInst *AI);
Bob Wilson69743022011-01-13 20:59:44 +0000250
Chris Lattner4cc576b2010-04-16 00:24:57 +0000251private:
252 bool CanConvertToScalar(Value *V, uint64_t Offset);
253 void MergeInType(const Type *In, uint64_t Offset);
254 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Bob Wilson69743022011-01-13 20:59:44 +0000255
Chris Lattner4cc576b2010-04-16 00:24:57 +0000256 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
257 uint64_t Offset, IRBuilder<> &Builder);
258 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
259 uint64_t Offset, IRBuilder<> &Builder);
260};
261} // end anonymous namespace.
262
Chris Lattner91abace2010-09-01 05:14:33 +0000263
Chris Lattnera001b662010-04-16 00:38:19 +0000264/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
265/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
266/// alloca if possible or null if not.
267AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
268 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
269 // out.
270 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
271 return 0;
Bob Wilson69743022011-01-13 20:59:44 +0000272
Chris Lattnera001b662010-04-16 00:38:19 +0000273 // If we were able to find a vector type that can handle this with
274 // insert/extract elements, and if there was at least one use that had
275 // a vector type, promote this to a vector. We don't want to promote
276 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
277 // we just get a lot of insert/extracts. If at least one vector is
278 // involved, then we probably really do have a union of vector/array.
279 const Type *NewTy;
Chris Lattner85a7c692011-01-23 06:40:33 +0000280 if (VectorTy && VectorTy->isVectorTy() && HadAVector) {
Chris Lattnera001b662010-04-16 00:38:19 +0000281 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
282 << *VectorTy << '\n');
283 NewTy = VectorTy; // Use the vector type.
284 } else {
285 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
286 // Create and insert the integer alloca.
287 NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
288 }
289 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
290 ConvertUsesToScalar(AI, NewAI, 0);
291 return NewAI;
292}
293
294/// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
295/// so far at the offset specified by Offset (which is specified in bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000296///
297/// There are two cases we handle here:
298/// 1) A union of vector types of the same size and potentially its elements.
299/// Here we turn element accesses into insert/extract element operations.
300/// This promotes a <4 x float> with a store of float to the third element
301/// into a <4 x float> that uses insert element.
302/// 2) A fully general blob of memory, which we turn into some (potentially
303/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000304/// and stores would mutate the memory. We mark this by setting VectorTy
305/// to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000306void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000307 // If we already decided to turn this into a blob of integer memory, there is
308 // nothing to be done.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000309 if (VectorTy && VectorTy->isVoidTy())
310 return;
Bob Wilson69743022011-01-13 20:59:44 +0000311
Chris Lattner4cc576b2010-04-16 00:24:57 +0000312 // If this could be contributing to a vector, analyze it.
313
314 // If the In type is a vector that is the same size as the alloca, see if it
315 // matches the existing VecTy.
316 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000317 // Remember if we saw a vector type.
318 HadAVector = true;
Bob Wilson69743022011-01-13 20:59:44 +0000319
Chris Lattner4cc576b2010-04-16 00:24:57 +0000320 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
321 // If we're storing/loading a vector of the right size, allow it as a
322 // vector. If this the first vector we see, remember the type so that
Chris Lattnera001b662010-04-16 00:38:19 +0000323 // we know the element size. If this is a subsequent access, ignore it
324 // even if it is a differing type but the same size. Worst case we can
325 // bitcast the resultant vectors.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000326 if (VectorTy == 0)
327 VectorTy = VInTy;
328 return;
329 }
330 } else if (In->isFloatTy() || In->isDoubleTy() ||
331 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
332 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
333 // If we're accessing something that could be an element of a vector, see
334 // if the implied vector agrees with what we already have and if Offset is
335 // compatible with it.
336 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
337 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Bob Wilson69743022011-01-13 20:59:44 +0000338 (VectorTy == 0 ||
Chris Lattner4cc576b2010-04-16 00:24:57 +0000339 cast<VectorType>(VectorTy)->getElementType()
340 ->getPrimitiveSizeInBits()/8 == EltSize)) {
341 if (VectorTy == 0)
342 VectorTy = VectorType::get(In, AllocaSize/EltSize);
343 return;
344 }
345 }
Bob Wilson69743022011-01-13 20:59:44 +0000346
Chris Lattner4cc576b2010-04-16 00:24:57 +0000347 // Otherwise, we have a case that we can't handle with an optimized vector
348 // form. We can still turn this into a large integer.
349 VectorTy = Type::getVoidTy(In->getContext());
350}
351
352/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
353/// its accesses to a single vector type, return true and set VecTy to
354/// the new type. If we could convert the alloca into a single promotable
355/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
356/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
357/// is the current offset from the base of the alloca being analyzed.
358///
359/// If we see at least one access to the value that is as a vector type, set the
360/// SawVec flag.
361bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
362 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
363 Instruction *User = cast<Instruction>(*UI);
Bob Wilson69743022011-01-13 20:59:44 +0000364
Chris Lattner4cc576b2010-04-16 00:24:57 +0000365 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
366 // Don't break volatile loads.
367 if (LI->isVolatile())
368 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000369 // Don't touch MMX operations.
370 if (LI->getType()->isX86_MMXTy())
371 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000372 MergeInType(LI->getType(), Offset);
373 continue;
374 }
Bob Wilson69743022011-01-13 20:59:44 +0000375
Chris Lattner4cc576b2010-04-16 00:24:57 +0000376 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
377 // Storing the pointer, not into the value?
378 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000379 // Don't touch MMX operations.
380 if (SI->getOperand(0)->getType()->isX86_MMXTy())
381 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000382 MergeInType(SI->getOperand(0)->getType(), Offset);
383 continue;
384 }
Bob Wilson69743022011-01-13 20:59:44 +0000385
Chris Lattner4cc576b2010-04-16 00:24:57 +0000386 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000387 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000388 if (!CanConvertToScalar(BCI, Offset))
389 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000390 continue;
391 }
392
393 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
394 // If this is a GEP with a variable indices, we can't handle it.
395 if (!GEP->hasAllConstantIndices())
396 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000397
Chris Lattner4cc576b2010-04-16 00:24:57 +0000398 // Compute the offset that this GEP adds to the pointer.
399 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
400 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
401 &Indices[0], Indices.size());
402 // See if all uses can be converted.
403 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
404 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000405 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000406 continue;
407 }
408
409 // If this is a constant sized memset of a constant value (e.g. 0) we can
410 // handle it.
411 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
412 // Store of constant value and constant size.
Chris Lattnera001b662010-04-16 00:38:19 +0000413 if (!isa<ConstantInt>(MSI->getValue()) ||
414 !isa<ConstantInt>(MSI->getLength()))
415 return false;
416 IsNotTrivial = true; // Can't be mem2reg'd.
417 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000418 }
419
420 // If this is a memcpy or memmove into or out of the whole allocation, we
421 // can handle it like a load or store of the scalar type.
422 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000423 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
424 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
425 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000426
Chris Lattnera001b662010-04-16 00:38:19 +0000427 IsNotTrivial = true; // Can't be mem2reg'd.
428 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000429 }
Bob Wilson69743022011-01-13 20:59:44 +0000430
Chris Lattner4cc576b2010-04-16 00:24:57 +0000431 // Otherwise, we cannot handle this!
432 return false;
433 }
Bob Wilson69743022011-01-13 20:59:44 +0000434
Chris Lattner4cc576b2010-04-16 00:24:57 +0000435 return true;
436}
437
438/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
439/// directly. This happens when we are converting an "integer union" to a
440/// single integer scalar, or when we are converting a "vector union" to a
441/// vector with insert/extractelement instructions.
442///
443/// Offset is an offset from the original alloca, in bits that need to be
444/// shifted to the right. By the end of this, there should be no uses of Ptr.
445void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
446 uint64_t Offset) {
447 while (!Ptr->use_empty()) {
448 Instruction *User = cast<Instruction>(Ptr->use_back());
449
450 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
451 ConvertUsesToScalar(CI, NewAI, Offset);
452 CI->eraseFromParent();
453 continue;
454 }
455
456 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
457 // Compute the offset that this GEP adds to the pointer.
458 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
459 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
460 &Indices[0], Indices.size());
461 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
462 GEP->eraseFromParent();
463 continue;
464 }
Bob Wilson69743022011-01-13 20:59:44 +0000465
Chris Lattner61db1f52010-12-26 22:57:41 +0000466 IRBuilder<> Builder(User);
Bob Wilson69743022011-01-13 20:59:44 +0000467
Chris Lattner4cc576b2010-04-16 00:24:57 +0000468 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
469 // The load is a bit extract from NewAI shifted right by Offset bits.
470 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
471 Value *NewLoadVal
472 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
473 LI->replaceAllUsesWith(NewLoadVal);
474 LI->eraseFromParent();
475 continue;
476 }
Bob Wilson69743022011-01-13 20:59:44 +0000477
Chris Lattner4cc576b2010-04-16 00:24:57 +0000478 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
479 assert(SI->getOperand(0) != Ptr && "Consistency error!");
480 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
481 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
482 Builder);
483 Builder.CreateStore(New, NewAI);
484 SI->eraseFromParent();
Bob Wilson69743022011-01-13 20:59:44 +0000485
Chris Lattner4cc576b2010-04-16 00:24:57 +0000486 // If the load we just inserted is now dead, then the inserted store
487 // overwrote the entire thing.
488 if (Old->use_empty())
489 Old->eraseFromParent();
490 continue;
491 }
Bob Wilson69743022011-01-13 20:59:44 +0000492
Chris Lattner4cc576b2010-04-16 00:24:57 +0000493 // If this is a constant sized memset of a constant value (e.g. 0) we can
494 // transform it into a store of the expanded constant value.
495 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
496 assert(MSI->getRawDest() == Ptr && "Consistency error!");
497 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
498 if (NumBytes != 0) {
499 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson69743022011-01-13 20:59:44 +0000500
Chris Lattner4cc576b2010-04-16 00:24:57 +0000501 // Compute the value replicated the right number of times.
502 APInt APVal(NumBytes*8, Val);
503
504 // Splat the value if non-zero.
505 if (Val)
506 for (unsigned i = 1; i != NumBytes; ++i)
507 APVal |= APVal << 8;
Bob Wilson69743022011-01-13 20:59:44 +0000508
Chris Lattner4cc576b2010-04-16 00:24:57 +0000509 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
510 Value *New = ConvertScalar_InsertValue(
511 ConstantInt::get(User->getContext(), APVal),
512 Old, Offset, Builder);
513 Builder.CreateStore(New, NewAI);
Bob Wilson69743022011-01-13 20:59:44 +0000514
Chris Lattner4cc576b2010-04-16 00:24:57 +0000515 // If the load we just inserted is now dead, then the memset overwrote
516 // the entire thing.
517 if (Old->use_empty())
Bob Wilson69743022011-01-13 20:59:44 +0000518 Old->eraseFromParent();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000519 }
520 MSI->eraseFromParent();
521 continue;
522 }
523
524 // If this is a memcpy or memmove into or out of the whole allocation, we
525 // can handle it like a load or store of the scalar type.
526 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
527 assert(Offset == 0 && "must be store to start of alloca");
Bob Wilson69743022011-01-13 20:59:44 +0000528
Chris Lattner4cc576b2010-04-16 00:24:57 +0000529 // If the source and destination are both to the same alloca, then this is
530 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
531 // as appropriate.
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000532 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
Bob Wilson69743022011-01-13 20:59:44 +0000533
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000534 if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000535 // Dest must be OrigAI, change this to be a load from the original
536 // pointer (bitcasted), then a store to our new alloca.
537 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
538 Value *SrcPtr = MTI->getSource();
Mon P Wange90a6332010-12-23 01:41:32 +0000539 const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
540 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
541 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
542 AIPTy = PointerType::get(AIPTy->getElementType(),
543 SPTy->getAddressSpace());
544 }
545 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
546
Chris Lattner4cc576b2010-04-16 00:24:57 +0000547 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
548 SrcVal->setAlignment(MTI->getAlignment());
549 Builder.CreateStore(SrcVal, NewAI);
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000550 } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000551 // Src must be OrigAI, change this to be a load from NewAI then a store
552 // through the original dest pointer (bitcasted).
553 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
554 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
555
Mon P Wange90a6332010-12-23 01:41:32 +0000556 const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
557 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
558 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
559 AIPTy = PointerType::get(AIPTy->getElementType(),
560 DPTy->getAddressSpace());
561 }
562 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
563
Chris Lattner4cc576b2010-04-16 00:24:57 +0000564 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
565 NewStore->setAlignment(MTI->getAlignment());
566 } else {
567 // Noop transfer. Src == Dst
568 }
569
570 MTI->eraseFromParent();
571 continue;
572 }
Bob Wilson69743022011-01-13 20:59:44 +0000573
Chris Lattner4cc576b2010-04-16 00:24:57 +0000574 llvm_unreachable("Unsupported operation!");
575 }
576}
577
578/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
579/// or vector value FromVal, extracting the bits from the offset specified by
580/// Offset. This returns the value, which is of type ToType.
581///
582/// This happens when we are converting an "integer union" to a single
583/// integer scalar, or when we are converting a "vector union" to a vector with
584/// insert/extractelement instructions.
585///
586/// Offset is an offset from the original alloca, in bits that need to be
587/// shifted to the right.
588Value *ConvertToScalarInfo::
589ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
590 uint64_t Offset, IRBuilder<> &Builder) {
591 // If the load is of the whole new alloca, no conversion is needed.
592 if (FromVal->getType() == ToType && Offset == 0)
593 return FromVal;
594
595 // If the result alloca is a vector type, this is either an element
596 // access or a bitcast to another vector type of the same size.
597 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
598 if (ToType->isVectorTy())
599 return Builder.CreateBitCast(FromVal, ToType, "tmp");
600
601 // Otherwise it must be an element access.
602 unsigned Elt = 0;
603 if (Offset) {
604 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
605 Elt = Offset/EltSize;
606 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
607 }
608 // Return the element extracted out of it.
609 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
610 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
611 if (V->getType() != ToType)
612 V = Builder.CreateBitCast(V, ToType, "tmp");
613 return V;
614 }
Bob Wilson69743022011-01-13 20:59:44 +0000615
Chris Lattner4cc576b2010-04-16 00:24:57 +0000616 // If ToType is a first class aggregate, extract out each of the pieces and
617 // use insertvalue's to form the FCA.
618 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
619 const StructLayout &Layout = *TD.getStructLayout(ST);
620 Value *Res = UndefValue::get(ST);
621 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
622 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
623 Offset+Layout.getElementOffsetInBits(i),
624 Builder);
625 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
626 }
627 return Res;
628 }
Bob Wilson69743022011-01-13 20:59:44 +0000629
Chris Lattner4cc576b2010-04-16 00:24:57 +0000630 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
631 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
632 Value *Res = UndefValue::get(AT);
633 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
634 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
635 Offset+i*EltSize, Builder);
636 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
637 }
638 return Res;
639 }
640
641 // Otherwise, this must be a union that was converted to an integer value.
642 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
643
644 // If this is a big-endian system and the load is narrower than the
645 // full alloca type, we need to do a shift to get the right bits.
646 int ShAmt = 0;
647 if (TD.isBigEndian()) {
648 // On big-endian machines, the lowest bit is stored at the bit offset
649 // from the pointer given by getTypeStoreSizeInBits. This matters for
650 // integers with a bitwidth that is not a multiple of 8.
651 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
652 TD.getTypeStoreSizeInBits(ToType) - Offset;
653 } else {
654 ShAmt = Offset;
655 }
656
657 // Note: we support negative bitwidths (with shl) which are not defined.
658 // We do this to support (f.e.) loads off the end of a structure where
659 // only some bits are used.
660 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
661 FromVal = Builder.CreateLShr(FromVal,
662 ConstantInt::get(FromVal->getType(),
663 ShAmt), "tmp");
664 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson69743022011-01-13 20:59:44 +0000665 FromVal = Builder.CreateShl(FromVal,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000666 ConstantInt::get(FromVal->getType(),
667 -ShAmt), "tmp");
668
669 // Finally, unconditionally truncate the integer to the right width.
670 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
671 if (LIBitWidth < NTy->getBitWidth())
672 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000673 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000674 LIBitWidth), "tmp");
675 else if (LIBitWidth > NTy->getBitWidth())
676 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000677 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000678 LIBitWidth), "tmp");
679
680 // If the result is an integer, this is a trunc or bitcast.
681 if (ToType->isIntegerTy()) {
682 // Should be done.
683 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
684 // Just do a bitcast, we know the sizes match up.
685 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
686 } else {
687 // Otherwise must be a pointer.
688 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
689 }
690 assert(FromVal->getType() == ToType && "Didn't convert right?");
691 return FromVal;
692}
693
694/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
695/// or vector value "Old" at the offset specified by Offset.
696///
697/// This happens when we are converting an "integer union" to a
698/// single integer scalar, or when we are converting a "vector union" to a
699/// vector with insert/extractelement instructions.
700///
701/// Offset is an offset from the original alloca, in bits that need to be
702/// shifted to the right.
703Value *ConvertToScalarInfo::
704ConvertScalar_InsertValue(Value *SV, Value *Old,
705 uint64_t Offset, IRBuilder<> &Builder) {
706 // Convert the stored type to the actual type, shift it left to insert
707 // then 'or' into place.
708 const Type *AllocaType = Old->getType();
709 LLVMContext &Context = Old->getContext();
710
711 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
712 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
713 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
Bob Wilson69743022011-01-13 20:59:44 +0000714
Chris Lattner4cc576b2010-04-16 00:24:57 +0000715 // Changing the whole vector with memset or with an access of a different
716 // vector type?
717 if (ValSize == VecSize)
718 return Builder.CreateBitCast(SV, AllocaType, "tmp");
719
720 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
721
722 // Must be an element insertion.
723 unsigned Elt = Offset/EltSize;
Bob Wilson69743022011-01-13 20:59:44 +0000724
Chris Lattner4cc576b2010-04-16 00:24:57 +0000725 if (SV->getType() != VTy->getElementType())
726 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000727
728 SV = Builder.CreateInsertElement(Old, SV,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000729 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
730 "tmp");
731 return SV;
732 }
Bob Wilson69743022011-01-13 20:59:44 +0000733
Chris Lattner4cc576b2010-04-16 00:24:57 +0000734 // If SV is a first-class aggregate value, insert each value recursively.
735 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
736 const StructLayout &Layout = *TD.getStructLayout(ST);
737 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
738 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000739 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000740 Offset+Layout.getElementOffsetInBits(i),
741 Builder);
742 }
743 return Old;
744 }
Bob Wilson69743022011-01-13 20:59:44 +0000745
Chris Lattner4cc576b2010-04-16 00:24:57 +0000746 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
747 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
748 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
749 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
750 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
751 }
752 return Old;
753 }
754
755 // If SV is a float, convert it to the appropriate integer type.
756 // If it is a pointer, do the same.
757 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
758 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
759 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
760 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
761 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
762 SV = Builder.CreateBitCast(SV,
763 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
764 else if (SV->getType()->isPointerTy())
765 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
766
767 // Zero extend or truncate the value if needed.
768 if (SV->getType() != AllocaType) {
769 if (SV->getType()->getPrimitiveSizeInBits() <
770 AllocaType->getPrimitiveSizeInBits())
771 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
772 else {
773 // Truncation may be needed if storing more than the alloca can hold
774 // (undefined behavior).
775 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
776 SrcWidth = DestWidth;
777 SrcStoreWidth = DestStoreWidth;
778 }
779 }
780
781 // If this is a big-endian system and the store is narrower than the
782 // full alloca type, we need to do a shift to get the right bits.
783 int ShAmt = 0;
784 if (TD.isBigEndian()) {
785 // On big-endian machines, the lowest bit is stored at the bit offset
786 // from the pointer given by getTypeStoreSizeInBits. This matters for
787 // integers with a bitwidth that is not a multiple of 8.
788 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
789 } else {
790 ShAmt = Offset;
791 }
792
793 // Note: we support negative bitwidths (with shr) which are not defined.
794 // We do this to support (f.e.) stores off the end of a structure where
795 // only some bits in the structure are set.
796 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
797 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
798 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
799 ShAmt), "tmp");
800 Mask <<= ShAmt;
801 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
802 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
803 -ShAmt), "tmp");
804 Mask = Mask.lshr(-ShAmt);
805 }
806
807 // Mask out the bits we are about to insert from the old value, and or
808 // in the new bits.
809 if (SrcWidth != DestWidth) {
810 assert(DestWidth > SrcWidth);
811 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
812 SV = Builder.CreateOr(Old, SV, "ins");
813 }
814 return SV;
815}
816
817
818//===----------------------------------------------------------------------===//
819// SRoA Driver
820//===----------------------------------------------------------------------===//
821
822
Chris Lattnered7b41e2003-05-27 15:45:27 +0000823bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000824 TD = getAnalysisIfAvailable<TargetData>();
825
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000826 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000827
828 // FIXME: ScalarRepl currently depends on TargetData more than it
829 // theoretically needs to. It should be refactored in order to support
830 // target-independent IR. Until this is done, just skip the actual
831 // scalar-replacement portion of this pass.
832 if (!TD) return Changed;
833
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000834 while (1) {
835 bool LocalChange = performScalarRepl(F);
836 if (!LocalChange) break; // No need to repromote if no scalarrepl
837 Changed = true;
838 LocalChange = performPromotion(F);
839 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
840 }
Chris Lattner38aec322003-09-11 16:45:55 +0000841
842 return Changed;
843}
844
Chris Lattnerd0f56132011-01-14 19:50:47 +0000845namespace {
846class AllocaPromoter : public LoadAndStorePromoter {
847 AllocaInst *AI;
848public:
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000849 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S)
850 : LoadAndStorePromoter(Insts, S), AI(0) {}
Chris Lattnerd0f56132011-01-14 19:50:47 +0000851
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000852 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerd0f56132011-01-14 19:50:47 +0000853 // Remember which alloca we're promoting (for isInstInList).
854 this->AI = AI;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000855 LoadAndStorePromoter::run(Insts);
Chris Lattnerd0f56132011-01-14 19:50:47 +0000856 AI->eraseFromParent();
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000857 }
858
Chris Lattnerd0f56132011-01-14 19:50:47 +0000859 virtual bool isInstInList(Instruction *I,
860 const SmallVectorImpl<Instruction*> &Insts) const {
861 if (LoadInst *LI = dyn_cast<LoadInst>(I))
862 return LI->getOperand(0) == AI;
863 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000864 }
Chris Lattnerd0f56132011-01-14 19:50:47 +0000865};
866} // end anon namespace
Chris Lattner38aec322003-09-11 16:45:55 +0000867
Chris Lattnerc87c50a2011-01-23 22:04:55 +0000868/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
869/// subsequently loaded can be rewritten to load both input pointers and then
870/// select between the result, allowing the load of the alloca to be promoted.
871/// From this:
872/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
873/// %V = load i32* %P2
874/// to:
875/// %V1 = load i32* %Alloca -> will be mem2reg'd
876/// %V2 = load i32* %Other
Chris Lattnere3357862011-01-24 01:07:11 +0000877/// %V = select i1 %cond, i32 %V1, i32 %V2
Chris Lattnerc87c50a2011-01-23 22:04:55 +0000878///
879/// We can do this to a select if its only uses are loads and if the operand to
880/// the select can be loaded unconditionally.
881static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
882 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
883 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
884
885 for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
886 UI != UE; ++UI) {
887 LoadInst *LI = dyn_cast<LoadInst>(*UI);
888 if (LI == 0 || LI->isVolatile()) return false;
889
Chris Lattnere3357862011-01-24 01:07:11 +0000890 // Both operands to the select need to be dereferencable, either absolutely
Chris Lattnerc87c50a2011-01-23 22:04:55 +0000891 // (e.g. allocas) or at this point because we can see other accesses to it.
892 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
893 LI->getAlignment(), TD))
894 return false;
895 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
896 LI->getAlignment(), TD))
897 return false;
898 }
899
900 return true;
901}
902
Chris Lattnere3357862011-01-24 01:07:11 +0000903/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
904/// subsequently loaded can be rewritten to load both input pointers in the pred
905/// blocks and then PHI the results, allowing the load of the alloca to be
906/// promoted.
907/// From this:
908/// %P2 = phi [i32* %Alloca, i32* %Other]
909/// %V = load i32* %P2
910/// to:
911/// %V1 = load i32* %Alloca -> will be mem2reg'd
912/// ...
913/// %V2 = load i32* %Other
914/// ...
915/// %V = phi [i32 %V1, i32 %V2]
916///
917/// We can do this to a select if its only uses are loads and if the operand to
918/// the select can be loaded unconditionally.
919static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
920 // For now, we can only do this promotion if the load is in the same block as
921 // the PHI, and if there are no stores between the phi and load.
922 // TODO: Allow recursive phi users.
923 // TODO: Allow stores.
924 BasicBlock *BB = PN->getParent();
925 unsigned MaxAlign = 0;
926 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
927 UI != UE; ++UI) {
928 LoadInst *LI = dyn_cast<LoadInst>(*UI);
929 if (LI == 0 || LI->isVolatile()) return false;
930
931 // For now we only allow loads in the same block as the PHI. This is a
932 // common case that happens when instcombine merges two loads through a PHI.
933 if (LI->getParent() != BB) return false;
934
935 // Ensure that there are no instructions between the PHI and the load that
936 // could store.
937 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
938 if (BBI->mayWriteToMemory())
939 return false;
940
941 MaxAlign = std::max(MaxAlign, LI->getAlignment());
942 }
943
944 // Okay, we know that we have one or more loads in the same block as the PHI.
945 // We can transform this if it is safe to push the loads into the predecessor
946 // blocks. The only thing to watch out for is that we can't put a possibly
947 // trapping load in the predecessor if it is a critical edge.
948 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
949 BasicBlock *Pred = PN->getIncomingBlock(i);
950
951 // If the predecessor has a single successor, then the edge isn't critical.
952 if (Pred->getTerminator()->getNumSuccessors() == 1)
953 continue;
954
955 Value *InVal = PN->getIncomingValue(i);
956
957 // If the InVal is an invoke in the pred, we can't put a load on the edge.
958 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
959 if (II->getParent() == Pred)
960 return false;
961
962 // If this pointer is always safe to load, or if we can prove that there is
963 // already a load in the block, then we can move the load to the pred block.
964 if (InVal->isDereferenceablePointer() ||
965 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
966 continue;
967
968 return false;
969 }
970
971 return true;
972}
973
Chris Lattnerc87c50a2011-01-23 22:04:55 +0000974
975/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
976/// direct (non-volatile) loads and stores to it. If the alloca is close but
977/// not quite there, this will transform the code to allow promotion. As such,
978/// it is a non-pure predicate.
979static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
980 SetVector<Instruction*, SmallVector<Instruction*, 4>,
981 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
982
983 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
984 UI != UE; ++UI) {
985 User *U = *UI;
986 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
987 if (LI->isVolatile())
988 return false;
989 continue;
990 }
991
992 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
993 if (SI->getOperand(0) == AI || SI->isVolatile())
994 return false; // Don't allow a store OF the AI, only INTO the AI.
995 continue;
996 }
997
998 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
999 // If the condition being selected on is a constant, fold the select, yes
1000 // this does (rarely) happen early on.
1001 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1002 Value *Result = SI->getOperand(1+CI->isZero());
1003 SI->replaceAllUsesWith(Result);
1004 SI->eraseFromParent();
1005
1006 // This is very rare and we just scrambled the use list of AI, start
1007 // over completely.
1008 return tryToMakeAllocaBePromotable(AI, TD);
1009 }
1010
1011 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1012 // loads, then we can transform this by rewriting the select.
1013 if (!isSafeSelectToSpeculate(SI, TD))
1014 return false;
1015
1016 InstsToRewrite.insert(SI);
1017 continue;
1018 }
1019
Chris Lattnere3357862011-01-24 01:07:11 +00001020 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1021 if (PN->use_empty()) { // Dead PHIs can be stripped.
1022 InstsToRewrite.insert(PN);
1023 continue;
1024 }
1025
1026 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1027 // in the pred blocks, then we can transform this by rewriting the PHI.
1028 if (!isSafePHIToSpeculate(PN, TD))
1029 return false;
1030
1031 InstsToRewrite.insert(PN);
1032 continue;
1033 }
1034
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001035 return false;
1036 }
1037
1038 // If there are no instructions to rewrite, then all uses are load/stores and
1039 // we're done!
1040 if (InstsToRewrite.empty())
1041 return true;
1042
1043 // If we have instructions that need to be rewritten for this to be promotable
1044 // take care of it now.
1045 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
Chris Lattnere3357862011-01-24 01:07:11 +00001046 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1047 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1048 // loads with a new select.
1049 while (!SI->use_empty()) {
1050 LoadInst *LI = cast<LoadInst>(SI->use_back());
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001051
Chris Lattnere3357862011-01-24 01:07:11 +00001052 IRBuilder<> Builder(LI);
1053 LoadInst *TrueLoad =
1054 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1055 LoadInst *FalseLoad =
1056 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".t");
1057
1058 // Transfer alignment and TBAA info if present.
1059 TrueLoad->setAlignment(LI->getAlignment());
1060 FalseLoad->setAlignment(LI->getAlignment());
1061 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1062 TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1063 FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1064 }
1065
1066 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1067 V->takeName(LI);
1068 LI->replaceAllUsesWith(V);
1069 LI->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001070 }
Chris Lattnere3357862011-01-24 01:07:11 +00001071
1072 // Now that all the loads are gone, the select is gone too.
1073 SI->eraseFromParent();
1074 continue;
1075 }
1076
1077 // Otherwise, we have a PHI node which allows us to push the loads into the
1078 // predecessors.
1079 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1080 if (PN->use_empty()) {
1081 PN->eraseFromParent();
1082 continue;
1083 }
1084
1085 const Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
1086 PHINode *NewPN = PHINode::Create(LoadTy, PN->getName()+".ld", PN);
1087
1088 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1089 // matter which one we get and if any differ, it doesn't matter.
1090 LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1091 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1092 unsigned Align = SomeLoad->getAlignment();
1093
1094 // Rewrite all loads of the PN to use the new PHI.
1095 while (!PN->use_empty()) {
1096 LoadInst *LI = cast<LoadInst>(PN->use_back());
1097 LI->replaceAllUsesWith(NewPN);
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001098 LI->eraseFromParent();
1099 }
1100
Chris Lattnere3357862011-01-24 01:07:11 +00001101 // Inject loads into all of the pred blocks. Keep track of which blocks we
1102 // insert them into in case we have multiple edges from the same block.
1103 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1104
1105 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1106 BasicBlock *Pred = PN->getIncomingBlock(i);
1107 LoadInst *&Load = InsertedLoads[Pred];
1108 if (Load == 0) {
1109 Load = new LoadInst(PN->getIncomingValue(i),
1110 PN->getName() + "." + Pred->getName(),
1111 Pred->getTerminator());
1112 Load->setAlignment(Align);
1113 if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1114 }
1115
1116 NewPN->addIncoming(Load, Pred);
1117 }
1118
1119 PN->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001120 }
1121
1122 ++NumAdjusted;
1123 return true;
1124}
1125
1126
Chris Lattner38aec322003-09-11 16:45:55 +00001127bool SROA::performPromotion(Function &F) {
1128 std::vector<AllocaInst*> Allocas;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001129 DominatorTree *DT = 0;
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001130 if (HasDomTree)
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001131 DT = &getAnalysis<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +00001132
Chris Lattner02a3be02003-09-20 14:39:18 +00001133 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +00001134
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001135 bool Changed = false;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001136 SmallVector<Instruction*, 64> Insts;
Chris Lattner38aec322003-09-11 16:45:55 +00001137 while (1) {
1138 Allocas.clear();
1139
1140 // Find allocas that are safe to promote, by looking at all instructions in
1141 // the entry node
1142 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1143 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001144 if (tryToMakeAllocaBePromotable(AI, TD))
Chris Lattner38aec322003-09-11 16:45:55 +00001145 Allocas.push_back(AI);
1146
1147 if (Allocas.empty()) break;
1148
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001149 if (HasDomTree)
Cameron Zwarich419e8a62011-01-17 17:38:41 +00001150 PromoteMemToReg(Allocas, *DT);
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001151 else {
1152 SSAUpdater SSA;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001153 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1154 AllocaInst *AI = Allocas[i];
1155
1156 // Build list of instructions to promote.
1157 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1158 UI != E; ++UI)
1159 Insts.push_back(cast<Instruction>(*UI));
1160
1161 AllocaPromoter(Insts, SSA).run(AI, Insts);
1162 Insts.clear();
1163 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001164 }
Chris Lattner38aec322003-09-11 16:45:55 +00001165 NumPromoted += Allocas.size();
1166 Changed = true;
1167 }
1168
1169 return Changed;
1170}
1171
Chris Lattner4cc576b2010-04-16 00:24:57 +00001172
Bob Wilson3992feb2010-02-03 17:23:56 +00001173/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1174/// SROA. It must be a struct or array type with a small number of elements.
1175static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
1176 const Type *T = AI->getAllocatedType();
1177 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +00001178 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +00001179 return ST->getNumElements() <= 32;
1180 // Arrays are much less likely to be safe for SROA; only consider
1181 // them if they are very small.
1182 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1183 return AT->getNumElements() <= 8;
1184 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +00001185}
1186
Chris Lattnerc4472072010-04-15 23:50:26 +00001187
Chris Lattner38aec322003-09-11 16:45:55 +00001188// performScalarRepl - This algorithm is a simple worklist driven algorithm,
1189// which runs on all of the malloc/alloca instructions in the function, removing
1190// them if they are only used by getelementptr instructions.
1191//
1192bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001193 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +00001194
Chris Lattner31d80102010-04-15 21:59:20 +00001195 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +00001196 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001197 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +00001198 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +00001199 WorkList.push_back(A);
1200
1201 // Process the worklist
1202 bool Changed = false;
1203 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001204 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001205 WorkList.pop_back();
Bob Wilson69743022011-01-13 20:59:44 +00001206
Chris Lattneradd2bd72006-12-22 23:14:42 +00001207 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1208 // with unused elements.
1209 if (AI->use_empty()) {
1210 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +00001211 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +00001212 continue;
1213 }
Chris Lattner7809ecd2009-02-03 01:30:09 +00001214
1215 // If this alloca is impossible for us to promote, reject it early.
1216 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1217 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001218
Chris Lattner79b3bd32007-04-25 06:40:51 +00001219 // Check to see if this allocation is only modified by a memcpy/memmove from
1220 // a constant global. If this is the case, we can change all users to use
1221 // the constant global instead. This is commonly produced by the CFE by
1222 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1223 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +00001224 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +00001225 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
1226 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +00001227 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001228 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +00001229 TheCopy->eraseFromParent(); // Don't mutate the global.
1230 AI->eraseFromParent();
1231 ++NumGlobals;
1232 Changed = true;
1233 continue;
1234 }
Bob Wilson69743022011-01-13 20:59:44 +00001235
Chris Lattner7809ecd2009-02-03 01:30:09 +00001236 // Check to see if we can perform the core SROA transformation. We cannot
1237 // transform the allocation instruction if it is an array allocation
1238 // (allocations OF arrays are ok though), and an allocation of a scalar
1239 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +00001240 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +00001241
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +00001242 // Do not promote [0 x %struct].
1243 if (AllocaSize == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001244
Chris Lattner31d80102010-04-15 21:59:20 +00001245 // Do not promote any struct whose size is too big.
1246 if (AllocaSize > SRThreshold) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001247
Bob Wilson3992feb2010-02-03 17:23:56 +00001248 // If the alloca looks like a good candidate for scalar replacement, and if
1249 // all its users can be transformed, then split up the aggregate into its
1250 // separate elements.
1251 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1252 DoScalarReplacement(AI, WorkList);
1253 Changed = true;
1254 continue;
1255 }
1256
Chris Lattner6e733d32009-01-28 20:16:43 +00001257 // If we can turn this aggregate value (potentially with casts) into a
1258 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001259 // IsNotTrivial tracks whether this is something that mem2reg could have
1260 // promoted itself. If so, we don't want to transform it needlessly. Note
1261 // that we can't just check based on the type: the alloca may be of an i32
1262 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +00001263 if (AllocaInst *NewAI =
1264 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001265 NewAI->takeName(AI);
1266 AI->eraseFromParent();
1267 ++NumConverted;
1268 Changed = true;
1269 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001270 }
1271
Chris Lattner7809ecd2009-02-03 01:30:09 +00001272 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +00001273 }
1274
1275 return Changed;
1276}
Chris Lattner5e062a12003-05-30 04:15:41 +00001277
Chris Lattnera10b29b2007-04-25 05:02:56 +00001278/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1279/// predicate, do SROA now.
Bob Wilson69743022011-01-13 20:59:44 +00001280void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001281 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +00001282 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +00001283 SmallVector<AllocaInst*, 32> ElementAllocas;
1284 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1285 ElementAllocas.reserve(ST->getNumContainedTypes());
1286 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Bob Wilson69743022011-01-13 20:59:44 +00001287 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +00001288 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001289 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001290 ElementAllocas.push_back(NA);
1291 WorkList.push_back(NA); // Add to worklist for recursive processing
1292 }
1293 } else {
1294 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1295 ElementAllocas.reserve(AT->getNumElements());
1296 const Type *ElTy = AT->getElementType();
1297 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +00001298 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001299 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001300 ElementAllocas.push_back(NA);
1301 WorkList.push_back(NA); // Add to worklist for recursive processing
1302 }
1303 }
1304
Bob Wilsonb742def2009-12-18 20:14:40 +00001305 // Now that we have created the new alloca instructions, rewrite all the
1306 // uses of the old alloca.
1307 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +00001308
Bob Wilsonb742def2009-12-18 20:14:40 +00001309 // Now erase any instructions that were made dead while rewriting the alloca.
1310 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +00001311 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +00001312
Dan Gohmanfe601042010-06-22 15:08:57 +00001313 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +00001314}
Chris Lattnera59adc42009-12-14 05:11:02 +00001315
Bob Wilsonb742def2009-12-18 20:14:40 +00001316/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1317/// recursively including all their operands that become trivially dead.
1318void SROA::DeleteDeadInstructions() {
1319 while (!DeadInsts.empty()) {
1320 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +00001321
Bob Wilsonb742def2009-12-18 20:14:40 +00001322 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1323 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1324 // Zero out the operand and see if it becomes trivially dead.
1325 // (But, don't add allocas to the dead instruction list -- they are
1326 // already on the worklist and will be deleted separately.)
1327 *OI = 0;
1328 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1329 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +00001330 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001331
1332 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +00001333 }
Chris Lattnera59adc42009-12-14 05:11:02 +00001334}
Bob Wilson69743022011-01-13 20:59:44 +00001335
Bob Wilsonb742def2009-12-18 20:14:40 +00001336/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1337/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001338/// the Info parameter. Offset indicates the position within AI that is
1339/// referenced by this instruction.
Chris Lattner6c95d242011-01-23 07:29:29 +00001340void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001341 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001342 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1343 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +00001344
Bob Wilsonb742def2009-12-18 20:14:40 +00001345 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Chris Lattner6c95d242011-01-23 07:29:29 +00001346 isSafeForScalarRepl(BC, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001347 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001348 uint64_t GEPOffset = Offset;
Chris Lattner6c95d242011-01-23 07:29:29 +00001349 isSafeGEP(GEPI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001350 if (!Info.isUnsafe)
Chris Lattner6c95d242011-01-23 07:29:29 +00001351 isSafeForScalarRepl(GEPI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001352 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001353 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001354 if (Length == 0)
1355 return MarkUnsafe(Info, User);
Chris Lattner6c95d242011-01-23 07:29:29 +00001356 isSafeMemAccess(Offset, Length->getZExtValue(), 0,
Chris Lattner145c5322011-01-23 08:27:54 +00001357 UI.getOperandNo() == 0, Info, MI,
1358 true /*AllowWholeAccess*/);
Bob Wilsonb742def2009-12-18 20:14:40 +00001359 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001360 if (LI->isVolatile())
1361 return MarkUnsafe(Info, User);
1362 const Type *LIType = LI->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001363 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001364 LIType, false, Info, LI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001365 Info.hasALoadOrStore = true;
1366
Bob Wilsonb742def2009-12-18 20:14:40 +00001367 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1368 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001369 if (SI->isVolatile() || SI->getOperand(0) == I)
1370 return MarkUnsafe(Info, User);
1371
1372 const Type *SIType = SI->getOperand(0)->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001373 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001374 SIType, true, Info, SI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001375 Info.hasALoadOrStore = true;
Chris Lattner145c5322011-01-23 08:27:54 +00001376 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1377 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1378 } else {
1379 return MarkUnsafe(Info, User);
1380 }
1381 if (Info.isUnsafe) return;
1382 }
1383}
1384
1385
1386/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1387/// derived from the alloca, we can often still split the alloca into elements.
1388/// This is useful if we have a large alloca where one element is phi'd
1389/// together somewhere: we can SRoA and promote all the other elements even if
1390/// we end up not being able to promote this one.
1391///
1392/// All we require is that the uses of the PHI do not index into other parts of
1393/// the alloca. The most important use case for this is single load and stores
1394/// that are PHI'd together, which can happen due to code sinking.
1395void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1396 AllocaInfo &Info) {
1397 // If we've already checked this PHI, don't do it again.
1398 if (PHINode *PN = dyn_cast<PHINode>(I))
1399 if (!Info.CheckedPHIs.insert(PN))
1400 return;
1401
1402 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1403 Instruction *User = cast<Instruction>(*UI);
1404
1405 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1406 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1407 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1408 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1409 // but would have to prove that we're staying inside of an element being
1410 // promoted.
1411 if (!GEPI->hasAllZeroIndices())
1412 return MarkUnsafe(Info, User);
1413 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1414 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1415 if (LI->isVolatile())
1416 return MarkUnsafe(Info, User);
1417 const Type *LIType = LI->getType();
1418 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1419 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1420 Info.hasALoadOrStore = true;
1421
1422 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1423 // Store is ok if storing INTO the pointer, not storing the pointer
1424 if (SI->isVolatile() || SI->getOperand(0) == I)
1425 return MarkUnsafe(Info, User);
1426
1427 const Type *SIType = SI->getOperand(0)->getType();
1428 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1429 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1430 Info.hasALoadOrStore = true;
1431 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1432 isSafePHISelectUseForScalarRepl(User, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001433 } else {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001434 return MarkUnsafe(Info, User);
Bob Wilsonb742def2009-12-18 20:14:40 +00001435 }
1436 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001437 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001438}
Bob Wilson39c88a62009-12-17 18:34:24 +00001439
Bob Wilsonb742def2009-12-18 20:14:40 +00001440/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1441/// replacement. It is safe when all the indices are constant, in-bounds
1442/// references, and when the resulting offset corresponds to an element within
1443/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001444/// return, Offset is adjusted as specified by the GEP indices.
Chris Lattner6c95d242011-01-23 07:29:29 +00001445void SROA::isSafeGEP(GetElementPtrInst *GEPI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001446 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001447 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1448 if (GEPIt == E)
1449 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001450
Chris Lattner88e6dc82008-08-23 05:21:06 +00001451 // Walk through the GEP type indices, checking the types that this indexes
1452 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001453 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001454 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001455 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001456 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001457
Bob Wilsonb742def2009-12-18 20:14:40 +00001458 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1459 if (!IdxVal)
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001460 return MarkUnsafe(Info, GEPI);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001461 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001462
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001463 // Compute the offset due to this GEP and check if the alloca has a
1464 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001465 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1466 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1467 &Indices[0], Indices.size());
Chris Lattner6c95d242011-01-23 07:29:29 +00001468 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001469 MarkUnsafe(Info, GEPI);
Chris Lattner5e062a12003-05-30 04:15:41 +00001470}
1471
Bob Wilson704d1342011-01-13 17:45:11 +00001472/// isHomogeneousAggregate - Check if type T is a struct or array containing
1473/// elements of the same type (which is always true for arrays). If so,
1474/// return true with NumElts and EltTy set to the number of elements and the
1475/// element type, respectively.
1476static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1477 const Type *&EltTy) {
1478 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1479 NumElts = AT->getNumElements();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001480 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
Bob Wilson704d1342011-01-13 17:45:11 +00001481 return true;
1482 }
1483 if (const StructType *ST = dyn_cast<StructType>(T)) {
1484 NumElts = ST->getNumContainedTypes();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001485 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
Bob Wilson704d1342011-01-13 17:45:11 +00001486 for (unsigned n = 1; n < NumElts; ++n) {
1487 if (ST->getContainedType(n) != EltTy)
1488 return false;
1489 }
1490 return true;
1491 }
1492 return false;
1493}
1494
1495/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1496/// "homogeneous" aggregates with the same element type and number of elements.
1497static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1498 if (T1 == T2)
1499 return true;
1500
1501 unsigned NumElts1, NumElts2;
1502 const Type *EltTy1, *EltTy2;
1503 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1504 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1505 NumElts1 == NumElts2 &&
1506 EltTy1 == EltTy2)
1507 return true;
1508
1509 return false;
1510}
1511
Bob Wilsonb742def2009-12-18 20:14:40 +00001512/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1513/// alloca or has an offset and size that corresponds to a component element
1514/// within it. The offset checked here may have been formed from a GEP with a
1515/// pointer bitcasted to a different type.
Chris Lattner145c5322011-01-23 08:27:54 +00001516///
1517/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1518/// unit. If false, it only allows accesses known to be in a single element.
Chris Lattner6c95d242011-01-23 07:29:29 +00001519void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001520 const Type *MemOpType, bool isStore,
Chris Lattner145c5322011-01-23 08:27:54 +00001521 AllocaInfo &Info, Instruction *TheAccess,
1522 bool AllowWholeAccess) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001523 // Check if this is a load/store of the entire alloca.
Chris Lattner145c5322011-01-23 08:27:54 +00001524 if (Offset == 0 && AllowWholeAccess &&
Chris Lattner6c95d242011-01-23 07:29:29 +00001525 MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
Bob Wilson704d1342011-01-13 17:45:11 +00001526 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1527 // loads/stores (which are essentially the same as the MemIntrinsics with
1528 // regard to copying padding between elements). But, if an alloca is
1529 // flagged as both a source and destination of such operations, we'll need
1530 // to check later for padding between elements.
1531 if (!MemOpType || MemOpType->isIntegerTy()) {
1532 if (isStore)
1533 Info.isMemCpyDst = true;
1534 else
1535 Info.isMemCpySrc = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001536 return;
1537 }
Bob Wilson704d1342011-01-13 17:45:11 +00001538 // This is also safe for references using a type that is compatible with
1539 // the type of the alloca, so that loads/stores can be rewritten using
1540 // insertvalue/extractvalue.
Chris Lattner6c95d242011-01-23 07:29:29 +00001541 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
Chris Lattner7e9b4272011-01-16 06:18:28 +00001542 Info.hasSubelementAccess = true;
Bob Wilson704d1342011-01-13 17:45:11 +00001543 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001544 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001545 }
1546 // Check if the offset/size correspond to a component within the alloca type.
Chris Lattner6c95d242011-01-23 07:29:29 +00001547 const Type *T = Info.AI->getAllocatedType();
Chris Lattner7e9b4272011-01-16 06:18:28 +00001548 if (TypeHasComponent(T, Offset, MemSize)) {
1549 Info.hasSubelementAccess = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001550 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001551 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001552
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001553 return MarkUnsafe(Info, TheAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +00001554}
1555
1556/// TypeHasComponent - Return true if T has a component type with the
1557/// specified offset and size. If Size is zero, do not check the size.
1558bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1559 const Type *EltTy;
1560 uint64_t EltSize;
1561 if (const StructType *ST = dyn_cast<StructType>(T)) {
1562 const StructLayout *Layout = TD->getStructLayout(ST);
1563 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1564 EltTy = ST->getContainedType(EltIdx);
1565 EltSize = TD->getTypeAllocSize(EltTy);
1566 Offset -= Layout->getElementOffset(EltIdx);
1567 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1568 EltTy = AT->getElementType();
1569 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001570 if (Offset >= AT->getNumElements() * EltSize)
1571 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001572 Offset %= EltSize;
1573 } else {
1574 return false;
1575 }
1576 if (Offset == 0 && (Size == 0 || EltSize == Size))
1577 return true;
1578 // Check if the component spans multiple elements.
1579 if (Offset + Size > EltSize)
1580 return false;
1581 return TypeHasComponent(EltTy, Offset, Size);
1582}
1583
1584/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1585/// the instruction I, which references it, to use the separate elements.
1586/// Offset indicates the position within AI that is referenced by this
1587/// instruction.
1588void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1589 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner145c5322011-01-23 08:27:54 +00001590 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1591 Use &TheUse = UI.getUse();
1592 Instruction *User = cast<Instruction>(*UI++);
Bob Wilsonb742def2009-12-18 20:14:40 +00001593
1594 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1595 RewriteBitCast(BC, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001596 continue;
1597 }
1598
1599 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001600 RewriteGEP(GEPI, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001601 continue;
1602 }
1603
1604 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001605 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1606 uint64_t MemSize = Length->getZExtValue();
1607 if (Offset == 0 &&
1608 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1609 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001610 // Otherwise the intrinsic can only touch a single element and the
1611 // address operand will be updated, so nothing else needs to be done.
Chris Lattner145c5322011-01-23 08:27:54 +00001612 continue;
1613 }
1614
1615 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001616 const Type *LIType = LI->getType();
Chris Lattner192228e2011-01-16 05:28:59 +00001617
Bob Wilson704d1342011-01-13 17:45:11 +00001618 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001619 // Replace:
1620 // %res = load { i32, i32 }* %alloc
1621 // with:
1622 // %load.0 = load i32* %alloc.0
1623 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1624 // %load.1 = load i32* %alloc.1
1625 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1626 // (Also works for arrays instead of structs)
1627 Value *Insert = UndefValue::get(LIType);
1628 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1629 Value *Load = new LoadInst(NewElts[i], "load", LI);
1630 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1631 }
1632 LI->replaceAllUsesWith(Insert);
1633 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001634 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001635 TD->getTypeAllocSize(LIType) ==
1636 TD->getTypeAllocSize(AI->getAllocatedType())) {
1637 // If this is a load of the entire alloca to an integer, rewrite it.
1638 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1639 }
Chris Lattner145c5322011-01-23 08:27:54 +00001640 continue;
1641 }
1642
1643 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001644 Value *Val = SI->getOperand(0);
1645 const Type *SIType = Val->getType();
Bob Wilson704d1342011-01-13 17:45:11 +00001646 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001647 // Replace:
1648 // store { i32, i32 } %val, { i32, i32 }* %alloc
1649 // with:
1650 // %val.0 = extractvalue { i32, i32 } %val, 0
1651 // store i32 %val.0, i32* %alloc.0
1652 // %val.1 = extractvalue { i32, i32 } %val, 1
1653 // store i32 %val.1, i32* %alloc.1
1654 // (Also works for arrays instead of structs)
1655 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1656 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1657 new StoreInst(Extract, NewElts[i], SI);
1658 }
1659 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001660 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001661 TD->getTypeAllocSize(SIType) ==
1662 TD->getTypeAllocSize(AI->getAllocatedType())) {
1663 // If this is a store of the entire alloca from an integer, rewrite it.
1664 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1665 }
Chris Lattner145c5322011-01-23 08:27:54 +00001666 continue;
1667 }
1668
1669 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1670 // If we have a PHI user of the alloca itself (as opposed to a GEP or
1671 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1672 // the new pointer.
1673 if (!isa<AllocaInst>(I)) continue;
1674
1675 assert(Offset == 0 && NewElts[0] &&
1676 "Direct alloca use should have a zero offset");
1677
1678 // If we have a use of the alloca, we know the derived uses will be
1679 // utilizing just the first element of the scalarized result. Insert a
1680 // bitcast of the first alloca before the user as required.
1681 AllocaInst *NewAI = NewElts[0];
1682 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1683 NewAI->moveBefore(BCI);
1684 TheUse = BCI;
1685 continue;
Bob Wilsonb742def2009-12-18 20:14:40 +00001686 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001687 }
1688}
1689
Bob Wilsonb742def2009-12-18 20:14:40 +00001690/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1691/// and recursively continue updating all of its uses.
1692void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1693 SmallVector<AllocaInst*, 32> &NewElts) {
1694 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1695 if (BC->getOperand(0) != AI)
1696 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001697
Bob Wilsonb742def2009-12-18 20:14:40 +00001698 // The bitcast references the original alloca. Replace its uses with
1699 // references to the first new element alloca.
1700 Instruction *Val = NewElts[0];
1701 if (Val->getType() != BC->getDestTy()) {
1702 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1703 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001704 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001705 BC->replaceAllUsesWith(Val);
1706 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001707}
1708
Bob Wilsonb742def2009-12-18 20:14:40 +00001709/// FindElementAndOffset - Return the index of the element containing Offset
1710/// within the specified type, which must be either a struct or an array.
1711/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001712/// element. IdxTy is set to the type of the index result to be used in a
1713/// GEP instruction.
1714uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1715 const Type *&IdxTy) {
1716 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001717 if (const StructType *ST = dyn_cast<StructType>(T)) {
1718 const StructLayout *Layout = TD->getStructLayout(ST);
1719 Idx = Layout->getElementContainingOffset(Offset);
1720 T = ST->getContainedType(Idx);
1721 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001722 IdxTy = Type::getInt32Ty(T->getContext());
1723 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001724 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001725 const ArrayType *AT = cast<ArrayType>(T);
1726 T = AT->getElementType();
1727 uint64_t EltSize = TD->getTypeAllocSize(T);
1728 Idx = Offset / EltSize;
1729 Offset -= Idx * EltSize;
1730 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001731 return Idx;
1732}
1733
1734/// RewriteGEP - Check if this GEP instruction moves the pointer across
1735/// elements of the alloca that are being split apart, and if so, rewrite
1736/// the GEP to be relative to the new element.
1737void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1738 SmallVector<AllocaInst*, 32> &NewElts) {
1739 uint64_t OldOffset = Offset;
1740 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1741 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1742 &Indices[0], Indices.size());
1743
1744 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1745
1746 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00001747 const Type *IdxTy;
1748 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001749 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001750 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001751
1752 T = AI->getAllocatedType();
1753 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001754 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001755
1756 // If this GEP does not move the pointer across elements of the alloca
1757 // being split, then it does not needs to be rewritten.
1758 if (Idx == OldIdx)
1759 return;
1760
1761 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1762 SmallVector<Value*, 8> NewArgs;
1763 NewArgs.push_back(Constant::getNullValue(i32Ty));
1764 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001765 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1766 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00001767 }
1768 Instruction *Val = NewElts[Idx];
1769 if (NewArgs.size() > 1) {
1770 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1771 NewArgs.end(), "", GEPI);
1772 Val->takeName(GEPI);
1773 }
1774 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001775 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001776 GEPI->replaceAllUsesWith(Val);
1777 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001778}
1779
1780/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1781/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00001782void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001783 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00001784 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001785 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00001786 // appropriate type. The "Other" pointer is the pointer that goes to memory
1787 // that doesn't have anything to do with the alloca that we are promoting. For
1788 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00001789 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001790 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00001791 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00001792 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00001793 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001794 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00001795 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00001796 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001797 }
1798 }
Bob Wilson78c50b82009-12-08 18:22:03 +00001799
Chris Lattnerd93afec2009-01-07 07:18:45 +00001800 // If there is an other pointer, we want to convert it to the same pointer
1801 // type as AI has, so we can GEP through it safely.
1802 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00001803 unsigned AddrSpace =
1804 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00001805
1806 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
1807 // optimization, but it's also required to detect the corner case where
1808 // both pointer operands are referencing the same memory, and where
1809 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
1810 // function is only called for mem intrinsics that access the whole
1811 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00001812 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson69743022011-01-13 20:59:44 +00001813
Bob Wilsona756b1d2010-01-19 04:32:48 +00001814 // Copying the alloca to itself is a no-op: just delete it.
1815 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1816 // This code will run twice for a no-op memcpy -- once for each operand.
1817 // Put only one reference to MI on the DeadInsts list.
1818 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1819 E = DeadInsts.end(); I != E; ++I)
1820 if (*I == MI) return;
1821 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001822 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00001823 }
Bob Wilson69743022011-01-13 20:59:44 +00001824
Chris Lattnerd93afec2009-01-07 07:18:45 +00001825 // If the pointer is not the right type, insert a bitcast to the right
1826 // type.
Chris Lattner0238f8c2010-07-08 00:27:05 +00001827 const Type *NewTy =
1828 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson69743022011-01-13 20:59:44 +00001829
Chris Lattner0238f8c2010-07-08 00:27:05 +00001830 if (OtherPtr->getType() != NewTy)
1831 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001832 }
Bob Wilson69743022011-01-13 20:59:44 +00001833
Chris Lattnerd93afec2009-01-07 07:18:45 +00001834 // Process each element of the aggregate.
Bob Wilsonb742def2009-12-18 20:14:40 +00001835 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson69743022011-01-13 20:59:44 +00001836
Owen Anderson1d0be152009-08-13 21:58:54 +00001837 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00001838
1839 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1840 // If this is a memcpy/memmove, emit a GEP of the other element address.
1841 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001842 unsigned OtherEltAlign = MemAlignment;
Bob Wilson69743022011-01-13 20:59:44 +00001843
Bob Wilsona756b1d2010-01-19 04:32:48 +00001844 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001845 Value *Idx[2] = { Zero,
1846 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00001847 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001848 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00001849 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00001850 uint64_t EltOffset;
1851 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001852 const Type *OtherTy = OtherPtrTy->getElementType();
1853 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001854 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1855 } else {
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001856 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001857 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001858 }
Bob Wilson69743022011-01-13 20:59:44 +00001859
Chris Lattner1541e0f2009-03-04 19:20:50 +00001860 // The alignment of the other pointer is the guaranteed alignment of the
1861 // element, which is affected by both the known alignment of the whole
1862 // mem intrinsic and the alignment of the element. If the alignment of
1863 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1864 // known alignment is just 4 bytes.
1865 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00001866 }
Bob Wilson69743022011-01-13 20:59:44 +00001867
Chris Lattnerd93afec2009-01-07 07:18:45 +00001868 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00001869 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson69743022011-01-13 20:59:44 +00001870
Chris Lattnerd93afec2009-01-07 07:18:45 +00001871 // If we got down to a scalar, insert a load or store as appropriate.
1872 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001873 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001874 if (SROADest) {
1875 // From Other to Alloca.
1876 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1877 new StoreInst(Elt, EltPtr, MI);
1878 } else {
1879 // From Alloca to Other.
1880 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1881 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1882 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001883 continue;
1884 }
1885 assert(isa<MemSetInst>(MI));
Bob Wilson69743022011-01-13 20:59:44 +00001886
Chris Lattnerd93afec2009-01-07 07:18:45 +00001887 // If the stored element is zero (common case), just store a null
1888 // constant.
1889 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001890 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001891 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001892 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00001893 } else {
1894 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00001895 const Type *ValTy = EltTy->getScalarType();
1896
Chris Lattnerd93afec2009-01-07 07:18:45 +00001897 // Construct an integer with the right value.
1898 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1899 APInt OneVal(EltSize, CI->getZExtValue());
1900 APInt TotalVal(OneVal);
1901 // Set each byte.
1902 for (unsigned i = 0; 8*i < EltSize; ++i) {
1903 TotalVal = TotalVal.shl(8);
1904 TotalVal |= OneVal;
1905 }
Bob Wilson69743022011-01-13 20:59:44 +00001906
Chris Lattnerd93afec2009-01-07 07:18:45 +00001907 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001908 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001909 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001910 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001911 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001912 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001913 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson69743022011-01-13 20:59:44 +00001914
Chris Lattnerd93afec2009-01-07 07:18:45 +00001915 // If the requested value was a vector constant, create it.
1916 if (EltTy != ValTy) {
1917 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1918 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +00001919 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001920 }
1921 }
1922 new StoreInst(StoreVal, EltPtr, MI);
1923 continue;
1924 }
1925 // Otherwise, if we're storing a byte variable, use a memset call for
1926 // this element.
1927 }
Bob Wilson69743022011-01-13 20:59:44 +00001928
Duncan Sands777d2302009-05-09 07:06:46 +00001929 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001930
Chris Lattner61db1f52010-12-26 22:57:41 +00001931 IRBuilder<> Builder(MI);
Bob Wilson69743022011-01-13 20:59:44 +00001932
Chris Lattnerd93afec2009-01-07 07:18:45 +00001933 // Finally, insert the meminst for this element.
Chris Lattner61db1f52010-12-26 22:57:41 +00001934 if (isa<MemSetInst>(MI)) {
1935 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
1936 MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00001937 } else {
Chris Lattner61db1f52010-12-26 22:57:41 +00001938 assert(isa<MemTransferInst>(MI));
1939 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
1940 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson69743022011-01-13 20:59:44 +00001941
Chris Lattner61db1f52010-12-26 22:57:41 +00001942 if (isa<MemCpyInst>(MI))
1943 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
1944 else
1945 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00001946 }
Chris Lattner372dda82007-03-05 07:52:57 +00001947 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001948 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00001949}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001950
Bob Wilson39fdd692009-12-04 21:57:37 +00001951/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001952/// overwrites the entire allocation. Extract out the pieces of the stored
1953/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001954void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001955 SmallVector<AllocaInst*, 32> &NewElts){
1956 // Extract each element out of the integer according to its structure offset
1957 // and store the element value to the individual alloca.
1958 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00001959 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001960 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001961
Chris Lattner70728532011-01-16 05:58:24 +00001962 IRBuilder<> Builder(SI);
1963
Eli Friedman41b33f42009-06-01 09:14:32 +00001964 // Handle tail padding by extending the operand
1965 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00001966 SrcVal = Builder.CreateZExt(SrcVal,
1967 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001968
David Greene504c7d82010-01-05 01:27:09 +00001969 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00001970 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001971
1972 // There are two forms here: AI could be an array or struct. Both cases
1973 // have different ways to compute the element offset.
1974 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1975 const StructLayout *Layout = TD->getStructLayout(EltSTy);
Bob Wilson69743022011-01-13 20:59:44 +00001976
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001977 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1978 // Get the number of bits to shift SrcVal to get the value.
1979 const Type *FieldTy = EltSTy->getElementType(i);
1980 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson69743022011-01-13 20:59:44 +00001981
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001982 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00001983 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00001984
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001985 Value *EltVal = SrcVal;
1986 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001987 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00001988 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001989 }
Bob Wilson69743022011-01-13 20:59:44 +00001990
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001991 // Truncate down to an integer of the right size.
1992 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00001993
Chris Lattner583dd602009-01-09 18:18:43 +00001994 // Ignore zero sized fields like {}, they obviously contain no data.
1995 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001996
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001997 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00001998 EltVal = Builder.CreateTrunc(EltVal,
1999 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002000 Value *DestField = NewElts[i];
2001 if (EltVal->getType() == FieldTy) {
2002 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00002003 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002004 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002005 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002006 } else {
2007 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002008 DestField = Builder.CreateBitCast(DestField,
2009 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002010 }
2011 new StoreInst(EltVal, DestField, SI);
2012 }
Bob Wilson69743022011-01-13 20:59:44 +00002013
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002014 } else {
2015 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2016 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002017 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002018 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2019
2020 uint64_t Shift;
Bob Wilson69743022011-01-13 20:59:44 +00002021
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002022 if (TD->isBigEndian())
2023 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002024 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002025 Shift = 0;
Bob Wilson69743022011-01-13 20:59:44 +00002026
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002027 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00002028 // Ignore zero sized fields like {}, they obviously contain no data.
2029 if (ElementSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002030
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002031 Value *EltVal = SrcVal;
2032 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002033 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002034 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002035 }
Bob Wilson69743022011-01-13 20:59:44 +00002036
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002037 // Truncate down to an integer of the right size.
2038 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002039 EltVal = Builder.CreateTrunc(EltVal,
2040 IntegerType::get(SI->getContext(),
2041 ElementSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002042 Value *DestField = NewElts[i];
2043 if (EltVal->getType() == ArrayEltTy) {
2044 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002045 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00002046 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002047 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002048 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002049 } else {
2050 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002051 DestField = Builder.CreateBitCast(DestField,
2052 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002053 }
2054 new StoreInst(EltVal, DestField, SI);
Bob Wilson69743022011-01-13 20:59:44 +00002055
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002056 if (TD->isBigEndian())
2057 Shift -= ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002058 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002059 Shift += ElementOffset;
2060 }
2061 }
Bob Wilson69743022011-01-13 20:59:44 +00002062
Bob Wilsonb742def2009-12-18 20:14:40 +00002063 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002064}
2065
Bob Wilson39fdd692009-12-04 21:57:37 +00002066/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002067/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002068void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002069 SmallVector<AllocaInst*, 32> &NewElts) {
2070 // Extract each element out of the NewElts according to its structure offset
2071 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00002072 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002073 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002074
David Greene504c7d82010-01-05 01:27:09 +00002075 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00002076 << '\n');
Bob Wilson69743022011-01-13 20:59:44 +00002077
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002078 // There are two forms here: AI could be an array or struct. Both cases
2079 // have different ways to compute the element offset.
2080 const StructLayout *Layout = 0;
2081 uint64_t ArrayEltBitOffset = 0;
2082 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2083 Layout = TD->getStructLayout(EltSTy);
2084 } else {
2085 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002086 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002087 }
2088
2089 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00002090 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson69743022011-01-13 20:59:44 +00002091
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002092 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2093 // Load the value from the alloca. If the NewElt is an aggregate, cast
2094 // the pointer to an integer of the same size before doing the load.
2095 Value *SrcField = NewElts[i];
2096 const Type *FieldTy =
2097 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00002098 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002099
Chris Lattner583dd602009-01-09 18:18:43 +00002100 // Ignore zero sized fields like {}, they obviously contain no data.
2101 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002102
2103 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +00002104 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00002105 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2106 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00002107 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00002108 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002109 "", LI);
2110 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2111
2112 // If SrcField is a fp or vector of the right size but that isn't an
2113 // integer type, bitcast to an integer so we can shift it.
2114 if (SrcField->getType() != FieldIntTy)
2115 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2116
2117 // Zero extend the field to be the same size as the final alloca so that
2118 // we can shift and insert it.
2119 if (SrcField->getType() != ResultVal->getType())
2120 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson69743022011-01-13 20:59:44 +00002121
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002122 // Determine the number of bits to shift SrcField.
2123 uint64_t Shift;
2124 if (Layout) // Struct case.
2125 Shift = Layout->getElementOffsetInBits(i);
2126 else // Array case.
2127 Shift = i*ArrayEltBitOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002128
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002129 if (TD->isBigEndian())
2130 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson69743022011-01-13 20:59:44 +00002131
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002132 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002133 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002134 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2135 }
2136
Chris Lattner14952472010-06-27 07:58:26 +00002137 // Don't create an 'or x, 0' on the first iteration.
2138 if (!isa<Constant>(ResultVal) ||
2139 !cast<Constant>(ResultVal)->isNullValue())
2140 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2141 else
2142 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002143 }
Eli Friedman41b33f42009-06-01 09:14:32 +00002144
2145 // Handle tail padding by truncating the result
2146 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2147 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2148
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002149 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00002150 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002151}
2152
Duncan Sands3cb36502007-11-04 14:43:57 +00002153/// HasPadding - Return true if the specified type has any structure or
Bob Wilson694a10e2011-01-13 17:45:08 +00002154/// alignment padding in between the elements that would be split apart
2155/// by SROA; return false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00002156static bool HasPadding(const Type *Ty, const TargetData &TD) {
Bob Wilson694a10e2011-01-13 17:45:08 +00002157 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2158 Ty = ATy->getElementType();
2159 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00002160 }
Bob Wilson694a10e2011-01-13 17:45:08 +00002161
2162 // SROA currently handles only Arrays and Structs.
2163 const StructType *STy = cast<StructType>(Ty);
2164 const StructLayout *SL = TD.getStructLayout(STy);
2165 unsigned PrevFieldBitOffset = 0;
2166 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2167 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2168
2169 // Check to see if there is any padding between this element and the
2170 // previous one.
2171 if (i) {
2172 unsigned PrevFieldEnd =
2173 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2174 if (PrevFieldEnd < FieldBitOffset)
2175 return true;
2176 }
2177 PrevFieldBitOffset = FieldBitOffset;
2178 }
2179 // Check for tail padding.
2180 if (unsigned EltCount = STy->getNumElements()) {
2181 unsigned PrevFieldEnd = PrevFieldBitOffset +
2182 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2183 if (PrevFieldEnd < SL->getSizeInBits())
2184 return true;
2185 }
2186 return false;
Chris Lattner39a1c042007-05-30 06:11:23 +00002187}
Chris Lattner372dda82007-03-05 07:52:57 +00002188
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002189/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2190/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2191/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002192bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00002193 // Loop over the use list of the alloca. We can only transform it if all of
2194 // the users are safe to transform.
Chris Lattner6c95d242011-01-23 07:29:29 +00002195 AllocaInfo Info(AI);
Bob Wilson69743022011-01-13 20:59:44 +00002196
Chris Lattner6c95d242011-01-23 07:29:29 +00002197 isSafeForScalarRepl(AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00002198 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00002199 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002200 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002201 }
Bob Wilson69743022011-01-13 20:59:44 +00002202
Chris Lattner39a1c042007-05-30 06:11:23 +00002203 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2204 // source and destination, we have to be careful. In particular, the memcpy
2205 // could be moving around elements that live in structure padding of the LLVM
2206 // types, but may actually be used. In these cases, we refuse to promote the
2207 // struct.
2208 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00002209 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002210 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00002211
Chris Lattner396a0562011-01-16 17:46:19 +00002212 // If the alloca never has an access to just *part* of it, but is accessed
2213 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner7e9b4272011-01-16 06:18:28 +00002214 // the alloca instead of promoting each piece at a time and inserting fission
2215 // and fusion code.
2216 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2217 // If the struct/array just has one element, use basic SRoA.
2218 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2219 if (ST->getNumElements() > 1) return false;
2220 } else {
2221 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2222 return false;
2223 }
2224 }
Chris Lattner145c5322011-01-23 08:27:54 +00002225
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002226 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00002227}
Chris Lattnera1888942005-12-12 07:19:13 +00002228
Chris Lattner800de312008-02-29 07:03:13 +00002229
Chris Lattner79b3bd32007-04-25 06:40:51 +00002230
2231/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2232/// some part of a constant global variable. This intentionally only accepts
2233/// constant expressions because we don't can't rewrite arbitrary instructions.
2234static bool PointsToConstantGlobal(Value *V) {
2235 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2236 return GV->isConstant();
2237 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Bob Wilson69743022011-01-13 20:59:44 +00002238 if (CE->getOpcode() == Instruction::BitCast ||
Chris Lattner79b3bd32007-04-25 06:40:51 +00002239 CE->getOpcode() == Instruction::GetElementPtr)
2240 return PointsToConstantGlobal(CE->getOperand(0));
2241 return false;
2242}
2243
2244/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2245/// pointer to an alloca. Ignore any reads of the pointer, return false if we
2246/// see any stores or other unknown uses. If we see pointer arithmetic, keep
2247/// track of whether it moves the pointer (with isOffset) but otherwise traverse
2248/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
Nick Lewycky081f8002010-11-24 22:04:20 +00002249/// the alloca, and if the source pointer is a pointer to a constant global, we
Chris Lattner79b3bd32007-04-25 06:40:51 +00002250/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00002251static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00002252 bool isOffset) {
2253 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00002254 User *U = cast<Instruction>(*UI);
2255
Chris Lattner2e618492010-11-18 06:20:47 +00002256 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00002257 // Ignore non-volatile loads, they are always ok.
Chris Lattner2e618492010-11-18 06:20:47 +00002258 if (LI->isVolatile()) return false;
2259 continue;
2260 }
Bob Wilson69743022011-01-13 20:59:44 +00002261
Gabor Greif8a8a4352010-04-06 19:32:30 +00002262 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002263 // If uses of the bitcast are ok, we are ok.
2264 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
2265 return false;
2266 continue;
2267 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00002268 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002269 // If the GEP has all zero indices, it doesn't offset the pointer. If it
2270 // doesn't, it does.
2271 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
2272 isOffset || !GEP->hasAllZeroIndices()))
2273 return false;
2274 continue;
2275 }
Bob Wilson69743022011-01-13 20:59:44 +00002276
Chris Lattner62480652010-11-18 06:41:51 +00002277 if (CallSite CS = U) {
2278 // If this is a readonly/readnone call site, then we know it is just a
2279 // load and we can ignore it.
Chris Lattnera9be1df2010-11-18 06:26:49 +00002280 if (CS.onlyReadsMemory())
2281 continue;
Nick Lewycky081f8002010-11-24 22:04:20 +00002282
2283 // If this is the function being called then we treat it like a load and
2284 // ignore it.
2285 if (CS.isCallee(UI))
2286 continue;
Bob Wilson69743022011-01-13 20:59:44 +00002287
Chris Lattner62480652010-11-18 06:41:51 +00002288 // If this is being passed as a byval argument, the caller is making a
2289 // copy, so it is only a read of the alloca.
2290 unsigned ArgNo = CS.getArgumentNo(UI);
2291 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
2292 continue;
2293 }
Bob Wilson69743022011-01-13 20:59:44 +00002294
Chris Lattner79b3bd32007-04-25 06:40:51 +00002295 // If this is isn't our memcpy/memmove, reject it as something we can't
2296 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00002297 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2298 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00002299 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002300
Chris Lattner2e618492010-11-18 06:20:47 +00002301 // If the transfer is using the alloca as a source of the transfer, then
Chris Lattner2e29ebd2010-11-18 07:32:33 +00002302 // ignore it since it is a load (unless the transfer is volatile).
Chris Lattner2e618492010-11-18 06:20:47 +00002303 if (UI.getOperandNo() == 1) {
2304 if (MI->isVolatile()) return false;
2305 continue;
2306 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00002307
2308 // If we already have seen a copy, reject the second one.
2309 if (TheCopy) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002310
Chris Lattner79b3bd32007-04-25 06:40:51 +00002311 // If the pointer has been offset from the start of the alloca, we can't
2312 // safely handle this.
2313 if (isOffset) return false;
2314
2315 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00002316 if (UI.getOperandNo() != 0) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002317
Chris Lattner79b3bd32007-04-25 06:40:51 +00002318 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00002319 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002320 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002321
Chris Lattner79b3bd32007-04-25 06:40:51 +00002322 // Otherwise, the transform is safe. Remember the copy instruction.
2323 TheCopy = MI;
2324 }
2325 return true;
2326}
2327
2328/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2329/// modified by a copy from a constant global. If we can prove this, we can
2330/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00002331MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
2332 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00002333 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
2334 return TheCopy;
2335 return 0;
2336}