blob: d36a18f21c6fcb57d122eb7628460f4ba67d5e41 [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 if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
302 ScalarKind = Integer;
303
Chris Lattnera001b662010-04-16 00:38:19 +0000304 // If we were able to find a vector type that can handle this with
305 // insert/extract elements, and if there was at least one use that had
306 // a vector type, promote this to a vector. We don't want to promote
307 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
308 // we just get a lot of insert/extracts. If at least one vector is
309 // involved, then we probably really do have a union of vector/array.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000310 Type *NewTy;
Cameron Zwarich5b93d3c2011-06-14 06:33:51 +0000311 if (ScalarKind == Vector) {
312 assert(VectorTy && "Missing type for vector scalar.");
Chris Lattnera001b662010-04-16 00:38:19 +0000313 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
314 << *VectorTy << '\n');
315 NewTy = VectorTy; // Use the vector type.
316 } else {
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000317 unsigned BitWidth = AllocaSize * 8;
Cameron Zwarich51797822011-06-13 21:44:40 +0000318 if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
319 !HadNonMemTransferAccess && !TD.fitsInLegalInteger(BitWidth))
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000320 return 0;
321
Chris Lattnera001b662010-04-16 00:38:19 +0000322 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
323 // Create and insert the integer alloca.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000324 NewTy = IntegerType::get(AI->getContext(), BitWidth);
Chris Lattnera001b662010-04-16 00:38:19 +0000325 }
326 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
327 ConvertUsesToScalar(AI, NewAI, 0);
328 return NewAI;
329}
330
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000331/// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
332/// (VectorTy) so far at the offset specified by Offset (which is specified in
333/// bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000334///
Cameron Zwarich446d9522011-10-11 06:10:30 +0000335/// There are two cases we handle here:
Chris Lattner4cc576b2010-04-16 00:24:57 +0000336/// 1) A union of vector types of the same size and potentially its elements.
337/// Here we turn element accesses into insert/extract element operations.
338/// This promotes a <4 x float> with a store of float to the third element
339/// into a <4 x float> that uses insert element.
Cameron Zwarich446d9522011-10-11 06:10:30 +0000340/// 2) A fully general blob of memory, which we turn into some (potentially
Chris Lattner4cc576b2010-04-16 00:24:57 +0000341/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000342/// and stores would mutate the memory. We mark this by setting VectorTy
343/// to VoidTy.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000344void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000345 uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000346 // If we already decided to turn this into a blob of integer memory, there is
347 // nothing to be done.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000348 if (ScalarKind == Integer)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000349 return;
Bob Wilson69743022011-01-13 20:59:44 +0000350
Chris Lattner4cc576b2010-04-16 00:24:57 +0000351 // If this could be contributing to a vector, analyze it.
352
353 // If the In type is a vector that is the same size as the alloca, see if it
354 // matches the existing VecTy.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000355 if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000356 if (MergeInVectorType(VInTy, Offset))
Chris Lattner4cc576b2010-04-16 00:24:57 +0000357 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000358 } else if (In->isFloatTy() || In->isDoubleTy() ||
359 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
360 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
Cameron Zwarich9827b782011-03-29 05:19:52 +0000361 // Full width accesses can be ignored, because they can always be turned
362 // into bitcasts.
363 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
Cameron Zwarichdd689122011-06-13 21:44:31 +0000364 if (EltSize == AllocaSize)
Cameron Zwarich9827b782011-03-29 05:19:52 +0000365 return;
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000366
Chris Lattner4cc576b2010-04-16 00:24:57 +0000367 // If we're accessing something that could be an element of a vector, see
368 // if the implied vector agrees with what we already have and if Offset is
369 // compatible with it.
Cameron Zwarich96cc1d02011-06-09 01:45:33 +0000370 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Cameron Zwarich446d9522011-10-11 06:10:30 +0000371 (!VectorTy || EltSize == VectorTy->getElementType()
372 ->getPrimitiveSizeInBits()/8)) {
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000373 if (!VectorTy) {
Cameron Zwarich51797822011-06-13 21:44:40 +0000374 ScalarKind = ImplicitVector;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000375 VectorTy = VectorType::get(In, AllocaSize/EltSize);
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000376 }
Cameron Zwarich446d9522011-10-11 06:10:30 +0000377 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000378 }
379 }
Bob Wilson69743022011-01-13 20:59:44 +0000380
Chris Lattner4cc576b2010-04-16 00:24:57 +0000381 // Otherwise, we have a case that we can't handle with an optimized vector
382 // form. We can still turn this into a large integer.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000383 ScalarKind = Integer;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000384}
385
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000386/// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
387/// returning true if the type was successfully merged and false otherwise.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000388bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000389 uint64_t Offset) {
Cameron Zwarich446d9522011-10-11 06:10:30 +0000390 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
391 // If we're storing/loading a vector of the right size, allow it as a
392 // vector. If this the first vector we see, remember the type so that
393 // we know the element size. If this is a subsequent access, ignore it
394 // even if it is a differing type but the same size. Worst case we can
395 // bitcast the resultant vectors.
396 if (!VectorTy)
397 VectorTy = VInTy;
Cameron Zwarich51797822011-06-13 21:44:40 +0000398 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000399 return true;
Cameron Zwarich51797822011-06-13 21:44:40 +0000400 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000401
Cameron Zwarich446d9522011-10-11 06:10:30 +0000402 return false;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000403}
404
Chris Lattner4cc576b2010-04-16 00:24:57 +0000405/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
406/// its accesses to a single vector type, return true and set VecTy to
407/// the new type. If we could convert the alloca into a single promotable
408/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
409/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
410/// is the current offset from the base of the alloca being analyzed.
411///
412/// If we see at least one access to the value that is as a vector type, set the
413/// SawVec flag.
414bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
415 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
416 Instruction *User = cast<Instruction>(*UI);
Bob Wilson69743022011-01-13 20:59:44 +0000417
Chris Lattner4cc576b2010-04-16 00:24:57 +0000418 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
419 // Don't break volatile loads.
Eli Friedman2bc3d522011-09-12 20:23:13 +0000420 if (!LI->isSimple())
Chris Lattner4cc576b2010-04-16 00:24:57 +0000421 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000422 // Don't touch MMX operations.
423 if (LI->getType()->isX86_MMXTy())
424 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000425 HadNonMemTransferAccess = true;
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000426 MergeInTypeForLoadOrStore(LI->getType(), Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000427 continue;
428 }
Bob Wilson69743022011-01-13 20:59:44 +0000429
Chris Lattner4cc576b2010-04-16 00:24:57 +0000430 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
431 // Storing the pointer, not into the value?
Eli Friedman2bc3d522011-09-12 20:23:13 +0000432 if (SI->getOperand(0) == V || !SI->isSimple()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000433 // Don't touch MMX operations.
434 if (SI->getOperand(0)->getType()->isX86_MMXTy())
435 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000436 HadNonMemTransferAccess = true;
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000437 MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000438 continue;
439 }
Bob Wilson69743022011-01-13 20:59:44 +0000440
Chris Lattner4cc576b2010-04-16 00:24:57 +0000441 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Nick Lewycky5a1cb642011-07-25 23:14:22 +0000442 if (!onlyUsedByLifetimeMarkers(BCI))
443 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000444 if (!CanConvertToScalar(BCI, Offset))
445 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000446 continue;
447 }
448
449 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
450 // If this is a GEP with a variable indices, we can't handle it.
451 if (!GEP->hasAllConstantIndices())
452 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000453
Chris Lattner4cc576b2010-04-16 00:24:57 +0000454 // Compute the offset that this GEP adds to the pointer.
455 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Nadav Rotem16087692011-12-05 06:29:09 +0000456 if (!GEP->getPointerOperandType()->isPointerTy())
457 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000458 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
Jay Foad8fbbb392011-07-19 14:01:37 +0000459 Indices);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000460 // See if all uses can be converted.
461 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
462 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000463 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000464 HadNonMemTransferAccess = true;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000465 continue;
466 }
467
468 // If this is a constant sized memset of a constant value (e.g. 0) we can
469 // handle it.
470 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
Cameron Zwarich6be41eb2011-06-18 05:47:49 +0000471 // Store of constant value.
472 if (!isa<ConstantInt>(MSI->getValue()))
Chris Lattnera001b662010-04-16 00:38:19 +0000473 return false;
Cameron Zwarich6be41eb2011-06-18 05:47:49 +0000474
475 // Store of constant size.
476 ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
477 if (!Len)
478 return false;
479
480 // If the size differs from the alloca, we can only convert the alloca to
481 // an integer bag-of-bits.
482 // FIXME: This should handle all of the cases that are currently accepted
483 // as vector element insertions.
484 if (Len->getZExtValue() != AllocaSize || Offset != 0)
485 ScalarKind = Integer;
486
Chris Lattnera001b662010-04-16 00:38:19 +0000487 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000488 HadNonMemTransferAccess = true;
Chris Lattnera001b662010-04-16 00:38:19 +0000489 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000490 }
491
492 // If this is a memcpy or memmove into or out of the whole allocation, we
493 // can handle it like a load or store of the scalar type.
494 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000495 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
496 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
497 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000498
Chris Lattnera001b662010-04-16 00:38:19 +0000499 IsNotTrivial = true; // Can't be mem2reg'd.
500 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000501 }
Bob Wilson69743022011-01-13 20:59:44 +0000502
Nick Lewycky5a1cb642011-07-25 23:14:22 +0000503 // If this is a lifetime intrinsic, we can handle it.
504 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
505 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
506 II->getIntrinsicID() == Intrinsic::lifetime_end) {
507 continue;
508 }
509 }
510
Chris Lattner4cc576b2010-04-16 00:24:57 +0000511 // Otherwise, we cannot handle this!
512 return false;
513 }
Bob Wilson69743022011-01-13 20:59:44 +0000514
Chris Lattner4cc576b2010-04-16 00:24:57 +0000515 return true;
516}
517
518/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
519/// directly. This happens when we are converting an "integer union" to a
520/// single integer scalar, or when we are converting a "vector union" to a
521/// vector with insert/extractelement instructions.
522///
523/// Offset is an offset from the original alloca, in bits that need to be
524/// shifted to the right. By the end of this, there should be no uses of Ptr.
525void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
526 uint64_t Offset) {
527 while (!Ptr->use_empty()) {
528 Instruction *User = cast<Instruction>(Ptr->use_back());
529
530 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
531 ConvertUsesToScalar(CI, NewAI, Offset);
532 CI->eraseFromParent();
533 continue;
534 }
535
536 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
537 // Compute the offset that this GEP adds to the pointer.
538 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
539 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
Jay Foad8fbbb392011-07-19 14:01:37 +0000540 Indices);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000541 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
542 GEP->eraseFromParent();
543 continue;
544 }
Bob Wilson69743022011-01-13 20:59:44 +0000545
Chris Lattner61db1f52010-12-26 22:57:41 +0000546 IRBuilder<> Builder(User);
Bob Wilson69743022011-01-13 20:59:44 +0000547
Chris Lattner4cc576b2010-04-16 00:24:57 +0000548 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
549 // The load is a bit extract from NewAI shifted right by Offset bits.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000550 Value *LoadedVal = Builder.CreateLoad(NewAI);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000551 Value *NewLoadVal
552 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
553 LI->replaceAllUsesWith(NewLoadVal);
554 LI->eraseFromParent();
555 continue;
556 }
Bob Wilson69743022011-01-13 20:59:44 +0000557
Chris Lattner4cc576b2010-04-16 00:24:57 +0000558 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
559 assert(SI->getOperand(0) != Ptr && "Consistency error!");
560 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
561 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
562 Builder);
563 Builder.CreateStore(New, NewAI);
564 SI->eraseFromParent();
Bob Wilson69743022011-01-13 20:59:44 +0000565
Chris Lattner4cc576b2010-04-16 00:24:57 +0000566 // If the load we just inserted is now dead, then the inserted store
567 // overwrote the entire thing.
568 if (Old->use_empty())
569 Old->eraseFromParent();
570 continue;
571 }
Bob Wilson69743022011-01-13 20:59:44 +0000572
Chris Lattner4cc576b2010-04-16 00:24:57 +0000573 // If this is a constant sized memset of a constant value (e.g. 0) we can
574 // transform it into a store of the expanded constant value.
575 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
576 assert(MSI->getRawDest() == Ptr && "Consistency error!");
Aaron Ballman7e2fa312012-03-15 00:05:31 +0000577 signed SNumBytes = cast<ConstantInt>(MSI->getLength())->getSExtValue();
578 if (SNumBytes > 0) {
579 unsigned NumBytes = static_cast<unsigned>(SNumBytes);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000580 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson69743022011-01-13 20:59:44 +0000581
Chris Lattner4cc576b2010-04-16 00:24:57 +0000582 // Compute the value replicated the right number of times.
583 APInt APVal(NumBytes*8, Val);
584
585 // Splat the value if non-zero.
586 if (Val)
587 for (unsigned i = 1; i != NumBytes; ++i)
588 APVal |= APVal << 8;
Bob Wilson69743022011-01-13 20:59:44 +0000589
Chris Lattner4cc576b2010-04-16 00:24:57 +0000590 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
591 Value *New = ConvertScalar_InsertValue(
592 ConstantInt::get(User->getContext(), APVal),
593 Old, Offset, Builder);
594 Builder.CreateStore(New, NewAI);
Bob Wilson69743022011-01-13 20:59:44 +0000595
Chris Lattner4cc576b2010-04-16 00:24:57 +0000596 // If the load we just inserted is now dead, then the memset overwrote
597 // the entire thing.
598 if (Old->use_empty())
Bob Wilson69743022011-01-13 20:59:44 +0000599 Old->eraseFromParent();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000600 }
601 MSI->eraseFromParent();
602 continue;
603 }
604
605 // If this is a memcpy or memmove into or out of the whole allocation, we
606 // can handle it like a load or store of the scalar type.
607 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
608 assert(Offset == 0 && "must be store to start of alloca");
Bob Wilson69743022011-01-13 20:59:44 +0000609
Chris Lattner4cc576b2010-04-16 00:24:57 +0000610 // If the source and destination are both to the same alloca, then this is
611 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
612 // as appropriate.
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000613 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
Bob Wilson69743022011-01-13 20:59:44 +0000614
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000615 if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000616 // Dest must be OrigAI, change this to be a load from the original
617 // pointer (bitcasted), then a store to our new alloca.
618 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
619 Value *SrcPtr = MTI->getSource();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000620 PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
621 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
Mon P Wange90a6332010-12-23 01:41:32 +0000622 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
623 AIPTy = PointerType::get(AIPTy->getElementType(),
624 SPTy->getAddressSpace());
625 }
626 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
627
Chris Lattner4cc576b2010-04-16 00:24:57 +0000628 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
629 SrcVal->setAlignment(MTI->getAlignment());
630 Builder.CreateStore(SrcVal, NewAI);
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000631 } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000632 // Src must be OrigAI, change this to be a load from NewAI then a store
633 // through the original dest pointer (bitcasted).
634 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
635 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
636
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000637 PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
638 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
Mon P Wange90a6332010-12-23 01:41:32 +0000639 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
640 AIPTy = PointerType::get(AIPTy->getElementType(),
641 DPTy->getAddressSpace());
642 }
643 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
644
Chris Lattner4cc576b2010-04-16 00:24:57 +0000645 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
646 NewStore->setAlignment(MTI->getAlignment());
647 } else {
648 // Noop transfer. Src == Dst
649 }
650
651 MTI->eraseFromParent();
652 continue;
653 }
Bob Wilson69743022011-01-13 20:59:44 +0000654
Nick Lewycky5a1cb642011-07-25 23:14:22 +0000655 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
656 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
657 II->getIntrinsicID() == Intrinsic::lifetime_end) {
658 // There's no need to preserve these, as the resulting alloca will be
659 // converted to a register anyways.
660 II->eraseFromParent();
661 continue;
662 }
663 }
664
Chris Lattner4cc576b2010-04-16 00:24:57 +0000665 llvm_unreachable("Unsupported operation!");
666 }
667}
668
669/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
670/// or vector value FromVal, extracting the bits from the offset specified by
671/// Offset. This returns the value, which is of type ToType.
672///
673/// This happens when we are converting an "integer union" to a single
674/// integer scalar, or when we are converting a "vector union" to a vector with
675/// insert/extractelement instructions.
676///
677/// Offset is an offset from the original alloca, in bits that need to be
678/// shifted to the right.
679Value *ConvertToScalarInfo::
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000680ConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000681 uint64_t Offset, IRBuilder<> &Builder) {
682 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000683 Type *FromType = FromVal->getType();
Mon P Wangbe0761c2011-04-13 21:40:02 +0000684 if (FromType == ToType && Offset == 0)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000685 return FromVal;
686
687 // If the result alloca is a vector type, this is either an element
688 // access or a bitcast to another vector type of the same size.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000689 if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
Cameron Zwarich0398d612011-06-08 22:08:31 +0000690 unsigned FromTypeSize = TD.getTypeAllocSize(FromType);
Cameron Zwarich9827b782011-03-29 05:19:52 +0000691 unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
Cameron Zwarich446d9522011-10-11 06:10:30 +0000692 if (FromTypeSize == ToTypeSize)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000693 return Builder.CreateBitCast(FromVal, ToType);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000694
695 // Otherwise it must be an element access.
696 unsigned Elt = 0;
697 if (Offset) {
698 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
699 Elt = Offset/EltSize;
700 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
701 }
702 // Return the element extracted out of it.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000703 Value *V = Builder.CreateExtractElement(FromVal, Builder.getInt32(Elt));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000704 if (V->getType() != ToType)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000705 V = Builder.CreateBitCast(V, ToType);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000706 return V;
707 }
Bob Wilson69743022011-01-13 20:59:44 +0000708
Chris Lattner4cc576b2010-04-16 00:24:57 +0000709 // If ToType is a first class aggregate, extract out each of the pieces and
710 // use insertvalue's to form the FCA.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000711 if (StructType *ST = dyn_cast<StructType>(ToType)) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000712 const StructLayout &Layout = *TD.getStructLayout(ST);
713 Value *Res = UndefValue::get(ST);
714 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
715 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
716 Offset+Layout.getElementOffsetInBits(i),
717 Builder);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000718 Res = Builder.CreateInsertValue(Res, Elt, i);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000719 }
720 return Res;
721 }
Bob Wilson69743022011-01-13 20:59:44 +0000722
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000723 if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000724 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
725 Value *Res = UndefValue::get(AT);
726 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
727 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
728 Offset+i*EltSize, Builder);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000729 Res = Builder.CreateInsertValue(Res, Elt, i);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000730 }
731 return Res;
732 }
733
734 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000735 IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Chris Lattner4cc576b2010-04-16 00:24:57 +0000736
737 // If this is a big-endian system and the load is narrower than the
738 // full alloca type, we need to do a shift to get the right bits.
739 int ShAmt = 0;
740 if (TD.isBigEndian()) {
741 // On big-endian machines, the lowest bit is stored at the bit offset
742 // from the pointer given by getTypeStoreSizeInBits. This matters for
743 // integers with a bitwidth that is not a multiple of 8.
744 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
745 TD.getTypeStoreSizeInBits(ToType) - Offset;
746 } else {
747 ShAmt = Offset;
748 }
749
750 // Note: we support negative bitwidths (with shl) which are not defined.
751 // We do this to support (f.e.) loads off the end of a structure where
752 // only some bits are used.
753 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
754 FromVal = Builder.CreateLShr(FromVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +0000755 ConstantInt::get(FromVal->getType(), ShAmt));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000756 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson69743022011-01-13 20:59:44 +0000757 FromVal = Builder.CreateShl(FromVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +0000758 ConstantInt::get(FromVal->getType(), -ShAmt));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000759
760 // Finally, unconditionally truncate the integer to the right width.
761 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
762 if (LIBitWidth < NTy->getBitWidth())
763 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000764 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Benjamin Kramera9390a42011-09-27 20:39:19 +0000765 LIBitWidth));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000766 else if (LIBitWidth > NTy->getBitWidth())
767 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000768 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Benjamin Kramera9390a42011-09-27 20:39:19 +0000769 LIBitWidth));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000770
771 // If the result is an integer, this is a trunc or bitcast.
772 if (ToType->isIntegerTy()) {
773 // Should be done.
774 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
775 // Just do a bitcast, we know the sizes match up.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000776 FromVal = Builder.CreateBitCast(FromVal, ToType);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000777 } else {
778 // Otherwise must be a pointer.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000779 FromVal = Builder.CreateIntToPtr(FromVal, ToType);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000780 }
781 assert(FromVal->getType() == ToType && "Didn't convert right?");
782 return FromVal;
783}
784
785/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
786/// or vector value "Old" at the offset specified by Offset.
787///
788/// This happens when we are converting an "integer union" to a
789/// single integer scalar, or when we are converting a "vector union" to a
790/// vector with insert/extractelement instructions.
791///
792/// Offset is an offset from the original alloca, in bits that need to be
793/// shifted to the right.
794Value *ConvertToScalarInfo::
795ConvertScalar_InsertValue(Value *SV, Value *Old,
796 uint64_t Offset, IRBuilder<> &Builder) {
797 // Convert the stored type to the actual type, shift it left to insert
798 // then 'or' into place.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000799 Type *AllocaType = Old->getType();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000800 LLVMContext &Context = Old->getContext();
801
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000802 if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000803 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
804 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
Bob Wilson69743022011-01-13 20:59:44 +0000805
Chris Lattner4cc576b2010-04-16 00:24:57 +0000806 // Changing the whole vector with memset or with an access of a different
807 // vector type?
Cameron Zwarich446d9522011-10-11 06:10:30 +0000808 if (ValSize == VecSize)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000809 return Builder.CreateBitCast(SV, AllocaType);
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000810
Chris Lattner4cc576b2010-04-16 00:24:57 +0000811 // Must be an element insertion.
Cameron Zwarich90747e32011-10-23 07:02:10 +0000812 Type *EltTy = VTy->getElementType();
813 if (SV->getType() != EltTy)
814 SV = Builder.CreateBitCast(SV, EltTy);
815 uint64_t EltSize = TD.getTypeAllocSizeInBits(EltTy);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000816 unsigned Elt = Offset/EltSize;
Benjamin Kramera9390a42011-09-27 20:39:19 +0000817 return Builder.CreateInsertElement(Old, SV, Builder.getInt32(Elt));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000818 }
Bob Wilson69743022011-01-13 20:59:44 +0000819
Chris Lattner4cc576b2010-04-16 00:24:57 +0000820 // If SV is a first-class aggregate value, insert each value recursively.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000821 if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000822 const StructLayout &Layout = *TD.getStructLayout(ST);
823 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000824 Value *Elt = Builder.CreateExtractValue(SV, i);
Bob Wilson69743022011-01-13 20:59:44 +0000825 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000826 Offset+Layout.getElementOffsetInBits(i),
827 Builder);
828 }
829 return Old;
830 }
Bob Wilson69743022011-01-13 20:59:44 +0000831
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000832 if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000833 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
834 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000835 Value *Elt = Builder.CreateExtractValue(SV, i);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000836 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
837 }
838 return Old;
839 }
840
841 // If SV is a float, convert it to the appropriate integer type.
842 // If it is a pointer, do the same.
843 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
844 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
845 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
846 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
847 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000848 SV = Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(),SrcWidth));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000849 else if (SV->getType()->isPointerTy())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000850 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000851
852 // Zero extend or truncate the value if needed.
853 if (SV->getType() != AllocaType) {
854 if (SV->getType()->getPrimitiveSizeInBits() <
855 AllocaType->getPrimitiveSizeInBits())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000856 SV = Builder.CreateZExt(SV, AllocaType);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000857 else {
858 // Truncation may be needed if storing more than the alloca can hold
859 // (undefined behavior).
Benjamin Kramera9390a42011-09-27 20:39:19 +0000860 SV = Builder.CreateTrunc(SV, AllocaType);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000861 SrcWidth = DestWidth;
862 SrcStoreWidth = DestStoreWidth;
863 }
864 }
865
866 // If this is a big-endian system and the store is narrower than the
867 // full alloca type, we need to do a shift to get the right bits.
868 int ShAmt = 0;
869 if (TD.isBigEndian()) {
870 // On big-endian machines, the lowest bit is stored at the bit offset
871 // from the pointer given by getTypeStoreSizeInBits. This matters for
872 // integers with a bitwidth that is not a multiple of 8.
873 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
874 } else {
875 ShAmt = Offset;
876 }
877
878 // Note: we support negative bitwidths (with shr) which are not defined.
879 // We do this to support (f.e.) stores off the end of a structure where
880 // only some bits in the structure are set.
881 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
882 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000883 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000884 Mask <<= ShAmt;
885 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000886 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000887 Mask = Mask.lshr(-ShAmt);
888 }
889
890 // Mask out the bits we are about to insert from the old value, and or
891 // in the new bits.
892 if (SrcWidth != DestWidth) {
893 assert(DestWidth > SrcWidth);
894 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
895 SV = Builder.CreateOr(Old, SV, "ins");
896 }
897 return SV;
898}
899
900
901//===----------------------------------------------------------------------===//
902// SRoA Driver
903//===----------------------------------------------------------------------===//
904
905
Chris Lattnered7b41e2003-05-27 15:45:27 +0000906bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000907 TD = getAnalysisIfAvailable<TargetData>();
908
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000909 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000910
911 // FIXME: ScalarRepl currently depends on TargetData more than it
912 // theoretically needs to. It should be refactored in order to support
913 // target-independent IR. Until this is done, just skip the actual
914 // scalar-replacement portion of this pass.
915 if (!TD) return Changed;
916
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000917 while (1) {
918 bool LocalChange = performScalarRepl(F);
919 if (!LocalChange) break; // No need to repromote if no scalarrepl
920 Changed = true;
921 LocalChange = performPromotion(F);
922 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
923 }
Chris Lattner38aec322003-09-11 16:45:55 +0000924
925 return Changed;
926}
927
Chris Lattnerd0f56132011-01-14 19:50:47 +0000928namespace {
929class AllocaPromoter : public LoadAndStorePromoter {
930 AllocaInst *AI;
Devang Patel231a5ab2011-07-06 21:09:55 +0000931 DIBuilder *DIB;
Devang Patel4fd3c592011-07-06 22:06:11 +0000932 SmallVector<DbgDeclareInst *, 4> DDIs;
933 SmallVector<DbgValueInst *, 4> DVIs;
Chris Lattnerd0f56132011-01-14 19:50:47 +0000934public:
Cameron Zwarichc8279392011-05-24 03:10:43 +0000935 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
Devang Patel231a5ab2011-07-06 21:09:55 +0000936 DIBuilder *DB)
Devang Patel4fd3c592011-07-06 22:06:11 +0000937 : LoadAndStorePromoter(Insts, S), AI(0), DIB(DB) {}
Chris Lattnerd0f56132011-01-14 19:50:47 +0000938
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000939 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerd0f56132011-01-14 19:50:47 +0000940 // Remember which alloca we're promoting (for isInstInList).
941 this->AI = AI;
Rafael Espindola125ef762011-12-26 23:12:42 +0000942 if (MDNode *DebugNode = MDNode::getIfExists(AI->getContext(), AI)) {
Devang Patel4fd3c592011-07-06 22:06:11 +0000943 for (Value::use_iterator UI = DebugNode->use_begin(),
944 E = DebugNode->use_end(); UI != E; ++UI)
945 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
946 DDIs.push_back(DDI);
947 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
948 DVIs.push_back(DVI);
Rafael Espindola125ef762011-12-26 23:12:42 +0000949 }
Devang Patel4fd3c592011-07-06 22:06:11 +0000950
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000951 LoadAndStorePromoter::run(Insts);
Chris Lattnerd0f56132011-01-14 19:50:47 +0000952 AI->eraseFromParent();
Devang Patel4fd3c592011-07-06 22:06:11 +0000953 for (SmallVector<DbgDeclareInst *, 4>::iterator I = DDIs.begin(),
954 E = DDIs.end(); I != E; ++I) {
955 DbgDeclareInst *DDI = *I;
Devang Patel231a5ab2011-07-06 21:09:55 +0000956 DDI->eraseFromParent();
Devang Patel4fd3c592011-07-06 22:06:11 +0000957 }
958 for (SmallVector<DbgValueInst *, 4>::iterator I = DVIs.begin(),
959 E = DVIs.end(); I != E; ++I) {
960 DbgValueInst *DVI = *I;
961 DVI->eraseFromParent();
962 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000963 }
964
Chris Lattnerd0f56132011-01-14 19:50:47 +0000965 virtual bool isInstInList(Instruction *I,
966 const SmallVectorImpl<Instruction*> &Insts) const {
967 if (LoadInst *LI = dyn_cast<LoadInst>(I))
968 return LI->getOperand(0) == AI;
969 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000970 }
Devang Patel231a5ab2011-07-06 21:09:55 +0000971
Devang Patel4fd3c592011-07-06 22:06:11 +0000972 virtual void updateDebugInfo(Instruction *Inst) const {
973 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
974 E = DDIs.end(); I != E; ++I) {
975 DbgDeclareInst *DDI = *I;
976 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
977 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
978 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
979 ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
980 }
981 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
982 E = DVIs.end(); I != E; ++I) {
983 DbgValueInst *DVI = *I;
Benjamin Kramer6a1c7792012-02-23 17:42:19 +0000984 Value *Arg = NULL;
Devang Patel4fd3c592011-07-06 22:06:11 +0000985 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Devang Patel4fd3c592011-07-06 22:06:11 +0000986 // If an argument is zero extended then use argument directly. The ZExt
987 // may be zapped by an optimization pass in future.
Devang Patel4fd3c592011-07-06 22:06:11 +0000988 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
Benjamin Kramer6a1c7792012-02-23 17:42:19 +0000989 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Devang Patel4fd3c592011-07-06 22:06:11 +0000990 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Benjamin Kramer6a1c7792012-02-23 17:42:19 +0000991 Arg = dyn_cast<Argument>(SExt->getOperand(0));
992 if (!Arg)
993 Arg = SI->getOperand(0);
Devang Patel4fd3c592011-07-06 22:06:11 +0000994 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Benjamin Kramer6a1c7792012-02-23 17:42:19 +0000995 Arg = LI->getOperand(0);
996 } else {
997 continue;
Devang Patel4fd3c592011-07-06 22:06:11 +0000998 }
Benjamin Kramer6a1c7792012-02-23 17:42:19 +0000999 Instruction *DbgVal =
1000 DIB->insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1001 Inst);
1002 DbgVal->setDebugLoc(DVI->getDebugLoc());
Devang Patel4fd3c592011-07-06 22:06:11 +00001003 }
Devang Patel231a5ab2011-07-06 21:09:55 +00001004 }
Chris Lattnerd0f56132011-01-14 19:50:47 +00001005};
1006} // end anon namespace
Chris Lattner38aec322003-09-11 16:45:55 +00001007
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001008/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1009/// subsequently loaded can be rewritten to load both input pointers and then
1010/// select between the result, allowing the load of the alloca to be promoted.
1011/// From this:
1012/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1013/// %V = load i32* %P2
1014/// to:
1015/// %V1 = load i32* %Alloca -> will be mem2reg'd
1016/// %V2 = load i32* %Other
Chris Lattnere3357862011-01-24 01:07:11 +00001017/// %V = select i1 %cond, i32 %V1, i32 %V2
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001018///
1019/// We can do this to a select if its only uses are loads and if the operand to
1020/// the select can be loaded unconditionally.
1021static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
1022 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1023 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1024
1025 for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1026 UI != UE; ++UI) {
1027 LoadInst *LI = dyn_cast<LoadInst>(*UI);
Eli Friedman2bc3d522011-09-12 20:23:13 +00001028 if (LI == 0 || !LI->isSimple()) return false;
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001029
Chris Lattnere3357862011-01-24 01:07:11 +00001030 // Both operands to the select need to be dereferencable, either absolutely
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001031 // (e.g. allocas) or at this point because we can see other accesses to it.
1032 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1033 LI->getAlignment(), TD))
1034 return false;
1035 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1036 LI->getAlignment(), TD))
1037 return false;
1038 }
1039
1040 return true;
1041}
1042
Chris Lattnere3357862011-01-24 01:07:11 +00001043/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1044/// subsequently loaded can be rewritten to load both input pointers in the pred
1045/// blocks and then PHI the results, allowing the load of the alloca to be
1046/// promoted.
1047/// From this:
1048/// %P2 = phi [i32* %Alloca, i32* %Other]
1049/// %V = load i32* %P2
1050/// to:
1051/// %V1 = load i32* %Alloca -> will be mem2reg'd
1052/// ...
1053/// %V2 = load i32* %Other
1054/// ...
1055/// %V = phi [i32 %V1, i32 %V2]
1056///
1057/// We can do this to a select if its only uses are loads and if the operand to
1058/// the select can be loaded unconditionally.
1059static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
1060 // For now, we can only do this promotion if the load is in the same block as
1061 // the PHI, and if there are no stores between the phi and load.
1062 // TODO: Allow recursive phi users.
1063 // TODO: Allow stores.
1064 BasicBlock *BB = PN->getParent();
1065 unsigned MaxAlign = 0;
1066 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1067 UI != UE; ++UI) {
1068 LoadInst *LI = dyn_cast<LoadInst>(*UI);
Eli Friedman2bc3d522011-09-12 20:23:13 +00001069 if (LI == 0 || !LI->isSimple()) return false;
Chris Lattnere3357862011-01-24 01:07:11 +00001070
1071 // For now we only allow loads in the same block as the PHI. This is a
1072 // common case that happens when instcombine merges two loads through a PHI.
1073 if (LI->getParent() != BB) return false;
1074
1075 // Ensure that there are no instructions between the PHI and the load that
1076 // could store.
1077 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1078 if (BBI->mayWriteToMemory())
1079 return false;
1080
1081 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1082 }
1083
1084 // Okay, we know that we have one or more loads in the same block as the PHI.
1085 // We can transform this if it is safe to push the loads into the predecessor
1086 // blocks. The only thing to watch out for is that we can't put a possibly
1087 // trapping load in the predecessor if it is a critical edge.
1088 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1089 BasicBlock *Pred = PN->getIncomingBlock(i);
Eli Friedmand102a032011-09-22 18:56:30 +00001090 Value *InVal = PN->getIncomingValue(i);
1091
1092 // If the terminator of the predecessor has side-effects (an invoke),
1093 // there is no safe place to put a load in the predecessor.
1094 if (Pred->getTerminator()->mayHaveSideEffects())
1095 return false;
1096
1097 // If the value is produced by the terminator of the predecessor
1098 // (an invoke), there is no valid place to put a load in the predecessor.
1099 if (Pred->getTerminator() == InVal)
1100 return false;
Chris Lattnere3357862011-01-24 01:07:11 +00001101
1102 // If the predecessor has a single successor, then the edge isn't critical.
1103 if (Pred->getTerminator()->getNumSuccessors() == 1)
1104 continue;
Chris Lattnere3357862011-01-24 01:07:11 +00001105
1106 // If this pointer is always safe to load, or if we can prove that there is
1107 // already a load in the block, then we can move the load to the pred block.
1108 if (InVal->isDereferenceablePointer() ||
1109 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1110 continue;
1111
1112 return false;
1113 }
1114
1115 return true;
1116}
1117
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001118
1119/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1120/// direct (non-volatile) loads and stores to it. If the alloca is close but
1121/// not quite there, this will transform the code to allow promotion. As such,
1122/// it is a non-pure predicate.
1123static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
1124 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1125 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1126
1127 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1128 UI != UE; ++UI) {
1129 User *U = *UI;
1130 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Eli Friedman2bc3d522011-09-12 20:23:13 +00001131 if (!LI->isSimple())
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001132 return false;
1133 continue;
1134 }
1135
1136 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Eli Friedman2bc3d522011-09-12 20:23:13 +00001137 if (SI->getOperand(0) == AI || !SI->isSimple())
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001138 return false; // Don't allow a store OF the AI, only INTO the AI.
1139 continue;
1140 }
1141
1142 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1143 // If the condition being selected on is a constant, fold the select, yes
1144 // this does (rarely) happen early on.
1145 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1146 Value *Result = SI->getOperand(1+CI->isZero());
1147 SI->replaceAllUsesWith(Result);
1148 SI->eraseFromParent();
1149
1150 // This is very rare and we just scrambled the use list of AI, start
1151 // over completely.
1152 return tryToMakeAllocaBePromotable(AI, TD);
1153 }
1154
1155 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1156 // loads, then we can transform this by rewriting the select.
1157 if (!isSafeSelectToSpeculate(SI, TD))
1158 return false;
1159
1160 InstsToRewrite.insert(SI);
1161 continue;
1162 }
1163
Chris Lattnere3357862011-01-24 01:07:11 +00001164 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1165 if (PN->use_empty()) { // Dead PHIs can be stripped.
1166 InstsToRewrite.insert(PN);
1167 continue;
1168 }
1169
1170 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1171 // in the pred blocks, then we can transform this by rewriting the PHI.
1172 if (!isSafePHIToSpeculate(PN, TD))
1173 return false;
1174
1175 InstsToRewrite.insert(PN);
1176 continue;
1177 }
1178
Nick Lewycky5a1cb642011-07-25 23:14:22 +00001179 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1180 if (onlyUsedByLifetimeMarkers(BCI)) {
1181 InstsToRewrite.insert(BCI);
1182 continue;
1183 }
1184 }
1185
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001186 return false;
1187 }
1188
1189 // If there are no instructions to rewrite, then all uses are load/stores and
1190 // we're done!
1191 if (InstsToRewrite.empty())
1192 return true;
1193
1194 // If we have instructions that need to be rewritten for this to be promotable
1195 // take care of it now.
1196 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
Nick Lewycky5a1cb642011-07-25 23:14:22 +00001197 if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
1198 // This could only be a bitcast used by nothing but lifetime intrinsics.
1199 for (BitCastInst::use_iterator I = BCI->use_begin(), E = BCI->use_end();
1200 I != E;) {
1201 Use &U = I.getUse();
1202 ++I;
1203 cast<Instruction>(U.getUser())->eraseFromParent();
1204 }
1205 BCI->eraseFromParent();
1206 continue;
1207 }
1208
Chris Lattnere3357862011-01-24 01:07:11 +00001209 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1210 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1211 // loads with a new select.
1212 while (!SI->use_empty()) {
1213 LoadInst *LI = cast<LoadInst>(SI->use_back());
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001214
Chris Lattnere3357862011-01-24 01:07:11 +00001215 IRBuilder<> Builder(LI);
1216 LoadInst *TrueLoad =
1217 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1218 LoadInst *FalseLoad =
Nick Lewycky394d1f12011-07-01 06:27:03 +00001219 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
Chris Lattnere3357862011-01-24 01:07:11 +00001220
1221 // Transfer alignment and TBAA info if present.
1222 TrueLoad->setAlignment(LI->getAlignment());
1223 FalseLoad->setAlignment(LI->getAlignment());
1224 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1225 TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1226 FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1227 }
1228
1229 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1230 V->takeName(LI);
1231 LI->replaceAllUsesWith(V);
1232 LI->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001233 }
Chris Lattnere3357862011-01-24 01:07:11 +00001234
1235 // Now that all the loads are gone, the select is gone too.
1236 SI->eraseFromParent();
1237 continue;
1238 }
1239
1240 // Otherwise, we have a PHI node which allows us to push the loads into the
1241 // predecessors.
1242 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1243 if (PN->use_empty()) {
1244 PN->eraseFromParent();
1245 continue;
1246 }
1247
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001248 Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
Jay Foad3ecfc862011-03-30 11:28:46 +00001249 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1250 PN->getName()+".ld", PN);
Chris Lattnere3357862011-01-24 01:07:11 +00001251
1252 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1253 // matter which one we get and if any differ, it doesn't matter.
1254 LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1255 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1256 unsigned Align = SomeLoad->getAlignment();
1257
1258 // Rewrite all loads of the PN to use the new PHI.
1259 while (!PN->use_empty()) {
1260 LoadInst *LI = cast<LoadInst>(PN->use_back());
1261 LI->replaceAllUsesWith(NewPN);
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001262 LI->eraseFromParent();
1263 }
1264
Chris Lattnere3357862011-01-24 01:07:11 +00001265 // Inject loads into all of the pred blocks. Keep track of which blocks we
1266 // insert them into in case we have multiple edges from the same block.
1267 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1268
1269 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1270 BasicBlock *Pred = PN->getIncomingBlock(i);
1271 LoadInst *&Load = InsertedLoads[Pred];
1272 if (Load == 0) {
1273 Load = new LoadInst(PN->getIncomingValue(i),
1274 PN->getName() + "." + Pred->getName(),
1275 Pred->getTerminator());
1276 Load->setAlignment(Align);
1277 if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1278 }
1279
1280 NewPN->addIncoming(Load, Pred);
1281 }
1282
1283 PN->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001284 }
1285
1286 ++NumAdjusted;
1287 return true;
1288}
1289
Chris Lattner38aec322003-09-11 16:45:55 +00001290bool SROA::performPromotion(Function &F) {
1291 std::vector<AllocaInst*> Allocas;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001292 DominatorTree *DT = 0;
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001293 if (HasDomTree)
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001294 DT = &getAnalysis<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +00001295
Chris Lattner02a3be02003-09-20 14:39:18 +00001296 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Devang Patel231a5ab2011-07-06 21:09:55 +00001297 DIBuilder DIB(*F.getParent());
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001298 bool Changed = false;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001299 SmallVector<Instruction*, 64> Insts;
Chris Lattner38aec322003-09-11 16:45:55 +00001300 while (1) {
1301 Allocas.clear();
1302
1303 // Find allocas that are safe to promote, by looking at all instructions in
1304 // the entry node
1305 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1306 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001307 if (tryToMakeAllocaBePromotable(AI, TD))
Chris Lattner38aec322003-09-11 16:45:55 +00001308 Allocas.push_back(AI);
1309
1310 if (Allocas.empty()) break;
1311
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001312 if (HasDomTree)
Cameron Zwarich419e8a62011-01-17 17:38:41 +00001313 PromoteMemToReg(Allocas, *DT);
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001314 else {
1315 SSAUpdater SSA;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001316 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1317 AllocaInst *AI = Allocas[i];
1318
1319 // Build list of instructions to promote.
1320 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1321 UI != E; ++UI)
1322 Insts.push_back(cast<Instruction>(*UI));
Devang Patel231a5ab2011-07-06 21:09:55 +00001323 AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001324 Insts.clear();
1325 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001326 }
Chris Lattner38aec322003-09-11 16:45:55 +00001327 NumPromoted += Allocas.size();
1328 Changed = true;
1329 }
1330
1331 return Changed;
1332}
1333
Chris Lattner4cc576b2010-04-16 00:24:57 +00001334
Bob Wilson3992feb2010-02-03 17:23:56 +00001335/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1336/// SROA. It must be a struct or array type with a small number of elements.
1337static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001338 Type *T = AI->getAllocatedType();
Bob Wilson3992feb2010-02-03 17:23:56 +00001339 // Do not promote any struct into more than 32 separate vars.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001340 if (StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +00001341 return ST->getNumElements() <= 32;
1342 // Arrays are much less likely to be safe for SROA; only consider
1343 // them if they are very small.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001344 if (ArrayType *AT = dyn_cast<ArrayType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +00001345 return AT->getNumElements() <= 8;
1346 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +00001347}
1348
Chris Lattnerc4472072010-04-15 23:50:26 +00001349
Chris Lattner38aec322003-09-11 16:45:55 +00001350// performScalarRepl - This algorithm is a simple worklist driven algorithm,
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001351// which runs on all of the alloca instructions in the function, removing them
1352// if they are only used by getelementptr instructions.
Chris Lattner38aec322003-09-11 16:45:55 +00001353//
1354bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001355 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +00001356
Chris Lattner31d80102010-04-15 21:59:20 +00001357 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +00001358 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001359 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +00001360 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +00001361 WorkList.push_back(A);
1362
1363 // Process the worklist
1364 bool Changed = false;
1365 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001366 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001367 WorkList.pop_back();
Bob Wilson69743022011-01-13 20:59:44 +00001368
Chris Lattneradd2bd72006-12-22 23:14:42 +00001369 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1370 // with unused elements.
1371 if (AI->use_empty()) {
1372 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +00001373 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +00001374 continue;
1375 }
Chris Lattner7809ecd2009-02-03 01:30:09 +00001376
1377 // If this alloca is impossible for us to promote, reject it early.
1378 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1379 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001380
Chris Lattner79b3bd32007-04-25 06:40:51 +00001381 // Check to see if this allocation is only modified by a memcpy/memmove from
1382 // a constant global. If this is the case, we can change all users to use
1383 // the constant global instead. This is commonly produced by the CFE by
1384 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1385 // is only subsequently read.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001386 SmallVector<Instruction *, 4> ToDelete;
1387 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(AI, ToDelete)) {
David Greene504c7d82010-01-05 01:27:09 +00001388 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001389 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
1390 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
1391 ToDelete[i]->eraseFromParent();
1392 Constant *TheSrc = cast<Constant>(Copy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001393 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001394 Copy->eraseFromParent(); // Don't mutate the global.
Chris Lattner79b3bd32007-04-25 06:40:51 +00001395 AI->eraseFromParent();
1396 ++NumGlobals;
1397 Changed = true;
1398 continue;
1399 }
Bob Wilson69743022011-01-13 20:59:44 +00001400
Chris Lattner7809ecd2009-02-03 01:30:09 +00001401 // Check to see if we can perform the core SROA transformation. We cannot
1402 // transform the allocation instruction if it is an array allocation
1403 // (allocations OF arrays are ok though), and an allocation of a scalar
1404 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +00001405 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +00001406
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +00001407 // Do not promote [0 x %struct].
1408 if (AllocaSize == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001409
Chris Lattner31d80102010-04-15 21:59:20 +00001410 // Do not promote any struct whose size is too big.
1411 if (AllocaSize > SRThreshold) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001412
Bob Wilson3992feb2010-02-03 17:23:56 +00001413 // If the alloca looks like a good candidate for scalar replacement, and if
1414 // all its users can be transformed, then split up the aggregate into its
1415 // separate elements.
1416 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1417 DoScalarReplacement(AI, WorkList);
1418 Changed = true;
1419 continue;
1420 }
1421
Chris Lattner6e733d32009-01-28 20:16:43 +00001422 // If we can turn this aggregate value (potentially with casts) into a
1423 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001424 // IsNotTrivial tracks whether this is something that mem2reg could have
1425 // promoted itself. If so, we don't want to transform it needlessly. Note
1426 // that we can't just check based on the type: the alloca may be of an i32
1427 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +00001428 if (AllocaInst *NewAI =
1429 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001430 NewAI->takeName(AI);
1431 AI->eraseFromParent();
1432 ++NumConverted;
1433 Changed = true;
1434 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001435 }
1436
Chris Lattner7809ecd2009-02-03 01:30:09 +00001437 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +00001438 }
1439
1440 return Changed;
1441}
Chris Lattner5e062a12003-05-30 04:15:41 +00001442
Chris Lattnera10b29b2007-04-25 05:02:56 +00001443/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1444/// predicate, do SROA now.
Bob Wilson69743022011-01-13 20:59:44 +00001445void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001446 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +00001447 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +00001448 SmallVector<AllocaInst*, 32> ElementAllocas;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001449 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
Chris Lattnera10b29b2007-04-25 05:02:56 +00001450 ElementAllocas.reserve(ST->getNumContainedTypes());
1451 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Bob Wilson69743022011-01-13 20:59:44 +00001452 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +00001453 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001454 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001455 ElementAllocas.push_back(NA);
1456 WorkList.push_back(NA); // Add to worklist for recursive processing
1457 }
1458 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001459 ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
Chris Lattnera10b29b2007-04-25 05:02:56 +00001460 ElementAllocas.reserve(AT->getNumElements());
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001461 Type *ElTy = AT->getElementType();
Chris Lattnera10b29b2007-04-25 05:02:56 +00001462 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +00001463 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001464 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001465 ElementAllocas.push_back(NA);
1466 WorkList.push_back(NA); // Add to worklist for recursive processing
1467 }
1468 }
1469
Bob Wilsonb742def2009-12-18 20:14:40 +00001470 // Now that we have created the new alloca instructions, rewrite all the
1471 // uses of the old alloca.
1472 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +00001473
Bob Wilsonb742def2009-12-18 20:14:40 +00001474 // Now erase any instructions that were made dead while rewriting the alloca.
1475 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +00001476 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +00001477
Dan Gohmanfe601042010-06-22 15:08:57 +00001478 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +00001479}
Chris Lattnera59adc42009-12-14 05:11:02 +00001480
Bob Wilsonb742def2009-12-18 20:14:40 +00001481/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1482/// recursively including all their operands that become trivially dead.
1483void SROA::DeleteDeadInstructions() {
1484 while (!DeadInsts.empty()) {
1485 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +00001486
Bob Wilsonb742def2009-12-18 20:14:40 +00001487 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1488 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1489 // Zero out the operand and see if it becomes trivially dead.
1490 // (But, don't add allocas to the dead instruction list -- they are
1491 // already on the worklist and will be deleted separately.)
1492 *OI = 0;
1493 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1494 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +00001495 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001496
1497 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +00001498 }
Chris Lattnera59adc42009-12-14 05:11:02 +00001499}
Bob Wilson69743022011-01-13 20:59:44 +00001500
Bob Wilsonb742def2009-12-18 20:14:40 +00001501/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1502/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001503/// the Info parameter. Offset indicates the position within AI that is
1504/// referenced by this instruction.
Chris Lattner6c95d242011-01-23 07:29:29 +00001505void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001506 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001507 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1508 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +00001509
Bob Wilsonb742def2009-12-18 20:14:40 +00001510 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Chris Lattner6c95d242011-01-23 07:29:29 +00001511 isSafeForScalarRepl(BC, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001512 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001513 uint64_t GEPOffset = Offset;
Chris Lattner6c95d242011-01-23 07:29:29 +00001514 isSafeGEP(GEPI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001515 if (!Info.isUnsafe)
Chris Lattner6c95d242011-01-23 07:29:29 +00001516 isSafeForScalarRepl(GEPI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001517 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001518 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001519 if (Length == 0)
1520 return MarkUnsafe(Info, User);
Aaron Ballman7e2fa312012-03-15 00:05:31 +00001521 if (Length->isNegative())
1522 return MarkUnsafe(Info, User);
1523
Chris Lattner6c95d242011-01-23 07:29:29 +00001524 isSafeMemAccess(Offset, Length->getZExtValue(), 0,
Chris Lattner145c5322011-01-23 08:27:54 +00001525 UI.getOperandNo() == 0, Info, MI,
1526 true /*AllowWholeAccess*/);
Bob Wilsonb742def2009-12-18 20:14:40 +00001527 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Eli Friedman2bc3d522011-09-12 20:23:13 +00001528 if (!LI->isSimple())
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001529 return MarkUnsafe(Info, User);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001530 Type *LIType = LI->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001531 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001532 LIType, false, Info, LI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001533 Info.hasALoadOrStore = true;
1534
Bob Wilsonb742def2009-12-18 20:14:40 +00001535 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1536 // Store is ok if storing INTO the pointer, not storing the pointer
Eli Friedman2bc3d522011-09-12 20:23:13 +00001537 if (!SI->isSimple() || SI->getOperand(0) == I)
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001538 return MarkUnsafe(Info, User);
1539
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001540 Type *SIType = SI->getOperand(0)->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001541 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001542 SIType, true, Info, SI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001543 Info.hasALoadOrStore = true;
Nick Lewycky5a1cb642011-07-25 23:14:22 +00001544 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1545 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1546 II->getIntrinsicID() != Intrinsic::lifetime_end)
1547 return MarkUnsafe(Info, User);
Chris Lattner145c5322011-01-23 08:27:54 +00001548 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1549 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1550 } else {
1551 return MarkUnsafe(Info, User);
1552 }
1553 if (Info.isUnsafe) return;
1554 }
1555}
1556
1557
1558/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1559/// derived from the alloca, we can often still split the alloca into elements.
1560/// This is useful if we have a large alloca where one element is phi'd
1561/// together somewhere: we can SRoA and promote all the other elements even if
1562/// we end up not being able to promote this one.
1563///
1564/// All we require is that the uses of the PHI do not index into other parts of
1565/// the alloca. The most important use case for this is single load and stores
1566/// that are PHI'd together, which can happen due to code sinking.
1567void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1568 AllocaInfo &Info) {
1569 // If we've already checked this PHI, don't do it again.
1570 if (PHINode *PN = dyn_cast<PHINode>(I))
1571 if (!Info.CheckedPHIs.insert(PN))
1572 return;
1573
1574 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1575 Instruction *User = cast<Instruction>(*UI);
1576
1577 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1578 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1579 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1580 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1581 // but would have to prove that we're staying inside of an element being
1582 // promoted.
1583 if (!GEPI->hasAllZeroIndices())
1584 return MarkUnsafe(Info, User);
1585 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1586 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Eli Friedman2bc3d522011-09-12 20:23:13 +00001587 if (!LI->isSimple())
Chris Lattner145c5322011-01-23 08:27:54 +00001588 return MarkUnsafe(Info, User);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001589 Type *LIType = LI->getType();
Chris Lattner145c5322011-01-23 08:27:54 +00001590 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1591 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1592 Info.hasALoadOrStore = true;
1593
1594 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1595 // Store is ok if storing INTO the pointer, not storing the pointer
Eli Friedman2bc3d522011-09-12 20:23:13 +00001596 if (!SI->isSimple() || SI->getOperand(0) == I)
Chris Lattner145c5322011-01-23 08:27:54 +00001597 return MarkUnsafe(Info, User);
1598
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001599 Type *SIType = SI->getOperand(0)->getType();
Chris Lattner145c5322011-01-23 08:27:54 +00001600 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1601 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1602 Info.hasALoadOrStore = true;
1603 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1604 isSafePHISelectUseForScalarRepl(User, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001605 } else {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001606 return MarkUnsafe(Info, User);
Bob Wilsonb742def2009-12-18 20:14:40 +00001607 }
1608 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001609 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001610}
Bob Wilson39c88a62009-12-17 18:34:24 +00001611
Bob Wilsonb742def2009-12-18 20:14:40 +00001612/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1613/// replacement. It is safe when all the indices are constant, in-bounds
1614/// references, and when the resulting offset corresponds to an element within
1615/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001616/// return, Offset is adjusted as specified by the GEP indices.
Chris Lattner6c95d242011-01-23 07:29:29 +00001617void SROA::isSafeGEP(GetElementPtrInst *GEPI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001618 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001619 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1620 if (GEPIt == E)
1621 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001622
Chris Lattner88e6dc82008-08-23 05:21:06 +00001623 // Walk through the GEP type indices, checking the types that this indexes
1624 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001625 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001626 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001627 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001628 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001629
Bob Wilsonb742def2009-12-18 20:14:40 +00001630 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1631 if (!IdxVal)
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001632 return MarkUnsafe(Info, GEPI);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001633 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001634
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001635 // Compute the offset due to this GEP and check if the alloca has a
1636 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001637 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
Jay Foad8fbbb392011-07-19 14:01:37 +00001638 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
Chris Lattner6c95d242011-01-23 07:29:29 +00001639 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001640 MarkUnsafe(Info, GEPI);
Chris Lattner5e062a12003-05-30 04:15:41 +00001641}
1642
Bob Wilson704d1342011-01-13 17:45:11 +00001643/// isHomogeneousAggregate - Check if type T is a struct or array containing
1644/// elements of the same type (which is always true for arrays). If so,
1645/// return true with NumElts and EltTy set to the number of elements and the
1646/// element type, respectively.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001647static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
1648 Type *&EltTy) {
1649 if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
Bob Wilson704d1342011-01-13 17:45:11 +00001650 NumElts = AT->getNumElements();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001651 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
Bob Wilson704d1342011-01-13 17:45:11 +00001652 return true;
1653 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001654 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilson704d1342011-01-13 17:45:11 +00001655 NumElts = ST->getNumContainedTypes();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001656 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
Bob Wilson704d1342011-01-13 17:45:11 +00001657 for (unsigned n = 1; n < NumElts; ++n) {
1658 if (ST->getContainedType(n) != EltTy)
1659 return false;
1660 }
1661 return true;
1662 }
1663 return false;
1664}
1665
1666/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1667/// "homogeneous" aggregates with the same element type and number of elements.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001668static bool isCompatibleAggregate(Type *T1, Type *T2) {
Bob Wilson704d1342011-01-13 17:45:11 +00001669 if (T1 == T2)
1670 return true;
1671
1672 unsigned NumElts1, NumElts2;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001673 Type *EltTy1, *EltTy2;
Bob Wilson704d1342011-01-13 17:45:11 +00001674 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1675 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1676 NumElts1 == NumElts2 &&
1677 EltTy1 == EltTy2)
1678 return true;
1679
1680 return false;
1681}
1682
Bob Wilsonb742def2009-12-18 20:14:40 +00001683/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1684/// alloca or has an offset and size that corresponds to a component element
1685/// within it. The offset checked here may have been formed from a GEP with a
1686/// pointer bitcasted to a different type.
Chris Lattner145c5322011-01-23 08:27:54 +00001687///
1688/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1689/// unit. If false, it only allows accesses known to be in a single element.
Chris Lattner6c95d242011-01-23 07:29:29 +00001690void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001691 Type *MemOpType, bool isStore,
Chris Lattner145c5322011-01-23 08:27:54 +00001692 AllocaInfo &Info, Instruction *TheAccess,
1693 bool AllowWholeAccess) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001694 // Check if this is a load/store of the entire alloca.
Chris Lattner145c5322011-01-23 08:27:54 +00001695 if (Offset == 0 && AllowWholeAccess &&
Chris Lattner6c95d242011-01-23 07:29:29 +00001696 MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
Bob Wilson704d1342011-01-13 17:45:11 +00001697 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1698 // loads/stores (which are essentially the same as the MemIntrinsics with
1699 // regard to copying padding between elements). But, if an alloca is
1700 // flagged as both a source and destination of such operations, we'll need
1701 // to check later for padding between elements.
1702 if (!MemOpType || MemOpType->isIntegerTy()) {
1703 if (isStore)
1704 Info.isMemCpyDst = true;
1705 else
1706 Info.isMemCpySrc = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001707 return;
1708 }
Bob Wilson704d1342011-01-13 17:45:11 +00001709 // This is also safe for references using a type that is compatible with
1710 // the type of the alloca, so that loads/stores can be rewritten using
1711 // insertvalue/extractvalue.
Chris Lattner6c95d242011-01-23 07:29:29 +00001712 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
Chris Lattner7e9b4272011-01-16 06:18:28 +00001713 Info.hasSubelementAccess = true;
Bob Wilson704d1342011-01-13 17:45:11 +00001714 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001715 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001716 }
1717 // Check if the offset/size correspond to a component within the alloca type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001718 Type *T = Info.AI->getAllocatedType();
Chris Lattner7e9b4272011-01-16 06:18:28 +00001719 if (TypeHasComponent(T, Offset, MemSize)) {
1720 Info.hasSubelementAccess = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001721 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001722 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001723
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001724 return MarkUnsafe(Info, TheAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +00001725}
1726
1727/// TypeHasComponent - Return true if T has a component type with the
1728/// specified offset and size. If Size is zero, do not check the size.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001729bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) {
1730 Type *EltTy;
Bob Wilsonb742def2009-12-18 20:14:40 +00001731 uint64_t EltSize;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001732 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001733 const StructLayout *Layout = TD->getStructLayout(ST);
1734 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1735 EltTy = ST->getContainedType(EltIdx);
1736 EltSize = TD->getTypeAllocSize(EltTy);
1737 Offset -= Layout->getElementOffset(EltIdx);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001738 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001739 EltTy = AT->getElementType();
1740 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001741 if (Offset >= AT->getNumElements() * EltSize)
1742 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001743 Offset %= EltSize;
1744 } else {
1745 return false;
1746 }
1747 if (Offset == 0 && (Size == 0 || EltSize == Size))
1748 return true;
1749 // Check if the component spans multiple elements.
1750 if (Offset + Size > EltSize)
1751 return false;
1752 return TypeHasComponent(EltTy, Offset, Size);
1753}
1754
1755/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1756/// the instruction I, which references it, to use the separate elements.
1757/// Offset indicates the position within AI that is referenced by this
1758/// instruction.
1759void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1760 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner145c5322011-01-23 08:27:54 +00001761 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1762 Use &TheUse = UI.getUse();
1763 Instruction *User = cast<Instruction>(*UI++);
Bob Wilsonb742def2009-12-18 20:14:40 +00001764
1765 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1766 RewriteBitCast(BC, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001767 continue;
1768 }
1769
1770 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001771 RewriteGEP(GEPI, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001772 continue;
1773 }
1774
1775 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001776 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1777 uint64_t MemSize = Length->getZExtValue();
1778 if (Offset == 0 &&
1779 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1780 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001781 // Otherwise the intrinsic can only touch a single element and the
1782 // address operand will be updated, so nothing else needs to be done.
Chris Lattner145c5322011-01-23 08:27:54 +00001783 continue;
1784 }
Nick Lewycky5a1cb642011-07-25 23:14:22 +00001785
1786 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1787 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1788 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1789 RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
1790 }
1791 continue;
1792 }
Chris Lattner145c5322011-01-23 08:27:54 +00001793
1794 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001795 Type *LIType = LI->getType();
Chris Lattner192228e2011-01-16 05:28:59 +00001796
Bob Wilson704d1342011-01-13 17:45:11 +00001797 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001798 // Replace:
1799 // %res = load { i32, i32 }* %alloc
1800 // with:
1801 // %load.0 = load i32* %alloc.0
1802 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1803 // %load.1 = load i32* %alloc.1
1804 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1805 // (Also works for arrays instead of structs)
1806 Value *Insert = UndefValue::get(LIType);
Devang Patelabb25122011-06-03 19:46:19 +00001807 IRBuilder<> Builder(LI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001808 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patelabb25122011-06-03 19:46:19 +00001809 Value *Load = Builder.CreateLoad(NewElts[i], "load");
1810 Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
Bob Wilsonb742def2009-12-18 20:14:40 +00001811 }
1812 LI->replaceAllUsesWith(Insert);
1813 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001814 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001815 TD->getTypeAllocSize(LIType) ==
1816 TD->getTypeAllocSize(AI->getAllocatedType())) {
1817 // If this is a load of the entire alloca to an integer, rewrite it.
1818 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1819 }
Chris Lattner145c5322011-01-23 08:27:54 +00001820 continue;
1821 }
1822
1823 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001824 Value *Val = SI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001825 Type *SIType = Val->getType();
Bob Wilson704d1342011-01-13 17:45:11 +00001826 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001827 // Replace:
1828 // store { i32, i32 } %val, { i32, i32 }* %alloc
1829 // with:
1830 // %val.0 = extractvalue { i32, i32 } %val, 0
1831 // store i32 %val.0, i32* %alloc.0
1832 // %val.1 = extractvalue { i32, i32 } %val, 1
1833 // store i32 %val.1, i32* %alloc.1
1834 // (Also works for arrays instead of structs)
Devang Patelabb25122011-06-03 19:46:19 +00001835 IRBuilder<> Builder(SI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001836 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patelabb25122011-06-03 19:46:19 +00001837 Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1838 Builder.CreateStore(Extract, NewElts[i]);
Bob Wilsonb742def2009-12-18 20:14:40 +00001839 }
1840 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001841 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001842 TD->getTypeAllocSize(SIType) ==
1843 TD->getTypeAllocSize(AI->getAllocatedType())) {
1844 // If this is a store of the entire alloca from an integer, rewrite it.
1845 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1846 }
Chris Lattner145c5322011-01-23 08:27:54 +00001847 continue;
1848 }
1849
1850 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1851 // If we have a PHI user of the alloca itself (as opposed to a GEP or
1852 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1853 // the new pointer.
1854 if (!isa<AllocaInst>(I)) continue;
1855
1856 assert(Offset == 0 && NewElts[0] &&
1857 "Direct alloca use should have a zero offset");
1858
1859 // If we have a use of the alloca, we know the derived uses will be
1860 // utilizing just the first element of the scalarized result. Insert a
1861 // bitcast of the first alloca before the user as required.
1862 AllocaInst *NewAI = NewElts[0];
1863 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1864 NewAI->moveBefore(BCI);
1865 TheUse = BCI;
1866 continue;
Bob Wilsonb742def2009-12-18 20:14:40 +00001867 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001868 }
1869}
1870
Bob Wilsonb742def2009-12-18 20:14:40 +00001871/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1872/// and recursively continue updating all of its uses.
1873void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1874 SmallVector<AllocaInst*, 32> &NewElts) {
1875 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1876 if (BC->getOperand(0) != AI)
1877 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001878
Bob Wilsonb742def2009-12-18 20:14:40 +00001879 // The bitcast references the original alloca. Replace its uses with
Eli Friedman75f69e32011-11-12 02:07:50 +00001880 // references to the alloca containing offset zero (which is normally at
1881 // index zero, but might not be in cases involving structs with elements
1882 // of size zero).
1883 Type *T = AI->getAllocatedType();
1884 uint64_t EltOffset = 0;
1885 Type *IdxTy;
1886 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1887 Instruction *Val = NewElts[Idx];
Bob Wilsonb742def2009-12-18 20:14:40 +00001888 if (Val->getType() != BC->getDestTy()) {
1889 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1890 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001891 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001892 BC->replaceAllUsesWith(Val);
1893 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001894}
1895
Bob Wilsonb742def2009-12-18 20:14:40 +00001896/// FindElementAndOffset - Return the index of the element containing Offset
1897/// within the specified type, which must be either a struct or an array.
1898/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001899/// element. IdxTy is set to the type of the index result to be used in a
1900/// GEP instruction.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001901uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset,
1902 Type *&IdxTy) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001903 uint64_t Idx = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001904 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001905 const StructLayout *Layout = TD->getStructLayout(ST);
1906 Idx = Layout->getElementContainingOffset(Offset);
1907 T = ST->getContainedType(Idx);
1908 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001909 IdxTy = Type::getInt32Ty(T->getContext());
1910 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001911 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001912 ArrayType *AT = cast<ArrayType>(T);
Bob Wilsone88728d2009-12-19 06:53:17 +00001913 T = AT->getElementType();
1914 uint64_t EltSize = TD->getTypeAllocSize(T);
1915 Idx = Offset / EltSize;
1916 Offset -= Idx * EltSize;
1917 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001918 return Idx;
1919}
1920
1921/// RewriteGEP - Check if this GEP instruction moves the pointer across
1922/// elements of the alloca that are being split apart, and if so, rewrite
1923/// the GEP to be relative to the new element.
1924void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1925 SmallVector<AllocaInst*, 32> &NewElts) {
1926 uint64_t OldOffset = Offset;
1927 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
Jay Foad8fbbb392011-07-19 14:01:37 +00001928 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
Bob Wilsonb742def2009-12-18 20:14:40 +00001929
1930 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1931
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001932 Type *T = AI->getAllocatedType();
1933 Type *IdxTy;
Bob Wilsone88728d2009-12-19 06:53:17 +00001934 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001935 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001936 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001937
1938 T = AI->getAllocatedType();
1939 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001940 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001941
1942 // If this GEP does not move the pointer across elements of the alloca
1943 // being split, then it does not needs to be rewritten.
1944 if (Idx == OldIdx)
1945 return;
1946
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001947 Type *i32Ty = Type::getInt32Ty(AI->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001948 SmallVector<Value*, 8> NewArgs;
1949 NewArgs.push_back(Constant::getNullValue(i32Ty));
1950 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001951 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1952 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00001953 }
1954 Instruction *Val = NewElts[Idx];
1955 if (NewArgs.size() > 1) {
Jay Foada9203102011-07-25 09:48:08 +00001956 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001957 Val->takeName(GEPI);
1958 }
1959 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001960 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001961 GEPI->replaceAllUsesWith(Val);
1962 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001963}
1964
Nick Lewycky5a1cb642011-07-25 23:14:22 +00001965/// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
1966/// to mark the lifetime of the scalarized memory.
1967void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
1968 uint64_t Offset,
1969 SmallVector<AllocaInst*, 32> &NewElts) {
1970 ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
1971 // Put matching lifetime markers on everything from Offset up to
1972 // Offset+OldSize.
1973 Type *AIType = AI->getAllocatedType();
1974 uint64_t NewOffset = Offset;
1975 Type *IdxTy;
1976 uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy);
1977
1978 IRBuilder<> Builder(II);
1979 uint64_t Size = OldSize->getLimitedValue();
1980
1981 if (NewOffset) {
1982 // Splice the first element and index 'NewOffset' bytes in. SROA will
1983 // split the alloca again later.
1984 Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy());
1985 V = Builder.CreateGEP(V, Builder.getInt64(NewOffset));
1986
1987 IdxTy = NewElts[Idx]->getAllocatedType();
1988 uint64_t EltSize = TD->getTypeAllocSize(IdxTy) - NewOffset;
1989 if (EltSize > Size) {
1990 EltSize = Size;
1991 Size = 0;
1992 } else {
1993 Size -= EltSize;
1994 }
1995 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1996 Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
1997 else
1998 Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
1999 ++Idx;
2000 }
2001
2002 for (; Idx != NewElts.size() && Size; ++Idx) {
2003 IdxTy = NewElts[Idx]->getAllocatedType();
2004 uint64_t EltSize = TD->getTypeAllocSize(IdxTy);
2005 if (EltSize > Size) {
2006 EltSize = Size;
2007 Size = 0;
2008 } else {
2009 Size -= EltSize;
2010 }
2011 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2012 Builder.CreateLifetimeStart(NewElts[Idx],
2013 Builder.getInt64(EltSize));
2014 else
2015 Builder.CreateLifetimeEnd(NewElts[Idx],
2016 Builder.getInt64(EltSize));
2017 }
2018 DeadInsts.push_back(II);
2019}
2020
Chris Lattnerd93afec2009-01-07 07:18:45 +00002021/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2022/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00002023void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00002024 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00002025 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002026 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00002027 // appropriate type. The "Other" pointer is the pointer that goes to memory
2028 // that doesn't have anything to do with the alloca that we are promoting. For
2029 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00002030 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00002031 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00002032 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00002033 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00002034 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00002035 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00002036 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00002037 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00002038 }
2039 }
Bob Wilson78c50b82009-12-08 18:22:03 +00002040
Chris Lattnerd93afec2009-01-07 07:18:45 +00002041 // If there is an other pointer, we want to convert it to the same pointer
2042 // type as AI has, so we can GEP through it safely.
2043 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00002044 unsigned AddrSpace =
2045 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00002046
2047 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2048 // optimization, but it's also required to detect the corner case where
2049 // both pointer operands are referencing the same memory, and where
2050 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2051 // function is only called for mem intrinsics that access the whole
2052 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00002053 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson69743022011-01-13 20:59:44 +00002054
Bob Wilsona756b1d2010-01-19 04:32:48 +00002055 // Copying the alloca to itself is a no-op: just delete it.
2056 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2057 // This code will run twice for a no-op memcpy -- once for each operand.
2058 // Put only one reference to MI on the DeadInsts list.
2059 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
2060 E = DeadInsts.end(); I != E; ++I)
2061 if (*I == MI) return;
2062 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002063 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00002064 }
Bob Wilson69743022011-01-13 20:59:44 +00002065
Chris Lattnerd93afec2009-01-07 07:18:45 +00002066 // If the pointer is not the right type, insert a bitcast to the right
2067 // type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002068 Type *NewTy =
Chris Lattner0238f8c2010-07-08 00:27:05 +00002069 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson69743022011-01-13 20:59:44 +00002070
Chris Lattner0238f8c2010-07-08 00:27:05 +00002071 if (OtherPtr->getType() != NewTy)
2072 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002073 }
Bob Wilson69743022011-01-13 20:59:44 +00002074
Chris Lattnerd93afec2009-01-07 07:18:45 +00002075 // Process each element of the aggregate.
Bob Wilsonb742def2009-12-18 20:14:40 +00002076 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson69743022011-01-13 20:59:44 +00002077
Owen Anderson1d0be152009-08-13 21:58:54 +00002078 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00002079
2080 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2081 // If this is a memcpy/memmove, emit a GEP of the other element address.
2082 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002083 unsigned OtherEltAlign = MemAlignment;
Bob Wilson69743022011-01-13 20:59:44 +00002084
Bob Wilsona756b1d2010-01-19 04:32:48 +00002085 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002086 Value *Idx[2] = { Zero,
2087 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Jay Foada9203102011-07-25 09:48:08 +00002088 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00002089 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00002090 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00002091 uint64_t EltOffset;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002092 PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2093 Type *OtherTy = OtherPtrTy->getElementType();
2094 if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002095 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
2096 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002097 Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002098 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002099 }
Bob Wilson69743022011-01-13 20:59:44 +00002100
Chris Lattner1541e0f2009-03-04 19:20:50 +00002101 // The alignment of the other pointer is the guaranteed alignment of the
2102 // element, which is affected by both the known alignment of the whole
2103 // mem intrinsic and the alignment of the element. If the alignment of
2104 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2105 // known alignment is just 4 bytes.
2106 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00002107 }
Bob Wilson69743022011-01-13 20:59:44 +00002108
Chris Lattnerd93afec2009-01-07 07:18:45 +00002109 Value *EltPtr = NewElts[i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002110 Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson69743022011-01-13 20:59:44 +00002111
Chris Lattnerd93afec2009-01-07 07:18:45 +00002112 // If we got down to a scalar, insert a load or store as appropriate.
2113 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00002114 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002115 if (SROADest) {
2116 // From Other to Alloca.
2117 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2118 new StoreInst(Elt, EltPtr, MI);
2119 } else {
2120 // From Alloca to Other.
2121 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2122 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2123 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00002124 continue;
2125 }
2126 assert(isa<MemSetInst>(MI));
Bob Wilson69743022011-01-13 20:59:44 +00002127
Chris Lattnerd93afec2009-01-07 07:18:45 +00002128 // If the stored element is zero (common case), just store a null
2129 // constant.
2130 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00002131 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002132 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00002133 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00002134 } else {
2135 // If EltTy is a vector type, get the element type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002136 Type *ValTy = EltTy->getScalarType();
Dan Gohman44118f02009-06-16 00:20:26 +00002137
Chris Lattnerd93afec2009-01-07 07:18:45 +00002138 // Construct an integer with the right value.
2139 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2140 APInt OneVal(EltSize, CI->getZExtValue());
2141 APInt TotalVal(OneVal);
2142 // Set each byte.
2143 for (unsigned i = 0; 8*i < EltSize; ++i) {
2144 TotalVal = TotalVal.shl(8);
2145 TotalVal |= OneVal;
2146 }
Bob Wilson69743022011-01-13 20:59:44 +00002147
Chris Lattnerd93afec2009-01-07 07:18:45 +00002148 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002149 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00002150 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002151 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002152 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002153 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002154 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson69743022011-01-13 20:59:44 +00002155
Chris Lattnerd93afec2009-01-07 07:18:45 +00002156 // If the requested value was a vector constant, create it.
Cameron Zwarichc055a872011-10-11 21:26:40 +00002157 if (EltTy->isVectorTy()) {
2158 unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
Chris Lattner4ca829e2012-01-25 06:02:56 +00002159 StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002160 }
2161 }
2162 new StoreInst(StoreVal, EltPtr, MI);
2163 continue;
2164 }
2165 // Otherwise, if we're storing a byte variable, use a memset call for
2166 // this element.
2167 }
Bob Wilson69743022011-01-13 20:59:44 +00002168
Duncan Sands777d2302009-05-09 07:06:46 +00002169 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Eli Friedman75f69e32011-11-12 02:07:50 +00002170 if (!EltSize)
2171 continue;
Bob Wilson69743022011-01-13 20:59:44 +00002172
Chris Lattner61db1f52010-12-26 22:57:41 +00002173 IRBuilder<> Builder(MI);
Bob Wilson69743022011-01-13 20:59:44 +00002174
Chris Lattnerd93afec2009-01-07 07:18:45 +00002175 // Finally, insert the meminst for this element.
Chris Lattner61db1f52010-12-26 22:57:41 +00002176 if (isa<MemSetInst>(MI)) {
2177 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2178 MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002179 } else {
Chris Lattner61db1f52010-12-26 22:57:41 +00002180 assert(isa<MemTransferInst>(MI));
2181 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2182 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson69743022011-01-13 20:59:44 +00002183
Chris Lattner61db1f52010-12-26 22:57:41 +00002184 if (isa<MemCpyInst>(MI))
2185 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2186 else
2187 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002188 }
Chris Lattner372dda82007-03-05 07:52:57 +00002189 }
Bob Wilsonb742def2009-12-18 20:14:40 +00002190 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00002191}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002192
Bob Wilson39fdd692009-12-04 21:57:37 +00002193/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002194/// overwrites the entire allocation. Extract out the pieces of the stored
2195/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002196void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002197 SmallVector<AllocaInst*, 32> &NewElts){
2198 // Extract each element out of the integer according to its structure offset
2199 // and store the element value to the individual alloca.
2200 Value *SrcVal = SI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002201 Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002202 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002203
Chris Lattner70728532011-01-16 05:58:24 +00002204 IRBuilder<> Builder(SI);
2205
Eli Friedman41b33f42009-06-01 09:14:32 +00002206 // Handle tail padding by extending the operand
2207 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002208 SrcVal = Builder.CreateZExt(SrcVal,
2209 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002210
David Greene504c7d82010-01-05 01:27:09 +00002211 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00002212 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002213
2214 // There are two forms here: AI could be an array or struct. Both cases
2215 // have different ways to compute the element offset.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002216 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002217 const StructLayout *Layout = TD->getStructLayout(EltSTy);
Bob Wilson69743022011-01-13 20:59:44 +00002218
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002219 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2220 // Get the number of bits to shift SrcVal to get the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002221 Type *FieldTy = EltSTy->getElementType(i);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002222 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson69743022011-01-13 20:59:44 +00002223
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002224 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00002225 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002226
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002227 Value *EltVal = SrcVal;
2228 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002229 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002230 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002231 }
Bob Wilson69743022011-01-13 20:59:44 +00002232
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002233 // Truncate down to an integer of the right size.
2234 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002235
Chris Lattner583dd602009-01-09 18:18:43 +00002236 // Ignore zero sized fields like {}, they obviously contain no data.
2237 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002238
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002239 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002240 EltVal = Builder.CreateTrunc(EltVal,
2241 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002242 Value *DestField = NewElts[i];
2243 if (EltVal->getType() == FieldTy) {
2244 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00002245 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002246 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002247 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002248 } else {
2249 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002250 DestField = Builder.CreateBitCast(DestField,
2251 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002252 }
2253 new StoreInst(EltVal, DestField, SI);
2254 }
Bob Wilson69743022011-01-13 20:59:44 +00002255
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002256 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002257 ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2258 Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002259 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002260 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2261
2262 uint64_t Shift;
Bob Wilson69743022011-01-13 20:59:44 +00002263
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002264 if (TD->isBigEndian())
2265 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002266 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002267 Shift = 0;
Bob Wilson69743022011-01-13 20:59:44 +00002268
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002269 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00002270 // Ignore zero sized fields like {}, they obviously contain no data.
2271 if (ElementSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002272
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002273 Value *EltVal = SrcVal;
2274 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002275 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002276 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002277 }
Bob Wilson69743022011-01-13 20:59:44 +00002278
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002279 // Truncate down to an integer of the right size.
2280 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002281 EltVal = Builder.CreateTrunc(EltVal,
2282 IntegerType::get(SI->getContext(),
2283 ElementSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002284 Value *DestField = NewElts[i];
2285 if (EltVal->getType() == ArrayEltTy) {
2286 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002287 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00002288 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002289 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002290 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002291 } else {
2292 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002293 DestField = Builder.CreateBitCast(DestField,
2294 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002295 }
2296 new StoreInst(EltVal, DestField, SI);
Bob Wilson69743022011-01-13 20:59:44 +00002297
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002298 if (TD->isBigEndian())
2299 Shift -= ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002300 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002301 Shift += ElementOffset;
2302 }
2303 }
Bob Wilson69743022011-01-13 20:59:44 +00002304
Bob Wilsonb742def2009-12-18 20:14:40 +00002305 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002306}
2307
Bob Wilson39fdd692009-12-04 21:57:37 +00002308/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002309/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002310void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002311 SmallVector<AllocaInst*, 32> &NewElts) {
2312 // Extract each element out of the NewElts according to its structure offset
2313 // and form the result value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002314 Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002315 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002316
David Greene504c7d82010-01-05 01:27:09 +00002317 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00002318 << '\n');
Bob Wilson69743022011-01-13 20:59:44 +00002319
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002320 // There are two forms here: AI could be an array or struct. Both cases
2321 // have different ways to compute the element offset.
2322 const StructLayout *Layout = 0;
2323 uint64_t ArrayEltBitOffset = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002324 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002325 Layout = TD->getStructLayout(EltSTy);
2326 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002327 Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002328 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002329 }
2330
2331 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00002332 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson69743022011-01-13 20:59:44 +00002333
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002334 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2335 // Load the value from the alloca. If the NewElt is an aggregate, cast
2336 // the pointer to an integer of the same size before doing the load.
2337 Value *SrcField = NewElts[i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002338 Type *FieldTy =
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002339 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00002340 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002341
Chris Lattner583dd602009-01-09 18:18:43 +00002342 // Ignore zero sized fields like {}, they obviously contain no data.
2343 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002344
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002345 IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +00002346 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00002347 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2348 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00002349 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00002350 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002351 "", LI);
2352 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2353
2354 // If SrcField is a fp or vector of the right size but that isn't an
2355 // integer type, bitcast to an integer so we can shift it.
2356 if (SrcField->getType() != FieldIntTy)
2357 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2358
2359 // Zero extend the field to be the same size as the final alloca so that
2360 // we can shift and insert it.
2361 if (SrcField->getType() != ResultVal->getType())
2362 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson69743022011-01-13 20:59:44 +00002363
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002364 // Determine the number of bits to shift SrcField.
2365 uint64_t Shift;
2366 if (Layout) // Struct case.
2367 Shift = Layout->getElementOffsetInBits(i);
2368 else // Array case.
2369 Shift = i*ArrayEltBitOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002370
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002371 if (TD->isBigEndian())
2372 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson69743022011-01-13 20:59:44 +00002373
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002374 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002375 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002376 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2377 }
2378
Chris Lattner14952472010-06-27 07:58:26 +00002379 // Don't create an 'or x, 0' on the first iteration.
2380 if (!isa<Constant>(ResultVal) ||
2381 !cast<Constant>(ResultVal)->isNullValue())
2382 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2383 else
2384 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002385 }
Eli Friedman41b33f42009-06-01 09:14:32 +00002386
2387 // Handle tail padding by truncating the result
2388 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2389 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2390
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002391 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00002392 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002393}
2394
Duncan Sands3cb36502007-11-04 14:43:57 +00002395/// HasPadding - Return true if the specified type has any structure or
Bob Wilson694a10e2011-01-13 17:45:08 +00002396/// alignment padding in between the elements that would be split apart
2397/// by SROA; return false otherwise.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002398static bool HasPadding(Type *Ty, const TargetData &TD) {
2399 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Bob Wilson694a10e2011-01-13 17:45:08 +00002400 Ty = ATy->getElementType();
2401 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00002402 }
Bob Wilson694a10e2011-01-13 17:45:08 +00002403
2404 // SROA currently handles only Arrays and Structs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002405 StructType *STy = cast<StructType>(Ty);
Bob Wilson694a10e2011-01-13 17:45:08 +00002406 const StructLayout *SL = TD.getStructLayout(STy);
2407 unsigned PrevFieldBitOffset = 0;
2408 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2409 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2410
2411 // Check to see if there is any padding between this element and the
2412 // previous one.
2413 if (i) {
2414 unsigned PrevFieldEnd =
2415 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2416 if (PrevFieldEnd < FieldBitOffset)
2417 return true;
2418 }
2419 PrevFieldBitOffset = FieldBitOffset;
2420 }
2421 // Check for tail padding.
2422 if (unsigned EltCount = STy->getNumElements()) {
2423 unsigned PrevFieldEnd = PrevFieldBitOffset +
2424 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2425 if (PrevFieldEnd < SL->getSizeInBits())
2426 return true;
2427 }
2428 return false;
Chris Lattner39a1c042007-05-30 06:11:23 +00002429}
Chris Lattner372dda82007-03-05 07:52:57 +00002430
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002431/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2432/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2433/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002434bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00002435 // Loop over the use list of the alloca. We can only transform it if all of
2436 // the users are safe to transform.
Chris Lattner6c95d242011-01-23 07:29:29 +00002437 AllocaInfo Info(AI);
Bob Wilson69743022011-01-13 20:59:44 +00002438
Chris Lattner6c95d242011-01-23 07:29:29 +00002439 isSafeForScalarRepl(AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00002440 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00002441 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002442 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002443 }
Bob Wilson69743022011-01-13 20:59:44 +00002444
Chris Lattner39a1c042007-05-30 06:11:23 +00002445 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2446 // source and destination, we have to be careful. In particular, the memcpy
2447 // could be moving around elements that live in structure padding of the LLVM
2448 // types, but may actually be used. In these cases, we refuse to promote the
2449 // struct.
2450 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00002451 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002452 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00002453
Chris Lattner396a0562011-01-16 17:46:19 +00002454 // If the alloca never has an access to just *part* of it, but is accessed
2455 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner7e9b4272011-01-16 06:18:28 +00002456 // the alloca instead of promoting each piece at a time and inserting fission
2457 // and fusion code.
2458 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2459 // If the struct/array just has one element, use basic SRoA.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002460 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
Chris Lattner7e9b4272011-01-16 06:18:28 +00002461 if (ST->getNumElements() > 1) return false;
2462 } else {
2463 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2464 return false;
2465 }
2466 }
Chris Lattner145c5322011-01-23 08:27:54 +00002467
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002468 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00002469}
Chris Lattnera1888942005-12-12 07:19:13 +00002470
Chris Lattner800de312008-02-29 07:03:13 +00002471
Chris Lattner79b3bd32007-04-25 06:40:51 +00002472
2473/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2474/// some part of a constant global variable. This intentionally only accepts
2475/// constant expressions because we don't can't rewrite arbitrary instructions.
2476static bool PointsToConstantGlobal(Value *V) {
2477 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2478 return GV->isConstant();
2479 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Bob Wilson69743022011-01-13 20:59:44 +00002480 if (CE->getOpcode() == Instruction::BitCast ||
Chris Lattner79b3bd32007-04-25 06:40:51 +00002481 CE->getOpcode() == Instruction::GetElementPtr)
2482 return PointsToConstantGlobal(CE->getOperand(0));
2483 return false;
2484}
2485
2486/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2487/// pointer to an alloca. Ignore any reads of the pointer, return false if we
2488/// see any stores or other unknown uses. If we see pointer arithmetic, keep
2489/// track of whether it moves the pointer (with isOffset) but otherwise traverse
2490/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
Nick Lewycky081f8002010-11-24 22:04:20 +00002491/// the alloca, and if the source pointer is a pointer to a constant global, we
Chris Lattner79b3bd32007-04-25 06:40:51 +00002492/// can optimize this.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002493static bool
2494isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
2495 bool isOffset,
2496 SmallVector<Instruction *, 4> &LifetimeMarkers) {
2497 // We track lifetime intrinsics as we encounter them. If we decide to go
2498 // ahead and replace the value with the global, this lets the caller quickly
2499 // eliminate the markers.
2500
Chris Lattner79b3bd32007-04-25 06:40:51 +00002501 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00002502 User *U = cast<Instruction>(*UI);
2503
Chris Lattner2e618492010-11-18 06:20:47 +00002504 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00002505 // Ignore non-volatile loads, they are always ok.
Eli Friedman2bc3d522011-09-12 20:23:13 +00002506 if (!LI->isSimple()) return false;
Chris Lattner2e618492010-11-18 06:20:47 +00002507 continue;
2508 }
Bob Wilson69743022011-01-13 20:59:44 +00002509
Gabor Greif8a8a4352010-04-06 19:32:30 +00002510 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002511 // If uses of the bitcast are ok, we are ok.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002512 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset,
2513 LifetimeMarkers))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002514 return false;
2515 continue;
2516 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00002517 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002518 // If the GEP has all zero indices, it doesn't offset the pointer. If it
2519 // doesn't, it does.
2520 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002521 isOffset || !GEP->hasAllZeroIndices(),
2522 LifetimeMarkers))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002523 return false;
2524 continue;
2525 }
Bob Wilson69743022011-01-13 20:59:44 +00002526
Chris Lattner62480652010-11-18 06:41:51 +00002527 if (CallSite CS = U) {
Nick Lewycky081f8002010-11-24 22:04:20 +00002528 // If this is the function being called then we treat it like a load and
2529 // ignore it.
2530 if (CS.isCallee(UI))
2531 continue;
Bob Wilson69743022011-01-13 20:59:44 +00002532
Duncan Sands53892102011-05-06 10:30:37 +00002533 // If this is a readonly/readnone call site, then we know it is just a
2534 // load (but one that potentially returns the value itself), so we can
2535 // ignore it if we know that the value isn't captured.
2536 unsigned ArgNo = CS.getArgumentNo(UI);
2537 if (CS.onlyReadsMemory() &&
Nick Lewycky173862e2011-11-20 19:09:04 +00002538 (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
Duncan Sands53892102011-05-06 10:30:37 +00002539 continue;
2540
Chris Lattner62480652010-11-18 06:41:51 +00002541 // If this is being passed as a byval argument, the caller is making a
2542 // copy, so it is only a read of the alloca.
Nick Lewycky173862e2011-11-20 19:09:04 +00002543 if (CS.isByValArgument(ArgNo))
Chris Lattner62480652010-11-18 06:41:51 +00002544 continue;
2545 }
Bob Wilson69743022011-01-13 20:59:44 +00002546
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002547 // Lifetime intrinsics can be handled by the caller.
2548 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
2549 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2550 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2551 assert(II->use_empty() && "Lifetime markers have no result to use!");
2552 LifetimeMarkers.push_back(II);
2553 continue;
2554 }
2555 }
2556
Chris Lattner79b3bd32007-04-25 06:40:51 +00002557 // If this is isn't our memcpy/memmove, reject it as something we can't
2558 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00002559 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2560 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00002561 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002562
Chris Lattner2e618492010-11-18 06:20:47 +00002563 // If the transfer is using the alloca as a source of the transfer, then
Chris Lattner2e29ebd2010-11-18 07:32:33 +00002564 // ignore it since it is a load (unless the transfer is volatile).
Chris Lattner2e618492010-11-18 06:20:47 +00002565 if (UI.getOperandNo() == 1) {
2566 if (MI->isVolatile()) return false;
2567 continue;
2568 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00002569
2570 // If we already have seen a copy, reject the second one.
2571 if (TheCopy) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002572
Chris Lattner79b3bd32007-04-25 06:40:51 +00002573 // If the pointer has been offset from the start of the alloca, we can't
2574 // safely handle this.
2575 if (isOffset) return false;
2576
2577 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00002578 if (UI.getOperandNo() != 0) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002579
Chris Lattner79b3bd32007-04-25 06:40:51 +00002580 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00002581 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002582 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002583
Chris Lattner79b3bd32007-04-25 06:40:51 +00002584 // Otherwise, the transform is safe. Remember the copy instruction.
2585 TheCopy = MI;
2586 }
2587 return true;
2588}
2589
2590/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2591/// modified by a copy from a constant global. If we can prove this, we can
2592/// replace any uses of the alloca with uses of the global directly.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002593MemTransferInst *
2594SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
2595 SmallVector<Instruction*, 4> &ToDelete) {
Chris Lattner31d80102010-04-15 21:59:20 +00002596 MemTransferInst *TheCopy = 0;
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002597 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false, ToDelete))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002598 return TheCopy;
2599 return 0;
2600}