blob: 82364c36e42747bf7fc0ff8a9cfd33efd4aa49b8 [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);
Nick Lewycky5a1cb642011-07-25 23:14:22 +0000148 void RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
149 uint64_t Offset,
150 SmallVector<AllocaInst*, 32> &NewElts);
Bob Wilsonb742def2009-12-18 20:14:40 +0000151 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000152 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000153 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000154 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000155 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000156 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000157 SmallVector<AllocaInst*, 32> &NewElts);
Bob Wilson69743022011-01-13 20:59:44 +0000158
Nick Lewycky9174d5c2011-06-27 05:40:02 +0000159 static MemTransferInst *isOnlyCopiedFromConstantGlobal(
160 AllocaInst *AI, SmallVector<Instruction*, 4> &ToDelete);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000161 };
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000162
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000163 // SROA_DT - SROA that uses DominatorTree.
164 struct SROA_DT : public SROA {
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000165 static char ID;
166 public:
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000167 SROA_DT(int T = -1) : SROA(T, true, ID) {
168 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000169 }
170
171 // getAnalysisUsage - This pass does not require any passes, but we know it
172 // will not alter the CFG, so say so.
173 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
174 AU.addRequired<DominatorTree>();
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000175 AU.setPreservesCFG();
176 }
177 };
178
179 // SROA_SSAUp - SROA that uses SSAUpdater.
180 struct SROA_SSAUp : public SROA {
181 static char ID;
182 public:
183 SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
184 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
185 }
186
187 // getAnalysisUsage - This pass does not require any passes, but we know it
188 // will not alter the CFG, so say so.
189 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
190 AU.setPreservesCFG();
191 }
192 };
193
Chris Lattnered7b41e2003-05-27 15:45:27 +0000194}
195
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000196char SROA_DT::ID = 0;
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000197char SROA_SSAUp::ID = 0;
198
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000199INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
200 "Scalar Replacement of Aggregates (DT)", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000201INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000202INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
203 "Scalar Replacement of Aggregates (DT)", false, false)
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000204
205INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
206 "Scalar Replacement of Aggregates (SSAUp)", false, false)
207INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
208 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000209
Brian Gaeked0fde302003-11-11 22:41:34 +0000210// Public interface to the ScalarReplAggregates pass
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000211FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000212 bool UseDomTree) {
213 if (UseDomTree)
214 return new SROA_DT(Threshold);
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000215 return new SROA_SSAUp(Threshold);
Devang Patelff366852007-07-09 21:19:23 +0000216}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000217
218
Chris Lattner4cc576b2010-04-16 00:24:57 +0000219//===----------------------------------------------------------------------===//
220// Convert To Scalar Optimization.
221//===----------------------------------------------------------------------===//
222
223namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000224/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
225/// optimization, which scans the uses of an alloca and determines if it can
226/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000227class ConvertToScalarInfo {
Cameron Zwarichd4c9c3e2011-03-16 00:13:35 +0000228 /// AllocaSize - The size of the alloca being considered in bytes.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000229 unsigned AllocaSize;
230 const TargetData &TD;
Bob Wilson69743022011-01-13 20:59:44 +0000231
Chris Lattnera0bada72010-04-16 02:32:17 +0000232 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000233 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000234 bool IsNotTrivial;
Bob Wilson69743022011-01-13 20:59:44 +0000235
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000236 /// ScalarKind - Tracks the kind of alloca being considered for promotion,
237 /// computed based on the uses of the alloca rather than the LLVM type system.
238 enum {
239 Unknown,
Cameron Zwarich51797822011-06-13 21:44:40 +0000240
Cameron Zwarich15cd80c2011-06-13 23:39:23 +0000241 // Accesses via GEPs that are consistent with element access of a vector
Cameron Zwarich51797822011-06-13 21:44:40 +0000242 // type. This will not be converted into a vector unless there is a later
243 // access using an actual vector type.
244 ImplicitVector,
245
Cameron Zwarich15cd80c2011-06-13 23:39:23 +0000246 // Accesses via vector operations and GEPs that are consistent with the
247 // layout of a vector type.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000248 Vector,
Cameron Zwarich51797822011-06-13 21:44:40 +0000249
250 // An integer bag-of-bits with bitwise operations for insertion and
251 // extraction. Any combination of types can be converted into this kind
252 // of scalar.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000253 Integer
254 } ScalarKind;
255
Chris Lattnera001b662010-04-16 00:38:19 +0000256 /// VectorTy - This tracks the type that we should promote the vector to if
257 /// it is possible to turn it into a vector. This starts out null, and if it
258 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000259 VectorType *VectorTy;
Bob Wilson69743022011-01-13 20:59:44 +0000260
Cameron Zwarich1bcdb6f2011-03-16 08:13:42 +0000261 /// HadNonMemTransferAccess - True if there is at least one access to the
262 /// alloca that is not a MemTransferInst. We don't want to turn structs into
263 /// large integers unless there is some potential for optimization.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000264 bool HadNonMemTransferAccess;
265
Chris Lattner4cc576b2010-04-16 00:24:57 +0000266public:
267 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000268 : AllocaSize(Size), TD(td), IsNotTrivial(false), ScalarKind(Unknown),
Cameron Zwarich51797822011-06-13 21:44:40 +0000269 VectorTy(0), HadNonMemTransferAccess(false) { }
Bob Wilson69743022011-01-13 20:59:44 +0000270
Chris Lattnera001b662010-04-16 00:38:19 +0000271 AllocaInst *TryConvert(AllocaInst *AI);
Bob Wilson69743022011-01-13 20:59:44 +0000272
Chris Lattner4cc576b2010-04-16 00:24:57 +0000273private:
274 bool CanConvertToScalar(Value *V, uint64_t Offset);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000275 void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
276 bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000277 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Bob Wilson69743022011-01-13 20:59:44 +0000278
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000279 Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000280 uint64_t Offset, IRBuilder<> &Builder);
281 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
282 uint64_t Offset, IRBuilder<> &Builder);
283};
284} // end anonymous namespace.
285
Chris Lattner91abace2010-09-01 05:14:33 +0000286
Chris Lattnera001b662010-04-16 00:38:19 +0000287/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
288/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
289/// alloca if possible or null if not.
290AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
291 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
292 // out.
293 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
294 return 0;
Bob Wilson69743022011-01-13 20:59:44 +0000295
Cameron Zwarich51797822011-06-13 21:44:40 +0000296 // If an alloca has only memset / memcpy uses, it may still have an Unknown
297 // ScalarKind. Treat it as an Integer below.
298 if (ScalarKind == Unknown)
299 ScalarKind = Integer;
300
Cameron Zwarich3ebb05d2011-06-18 06:17:51 +0000301 // FIXME: It should be possible to promote the vector type up to the alloca's
302 // size.
303 if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
304 ScalarKind = Integer;
305
Chris Lattnera001b662010-04-16 00:38:19 +0000306 // If we were able to find a vector type that can handle this with
307 // insert/extract elements, and if there was at least one use that had
308 // a vector type, promote this to a vector. We don't want to promote
309 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
310 // we just get a lot of insert/extracts. If at least one vector is
311 // involved, then we probably really do have a union of vector/array.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000312 Type *NewTy;
Cameron Zwarich5b93d3c2011-06-14 06:33:51 +0000313 if (ScalarKind == Vector) {
314 assert(VectorTy && "Missing type for vector scalar.");
Chris Lattnera001b662010-04-16 00:38:19 +0000315 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
316 << *VectorTy << '\n');
317 NewTy = VectorTy; // Use the vector type.
318 } else {
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000319 unsigned BitWidth = AllocaSize * 8;
Cameron Zwarich51797822011-06-13 21:44:40 +0000320 if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
321 !HadNonMemTransferAccess && !TD.fitsInLegalInteger(BitWidth))
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000322 return 0;
323
Chris Lattnera001b662010-04-16 00:38:19 +0000324 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
325 // Create and insert the integer alloca.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000326 NewTy = IntegerType::get(AI->getContext(), BitWidth);
Chris Lattnera001b662010-04-16 00:38:19 +0000327 }
328 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
329 ConvertUsesToScalar(AI, NewAI, 0);
330 return NewAI;
331}
332
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000333/// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
334/// (VectorTy) so far at the offset specified by Offset (which is specified in
335/// bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000336///
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000337/// There are three cases we handle here:
Chris Lattner4cc576b2010-04-16 00:24:57 +0000338/// 1) A union of vector types of the same size and potentially its elements.
339/// Here we turn element accesses into insert/extract element operations.
340/// This promotes a <4 x float> with a store of float to the third element
341/// into a <4 x float> that uses insert element.
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000342/// 2) A union of vector types with power-of-2 size differences, e.g. a float,
343/// <2 x float> and <4 x float>. Here we turn element accesses into insert
344/// and extract element operations, and <2 x float> accesses into a cast to
345/// <2 x double>, an extract, and a cast back to <2 x float>.
346/// 3) A fully general blob of memory, which we turn into some (potentially
Chris Lattner4cc576b2010-04-16 00:24:57 +0000347/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000348/// and stores would mutate the memory. We mark this by setting VectorTy
349/// to VoidTy.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000350void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000351 uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000352 // If we already decided to turn this into a blob of integer memory, there is
353 // nothing to be done.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000354 if (ScalarKind == Integer)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000355 return;
Bob Wilson69743022011-01-13 20:59:44 +0000356
Chris Lattner4cc576b2010-04-16 00:24:57 +0000357 // If this could be contributing to a vector, analyze it.
358
359 // If the In type is a vector that is the same size as the alloca, see if it
360 // matches the existing VecTy.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000361 if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000362 if (MergeInVectorType(VInTy, Offset))
Chris Lattner4cc576b2010-04-16 00:24:57 +0000363 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000364 } else if (In->isFloatTy() || In->isDoubleTy() ||
365 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
366 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
Cameron Zwarich9827b782011-03-29 05:19:52 +0000367 // Full width accesses can be ignored, because they can always be turned
368 // into bitcasts.
369 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
Cameron Zwarichdd689122011-06-13 21:44:31 +0000370 if (EltSize == AllocaSize)
Cameron Zwarich9827b782011-03-29 05:19:52 +0000371 return;
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000372
Chris Lattner4cc576b2010-04-16 00:24:57 +0000373 // If we're accessing something that could be an element of a vector, see
374 // if the implied vector agrees with what we already have and if Offset is
375 // compatible with it.
Cameron Zwarich96cc1d02011-06-09 01:45:33 +0000376 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Cameron Zwarichc4f78202011-06-09 01:52:44 +0000377 (!VectorTy || Offset * 8 < VectorTy->getPrimitiveSizeInBits())) {
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000378 if (!VectorTy) {
Cameron Zwarich51797822011-06-13 21:44:40 +0000379 ScalarKind = ImplicitVector;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000380 VectorTy = VectorType::get(In, AllocaSize/EltSize);
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000381 return;
382 }
383
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000384 unsigned CurrentEltSize = VectorTy->getElementType()
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000385 ->getPrimitiveSizeInBits()/8;
386 if (EltSize == CurrentEltSize)
387 return;
Cameron Zwarich344731c2011-04-20 21:48:38 +0000388
389 if (In->isIntegerTy() && isPowerOf2_32(AllocaSize / EltSize))
390 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000391 }
392 }
Bob Wilson69743022011-01-13 20:59:44 +0000393
Chris Lattner4cc576b2010-04-16 00:24:57 +0000394 // Otherwise, we have a case that we can't handle with an optimized vector
395 // form. We can still turn this into a large integer.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000396 ScalarKind = Integer;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000397}
398
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000399/// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
400/// returning true if the type was successfully merged and false otherwise.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000401bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000402 uint64_t Offset) {
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000403 // TODO: Support nonzero offsets?
404 if (Offset != 0)
405 return false;
406
407 // Only allow vectors that are a power-of-2 away from the size of the alloca.
408 if (!isPowerOf2_64(AllocaSize / (VInTy->getBitWidth() / 8)))
409 return false;
410
411 // If this the first vector we see, remember the type so that we know the
412 // element size.
413 if (!VectorTy) {
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000414 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000415 VectorTy = VInTy;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000416 return true;
417 }
418
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000419 unsigned BitWidth = VectorTy->getBitWidth();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000420 unsigned InBitWidth = VInTy->getBitWidth();
421
422 // Vectors of the same size can be converted using a simple bitcast.
Cameron Zwarich51797822011-06-13 21:44:40 +0000423 if (InBitWidth == BitWidth && AllocaSize == (InBitWidth / 8)) {
424 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000425 return true;
Cameron Zwarich51797822011-06-13 21:44:40 +0000426 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000427
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000428 Type *ElementTy = VectorTy->getElementType();
429 Type *InElementTy = VInTy->getElementType();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000430
Dan Gohman856e13d2011-07-21 23:30:09 +0000431 // If they're the same alloc size, we'll be attempting to convert between
432 // them with a vector shuffle, which requires the element types to match.
433 if (TD.getTypeAllocSize(VectorTy) == TD.getTypeAllocSize(VInTy) &&
434 ElementTy != InElementTy)
435 return false;
436
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000437 // Do not allow mixed integer and floating-point accesses from vectors of
438 // different sizes.
439 if (ElementTy->isFloatingPointTy() != InElementTy->isFloatingPointTy())
440 return false;
441
442 if (ElementTy->isFloatingPointTy()) {
443 // Only allow floating-point vectors of different sizes if they have the
444 // same element type.
445 // TODO: This could be loosened a bit, but would anything benefit?
446 if (ElementTy != InElementTy)
447 return false;
448
449 // There are no arbitrary-precision floating-point types, which limits the
450 // number of legal vector types with larger element types that we can form
451 // to bitcast and extract a subvector.
452 // TODO: We could support some more cases with mixed fp128 and double here.
453 if (!(BitWidth == 64 || BitWidth == 128) ||
454 !(InBitWidth == 64 || InBitWidth == 128))
455 return false;
456 } else {
457 assert(ElementTy->isIntegerTy() && "Vector elements must be either integer "
458 "or floating-point.");
459 unsigned BitWidth = ElementTy->getPrimitiveSizeInBits();
460 unsigned InBitWidth = InElementTy->getPrimitiveSizeInBits();
461
462 // Do not allow integer types smaller than a byte or types whose widths are
463 // not a multiple of a byte.
464 if (BitWidth < 8 || InBitWidth < 8 ||
465 BitWidth % 8 != 0 || InBitWidth % 8 != 0)
466 return false;
467 }
468
469 // Pick the largest of the two vector types.
Cameron Zwarich51797822011-06-13 21:44:40 +0000470 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000471 if (InBitWidth > BitWidth)
472 VectorTy = VInTy;
473
474 return true;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000475}
476
Chris Lattner4cc576b2010-04-16 00:24:57 +0000477/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
478/// its accesses to a single vector type, return true and set VecTy to
479/// the new type. If we could convert the alloca into a single promotable
480/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
481/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
482/// is the current offset from the base of the alloca being analyzed.
483///
484/// If we see at least one access to the value that is as a vector type, set the
485/// SawVec flag.
486bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
487 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
488 Instruction *User = cast<Instruction>(*UI);
Bob Wilson69743022011-01-13 20:59:44 +0000489
Chris Lattner4cc576b2010-04-16 00:24:57 +0000490 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
491 // Don't break volatile loads.
Eli Friedman2bc3d522011-09-12 20:23:13 +0000492 if (!LI->isSimple())
Chris Lattner4cc576b2010-04-16 00:24:57 +0000493 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000494 // Don't touch MMX operations.
495 if (LI->getType()->isX86_MMXTy())
496 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000497 HadNonMemTransferAccess = true;
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000498 MergeInTypeForLoadOrStore(LI->getType(), Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000499 continue;
500 }
Bob Wilson69743022011-01-13 20:59:44 +0000501
Chris Lattner4cc576b2010-04-16 00:24:57 +0000502 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
503 // Storing the pointer, not into the value?
Eli Friedman2bc3d522011-09-12 20:23:13 +0000504 if (SI->getOperand(0) == V || !SI->isSimple()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000505 // Don't touch MMX operations.
506 if (SI->getOperand(0)->getType()->isX86_MMXTy())
507 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000508 HadNonMemTransferAccess = true;
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000509 MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000510 continue;
511 }
Bob Wilson69743022011-01-13 20:59:44 +0000512
Chris Lattner4cc576b2010-04-16 00:24:57 +0000513 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Nick Lewycky5a1cb642011-07-25 23:14:22 +0000514 if (!onlyUsedByLifetimeMarkers(BCI))
515 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000516 if (!CanConvertToScalar(BCI, Offset))
517 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000518 continue;
519 }
520
521 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
522 // If this is a GEP with a variable indices, we can't handle it.
523 if (!GEP->hasAllConstantIndices())
524 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000525
Chris Lattner4cc576b2010-04-16 00:24:57 +0000526 // Compute the offset that this GEP adds to the pointer.
527 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
528 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
Jay Foad8fbbb392011-07-19 14:01:37 +0000529 Indices);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000530 // See if all uses can be converted.
531 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
532 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000533 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000534 HadNonMemTransferAccess = true;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000535 continue;
536 }
537
538 // If this is a constant sized memset of a constant value (e.g. 0) we can
539 // handle it.
540 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
Cameron Zwarich6be41eb2011-06-18 05:47:49 +0000541 // Store of constant value.
542 if (!isa<ConstantInt>(MSI->getValue()))
Chris Lattnera001b662010-04-16 00:38:19 +0000543 return false;
Cameron Zwarich6be41eb2011-06-18 05:47:49 +0000544
545 // Store of constant size.
546 ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
547 if (!Len)
548 return false;
549
550 // If the size differs from the alloca, we can only convert the alloca to
551 // an integer bag-of-bits.
552 // FIXME: This should handle all of the cases that are currently accepted
553 // as vector element insertions.
554 if (Len->getZExtValue() != AllocaSize || Offset != 0)
555 ScalarKind = Integer;
556
Chris Lattnera001b662010-04-16 00:38:19 +0000557 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000558 HadNonMemTransferAccess = true;
Chris Lattnera001b662010-04-16 00:38:19 +0000559 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000560 }
561
562 // If this is a memcpy or memmove into or out of the whole allocation, we
563 // can handle it like a load or store of the scalar type.
564 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000565 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
566 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
567 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000568
Chris Lattnera001b662010-04-16 00:38:19 +0000569 IsNotTrivial = true; // Can't be mem2reg'd.
570 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000571 }
Bob Wilson69743022011-01-13 20:59:44 +0000572
Nick Lewycky5a1cb642011-07-25 23:14:22 +0000573 // If this is a lifetime intrinsic, we can handle it.
574 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
575 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
576 II->getIntrinsicID() == Intrinsic::lifetime_end) {
577 continue;
578 }
579 }
580
Chris Lattner4cc576b2010-04-16 00:24:57 +0000581 // Otherwise, we cannot handle this!
582 return false;
583 }
Bob Wilson69743022011-01-13 20:59:44 +0000584
Chris Lattner4cc576b2010-04-16 00:24:57 +0000585 return true;
586}
587
588/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
589/// directly. This happens when we are converting an "integer union" to a
590/// single integer scalar, or when we are converting a "vector union" to a
591/// vector with insert/extractelement instructions.
592///
593/// Offset is an offset from the original alloca, in bits that need to be
594/// shifted to the right. By the end of this, there should be no uses of Ptr.
595void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
596 uint64_t Offset) {
597 while (!Ptr->use_empty()) {
598 Instruction *User = cast<Instruction>(Ptr->use_back());
599
600 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
601 ConvertUsesToScalar(CI, NewAI, Offset);
602 CI->eraseFromParent();
603 continue;
604 }
605
606 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
607 // Compute the offset that this GEP adds to the pointer.
608 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
609 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
Jay Foad8fbbb392011-07-19 14:01:37 +0000610 Indices);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000611 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
612 GEP->eraseFromParent();
613 continue;
614 }
Bob Wilson69743022011-01-13 20:59:44 +0000615
Chris Lattner61db1f52010-12-26 22:57:41 +0000616 IRBuilder<> Builder(User);
Bob Wilson69743022011-01-13 20:59:44 +0000617
Chris Lattner4cc576b2010-04-16 00:24:57 +0000618 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
619 // The load is a bit extract from NewAI shifted right by Offset bits.
620 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
621 Value *NewLoadVal
622 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
623 LI->replaceAllUsesWith(NewLoadVal);
624 LI->eraseFromParent();
625 continue;
626 }
Bob Wilson69743022011-01-13 20:59:44 +0000627
Chris Lattner4cc576b2010-04-16 00:24:57 +0000628 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
629 assert(SI->getOperand(0) != Ptr && "Consistency error!");
630 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
631 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
632 Builder);
633 Builder.CreateStore(New, NewAI);
634 SI->eraseFromParent();
Bob Wilson69743022011-01-13 20:59:44 +0000635
Chris Lattner4cc576b2010-04-16 00:24:57 +0000636 // If the load we just inserted is now dead, then the inserted store
637 // overwrote the entire thing.
638 if (Old->use_empty())
639 Old->eraseFromParent();
640 continue;
641 }
Bob Wilson69743022011-01-13 20:59:44 +0000642
Chris Lattner4cc576b2010-04-16 00:24:57 +0000643 // If this is a constant sized memset of a constant value (e.g. 0) we can
644 // transform it into a store of the expanded constant value.
645 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
646 assert(MSI->getRawDest() == Ptr && "Consistency error!");
647 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
648 if (NumBytes != 0) {
649 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson69743022011-01-13 20:59:44 +0000650
Chris Lattner4cc576b2010-04-16 00:24:57 +0000651 // Compute the value replicated the right number of times.
652 APInt APVal(NumBytes*8, Val);
653
654 // Splat the value if non-zero.
655 if (Val)
656 for (unsigned i = 1; i != NumBytes; ++i)
657 APVal |= APVal << 8;
Bob Wilson69743022011-01-13 20:59:44 +0000658
Chris Lattner4cc576b2010-04-16 00:24:57 +0000659 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
660 Value *New = ConvertScalar_InsertValue(
661 ConstantInt::get(User->getContext(), APVal),
662 Old, Offset, Builder);
663 Builder.CreateStore(New, NewAI);
Bob Wilson69743022011-01-13 20:59:44 +0000664
Chris Lattner4cc576b2010-04-16 00:24:57 +0000665 // If the load we just inserted is now dead, then the memset overwrote
666 // the entire thing.
667 if (Old->use_empty())
Bob Wilson69743022011-01-13 20:59:44 +0000668 Old->eraseFromParent();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000669 }
670 MSI->eraseFromParent();
671 continue;
672 }
673
674 // If this is a memcpy or memmove into or out of the whole allocation, we
675 // can handle it like a load or store of the scalar type.
676 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
677 assert(Offset == 0 && "must be store to start of alloca");
Bob Wilson69743022011-01-13 20:59:44 +0000678
Chris Lattner4cc576b2010-04-16 00:24:57 +0000679 // If the source and destination are both to the same alloca, then this is
680 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
681 // as appropriate.
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000682 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
Bob Wilson69743022011-01-13 20:59:44 +0000683
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000684 if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000685 // Dest must be OrigAI, change this to be a load from the original
686 // pointer (bitcasted), then a store to our new alloca.
687 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
688 Value *SrcPtr = MTI->getSource();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000689 PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
690 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
Mon P Wange90a6332010-12-23 01:41:32 +0000691 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
692 AIPTy = PointerType::get(AIPTy->getElementType(),
693 SPTy->getAddressSpace());
694 }
695 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
696
Chris Lattner4cc576b2010-04-16 00:24:57 +0000697 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
698 SrcVal->setAlignment(MTI->getAlignment());
699 Builder.CreateStore(SrcVal, NewAI);
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000700 } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000701 // Src must be OrigAI, change this to be a load from NewAI then a store
702 // through the original dest pointer (bitcasted).
703 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
704 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
705
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000706 PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
707 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
Mon P Wange90a6332010-12-23 01:41:32 +0000708 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
709 AIPTy = PointerType::get(AIPTy->getElementType(),
710 DPTy->getAddressSpace());
711 }
712 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
713
Chris Lattner4cc576b2010-04-16 00:24:57 +0000714 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
715 NewStore->setAlignment(MTI->getAlignment());
716 } else {
717 // Noop transfer. Src == Dst
718 }
719
720 MTI->eraseFromParent();
721 continue;
722 }
Bob Wilson69743022011-01-13 20:59:44 +0000723
Nick Lewycky5a1cb642011-07-25 23:14:22 +0000724 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
725 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
726 II->getIntrinsicID() == Intrinsic::lifetime_end) {
727 // There's no need to preserve these, as the resulting alloca will be
728 // converted to a register anyways.
729 II->eraseFromParent();
730 continue;
731 }
732 }
733
Chris Lattner4cc576b2010-04-16 00:24:57 +0000734 llvm_unreachable("Unsupported operation!");
735 }
736}
737
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000738/// getScaledElementType - Gets a scaled element type for a partial vector
Cameron Zwarich344731c2011-04-20 21:48:38 +0000739/// access of an alloca. The input types must be integer or floating-point
740/// scalar or vector types, and the resulting type is an integer, float or
741/// double.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000742static Type *getScaledElementType(Type *Ty1, Type *Ty2,
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000743 unsigned NewBitWidth) {
Cameron Zwarich344731c2011-04-20 21:48:38 +0000744 bool IsFP1 = Ty1->isFloatingPointTy() ||
745 (Ty1->isVectorTy() &&
746 cast<VectorType>(Ty1)->getElementType()->isFloatingPointTy());
747 bool IsFP2 = Ty2->isFloatingPointTy() ||
748 (Ty2->isVectorTy() &&
749 cast<VectorType>(Ty2)->getElementType()->isFloatingPointTy());
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000750
Cameron Zwarich344731c2011-04-20 21:48:38 +0000751 LLVMContext &Context = Ty1->getContext();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000752
Cameron Zwarich344731c2011-04-20 21:48:38 +0000753 // Prefer floating-point types over integer types, as integer types may have
754 // been created by earlier scalar replacement.
755 if (IsFP1 || IsFP2) {
756 if (NewBitWidth == 32)
757 return Type::getFloatTy(Context);
758 if (NewBitWidth == 64)
759 return Type::getDoubleTy(Context);
760 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000761
Cameron Zwarich344731c2011-04-20 21:48:38 +0000762 return Type::getIntNTy(Context, NewBitWidth);
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000763}
764
Mon P Wangddf9abf2011-04-14 08:04:01 +0000765/// CreateShuffleVectorCast - Creates a shuffle vector to convert one vector
766/// to another vector of the same element type which has the same allocation
767/// size but different primitive sizes (e.g. <3 x i32> and <4 x i32>).
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000768static Value *CreateShuffleVectorCast(Value *FromVal, Type *ToType,
Mon P Wangddf9abf2011-04-14 08:04:01 +0000769 IRBuilder<> &Builder) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000770 Type *FromType = FromVal->getType();
771 VectorType *FromVTy = cast<VectorType>(FromType);
772 VectorType *ToVTy = cast<VectorType>(ToType);
Mon P Wang481823a2011-04-14 19:20:42 +0000773 assert((ToVTy->getElementType() == FromVTy->getElementType()) &&
Mon P Wangddf9abf2011-04-14 08:04:01 +0000774 "Vectors must have the same element type");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000775 Value *UnV = UndefValue::get(FromType);
776 unsigned numEltsFrom = FromVTy->getNumElements();
777 unsigned numEltsTo = ToVTy->getNumElements();
778
779 SmallVector<Constant*, 3> Args;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000780 Type* Int32Ty = Builder.getInt32Ty();
Mon P Wangddf9abf2011-04-14 08:04:01 +0000781 unsigned minNumElts = std::min(numEltsFrom, numEltsTo);
782 unsigned i;
783 for (i=0; i != minNumElts; ++i)
Mon P Wang481823a2011-04-14 19:20:42 +0000784 Args.push_back(ConstantInt::get(Int32Ty, i));
Mon P Wangddf9abf2011-04-14 08:04:01 +0000785
786 if (i < numEltsTo) {
Mon P Wang481823a2011-04-14 19:20:42 +0000787 Constant* UnC = UndefValue::get(Int32Ty);
Mon P Wangddf9abf2011-04-14 08:04:01 +0000788 for (; i != numEltsTo; ++i)
789 Args.push_back(UnC);
790 }
791 Constant *Mask = ConstantVector::get(Args);
792 return Builder.CreateShuffleVector(FromVal, UnV, Mask, "tmpV");
793}
794
Chris Lattner4cc576b2010-04-16 00:24:57 +0000795/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
796/// or vector value FromVal, extracting the bits from the offset specified by
797/// Offset. This returns the value, which is of type ToType.
798///
799/// This happens when we are converting an "integer union" to a single
800/// integer scalar, or when we are converting a "vector union" to a vector with
801/// insert/extractelement instructions.
802///
803/// Offset is an offset from the original alloca, in bits that need to be
804/// shifted to the right.
805Value *ConvertToScalarInfo::
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000806ConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000807 uint64_t Offset, IRBuilder<> &Builder) {
808 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000809 Type *FromType = FromVal->getType();
Mon P Wangbe0761c2011-04-13 21:40:02 +0000810 if (FromType == ToType && Offset == 0)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000811 return FromVal;
812
813 // If the result alloca is a vector type, this is either an element
814 // access or a bitcast to another vector type of the same size.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000815 if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
Cameron Zwarich0398d612011-06-08 22:08:31 +0000816 unsigned FromTypeSize = TD.getTypeAllocSize(FromType);
Cameron Zwarich9827b782011-03-29 05:19:52 +0000817 unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
Cameron Zwarich0398d612011-06-08 22:08:31 +0000818 if (FromTypeSize == ToTypeSize) {
Mon P Wangddf9abf2011-04-14 08:04:01 +0000819 // If the two types have the same primitive size, use a bit cast.
820 // Otherwise, it is two vectors with the same element type that has
821 // the same allocation size but different number of elements so use
822 // a shuffle vector.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000823 if (FromType->getPrimitiveSizeInBits() ==
824 ToType->getPrimitiveSizeInBits())
825 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000826 else
827 return CreateShuffleVectorCast(FromVal, ToType, Builder);
Mon P Wangbe0761c2011-04-13 21:40:02 +0000828 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000829
Cameron Zwarich0398d612011-06-08 22:08:31 +0000830 if (isPowerOf2_64(FromTypeSize / ToTypeSize)) {
Cameron Zwarich344731c2011-04-20 21:48:38 +0000831 assert(!(ToType->isVectorTy() && Offset != 0) && "Can't extract a value "
832 "of a smaller vector type at a nonzero offset.");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000833
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000834 Type *CastElementTy = getScaledElementType(FromType, ToType,
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000835 ToTypeSize * 8);
Cameron Zwarich0398d612011-06-08 22:08:31 +0000836 unsigned NumCastVectorElements = FromTypeSize / ToTypeSize;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000837
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000838 LLVMContext &Context = FromVal->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000839 Type *CastTy = VectorType::get(CastElementTy,
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000840 NumCastVectorElements);
841 Value *Cast = Builder.CreateBitCast(FromVal, CastTy, "tmp");
Cameron Zwarich344731c2011-04-20 21:48:38 +0000842
843 unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
844 unsigned Elt = Offset/EltSize;
845 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000846 Value *Extract = Builder.CreateExtractElement(Cast, ConstantInt::get(
Cameron Zwarich344731c2011-04-20 21:48:38 +0000847 Type::getInt32Ty(Context), Elt), "tmp");
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000848 return Builder.CreateBitCast(Extract, ToType, "tmp");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000849 }
Chris Lattner4cc576b2010-04-16 00:24:57 +0000850
851 // Otherwise it must be an element access.
852 unsigned Elt = 0;
853 if (Offset) {
854 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
855 Elt = Offset/EltSize;
856 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
857 }
858 // Return the element extracted out of it.
859 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
860 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
861 if (V->getType() != ToType)
862 V = Builder.CreateBitCast(V, ToType, "tmp");
863 return V;
864 }
Bob Wilson69743022011-01-13 20:59:44 +0000865
Chris Lattner4cc576b2010-04-16 00:24:57 +0000866 // If ToType is a first class aggregate, extract out each of the pieces and
867 // use insertvalue's to form the FCA.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000868 if (StructType *ST = dyn_cast<StructType>(ToType)) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000869 const StructLayout &Layout = *TD.getStructLayout(ST);
870 Value *Res = UndefValue::get(ST);
871 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
872 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
873 Offset+Layout.getElementOffsetInBits(i),
874 Builder);
875 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
876 }
877 return Res;
878 }
Bob Wilson69743022011-01-13 20:59:44 +0000879
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000880 if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000881 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
882 Value *Res = UndefValue::get(AT);
883 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
884 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
885 Offset+i*EltSize, Builder);
886 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
887 }
888 return Res;
889 }
890
891 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000892 IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Chris Lattner4cc576b2010-04-16 00:24:57 +0000893
894 // If this is a big-endian system and the load is narrower than the
895 // full alloca type, we need to do a shift to get the right bits.
896 int ShAmt = 0;
897 if (TD.isBigEndian()) {
898 // On big-endian machines, the lowest bit is stored at the bit offset
899 // from the pointer given by getTypeStoreSizeInBits. This matters for
900 // integers with a bitwidth that is not a multiple of 8.
901 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
902 TD.getTypeStoreSizeInBits(ToType) - Offset;
903 } else {
904 ShAmt = Offset;
905 }
906
907 // Note: we support negative bitwidths (with shl) which are not defined.
908 // We do this to support (f.e.) loads off the end of a structure where
909 // only some bits are used.
910 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
911 FromVal = Builder.CreateLShr(FromVal,
912 ConstantInt::get(FromVal->getType(),
913 ShAmt), "tmp");
914 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson69743022011-01-13 20:59:44 +0000915 FromVal = Builder.CreateShl(FromVal,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000916 ConstantInt::get(FromVal->getType(),
917 -ShAmt), "tmp");
918
919 // Finally, unconditionally truncate the integer to the right width.
920 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
921 if (LIBitWidth < NTy->getBitWidth())
922 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000923 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000924 LIBitWidth), "tmp");
925 else if (LIBitWidth > NTy->getBitWidth())
926 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000927 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000928 LIBitWidth), "tmp");
929
930 // If the result is an integer, this is a trunc or bitcast.
931 if (ToType->isIntegerTy()) {
932 // Should be done.
933 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
934 // Just do a bitcast, we know the sizes match up.
935 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
936 } else {
937 // Otherwise must be a pointer.
938 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
939 }
940 assert(FromVal->getType() == ToType && "Didn't convert right?");
941 return FromVal;
942}
943
944/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
945/// or vector value "Old" at the offset specified by Offset.
946///
947/// This happens when we are converting an "integer union" to a
948/// single integer scalar, or when we are converting a "vector union" to a
949/// vector with insert/extractelement instructions.
950///
951/// Offset is an offset from the original alloca, in bits that need to be
952/// shifted to the right.
953Value *ConvertToScalarInfo::
954ConvertScalar_InsertValue(Value *SV, Value *Old,
955 uint64_t Offset, IRBuilder<> &Builder) {
956 // Convert the stored type to the actual type, shift it left to insert
957 // then 'or' into place.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000958 Type *AllocaType = Old->getType();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000959 LLVMContext &Context = Old->getContext();
960
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000961 if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000962 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
963 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
Bob Wilson69743022011-01-13 20:59:44 +0000964
Chris Lattner4cc576b2010-04-16 00:24:57 +0000965 // Changing the whole vector with memset or with an access of a different
966 // vector type?
Mon P Wangbe0761c2011-04-13 21:40:02 +0000967 if (ValSize == VecSize) {
Mon P Wangddf9abf2011-04-14 08:04:01 +0000968 // If the two types have the same primitive size, use a bit cast.
969 // Otherwise, it is two vectors with the same element type that has
970 // the same allocation size but different number of elements so use
971 // a shuffle vector.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000972 if (VTy->getPrimitiveSizeInBits() ==
973 SV->getType()->getPrimitiveSizeInBits())
974 return Builder.CreateBitCast(SV, AllocaType, "tmp");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000975 else
976 return CreateShuffleVectorCast(SV, VTy, Builder);
Mon P Wangbe0761c2011-04-13 21:40:02 +0000977 }
Chris Lattner4cc576b2010-04-16 00:24:57 +0000978
Cameron Zwarich344731c2011-04-20 21:48:38 +0000979 if (isPowerOf2_64(VecSize / ValSize)) {
980 assert(!(SV->getType()->isVectorTy() && Offset != 0) && "Can't insert a "
981 "value of a smaller vector type at a nonzero offset.");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000982
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000983 Type *CastElementTy = getScaledElementType(VTy, SV->getType(),
Cameron Zwarich344731c2011-04-20 21:48:38 +0000984 ValSize);
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000985 unsigned NumCastVectorElements = VecSize / ValSize;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000986
987 LLVMContext &Context = SV->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000988 Type *OldCastTy = VectorType::get(CastElementTy,
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000989 NumCastVectorElements);
990 Value *OldCast = Builder.CreateBitCast(Old, OldCastTy, "tmp");
991
992 Value *SVCast = Builder.CreateBitCast(SV, CastElementTy, "tmp");
Cameron Zwarich344731c2011-04-20 21:48:38 +0000993
994 unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
995 unsigned Elt = Offset/EltSize;
996 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000997 Value *Insert =
998 Builder.CreateInsertElement(OldCast, SVCast, ConstantInt::get(
Cameron Zwarich344731c2011-04-20 21:48:38 +0000999 Type::getInt32Ty(Context), Elt), "tmp");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +00001000 return Builder.CreateBitCast(Insert, AllocaType, "tmp");
1001 }
1002
Chris Lattner4cc576b2010-04-16 00:24:57 +00001003 // Must be an element insertion.
Cameron Zwarichc5c43b92011-04-20 21:48:34 +00001004 assert(SV->getType() == VTy->getElementType());
1005 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner4cc576b2010-04-16 00:24:57 +00001006 unsigned Elt = Offset/EltSize;
Cameron Zwarichc5c43b92011-04-20 21:48:34 +00001007 return Builder.CreateInsertElement(Old, SV,
Chris Lattner4cc576b2010-04-16 00:24:57 +00001008 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
1009 "tmp");
Chris Lattner4cc576b2010-04-16 00:24:57 +00001010 }
Bob Wilson69743022011-01-13 20:59:44 +00001011
Chris Lattner4cc576b2010-04-16 00:24:57 +00001012 // If SV is a first-class aggregate value, insert each value recursively.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001013 if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
Chris Lattner4cc576b2010-04-16 00:24:57 +00001014 const StructLayout &Layout = *TD.getStructLayout(ST);
1015 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1016 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Bob Wilson69743022011-01-13 20:59:44 +00001017 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner4cc576b2010-04-16 00:24:57 +00001018 Offset+Layout.getElementOffsetInBits(i),
1019 Builder);
1020 }
1021 return Old;
1022 }
Bob Wilson69743022011-01-13 20:59:44 +00001023
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001024 if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Chris Lattner4cc576b2010-04-16 00:24:57 +00001025 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
1026 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1027 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1028 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
1029 }
1030 return Old;
1031 }
1032
1033 // If SV is a float, convert it to the appropriate integer type.
1034 // If it is a pointer, do the same.
1035 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
1036 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
1037 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
1038 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
1039 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
1040 SV = Builder.CreateBitCast(SV,
1041 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
1042 else if (SV->getType()->isPointerTy())
1043 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
1044
1045 // Zero extend or truncate the value if needed.
1046 if (SV->getType() != AllocaType) {
1047 if (SV->getType()->getPrimitiveSizeInBits() <
1048 AllocaType->getPrimitiveSizeInBits())
1049 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
1050 else {
1051 // Truncation may be needed if storing more than the alloca can hold
1052 // (undefined behavior).
1053 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
1054 SrcWidth = DestWidth;
1055 SrcStoreWidth = DestStoreWidth;
1056 }
1057 }
1058
1059 // If this is a big-endian system and the store is narrower than the
1060 // full alloca type, we need to do a shift to get the right bits.
1061 int ShAmt = 0;
1062 if (TD.isBigEndian()) {
1063 // On big-endian machines, the lowest bit is stored at the bit offset
1064 // from the pointer given by getTypeStoreSizeInBits. This matters for
1065 // integers with a bitwidth that is not a multiple of 8.
1066 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1067 } else {
1068 ShAmt = Offset;
1069 }
1070
1071 // Note: we support negative bitwidths (with shr) which are not defined.
1072 // We do this to support (f.e.) stores off the end of a structure where
1073 // only some bits in the structure are set.
1074 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1075 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1076 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
1077 ShAmt), "tmp");
1078 Mask <<= ShAmt;
1079 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1080 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
1081 -ShAmt), "tmp");
1082 Mask = Mask.lshr(-ShAmt);
1083 }
1084
1085 // Mask out the bits we are about to insert from the old value, and or
1086 // in the new bits.
1087 if (SrcWidth != DestWidth) {
1088 assert(DestWidth > SrcWidth);
1089 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1090 SV = Builder.CreateOr(Old, SV, "ins");
1091 }
1092 return SV;
1093}
1094
1095
1096//===----------------------------------------------------------------------===//
1097// SRoA Driver
1098//===----------------------------------------------------------------------===//
1099
1100
Chris Lattnered7b41e2003-05-27 15:45:27 +00001101bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +00001102 TD = getAnalysisIfAvailable<TargetData>();
1103
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001104 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +00001105
1106 // FIXME: ScalarRepl currently depends on TargetData more than it
1107 // theoretically needs to. It should be refactored in order to support
1108 // target-independent IR. Until this is done, just skip the actual
1109 // scalar-replacement portion of this pass.
1110 if (!TD) return Changed;
1111
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001112 while (1) {
1113 bool LocalChange = performScalarRepl(F);
1114 if (!LocalChange) break; // No need to repromote if no scalarrepl
1115 Changed = true;
1116 LocalChange = performPromotion(F);
1117 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
1118 }
Chris Lattner38aec322003-09-11 16:45:55 +00001119
1120 return Changed;
1121}
1122
Chris Lattnerd0f56132011-01-14 19:50:47 +00001123namespace {
1124class AllocaPromoter : public LoadAndStorePromoter {
1125 AllocaInst *AI;
Devang Patel231a5ab2011-07-06 21:09:55 +00001126 DIBuilder *DIB;
Devang Patel4fd3c592011-07-06 22:06:11 +00001127 SmallVector<DbgDeclareInst *, 4> DDIs;
1128 SmallVector<DbgValueInst *, 4> DVIs;
Chris Lattnerd0f56132011-01-14 19:50:47 +00001129public:
Cameron Zwarichc8279392011-05-24 03:10:43 +00001130 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
Devang Patel231a5ab2011-07-06 21:09:55 +00001131 DIBuilder *DB)
Devang Patel4fd3c592011-07-06 22:06:11 +00001132 : LoadAndStorePromoter(Insts, S), AI(0), DIB(DB) {}
Chris Lattnerd0f56132011-01-14 19:50:47 +00001133
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001134 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerd0f56132011-01-14 19:50:47 +00001135 // Remember which alloca we're promoting (for isInstInList).
1136 this->AI = AI;
Devang Patel4fd3c592011-07-06 22:06:11 +00001137 if (MDNode *DebugNode = MDNode::getIfExists(AI->getContext(), AI))
1138 for (Value::use_iterator UI = DebugNode->use_begin(),
1139 E = DebugNode->use_end(); UI != E; ++UI)
1140 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1141 DDIs.push_back(DDI);
1142 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1143 DVIs.push_back(DVI);
1144
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001145 LoadAndStorePromoter::run(Insts);
Chris Lattnerd0f56132011-01-14 19:50:47 +00001146 AI->eraseFromParent();
Devang Patel4fd3c592011-07-06 22:06:11 +00001147 for (SmallVector<DbgDeclareInst *, 4>::iterator I = DDIs.begin(),
1148 E = DDIs.end(); I != E; ++I) {
1149 DbgDeclareInst *DDI = *I;
Devang Patel231a5ab2011-07-06 21:09:55 +00001150 DDI->eraseFromParent();
Devang Patel4fd3c592011-07-06 22:06:11 +00001151 }
1152 for (SmallVector<DbgValueInst *, 4>::iterator I = DVIs.begin(),
1153 E = DVIs.end(); I != E; ++I) {
1154 DbgValueInst *DVI = *I;
1155 DVI->eraseFromParent();
1156 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001157 }
1158
Chris Lattnerd0f56132011-01-14 19:50:47 +00001159 virtual bool isInstInList(Instruction *I,
1160 const SmallVectorImpl<Instruction*> &Insts) const {
1161 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1162 return LI->getOperand(0) == AI;
1163 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001164 }
Devang Patel231a5ab2011-07-06 21:09:55 +00001165
Devang Patel4fd3c592011-07-06 22:06:11 +00001166 virtual void updateDebugInfo(Instruction *Inst) const {
1167 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1168 E = DDIs.end(); I != E; ++I) {
1169 DbgDeclareInst *DDI = *I;
1170 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1171 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
1172 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1173 ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
1174 }
1175 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1176 E = DVIs.end(); I != E; ++I) {
1177 DbgValueInst *DVI = *I;
1178 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1179 Instruction *DbgVal = NULL;
1180 // If an argument is zero extended then use argument directly. The ZExt
1181 // may be zapped by an optimization pass in future.
1182 Argument *ExtendedArg = NULL;
1183 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1184 ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
1185 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1186 ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
1187 if (ExtendedArg)
1188 DbgVal = DIB->insertDbgValueIntrinsic(ExtendedArg, 0,
1189 DIVariable(DVI->getVariable()),
1190 SI);
1191 else
1192 DbgVal = DIB->insertDbgValueIntrinsic(SI->getOperand(0), 0,
1193 DIVariable(DVI->getVariable()),
1194 SI);
Devang Patela4acb002011-07-07 00:05:58 +00001195 DbgVal->setDebugLoc(DVI->getDebugLoc());
Devang Patel4fd3c592011-07-06 22:06:11 +00001196 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1197 Instruction *DbgVal =
1198 DIB->insertDbgValueIntrinsic(LI->getOperand(0), 0,
1199 DIVariable(DVI->getVariable()), LI);
Devang Patela4acb002011-07-07 00:05:58 +00001200 DbgVal->setDebugLoc(DVI->getDebugLoc());
Devang Patel4fd3c592011-07-06 22:06:11 +00001201 }
1202 }
Devang Patel231a5ab2011-07-06 21:09:55 +00001203 }
Chris Lattnerd0f56132011-01-14 19:50:47 +00001204};
1205} // end anon namespace
Chris Lattner38aec322003-09-11 16:45:55 +00001206
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001207/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1208/// subsequently loaded can be rewritten to load both input pointers and then
1209/// select between the result, allowing the load of the alloca to be promoted.
1210/// From this:
1211/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1212/// %V = load i32* %P2
1213/// to:
1214/// %V1 = load i32* %Alloca -> will be mem2reg'd
1215/// %V2 = load i32* %Other
Chris Lattnere3357862011-01-24 01:07:11 +00001216/// %V = select i1 %cond, i32 %V1, i32 %V2
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001217///
1218/// We can do this to a select if its only uses are loads and if the operand to
1219/// the select can be loaded unconditionally.
1220static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
1221 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1222 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1223
1224 for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1225 UI != UE; ++UI) {
1226 LoadInst *LI = dyn_cast<LoadInst>(*UI);
Eli Friedman2bc3d522011-09-12 20:23:13 +00001227 if (LI == 0 || !LI->isSimple()) return false;
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001228
Chris Lattnere3357862011-01-24 01:07:11 +00001229 // Both operands to the select need to be dereferencable, either absolutely
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001230 // (e.g. allocas) or at this point because we can see other accesses to it.
1231 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1232 LI->getAlignment(), TD))
1233 return false;
1234 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1235 LI->getAlignment(), TD))
1236 return false;
1237 }
1238
1239 return true;
1240}
1241
Chris Lattnere3357862011-01-24 01:07:11 +00001242/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1243/// subsequently loaded can be rewritten to load both input pointers in the pred
1244/// blocks and then PHI the results, allowing the load of the alloca to be
1245/// promoted.
1246/// From this:
1247/// %P2 = phi [i32* %Alloca, i32* %Other]
1248/// %V = load i32* %P2
1249/// to:
1250/// %V1 = load i32* %Alloca -> will be mem2reg'd
1251/// ...
1252/// %V2 = load i32* %Other
1253/// ...
1254/// %V = phi [i32 %V1, i32 %V2]
1255///
1256/// We can do this to a select if its only uses are loads and if the operand to
1257/// the select can be loaded unconditionally.
1258static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
1259 // For now, we can only do this promotion if the load is in the same block as
1260 // the PHI, and if there are no stores between the phi and load.
1261 // TODO: Allow recursive phi users.
1262 // TODO: Allow stores.
1263 BasicBlock *BB = PN->getParent();
1264 unsigned MaxAlign = 0;
1265 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1266 UI != UE; ++UI) {
1267 LoadInst *LI = dyn_cast<LoadInst>(*UI);
Eli Friedman2bc3d522011-09-12 20:23:13 +00001268 if (LI == 0 || !LI->isSimple()) return false;
Chris Lattnere3357862011-01-24 01:07:11 +00001269
1270 // For now we only allow loads in the same block as the PHI. This is a
1271 // common case that happens when instcombine merges two loads through a PHI.
1272 if (LI->getParent() != BB) return false;
1273
1274 // Ensure that there are no instructions between the PHI and the load that
1275 // could store.
1276 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1277 if (BBI->mayWriteToMemory())
1278 return false;
1279
1280 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1281 }
1282
1283 // Okay, we know that we have one or more loads in the same block as the PHI.
1284 // We can transform this if it is safe to push the loads into the predecessor
1285 // blocks. The only thing to watch out for is that we can't put a possibly
1286 // trapping load in the predecessor if it is a critical edge.
1287 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1288 BasicBlock *Pred = PN->getIncomingBlock(i);
Eli Friedmand102a032011-09-22 18:56:30 +00001289 Value *InVal = PN->getIncomingValue(i);
1290
1291 // If the terminator of the predecessor has side-effects (an invoke),
1292 // there is no safe place to put a load in the predecessor.
1293 if (Pred->getTerminator()->mayHaveSideEffects())
1294 return false;
1295
1296 // If the value is produced by the terminator of the predecessor
1297 // (an invoke), there is no valid place to put a load in the predecessor.
1298 if (Pred->getTerminator() == InVal)
1299 return false;
Chris Lattnere3357862011-01-24 01:07:11 +00001300
1301 // If the predecessor has a single successor, then the edge isn't critical.
1302 if (Pred->getTerminator()->getNumSuccessors() == 1)
1303 continue;
Chris Lattnere3357862011-01-24 01:07:11 +00001304
1305 // If this pointer is always safe to load, or if we can prove that there is
1306 // already a load in the block, then we can move the load to the pred block.
1307 if (InVal->isDereferenceablePointer() ||
1308 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1309 continue;
1310
1311 return false;
1312 }
1313
1314 return true;
1315}
1316
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001317
1318/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1319/// direct (non-volatile) loads and stores to it. If the alloca is close but
1320/// not quite there, this will transform the code to allow promotion. As such,
1321/// it is a non-pure predicate.
1322static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
1323 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1324 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1325
1326 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1327 UI != UE; ++UI) {
1328 User *U = *UI;
1329 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Eli Friedman2bc3d522011-09-12 20:23:13 +00001330 if (!LI->isSimple())
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001331 return false;
1332 continue;
1333 }
1334
1335 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Eli Friedman2bc3d522011-09-12 20:23:13 +00001336 if (SI->getOperand(0) == AI || !SI->isSimple())
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001337 return false; // Don't allow a store OF the AI, only INTO the AI.
1338 continue;
1339 }
1340
1341 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1342 // If the condition being selected on is a constant, fold the select, yes
1343 // this does (rarely) happen early on.
1344 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1345 Value *Result = SI->getOperand(1+CI->isZero());
1346 SI->replaceAllUsesWith(Result);
1347 SI->eraseFromParent();
1348
1349 // This is very rare and we just scrambled the use list of AI, start
1350 // over completely.
1351 return tryToMakeAllocaBePromotable(AI, TD);
1352 }
1353
1354 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1355 // loads, then we can transform this by rewriting the select.
1356 if (!isSafeSelectToSpeculate(SI, TD))
1357 return false;
1358
1359 InstsToRewrite.insert(SI);
1360 continue;
1361 }
1362
Chris Lattnere3357862011-01-24 01:07:11 +00001363 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1364 if (PN->use_empty()) { // Dead PHIs can be stripped.
1365 InstsToRewrite.insert(PN);
1366 continue;
1367 }
1368
1369 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1370 // in the pred blocks, then we can transform this by rewriting the PHI.
1371 if (!isSafePHIToSpeculate(PN, TD))
1372 return false;
1373
1374 InstsToRewrite.insert(PN);
1375 continue;
1376 }
1377
Nick Lewycky5a1cb642011-07-25 23:14:22 +00001378 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1379 if (onlyUsedByLifetimeMarkers(BCI)) {
1380 InstsToRewrite.insert(BCI);
1381 continue;
1382 }
1383 }
1384
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001385 return false;
1386 }
1387
1388 // If there are no instructions to rewrite, then all uses are load/stores and
1389 // we're done!
1390 if (InstsToRewrite.empty())
1391 return true;
1392
1393 // If we have instructions that need to be rewritten for this to be promotable
1394 // take care of it now.
1395 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
Nick Lewycky5a1cb642011-07-25 23:14:22 +00001396 if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
1397 // This could only be a bitcast used by nothing but lifetime intrinsics.
1398 for (BitCastInst::use_iterator I = BCI->use_begin(), E = BCI->use_end();
1399 I != E;) {
1400 Use &U = I.getUse();
1401 ++I;
1402 cast<Instruction>(U.getUser())->eraseFromParent();
1403 }
1404 BCI->eraseFromParent();
1405 continue;
1406 }
1407
Chris Lattnere3357862011-01-24 01:07:11 +00001408 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1409 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1410 // loads with a new select.
1411 while (!SI->use_empty()) {
1412 LoadInst *LI = cast<LoadInst>(SI->use_back());
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001413
Chris Lattnere3357862011-01-24 01:07:11 +00001414 IRBuilder<> Builder(LI);
1415 LoadInst *TrueLoad =
1416 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1417 LoadInst *FalseLoad =
Nick Lewycky394d1f12011-07-01 06:27:03 +00001418 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
Chris Lattnere3357862011-01-24 01:07:11 +00001419
1420 // Transfer alignment and TBAA info if present.
1421 TrueLoad->setAlignment(LI->getAlignment());
1422 FalseLoad->setAlignment(LI->getAlignment());
1423 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1424 TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1425 FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1426 }
1427
1428 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1429 V->takeName(LI);
1430 LI->replaceAllUsesWith(V);
1431 LI->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001432 }
Chris Lattnere3357862011-01-24 01:07:11 +00001433
1434 // Now that all the loads are gone, the select is gone too.
1435 SI->eraseFromParent();
1436 continue;
1437 }
1438
1439 // Otherwise, we have a PHI node which allows us to push the loads into the
1440 // predecessors.
1441 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1442 if (PN->use_empty()) {
1443 PN->eraseFromParent();
1444 continue;
1445 }
1446
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001447 Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
Jay Foad3ecfc862011-03-30 11:28:46 +00001448 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1449 PN->getName()+".ld", PN);
Chris Lattnere3357862011-01-24 01:07:11 +00001450
1451 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1452 // matter which one we get and if any differ, it doesn't matter.
1453 LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1454 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1455 unsigned Align = SomeLoad->getAlignment();
1456
1457 // Rewrite all loads of the PN to use the new PHI.
1458 while (!PN->use_empty()) {
1459 LoadInst *LI = cast<LoadInst>(PN->use_back());
1460 LI->replaceAllUsesWith(NewPN);
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001461 LI->eraseFromParent();
1462 }
1463
Chris Lattnere3357862011-01-24 01:07:11 +00001464 // Inject loads into all of the pred blocks. Keep track of which blocks we
1465 // insert them into in case we have multiple edges from the same block.
1466 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1467
1468 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1469 BasicBlock *Pred = PN->getIncomingBlock(i);
1470 LoadInst *&Load = InsertedLoads[Pred];
1471 if (Load == 0) {
1472 Load = new LoadInst(PN->getIncomingValue(i),
1473 PN->getName() + "." + Pred->getName(),
1474 Pred->getTerminator());
1475 Load->setAlignment(Align);
1476 if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1477 }
1478
1479 NewPN->addIncoming(Load, Pred);
1480 }
1481
1482 PN->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001483 }
1484
1485 ++NumAdjusted;
1486 return true;
1487}
1488
Chris Lattner38aec322003-09-11 16:45:55 +00001489bool SROA::performPromotion(Function &F) {
1490 std::vector<AllocaInst*> Allocas;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001491 DominatorTree *DT = 0;
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001492 if (HasDomTree)
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001493 DT = &getAnalysis<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +00001494
Chris Lattner02a3be02003-09-20 14:39:18 +00001495 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Devang Patel231a5ab2011-07-06 21:09:55 +00001496 DIBuilder DIB(*F.getParent());
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001497 bool Changed = false;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001498 SmallVector<Instruction*, 64> Insts;
Chris Lattner38aec322003-09-11 16:45:55 +00001499 while (1) {
1500 Allocas.clear();
1501
1502 // Find allocas that are safe to promote, by looking at all instructions in
1503 // the entry node
1504 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1505 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001506 if (tryToMakeAllocaBePromotable(AI, TD))
Chris Lattner38aec322003-09-11 16:45:55 +00001507 Allocas.push_back(AI);
1508
1509 if (Allocas.empty()) break;
1510
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001511 if (HasDomTree)
Cameron Zwarich419e8a62011-01-17 17:38:41 +00001512 PromoteMemToReg(Allocas, *DT);
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001513 else {
1514 SSAUpdater SSA;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001515 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1516 AllocaInst *AI = Allocas[i];
1517
1518 // Build list of instructions to promote.
1519 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1520 UI != E; ++UI)
1521 Insts.push_back(cast<Instruction>(*UI));
Devang Patel231a5ab2011-07-06 21:09:55 +00001522 AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001523 Insts.clear();
1524 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001525 }
Chris Lattner38aec322003-09-11 16:45:55 +00001526 NumPromoted += Allocas.size();
1527 Changed = true;
1528 }
1529
1530 return Changed;
1531}
1532
Chris Lattner4cc576b2010-04-16 00:24:57 +00001533
Bob Wilson3992feb2010-02-03 17:23:56 +00001534/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1535/// SROA. It must be a struct or array type with a small number of elements.
1536static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001537 Type *T = AI->getAllocatedType();
Bob Wilson3992feb2010-02-03 17:23:56 +00001538 // Do not promote any struct into more than 32 separate vars.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001539 if (StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +00001540 return ST->getNumElements() <= 32;
1541 // Arrays are much less likely to be safe for SROA; only consider
1542 // them if they are very small.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001543 if (ArrayType *AT = dyn_cast<ArrayType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +00001544 return AT->getNumElements() <= 8;
1545 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +00001546}
1547
Chris Lattnerc4472072010-04-15 23:50:26 +00001548
Chris Lattner38aec322003-09-11 16:45:55 +00001549// performScalarRepl - This algorithm is a simple worklist driven algorithm,
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001550// which runs on all of the alloca instructions in the function, removing them
1551// if they are only used by getelementptr instructions.
Chris Lattner38aec322003-09-11 16:45:55 +00001552//
1553bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001554 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +00001555
Chris Lattner31d80102010-04-15 21:59:20 +00001556 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +00001557 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001558 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +00001559 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +00001560 WorkList.push_back(A);
1561
1562 // Process the worklist
1563 bool Changed = false;
1564 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001565 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001566 WorkList.pop_back();
Bob Wilson69743022011-01-13 20:59:44 +00001567
Chris Lattneradd2bd72006-12-22 23:14:42 +00001568 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1569 // with unused elements.
1570 if (AI->use_empty()) {
1571 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +00001572 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +00001573 continue;
1574 }
Chris Lattner7809ecd2009-02-03 01:30:09 +00001575
1576 // If this alloca is impossible for us to promote, reject it early.
1577 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1578 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001579
Chris Lattner79b3bd32007-04-25 06:40:51 +00001580 // Check to see if this allocation is only modified by a memcpy/memmove from
1581 // a constant global. If this is the case, we can change all users to use
1582 // the constant global instead. This is commonly produced by the CFE by
1583 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1584 // is only subsequently read.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001585 SmallVector<Instruction *, 4> ToDelete;
1586 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(AI, ToDelete)) {
David Greene504c7d82010-01-05 01:27:09 +00001587 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001588 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
1589 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
1590 ToDelete[i]->eraseFromParent();
1591 Constant *TheSrc = cast<Constant>(Copy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001592 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001593 Copy->eraseFromParent(); // Don't mutate the global.
Chris Lattner79b3bd32007-04-25 06:40:51 +00001594 AI->eraseFromParent();
1595 ++NumGlobals;
1596 Changed = true;
1597 continue;
1598 }
Bob Wilson69743022011-01-13 20:59:44 +00001599
Chris Lattner7809ecd2009-02-03 01:30:09 +00001600 // Check to see if we can perform the core SROA transformation. We cannot
1601 // transform the allocation instruction if it is an array allocation
1602 // (allocations OF arrays are ok though), and an allocation of a scalar
1603 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +00001604 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +00001605
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +00001606 // Do not promote [0 x %struct].
1607 if (AllocaSize == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001608
Chris Lattner31d80102010-04-15 21:59:20 +00001609 // Do not promote any struct whose size is too big.
1610 if (AllocaSize > SRThreshold) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001611
Bob Wilson3992feb2010-02-03 17:23:56 +00001612 // If the alloca looks like a good candidate for scalar replacement, and if
1613 // all its users can be transformed, then split up the aggregate into its
1614 // separate elements.
1615 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1616 DoScalarReplacement(AI, WorkList);
1617 Changed = true;
1618 continue;
1619 }
1620
Chris Lattner6e733d32009-01-28 20:16:43 +00001621 // If we can turn this aggregate value (potentially with casts) into a
1622 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001623 // IsNotTrivial tracks whether this is something that mem2reg could have
1624 // promoted itself. If so, we don't want to transform it needlessly. Note
1625 // that we can't just check based on the type: the alloca may be of an i32
1626 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +00001627 if (AllocaInst *NewAI =
1628 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001629 NewAI->takeName(AI);
1630 AI->eraseFromParent();
1631 ++NumConverted;
1632 Changed = true;
1633 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001634 }
1635
Chris Lattner7809ecd2009-02-03 01:30:09 +00001636 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +00001637 }
1638
1639 return Changed;
1640}
Chris Lattner5e062a12003-05-30 04:15:41 +00001641
Chris Lattnera10b29b2007-04-25 05:02:56 +00001642/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1643/// predicate, do SROA now.
Bob Wilson69743022011-01-13 20:59:44 +00001644void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001645 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +00001646 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +00001647 SmallVector<AllocaInst*, 32> ElementAllocas;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001648 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
Chris Lattnera10b29b2007-04-25 05:02:56 +00001649 ElementAllocas.reserve(ST->getNumContainedTypes());
1650 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Bob Wilson69743022011-01-13 20:59:44 +00001651 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +00001652 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001653 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001654 ElementAllocas.push_back(NA);
1655 WorkList.push_back(NA); // Add to worklist for recursive processing
1656 }
1657 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001658 ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
Chris Lattnera10b29b2007-04-25 05:02:56 +00001659 ElementAllocas.reserve(AT->getNumElements());
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001660 Type *ElTy = AT->getElementType();
Chris Lattnera10b29b2007-04-25 05:02:56 +00001661 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +00001662 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001663 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001664 ElementAllocas.push_back(NA);
1665 WorkList.push_back(NA); // Add to worklist for recursive processing
1666 }
1667 }
1668
Bob Wilsonb742def2009-12-18 20:14:40 +00001669 // Now that we have created the new alloca instructions, rewrite all the
1670 // uses of the old alloca.
1671 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +00001672
Bob Wilsonb742def2009-12-18 20:14:40 +00001673 // Now erase any instructions that were made dead while rewriting the alloca.
1674 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +00001675 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +00001676
Dan Gohmanfe601042010-06-22 15:08:57 +00001677 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +00001678}
Chris Lattnera59adc42009-12-14 05:11:02 +00001679
Bob Wilsonb742def2009-12-18 20:14:40 +00001680/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1681/// recursively including all their operands that become trivially dead.
1682void SROA::DeleteDeadInstructions() {
1683 while (!DeadInsts.empty()) {
1684 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +00001685
Bob Wilsonb742def2009-12-18 20:14:40 +00001686 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1687 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1688 // Zero out the operand and see if it becomes trivially dead.
1689 // (But, don't add allocas to the dead instruction list -- they are
1690 // already on the worklist and will be deleted separately.)
1691 *OI = 0;
1692 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1693 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +00001694 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001695
1696 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +00001697 }
Chris Lattnera59adc42009-12-14 05:11:02 +00001698}
Bob Wilson69743022011-01-13 20:59:44 +00001699
Bob Wilsonb742def2009-12-18 20:14:40 +00001700/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1701/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001702/// the Info parameter. Offset indicates the position within AI that is
1703/// referenced by this instruction.
Chris Lattner6c95d242011-01-23 07:29:29 +00001704void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001705 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001706 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1707 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +00001708
Bob Wilsonb742def2009-12-18 20:14:40 +00001709 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Chris Lattner6c95d242011-01-23 07:29:29 +00001710 isSafeForScalarRepl(BC, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001711 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001712 uint64_t GEPOffset = Offset;
Chris Lattner6c95d242011-01-23 07:29:29 +00001713 isSafeGEP(GEPI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001714 if (!Info.isUnsafe)
Chris Lattner6c95d242011-01-23 07:29:29 +00001715 isSafeForScalarRepl(GEPI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001716 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001717 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001718 if (Length == 0)
1719 return MarkUnsafe(Info, User);
Chris Lattner6c95d242011-01-23 07:29:29 +00001720 isSafeMemAccess(Offset, Length->getZExtValue(), 0,
Chris Lattner145c5322011-01-23 08:27:54 +00001721 UI.getOperandNo() == 0, Info, MI,
1722 true /*AllowWholeAccess*/);
Bob Wilsonb742def2009-12-18 20:14:40 +00001723 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Eli Friedman2bc3d522011-09-12 20:23:13 +00001724 if (!LI->isSimple())
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001725 return MarkUnsafe(Info, User);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001726 Type *LIType = LI->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001727 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001728 LIType, false, Info, LI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001729 Info.hasALoadOrStore = true;
1730
Bob Wilsonb742def2009-12-18 20:14:40 +00001731 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1732 // Store is ok if storing INTO the pointer, not storing the pointer
Eli Friedman2bc3d522011-09-12 20:23:13 +00001733 if (!SI->isSimple() || SI->getOperand(0) == I)
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001734 return MarkUnsafe(Info, User);
1735
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001736 Type *SIType = SI->getOperand(0)->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001737 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001738 SIType, true, Info, SI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001739 Info.hasALoadOrStore = true;
Nick Lewycky5a1cb642011-07-25 23:14:22 +00001740 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1741 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1742 II->getIntrinsicID() != Intrinsic::lifetime_end)
1743 return MarkUnsafe(Info, User);
Chris Lattner145c5322011-01-23 08:27:54 +00001744 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1745 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1746 } else {
1747 return MarkUnsafe(Info, User);
1748 }
1749 if (Info.isUnsafe) return;
1750 }
1751}
1752
1753
1754/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1755/// derived from the alloca, we can often still split the alloca into elements.
1756/// This is useful if we have a large alloca where one element is phi'd
1757/// together somewhere: we can SRoA and promote all the other elements even if
1758/// we end up not being able to promote this one.
1759///
1760/// All we require is that the uses of the PHI do not index into other parts of
1761/// the alloca. The most important use case for this is single load and stores
1762/// that are PHI'd together, which can happen due to code sinking.
1763void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1764 AllocaInfo &Info) {
1765 // If we've already checked this PHI, don't do it again.
1766 if (PHINode *PN = dyn_cast<PHINode>(I))
1767 if (!Info.CheckedPHIs.insert(PN))
1768 return;
1769
1770 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1771 Instruction *User = cast<Instruction>(*UI);
1772
1773 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1774 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1775 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1776 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1777 // but would have to prove that we're staying inside of an element being
1778 // promoted.
1779 if (!GEPI->hasAllZeroIndices())
1780 return MarkUnsafe(Info, User);
1781 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1782 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Eli Friedman2bc3d522011-09-12 20:23:13 +00001783 if (!LI->isSimple())
Chris Lattner145c5322011-01-23 08:27:54 +00001784 return MarkUnsafe(Info, User);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001785 Type *LIType = LI->getType();
Chris Lattner145c5322011-01-23 08:27:54 +00001786 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1787 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1788 Info.hasALoadOrStore = true;
1789
1790 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1791 // Store is ok if storing INTO the pointer, not storing the pointer
Eli Friedman2bc3d522011-09-12 20:23:13 +00001792 if (!SI->isSimple() || SI->getOperand(0) == I)
Chris Lattner145c5322011-01-23 08:27:54 +00001793 return MarkUnsafe(Info, User);
1794
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001795 Type *SIType = SI->getOperand(0)->getType();
Chris Lattner145c5322011-01-23 08:27:54 +00001796 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1797 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1798 Info.hasALoadOrStore = true;
1799 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1800 isSafePHISelectUseForScalarRepl(User, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001801 } else {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001802 return MarkUnsafe(Info, User);
Bob Wilsonb742def2009-12-18 20:14:40 +00001803 }
1804 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001805 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001806}
Bob Wilson39c88a62009-12-17 18:34:24 +00001807
Bob Wilsonb742def2009-12-18 20:14:40 +00001808/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1809/// replacement. It is safe when all the indices are constant, in-bounds
1810/// references, and when the resulting offset corresponds to an element within
1811/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001812/// return, Offset is adjusted as specified by the GEP indices.
Chris Lattner6c95d242011-01-23 07:29:29 +00001813void SROA::isSafeGEP(GetElementPtrInst *GEPI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001814 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001815 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1816 if (GEPIt == E)
1817 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001818
Chris Lattner88e6dc82008-08-23 05:21:06 +00001819 // Walk through the GEP type indices, checking the types that this indexes
1820 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001821 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001822 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001823 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001824 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001825
Bob Wilsonb742def2009-12-18 20:14:40 +00001826 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1827 if (!IdxVal)
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001828 return MarkUnsafe(Info, GEPI);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001829 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001830
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001831 // Compute the offset due to this GEP and check if the alloca has a
1832 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001833 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
Jay Foad8fbbb392011-07-19 14:01:37 +00001834 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
Chris Lattner6c95d242011-01-23 07:29:29 +00001835 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001836 MarkUnsafe(Info, GEPI);
Chris Lattner5e062a12003-05-30 04:15:41 +00001837}
1838
Bob Wilson704d1342011-01-13 17:45:11 +00001839/// isHomogeneousAggregate - Check if type T is a struct or array containing
1840/// elements of the same type (which is always true for arrays). If so,
1841/// return true with NumElts and EltTy set to the number of elements and the
1842/// element type, respectively.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001843static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
1844 Type *&EltTy) {
1845 if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
Bob Wilson704d1342011-01-13 17:45:11 +00001846 NumElts = AT->getNumElements();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001847 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
Bob Wilson704d1342011-01-13 17:45:11 +00001848 return true;
1849 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001850 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilson704d1342011-01-13 17:45:11 +00001851 NumElts = ST->getNumContainedTypes();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001852 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
Bob Wilson704d1342011-01-13 17:45:11 +00001853 for (unsigned n = 1; n < NumElts; ++n) {
1854 if (ST->getContainedType(n) != EltTy)
1855 return false;
1856 }
1857 return true;
1858 }
1859 return false;
1860}
1861
1862/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1863/// "homogeneous" aggregates with the same element type and number of elements.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001864static bool isCompatibleAggregate(Type *T1, Type *T2) {
Bob Wilson704d1342011-01-13 17:45:11 +00001865 if (T1 == T2)
1866 return true;
1867
1868 unsigned NumElts1, NumElts2;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001869 Type *EltTy1, *EltTy2;
Bob Wilson704d1342011-01-13 17:45:11 +00001870 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1871 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1872 NumElts1 == NumElts2 &&
1873 EltTy1 == EltTy2)
1874 return true;
1875
1876 return false;
1877}
1878
Bob Wilsonb742def2009-12-18 20:14:40 +00001879/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1880/// alloca or has an offset and size that corresponds to a component element
1881/// within it. The offset checked here may have been formed from a GEP with a
1882/// pointer bitcasted to a different type.
Chris Lattner145c5322011-01-23 08:27:54 +00001883///
1884/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1885/// unit. If false, it only allows accesses known to be in a single element.
Chris Lattner6c95d242011-01-23 07:29:29 +00001886void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001887 Type *MemOpType, bool isStore,
Chris Lattner145c5322011-01-23 08:27:54 +00001888 AllocaInfo &Info, Instruction *TheAccess,
1889 bool AllowWholeAccess) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001890 // Check if this is a load/store of the entire alloca.
Chris Lattner145c5322011-01-23 08:27:54 +00001891 if (Offset == 0 && AllowWholeAccess &&
Chris Lattner6c95d242011-01-23 07:29:29 +00001892 MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
Bob Wilson704d1342011-01-13 17:45:11 +00001893 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1894 // loads/stores (which are essentially the same as the MemIntrinsics with
1895 // regard to copying padding between elements). But, if an alloca is
1896 // flagged as both a source and destination of such operations, we'll need
1897 // to check later for padding between elements.
1898 if (!MemOpType || MemOpType->isIntegerTy()) {
1899 if (isStore)
1900 Info.isMemCpyDst = true;
1901 else
1902 Info.isMemCpySrc = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001903 return;
1904 }
Bob Wilson704d1342011-01-13 17:45:11 +00001905 // This is also safe for references using a type that is compatible with
1906 // the type of the alloca, so that loads/stores can be rewritten using
1907 // insertvalue/extractvalue.
Chris Lattner6c95d242011-01-23 07:29:29 +00001908 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
Chris Lattner7e9b4272011-01-16 06:18:28 +00001909 Info.hasSubelementAccess = true;
Bob Wilson704d1342011-01-13 17:45:11 +00001910 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001911 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001912 }
1913 // Check if the offset/size correspond to a component within the alloca type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001914 Type *T = Info.AI->getAllocatedType();
Chris Lattner7e9b4272011-01-16 06:18:28 +00001915 if (TypeHasComponent(T, Offset, MemSize)) {
1916 Info.hasSubelementAccess = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001917 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001918 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001919
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001920 return MarkUnsafe(Info, TheAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +00001921}
1922
1923/// TypeHasComponent - Return true if T has a component type with the
1924/// specified offset and size. If Size is zero, do not check the size.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001925bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) {
1926 Type *EltTy;
Bob Wilsonb742def2009-12-18 20:14:40 +00001927 uint64_t EltSize;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001928 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001929 const StructLayout *Layout = TD->getStructLayout(ST);
1930 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1931 EltTy = ST->getContainedType(EltIdx);
1932 EltSize = TD->getTypeAllocSize(EltTy);
1933 Offset -= Layout->getElementOffset(EltIdx);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001934 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001935 EltTy = AT->getElementType();
1936 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001937 if (Offset >= AT->getNumElements() * EltSize)
1938 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001939 Offset %= EltSize;
1940 } else {
1941 return false;
1942 }
1943 if (Offset == 0 && (Size == 0 || EltSize == Size))
1944 return true;
1945 // Check if the component spans multiple elements.
1946 if (Offset + Size > EltSize)
1947 return false;
1948 return TypeHasComponent(EltTy, Offset, Size);
1949}
1950
1951/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1952/// the instruction I, which references it, to use the separate elements.
1953/// Offset indicates the position within AI that is referenced by this
1954/// instruction.
1955void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1956 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner145c5322011-01-23 08:27:54 +00001957 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1958 Use &TheUse = UI.getUse();
1959 Instruction *User = cast<Instruction>(*UI++);
Bob Wilsonb742def2009-12-18 20:14:40 +00001960
1961 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1962 RewriteBitCast(BC, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001963 continue;
1964 }
1965
1966 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001967 RewriteGEP(GEPI, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001968 continue;
1969 }
1970
1971 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001972 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1973 uint64_t MemSize = Length->getZExtValue();
1974 if (Offset == 0 &&
1975 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1976 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001977 // Otherwise the intrinsic can only touch a single element and the
1978 // address operand will be updated, so nothing else needs to be done.
Chris Lattner145c5322011-01-23 08:27:54 +00001979 continue;
1980 }
Nick Lewycky5a1cb642011-07-25 23:14:22 +00001981
1982 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1983 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1984 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1985 RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
1986 }
1987 continue;
1988 }
Chris Lattner145c5322011-01-23 08:27:54 +00001989
1990 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001991 Type *LIType = LI->getType();
Chris Lattner192228e2011-01-16 05:28:59 +00001992
Bob Wilson704d1342011-01-13 17:45:11 +00001993 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001994 // Replace:
1995 // %res = load { i32, i32 }* %alloc
1996 // with:
1997 // %load.0 = load i32* %alloc.0
1998 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1999 // %load.1 = load i32* %alloc.1
2000 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
2001 // (Also works for arrays instead of structs)
2002 Value *Insert = UndefValue::get(LIType);
Devang Patelabb25122011-06-03 19:46:19 +00002003 IRBuilder<> Builder(LI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002004 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patelabb25122011-06-03 19:46:19 +00002005 Value *Load = Builder.CreateLoad(NewElts[i], "load");
2006 Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
Bob Wilsonb742def2009-12-18 20:14:40 +00002007 }
2008 LI->replaceAllUsesWith(Insert);
2009 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00002010 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00002011 TD->getTypeAllocSize(LIType) ==
2012 TD->getTypeAllocSize(AI->getAllocatedType())) {
2013 // If this is a load of the entire alloca to an integer, rewrite it.
2014 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
2015 }
Chris Lattner145c5322011-01-23 08:27:54 +00002016 continue;
2017 }
2018
2019 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00002020 Value *Val = SI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002021 Type *SIType = Val->getType();
Bob Wilson704d1342011-01-13 17:45:11 +00002022 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00002023 // Replace:
2024 // store { i32, i32 } %val, { i32, i32 }* %alloc
2025 // with:
2026 // %val.0 = extractvalue { i32, i32 } %val, 0
2027 // store i32 %val.0, i32* %alloc.0
2028 // %val.1 = extractvalue { i32, i32 } %val, 1
2029 // store i32 %val.1, i32* %alloc.1
2030 // (Also works for arrays instead of structs)
Devang Patelabb25122011-06-03 19:46:19 +00002031 IRBuilder<> Builder(SI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002032 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patelabb25122011-06-03 19:46:19 +00002033 Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
2034 Builder.CreateStore(Extract, NewElts[i]);
Bob Wilsonb742def2009-12-18 20:14:40 +00002035 }
2036 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00002037 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00002038 TD->getTypeAllocSize(SIType) ==
2039 TD->getTypeAllocSize(AI->getAllocatedType())) {
2040 // If this is a store of the entire alloca from an integer, rewrite it.
2041 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
2042 }
Chris Lattner145c5322011-01-23 08:27:54 +00002043 continue;
2044 }
2045
2046 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
2047 // If we have a PHI user of the alloca itself (as opposed to a GEP or
2048 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
2049 // the new pointer.
2050 if (!isa<AllocaInst>(I)) continue;
2051
2052 assert(Offset == 0 && NewElts[0] &&
2053 "Direct alloca use should have a zero offset");
2054
2055 // If we have a use of the alloca, we know the derived uses will be
2056 // utilizing just the first element of the scalarized result. Insert a
2057 // bitcast of the first alloca before the user as required.
2058 AllocaInst *NewAI = NewElts[0];
2059 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
2060 NewAI->moveBefore(BCI);
2061 TheUse = BCI;
2062 continue;
Bob Wilsonb742def2009-12-18 20:14:40 +00002063 }
Bob Wilson39c88a62009-12-17 18:34:24 +00002064 }
2065}
2066
Bob Wilsonb742def2009-12-18 20:14:40 +00002067/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
2068/// and recursively continue updating all of its uses.
2069void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
2070 SmallVector<AllocaInst*, 32> &NewElts) {
2071 RewriteForScalarRepl(BC, AI, Offset, NewElts);
2072 if (BC->getOperand(0) != AI)
2073 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00002074
Bob Wilsonb742def2009-12-18 20:14:40 +00002075 // The bitcast references the original alloca. Replace its uses with
2076 // references to the first new element alloca.
2077 Instruction *Val = NewElts[0];
2078 if (Val->getType() != BC->getDestTy()) {
2079 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
2080 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00002081 }
Bob Wilsonb742def2009-12-18 20:14:40 +00002082 BC->replaceAllUsesWith(Val);
2083 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00002084}
2085
Bob Wilsonb742def2009-12-18 20:14:40 +00002086/// FindElementAndOffset - Return the index of the element containing Offset
2087/// within the specified type, which must be either a struct or an array.
2088/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00002089/// element. IdxTy is set to the type of the index result to be used in a
2090/// GEP instruction.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002091uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset,
2092 Type *&IdxTy) {
Bob Wilsone88728d2009-12-19 06:53:17 +00002093 uint64_t Idx = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002094 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00002095 const StructLayout *Layout = TD->getStructLayout(ST);
2096 Idx = Layout->getElementContainingOffset(Offset);
2097 T = ST->getContainedType(Idx);
2098 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00002099 IdxTy = Type::getInt32Ty(T->getContext());
2100 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00002101 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002102 ArrayType *AT = cast<ArrayType>(T);
Bob Wilsone88728d2009-12-19 06:53:17 +00002103 T = AT->getElementType();
2104 uint64_t EltSize = TD->getTypeAllocSize(T);
2105 Idx = Offset / EltSize;
2106 Offset -= Idx * EltSize;
2107 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00002108 return Idx;
2109}
2110
2111/// RewriteGEP - Check if this GEP instruction moves the pointer across
2112/// elements of the alloca that are being split apart, and if so, rewrite
2113/// the GEP to be relative to the new element.
2114void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
2115 SmallVector<AllocaInst*, 32> &NewElts) {
2116 uint64_t OldOffset = Offset;
2117 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
Jay Foad8fbbb392011-07-19 14:01:37 +00002118 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
Bob Wilsonb742def2009-12-18 20:14:40 +00002119
2120 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
2121
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002122 Type *T = AI->getAllocatedType();
2123 Type *IdxTy;
Bob Wilsone88728d2009-12-19 06:53:17 +00002124 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00002125 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00002126 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00002127
2128 T = AI->getAllocatedType();
2129 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00002130 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00002131
2132 // If this GEP does not move the pointer across elements of the alloca
2133 // being split, then it does not needs to be rewritten.
2134 if (Idx == OldIdx)
2135 return;
2136
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002137 Type *i32Ty = Type::getInt32Ty(AI->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00002138 SmallVector<Value*, 8> NewArgs;
2139 NewArgs.push_back(Constant::getNullValue(i32Ty));
2140 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00002141 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
2142 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00002143 }
2144 Instruction *Val = NewElts[Idx];
2145 if (NewArgs.size() > 1) {
Jay Foada9203102011-07-25 09:48:08 +00002146 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002147 Val->takeName(GEPI);
2148 }
2149 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00002150 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002151 GEPI->replaceAllUsesWith(Val);
2152 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002153}
2154
Nick Lewycky5a1cb642011-07-25 23:14:22 +00002155/// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
2156/// to mark the lifetime of the scalarized memory.
2157void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
2158 uint64_t Offset,
2159 SmallVector<AllocaInst*, 32> &NewElts) {
2160 ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
2161 // Put matching lifetime markers on everything from Offset up to
2162 // Offset+OldSize.
2163 Type *AIType = AI->getAllocatedType();
2164 uint64_t NewOffset = Offset;
2165 Type *IdxTy;
2166 uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy);
2167
2168 IRBuilder<> Builder(II);
2169 uint64_t Size = OldSize->getLimitedValue();
2170
2171 if (NewOffset) {
2172 // Splice the first element and index 'NewOffset' bytes in. SROA will
2173 // split the alloca again later.
2174 Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy());
2175 V = Builder.CreateGEP(V, Builder.getInt64(NewOffset));
2176
2177 IdxTy = NewElts[Idx]->getAllocatedType();
2178 uint64_t EltSize = TD->getTypeAllocSize(IdxTy) - NewOffset;
2179 if (EltSize > Size) {
2180 EltSize = Size;
2181 Size = 0;
2182 } else {
2183 Size -= EltSize;
2184 }
2185 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2186 Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
2187 else
2188 Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
2189 ++Idx;
2190 }
2191
2192 for (; Idx != NewElts.size() && Size; ++Idx) {
2193 IdxTy = NewElts[Idx]->getAllocatedType();
2194 uint64_t EltSize = TD->getTypeAllocSize(IdxTy);
2195 if (EltSize > Size) {
2196 EltSize = Size;
2197 Size = 0;
2198 } else {
2199 Size -= EltSize;
2200 }
2201 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2202 Builder.CreateLifetimeStart(NewElts[Idx],
2203 Builder.getInt64(EltSize));
2204 else
2205 Builder.CreateLifetimeEnd(NewElts[Idx],
2206 Builder.getInt64(EltSize));
2207 }
2208 DeadInsts.push_back(II);
2209}
2210
Chris Lattnerd93afec2009-01-07 07:18:45 +00002211/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2212/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00002213void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00002214 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00002215 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002216 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00002217 // appropriate type. The "Other" pointer is the pointer that goes to memory
2218 // that doesn't have anything to do with the alloca that we are promoting. For
2219 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00002220 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00002221 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00002222 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00002223 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00002224 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00002225 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00002226 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00002227 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00002228 }
2229 }
Bob Wilson78c50b82009-12-08 18:22:03 +00002230
Chris Lattnerd93afec2009-01-07 07:18:45 +00002231 // If there is an other pointer, we want to convert it to the same pointer
2232 // type as AI has, so we can GEP through it safely.
2233 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00002234 unsigned AddrSpace =
2235 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00002236
2237 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2238 // optimization, but it's also required to detect the corner case where
2239 // both pointer operands are referencing the same memory, and where
2240 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2241 // function is only called for mem intrinsics that access the whole
2242 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00002243 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson69743022011-01-13 20:59:44 +00002244
Bob Wilsona756b1d2010-01-19 04:32:48 +00002245 // Copying the alloca to itself is a no-op: just delete it.
2246 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2247 // This code will run twice for a no-op memcpy -- once for each operand.
2248 // Put only one reference to MI on the DeadInsts list.
2249 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
2250 E = DeadInsts.end(); I != E; ++I)
2251 if (*I == MI) return;
2252 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002253 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00002254 }
Bob Wilson69743022011-01-13 20:59:44 +00002255
Chris Lattnerd93afec2009-01-07 07:18:45 +00002256 // If the pointer is not the right type, insert a bitcast to the right
2257 // type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002258 Type *NewTy =
Chris Lattner0238f8c2010-07-08 00:27:05 +00002259 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson69743022011-01-13 20:59:44 +00002260
Chris Lattner0238f8c2010-07-08 00:27:05 +00002261 if (OtherPtr->getType() != NewTy)
2262 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002263 }
Bob Wilson69743022011-01-13 20:59:44 +00002264
Chris Lattnerd93afec2009-01-07 07:18:45 +00002265 // Process each element of the aggregate.
Bob Wilsonb742def2009-12-18 20:14:40 +00002266 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson69743022011-01-13 20:59:44 +00002267
Owen Anderson1d0be152009-08-13 21:58:54 +00002268 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00002269
2270 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2271 // If this is a memcpy/memmove, emit a GEP of the other element address.
2272 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002273 unsigned OtherEltAlign = MemAlignment;
Bob Wilson69743022011-01-13 20:59:44 +00002274
Bob Wilsona756b1d2010-01-19 04:32:48 +00002275 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002276 Value *Idx[2] = { Zero,
2277 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Jay Foada9203102011-07-25 09:48:08 +00002278 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00002279 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00002280 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00002281 uint64_t EltOffset;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002282 PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2283 Type *OtherTy = OtherPtrTy->getElementType();
2284 if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002285 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
2286 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002287 Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002288 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002289 }
Bob Wilson69743022011-01-13 20:59:44 +00002290
Chris Lattner1541e0f2009-03-04 19:20:50 +00002291 // The alignment of the other pointer is the guaranteed alignment of the
2292 // element, which is affected by both the known alignment of the whole
2293 // mem intrinsic and the alignment of the element. If the alignment of
2294 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2295 // known alignment is just 4 bytes.
2296 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00002297 }
Bob Wilson69743022011-01-13 20:59:44 +00002298
Chris Lattnerd93afec2009-01-07 07:18:45 +00002299 Value *EltPtr = NewElts[i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002300 Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson69743022011-01-13 20:59:44 +00002301
Chris Lattnerd93afec2009-01-07 07:18:45 +00002302 // If we got down to a scalar, insert a load or store as appropriate.
2303 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00002304 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002305 if (SROADest) {
2306 // From Other to Alloca.
2307 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2308 new StoreInst(Elt, EltPtr, MI);
2309 } else {
2310 // From Alloca to Other.
2311 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2312 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2313 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00002314 continue;
2315 }
2316 assert(isa<MemSetInst>(MI));
Bob Wilson69743022011-01-13 20:59:44 +00002317
Chris Lattnerd93afec2009-01-07 07:18:45 +00002318 // If the stored element is zero (common case), just store a null
2319 // constant.
2320 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00002321 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002322 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00002323 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00002324 } else {
2325 // If EltTy is a vector type, get the element type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002326 Type *ValTy = EltTy->getScalarType();
Dan Gohman44118f02009-06-16 00:20:26 +00002327
Chris Lattnerd93afec2009-01-07 07:18:45 +00002328 // Construct an integer with the right value.
2329 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2330 APInt OneVal(EltSize, CI->getZExtValue());
2331 APInt TotalVal(OneVal);
2332 // Set each byte.
2333 for (unsigned i = 0; 8*i < EltSize; ++i) {
2334 TotalVal = TotalVal.shl(8);
2335 TotalVal |= OneVal;
2336 }
Bob Wilson69743022011-01-13 20:59:44 +00002337
Chris Lattnerd93afec2009-01-07 07:18:45 +00002338 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002339 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00002340 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002341 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002342 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002343 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002344 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson69743022011-01-13 20:59:44 +00002345
Chris Lattnerd93afec2009-01-07 07:18:45 +00002346 // If the requested value was a vector constant, create it.
2347 if (EltTy != ValTy) {
2348 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
2349 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Chris Lattner2ca5c862011-02-15 00:14:00 +00002350 StoreVal = ConstantVector::get(Elts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002351 }
2352 }
2353 new StoreInst(StoreVal, EltPtr, MI);
2354 continue;
2355 }
2356 // Otherwise, if we're storing a byte variable, use a memset call for
2357 // this element.
2358 }
Bob Wilson69743022011-01-13 20:59:44 +00002359
Duncan Sands777d2302009-05-09 07:06:46 +00002360 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002361
Chris Lattner61db1f52010-12-26 22:57:41 +00002362 IRBuilder<> Builder(MI);
Bob Wilson69743022011-01-13 20:59:44 +00002363
Chris Lattnerd93afec2009-01-07 07:18:45 +00002364 // Finally, insert the meminst for this element.
Chris Lattner61db1f52010-12-26 22:57:41 +00002365 if (isa<MemSetInst>(MI)) {
2366 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2367 MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002368 } else {
Chris Lattner61db1f52010-12-26 22:57:41 +00002369 assert(isa<MemTransferInst>(MI));
2370 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2371 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson69743022011-01-13 20:59:44 +00002372
Chris Lattner61db1f52010-12-26 22:57:41 +00002373 if (isa<MemCpyInst>(MI))
2374 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2375 else
2376 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002377 }
Chris Lattner372dda82007-03-05 07:52:57 +00002378 }
Bob Wilsonb742def2009-12-18 20:14:40 +00002379 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00002380}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002381
Bob Wilson39fdd692009-12-04 21:57:37 +00002382/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002383/// overwrites the entire allocation. Extract out the pieces of the stored
2384/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002385void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002386 SmallVector<AllocaInst*, 32> &NewElts){
2387 // Extract each element out of the integer according to its structure offset
2388 // and store the element value to the individual alloca.
2389 Value *SrcVal = SI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002390 Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002391 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002392
Chris Lattner70728532011-01-16 05:58:24 +00002393 IRBuilder<> Builder(SI);
2394
Eli Friedman41b33f42009-06-01 09:14:32 +00002395 // Handle tail padding by extending the operand
2396 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002397 SrcVal = Builder.CreateZExt(SrcVal,
2398 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002399
David Greene504c7d82010-01-05 01:27:09 +00002400 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00002401 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002402
2403 // There are two forms here: AI could be an array or struct. Both cases
2404 // have different ways to compute the element offset.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002405 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002406 const StructLayout *Layout = TD->getStructLayout(EltSTy);
Bob Wilson69743022011-01-13 20:59:44 +00002407
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002408 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2409 // Get the number of bits to shift SrcVal to get the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002410 Type *FieldTy = EltSTy->getElementType(i);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002411 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson69743022011-01-13 20:59:44 +00002412
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002413 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00002414 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002415
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002416 Value *EltVal = SrcVal;
2417 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002418 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002419 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002420 }
Bob Wilson69743022011-01-13 20:59:44 +00002421
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002422 // Truncate down to an integer of the right size.
2423 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002424
Chris Lattner583dd602009-01-09 18:18:43 +00002425 // Ignore zero sized fields like {}, they obviously contain no data.
2426 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002427
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002428 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002429 EltVal = Builder.CreateTrunc(EltVal,
2430 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002431 Value *DestField = NewElts[i];
2432 if (EltVal->getType() == FieldTy) {
2433 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00002434 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002435 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002436 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002437 } else {
2438 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002439 DestField = Builder.CreateBitCast(DestField,
2440 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002441 }
2442 new StoreInst(EltVal, DestField, SI);
2443 }
Bob Wilson69743022011-01-13 20:59:44 +00002444
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002445 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002446 ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2447 Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002448 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002449 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2450
2451 uint64_t Shift;
Bob Wilson69743022011-01-13 20:59:44 +00002452
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002453 if (TD->isBigEndian())
2454 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002455 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002456 Shift = 0;
Bob Wilson69743022011-01-13 20:59:44 +00002457
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002458 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00002459 // Ignore zero sized fields like {}, they obviously contain no data.
2460 if (ElementSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002461
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002462 Value *EltVal = SrcVal;
2463 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002464 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002465 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002466 }
Bob Wilson69743022011-01-13 20:59:44 +00002467
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002468 // Truncate down to an integer of the right size.
2469 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002470 EltVal = Builder.CreateTrunc(EltVal,
2471 IntegerType::get(SI->getContext(),
2472 ElementSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002473 Value *DestField = NewElts[i];
2474 if (EltVal->getType() == ArrayEltTy) {
2475 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002476 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00002477 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002478 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002479 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002480 } else {
2481 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002482 DestField = Builder.CreateBitCast(DestField,
2483 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002484 }
2485 new StoreInst(EltVal, DestField, SI);
Bob Wilson69743022011-01-13 20:59:44 +00002486
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002487 if (TD->isBigEndian())
2488 Shift -= ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002489 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002490 Shift += ElementOffset;
2491 }
2492 }
Bob Wilson69743022011-01-13 20:59:44 +00002493
Bob Wilsonb742def2009-12-18 20:14:40 +00002494 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002495}
2496
Bob Wilson39fdd692009-12-04 21:57:37 +00002497/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002498/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002499void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002500 SmallVector<AllocaInst*, 32> &NewElts) {
2501 // Extract each element out of the NewElts according to its structure offset
2502 // and form the result value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002503 Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002504 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002505
David Greene504c7d82010-01-05 01:27:09 +00002506 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00002507 << '\n');
Bob Wilson69743022011-01-13 20:59:44 +00002508
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002509 // There are two forms here: AI could be an array or struct. Both cases
2510 // have different ways to compute the element offset.
2511 const StructLayout *Layout = 0;
2512 uint64_t ArrayEltBitOffset = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002513 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002514 Layout = TD->getStructLayout(EltSTy);
2515 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002516 Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002517 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002518 }
2519
2520 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00002521 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson69743022011-01-13 20:59:44 +00002522
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002523 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2524 // Load the value from the alloca. If the NewElt is an aggregate, cast
2525 // the pointer to an integer of the same size before doing the load.
2526 Value *SrcField = NewElts[i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002527 Type *FieldTy =
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002528 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00002529 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002530
Chris Lattner583dd602009-01-09 18:18:43 +00002531 // Ignore zero sized fields like {}, they obviously contain no data.
2532 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002533
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002534 IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +00002535 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00002536 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2537 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00002538 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00002539 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002540 "", LI);
2541 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2542
2543 // If SrcField is a fp or vector of the right size but that isn't an
2544 // integer type, bitcast to an integer so we can shift it.
2545 if (SrcField->getType() != FieldIntTy)
2546 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2547
2548 // Zero extend the field to be the same size as the final alloca so that
2549 // we can shift and insert it.
2550 if (SrcField->getType() != ResultVal->getType())
2551 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson69743022011-01-13 20:59:44 +00002552
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002553 // Determine the number of bits to shift SrcField.
2554 uint64_t Shift;
2555 if (Layout) // Struct case.
2556 Shift = Layout->getElementOffsetInBits(i);
2557 else // Array case.
2558 Shift = i*ArrayEltBitOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002559
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002560 if (TD->isBigEndian())
2561 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson69743022011-01-13 20:59:44 +00002562
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002563 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002564 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002565 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2566 }
2567
Chris Lattner14952472010-06-27 07:58:26 +00002568 // Don't create an 'or x, 0' on the first iteration.
2569 if (!isa<Constant>(ResultVal) ||
2570 !cast<Constant>(ResultVal)->isNullValue())
2571 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2572 else
2573 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002574 }
Eli Friedman41b33f42009-06-01 09:14:32 +00002575
2576 // Handle tail padding by truncating the result
2577 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2578 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2579
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002580 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00002581 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002582}
2583
Duncan Sands3cb36502007-11-04 14:43:57 +00002584/// HasPadding - Return true if the specified type has any structure or
Bob Wilson694a10e2011-01-13 17:45:08 +00002585/// alignment padding in between the elements that would be split apart
2586/// by SROA; return false otherwise.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002587static bool HasPadding(Type *Ty, const TargetData &TD) {
2588 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Bob Wilson694a10e2011-01-13 17:45:08 +00002589 Ty = ATy->getElementType();
2590 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00002591 }
Bob Wilson694a10e2011-01-13 17:45:08 +00002592
2593 // SROA currently handles only Arrays and Structs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002594 StructType *STy = cast<StructType>(Ty);
Bob Wilson694a10e2011-01-13 17:45:08 +00002595 const StructLayout *SL = TD.getStructLayout(STy);
2596 unsigned PrevFieldBitOffset = 0;
2597 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2598 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2599
2600 // Check to see if there is any padding between this element and the
2601 // previous one.
2602 if (i) {
2603 unsigned PrevFieldEnd =
2604 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2605 if (PrevFieldEnd < FieldBitOffset)
2606 return true;
2607 }
2608 PrevFieldBitOffset = FieldBitOffset;
2609 }
2610 // Check for tail padding.
2611 if (unsigned EltCount = STy->getNumElements()) {
2612 unsigned PrevFieldEnd = PrevFieldBitOffset +
2613 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2614 if (PrevFieldEnd < SL->getSizeInBits())
2615 return true;
2616 }
2617 return false;
Chris Lattner39a1c042007-05-30 06:11:23 +00002618}
Chris Lattner372dda82007-03-05 07:52:57 +00002619
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002620/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2621/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2622/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002623bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00002624 // Loop over the use list of the alloca. We can only transform it if all of
2625 // the users are safe to transform.
Chris Lattner6c95d242011-01-23 07:29:29 +00002626 AllocaInfo Info(AI);
Bob Wilson69743022011-01-13 20:59:44 +00002627
Chris Lattner6c95d242011-01-23 07:29:29 +00002628 isSafeForScalarRepl(AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00002629 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00002630 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002631 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002632 }
Bob Wilson69743022011-01-13 20:59:44 +00002633
Chris Lattner39a1c042007-05-30 06:11:23 +00002634 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2635 // source and destination, we have to be careful. In particular, the memcpy
2636 // could be moving around elements that live in structure padding of the LLVM
2637 // types, but may actually be used. In these cases, we refuse to promote the
2638 // struct.
2639 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00002640 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002641 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00002642
Chris Lattner396a0562011-01-16 17:46:19 +00002643 // If the alloca never has an access to just *part* of it, but is accessed
2644 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner7e9b4272011-01-16 06:18:28 +00002645 // the alloca instead of promoting each piece at a time and inserting fission
2646 // and fusion code.
2647 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2648 // If the struct/array just has one element, use basic SRoA.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002649 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
Chris Lattner7e9b4272011-01-16 06:18:28 +00002650 if (ST->getNumElements() > 1) return false;
2651 } else {
2652 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2653 return false;
2654 }
2655 }
Chris Lattner145c5322011-01-23 08:27:54 +00002656
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002657 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00002658}
Chris Lattnera1888942005-12-12 07:19:13 +00002659
Chris Lattner800de312008-02-29 07:03:13 +00002660
Chris Lattner79b3bd32007-04-25 06:40:51 +00002661
2662/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2663/// some part of a constant global variable. This intentionally only accepts
2664/// constant expressions because we don't can't rewrite arbitrary instructions.
2665static bool PointsToConstantGlobal(Value *V) {
2666 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2667 return GV->isConstant();
2668 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Bob Wilson69743022011-01-13 20:59:44 +00002669 if (CE->getOpcode() == Instruction::BitCast ||
Chris Lattner79b3bd32007-04-25 06:40:51 +00002670 CE->getOpcode() == Instruction::GetElementPtr)
2671 return PointsToConstantGlobal(CE->getOperand(0));
2672 return false;
2673}
2674
2675/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2676/// pointer to an alloca. Ignore any reads of the pointer, return false if we
2677/// see any stores or other unknown uses. If we see pointer arithmetic, keep
2678/// track of whether it moves the pointer (with isOffset) but otherwise traverse
2679/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
Nick Lewycky081f8002010-11-24 22:04:20 +00002680/// the alloca, and if the source pointer is a pointer to a constant global, we
Chris Lattner79b3bd32007-04-25 06:40:51 +00002681/// can optimize this.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002682static bool
2683isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
2684 bool isOffset,
2685 SmallVector<Instruction *, 4> &LifetimeMarkers) {
2686 // We track lifetime intrinsics as we encounter them. If we decide to go
2687 // ahead and replace the value with the global, this lets the caller quickly
2688 // eliminate the markers.
2689
Chris Lattner79b3bd32007-04-25 06:40:51 +00002690 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00002691 User *U = cast<Instruction>(*UI);
2692
Chris Lattner2e618492010-11-18 06:20:47 +00002693 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00002694 // Ignore non-volatile loads, they are always ok.
Eli Friedman2bc3d522011-09-12 20:23:13 +00002695 if (!LI->isSimple()) return false;
Chris Lattner2e618492010-11-18 06:20:47 +00002696 continue;
2697 }
Bob Wilson69743022011-01-13 20:59:44 +00002698
Gabor Greif8a8a4352010-04-06 19:32:30 +00002699 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002700 // If uses of the bitcast are ok, we are ok.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002701 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset,
2702 LifetimeMarkers))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002703 return false;
2704 continue;
2705 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00002706 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002707 // If the GEP has all zero indices, it doesn't offset the pointer. If it
2708 // doesn't, it does.
2709 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002710 isOffset || !GEP->hasAllZeroIndices(),
2711 LifetimeMarkers))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002712 return false;
2713 continue;
2714 }
Bob Wilson69743022011-01-13 20:59:44 +00002715
Chris Lattner62480652010-11-18 06:41:51 +00002716 if (CallSite CS = U) {
Nick Lewycky081f8002010-11-24 22:04:20 +00002717 // If this is the function being called then we treat it like a load and
2718 // ignore it.
2719 if (CS.isCallee(UI))
2720 continue;
Bob Wilson69743022011-01-13 20:59:44 +00002721
Duncan Sands53892102011-05-06 10:30:37 +00002722 // If this is a readonly/readnone call site, then we know it is just a
2723 // load (but one that potentially returns the value itself), so we can
2724 // ignore it if we know that the value isn't captured.
2725 unsigned ArgNo = CS.getArgumentNo(UI);
2726 if (CS.onlyReadsMemory() &&
2727 (CS.getInstruction()->use_empty() ||
2728 CS.paramHasAttr(ArgNo+1, Attribute::NoCapture)))
2729 continue;
2730
Chris Lattner62480652010-11-18 06:41:51 +00002731 // If this is being passed as a byval argument, the caller is making a
2732 // copy, so it is only a read of the alloca.
Chris Lattner62480652010-11-18 06:41:51 +00002733 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
2734 continue;
2735 }
Bob Wilson69743022011-01-13 20:59:44 +00002736
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002737 // Lifetime intrinsics can be handled by the caller.
2738 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
2739 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2740 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2741 assert(II->use_empty() && "Lifetime markers have no result to use!");
2742 LifetimeMarkers.push_back(II);
2743 continue;
2744 }
2745 }
2746
Chris Lattner79b3bd32007-04-25 06:40:51 +00002747 // If this is isn't our memcpy/memmove, reject it as something we can't
2748 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00002749 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2750 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00002751 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002752
Chris Lattner2e618492010-11-18 06:20:47 +00002753 // If the transfer is using the alloca as a source of the transfer, then
Chris Lattner2e29ebd2010-11-18 07:32:33 +00002754 // ignore it since it is a load (unless the transfer is volatile).
Chris Lattner2e618492010-11-18 06:20:47 +00002755 if (UI.getOperandNo() == 1) {
2756 if (MI->isVolatile()) return false;
2757 continue;
2758 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00002759
2760 // If we already have seen a copy, reject the second one.
2761 if (TheCopy) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002762
Chris Lattner79b3bd32007-04-25 06:40:51 +00002763 // If the pointer has been offset from the start of the alloca, we can't
2764 // safely handle this.
2765 if (isOffset) return false;
2766
2767 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00002768 if (UI.getOperandNo() != 0) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002769
Chris Lattner79b3bd32007-04-25 06:40:51 +00002770 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00002771 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002772 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002773
Chris Lattner79b3bd32007-04-25 06:40:51 +00002774 // Otherwise, the transform is safe. Remember the copy instruction.
2775 TheCopy = MI;
2776 }
2777 return true;
2778}
2779
2780/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2781/// modified by a copy from a constant global. If we can prove this, we can
2782/// replace any uses of the alloca with uses of the global directly.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002783MemTransferInst *
2784SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
2785 SmallVector<Instruction*, 4> &ToDelete) {
Chris Lattner31d80102010-04-15 21:59:20 +00002786 MemTransferInst *TheCopy = 0;
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002787 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false, ToDelete))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002788 return TheCopy;
2789 return 0;
2790}