blob: b3d7ef6ec102d727da5a201a36e82625e64815f5 [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"
Devang Patel4fd3c592011-07-06 22:06:11 +000033#include "llvm/Analysis/DebugInfo.h"
Cameron Zwarichc8279392011-05-24 03:10:43 +000034#include "llvm/Analysis/DIBuilder.h"
Cameron Zwarichb1686c32011-01-18 03:53:26 +000035#include "llvm/Analysis/Dominators.h"
Chris Lattnerc87c50a2011-01-23 22:04:55 +000036#include "llvm/Analysis/Loads.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000037#include "llvm/Analysis/ValueTracking.h"
Chris Lattner38aec322003-09-11 16:45:55 +000038#include "llvm/Target/TargetData.h"
39#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000040#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere0a1a5b2011-01-14 07:50:47 +000041#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattnera9be1df2010-11-18 06:26:49 +000042#include "llvm/Support/CallSite.h"
Chris Lattner95255282006-06-28 23:17:24 +000043#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000044#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000045#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000046#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000047#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000048#include "llvm/Support/raw_ostream.h"
Chris Lattnerc87c50a2011-01-23 22:04:55 +000049#include "llvm/ADT/SetVector.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000050#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000051#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000052using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000053
Chris Lattner0e5f4992006-12-19 21:40:18 +000054STATISTIC(NumReplaced, "Number of allocas broken up");
55STATISTIC(NumPromoted, "Number of allocas promoted");
Chris Lattnerc87c50a2011-01-23 22:04:55 +000056STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
Chris Lattner0e5f4992006-12-19 21:40:18 +000057STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000058STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000059
Chris Lattner0e5f4992006-12-19 21:40:18 +000060namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000061 struct SROA : public FunctionPass {
Cameron Zwarichb1686c32011-01-18 03:53:26 +000062 SROA(int T, bool hasDT, char &ID)
63 : FunctionPass(ID), HasDomTree(hasDT) {
Devang Patelff366852007-07-09 21:19:23 +000064 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000065 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000066 else
67 SRThreshold = T;
68 }
Devang Patel794fd752007-05-01 21:15:47 +000069
Chris Lattnered7b41e2003-05-27 15:45:27 +000070 bool runOnFunction(Function &F);
71
Chris Lattner38aec322003-09-11 16:45:55 +000072 bool performScalarRepl(Function &F);
73 bool performPromotion(Function &F);
74
Chris Lattnered7b41e2003-05-27 15:45:27 +000075 private:
Cameron Zwarichb1686c32011-01-18 03:53:26 +000076 bool HasDomTree;
Chris Lattner56c38522009-01-07 06:34:28 +000077 TargetData *TD;
Bob Wilson69743022011-01-13 20:59:44 +000078
Bob Wilsonb742def2009-12-18 20:14:40 +000079 /// DeadInsts - Keep track of instructions we have made dead, so that
80 /// we can remove them after we are done working.
81 SmallVector<Value*, 32> DeadInsts;
82
Chris Lattner39a1c042007-05-30 06:11:23 +000083 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
84 /// information about the uses. All these fields are initialized to false
85 /// and set to true when something is learned.
86 struct AllocaInfo {
Chris Lattner6c95d242011-01-23 07:29:29 +000087 /// The alloca to promote.
88 AllocaInst *AI;
89
Chris Lattner145c5322011-01-23 08:27:54 +000090 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
91 /// looping and avoid redundant work.
92 SmallPtrSet<PHINode*, 8> CheckedPHIs;
93
Chris Lattner39a1c042007-05-30 06:11:23 +000094 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
95 bool isUnsafe : 1;
Bob Wilson69743022011-01-13 20:59:44 +000096
Chris Lattner39a1c042007-05-30 06:11:23 +000097 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
98 bool isMemCpySrc : 1;
99
Zhou Sheng33b0b8d2007-07-06 06:01:16 +0000100 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +0000101 bool isMemCpyDst : 1;
102
Chris Lattner7e9b4272011-01-16 06:18:28 +0000103 /// hasSubelementAccess - This is true if a subelement of the alloca is
104 /// ever accessed, or false if the alloca is only accessed with mem
105 /// intrinsics or load/store that only access the entire alloca at once.
106 bool hasSubelementAccess : 1;
107
108 /// hasALoadOrStore - This is true if there are any loads or stores to it.
109 /// The alloca may just be accessed with memcpy, for example, which would
110 /// not set this.
111 bool hasALoadOrStore : 1;
112
Chris Lattner6c95d242011-01-23 07:29:29 +0000113 explicit AllocaInfo(AllocaInst *ai)
114 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
Chris Lattner7e9b4272011-01-16 06:18:28 +0000115 hasSubelementAccess(false), hasALoadOrStore(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +0000116 };
Bob Wilson69743022011-01-13 20:59:44 +0000117
Devang Patelff366852007-07-09 21:19:23 +0000118 unsigned SRThreshold;
119
Chris Lattnerd01a0da2011-01-23 07:05:44 +0000120 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
121 I.isUnsafe = true;
122 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
123 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000124
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000125 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000126
Chris Lattner6c95d242011-01-23 07:29:29 +0000127 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
Chris Lattner145c5322011-01-23 08:27:54 +0000128 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
129 AllocaInfo &Info);
Chris Lattner6c95d242011-01-23 07:29:29 +0000130 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
131 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000132 Type *MemOpType, bool isStore, AllocaInfo &Info,
Chris Lattner145c5322011-01-23 08:27:54 +0000133 Instruction *TheAccess, bool AllowWholeAccess);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000134 bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size);
135 uint64_t FindElementAndOffset(Type *&T, uint64_t &Offset,
136 Type *&IdxTy);
Bob Wilson69743022011-01-13 20:59:44 +0000137
138 void DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000139 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000140 void DeleteDeadInstructions();
Bob Wilson69743022011-01-13 20:59:44 +0000141
Bob Wilsonb742def2009-12-18 20:14:40 +0000142 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
143 SmallVector<AllocaInst*, 32> &NewElts);
144 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
145 SmallVector<AllocaInst*, 32> &NewElts);
146 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
147 SmallVector<AllocaInst*, 32> &NewElts);
148 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000149 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000150 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000151 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000152 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000153 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000154 SmallVector<AllocaInst*, 32> &NewElts);
Bob Wilson69743022011-01-13 20:59:44 +0000155
Nick Lewycky9174d5c2011-06-27 05:40:02 +0000156 static MemTransferInst *isOnlyCopiedFromConstantGlobal(
157 AllocaInst *AI, SmallVector<Instruction*, 4> &ToDelete);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000158 };
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000159
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000160 // SROA_DT - SROA that uses DominatorTree.
161 struct SROA_DT : public SROA {
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000162 static char ID;
163 public:
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000164 SROA_DT(int T = -1) : SROA(T, true, ID) {
165 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000166 }
167
168 // getAnalysisUsage - This pass does not require any passes, but we know it
169 // will not alter the CFG, so say so.
170 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
171 AU.addRequired<DominatorTree>();
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000172 AU.setPreservesCFG();
173 }
174 };
175
176 // SROA_SSAUp - SROA that uses SSAUpdater.
177 struct SROA_SSAUp : public SROA {
178 static char ID;
179 public:
180 SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
181 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
182 }
183
184 // getAnalysisUsage - This pass does not require any passes, but we know it
185 // will not alter the CFG, so say so.
186 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
187 AU.setPreservesCFG();
188 }
189 };
190
Chris Lattnered7b41e2003-05-27 15:45:27 +0000191}
192
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000193char SROA_DT::ID = 0;
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000194char SROA_SSAUp::ID = 0;
195
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000196INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
197 "Scalar Replacement of Aggregates (DT)", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000198INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000199INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
200 "Scalar Replacement of Aggregates (DT)", false, false)
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000201
202INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
203 "Scalar Replacement of Aggregates (SSAUp)", false, false)
204INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
205 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000206
Brian Gaeked0fde302003-11-11 22:41:34 +0000207// Public interface to the ScalarReplAggregates pass
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000208FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000209 bool UseDomTree) {
210 if (UseDomTree)
211 return new SROA_DT(Threshold);
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000212 return new SROA_SSAUp(Threshold);
Devang Patelff366852007-07-09 21:19:23 +0000213}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000214
215
Chris Lattner4cc576b2010-04-16 00:24:57 +0000216//===----------------------------------------------------------------------===//
217// Convert To Scalar Optimization.
218//===----------------------------------------------------------------------===//
219
220namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000221/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
222/// optimization, which scans the uses of an alloca and determines if it can
223/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000224class ConvertToScalarInfo {
Cameron Zwarichd4c9c3e2011-03-16 00:13:35 +0000225 /// AllocaSize - The size of the alloca being considered in bytes.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000226 unsigned AllocaSize;
227 const TargetData &TD;
Bob Wilson69743022011-01-13 20:59:44 +0000228
Chris Lattnera0bada72010-04-16 02:32:17 +0000229 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000230 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000231 bool IsNotTrivial;
Bob Wilson69743022011-01-13 20:59:44 +0000232
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000233 /// ScalarKind - Tracks the kind of alloca being considered for promotion,
234 /// computed based on the uses of the alloca rather than the LLVM type system.
235 enum {
236 Unknown,
Cameron Zwarich51797822011-06-13 21:44:40 +0000237
Cameron Zwarich15cd80c2011-06-13 23:39:23 +0000238 // Accesses via GEPs that are consistent with element access of a vector
Cameron Zwarich51797822011-06-13 21:44:40 +0000239 // type. This will not be converted into a vector unless there is a later
240 // access using an actual vector type.
241 ImplicitVector,
242
Cameron Zwarich15cd80c2011-06-13 23:39:23 +0000243 // Accesses via vector operations and GEPs that are consistent with the
244 // layout of a vector type.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000245 Vector,
Cameron Zwarich51797822011-06-13 21:44:40 +0000246
247 // An integer bag-of-bits with bitwise operations for insertion and
248 // extraction. Any combination of types can be converted into this kind
249 // of scalar.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000250 Integer
251 } ScalarKind;
252
Chris Lattnera001b662010-04-16 00:38:19 +0000253 /// VectorTy - This tracks the type that we should promote the vector to if
254 /// it is possible to turn it into a vector. This starts out null, and if it
255 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000256 VectorType *VectorTy;
Bob Wilson69743022011-01-13 20:59:44 +0000257
Cameron Zwarich1bcdb6f2011-03-16 08:13:42 +0000258 /// HadNonMemTransferAccess - True if there is at least one access to the
259 /// alloca that is not a MemTransferInst. We don't want to turn structs into
260 /// large integers unless there is some potential for optimization.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000261 bool HadNonMemTransferAccess;
262
Chris Lattner4cc576b2010-04-16 00:24:57 +0000263public:
264 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000265 : AllocaSize(Size), TD(td), IsNotTrivial(false), ScalarKind(Unknown),
Cameron Zwarich51797822011-06-13 21:44:40 +0000266 VectorTy(0), HadNonMemTransferAccess(false) { }
Bob Wilson69743022011-01-13 20:59:44 +0000267
Chris Lattnera001b662010-04-16 00:38:19 +0000268 AllocaInst *TryConvert(AllocaInst *AI);
Bob Wilson69743022011-01-13 20:59:44 +0000269
Chris Lattner4cc576b2010-04-16 00:24:57 +0000270private:
271 bool CanConvertToScalar(Value *V, uint64_t Offset);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000272 void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
273 bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000274 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Bob Wilson69743022011-01-13 20:59:44 +0000275
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000276 Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000277 uint64_t Offset, IRBuilder<> &Builder);
278 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
279 uint64_t Offset, IRBuilder<> &Builder);
280};
281} // end anonymous namespace.
282
Chris Lattner91abace2010-09-01 05:14:33 +0000283
Chris Lattnera001b662010-04-16 00:38:19 +0000284/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
285/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
286/// alloca if possible or null if not.
287AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
288 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
289 // out.
290 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
291 return 0;
Bob Wilson69743022011-01-13 20:59:44 +0000292
Cameron Zwarich51797822011-06-13 21:44:40 +0000293 // If an alloca has only memset / memcpy uses, it may still have an Unknown
294 // ScalarKind. Treat it as an Integer below.
295 if (ScalarKind == Unknown)
296 ScalarKind = Integer;
297
Cameron Zwarich3ebb05d2011-06-18 06:17:51 +0000298 // FIXME: It should be possible to promote the vector type up to the alloca's
299 // size.
300 if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
301 ScalarKind = Integer;
302
Chris Lattnera001b662010-04-16 00:38:19 +0000303 // If we were able to find a vector type that can handle this with
304 // insert/extract elements, and if there was at least one use that had
305 // a vector type, promote this to a vector. We don't want to promote
306 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
307 // we just get a lot of insert/extracts. If at least one vector is
308 // involved, then we probably really do have a union of vector/array.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000309 Type *NewTy;
Cameron Zwarich5b93d3c2011-06-14 06:33:51 +0000310 if (ScalarKind == Vector) {
311 assert(VectorTy && "Missing type for vector scalar.");
Chris Lattnera001b662010-04-16 00:38:19 +0000312 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
313 << *VectorTy << '\n');
314 NewTy = VectorTy; // Use the vector type.
315 } else {
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000316 unsigned BitWidth = AllocaSize * 8;
Cameron Zwarich51797822011-06-13 21:44:40 +0000317 if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
318 !HadNonMemTransferAccess && !TD.fitsInLegalInteger(BitWidth))
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000319 return 0;
320
Chris Lattnera001b662010-04-16 00:38:19 +0000321 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
322 // Create and insert the integer alloca.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000323 NewTy = IntegerType::get(AI->getContext(), BitWidth);
Chris Lattnera001b662010-04-16 00:38:19 +0000324 }
325 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
326 ConvertUsesToScalar(AI, NewAI, 0);
327 return NewAI;
328}
329
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000330/// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
331/// (VectorTy) so far at the offset specified by Offset (which is specified in
332/// bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000333///
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000334/// There are three cases we handle here:
Chris Lattner4cc576b2010-04-16 00:24:57 +0000335/// 1) A union of vector types of the same size and potentially its elements.
336/// Here we turn element accesses into insert/extract element operations.
337/// This promotes a <4 x float> with a store of float to the third element
338/// into a <4 x float> that uses insert element.
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000339/// 2) A union of vector types with power-of-2 size differences, e.g. a float,
340/// <2 x float> and <4 x float>. Here we turn element accesses into insert
341/// and extract element operations, and <2 x float> accesses into a cast to
342/// <2 x double>, an extract, and a cast back to <2 x float>.
343/// 3) A fully general blob of memory, which we turn into some (potentially
Chris Lattner4cc576b2010-04-16 00:24:57 +0000344/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000345/// and stores would mutate the memory. We mark this by setting VectorTy
346/// to VoidTy.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000347void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000348 uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000349 // If we already decided to turn this into a blob of integer memory, there is
350 // nothing to be done.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000351 if (ScalarKind == Integer)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000352 return;
Bob Wilson69743022011-01-13 20:59:44 +0000353
Chris Lattner4cc576b2010-04-16 00:24:57 +0000354 // If this could be contributing to a vector, analyze it.
355
356 // If the In type is a vector that is the same size as the alloca, see if it
357 // matches the existing VecTy.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000358 if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000359 if (MergeInVectorType(VInTy, Offset))
Chris Lattner4cc576b2010-04-16 00:24:57 +0000360 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000361 } else if (In->isFloatTy() || In->isDoubleTy() ||
362 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
363 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
Cameron Zwarich9827b782011-03-29 05:19:52 +0000364 // Full width accesses can be ignored, because they can always be turned
365 // into bitcasts.
366 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
Cameron Zwarichdd689122011-06-13 21:44:31 +0000367 if (EltSize == AllocaSize)
Cameron Zwarich9827b782011-03-29 05:19:52 +0000368 return;
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000369
Chris Lattner4cc576b2010-04-16 00:24:57 +0000370 // If we're accessing something that could be an element of a vector, see
371 // if the implied vector agrees with what we already have and if Offset is
372 // compatible with it.
Cameron Zwarich96cc1d02011-06-09 01:45:33 +0000373 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Cameron Zwarichc4f78202011-06-09 01:52:44 +0000374 (!VectorTy || Offset * 8 < VectorTy->getPrimitiveSizeInBits())) {
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000375 if (!VectorTy) {
Cameron Zwarich51797822011-06-13 21:44:40 +0000376 ScalarKind = ImplicitVector;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000377 VectorTy = VectorType::get(In, AllocaSize/EltSize);
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000378 return;
379 }
380
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000381 unsigned CurrentEltSize = VectorTy->getElementType()
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000382 ->getPrimitiveSizeInBits()/8;
383 if (EltSize == CurrentEltSize)
384 return;
Cameron Zwarich344731c2011-04-20 21:48:38 +0000385
386 if (In->isIntegerTy() && isPowerOf2_32(AllocaSize / EltSize))
387 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000388 }
389 }
Bob Wilson69743022011-01-13 20:59:44 +0000390
Chris Lattner4cc576b2010-04-16 00:24:57 +0000391 // Otherwise, we have a case that we can't handle with an optimized vector
392 // form. We can still turn this into a large integer.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000393 ScalarKind = Integer;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000394}
395
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000396/// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
397/// returning true if the type was successfully merged and false otherwise.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000398bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000399 uint64_t Offset) {
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000400 // TODO: Support nonzero offsets?
401 if (Offset != 0)
402 return false;
403
404 // Only allow vectors that are a power-of-2 away from the size of the alloca.
405 if (!isPowerOf2_64(AllocaSize / (VInTy->getBitWidth() / 8)))
406 return false;
407
408 // If this the first vector we see, remember the type so that we know the
409 // element size.
410 if (!VectorTy) {
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000411 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000412 VectorTy = VInTy;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000413 return true;
414 }
415
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000416 unsigned BitWidth = VectorTy->getBitWidth();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000417 unsigned InBitWidth = VInTy->getBitWidth();
418
419 // Vectors of the same size can be converted using a simple bitcast.
Cameron Zwarich51797822011-06-13 21:44:40 +0000420 if (InBitWidth == BitWidth && AllocaSize == (InBitWidth / 8)) {
421 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000422 return true;
Cameron Zwarich51797822011-06-13 21:44:40 +0000423 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000424
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000425 Type *ElementTy = VectorTy->getElementType();
426 Type *InElementTy = VInTy->getElementType();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000427
Dan Gohman856e13d2011-07-21 23:30:09 +0000428 // If they're the same alloc size, we'll be attempting to convert between
429 // them with a vector shuffle, which requires the element types to match.
430 if (TD.getTypeAllocSize(VectorTy) == TD.getTypeAllocSize(VInTy) &&
431 ElementTy != InElementTy)
432 return false;
433
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000434 // Do not allow mixed integer and floating-point accesses from vectors of
435 // different sizes.
436 if (ElementTy->isFloatingPointTy() != InElementTy->isFloatingPointTy())
437 return false;
438
439 if (ElementTy->isFloatingPointTy()) {
440 // Only allow floating-point vectors of different sizes if they have the
441 // same element type.
442 // TODO: This could be loosened a bit, but would anything benefit?
443 if (ElementTy != InElementTy)
444 return false;
445
446 // There are no arbitrary-precision floating-point types, which limits the
447 // number of legal vector types with larger element types that we can form
448 // to bitcast and extract a subvector.
449 // TODO: We could support some more cases with mixed fp128 and double here.
450 if (!(BitWidth == 64 || BitWidth == 128) ||
451 !(InBitWidth == 64 || InBitWidth == 128))
452 return false;
453 } else {
454 assert(ElementTy->isIntegerTy() && "Vector elements must be either integer "
455 "or floating-point.");
456 unsigned BitWidth = ElementTy->getPrimitiveSizeInBits();
457 unsigned InBitWidth = InElementTy->getPrimitiveSizeInBits();
458
459 // Do not allow integer types smaller than a byte or types whose widths are
460 // not a multiple of a byte.
461 if (BitWidth < 8 || InBitWidth < 8 ||
462 BitWidth % 8 != 0 || InBitWidth % 8 != 0)
463 return false;
464 }
465
466 // Pick the largest of the two vector types.
Cameron Zwarich51797822011-06-13 21:44:40 +0000467 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000468 if (InBitWidth > BitWidth)
469 VectorTy = VInTy;
470
471 return true;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000472}
473
Chris Lattner4cc576b2010-04-16 00:24:57 +0000474/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
475/// its accesses to a single vector type, return true and set VecTy to
476/// the new type. If we could convert the alloca into a single promotable
477/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
478/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
479/// is the current offset from the base of the alloca being analyzed.
480///
481/// If we see at least one access to the value that is as a vector type, set the
482/// SawVec flag.
483bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
484 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
485 Instruction *User = cast<Instruction>(*UI);
Bob Wilson69743022011-01-13 20:59:44 +0000486
Chris Lattner4cc576b2010-04-16 00:24:57 +0000487 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
488 // Don't break volatile loads.
489 if (LI->isVolatile())
490 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000491 // Don't touch MMX operations.
492 if (LI->getType()->isX86_MMXTy())
493 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000494 HadNonMemTransferAccess = true;
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000495 MergeInTypeForLoadOrStore(LI->getType(), Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000496 continue;
497 }
Bob Wilson69743022011-01-13 20:59:44 +0000498
Chris Lattner4cc576b2010-04-16 00:24:57 +0000499 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
500 // Storing the pointer, not into the value?
501 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000502 // Don't touch MMX operations.
503 if (SI->getOperand(0)->getType()->isX86_MMXTy())
504 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000505 HadNonMemTransferAccess = true;
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000506 MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000507 continue;
508 }
Bob Wilson69743022011-01-13 20:59:44 +0000509
Chris Lattner4cc576b2010-04-16 00:24:57 +0000510 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000511 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000512 if (!CanConvertToScalar(BCI, Offset))
513 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000514 continue;
515 }
516
517 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
518 // If this is a GEP with a variable indices, we can't handle it.
519 if (!GEP->hasAllConstantIndices())
520 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000521
Chris Lattner4cc576b2010-04-16 00:24:57 +0000522 // Compute the offset that this GEP adds to the pointer.
523 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
524 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
Jay Foad8fbbb392011-07-19 14:01:37 +0000525 Indices);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000526 // See if all uses can be converted.
527 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
528 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000529 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000530 HadNonMemTransferAccess = true;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000531 continue;
532 }
533
534 // If this is a constant sized memset of a constant value (e.g. 0) we can
535 // handle it.
536 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
Cameron Zwarich6be41eb2011-06-18 05:47:49 +0000537 // Store of constant value.
538 if (!isa<ConstantInt>(MSI->getValue()))
Chris Lattnera001b662010-04-16 00:38:19 +0000539 return false;
Cameron Zwarich6be41eb2011-06-18 05:47:49 +0000540
541 // Store of constant size.
542 ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
543 if (!Len)
544 return false;
545
546 // If the size differs from the alloca, we can only convert the alloca to
547 // an integer bag-of-bits.
548 // FIXME: This should handle all of the cases that are currently accepted
549 // as vector element insertions.
550 if (Len->getZExtValue() != AllocaSize || Offset != 0)
551 ScalarKind = Integer;
552
Chris Lattnera001b662010-04-16 00:38:19 +0000553 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000554 HadNonMemTransferAccess = true;
Chris Lattnera001b662010-04-16 00:38:19 +0000555 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000556 }
557
558 // If this is a memcpy or memmove into or out of the whole allocation, we
559 // can handle it like a load or store of the scalar type.
560 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000561 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
562 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
563 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000564
Chris Lattnera001b662010-04-16 00:38:19 +0000565 IsNotTrivial = true; // Can't be mem2reg'd.
566 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000567 }
Bob Wilson69743022011-01-13 20:59:44 +0000568
Chris Lattner4cc576b2010-04-16 00:24:57 +0000569 // Otherwise, we cannot handle this!
570 return false;
571 }
Bob Wilson69743022011-01-13 20:59:44 +0000572
Chris Lattner4cc576b2010-04-16 00:24:57 +0000573 return true;
574}
575
576/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
577/// directly. This happens when we are converting an "integer union" to a
578/// single integer scalar, or when we are converting a "vector union" to a
579/// vector with insert/extractelement instructions.
580///
581/// Offset is an offset from the original alloca, in bits that need to be
582/// shifted to the right. By the end of this, there should be no uses of Ptr.
583void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
584 uint64_t Offset) {
585 while (!Ptr->use_empty()) {
586 Instruction *User = cast<Instruction>(Ptr->use_back());
587
588 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
589 ConvertUsesToScalar(CI, NewAI, Offset);
590 CI->eraseFromParent();
591 continue;
592 }
593
594 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
595 // Compute the offset that this GEP adds to the pointer.
596 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
597 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
Jay Foad8fbbb392011-07-19 14:01:37 +0000598 Indices);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000599 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
600 GEP->eraseFromParent();
601 continue;
602 }
Bob Wilson69743022011-01-13 20:59:44 +0000603
Chris Lattner61db1f52010-12-26 22:57:41 +0000604 IRBuilder<> Builder(User);
Bob Wilson69743022011-01-13 20:59:44 +0000605
Chris Lattner4cc576b2010-04-16 00:24:57 +0000606 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
607 // The load is a bit extract from NewAI shifted right by Offset bits.
608 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
609 Value *NewLoadVal
610 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
611 LI->replaceAllUsesWith(NewLoadVal);
612 LI->eraseFromParent();
613 continue;
614 }
Bob Wilson69743022011-01-13 20:59:44 +0000615
Chris Lattner4cc576b2010-04-16 00:24:57 +0000616 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
617 assert(SI->getOperand(0) != Ptr && "Consistency error!");
618 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
619 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
620 Builder);
621 Builder.CreateStore(New, NewAI);
622 SI->eraseFromParent();
Bob Wilson69743022011-01-13 20:59:44 +0000623
Chris Lattner4cc576b2010-04-16 00:24:57 +0000624 // If the load we just inserted is now dead, then the inserted store
625 // overwrote the entire thing.
626 if (Old->use_empty())
627 Old->eraseFromParent();
628 continue;
629 }
Bob Wilson69743022011-01-13 20:59:44 +0000630
Chris Lattner4cc576b2010-04-16 00:24:57 +0000631 // If this is a constant sized memset of a constant value (e.g. 0) we can
632 // transform it into a store of the expanded constant value.
633 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
634 assert(MSI->getRawDest() == Ptr && "Consistency error!");
635 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
636 if (NumBytes != 0) {
637 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson69743022011-01-13 20:59:44 +0000638
Chris Lattner4cc576b2010-04-16 00:24:57 +0000639 // Compute the value replicated the right number of times.
640 APInt APVal(NumBytes*8, Val);
641
642 // Splat the value if non-zero.
643 if (Val)
644 for (unsigned i = 1; i != NumBytes; ++i)
645 APVal |= APVal << 8;
Bob Wilson69743022011-01-13 20:59:44 +0000646
Chris Lattner4cc576b2010-04-16 00:24:57 +0000647 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
648 Value *New = ConvertScalar_InsertValue(
649 ConstantInt::get(User->getContext(), APVal),
650 Old, Offset, Builder);
651 Builder.CreateStore(New, NewAI);
Bob Wilson69743022011-01-13 20:59:44 +0000652
Chris Lattner4cc576b2010-04-16 00:24:57 +0000653 // If the load we just inserted is now dead, then the memset overwrote
654 // the entire thing.
655 if (Old->use_empty())
Bob Wilson69743022011-01-13 20:59:44 +0000656 Old->eraseFromParent();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000657 }
658 MSI->eraseFromParent();
659 continue;
660 }
661
662 // If this is a memcpy or memmove into or out of the whole allocation, we
663 // can handle it like a load or store of the scalar type.
664 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
665 assert(Offset == 0 && "must be store to start of alloca");
Bob Wilson69743022011-01-13 20:59:44 +0000666
Chris Lattner4cc576b2010-04-16 00:24:57 +0000667 // If the source and destination are both to the same alloca, then this is
668 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
669 // as appropriate.
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000670 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
Bob Wilson69743022011-01-13 20:59:44 +0000671
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000672 if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000673 // Dest must be OrigAI, change this to be a load from the original
674 // pointer (bitcasted), then a store to our new alloca.
675 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
676 Value *SrcPtr = MTI->getSource();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000677 PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
678 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
Mon P Wange90a6332010-12-23 01:41:32 +0000679 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
680 AIPTy = PointerType::get(AIPTy->getElementType(),
681 SPTy->getAddressSpace());
682 }
683 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
684
Chris Lattner4cc576b2010-04-16 00:24:57 +0000685 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
686 SrcVal->setAlignment(MTI->getAlignment());
687 Builder.CreateStore(SrcVal, NewAI);
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000688 } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000689 // Src must be OrigAI, change this to be a load from NewAI then a store
690 // through the original dest pointer (bitcasted).
691 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
692 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
693
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000694 PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
695 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
Mon P Wange90a6332010-12-23 01:41:32 +0000696 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
697 AIPTy = PointerType::get(AIPTy->getElementType(),
698 DPTy->getAddressSpace());
699 }
700 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
701
Chris Lattner4cc576b2010-04-16 00:24:57 +0000702 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
703 NewStore->setAlignment(MTI->getAlignment());
704 } else {
705 // Noop transfer. Src == Dst
706 }
707
708 MTI->eraseFromParent();
709 continue;
710 }
Bob Wilson69743022011-01-13 20:59:44 +0000711
Chris Lattner4cc576b2010-04-16 00:24:57 +0000712 llvm_unreachable("Unsupported operation!");
713 }
714}
715
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000716/// getScaledElementType - Gets a scaled element type for a partial vector
Cameron Zwarich344731c2011-04-20 21:48:38 +0000717/// access of an alloca. The input types must be integer or floating-point
718/// scalar or vector types, and the resulting type is an integer, float or
719/// double.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000720static Type *getScaledElementType(Type *Ty1, Type *Ty2,
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000721 unsigned NewBitWidth) {
Cameron Zwarich344731c2011-04-20 21:48:38 +0000722 bool IsFP1 = Ty1->isFloatingPointTy() ||
723 (Ty1->isVectorTy() &&
724 cast<VectorType>(Ty1)->getElementType()->isFloatingPointTy());
725 bool IsFP2 = Ty2->isFloatingPointTy() ||
726 (Ty2->isVectorTy() &&
727 cast<VectorType>(Ty2)->getElementType()->isFloatingPointTy());
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000728
Cameron Zwarich344731c2011-04-20 21:48:38 +0000729 LLVMContext &Context = Ty1->getContext();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000730
Cameron Zwarich344731c2011-04-20 21:48:38 +0000731 // Prefer floating-point types over integer types, as integer types may have
732 // been created by earlier scalar replacement.
733 if (IsFP1 || IsFP2) {
734 if (NewBitWidth == 32)
735 return Type::getFloatTy(Context);
736 if (NewBitWidth == 64)
737 return Type::getDoubleTy(Context);
738 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000739
Cameron Zwarich344731c2011-04-20 21:48:38 +0000740 return Type::getIntNTy(Context, NewBitWidth);
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000741}
742
Mon P Wangddf9abf2011-04-14 08:04:01 +0000743/// CreateShuffleVectorCast - Creates a shuffle vector to convert one vector
744/// to another vector of the same element type which has the same allocation
745/// size but different primitive sizes (e.g. <3 x i32> and <4 x i32>).
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000746static Value *CreateShuffleVectorCast(Value *FromVal, Type *ToType,
Mon P Wangddf9abf2011-04-14 08:04:01 +0000747 IRBuilder<> &Builder) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000748 Type *FromType = FromVal->getType();
749 VectorType *FromVTy = cast<VectorType>(FromType);
750 VectorType *ToVTy = cast<VectorType>(ToType);
Mon P Wang481823a2011-04-14 19:20:42 +0000751 assert((ToVTy->getElementType() == FromVTy->getElementType()) &&
Mon P Wangddf9abf2011-04-14 08:04:01 +0000752 "Vectors must have the same element type");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000753 Value *UnV = UndefValue::get(FromType);
754 unsigned numEltsFrom = FromVTy->getNumElements();
755 unsigned numEltsTo = ToVTy->getNumElements();
756
757 SmallVector<Constant*, 3> Args;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000758 Type* Int32Ty = Builder.getInt32Ty();
Mon P Wangddf9abf2011-04-14 08:04:01 +0000759 unsigned minNumElts = std::min(numEltsFrom, numEltsTo);
760 unsigned i;
761 for (i=0; i != minNumElts; ++i)
Mon P Wang481823a2011-04-14 19:20:42 +0000762 Args.push_back(ConstantInt::get(Int32Ty, i));
Mon P Wangddf9abf2011-04-14 08:04:01 +0000763
764 if (i < numEltsTo) {
Mon P Wang481823a2011-04-14 19:20:42 +0000765 Constant* UnC = UndefValue::get(Int32Ty);
Mon P Wangddf9abf2011-04-14 08:04:01 +0000766 for (; i != numEltsTo; ++i)
767 Args.push_back(UnC);
768 }
769 Constant *Mask = ConstantVector::get(Args);
770 return Builder.CreateShuffleVector(FromVal, UnV, Mask, "tmpV");
771}
772
Chris Lattner4cc576b2010-04-16 00:24:57 +0000773/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
774/// or vector value FromVal, extracting the bits from the offset specified by
775/// Offset. This returns the value, which is of type ToType.
776///
777/// This happens when we are converting an "integer union" to a single
778/// integer scalar, or when we are converting a "vector union" to a vector with
779/// insert/extractelement instructions.
780///
781/// Offset is an offset from the original alloca, in bits that need to be
782/// shifted to the right.
783Value *ConvertToScalarInfo::
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000784ConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000785 uint64_t Offset, IRBuilder<> &Builder) {
786 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000787 Type *FromType = FromVal->getType();
Mon P Wangbe0761c2011-04-13 21:40:02 +0000788 if (FromType == ToType && Offset == 0)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000789 return FromVal;
790
791 // If the result alloca is a vector type, this is either an element
792 // access or a bitcast to another vector type of the same size.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000793 if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
Cameron Zwarich0398d612011-06-08 22:08:31 +0000794 unsigned FromTypeSize = TD.getTypeAllocSize(FromType);
Cameron Zwarich9827b782011-03-29 05:19:52 +0000795 unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
Cameron Zwarich0398d612011-06-08 22:08:31 +0000796 if (FromTypeSize == ToTypeSize) {
Mon P Wangddf9abf2011-04-14 08:04:01 +0000797 // If the two types have the same primitive size, use a bit cast.
798 // Otherwise, it is two vectors with the same element type that has
799 // the same allocation size but different number of elements so use
800 // a shuffle vector.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000801 if (FromType->getPrimitiveSizeInBits() ==
802 ToType->getPrimitiveSizeInBits())
803 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000804 else
805 return CreateShuffleVectorCast(FromVal, ToType, Builder);
Mon P Wangbe0761c2011-04-13 21:40:02 +0000806 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000807
Cameron Zwarich0398d612011-06-08 22:08:31 +0000808 if (isPowerOf2_64(FromTypeSize / ToTypeSize)) {
Cameron Zwarich344731c2011-04-20 21:48:38 +0000809 assert(!(ToType->isVectorTy() && Offset != 0) && "Can't extract a value "
810 "of a smaller vector type at a nonzero offset.");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000811
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000812 Type *CastElementTy = getScaledElementType(FromType, ToType,
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000813 ToTypeSize * 8);
Cameron Zwarich0398d612011-06-08 22:08:31 +0000814 unsigned NumCastVectorElements = FromTypeSize / ToTypeSize;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000815
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000816 LLVMContext &Context = FromVal->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000817 Type *CastTy = VectorType::get(CastElementTy,
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000818 NumCastVectorElements);
819 Value *Cast = Builder.CreateBitCast(FromVal, CastTy, "tmp");
Cameron Zwarich344731c2011-04-20 21:48:38 +0000820
821 unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
822 unsigned Elt = Offset/EltSize;
823 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000824 Value *Extract = Builder.CreateExtractElement(Cast, ConstantInt::get(
Cameron Zwarich344731c2011-04-20 21:48:38 +0000825 Type::getInt32Ty(Context), Elt), "tmp");
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000826 return Builder.CreateBitCast(Extract, ToType, "tmp");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000827 }
Chris Lattner4cc576b2010-04-16 00:24:57 +0000828
829 // Otherwise it must be an element access.
830 unsigned Elt = 0;
831 if (Offset) {
832 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
833 Elt = Offset/EltSize;
834 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
835 }
836 // Return the element extracted out of it.
837 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
838 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
839 if (V->getType() != ToType)
840 V = Builder.CreateBitCast(V, ToType, "tmp");
841 return V;
842 }
Bob Wilson69743022011-01-13 20:59:44 +0000843
Chris Lattner4cc576b2010-04-16 00:24:57 +0000844 // If ToType is a first class aggregate, extract out each of the pieces and
845 // use insertvalue's to form the FCA.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000846 if (StructType *ST = dyn_cast<StructType>(ToType)) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000847 const StructLayout &Layout = *TD.getStructLayout(ST);
848 Value *Res = UndefValue::get(ST);
849 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
850 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
851 Offset+Layout.getElementOffsetInBits(i),
852 Builder);
853 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
854 }
855 return Res;
856 }
Bob Wilson69743022011-01-13 20:59:44 +0000857
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000858 if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000859 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
860 Value *Res = UndefValue::get(AT);
861 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
862 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
863 Offset+i*EltSize, Builder);
864 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
865 }
866 return Res;
867 }
868
869 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000870 IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Chris Lattner4cc576b2010-04-16 00:24:57 +0000871
872 // If this is a big-endian system and the load is narrower than the
873 // full alloca type, we need to do a shift to get the right bits.
874 int ShAmt = 0;
875 if (TD.isBigEndian()) {
876 // On big-endian machines, the lowest bit is stored at the bit offset
877 // from the pointer given by getTypeStoreSizeInBits. This matters for
878 // integers with a bitwidth that is not a multiple of 8.
879 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
880 TD.getTypeStoreSizeInBits(ToType) - Offset;
881 } else {
882 ShAmt = Offset;
883 }
884
885 // Note: we support negative bitwidths (with shl) which are not defined.
886 // We do this to support (f.e.) loads off the end of a structure where
887 // only some bits are used.
888 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
889 FromVal = Builder.CreateLShr(FromVal,
890 ConstantInt::get(FromVal->getType(),
891 ShAmt), "tmp");
892 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson69743022011-01-13 20:59:44 +0000893 FromVal = Builder.CreateShl(FromVal,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000894 ConstantInt::get(FromVal->getType(),
895 -ShAmt), "tmp");
896
897 // Finally, unconditionally truncate the integer to the right width.
898 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
899 if (LIBitWidth < NTy->getBitWidth())
900 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000901 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000902 LIBitWidth), "tmp");
903 else if (LIBitWidth > NTy->getBitWidth())
904 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000905 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000906 LIBitWidth), "tmp");
907
908 // If the result is an integer, this is a trunc or bitcast.
909 if (ToType->isIntegerTy()) {
910 // Should be done.
911 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
912 // Just do a bitcast, we know the sizes match up.
913 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
914 } else {
915 // Otherwise must be a pointer.
916 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
917 }
918 assert(FromVal->getType() == ToType && "Didn't convert right?");
919 return FromVal;
920}
921
922/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
923/// or vector value "Old" at the offset specified by Offset.
924///
925/// This happens when we are converting an "integer union" to a
926/// single integer scalar, or when we are converting a "vector union" to a
927/// vector with insert/extractelement instructions.
928///
929/// Offset is an offset from the original alloca, in bits that need to be
930/// shifted to the right.
931Value *ConvertToScalarInfo::
932ConvertScalar_InsertValue(Value *SV, Value *Old,
933 uint64_t Offset, IRBuilder<> &Builder) {
934 // Convert the stored type to the actual type, shift it left to insert
935 // then 'or' into place.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000936 Type *AllocaType = Old->getType();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000937 LLVMContext &Context = Old->getContext();
938
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000939 if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000940 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
941 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
Bob Wilson69743022011-01-13 20:59:44 +0000942
Chris Lattner4cc576b2010-04-16 00:24:57 +0000943 // Changing the whole vector with memset or with an access of a different
944 // vector type?
Mon P Wangbe0761c2011-04-13 21:40:02 +0000945 if (ValSize == VecSize) {
Mon P Wangddf9abf2011-04-14 08:04:01 +0000946 // If the two types have the same primitive size, use a bit cast.
947 // Otherwise, it is two vectors with the same element type that has
948 // the same allocation size but different number of elements so use
949 // a shuffle vector.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000950 if (VTy->getPrimitiveSizeInBits() ==
951 SV->getType()->getPrimitiveSizeInBits())
952 return Builder.CreateBitCast(SV, AllocaType, "tmp");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000953 else
954 return CreateShuffleVectorCast(SV, VTy, Builder);
Mon P Wangbe0761c2011-04-13 21:40:02 +0000955 }
Chris Lattner4cc576b2010-04-16 00:24:57 +0000956
Cameron Zwarich344731c2011-04-20 21:48:38 +0000957 if (isPowerOf2_64(VecSize / ValSize)) {
958 assert(!(SV->getType()->isVectorTy() && Offset != 0) && "Can't insert a "
959 "value of a smaller vector type at a nonzero offset.");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000960
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000961 Type *CastElementTy = getScaledElementType(VTy, SV->getType(),
Cameron Zwarich344731c2011-04-20 21:48:38 +0000962 ValSize);
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000963 unsigned NumCastVectorElements = VecSize / ValSize;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000964
965 LLVMContext &Context = SV->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000966 Type *OldCastTy = VectorType::get(CastElementTy,
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000967 NumCastVectorElements);
968 Value *OldCast = Builder.CreateBitCast(Old, OldCastTy, "tmp");
969
970 Value *SVCast = Builder.CreateBitCast(SV, CastElementTy, "tmp");
Cameron Zwarich344731c2011-04-20 21:48:38 +0000971
972 unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
973 unsigned Elt = Offset/EltSize;
974 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000975 Value *Insert =
976 Builder.CreateInsertElement(OldCast, SVCast, ConstantInt::get(
Cameron Zwarich344731c2011-04-20 21:48:38 +0000977 Type::getInt32Ty(Context), Elt), "tmp");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000978 return Builder.CreateBitCast(Insert, AllocaType, "tmp");
979 }
980
Chris Lattner4cc576b2010-04-16 00:24:57 +0000981 // Must be an element insertion.
Cameron Zwarichc5c43b92011-04-20 21:48:34 +0000982 assert(SV->getType() == VTy->getElementType());
983 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner4cc576b2010-04-16 00:24:57 +0000984 unsigned Elt = Offset/EltSize;
Cameron Zwarichc5c43b92011-04-20 21:48:34 +0000985 return Builder.CreateInsertElement(Old, SV,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000986 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
987 "tmp");
Chris Lattner4cc576b2010-04-16 00:24:57 +0000988 }
Bob Wilson69743022011-01-13 20:59:44 +0000989
Chris Lattner4cc576b2010-04-16 00:24:57 +0000990 // If SV is a first-class aggregate value, insert each value recursively.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000991 if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000992 const StructLayout &Layout = *TD.getStructLayout(ST);
993 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
994 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000995 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000996 Offset+Layout.getElementOffsetInBits(i),
997 Builder);
998 }
999 return Old;
1000 }
Bob Wilson69743022011-01-13 20:59:44 +00001001
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001002 if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Chris Lattner4cc576b2010-04-16 00:24:57 +00001003 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
1004 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1005 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1006 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
1007 }
1008 return Old;
1009 }
1010
1011 // If SV is a float, convert it to the appropriate integer type.
1012 // If it is a pointer, do the same.
1013 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
1014 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
1015 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
1016 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
1017 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
1018 SV = Builder.CreateBitCast(SV,
1019 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
1020 else if (SV->getType()->isPointerTy())
1021 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
1022
1023 // Zero extend or truncate the value if needed.
1024 if (SV->getType() != AllocaType) {
1025 if (SV->getType()->getPrimitiveSizeInBits() <
1026 AllocaType->getPrimitiveSizeInBits())
1027 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
1028 else {
1029 // Truncation may be needed if storing more than the alloca can hold
1030 // (undefined behavior).
1031 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
1032 SrcWidth = DestWidth;
1033 SrcStoreWidth = DestStoreWidth;
1034 }
1035 }
1036
1037 // If this is a big-endian system and the store is narrower than the
1038 // full alloca type, we need to do a shift to get the right bits.
1039 int ShAmt = 0;
1040 if (TD.isBigEndian()) {
1041 // On big-endian machines, the lowest bit is stored at the bit offset
1042 // from the pointer given by getTypeStoreSizeInBits. This matters for
1043 // integers with a bitwidth that is not a multiple of 8.
1044 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1045 } else {
1046 ShAmt = Offset;
1047 }
1048
1049 // Note: we support negative bitwidths (with shr) which are not defined.
1050 // We do this to support (f.e.) stores off the end of a structure where
1051 // only some bits in the structure are set.
1052 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1053 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1054 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
1055 ShAmt), "tmp");
1056 Mask <<= ShAmt;
1057 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1058 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
1059 -ShAmt), "tmp");
1060 Mask = Mask.lshr(-ShAmt);
1061 }
1062
1063 // Mask out the bits we are about to insert from the old value, and or
1064 // in the new bits.
1065 if (SrcWidth != DestWidth) {
1066 assert(DestWidth > SrcWidth);
1067 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1068 SV = Builder.CreateOr(Old, SV, "ins");
1069 }
1070 return SV;
1071}
1072
1073
1074//===----------------------------------------------------------------------===//
1075// SRoA Driver
1076//===----------------------------------------------------------------------===//
1077
1078
Chris Lattnered7b41e2003-05-27 15:45:27 +00001079bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +00001080 TD = getAnalysisIfAvailable<TargetData>();
1081
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001082 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +00001083
1084 // FIXME: ScalarRepl currently depends on TargetData more than it
1085 // theoretically needs to. It should be refactored in order to support
1086 // target-independent IR. Until this is done, just skip the actual
1087 // scalar-replacement portion of this pass.
1088 if (!TD) return Changed;
1089
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001090 while (1) {
1091 bool LocalChange = performScalarRepl(F);
1092 if (!LocalChange) break; // No need to repromote if no scalarrepl
1093 Changed = true;
1094 LocalChange = performPromotion(F);
1095 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
1096 }
Chris Lattner38aec322003-09-11 16:45:55 +00001097
1098 return Changed;
1099}
1100
Chris Lattnerd0f56132011-01-14 19:50:47 +00001101namespace {
1102class AllocaPromoter : public LoadAndStorePromoter {
1103 AllocaInst *AI;
Devang Patel231a5ab2011-07-06 21:09:55 +00001104 DIBuilder *DIB;
Devang Patel4fd3c592011-07-06 22:06:11 +00001105 SmallVector<DbgDeclareInst *, 4> DDIs;
1106 SmallVector<DbgValueInst *, 4> DVIs;
Chris Lattnerd0f56132011-01-14 19:50:47 +00001107public:
Cameron Zwarichc8279392011-05-24 03:10:43 +00001108 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
Devang Patel231a5ab2011-07-06 21:09:55 +00001109 DIBuilder *DB)
Devang Patel4fd3c592011-07-06 22:06:11 +00001110 : LoadAndStorePromoter(Insts, S), AI(0), DIB(DB) {}
Chris Lattnerd0f56132011-01-14 19:50:47 +00001111
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001112 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerd0f56132011-01-14 19:50:47 +00001113 // Remember which alloca we're promoting (for isInstInList).
1114 this->AI = AI;
Devang Patel4fd3c592011-07-06 22:06:11 +00001115 if (MDNode *DebugNode = MDNode::getIfExists(AI->getContext(), AI))
1116 for (Value::use_iterator UI = DebugNode->use_begin(),
1117 E = DebugNode->use_end(); UI != E; ++UI)
1118 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1119 DDIs.push_back(DDI);
1120 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1121 DVIs.push_back(DVI);
1122
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001123 LoadAndStorePromoter::run(Insts);
Chris Lattnerd0f56132011-01-14 19:50:47 +00001124 AI->eraseFromParent();
Devang Patel4fd3c592011-07-06 22:06:11 +00001125 for (SmallVector<DbgDeclareInst *, 4>::iterator I = DDIs.begin(),
1126 E = DDIs.end(); I != E; ++I) {
1127 DbgDeclareInst *DDI = *I;
Devang Patel231a5ab2011-07-06 21:09:55 +00001128 DDI->eraseFromParent();
Devang Patel4fd3c592011-07-06 22:06:11 +00001129 }
1130 for (SmallVector<DbgValueInst *, 4>::iterator I = DVIs.begin(),
1131 E = DVIs.end(); I != E; ++I) {
1132 DbgValueInst *DVI = *I;
1133 DVI->eraseFromParent();
1134 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001135 }
1136
Chris Lattnerd0f56132011-01-14 19:50:47 +00001137 virtual bool isInstInList(Instruction *I,
1138 const SmallVectorImpl<Instruction*> &Insts) const {
1139 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1140 return LI->getOperand(0) == AI;
1141 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001142 }
Devang Patel231a5ab2011-07-06 21:09:55 +00001143
Devang Patel4fd3c592011-07-06 22:06:11 +00001144 virtual void updateDebugInfo(Instruction *Inst) const {
1145 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1146 E = DDIs.end(); I != E; ++I) {
1147 DbgDeclareInst *DDI = *I;
1148 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1149 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
1150 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1151 ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
1152 }
1153 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1154 E = DVIs.end(); I != E; ++I) {
1155 DbgValueInst *DVI = *I;
1156 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1157 Instruction *DbgVal = NULL;
1158 // If an argument is zero extended then use argument directly. The ZExt
1159 // may be zapped by an optimization pass in future.
1160 Argument *ExtendedArg = NULL;
1161 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1162 ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
1163 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1164 ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
1165 if (ExtendedArg)
1166 DbgVal = DIB->insertDbgValueIntrinsic(ExtendedArg, 0,
1167 DIVariable(DVI->getVariable()),
1168 SI);
1169 else
1170 DbgVal = DIB->insertDbgValueIntrinsic(SI->getOperand(0), 0,
1171 DIVariable(DVI->getVariable()),
1172 SI);
Devang Patela4acb002011-07-07 00:05:58 +00001173 DbgVal->setDebugLoc(DVI->getDebugLoc());
Devang Patel4fd3c592011-07-06 22:06:11 +00001174 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1175 Instruction *DbgVal =
1176 DIB->insertDbgValueIntrinsic(LI->getOperand(0), 0,
1177 DIVariable(DVI->getVariable()), LI);
Devang Patela4acb002011-07-07 00:05:58 +00001178 DbgVal->setDebugLoc(DVI->getDebugLoc());
Devang Patel4fd3c592011-07-06 22:06:11 +00001179 }
1180 }
Devang Patel231a5ab2011-07-06 21:09:55 +00001181 }
Chris Lattnerd0f56132011-01-14 19:50:47 +00001182};
1183} // end anon namespace
Chris Lattner38aec322003-09-11 16:45:55 +00001184
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001185/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1186/// subsequently loaded can be rewritten to load both input pointers and then
1187/// select between the result, allowing the load of the alloca to be promoted.
1188/// From this:
1189/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1190/// %V = load i32* %P2
1191/// to:
1192/// %V1 = load i32* %Alloca -> will be mem2reg'd
1193/// %V2 = load i32* %Other
Chris Lattnere3357862011-01-24 01:07:11 +00001194/// %V = select i1 %cond, i32 %V1, i32 %V2
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001195///
1196/// We can do this to a select if its only uses are loads and if the operand to
1197/// the select can be loaded unconditionally.
1198static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
1199 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1200 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1201
1202 for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1203 UI != UE; ++UI) {
1204 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1205 if (LI == 0 || LI->isVolatile()) return false;
1206
Chris Lattnere3357862011-01-24 01:07:11 +00001207 // Both operands to the select need to be dereferencable, either absolutely
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001208 // (e.g. allocas) or at this point because we can see other accesses to it.
1209 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1210 LI->getAlignment(), TD))
1211 return false;
1212 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1213 LI->getAlignment(), TD))
1214 return false;
1215 }
1216
1217 return true;
1218}
1219
Chris Lattnere3357862011-01-24 01:07:11 +00001220/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1221/// subsequently loaded can be rewritten to load both input pointers in the pred
1222/// blocks and then PHI the results, allowing the load of the alloca to be
1223/// promoted.
1224/// From this:
1225/// %P2 = phi [i32* %Alloca, i32* %Other]
1226/// %V = load i32* %P2
1227/// to:
1228/// %V1 = load i32* %Alloca -> will be mem2reg'd
1229/// ...
1230/// %V2 = load i32* %Other
1231/// ...
1232/// %V = phi [i32 %V1, i32 %V2]
1233///
1234/// We can do this to a select if its only uses are loads and if the operand to
1235/// the select can be loaded unconditionally.
1236static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
1237 // For now, we can only do this promotion if the load is in the same block as
1238 // the PHI, and if there are no stores between the phi and load.
1239 // TODO: Allow recursive phi users.
1240 // TODO: Allow stores.
1241 BasicBlock *BB = PN->getParent();
1242 unsigned MaxAlign = 0;
1243 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1244 UI != UE; ++UI) {
1245 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1246 if (LI == 0 || LI->isVolatile()) return false;
1247
1248 // For now we only allow loads in the same block as the PHI. This is a
1249 // common case that happens when instcombine merges two loads through a PHI.
1250 if (LI->getParent() != BB) return false;
1251
1252 // Ensure that there are no instructions between the PHI and the load that
1253 // could store.
1254 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1255 if (BBI->mayWriteToMemory())
1256 return false;
1257
1258 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1259 }
1260
1261 // Okay, we know that we have one or more loads in the same block as the PHI.
1262 // We can transform this if it is safe to push the loads into the predecessor
1263 // blocks. The only thing to watch out for is that we can't put a possibly
1264 // trapping load in the predecessor if it is a critical edge.
1265 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1266 BasicBlock *Pred = PN->getIncomingBlock(i);
1267
1268 // If the predecessor has a single successor, then the edge isn't critical.
1269 if (Pred->getTerminator()->getNumSuccessors() == 1)
1270 continue;
1271
1272 Value *InVal = PN->getIncomingValue(i);
1273
1274 // If the InVal is an invoke in the pred, we can't put a load on the edge.
1275 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
1276 if (II->getParent() == Pred)
1277 return false;
1278
1279 // If this pointer is always safe to load, or if we can prove that there is
1280 // already a load in the block, then we can move the load to the pred block.
1281 if (InVal->isDereferenceablePointer() ||
1282 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1283 continue;
1284
1285 return false;
1286 }
1287
1288 return true;
1289}
1290
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001291
1292/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1293/// direct (non-volatile) loads and stores to it. If the alloca is close but
1294/// not quite there, this will transform the code to allow promotion. As such,
1295/// it is a non-pure predicate.
1296static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
1297 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1298 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1299
1300 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1301 UI != UE; ++UI) {
1302 User *U = *UI;
1303 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1304 if (LI->isVolatile())
1305 return false;
1306 continue;
1307 }
1308
1309 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1310 if (SI->getOperand(0) == AI || SI->isVolatile())
1311 return false; // Don't allow a store OF the AI, only INTO the AI.
1312 continue;
1313 }
1314
1315 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1316 // If the condition being selected on is a constant, fold the select, yes
1317 // this does (rarely) happen early on.
1318 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1319 Value *Result = SI->getOperand(1+CI->isZero());
1320 SI->replaceAllUsesWith(Result);
1321 SI->eraseFromParent();
1322
1323 // This is very rare and we just scrambled the use list of AI, start
1324 // over completely.
1325 return tryToMakeAllocaBePromotable(AI, TD);
1326 }
1327
1328 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1329 // loads, then we can transform this by rewriting the select.
1330 if (!isSafeSelectToSpeculate(SI, TD))
1331 return false;
1332
1333 InstsToRewrite.insert(SI);
1334 continue;
1335 }
1336
Chris Lattnere3357862011-01-24 01:07:11 +00001337 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1338 if (PN->use_empty()) { // Dead PHIs can be stripped.
1339 InstsToRewrite.insert(PN);
1340 continue;
1341 }
1342
1343 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1344 // in the pred blocks, then we can transform this by rewriting the PHI.
1345 if (!isSafePHIToSpeculate(PN, TD))
1346 return false;
1347
1348 InstsToRewrite.insert(PN);
1349 continue;
1350 }
1351
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001352 return false;
1353 }
1354
1355 // If there are no instructions to rewrite, then all uses are load/stores and
1356 // we're done!
1357 if (InstsToRewrite.empty())
1358 return true;
1359
1360 // If we have instructions that need to be rewritten for this to be promotable
1361 // take care of it now.
1362 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
Chris Lattnere3357862011-01-24 01:07:11 +00001363 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1364 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1365 // loads with a new select.
1366 while (!SI->use_empty()) {
1367 LoadInst *LI = cast<LoadInst>(SI->use_back());
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001368
Chris Lattnere3357862011-01-24 01:07:11 +00001369 IRBuilder<> Builder(LI);
1370 LoadInst *TrueLoad =
1371 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1372 LoadInst *FalseLoad =
Nick Lewycky394d1f12011-07-01 06:27:03 +00001373 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
Chris Lattnere3357862011-01-24 01:07:11 +00001374
1375 // Transfer alignment and TBAA info if present.
1376 TrueLoad->setAlignment(LI->getAlignment());
1377 FalseLoad->setAlignment(LI->getAlignment());
1378 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1379 TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1380 FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1381 }
1382
1383 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1384 V->takeName(LI);
1385 LI->replaceAllUsesWith(V);
1386 LI->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001387 }
Chris Lattnere3357862011-01-24 01:07:11 +00001388
1389 // Now that all the loads are gone, the select is gone too.
1390 SI->eraseFromParent();
1391 continue;
1392 }
1393
1394 // Otherwise, we have a PHI node which allows us to push the loads into the
1395 // predecessors.
1396 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1397 if (PN->use_empty()) {
1398 PN->eraseFromParent();
1399 continue;
1400 }
1401
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001402 Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
Jay Foad3ecfc862011-03-30 11:28:46 +00001403 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1404 PN->getName()+".ld", PN);
Chris Lattnere3357862011-01-24 01:07:11 +00001405
1406 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1407 // matter which one we get and if any differ, it doesn't matter.
1408 LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1409 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1410 unsigned Align = SomeLoad->getAlignment();
1411
1412 // Rewrite all loads of the PN to use the new PHI.
1413 while (!PN->use_empty()) {
1414 LoadInst *LI = cast<LoadInst>(PN->use_back());
1415 LI->replaceAllUsesWith(NewPN);
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001416 LI->eraseFromParent();
1417 }
1418
Chris Lattnere3357862011-01-24 01:07:11 +00001419 // Inject loads into all of the pred blocks. Keep track of which blocks we
1420 // insert them into in case we have multiple edges from the same block.
1421 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1422
1423 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1424 BasicBlock *Pred = PN->getIncomingBlock(i);
1425 LoadInst *&Load = InsertedLoads[Pred];
1426 if (Load == 0) {
1427 Load = new LoadInst(PN->getIncomingValue(i),
1428 PN->getName() + "." + Pred->getName(),
1429 Pred->getTerminator());
1430 Load->setAlignment(Align);
1431 if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1432 }
1433
1434 NewPN->addIncoming(Load, Pred);
1435 }
1436
1437 PN->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001438 }
1439
1440 ++NumAdjusted;
1441 return true;
1442}
1443
Chris Lattner38aec322003-09-11 16:45:55 +00001444bool SROA::performPromotion(Function &F) {
1445 std::vector<AllocaInst*> Allocas;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001446 DominatorTree *DT = 0;
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001447 if (HasDomTree)
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001448 DT = &getAnalysis<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +00001449
Chris Lattner02a3be02003-09-20 14:39:18 +00001450 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Devang Patel231a5ab2011-07-06 21:09:55 +00001451 DIBuilder DIB(*F.getParent());
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001452 bool Changed = false;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001453 SmallVector<Instruction*, 64> Insts;
Chris Lattner38aec322003-09-11 16:45:55 +00001454 while (1) {
1455 Allocas.clear();
1456
1457 // Find allocas that are safe to promote, by looking at all instructions in
1458 // the entry node
1459 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1460 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001461 if (tryToMakeAllocaBePromotable(AI, TD))
Chris Lattner38aec322003-09-11 16:45:55 +00001462 Allocas.push_back(AI);
1463
1464 if (Allocas.empty()) break;
1465
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001466 if (HasDomTree)
Cameron Zwarich419e8a62011-01-17 17:38:41 +00001467 PromoteMemToReg(Allocas, *DT);
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001468 else {
1469 SSAUpdater SSA;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001470 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1471 AllocaInst *AI = Allocas[i];
1472
1473 // Build list of instructions to promote.
1474 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1475 UI != E; ++UI)
1476 Insts.push_back(cast<Instruction>(*UI));
Devang Patel231a5ab2011-07-06 21:09:55 +00001477 AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001478 Insts.clear();
1479 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001480 }
Chris Lattner38aec322003-09-11 16:45:55 +00001481 NumPromoted += Allocas.size();
1482 Changed = true;
1483 }
1484
1485 return Changed;
1486}
1487
Chris Lattner4cc576b2010-04-16 00:24:57 +00001488
Bob Wilson3992feb2010-02-03 17:23:56 +00001489/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1490/// SROA. It must be a struct or array type with a small number of elements.
1491static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001492 Type *T = AI->getAllocatedType();
Bob Wilson3992feb2010-02-03 17:23:56 +00001493 // Do not promote any struct into more than 32 separate vars.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001494 if (StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +00001495 return ST->getNumElements() <= 32;
1496 // Arrays are much less likely to be safe for SROA; only consider
1497 // them if they are very small.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001498 if (ArrayType *AT = dyn_cast<ArrayType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +00001499 return AT->getNumElements() <= 8;
1500 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +00001501}
1502
Chris Lattnerc4472072010-04-15 23:50:26 +00001503
Chris Lattner38aec322003-09-11 16:45:55 +00001504// performScalarRepl - This algorithm is a simple worklist driven algorithm,
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001505// which runs on all of the alloca instructions in the function, removing them
1506// if they are only used by getelementptr instructions.
Chris Lattner38aec322003-09-11 16:45:55 +00001507//
1508bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001509 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +00001510
Chris Lattner31d80102010-04-15 21:59:20 +00001511 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +00001512 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001513 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +00001514 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +00001515 WorkList.push_back(A);
1516
1517 // Process the worklist
1518 bool Changed = false;
1519 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001520 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001521 WorkList.pop_back();
Bob Wilson69743022011-01-13 20:59:44 +00001522
Chris Lattneradd2bd72006-12-22 23:14:42 +00001523 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1524 // with unused elements.
1525 if (AI->use_empty()) {
1526 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +00001527 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +00001528 continue;
1529 }
Chris Lattner7809ecd2009-02-03 01:30:09 +00001530
1531 // If this alloca is impossible for us to promote, reject it early.
1532 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1533 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001534
Chris Lattner79b3bd32007-04-25 06:40:51 +00001535 // Check to see if this allocation is only modified by a memcpy/memmove from
1536 // a constant global. If this is the case, we can change all users to use
1537 // the constant global instead. This is commonly produced by the CFE by
1538 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1539 // is only subsequently read.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001540 SmallVector<Instruction *, 4> ToDelete;
1541 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(AI, ToDelete)) {
David Greene504c7d82010-01-05 01:27:09 +00001542 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001543 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
1544 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
1545 ToDelete[i]->eraseFromParent();
1546 Constant *TheSrc = cast<Constant>(Copy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001547 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001548 Copy->eraseFromParent(); // Don't mutate the global.
Chris Lattner79b3bd32007-04-25 06:40:51 +00001549 AI->eraseFromParent();
1550 ++NumGlobals;
1551 Changed = true;
1552 continue;
1553 }
Bob Wilson69743022011-01-13 20:59:44 +00001554
Chris Lattner7809ecd2009-02-03 01:30:09 +00001555 // Check to see if we can perform the core SROA transformation. We cannot
1556 // transform the allocation instruction if it is an array allocation
1557 // (allocations OF arrays are ok though), and an allocation of a scalar
1558 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +00001559 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +00001560
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +00001561 // Do not promote [0 x %struct].
1562 if (AllocaSize == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001563
Chris Lattner31d80102010-04-15 21:59:20 +00001564 // Do not promote any struct whose size is too big.
1565 if (AllocaSize > SRThreshold) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001566
Bob Wilson3992feb2010-02-03 17:23:56 +00001567 // If the alloca looks like a good candidate for scalar replacement, and if
1568 // all its users can be transformed, then split up the aggregate into its
1569 // separate elements.
1570 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1571 DoScalarReplacement(AI, WorkList);
1572 Changed = true;
1573 continue;
1574 }
1575
Chris Lattner6e733d32009-01-28 20:16:43 +00001576 // If we can turn this aggregate value (potentially with casts) into a
1577 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001578 // IsNotTrivial tracks whether this is something that mem2reg could have
1579 // promoted itself. If so, we don't want to transform it needlessly. Note
1580 // that we can't just check based on the type: the alloca may be of an i32
1581 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +00001582 if (AllocaInst *NewAI =
1583 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001584 NewAI->takeName(AI);
1585 AI->eraseFromParent();
1586 ++NumConverted;
1587 Changed = true;
1588 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001589 }
1590
Chris Lattner7809ecd2009-02-03 01:30:09 +00001591 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +00001592 }
1593
1594 return Changed;
1595}
Chris Lattner5e062a12003-05-30 04:15:41 +00001596
Chris Lattnera10b29b2007-04-25 05:02:56 +00001597/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1598/// predicate, do SROA now.
Bob Wilson69743022011-01-13 20:59:44 +00001599void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001600 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +00001601 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +00001602 SmallVector<AllocaInst*, 32> ElementAllocas;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001603 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
Chris Lattnera10b29b2007-04-25 05:02:56 +00001604 ElementAllocas.reserve(ST->getNumContainedTypes());
1605 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Bob Wilson69743022011-01-13 20:59:44 +00001606 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +00001607 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001608 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001609 ElementAllocas.push_back(NA);
1610 WorkList.push_back(NA); // Add to worklist for recursive processing
1611 }
1612 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001613 ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
Chris Lattnera10b29b2007-04-25 05:02:56 +00001614 ElementAllocas.reserve(AT->getNumElements());
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001615 Type *ElTy = AT->getElementType();
Chris Lattnera10b29b2007-04-25 05:02:56 +00001616 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +00001617 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001618 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001619 ElementAllocas.push_back(NA);
1620 WorkList.push_back(NA); // Add to worklist for recursive processing
1621 }
1622 }
1623
Bob Wilsonb742def2009-12-18 20:14:40 +00001624 // Now that we have created the new alloca instructions, rewrite all the
1625 // uses of the old alloca.
1626 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +00001627
Bob Wilsonb742def2009-12-18 20:14:40 +00001628 // Now erase any instructions that were made dead while rewriting the alloca.
1629 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +00001630 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +00001631
Dan Gohmanfe601042010-06-22 15:08:57 +00001632 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +00001633}
Chris Lattnera59adc42009-12-14 05:11:02 +00001634
Bob Wilsonb742def2009-12-18 20:14:40 +00001635/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1636/// recursively including all their operands that become trivially dead.
1637void SROA::DeleteDeadInstructions() {
1638 while (!DeadInsts.empty()) {
1639 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +00001640
Bob Wilsonb742def2009-12-18 20:14:40 +00001641 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1642 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1643 // Zero out the operand and see if it becomes trivially dead.
1644 // (But, don't add allocas to the dead instruction list -- they are
1645 // already on the worklist and will be deleted separately.)
1646 *OI = 0;
1647 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1648 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +00001649 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001650
1651 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +00001652 }
Chris Lattnera59adc42009-12-14 05:11:02 +00001653}
Bob Wilson69743022011-01-13 20:59:44 +00001654
Bob Wilsonb742def2009-12-18 20:14:40 +00001655/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1656/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001657/// the Info parameter. Offset indicates the position within AI that is
1658/// referenced by this instruction.
Chris Lattner6c95d242011-01-23 07:29:29 +00001659void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001660 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001661 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1662 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +00001663
Bob Wilsonb742def2009-12-18 20:14:40 +00001664 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Chris Lattner6c95d242011-01-23 07:29:29 +00001665 isSafeForScalarRepl(BC, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001666 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001667 uint64_t GEPOffset = Offset;
Chris Lattner6c95d242011-01-23 07:29:29 +00001668 isSafeGEP(GEPI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001669 if (!Info.isUnsafe)
Chris Lattner6c95d242011-01-23 07:29:29 +00001670 isSafeForScalarRepl(GEPI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001671 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001672 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001673 if (Length == 0)
1674 return MarkUnsafe(Info, User);
Chris Lattner6c95d242011-01-23 07:29:29 +00001675 isSafeMemAccess(Offset, Length->getZExtValue(), 0,
Chris Lattner145c5322011-01-23 08:27:54 +00001676 UI.getOperandNo() == 0, Info, MI,
1677 true /*AllowWholeAccess*/);
Bob Wilsonb742def2009-12-18 20:14:40 +00001678 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001679 if (LI->isVolatile())
1680 return MarkUnsafe(Info, User);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001681 Type *LIType = LI->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001682 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001683 LIType, false, Info, LI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001684 Info.hasALoadOrStore = true;
1685
Bob Wilsonb742def2009-12-18 20:14:40 +00001686 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1687 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001688 if (SI->isVolatile() || SI->getOperand(0) == I)
1689 return MarkUnsafe(Info, User);
1690
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001691 Type *SIType = SI->getOperand(0)->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001692 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001693 SIType, true, Info, SI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001694 Info.hasALoadOrStore = true;
Chris Lattner145c5322011-01-23 08:27:54 +00001695 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1696 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1697 } else {
1698 return MarkUnsafe(Info, User);
1699 }
1700 if (Info.isUnsafe) return;
1701 }
1702}
1703
1704
1705/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1706/// derived from the alloca, we can often still split the alloca into elements.
1707/// This is useful if we have a large alloca where one element is phi'd
1708/// together somewhere: we can SRoA and promote all the other elements even if
1709/// we end up not being able to promote this one.
1710///
1711/// All we require is that the uses of the PHI do not index into other parts of
1712/// the alloca. The most important use case for this is single load and stores
1713/// that are PHI'd together, which can happen due to code sinking.
1714void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1715 AllocaInfo &Info) {
1716 // If we've already checked this PHI, don't do it again.
1717 if (PHINode *PN = dyn_cast<PHINode>(I))
1718 if (!Info.CheckedPHIs.insert(PN))
1719 return;
1720
1721 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1722 Instruction *User = cast<Instruction>(*UI);
1723
1724 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1725 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1726 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1727 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1728 // but would have to prove that we're staying inside of an element being
1729 // promoted.
1730 if (!GEPI->hasAllZeroIndices())
1731 return MarkUnsafe(Info, User);
1732 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1733 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1734 if (LI->isVolatile())
1735 return MarkUnsafe(Info, User);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001736 Type *LIType = LI->getType();
Chris Lattner145c5322011-01-23 08:27:54 +00001737 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1738 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1739 Info.hasALoadOrStore = true;
1740
1741 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1742 // Store is ok if storing INTO the pointer, not storing the pointer
1743 if (SI->isVolatile() || SI->getOperand(0) == I)
1744 return MarkUnsafe(Info, User);
1745
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001746 Type *SIType = SI->getOperand(0)->getType();
Chris Lattner145c5322011-01-23 08:27:54 +00001747 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1748 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1749 Info.hasALoadOrStore = true;
1750 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1751 isSafePHISelectUseForScalarRepl(User, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001752 } else {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001753 return MarkUnsafe(Info, User);
Bob Wilsonb742def2009-12-18 20:14:40 +00001754 }
1755 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001756 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001757}
Bob Wilson39c88a62009-12-17 18:34:24 +00001758
Bob Wilsonb742def2009-12-18 20:14:40 +00001759/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1760/// replacement. It is safe when all the indices are constant, in-bounds
1761/// references, and when the resulting offset corresponds to an element within
1762/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001763/// return, Offset is adjusted as specified by the GEP indices.
Chris Lattner6c95d242011-01-23 07:29:29 +00001764void SROA::isSafeGEP(GetElementPtrInst *GEPI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001765 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001766 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1767 if (GEPIt == E)
1768 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001769
Chris Lattner88e6dc82008-08-23 05:21:06 +00001770 // Walk through the GEP type indices, checking the types that this indexes
1771 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001772 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001773 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001774 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001775 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001776
Bob Wilsonb742def2009-12-18 20:14:40 +00001777 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1778 if (!IdxVal)
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001779 return MarkUnsafe(Info, GEPI);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001780 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001781
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001782 // Compute the offset due to this GEP and check if the alloca has a
1783 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001784 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
Jay Foad8fbbb392011-07-19 14:01:37 +00001785 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
Chris Lattner6c95d242011-01-23 07:29:29 +00001786 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001787 MarkUnsafe(Info, GEPI);
Chris Lattner5e062a12003-05-30 04:15:41 +00001788}
1789
Bob Wilson704d1342011-01-13 17:45:11 +00001790/// isHomogeneousAggregate - Check if type T is a struct or array containing
1791/// elements of the same type (which is always true for arrays). If so,
1792/// return true with NumElts and EltTy set to the number of elements and the
1793/// element type, respectively.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001794static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
1795 Type *&EltTy) {
1796 if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
Bob Wilson704d1342011-01-13 17:45:11 +00001797 NumElts = AT->getNumElements();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001798 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
Bob Wilson704d1342011-01-13 17:45:11 +00001799 return true;
1800 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001801 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilson704d1342011-01-13 17:45:11 +00001802 NumElts = ST->getNumContainedTypes();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001803 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
Bob Wilson704d1342011-01-13 17:45:11 +00001804 for (unsigned n = 1; n < NumElts; ++n) {
1805 if (ST->getContainedType(n) != EltTy)
1806 return false;
1807 }
1808 return true;
1809 }
1810 return false;
1811}
1812
1813/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1814/// "homogeneous" aggregates with the same element type and number of elements.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001815static bool isCompatibleAggregate(Type *T1, Type *T2) {
Bob Wilson704d1342011-01-13 17:45:11 +00001816 if (T1 == T2)
1817 return true;
1818
1819 unsigned NumElts1, NumElts2;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001820 Type *EltTy1, *EltTy2;
Bob Wilson704d1342011-01-13 17:45:11 +00001821 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1822 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1823 NumElts1 == NumElts2 &&
1824 EltTy1 == EltTy2)
1825 return true;
1826
1827 return false;
1828}
1829
Bob Wilsonb742def2009-12-18 20:14:40 +00001830/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1831/// alloca or has an offset and size that corresponds to a component element
1832/// within it. The offset checked here may have been formed from a GEP with a
1833/// pointer bitcasted to a different type.
Chris Lattner145c5322011-01-23 08:27:54 +00001834///
1835/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1836/// unit. If false, it only allows accesses known to be in a single element.
Chris Lattner6c95d242011-01-23 07:29:29 +00001837void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001838 Type *MemOpType, bool isStore,
Chris Lattner145c5322011-01-23 08:27:54 +00001839 AllocaInfo &Info, Instruction *TheAccess,
1840 bool AllowWholeAccess) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001841 // Check if this is a load/store of the entire alloca.
Chris Lattner145c5322011-01-23 08:27:54 +00001842 if (Offset == 0 && AllowWholeAccess &&
Chris Lattner6c95d242011-01-23 07:29:29 +00001843 MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
Bob Wilson704d1342011-01-13 17:45:11 +00001844 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1845 // loads/stores (which are essentially the same as the MemIntrinsics with
1846 // regard to copying padding between elements). But, if an alloca is
1847 // flagged as both a source and destination of such operations, we'll need
1848 // to check later for padding between elements.
1849 if (!MemOpType || MemOpType->isIntegerTy()) {
1850 if (isStore)
1851 Info.isMemCpyDst = true;
1852 else
1853 Info.isMemCpySrc = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001854 return;
1855 }
Bob Wilson704d1342011-01-13 17:45:11 +00001856 // This is also safe for references using a type that is compatible with
1857 // the type of the alloca, so that loads/stores can be rewritten using
1858 // insertvalue/extractvalue.
Chris Lattner6c95d242011-01-23 07:29:29 +00001859 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
Chris Lattner7e9b4272011-01-16 06:18:28 +00001860 Info.hasSubelementAccess = true;
Bob Wilson704d1342011-01-13 17:45:11 +00001861 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001862 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001863 }
1864 // Check if the offset/size correspond to a component within the alloca type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001865 Type *T = Info.AI->getAllocatedType();
Chris Lattner7e9b4272011-01-16 06:18:28 +00001866 if (TypeHasComponent(T, Offset, MemSize)) {
1867 Info.hasSubelementAccess = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001868 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001869 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001870
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001871 return MarkUnsafe(Info, TheAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +00001872}
1873
1874/// TypeHasComponent - Return true if T has a component type with the
1875/// specified offset and size. If Size is zero, do not check the size.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001876bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) {
1877 Type *EltTy;
Bob Wilsonb742def2009-12-18 20:14:40 +00001878 uint64_t EltSize;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001879 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001880 const StructLayout *Layout = TD->getStructLayout(ST);
1881 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1882 EltTy = ST->getContainedType(EltIdx);
1883 EltSize = TD->getTypeAllocSize(EltTy);
1884 Offset -= Layout->getElementOffset(EltIdx);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001885 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001886 EltTy = AT->getElementType();
1887 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001888 if (Offset >= AT->getNumElements() * EltSize)
1889 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001890 Offset %= EltSize;
1891 } else {
1892 return false;
1893 }
1894 if (Offset == 0 && (Size == 0 || EltSize == Size))
1895 return true;
1896 // Check if the component spans multiple elements.
1897 if (Offset + Size > EltSize)
1898 return false;
1899 return TypeHasComponent(EltTy, Offset, Size);
1900}
1901
1902/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1903/// the instruction I, which references it, to use the separate elements.
1904/// Offset indicates the position within AI that is referenced by this
1905/// instruction.
1906void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1907 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner145c5322011-01-23 08:27:54 +00001908 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1909 Use &TheUse = UI.getUse();
1910 Instruction *User = cast<Instruction>(*UI++);
Bob Wilsonb742def2009-12-18 20:14:40 +00001911
1912 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1913 RewriteBitCast(BC, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001914 continue;
1915 }
1916
1917 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001918 RewriteGEP(GEPI, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001919 continue;
1920 }
1921
1922 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001923 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1924 uint64_t MemSize = Length->getZExtValue();
1925 if (Offset == 0 &&
1926 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1927 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001928 // Otherwise the intrinsic can only touch a single element and the
1929 // address operand will be updated, so nothing else needs to be done.
Chris Lattner145c5322011-01-23 08:27:54 +00001930 continue;
1931 }
1932
1933 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001934 Type *LIType = LI->getType();
Chris Lattner192228e2011-01-16 05:28:59 +00001935
Bob Wilson704d1342011-01-13 17:45:11 +00001936 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001937 // Replace:
1938 // %res = load { i32, i32 }* %alloc
1939 // with:
1940 // %load.0 = load i32* %alloc.0
1941 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1942 // %load.1 = load i32* %alloc.1
1943 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1944 // (Also works for arrays instead of structs)
1945 Value *Insert = UndefValue::get(LIType);
Devang Patelabb25122011-06-03 19:46:19 +00001946 IRBuilder<> Builder(LI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001947 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patelabb25122011-06-03 19:46:19 +00001948 Value *Load = Builder.CreateLoad(NewElts[i], "load");
1949 Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
Bob Wilsonb742def2009-12-18 20:14:40 +00001950 }
1951 LI->replaceAllUsesWith(Insert);
1952 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001953 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001954 TD->getTypeAllocSize(LIType) ==
1955 TD->getTypeAllocSize(AI->getAllocatedType())) {
1956 // If this is a load of the entire alloca to an integer, rewrite it.
1957 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1958 }
Chris Lattner145c5322011-01-23 08:27:54 +00001959 continue;
1960 }
1961
1962 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001963 Value *Val = SI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001964 Type *SIType = Val->getType();
Bob Wilson704d1342011-01-13 17:45:11 +00001965 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001966 // Replace:
1967 // store { i32, i32 } %val, { i32, i32 }* %alloc
1968 // with:
1969 // %val.0 = extractvalue { i32, i32 } %val, 0
1970 // store i32 %val.0, i32* %alloc.0
1971 // %val.1 = extractvalue { i32, i32 } %val, 1
1972 // store i32 %val.1, i32* %alloc.1
1973 // (Also works for arrays instead of structs)
Devang Patelabb25122011-06-03 19:46:19 +00001974 IRBuilder<> Builder(SI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001975 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patelabb25122011-06-03 19:46:19 +00001976 Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1977 Builder.CreateStore(Extract, NewElts[i]);
Bob Wilsonb742def2009-12-18 20:14:40 +00001978 }
1979 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001980 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001981 TD->getTypeAllocSize(SIType) ==
1982 TD->getTypeAllocSize(AI->getAllocatedType())) {
1983 // If this is a store of the entire alloca from an integer, rewrite it.
1984 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1985 }
Chris Lattner145c5322011-01-23 08:27:54 +00001986 continue;
1987 }
1988
1989 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1990 // If we have a PHI user of the alloca itself (as opposed to a GEP or
1991 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1992 // the new pointer.
1993 if (!isa<AllocaInst>(I)) continue;
1994
1995 assert(Offset == 0 && NewElts[0] &&
1996 "Direct alloca use should have a zero offset");
1997
1998 // If we have a use of the alloca, we know the derived uses will be
1999 // utilizing just the first element of the scalarized result. Insert a
2000 // bitcast of the first alloca before the user as required.
2001 AllocaInst *NewAI = NewElts[0];
2002 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
2003 NewAI->moveBefore(BCI);
2004 TheUse = BCI;
2005 continue;
Bob Wilsonb742def2009-12-18 20:14:40 +00002006 }
Bob Wilson39c88a62009-12-17 18:34:24 +00002007 }
2008}
2009
Bob Wilsonb742def2009-12-18 20:14:40 +00002010/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
2011/// and recursively continue updating all of its uses.
2012void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
2013 SmallVector<AllocaInst*, 32> &NewElts) {
2014 RewriteForScalarRepl(BC, AI, Offset, NewElts);
2015 if (BC->getOperand(0) != AI)
2016 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00002017
Bob Wilsonb742def2009-12-18 20:14:40 +00002018 // The bitcast references the original alloca. Replace its uses with
2019 // references to the first new element alloca.
2020 Instruction *Val = NewElts[0];
2021 if (Val->getType() != BC->getDestTy()) {
2022 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
2023 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00002024 }
Bob Wilsonb742def2009-12-18 20:14:40 +00002025 BC->replaceAllUsesWith(Val);
2026 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00002027}
2028
Bob Wilsonb742def2009-12-18 20:14:40 +00002029/// FindElementAndOffset - Return the index of the element containing Offset
2030/// within the specified type, which must be either a struct or an array.
2031/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00002032/// element. IdxTy is set to the type of the index result to be used in a
2033/// GEP instruction.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002034uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset,
2035 Type *&IdxTy) {
Bob Wilsone88728d2009-12-19 06:53:17 +00002036 uint64_t Idx = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002037 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00002038 const StructLayout *Layout = TD->getStructLayout(ST);
2039 Idx = Layout->getElementContainingOffset(Offset);
2040 T = ST->getContainedType(Idx);
2041 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00002042 IdxTy = Type::getInt32Ty(T->getContext());
2043 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00002044 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002045 ArrayType *AT = cast<ArrayType>(T);
Bob Wilsone88728d2009-12-19 06:53:17 +00002046 T = AT->getElementType();
2047 uint64_t EltSize = TD->getTypeAllocSize(T);
2048 Idx = Offset / EltSize;
2049 Offset -= Idx * EltSize;
2050 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00002051 return Idx;
2052}
2053
2054/// RewriteGEP - Check if this GEP instruction moves the pointer across
2055/// elements of the alloca that are being split apart, and if so, rewrite
2056/// the GEP to be relative to the new element.
2057void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
2058 SmallVector<AllocaInst*, 32> &NewElts) {
2059 uint64_t OldOffset = Offset;
2060 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
Jay Foad8fbbb392011-07-19 14:01:37 +00002061 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
Bob Wilsonb742def2009-12-18 20:14:40 +00002062
2063 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
2064
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002065 Type *T = AI->getAllocatedType();
2066 Type *IdxTy;
Bob Wilsone88728d2009-12-19 06:53:17 +00002067 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00002068 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00002069 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00002070
2071 T = AI->getAllocatedType();
2072 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00002073 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00002074
2075 // If this GEP does not move the pointer across elements of the alloca
2076 // being split, then it does not needs to be rewritten.
2077 if (Idx == OldIdx)
2078 return;
2079
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002080 Type *i32Ty = Type::getInt32Ty(AI->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00002081 SmallVector<Value*, 8> NewArgs;
2082 NewArgs.push_back(Constant::getNullValue(i32Ty));
2083 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00002084 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
2085 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00002086 }
2087 Instruction *Val = NewElts[Idx];
2088 if (NewArgs.size() > 1) {
2089 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
2090 NewArgs.end(), "", GEPI);
2091 Val->takeName(GEPI);
2092 }
2093 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00002094 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002095 GEPI->replaceAllUsesWith(Val);
2096 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002097}
2098
2099/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2100/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00002101void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00002102 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00002103 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002104 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00002105 // appropriate type. The "Other" pointer is the pointer that goes to memory
2106 // that doesn't have anything to do with the alloca that we are promoting. For
2107 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00002108 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00002109 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00002110 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00002111 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00002112 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00002113 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00002114 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00002115 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00002116 }
2117 }
Bob Wilson78c50b82009-12-08 18:22:03 +00002118
Chris Lattnerd93afec2009-01-07 07:18:45 +00002119 // If there is an other pointer, we want to convert it to the same pointer
2120 // type as AI has, so we can GEP through it safely.
2121 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00002122 unsigned AddrSpace =
2123 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00002124
2125 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2126 // optimization, but it's also required to detect the corner case where
2127 // both pointer operands are referencing the same memory, and where
2128 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2129 // function is only called for mem intrinsics that access the whole
2130 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00002131 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson69743022011-01-13 20:59:44 +00002132
Bob Wilsona756b1d2010-01-19 04:32:48 +00002133 // Copying the alloca to itself is a no-op: just delete it.
2134 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2135 // This code will run twice for a no-op memcpy -- once for each operand.
2136 // Put only one reference to MI on the DeadInsts list.
2137 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
2138 E = DeadInsts.end(); I != E; ++I)
2139 if (*I == MI) return;
2140 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002141 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00002142 }
Bob Wilson69743022011-01-13 20:59:44 +00002143
Chris Lattnerd93afec2009-01-07 07:18:45 +00002144 // If the pointer is not the right type, insert a bitcast to the right
2145 // type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002146 Type *NewTy =
Chris Lattner0238f8c2010-07-08 00:27:05 +00002147 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson69743022011-01-13 20:59:44 +00002148
Chris Lattner0238f8c2010-07-08 00:27:05 +00002149 if (OtherPtr->getType() != NewTy)
2150 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002151 }
Bob Wilson69743022011-01-13 20:59:44 +00002152
Chris Lattnerd93afec2009-01-07 07:18:45 +00002153 // Process each element of the aggregate.
Bob Wilsonb742def2009-12-18 20:14:40 +00002154 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson69743022011-01-13 20:59:44 +00002155
Owen Anderson1d0be152009-08-13 21:58:54 +00002156 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00002157
2158 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2159 // If this is a memcpy/memmove, emit a GEP of the other element address.
2160 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002161 unsigned OtherEltAlign = MemAlignment;
Bob Wilson69743022011-01-13 20:59:44 +00002162
Bob Wilsona756b1d2010-01-19 04:32:48 +00002163 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002164 Value *Idx[2] = { Zero,
2165 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00002166 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00002167 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00002168 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00002169 uint64_t EltOffset;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002170 PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2171 Type *OtherTy = OtherPtrTy->getElementType();
2172 if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002173 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
2174 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002175 Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002176 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002177 }
Bob Wilson69743022011-01-13 20:59:44 +00002178
Chris Lattner1541e0f2009-03-04 19:20:50 +00002179 // The alignment of the other pointer is the guaranteed alignment of the
2180 // element, which is affected by both the known alignment of the whole
2181 // mem intrinsic and the alignment of the element. If the alignment of
2182 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2183 // known alignment is just 4 bytes.
2184 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00002185 }
Bob Wilson69743022011-01-13 20:59:44 +00002186
Chris Lattnerd93afec2009-01-07 07:18:45 +00002187 Value *EltPtr = NewElts[i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002188 Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson69743022011-01-13 20:59:44 +00002189
Chris Lattnerd93afec2009-01-07 07:18:45 +00002190 // If we got down to a scalar, insert a load or store as appropriate.
2191 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00002192 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002193 if (SROADest) {
2194 // From Other to Alloca.
2195 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2196 new StoreInst(Elt, EltPtr, MI);
2197 } else {
2198 // From Alloca to Other.
2199 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2200 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2201 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00002202 continue;
2203 }
2204 assert(isa<MemSetInst>(MI));
Bob Wilson69743022011-01-13 20:59:44 +00002205
Chris Lattnerd93afec2009-01-07 07:18:45 +00002206 // If the stored element is zero (common case), just store a null
2207 // constant.
2208 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00002209 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002210 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00002211 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00002212 } else {
2213 // If EltTy is a vector type, get the element type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002214 Type *ValTy = EltTy->getScalarType();
Dan Gohman44118f02009-06-16 00:20:26 +00002215
Chris Lattnerd93afec2009-01-07 07:18:45 +00002216 // Construct an integer with the right value.
2217 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2218 APInt OneVal(EltSize, CI->getZExtValue());
2219 APInt TotalVal(OneVal);
2220 // Set each byte.
2221 for (unsigned i = 0; 8*i < EltSize; ++i) {
2222 TotalVal = TotalVal.shl(8);
2223 TotalVal |= OneVal;
2224 }
Bob Wilson69743022011-01-13 20:59:44 +00002225
Chris Lattnerd93afec2009-01-07 07:18:45 +00002226 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002227 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00002228 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002229 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002230 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002231 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002232 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson69743022011-01-13 20:59:44 +00002233
Chris Lattnerd93afec2009-01-07 07:18:45 +00002234 // If the requested value was a vector constant, create it.
2235 if (EltTy != ValTy) {
2236 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
2237 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Chris Lattner2ca5c862011-02-15 00:14:00 +00002238 StoreVal = ConstantVector::get(Elts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002239 }
2240 }
2241 new StoreInst(StoreVal, EltPtr, MI);
2242 continue;
2243 }
2244 // Otherwise, if we're storing a byte variable, use a memset call for
2245 // this element.
2246 }
Bob Wilson69743022011-01-13 20:59:44 +00002247
Duncan Sands777d2302009-05-09 07:06:46 +00002248 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002249
Chris Lattner61db1f52010-12-26 22:57:41 +00002250 IRBuilder<> Builder(MI);
Bob Wilson69743022011-01-13 20:59:44 +00002251
Chris Lattnerd93afec2009-01-07 07:18:45 +00002252 // Finally, insert the meminst for this element.
Chris Lattner61db1f52010-12-26 22:57:41 +00002253 if (isa<MemSetInst>(MI)) {
2254 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2255 MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002256 } else {
Chris Lattner61db1f52010-12-26 22:57:41 +00002257 assert(isa<MemTransferInst>(MI));
2258 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2259 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson69743022011-01-13 20:59:44 +00002260
Chris Lattner61db1f52010-12-26 22:57:41 +00002261 if (isa<MemCpyInst>(MI))
2262 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2263 else
2264 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002265 }
Chris Lattner372dda82007-03-05 07:52:57 +00002266 }
Bob Wilsonb742def2009-12-18 20:14:40 +00002267 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00002268}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002269
Bob Wilson39fdd692009-12-04 21:57:37 +00002270/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002271/// overwrites the entire allocation. Extract out the pieces of the stored
2272/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002273void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002274 SmallVector<AllocaInst*, 32> &NewElts){
2275 // Extract each element out of the integer according to its structure offset
2276 // and store the element value to the individual alloca.
2277 Value *SrcVal = SI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002278 Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002279 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002280
Chris Lattner70728532011-01-16 05:58:24 +00002281 IRBuilder<> Builder(SI);
2282
Eli Friedman41b33f42009-06-01 09:14:32 +00002283 // Handle tail padding by extending the operand
2284 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002285 SrcVal = Builder.CreateZExt(SrcVal,
2286 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002287
David Greene504c7d82010-01-05 01:27:09 +00002288 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00002289 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002290
2291 // There are two forms here: AI could be an array or struct. Both cases
2292 // have different ways to compute the element offset.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002293 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002294 const StructLayout *Layout = TD->getStructLayout(EltSTy);
Bob Wilson69743022011-01-13 20:59:44 +00002295
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002296 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2297 // Get the number of bits to shift SrcVal to get the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002298 Type *FieldTy = EltSTy->getElementType(i);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002299 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson69743022011-01-13 20:59:44 +00002300
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002301 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00002302 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002303
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002304 Value *EltVal = SrcVal;
2305 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002306 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002307 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002308 }
Bob Wilson69743022011-01-13 20:59:44 +00002309
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002310 // Truncate down to an integer of the right size.
2311 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002312
Chris Lattner583dd602009-01-09 18:18:43 +00002313 // Ignore zero sized fields like {}, they obviously contain no data.
2314 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002315
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002316 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002317 EltVal = Builder.CreateTrunc(EltVal,
2318 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002319 Value *DestField = NewElts[i];
2320 if (EltVal->getType() == FieldTy) {
2321 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00002322 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002323 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002324 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002325 } else {
2326 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002327 DestField = Builder.CreateBitCast(DestField,
2328 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002329 }
2330 new StoreInst(EltVal, DestField, SI);
2331 }
Bob Wilson69743022011-01-13 20:59:44 +00002332
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002333 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002334 ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2335 Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002336 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002337 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2338
2339 uint64_t Shift;
Bob Wilson69743022011-01-13 20:59:44 +00002340
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002341 if (TD->isBigEndian())
2342 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002343 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002344 Shift = 0;
Bob Wilson69743022011-01-13 20:59:44 +00002345
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002346 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00002347 // Ignore zero sized fields like {}, they obviously contain no data.
2348 if (ElementSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002349
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002350 Value *EltVal = SrcVal;
2351 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002352 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002353 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002354 }
Bob Wilson69743022011-01-13 20:59:44 +00002355
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002356 // Truncate down to an integer of the right size.
2357 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002358 EltVal = Builder.CreateTrunc(EltVal,
2359 IntegerType::get(SI->getContext(),
2360 ElementSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002361 Value *DestField = NewElts[i];
2362 if (EltVal->getType() == ArrayEltTy) {
2363 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002364 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00002365 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002366 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002367 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002368 } else {
2369 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002370 DestField = Builder.CreateBitCast(DestField,
2371 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002372 }
2373 new StoreInst(EltVal, DestField, SI);
Bob Wilson69743022011-01-13 20:59:44 +00002374
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002375 if (TD->isBigEndian())
2376 Shift -= ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002377 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002378 Shift += ElementOffset;
2379 }
2380 }
Bob Wilson69743022011-01-13 20:59:44 +00002381
Bob Wilsonb742def2009-12-18 20:14:40 +00002382 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002383}
2384
Bob Wilson39fdd692009-12-04 21:57:37 +00002385/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002386/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002387void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002388 SmallVector<AllocaInst*, 32> &NewElts) {
2389 // Extract each element out of the NewElts according to its structure offset
2390 // and form the result value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002391 Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002392 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002393
David Greene504c7d82010-01-05 01:27:09 +00002394 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00002395 << '\n');
Bob Wilson69743022011-01-13 20:59:44 +00002396
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002397 // There are two forms here: AI could be an array or struct. Both cases
2398 // have different ways to compute the element offset.
2399 const StructLayout *Layout = 0;
2400 uint64_t ArrayEltBitOffset = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002401 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002402 Layout = TD->getStructLayout(EltSTy);
2403 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002404 Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002405 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002406 }
2407
2408 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00002409 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson69743022011-01-13 20:59:44 +00002410
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002411 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2412 // Load the value from the alloca. If the NewElt is an aggregate, cast
2413 // the pointer to an integer of the same size before doing the load.
2414 Value *SrcField = NewElts[i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002415 Type *FieldTy =
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002416 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00002417 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002418
Chris Lattner583dd602009-01-09 18:18:43 +00002419 // Ignore zero sized fields like {}, they obviously contain no data.
2420 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002421
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002422 IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +00002423 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00002424 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2425 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00002426 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00002427 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002428 "", LI);
2429 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2430
2431 // If SrcField is a fp or vector of the right size but that isn't an
2432 // integer type, bitcast to an integer so we can shift it.
2433 if (SrcField->getType() != FieldIntTy)
2434 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2435
2436 // Zero extend the field to be the same size as the final alloca so that
2437 // we can shift and insert it.
2438 if (SrcField->getType() != ResultVal->getType())
2439 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson69743022011-01-13 20:59:44 +00002440
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002441 // Determine the number of bits to shift SrcField.
2442 uint64_t Shift;
2443 if (Layout) // Struct case.
2444 Shift = Layout->getElementOffsetInBits(i);
2445 else // Array case.
2446 Shift = i*ArrayEltBitOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002447
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002448 if (TD->isBigEndian())
2449 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson69743022011-01-13 20:59:44 +00002450
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002451 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002452 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002453 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2454 }
2455
Chris Lattner14952472010-06-27 07:58:26 +00002456 // Don't create an 'or x, 0' on the first iteration.
2457 if (!isa<Constant>(ResultVal) ||
2458 !cast<Constant>(ResultVal)->isNullValue())
2459 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2460 else
2461 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002462 }
Eli Friedman41b33f42009-06-01 09:14:32 +00002463
2464 // Handle tail padding by truncating the result
2465 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2466 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2467
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002468 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00002469 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002470}
2471
Duncan Sands3cb36502007-11-04 14:43:57 +00002472/// HasPadding - Return true if the specified type has any structure or
Bob Wilson694a10e2011-01-13 17:45:08 +00002473/// alignment padding in between the elements that would be split apart
2474/// by SROA; return false otherwise.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002475static bool HasPadding(Type *Ty, const TargetData &TD) {
2476 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Bob Wilson694a10e2011-01-13 17:45:08 +00002477 Ty = ATy->getElementType();
2478 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00002479 }
Bob Wilson694a10e2011-01-13 17:45:08 +00002480
2481 // SROA currently handles only Arrays and Structs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002482 StructType *STy = cast<StructType>(Ty);
Bob Wilson694a10e2011-01-13 17:45:08 +00002483 const StructLayout *SL = TD.getStructLayout(STy);
2484 unsigned PrevFieldBitOffset = 0;
2485 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2486 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2487
2488 // Check to see if there is any padding between this element and the
2489 // previous one.
2490 if (i) {
2491 unsigned PrevFieldEnd =
2492 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2493 if (PrevFieldEnd < FieldBitOffset)
2494 return true;
2495 }
2496 PrevFieldBitOffset = FieldBitOffset;
2497 }
2498 // Check for tail padding.
2499 if (unsigned EltCount = STy->getNumElements()) {
2500 unsigned PrevFieldEnd = PrevFieldBitOffset +
2501 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2502 if (PrevFieldEnd < SL->getSizeInBits())
2503 return true;
2504 }
2505 return false;
Chris Lattner39a1c042007-05-30 06:11:23 +00002506}
Chris Lattner372dda82007-03-05 07:52:57 +00002507
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002508/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2509/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2510/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002511bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00002512 // Loop over the use list of the alloca. We can only transform it if all of
2513 // the users are safe to transform.
Chris Lattner6c95d242011-01-23 07:29:29 +00002514 AllocaInfo Info(AI);
Bob Wilson69743022011-01-13 20:59:44 +00002515
Chris Lattner6c95d242011-01-23 07:29:29 +00002516 isSafeForScalarRepl(AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00002517 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00002518 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002519 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002520 }
Bob Wilson69743022011-01-13 20:59:44 +00002521
Chris Lattner39a1c042007-05-30 06:11:23 +00002522 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2523 // source and destination, we have to be careful. In particular, the memcpy
2524 // could be moving around elements that live in structure padding of the LLVM
2525 // types, but may actually be used. In these cases, we refuse to promote the
2526 // struct.
2527 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00002528 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002529 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00002530
Chris Lattner396a0562011-01-16 17:46:19 +00002531 // If the alloca never has an access to just *part* of it, but is accessed
2532 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner7e9b4272011-01-16 06:18:28 +00002533 // the alloca instead of promoting each piece at a time and inserting fission
2534 // and fusion code.
2535 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2536 // If the struct/array just has one element, use basic SRoA.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002537 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
Chris Lattner7e9b4272011-01-16 06:18:28 +00002538 if (ST->getNumElements() > 1) return false;
2539 } else {
2540 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2541 return false;
2542 }
2543 }
Chris Lattner145c5322011-01-23 08:27:54 +00002544
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002545 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00002546}
Chris Lattnera1888942005-12-12 07:19:13 +00002547
Chris Lattner800de312008-02-29 07:03:13 +00002548
Chris Lattner79b3bd32007-04-25 06:40:51 +00002549
2550/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2551/// some part of a constant global variable. This intentionally only accepts
2552/// constant expressions because we don't can't rewrite arbitrary instructions.
2553static bool PointsToConstantGlobal(Value *V) {
2554 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2555 return GV->isConstant();
2556 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Bob Wilson69743022011-01-13 20:59:44 +00002557 if (CE->getOpcode() == Instruction::BitCast ||
Chris Lattner79b3bd32007-04-25 06:40:51 +00002558 CE->getOpcode() == Instruction::GetElementPtr)
2559 return PointsToConstantGlobal(CE->getOperand(0));
2560 return false;
2561}
2562
2563/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2564/// pointer to an alloca. Ignore any reads of the pointer, return false if we
2565/// see any stores or other unknown uses. If we see pointer arithmetic, keep
2566/// track of whether it moves the pointer (with isOffset) but otherwise traverse
2567/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
Nick Lewycky081f8002010-11-24 22:04:20 +00002568/// the alloca, and if the source pointer is a pointer to a constant global, we
Chris Lattner79b3bd32007-04-25 06:40:51 +00002569/// can optimize this.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002570static bool
2571isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
2572 bool isOffset,
2573 SmallVector<Instruction *, 4> &LifetimeMarkers) {
2574 // We track lifetime intrinsics as we encounter them. If we decide to go
2575 // ahead and replace the value with the global, this lets the caller quickly
2576 // eliminate the markers.
2577
Chris Lattner79b3bd32007-04-25 06:40:51 +00002578 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00002579 User *U = cast<Instruction>(*UI);
2580
Chris Lattner2e618492010-11-18 06:20:47 +00002581 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00002582 // Ignore non-volatile loads, they are always ok.
Chris Lattner2e618492010-11-18 06:20:47 +00002583 if (LI->isVolatile()) return false;
2584 continue;
2585 }
Bob Wilson69743022011-01-13 20:59:44 +00002586
Gabor Greif8a8a4352010-04-06 19:32:30 +00002587 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002588 // If uses of the bitcast are ok, we are ok.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002589 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset,
2590 LifetimeMarkers))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002591 return false;
2592 continue;
2593 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00002594 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002595 // If the GEP has all zero indices, it doesn't offset the pointer. If it
2596 // doesn't, it does.
2597 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002598 isOffset || !GEP->hasAllZeroIndices(),
2599 LifetimeMarkers))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002600 return false;
2601 continue;
2602 }
Bob Wilson69743022011-01-13 20:59:44 +00002603
Chris Lattner62480652010-11-18 06:41:51 +00002604 if (CallSite CS = U) {
Nick Lewycky081f8002010-11-24 22:04:20 +00002605 // If this is the function being called then we treat it like a load and
2606 // ignore it.
2607 if (CS.isCallee(UI))
2608 continue;
Bob Wilson69743022011-01-13 20:59:44 +00002609
Duncan Sands53892102011-05-06 10:30:37 +00002610 // If this is a readonly/readnone call site, then we know it is just a
2611 // load (but one that potentially returns the value itself), so we can
2612 // ignore it if we know that the value isn't captured.
2613 unsigned ArgNo = CS.getArgumentNo(UI);
2614 if (CS.onlyReadsMemory() &&
2615 (CS.getInstruction()->use_empty() ||
2616 CS.paramHasAttr(ArgNo+1, Attribute::NoCapture)))
2617 continue;
2618
Chris Lattner62480652010-11-18 06:41:51 +00002619 // If this is being passed as a byval argument, the caller is making a
2620 // copy, so it is only a read of the alloca.
Chris Lattner62480652010-11-18 06:41:51 +00002621 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
2622 continue;
2623 }
Bob Wilson69743022011-01-13 20:59:44 +00002624
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002625 // Lifetime intrinsics can be handled by the caller.
2626 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
2627 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2628 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2629 assert(II->use_empty() && "Lifetime markers have no result to use!");
2630 LifetimeMarkers.push_back(II);
2631 continue;
2632 }
2633 }
2634
Chris Lattner79b3bd32007-04-25 06:40:51 +00002635 // If this is isn't our memcpy/memmove, reject it as something we can't
2636 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00002637 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2638 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00002639 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002640
Chris Lattner2e618492010-11-18 06:20:47 +00002641 // If the transfer is using the alloca as a source of the transfer, then
Chris Lattner2e29ebd2010-11-18 07:32:33 +00002642 // ignore it since it is a load (unless the transfer is volatile).
Chris Lattner2e618492010-11-18 06:20:47 +00002643 if (UI.getOperandNo() == 1) {
2644 if (MI->isVolatile()) return false;
2645 continue;
2646 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00002647
2648 // If we already have seen a copy, reject the second one.
2649 if (TheCopy) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002650
Chris Lattner79b3bd32007-04-25 06:40:51 +00002651 // If the pointer has been offset from the start of the alloca, we can't
2652 // safely handle this.
2653 if (isOffset) return false;
2654
2655 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00002656 if (UI.getOperandNo() != 0) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002657
Chris Lattner79b3bd32007-04-25 06:40:51 +00002658 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00002659 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002660 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002661
Chris Lattner79b3bd32007-04-25 06:40:51 +00002662 // Otherwise, the transform is safe. Remember the copy instruction.
2663 TheCopy = MI;
2664 }
2665 return true;
2666}
2667
2668/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2669/// modified by a copy from a constant global. If we can prove this, we can
2670/// replace any uses of the alloca with uses of the global directly.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002671MemTransferInst *
2672SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
2673 SmallVector<Instruction*, 4> &ToDelete) {
Chris Lattner31d80102010-04-15 21:59:20 +00002674 MemTransferInst *TheCopy = 0;
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002675 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false, ToDelete))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002676 return TheCopy;
2677 return 0;
2678}