blob: ef520af302e06deee08b6efe66b8de88116daa75 [file] [log] [blame]
Chris Lattnered7b41e2003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnered7b41e2003-05-27 15:45:27 +00009//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation. This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
Chris Lattner38aec322003-09-11 16:45:55 +000013// each member (if possible). Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17// often interact, especially for C++ programs. As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
Chris Lattnered7b41e2003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
Chris Lattner0e5f4992006-12-19 21:40:18 +000022#define DEBUG_TYPE "scalarrepl"
Chris Lattnered7b41e2003-05-27 15:45:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattner38aec322003-09-11 16:45:55 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnered7b41e2003-05-27 15:45:27 +000026#include "llvm/Function.h"
Chris Lattner79b3bd32007-04-25 06:40:51 +000027#include "llvm/GlobalVariable.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000028#include "llvm/Instructions.h"
Chris Lattner372dda82007-03-05 07:52:57 +000029#include "llvm/IntrinsicInst.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Chris Lattner72eaa0e2010-09-01 23:09:27 +000031#include "llvm/Module.h"
Chris Lattner372dda82007-03-05 07:52:57 +000032#include "llvm/Pass.h"
Cameron Zwarichc8279392011-05-24 03:10:43 +000033#include "llvm/Analysis/DIBuilder.h"
Cameron Zwarichb1686c32011-01-18 03:53:26 +000034#include "llvm/Analysis/Dominators.h"
Chris Lattnerc87c50a2011-01-23 22:04:55 +000035#include "llvm/Analysis/Loads.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000036#include "llvm/Analysis/ValueTracking.h"
Chris Lattner38aec322003-09-11 16:45:55 +000037#include "llvm/Target/TargetData.h"
38#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000039#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere0a1a5b2011-01-14 07:50:47 +000040#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattnera9be1df2010-11-18 06:26:49 +000041#include "llvm/Support/CallSite.h"
Chris Lattner95255282006-06-28 23:17:24 +000042#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000043#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000044#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000045#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000046#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000047#include "llvm/Support/raw_ostream.h"
Chris Lattnerc87c50a2011-01-23 22:04:55 +000048#include "llvm/ADT/SetVector.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000049#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000050#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000051using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000052
Chris Lattner0e5f4992006-12-19 21:40:18 +000053STATISTIC(NumReplaced, "Number of allocas broken up");
54STATISTIC(NumPromoted, "Number of allocas promoted");
Chris Lattnerc87c50a2011-01-23 22:04:55 +000055STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
Chris Lattner0e5f4992006-12-19 21:40:18 +000056STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000057STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000058
Chris Lattner0e5f4992006-12-19 21:40:18 +000059namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000060 struct SROA : public FunctionPass {
Cameron Zwarichb1686c32011-01-18 03:53:26 +000061 SROA(int T, bool hasDT, char &ID)
62 : FunctionPass(ID), HasDomTree(hasDT) {
Devang Patelff366852007-07-09 21:19:23 +000063 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000064 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000065 else
66 SRThreshold = T;
67 }
Devang Patel794fd752007-05-01 21:15:47 +000068
Chris Lattnered7b41e2003-05-27 15:45:27 +000069 bool runOnFunction(Function &F);
70
Chris Lattner38aec322003-09-11 16:45:55 +000071 bool performScalarRepl(Function &F);
72 bool performPromotion(Function &F);
73
Chris Lattnered7b41e2003-05-27 15:45:27 +000074 private:
Cameron Zwarichb1686c32011-01-18 03:53:26 +000075 bool HasDomTree;
Chris Lattner56c38522009-01-07 06:34:28 +000076 TargetData *TD;
Bob Wilson69743022011-01-13 20:59:44 +000077
Bob Wilsonb742def2009-12-18 20:14:40 +000078 /// DeadInsts - Keep track of instructions we have made dead, so that
79 /// we can remove them after we are done working.
80 SmallVector<Value*, 32> DeadInsts;
81
Chris Lattner39a1c042007-05-30 06:11:23 +000082 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
83 /// information about the uses. All these fields are initialized to false
84 /// and set to true when something is learned.
85 struct AllocaInfo {
Chris Lattner6c95d242011-01-23 07:29:29 +000086 /// The alloca to promote.
87 AllocaInst *AI;
88
Chris Lattner145c5322011-01-23 08:27:54 +000089 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
90 /// looping and avoid redundant work.
91 SmallPtrSet<PHINode*, 8> CheckedPHIs;
92
Chris Lattner39a1c042007-05-30 06:11:23 +000093 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
94 bool isUnsafe : 1;
Bob Wilson69743022011-01-13 20:59:44 +000095
Chris Lattner39a1c042007-05-30 06:11:23 +000096 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
97 bool isMemCpySrc : 1;
98
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000099 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +0000100 bool isMemCpyDst : 1;
101
Chris Lattner7e9b4272011-01-16 06:18:28 +0000102 /// hasSubelementAccess - This is true if a subelement of the alloca is
103 /// ever accessed, or false if the alloca is only accessed with mem
104 /// intrinsics or load/store that only access the entire alloca at once.
105 bool hasSubelementAccess : 1;
106
107 /// hasALoadOrStore - This is true if there are any loads or stores to it.
108 /// The alloca may just be accessed with memcpy, for example, which would
109 /// not set this.
110 bool hasALoadOrStore : 1;
111
Chris Lattner6c95d242011-01-23 07:29:29 +0000112 explicit AllocaInfo(AllocaInst *ai)
113 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
Chris Lattner7e9b4272011-01-16 06:18:28 +0000114 hasSubelementAccess(false), hasALoadOrStore(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +0000115 };
Bob Wilson69743022011-01-13 20:59:44 +0000116
Devang Patelff366852007-07-09 21:19:23 +0000117 unsigned SRThreshold;
118
Chris Lattnerd01a0da2011-01-23 07:05:44 +0000119 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
120 I.isUnsafe = true;
121 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
122 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000123
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000124 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000125
Chris Lattner6c95d242011-01-23 07:29:29 +0000126 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
Chris Lattner145c5322011-01-23 08:27:54 +0000127 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
128 AllocaInfo &Info);
Chris Lattner6c95d242011-01-23 07:29:29 +0000129 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
130 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattnerd01a0da2011-01-23 07:05:44 +0000131 const Type *MemOpType, bool isStore, AllocaInfo &Info,
Chris Lattner145c5322011-01-23 08:27:54 +0000132 Instruction *TheAccess, bool AllowWholeAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +0000133 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000134 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
135 const Type *&IdxTy);
Bob Wilson69743022011-01-13 20:59:44 +0000136
137 void DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000138 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000139 void DeleteDeadInstructions();
Bob Wilson69743022011-01-13 20:59:44 +0000140
Bob Wilsonb742def2009-12-18 20:14:40 +0000141 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
142 SmallVector<AllocaInst*, 32> &NewElts);
143 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
144 SmallVector<AllocaInst*, 32> &NewElts);
145 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
146 SmallVector<AllocaInst*, 32> &NewElts);
147 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000148 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000149 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000150 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000151 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000152 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000153 SmallVector<AllocaInst*, 32> &NewElts);
Bob Wilson69743022011-01-13 20:59:44 +0000154
Nick Lewycky9174d5c2011-06-27 05:40:02 +0000155 static MemTransferInst *isOnlyCopiedFromConstantGlobal(
156 AllocaInst *AI, SmallVector<Instruction*, 4> &ToDelete);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000157 };
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000158
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000159 // SROA_DT - SROA that uses DominatorTree.
160 struct SROA_DT : public SROA {
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000161 static char ID;
162 public:
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000163 SROA_DT(int T = -1) : SROA(T, true, ID) {
164 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000165 }
166
167 // getAnalysisUsage - This pass does not require any passes, but we know it
168 // will not alter the CFG, so say so.
169 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
170 AU.addRequired<DominatorTree>();
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000171 AU.setPreservesCFG();
172 }
173 };
174
175 // SROA_SSAUp - SROA that uses SSAUpdater.
176 struct SROA_SSAUp : public SROA {
177 static char ID;
178 public:
179 SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
180 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
181 }
182
183 // getAnalysisUsage - This pass does not require any passes, but we know it
184 // will not alter the CFG, so say so.
185 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
186 AU.setPreservesCFG();
187 }
188 };
189
Chris Lattnered7b41e2003-05-27 15:45:27 +0000190}
191
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000192char SROA_DT::ID = 0;
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000193char SROA_SSAUp::ID = 0;
194
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000195INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
196 "Scalar Replacement of Aggregates (DT)", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000197INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000198INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
199 "Scalar Replacement of Aggregates (DT)", false, false)
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000200
201INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
202 "Scalar Replacement of Aggregates (SSAUp)", false, false)
203INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
204 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000205
Brian Gaeked0fde302003-11-11 22:41:34 +0000206// Public interface to the ScalarReplAggregates pass
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000207FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000208 bool UseDomTree) {
209 if (UseDomTree)
210 return new SROA_DT(Threshold);
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000211 return new SROA_SSAUp(Threshold);
Devang Patelff366852007-07-09 21:19:23 +0000212}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000213
214
Chris Lattner4cc576b2010-04-16 00:24:57 +0000215//===----------------------------------------------------------------------===//
216// Convert To Scalar Optimization.
217//===----------------------------------------------------------------------===//
218
219namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000220/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
221/// optimization, which scans the uses of an alloca and determines if it can
222/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000223class ConvertToScalarInfo {
Cameron Zwarichd4c9c3e2011-03-16 00:13:35 +0000224 /// AllocaSize - The size of the alloca being considered in bytes.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000225 unsigned AllocaSize;
226 const TargetData &TD;
Bob Wilson69743022011-01-13 20:59:44 +0000227
Chris Lattnera0bada72010-04-16 02:32:17 +0000228 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000229 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000230 bool IsNotTrivial;
Bob Wilson69743022011-01-13 20:59:44 +0000231
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000232 /// ScalarKind - Tracks the kind of alloca being considered for promotion,
233 /// computed based on the uses of the alloca rather than the LLVM type system.
234 enum {
235 Unknown,
Cameron Zwarich51797822011-06-13 21:44:40 +0000236
Cameron Zwarich15cd80c2011-06-13 23:39:23 +0000237 // Accesses via GEPs that are consistent with element access of a vector
Cameron Zwarich51797822011-06-13 21:44:40 +0000238 // type. This will not be converted into a vector unless there is a later
239 // access using an actual vector type.
240 ImplicitVector,
241
Cameron Zwarich15cd80c2011-06-13 23:39:23 +0000242 // Accesses via vector operations and GEPs that are consistent with the
243 // layout of a vector type.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000244 Vector,
Cameron Zwarich51797822011-06-13 21:44:40 +0000245
246 // An integer bag-of-bits with bitwise operations for insertion and
247 // extraction. Any combination of types can be converted into this kind
248 // of scalar.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000249 Integer
250 } ScalarKind;
251
Chris Lattnera001b662010-04-16 00:38:19 +0000252 /// VectorTy - This tracks the type that we should promote the vector to if
253 /// it is possible to turn it into a vector. This starts out null, and if it
254 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000255 const VectorType *VectorTy;
Bob Wilson69743022011-01-13 20:59:44 +0000256
Cameron Zwarich1bcdb6f2011-03-16 08:13:42 +0000257 /// HadNonMemTransferAccess - True if there is at least one access to the
258 /// alloca that is not a MemTransferInst. We don't want to turn structs into
259 /// large integers unless there is some potential for optimization.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000260 bool HadNonMemTransferAccess;
261
Chris Lattner4cc576b2010-04-16 00:24:57 +0000262public:
263 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000264 : AllocaSize(Size), TD(td), IsNotTrivial(false), ScalarKind(Unknown),
Cameron Zwarich51797822011-06-13 21:44:40 +0000265 VectorTy(0), HadNonMemTransferAccess(false) { }
Bob Wilson69743022011-01-13 20:59:44 +0000266
Chris Lattnera001b662010-04-16 00:38:19 +0000267 AllocaInst *TryConvert(AllocaInst *AI);
Bob Wilson69743022011-01-13 20:59:44 +0000268
Chris Lattner4cc576b2010-04-16 00:24:57 +0000269private:
270 bool CanConvertToScalar(Value *V, uint64_t Offset);
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000271 void MergeInTypeForLoadOrStore(const Type *In, uint64_t Offset);
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000272 bool MergeInVectorType(const VectorType *VInTy, uint64_t Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000273 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Bob Wilson69743022011-01-13 20:59:44 +0000274
Chris Lattner4cc576b2010-04-16 00:24:57 +0000275 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
276 uint64_t Offset, IRBuilder<> &Builder);
277 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
278 uint64_t Offset, IRBuilder<> &Builder);
279};
280} // end anonymous namespace.
281
Chris Lattner91abace2010-09-01 05:14:33 +0000282
Chris Lattnera001b662010-04-16 00:38:19 +0000283/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
284/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
285/// alloca if possible or null if not.
286AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
287 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
288 // out.
289 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
290 return 0;
Bob Wilson69743022011-01-13 20:59:44 +0000291
Cameron Zwarich51797822011-06-13 21:44:40 +0000292 // If an alloca has only memset / memcpy uses, it may still have an Unknown
293 // ScalarKind. Treat it as an Integer below.
294 if (ScalarKind == Unknown)
295 ScalarKind = Integer;
296
Cameron Zwarich3ebb05d2011-06-18 06:17:51 +0000297 // FIXME: It should be possible to promote the vector type up to the alloca's
298 // size.
299 if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
300 ScalarKind = Integer;
301
Chris Lattnera001b662010-04-16 00:38:19 +0000302 // If we were able to find a vector type that can handle this with
303 // insert/extract elements, and if there was at least one use that had
304 // a vector type, promote this to a vector. We don't want to promote
305 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
306 // we just get a lot of insert/extracts. If at least one vector is
307 // involved, then we probably really do have a union of vector/array.
308 const Type *NewTy;
Cameron Zwarich5b93d3c2011-06-14 06:33:51 +0000309 if (ScalarKind == Vector) {
310 assert(VectorTy && "Missing type for vector scalar.");
Chris Lattnera001b662010-04-16 00:38:19 +0000311 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
312 << *VectorTy << '\n');
313 NewTy = VectorTy; // Use the vector type.
314 } else {
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000315 unsigned BitWidth = AllocaSize * 8;
Cameron Zwarich51797822011-06-13 21:44:40 +0000316 if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
317 !HadNonMemTransferAccess && !TD.fitsInLegalInteger(BitWidth))
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000318 return 0;
319
Chris Lattnera001b662010-04-16 00:38:19 +0000320 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
321 // Create and insert the integer alloca.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000322 NewTy = IntegerType::get(AI->getContext(), BitWidth);
Chris Lattnera001b662010-04-16 00:38:19 +0000323 }
324 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
325 ConvertUsesToScalar(AI, NewAI, 0);
326 return NewAI;
327}
328
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000329/// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
330/// (VectorTy) so far at the offset specified by Offset (which is specified in
331/// bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000332///
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000333/// There are three cases we handle here:
Chris Lattner4cc576b2010-04-16 00:24:57 +0000334/// 1) A union of vector types of the same size and potentially its elements.
335/// Here we turn element accesses into insert/extract element operations.
336/// This promotes a <4 x float> with a store of float to the third element
337/// into a <4 x float> that uses insert element.
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000338/// 2) A union of vector types with power-of-2 size differences, e.g. a float,
339/// <2 x float> and <4 x float>. Here we turn element accesses into insert
340/// and extract element operations, and <2 x float> accesses into a cast to
341/// <2 x double>, an extract, and a cast back to <2 x float>.
342/// 3) A fully general blob of memory, which we turn into some (potentially
Chris Lattner4cc576b2010-04-16 00:24:57 +0000343/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000344/// and stores would mutate the memory. We mark this by setting VectorTy
345/// to VoidTy.
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000346void ConvertToScalarInfo::MergeInTypeForLoadOrStore(const Type *In,
347 uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000348 // If we already decided to turn this into a blob of integer memory, there is
349 // nothing to be done.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000350 if (ScalarKind == Integer)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000351 return;
Bob Wilson69743022011-01-13 20:59:44 +0000352
Chris Lattner4cc576b2010-04-16 00:24:57 +0000353 // If this could be contributing to a vector, analyze it.
354
355 // If the In type is a vector that is the same size as the alloca, see if it
356 // matches the existing VecTy.
357 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000358 if (MergeInVectorType(VInTy, Offset))
Chris Lattner4cc576b2010-04-16 00:24:57 +0000359 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000360 } else if (In->isFloatTy() || In->isDoubleTy() ||
361 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
362 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
Cameron Zwarich9827b782011-03-29 05:19:52 +0000363 // Full width accesses can be ignored, because they can always be turned
364 // into bitcasts.
365 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
Cameron Zwarichdd689122011-06-13 21:44:31 +0000366 if (EltSize == AllocaSize)
Cameron Zwarich9827b782011-03-29 05:19:52 +0000367 return;
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000368
Chris Lattner4cc576b2010-04-16 00:24:57 +0000369 // If we're accessing something that could be an element of a vector, see
370 // if the implied vector agrees with what we already have and if Offset is
371 // compatible with it.
Cameron Zwarich96cc1d02011-06-09 01:45:33 +0000372 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Cameron Zwarichc4f78202011-06-09 01:52:44 +0000373 (!VectorTy || Offset * 8 < VectorTy->getPrimitiveSizeInBits())) {
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000374 if (!VectorTy) {
Cameron Zwarich51797822011-06-13 21:44:40 +0000375 ScalarKind = ImplicitVector;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000376 VectorTy = VectorType::get(In, AllocaSize/EltSize);
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000377 return;
378 }
379
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000380 unsigned CurrentEltSize = VectorTy->getElementType()
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000381 ->getPrimitiveSizeInBits()/8;
382 if (EltSize == CurrentEltSize)
383 return;
Cameron Zwarich344731c2011-04-20 21:48:38 +0000384
385 if (In->isIntegerTy() && isPowerOf2_32(AllocaSize / EltSize))
386 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000387 }
388 }
Bob Wilson69743022011-01-13 20:59:44 +0000389
Chris Lattner4cc576b2010-04-16 00:24:57 +0000390 // Otherwise, we have a case that we can't handle with an optimized vector
391 // form. We can still turn this into a large integer.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000392 ScalarKind = Integer;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000393}
394
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000395/// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
396/// returning true if the type was successfully merged and false otherwise.
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000397bool ConvertToScalarInfo::MergeInVectorType(const VectorType *VInTy,
398 uint64_t Offset) {
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000399 // TODO: Support nonzero offsets?
400 if (Offset != 0)
401 return false;
402
403 // Only allow vectors that are a power-of-2 away from the size of the alloca.
404 if (!isPowerOf2_64(AllocaSize / (VInTy->getBitWidth() / 8)))
405 return false;
406
407 // If this the first vector we see, remember the type so that we know the
408 // element size.
409 if (!VectorTy) {
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000410 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000411 VectorTy = VInTy;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000412 return true;
413 }
414
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000415 unsigned BitWidth = VectorTy->getBitWidth();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000416 unsigned InBitWidth = VInTy->getBitWidth();
417
418 // Vectors of the same size can be converted using a simple bitcast.
Cameron Zwarich51797822011-06-13 21:44:40 +0000419 if (InBitWidth == BitWidth && AllocaSize == (InBitWidth / 8)) {
420 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000421 return true;
Cameron Zwarich51797822011-06-13 21:44:40 +0000422 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000423
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000424 const Type *ElementTy = VectorTy->getElementType();
425 const Type *InElementTy = VInTy->getElementType();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000426
427 // Do not allow mixed integer and floating-point accesses from vectors of
428 // different sizes.
429 if (ElementTy->isFloatingPointTy() != InElementTy->isFloatingPointTy())
430 return false;
431
432 if (ElementTy->isFloatingPointTy()) {
433 // Only allow floating-point vectors of different sizes if they have the
434 // same element type.
435 // TODO: This could be loosened a bit, but would anything benefit?
436 if (ElementTy != InElementTy)
437 return false;
438
439 // There are no arbitrary-precision floating-point types, which limits the
440 // number of legal vector types with larger element types that we can form
441 // to bitcast and extract a subvector.
442 // TODO: We could support some more cases with mixed fp128 and double here.
443 if (!(BitWidth == 64 || BitWidth == 128) ||
444 !(InBitWidth == 64 || InBitWidth == 128))
445 return false;
446 } else {
447 assert(ElementTy->isIntegerTy() && "Vector elements must be either integer "
448 "or floating-point.");
449 unsigned BitWidth = ElementTy->getPrimitiveSizeInBits();
450 unsigned InBitWidth = InElementTy->getPrimitiveSizeInBits();
451
452 // Do not allow integer types smaller than a byte or types whose widths are
453 // not a multiple of a byte.
454 if (BitWidth < 8 || InBitWidth < 8 ||
455 BitWidth % 8 != 0 || InBitWidth % 8 != 0)
456 return false;
457 }
458
459 // Pick the largest of the two vector types.
Cameron Zwarich51797822011-06-13 21:44:40 +0000460 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000461 if (InBitWidth > BitWidth)
462 VectorTy = VInTy;
463
464 return true;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000465}
466
Chris Lattner4cc576b2010-04-16 00:24:57 +0000467/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
468/// its accesses to a single vector type, return true and set VecTy to
469/// the new type. If we could convert the alloca into a single promotable
470/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
471/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
472/// is the current offset from the base of the alloca being analyzed.
473///
474/// If we see at least one access to the value that is as a vector type, set the
475/// SawVec flag.
476bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
477 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
478 Instruction *User = cast<Instruction>(*UI);
Bob Wilson69743022011-01-13 20:59:44 +0000479
Chris Lattner4cc576b2010-04-16 00:24:57 +0000480 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
481 // Don't break volatile loads.
482 if (LI->isVolatile())
483 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000484 // Don't touch MMX operations.
485 if (LI->getType()->isX86_MMXTy())
486 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000487 HadNonMemTransferAccess = true;
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000488 MergeInTypeForLoadOrStore(LI->getType(), Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000489 continue;
490 }
Bob Wilson69743022011-01-13 20:59:44 +0000491
Chris Lattner4cc576b2010-04-16 00:24:57 +0000492 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
493 // Storing the pointer, not into the value?
494 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000495 // Don't touch MMX operations.
496 if (SI->getOperand(0)->getType()->isX86_MMXTy())
497 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000498 HadNonMemTransferAccess = true;
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000499 MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000500 continue;
501 }
Bob Wilson69743022011-01-13 20:59:44 +0000502
Chris Lattner4cc576b2010-04-16 00:24:57 +0000503 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000504 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000505 if (!CanConvertToScalar(BCI, Offset))
506 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000507 continue;
508 }
509
510 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
511 // If this is a GEP with a variable indices, we can't handle it.
512 if (!GEP->hasAllConstantIndices())
513 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000514
Chris Lattner4cc576b2010-04-16 00:24:57 +0000515 // Compute the offset that this GEP adds to the pointer.
516 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
517 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
518 &Indices[0], Indices.size());
519 // See if all uses can be converted.
520 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
521 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000522 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000523 HadNonMemTransferAccess = true;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000524 continue;
525 }
526
527 // If this is a constant sized memset of a constant value (e.g. 0) we can
528 // handle it.
529 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
Cameron Zwarich6be41eb2011-06-18 05:47:49 +0000530 // Store of constant value.
531 if (!isa<ConstantInt>(MSI->getValue()))
Chris Lattnera001b662010-04-16 00:38:19 +0000532 return false;
Cameron Zwarich6be41eb2011-06-18 05:47:49 +0000533
534 // Store of constant size.
535 ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
536 if (!Len)
537 return false;
538
539 // If the size differs from the alloca, we can only convert the alloca to
540 // an integer bag-of-bits.
541 // FIXME: This should handle all of the cases that are currently accepted
542 // as vector element insertions.
543 if (Len->getZExtValue() != AllocaSize || Offset != 0)
544 ScalarKind = Integer;
545
Chris Lattnera001b662010-04-16 00:38:19 +0000546 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000547 HadNonMemTransferAccess = true;
Chris Lattnera001b662010-04-16 00:38:19 +0000548 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000549 }
550
551 // If this is a memcpy or memmove into or out of the whole allocation, we
552 // can handle it like a load or store of the scalar type.
553 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000554 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
555 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
556 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000557
Chris Lattnera001b662010-04-16 00:38:19 +0000558 IsNotTrivial = true; // Can't be mem2reg'd.
559 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000560 }
Bob Wilson69743022011-01-13 20:59:44 +0000561
Chris Lattner4cc576b2010-04-16 00:24:57 +0000562 // Otherwise, we cannot handle this!
563 return false;
564 }
Bob Wilson69743022011-01-13 20:59:44 +0000565
Chris Lattner4cc576b2010-04-16 00:24:57 +0000566 return true;
567}
568
569/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
570/// directly. This happens when we are converting an "integer union" to a
571/// single integer scalar, or when we are converting a "vector union" to a
572/// vector with insert/extractelement instructions.
573///
574/// Offset is an offset from the original alloca, in bits that need to be
575/// shifted to the right. By the end of this, there should be no uses of Ptr.
576void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
577 uint64_t Offset) {
578 while (!Ptr->use_empty()) {
579 Instruction *User = cast<Instruction>(Ptr->use_back());
580
581 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
582 ConvertUsesToScalar(CI, NewAI, Offset);
583 CI->eraseFromParent();
584 continue;
585 }
586
587 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
588 // Compute the offset that this GEP adds to the pointer.
589 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
590 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
591 &Indices[0], Indices.size());
592 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
593 GEP->eraseFromParent();
594 continue;
595 }
Bob Wilson69743022011-01-13 20:59:44 +0000596
Chris Lattner61db1f52010-12-26 22:57:41 +0000597 IRBuilder<> Builder(User);
Bob Wilson69743022011-01-13 20:59:44 +0000598
Chris Lattner4cc576b2010-04-16 00:24:57 +0000599 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
600 // The load is a bit extract from NewAI shifted right by Offset bits.
601 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
602 Value *NewLoadVal
603 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
604 LI->replaceAllUsesWith(NewLoadVal);
605 LI->eraseFromParent();
606 continue;
607 }
Bob Wilson69743022011-01-13 20:59:44 +0000608
Chris Lattner4cc576b2010-04-16 00:24:57 +0000609 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
610 assert(SI->getOperand(0) != Ptr && "Consistency error!");
611 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
612 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
613 Builder);
614 Builder.CreateStore(New, NewAI);
615 SI->eraseFromParent();
Bob Wilson69743022011-01-13 20:59:44 +0000616
Chris Lattner4cc576b2010-04-16 00:24:57 +0000617 // If the load we just inserted is now dead, then the inserted store
618 // overwrote the entire thing.
619 if (Old->use_empty())
620 Old->eraseFromParent();
621 continue;
622 }
Bob Wilson69743022011-01-13 20:59:44 +0000623
Chris Lattner4cc576b2010-04-16 00:24:57 +0000624 // If this is a constant sized memset of a constant value (e.g. 0) we can
625 // transform it into a store of the expanded constant value.
626 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
627 assert(MSI->getRawDest() == Ptr && "Consistency error!");
628 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
629 if (NumBytes != 0) {
630 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson69743022011-01-13 20:59:44 +0000631
Chris Lattner4cc576b2010-04-16 00:24:57 +0000632 // Compute the value replicated the right number of times.
633 APInt APVal(NumBytes*8, Val);
634
635 // Splat the value if non-zero.
636 if (Val)
637 for (unsigned i = 1; i != NumBytes; ++i)
638 APVal |= APVal << 8;
Bob Wilson69743022011-01-13 20:59:44 +0000639
Chris Lattner4cc576b2010-04-16 00:24:57 +0000640 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
641 Value *New = ConvertScalar_InsertValue(
642 ConstantInt::get(User->getContext(), APVal),
643 Old, Offset, Builder);
644 Builder.CreateStore(New, NewAI);
Bob Wilson69743022011-01-13 20:59:44 +0000645
Chris Lattner4cc576b2010-04-16 00:24:57 +0000646 // If the load we just inserted is now dead, then the memset overwrote
647 // the entire thing.
648 if (Old->use_empty())
Bob Wilson69743022011-01-13 20:59:44 +0000649 Old->eraseFromParent();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000650 }
651 MSI->eraseFromParent();
652 continue;
653 }
654
655 // If this is a memcpy or memmove into or out of the whole allocation, we
656 // can handle it like a load or store of the scalar type.
657 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
658 assert(Offset == 0 && "must be store to start of alloca");
Bob Wilson69743022011-01-13 20:59:44 +0000659
Chris Lattner4cc576b2010-04-16 00:24:57 +0000660 // If the source and destination are both to the same alloca, then this is
661 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
662 // as appropriate.
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000663 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
Bob Wilson69743022011-01-13 20:59:44 +0000664
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000665 if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000666 // Dest must be OrigAI, change this to be a load from the original
667 // pointer (bitcasted), then a store to our new alloca.
668 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
669 Value *SrcPtr = MTI->getSource();
Mon P Wange90a6332010-12-23 01:41:32 +0000670 const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
671 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
672 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
673 AIPTy = PointerType::get(AIPTy->getElementType(),
674 SPTy->getAddressSpace());
675 }
676 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
677
Chris Lattner4cc576b2010-04-16 00:24:57 +0000678 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
679 SrcVal->setAlignment(MTI->getAlignment());
680 Builder.CreateStore(SrcVal, NewAI);
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000681 } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000682 // Src must be OrigAI, change this to be a load from NewAI then a store
683 // through the original dest pointer (bitcasted).
684 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
685 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
686
Mon P Wange90a6332010-12-23 01:41:32 +0000687 const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
688 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
689 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
690 AIPTy = PointerType::get(AIPTy->getElementType(),
691 DPTy->getAddressSpace());
692 }
693 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
694
Chris Lattner4cc576b2010-04-16 00:24:57 +0000695 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
696 NewStore->setAlignment(MTI->getAlignment());
697 } else {
698 // Noop transfer. Src == Dst
699 }
700
701 MTI->eraseFromParent();
702 continue;
703 }
Bob Wilson69743022011-01-13 20:59:44 +0000704
Chris Lattner4cc576b2010-04-16 00:24:57 +0000705 llvm_unreachable("Unsupported operation!");
706 }
707}
708
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000709/// getScaledElementType - Gets a scaled element type for a partial vector
Cameron Zwarich344731c2011-04-20 21:48:38 +0000710/// access of an alloca. The input types must be integer or floating-point
711/// scalar or vector types, and the resulting type is an integer, float or
712/// double.
713static const Type *getScaledElementType(const Type *Ty1, const Type *Ty2,
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000714 unsigned NewBitWidth) {
Cameron Zwarich344731c2011-04-20 21:48:38 +0000715 bool IsFP1 = Ty1->isFloatingPointTy() ||
716 (Ty1->isVectorTy() &&
717 cast<VectorType>(Ty1)->getElementType()->isFloatingPointTy());
718 bool IsFP2 = Ty2->isFloatingPointTy() ||
719 (Ty2->isVectorTy() &&
720 cast<VectorType>(Ty2)->getElementType()->isFloatingPointTy());
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000721
Cameron Zwarich344731c2011-04-20 21:48:38 +0000722 LLVMContext &Context = Ty1->getContext();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000723
Cameron Zwarich344731c2011-04-20 21:48:38 +0000724 // Prefer floating-point types over integer types, as integer types may have
725 // been created by earlier scalar replacement.
726 if (IsFP1 || IsFP2) {
727 if (NewBitWidth == 32)
728 return Type::getFloatTy(Context);
729 if (NewBitWidth == 64)
730 return Type::getDoubleTy(Context);
731 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000732
Cameron Zwarich344731c2011-04-20 21:48:38 +0000733 return Type::getIntNTy(Context, NewBitWidth);
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000734}
735
Mon P Wangddf9abf2011-04-14 08:04:01 +0000736/// CreateShuffleVectorCast - Creates a shuffle vector to convert one vector
737/// to another vector of the same element type which has the same allocation
738/// size but different primitive sizes (e.g. <3 x i32> and <4 x i32>).
739static Value *CreateShuffleVectorCast(Value *FromVal, const Type *ToType,
740 IRBuilder<> &Builder) {
741 const Type *FromType = FromVal->getType();
Mon P Wang481823a2011-04-14 19:20:42 +0000742 const VectorType *FromVTy = cast<VectorType>(FromType);
743 const VectorType *ToVTy = cast<VectorType>(ToType);
744 assert((ToVTy->getElementType() == FromVTy->getElementType()) &&
Mon P Wangddf9abf2011-04-14 08:04:01 +0000745 "Vectors must have the same element type");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000746 Value *UnV = UndefValue::get(FromType);
747 unsigned numEltsFrom = FromVTy->getNumElements();
748 unsigned numEltsTo = ToVTy->getNumElements();
749
750 SmallVector<Constant*, 3> Args;
Mon P Wang481823a2011-04-14 19:20:42 +0000751 const Type* Int32Ty = Builder.getInt32Ty();
Mon P Wangddf9abf2011-04-14 08:04:01 +0000752 unsigned minNumElts = std::min(numEltsFrom, numEltsTo);
753 unsigned i;
754 for (i=0; i != minNumElts; ++i)
Mon P Wang481823a2011-04-14 19:20:42 +0000755 Args.push_back(ConstantInt::get(Int32Ty, i));
Mon P Wangddf9abf2011-04-14 08:04:01 +0000756
757 if (i < numEltsTo) {
Mon P Wang481823a2011-04-14 19:20:42 +0000758 Constant* UnC = UndefValue::get(Int32Ty);
Mon P Wangddf9abf2011-04-14 08:04:01 +0000759 for (; i != numEltsTo; ++i)
760 Args.push_back(UnC);
761 }
762 Constant *Mask = ConstantVector::get(Args);
763 return Builder.CreateShuffleVector(FromVal, UnV, Mask, "tmpV");
764}
765
Chris Lattner4cc576b2010-04-16 00:24:57 +0000766/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
767/// or vector value FromVal, extracting the bits from the offset specified by
768/// Offset. This returns the value, which is of type ToType.
769///
770/// This happens when we are converting an "integer union" to a single
771/// integer scalar, or when we are converting a "vector union" to a vector with
772/// insert/extractelement instructions.
773///
774/// Offset is an offset from the original alloca, in bits that need to be
775/// shifted to the right.
776Value *ConvertToScalarInfo::
777ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
778 uint64_t Offset, IRBuilder<> &Builder) {
779 // If the load is of the whole new alloca, no conversion is needed.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000780 const Type *FromType = FromVal->getType();
781 if (FromType == ToType && Offset == 0)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000782 return FromVal;
783
784 // If the result alloca is a vector type, this is either an element
785 // access or a bitcast to another vector type of the same size.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000786 if (const VectorType *VTy = dyn_cast<VectorType>(FromType)) {
Cameron Zwarich0398d612011-06-08 22:08:31 +0000787 unsigned FromTypeSize = TD.getTypeAllocSize(FromType);
Cameron Zwarich9827b782011-03-29 05:19:52 +0000788 unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
Cameron Zwarich0398d612011-06-08 22:08:31 +0000789 if (FromTypeSize == ToTypeSize) {
Mon P Wangddf9abf2011-04-14 08:04:01 +0000790 // If the two types have the same primitive size, use a bit cast.
791 // Otherwise, it is two vectors with the same element type that has
792 // the same allocation size but different number of elements so use
793 // a shuffle vector.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000794 if (FromType->getPrimitiveSizeInBits() ==
795 ToType->getPrimitiveSizeInBits())
796 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000797 else
798 return CreateShuffleVectorCast(FromVal, ToType, Builder);
Mon P Wangbe0761c2011-04-13 21:40:02 +0000799 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000800
Cameron Zwarich0398d612011-06-08 22:08:31 +0000801 if (isPowerOf2_64(FromTypeSize / ToTypeSize)) {
Cameron Zwarich344731c2011-04-20 21:48:38 +0000802 assert(!(ToType->isVectorTy() && Offset != 0) && "Can't extract a value "
803 "of a smaller vector type at a nonzero offset.");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000804
Cameron Zwarich344731c2011-04-20 21:48:38 +0000805 const Type *CastElementTy = getScaledElementType(FromType, ToType,
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000806 ToTypeSize * 8);
Cameron Zwarich0398d612011-06-08 22:08:31 +0000807 unsigned NumCastVectorElements = FromTypeSize / ToTypeSize;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000808
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000809 LLVMContext &Context = FromVal->getContext();
810 const Type *CastTy = VectorType::get(CastElementTy,
811 NumCastVectorElements);
812 Value *Cast = Builder.CreateBitCast(FromVal, CastTy, "tmp");
Cameron Zwarich344731c2011-04-20 21:48:38 +0000813
814 unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
815 unsigned Elt = Offset/EltSize;
816 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000817 Value *Extract = Builder.CreateExtractElement(Cast, ConstantInt::get(
Cameron Zwarich344731c2011-04-20 21:48:38 +0000818 Type::getInt32Ty(Context), Elt), "tmp");
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000819 return Builder.CreateBitCast(Extract, ToType, "tmp");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000820 }
Chris Lattner4cc576b2010-04-16 00:24:57 +0000821
822 // Otherwise it must be an element access.
823 unsigned Elt = 0;
824 if (Offset) {
825 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
826 Elt = Offset/EltSize;
827 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
828 }
829 // Return the element extracted out of it.
830 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
831 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
832 if (V->getType() != ToType)
833 V = Builder.CreateBitCast(V, ToType, "tmp");
834 return V;
835 }
Bob Wilson69743022011-01-13 20:59:44 +0000836
Chris Lattner4cc576b2010-04-16 00:24:57 +0000837 // If ToType is a first class aggregate, extract out each of the pieces and
838 // use insertvalue's to form the FCA.
839 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
840 const StructLayout &Layout = *TD.getStructLayout(ST);
841 Value *Res = UndefValue::get(ST);
842 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
843 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
844 Offset+Layout.getElementOffsetInBits(i),
845 Builder);
846 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
847 }
848 return Res;
849 }
Bob Wilson69743022011-01-13 20:59:44 +0000850
Chris Lattner4cc576b2010-04-16 00:24:57 +0000851 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
852 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
853 Value *Res = UndefValue::get(AT);
854 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
855 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
856 Offset+i*EltSize, Builder);
857 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
858 }
859 return Res;
860 }
861
862 // Otherwise, this must be a union that was converted to an integer value.
863 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
864
865 // If this is a big-endian system and the load is narrower than the
866 // full alloca type, we need to do a shift to get the right bits.
867 int ShAmt = 0;
868 if (TD.isBigEndian()) {
869 // On big-endian machines, the lowest bit is stored at the bit offset
870 // from the pointer given by getTypeStoreSizeInBits. This matters for
871 // integers with a bitwidth that is not a multiple of 8.
872 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
873 TD.getTypeStoreSizeInBits(ToType) - Offset;
874 } else {
875 ShAmt = Offset;
876 }
877
878 // Note: we support negative bitwidths (with shl) which are not defined.
879 // We do this to support (f.e.) loads off the end of a structure where
880 // only some bits are used.
881 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
882 FromVal = Builder.CreateLShr(FromVal,
883 ConstantInt::get(FromVal->getType(),
884 ShAmt), "tmp");
885 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson69743022011-01-13 20:59:44 +0000886 FromVal = Builder.CreateShl(FromVal,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000887 ConstantInt::get(FromVal->getType(),
888 -ShAmt), "tmp");
889
890 // Finally, unconditionally truncate the integer to the right width.
891 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
892 if (LIBitWidth < NTy->getBitWidth())
893 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000894 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000895 LIBitWidth), "tmp");
896 else if (LIBitWidth > NTy->getBitWidth())
897 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000898 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000899 LIBitWidth), "tmp");
900
901 // If the result is an integer, this is a trunc or bitcast.
902 if (ToType->isIntegerTy()) {
903 // Should be done.
904 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
905 // Just do a bitcast, we know the sizes match up.
906 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
907 } else {
908 // Otherwise must be a pointer.
909 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
910 }
911 assert(FromVal->getType() == ToType && "Didn't convert right?");
912 return FromVal;
913}
914
915/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
916/// or vector value "Old" at the offset specified by Offset.
917///
918/// This happens when we are converting an "integer union" to a
919/// single integer scalar, or when we are converting a "vector union" to a
920/// vector with insert/extractelement instructions.
921///
922/// Offset is an offset from the original alloca, in bits that need to be
923/// shifted to the right.
924Value *ConvertToScalarInfo::
925ConvertScalar_InsertValue(Value *SV, Value *Old,
926 uint64_t Offset, IRBuilder<> &Builder) {
927 // Convert the stored type to the actual type, shift it left to insert
928 // then 'or' into place.
929 const Type *AllocaType = Old->getType();
930 LLVMContext &Context = Old->getContext();
931
932 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
933 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
934 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
Bob Wilson69743022011-01-13 20:59:44 +0000935
Chris Lattner4cc576b2010-04-16 00:24:57 +0000936 // Changing the whole vector with memset or with an access of a different
937 // vector type?
Mon P Wangbe0761c2011-04-13 21:40:02 +0000938 if (ValSize == VecSize) {
Mon P Wangddf9abf2011-04-14 08:04:01 +0000939 // If the two types have the same primitive size, use a bit cast.
940 // Otherwise, it is two vectors with the same element type that has
941 // the same allocation size but different number of elements so use
942 // a shuffle vector.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000943 if (VTy->getPrimitiveSizeInBits() ==
944 SV->getType()->getPrimitiveSizeInBits())
945 return Builder.CreateBitCast(SV, AllocaType, "tmp");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000946 else
947 return CreateShuffleVectorCast(SV, VTy, Builder);
Mon P Wangbe0761c2011-04-13 21:40:02 +0000948 }
Chris Lattner4cc576b2010-04-16 00:24:57 +0000949
Cameron Zwarich344731c2011-04-20 21:48:38 +0000950 if (isPowerOf2_64(VecSize / ValSize)) {
951 assert(!(SV->getType()->isVectorTy() && Offset != 0) && "Can't insert a "
952 "value of a smaller vector type at a nonzero offset.");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000953
Cameron Zwarich344731c2011-04-20 21:48:38 +0000954 const Type *CastElementTy = getScaledElementType(VTy, SV->getType(),
955 ValSize);
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000956 unsigned NumCastVectorElements = VecSize / ValSize;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000957
958 LLVMContext &Context = SV->getContext();
959 const Type *OldCastTy = VectorType::get(CastElementTy,
960 NumCastVectorElements);
961 Value *OldCast = Builder.CreateBitCast(Old, OldCastTy, "tmp");
962
963 Value *SVCast = Builder.CreateBitCast(SV, CastElementTy, "tmp");
Cameron Zwarich344731c2011-04-20 21:48:38 +0000964
965 unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
966 unsigned Elt = Offset/EltSize;
967 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000968 Value *Insert =
969 Builder.CreateInsertElement(OldCast, SVCast, ConstantInt::get(
Cameron Zwarich344731c2011-04-20 21:48:38 +0000970 Type::getInt32Ty(Context), Elt), "tmp");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000971 return Builder.CreateBitCast(Insert, AllocaType, "tmp");
972 }
973
Chris Lattner4cc576b2010-04-16 00:24:57 +0000974 // Must be an element insertion.
Cameron Zwarichc5c43b92011-04-20 21:48:34 +0000975 assert(SV->getType() == VTy->getElementType());
976 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner4cc576b2010-04-16 00:24:57 +0000977 unsigned Elt = Offset/EltSize;
Cameron Zwarichc5c43b92011-04-20 21:48:34 +0000978 return Builder.CreateInsertElement(Old, SV,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000979 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
980 "tmp");
Chris Lattner4cc576b2010-04-16 00:24:57 +0000981 }
Bob Wilson69743022011-01-13 20:59:44 +0000982
Chris Lattner4cc576b2010-04-16 00:24:57 +0000983 // If SV is a first-class aggregate value, insert each value recursively.
984 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
985 const StructLayout &Layout = *TD.getStructLayout(ST);
986 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
987 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000988 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000989 Offset+Layout.getElementOffsetInBits(i),
990 Builder);
991 }
992 return Old;
993 }
Bob Wilson69743022011-01-13 20:59:44 +0000994
Chris Lattner4cc576b2010-04-16 00:24:57 +0000995 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
996 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
997 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
998 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
999 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
1000 }
1001 return Old;
1002 }
1003
1004 // If SV is a float, convert it to the appropriate integer type.
1005 // If it is a pointer, do the same.
1006 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
1007 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
1008 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
1009 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
1010 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
1011 SV = Builder.CreateBitCast(SV,
1012 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
1013 else if (SV->getType()->isPointerTy())
1014 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
1015
1016 // Zero extend or truncate the value if needed.
1017 if (SV->getType() != AllocaType) {
1018 if (SV->getType()->getPrimitiveSizeInBits() <
1019 AllocaType->getPrimitiveSizeInBits())
1020 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
1021 else {
1022 // Truncation may be needed if storing more than the alloca can hold
1023 // (undefined behavior).
1024 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
1025 SrcWidth = DestWidth;
1026 SrcStoreWidth = DestStoreWidth;
1027 }
1028 }
1029
1030 // If this is a big-endian system and the store is narrower than the
1031 // full alloca type, we need to do a shift to get the right bits.
1032 int ShAmt = 0;
1033 if (TD.isBigEndian()) {
1034 // On big-endian machines, the lowest bit is stored at the bit offset
1035 // from the pointer given by getTypeStoreSizeInBits. This matters for
1036 // integers with a bitwidth that is not a multiple of 8.
1037 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1038 } else {
1039 ShAmt = Offset;
1040 }
1041
1042 // Note: we support negative bitwidths (with shr) which are not defined.
1043 // We do this to support (f.e.) stores off the end of a structure where
1044 // only some bits in the structure are set.
1045 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1046 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1047 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
1048 ShAmt), "tmp");
1049 Mask <<= ShAmt;
1050 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1051 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
1052 -ShAmt), "tmp");
1053 Mask = Mask.lshr(-ShAmt);
1054 }
1055
1056 // Mask out the bits we are about to insert from the old value, and or
1057 // in the new bits.
1058 if (SrcWidth != DestWidth) {
1059 assert(DestWidth > SrcWidth);
1060 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1061 SV = Builder.CreateOr(Old, SV, "ins");
1062 }
1063 return SV;
1064}
1065
1066
1067//===----------------------------------------------------------------------===//
1068// SRoA Driver
1069//===----------------------------------------------------------------------===//
1070
1071
Chris Lattnered7b41e2003-05-27 15:45:27 +00001072bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +00001073 TD = getAnalysisIfAvailable<TargetData>();
1074
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001075 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +00001076
1077 // FIXME: ScalarRepl currently depends on TargetData more than it
1078 // theoretically needs to. It should be refactored in order to support
1079 // target-independent IR. Until this is done, just skip the actual
1080 // scalar-replacement portion of this pass.
1081 if (!TD) return Changed;
1082
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001083 while (1) {
1084 bool LocalChange = performScalarRepl(F);
1085 if (!LocalChange) break; // No need to repromote if no scalarrepl
1086 Changed = true;
1087 LocalChange = performPromotion(F);
1088 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
1089 }
Chris Lattner38aec322003-09-11 16:45:55 +00001090
1091 return Changed;
1092}
1093
Chris Lattnerd0f56132011-01-14 19:50:47 +00001094namespace {
1095class AllocaPromoter : public LoadAndStorePromoter {
1096 AllocaInst *AI;
Devang Patel231a5ab2011-07-06 21:09:55 +00001097 DbgDeclareInst *DDI;
1098 DIBuilder *DIB;
Chris Lattnerd0f56132011-01-14 19:50:47 +00001099public:
Cameron Zwarichc8279392011-05-24 03:10:43 +00001100 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
Devang Patel231a5ab2011-07-06 21:09:55 +00001101 DIBuilder *DB)
1102 : LoadAndStorePromoter(Insts, S), AI(0), DDI(0), DIB(DB) {}
Chris Lattnerd0f56132011-01-14 19:50:47 +00001103
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001104 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerd0f56132011-01-14 19:50:47 +00001105 // Remember which alloca we're promoting (for isInstInList).
1106 this->AI = AI;
Devang Patel231a5ab2011-07-06 21:09:55 +00001107 DDI = FindAllocaDbgDeclare(AI);
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001108 LoadAndStorePromoter::run(Insts);
Chris Lattnerd0f56132011-01-14 19:50:47 +00001109 AI->eraseFromParent();
Devang Patel231a5ab2011-07-06 21:09:55 +00001110 if (DDI)
1111 DDI->eraseFromParent();
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001112 }
1113
Chris Lattnerd0f56132011-01-14 19:50:47 +00001114 virtual bool isInstInList(Instruction *I,
1115 const SmallVectorImpl<Instruction*> &Insts) const {
1116 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1117 return LI->getOperand(0) == AI;
1118 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001119 }
Devang Patel231a5ab2011-07-06 21:09:55 +00001120
1121 virtual void updateDebugInfo(Instruction *I) const {
1122 if (!DDI)
1123 return;
1124 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1125 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
1126 else if (LoadInst *LI = dyn_cast<LoadInst>(I))
1127 ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
1128 }
Chris Lattnerd0f56132011-01-14 19:50:47 +00001129};
1130} // end anon namespace
Chris Lattner38aec322003-09-11 16:45:55 +00001131
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001132/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1133/// subsequently loaded can be rewritten to load both input pointers and then
1134/// select between the result, allowing the load of the alloca to be promoted.
1135/// From this:
1136/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1137/// %V = load i32* %P2
1138/// to:
1139/// %V1 = load i32* %Alloca -> will be mem2reg'd
1140/// %V2 = load i32* %Other
Chris Lattnere3357862011-01-24 01:07:11 +00001141/// %V = select i1 %cond, i32 %V1, i32 %V2
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001142///
1143/// We can do this to a select if its only uses are loads and if the operand to
1144/// the select can be loaded unconditionally.
1145static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
1146 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1147 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1148
1149 for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1150 UI != UE; ++UI) {
1151 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1152 if (LI == 0 || LI->isVolatile()) return false;
1153
Chris Lattnere3357862011-01-24 01:07:11 +00001154 // Both operands to the select need to be dereferencable, either absolutely
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001155 // (e.g. allocas) or at this point because we can see other accesses to it.
1156 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1157 LI->getAlignment(), TD))
1158 return false;
1159 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1160 LI->getAlignment(), TD))
1161 return false;
1162 }
1163
1164 return true;
1165}
1166
Chris Lattnere3357862011-01-24 01:07:11 +00001167/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1168/// subsequently loaded can be rewritten to load both input pointers in the pred
1169/// blocks and then PHI the results, allowing the load of the alloca to be
1170/// promoted.
1171/// From this:
1172/// %P2 = phi [i32* %Alloca, i32* %Other]
1173/// %V = load i32* %P2
1174/// to:
1175/// %V1 = load i32* %Alloca -> will be mem2reg'd
1176/// ...
1177/// %V2 = load i32* %Other
1178/// ...
1179/// %V = phi [i32 %V1, i32 %V2]
1180///
1181/// We can do this to a select if its only uses are loads and if the operand to
1182/// the select can be loaded unconditionally.
1183static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
1184 // For now, we can only do this promotion if the load is in the same block as
1185 // the PHI, and if there are no stores between the phi and load.
1186 // TODO: Allow recursive phi users.
1187 // TODO: Allow stores.
1188 BasicBlock *BB = PN->getParent();
1189 unsigned MaxAlign = 0;
1190 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1191 UI != UE; ++UI) {
1192 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1193 if (LI == 0 || LI->isVolatile()) return false;
1194
1195 // For now we only allow loads in the same block as the PHI. This is a
1196 // common case that happens when instcombine merges two loads through a PHI.
1197 if (LI->getParent() != BB) return false;
1198
1199 // Ensure that there are no instructions between the PHI and the load that
1200 // could store.
1201 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1202 if (BBI->mayWriteToMemory())
1203 return false;
1204
1205 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1206 }
1207
1208 // Okay, we know that we have one or more loads in the same block as the PHI.
1209 // We can transform this if it is safe to push the loads into the predecessor
1210 // blocks. The only thing to watch out for is that we can't put a possibly
1211 // trapping load in the predecessor if it is a critical edge.
1212 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1213 BasicBlock *Pred = PN->getIncomingBlock(i);
1214
1215 // If the predecessor has a single successor, then the edge isn't critical.
1216 if (Pred->getTerminator()->getNumSuccessors() == 1)
1217 continue;
1218
1219 Value *InVal = PN->getIncomingValue(i);
1220
1221 // If the InVal is an invoke in the pred, we can't put a load on the edge.
1222 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
1223 if (II->getParent() == Pred)
1224 return false;
1225
1226 // If this pointer is always safe to load, or if we can prove that there is
1227 // already a load in the block, then we can move the load to the pred block.
1228 if (InVal->isDereferenceablePointer() ||
1229 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1230 continue;
1231
1232 return false;
1233 }
1234
1235 return true;
1236}
1237
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001238
1239/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1240/// direct (non-volatile) loads and stores to it. If the alloca is close but
1241/// not quite there, this will transform the code to allow promotion. As such,
1242/// it is a non-pure predicate.
1243static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
1244 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1245 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1246
1247 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1248 UI != UE; ++UI) {
1249 User *U = *UI;
1250 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1251 if (LI->isVolatile())
1252 return false;
1253 continue;
1254 }
1255
1256 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1257 if (SI->getOperand(0) == AI || SI->isVolatile())
1258 return false; // Don't allow a store OF the AI, only INTO the AI.
1259 continue;
1260 }
1261
1262 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1263 // If the condition being selected on is a constant, fold the select, yes
1264 // this does (rarely) happen early on.
1265 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1266 Value *Result = SI->getOperand(1+CI->isZero());
1267 SI->replaceAllUsesWith(Result);
1268 SI->eraseFromParent();
1269
1270 // This is very rare and we just scrambled the use list of AI, start
1271 // over completely.
1272 return tryToMakeAllocaBePromotable(AI, TD);
1273 }
1274
1275 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1276 // loads, then we can transform this by rewriting the select.
1277 if (!isSafeSelectToSpeculate(SI, TD))
1278 return false;
1279
1280 InstsToRewrite.insert(SI);
1281 continue;
1282 }
1283
Chris Lattnere3357862011-01-24 01:07:11 +00001284 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1285 if (PN->use_empty()) { // Dead PHIs can be stripped.
1286 InstsToRewrite.insert(PN);
1287 continue;
1288 }
1289
1290 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1291 // in the pred blocks, then we can transform this by rewriting the PHI.
1292 if (!isSafePHIToSpeculate(PN, TD))
1293 return false;
1294
1295 InstsToRewrite.insert(PN);
1296 continue;
1297 }
1298
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001299 return false;
1300 }
1301
1302 // If there are no instructions to rewrite, then all uses are load/stores and
1303 // we're done!
1304 if (InstsToRewrite.empty())
1305 return true;
1306
1307 // If we have instructions that need to be rewritten for this to be promotable
1308 // take care of it now.
1309 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
Chris Lattnere3357862011-01-24 01:07:11 +00001310 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1311 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1312 // loads with a new select.
1313 while (!SI->use_empty()) {
1314 LoadInst *LI = cast<LoadInst>(SI->use_back());
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001315
Chris Lattnere3357862011-01-24 01:07:11 +00001316 IRBuilder<> Builder(LI);
1317 LoadInst *TrueLoad =
1318 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1319 LoadInst *FalseLoad =
Nick Lewycky394d1f12011-07-01 06:27:03 +00001320 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
Chris Lattnere3357862011-01-24 01:07:11 +00001321
1322 // Transfer alignment and TBAA info if present.
1323 TrueLoad->setAlignment(LI->getAlignment());
1324 FalseLoad->setAlignment(LI->getAlignment());
1325 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1326 TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1327 FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1328 }
1329
1330 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1331 V->takeName(LI);
1332 LI->replaceAllUsesWith(V);
1333 LI->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001334 }
Chris Lattnere3357862011-01-24 01:07:11 +00001335
1336 // Now that all the loads are gone, the select is gone too.
1337 SI->eraseFromParent();
1338 continue;
1339 }
1340
1341 // Otherwise, we have a PHI node which allows us to push the loads into the
1342 // predecessors.
1343 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1344 if (PN->use_empty()) {
1345 PN->eraseFromParent();
1346 continue;
1347 }
1348
1349 const Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
Jay Foad3ecfc862011-03-30 11:28:46 +00001350 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1351 PN->getName()+".ld", PN);
Chris Lattnere3357862011-01-24 01:07:11 +00001352
1353 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1354 // matter which one we get and if any differ, it doesn't matter.
1355 LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1356 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1357 unsigned Align = SomeLoad->getAlignment();
1358
1359 // Rewrite all loads of the PN to use the new PHI.
1360 while (!PN->use_empty()) {
1361 LoadInst *LI = cast<LoadInst>(PN->use_back());
1362 LI->replaceAllUsesWith(NewPN);
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001363 LI->eraseFromParent();
1364 }
1365
Chris Lattnere3357862011-01-24 01:07:11 +00001366 // Inject loads into all of the pred blocks. Keep track of which blocks we
1367 // insert them into in case we have multiple edges from the same block.
1368 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1369
1370 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1371 BasicBlock *Pred = PN->getIncomingBlock(i);
1372 LoadInst *&Load = InsertedLoads[Pred];
1373 if (Load == 0) {
1374 Load = new LoadInst(PN->getIncomingValue(i),
1375 PN->getName() + "." + Pred->getName(),
1376 Pred->getTerminator());
1377 Load->setAlignment(Align);
1378 if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1379 }
1380
1381 NewPN->addIncoming(Load, Pred);
1382 }
1383
1384 PN->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001385 }
1386
1387 ++NumAdjusted;
1388 return true;
1389}
1390
Chris Lattner38aec322003-09-11 16:45:55 +00001391bool SROA::performPromotion(Function &F) {
1392 std::vector<AllocaInst*> Allocas;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001393 DominatorTree *DT = 0;
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001394 if (HasDomTree)
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001395 DT = &getAnalysis<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +00001396
Chris Lattner02a3be02003-09-20 14:39:18 +00001397 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Devang Patel231a5ab2011-07-06 21:09:55 +00001398 DIBuilder DIB(*F.getParent());
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001399 bool Changed = false;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001400 SmallVector<Instruction*, 64> Insts;
Chris Lattner38aec322003-09-11 16:45:55 +00001401 while (1) {
1402 Allocas.clear();
1403
1404 // Find allocas that are safe to promote, by looking at all instructions in
1405 // the entry node
1406 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1407 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001408 if (tryToMakeAllocaBePromotable(AI, TD))
Chris Lattner38aec322003-09-11 16:45:55 +00001409 Allocas.push_back(AI);
1410
1411 if (Allocas.empty()) break;
1412
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001413 if (HasDomTree)
Cameron Zwarich419e8a62011-01-17 17:38:41 +00001414 PromoteMemToReg(Allocas, *DT);
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001415 else {
1416 SSAUpdater SSA;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001417 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1418 AllocaInst *AI = Allocas[i];
1419
1420 // Build list of instructions to promote.
1421 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1422 UI != E; ++UI)
1423 Insts.push_back(cast<Instruction>(*UI));
Devang Patel231a5ab2011-07-06 21:09:55 +00001424 AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001425 Insts.clear();
1426 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001427 }
Chris Lattner38aec322003-09-11 16:45:55 +00001428 NumPromoted += Allocas.size();
1429 Changed = true;
1430 }
1431
1432 return Changed;
1433}
1434
Chris Lattner4cc576b2010-04-16 00:24:57 +00001435
Bob Wilson3992feb2010-02-03 17:23:56 +00001436/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1437/// SROA. It must be a struct or array type with a small number of elements.
1438static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
1439 const Type *T = AI->getAllocatedType();
1440 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +00001441 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +00001442 return ST->getNumElements() <= 32;
1443 // Arrays are much less likely to be safe for SROA; only consider
1444 // them if they are very small.
1445 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1446 return AT->getNumElements() <= 8;
1447 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +00001448}
1449
Chris Lattnerc4472072010-04-15 23:50:26 +00001450
Chris Lattner38aec322003-09-11 16:45:55 +00001451// performScalarRepl - This algorithm is a simple worklist driven algorithm,
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001452// which runs on all of the alloca instructions in the function, removing them
1453// if they are only used by getelementptr instructions.
Chris Lattner38aec322003-09-11 16:45:55 +00001454//
1455bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001456 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +00001457
Chris Lattner31d80102010-04-15 21:59:20 +00001458 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +00001459 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001460 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +00001461 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +00001462 WorkList.push_back(A);
1463
1464 // Process the worklist
1465 bool Changed = false;
1466 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001467 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001468 WorkList.pop_back();
Bob Wilson69743022011-01-13 20:59:44 +00001469
Chris Lattneradd2bd72006-12-22 23:14:42 +00001470 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1471 // with unused elements.
1472 if (AI->use_empty()) {
1473 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +00001474 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +00001475 continue;
1476 }
Chris Lattner7809ecd2009-02-03 01:30:09 +00001477
1478 // If this alloca is impossible for us to promote, reject it early.
1479 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1480 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001481
Chris Lattner79b3bd32007-04-25 06:40:51 +00001482 // Check to see if this allocation is only modified by a memcpy/memmove from
1483 // a constant global. If this is the case, we can change all users to use
1484 // the constant global instead. This is commonly produced by the CFE by
1485 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1486 // is only subsequently read.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001487 SmallVector<Instruction *, 4> ToDelete;
1488 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(AI, ToDelete)) {
David Greene504c7d82010-01-05 01:27:09 +00001489 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001490 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
1491 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
1492 ToDelete[i]->eraseFromParent();
1493 Constant *TheSrc = cast<Constant>(Copy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001494 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001495 Copy->eraseFromParent(); // Don't mutate the global.
Chris Lattner79b3bd32007-04-25 06:40:51 +00001496 AI->eraseFromParent();
1497 ++NumGlobals;
1498 Changed = true;
1499 continue;
1500 }
Bob Wilson69743022011-01-13 20:59:44 +00001501
Chris Lattner7809ecd2009-02-03 01:30:09 +00001502 // Check to see if we can perform the core SROA transformation. We cannot
1503 // transform the allocation instruction if it is an array allocation
1504 // (allocations OF arrays are ok though), and an allocation of a scalar
1505 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +00001506 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +00001507
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +00001508 // Do not promote [0 x %struct].
1509 if (AllocaSize == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001510
Chris Lattner31d80102010-04-15 21:59:20 +00001511 // Do not promote any struct whose size is too big.
1512 if (AllocaSize > SRThreshold) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001513
Bob Wilson3992feb2010-02-03 17:23:56 +00001514 // If the alloca looks like a good candidate for scalar replacement, and if
1515 // all its users can be transformed, then split up the aggregate into its
1516 // separate elements.
1517 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1518 DoScalarReplacement(AI, WorkList);
1519 Changed = true;
1520 continue;
1521 }
1522
Chris Lattner6e733d32009-01-28 20:16:43 +00001523 // If we can turn this aggregate value (potentially with casts) into a
1524 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001525 // IsNotTrivial tracks whether this is something that mem2reg could have
1526 // promoted itself. If so, we don't want to transform it needlessly. Note
1527 // that we can't just check based on the type: the alloca may be of an i32
1528 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +00001529 if (AllocaInst *NewAI =
1530 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001531 NewAI->takeName(AI);
1532 AI->eraseFromParent();
1533 ++NumConverted;
1534 Changed = true;
1535 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001536 }
1537
Chris Lattner7809ecd2009-02-03 01:30:09 +00001538 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +00001539 }
1540
1541 return Changed;
1542}
Chris Lattner5e062a12003-05-30 04:15:41 +00001543
Chris Lattnera10b29b2007-04-25 05:02:56 +00001544/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1545/// predicate, do SROA now.
Bob Wilson69743022011-01-13 20:59:44 +00001546void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001547 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +00001548 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +00001549 SmallVector<AllocaInst*, 32> ElementAllocas;
1550 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1551 ElementAllocas.reserve(ST->getNumContainedTypes());
1552 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Bob Wilson69743022011-01-13 20:59:44 +00001553 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +00001554 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001555 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001556 ElementAllocas.push_back(NA);
1557 WorkList.push_back(NA); // Add to worklist for recursive processing
1558 }
1559 } else {
1560 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1561 ElementAllocas.reserve(AT->getNumElements());
1562 const Type *ElTy = AT->getElementType();
1563 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +00001564 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001565 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001566 ElementAllocas.push_back(NA);
1567 WorkList.push_back(NA); // Add to worklist for recursive processing
1568 }
1569 }
1570
Bob Wilsonb742def2009-12-18 20:14:40 +00001571 // Now that we have created the new alloca instructions, rewrite all the
1572 // uses of the old alloca.
1573 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +00001574
Bob Wilsonb742def2009-12-18 20:14:40 +00001575 // Now erase any instructions that were made dead while rewriting the alloca.
1576 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +00001577 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +00001578
Dan Gohmanfe601042010-06-22 15:08:57 +00001579 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +00001580}
Chris Lattnera59adc42009-12-14 05:11:02 +00001581
Bob Wilsonb742def2009-12-18 20:14:40 +00001582/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1583/// recursively including all their operands that become trivially dead.
1584void SROA::DeleteDeadInstructions() {
1585 while (!DeadInsts.empty()) {
1586 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +00001587
Bob Wilsonb742def2009-12-18 20:14:40 +00001588 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1589 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1590 // Zero out the operand and see if it becomes trivially dead.
1591 // (But, don't add allocas to the dead instruction list -- they are
1592 // already on the worklist and will be deleted separately.)
1593 *OI = 0;
1594 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1595 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +00001596 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001597
1598 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +00001599 }
Chris Lattnera59adc42009-12-14 05:11:02 +00001600}
Bob Wilson69743022011-01-13 20:59:44 +00001601
Bob Wilsonb742def2009-12-18 20:14:40 +00001602/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1603/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001604/// the Info parameter. Offset indicates the position within AI that is
1605/// referenced by this instruction.
Chris Lattner6c95d242011-01-23 07:29:29 +00001606void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001607 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001608 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1609 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +00001610
Bob Wilsonb742def2009-12-18 20:14:40 +00001611 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Chris Lattner6c95d242011-01-23 07:29:29 +00001612 isSafeForScalarRepl(BC, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001613 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001614 uint64_t GEPOffset = Offset;
Chris Lattner6c95d242011-01-23 07:29:29 +00001615 isSafeGEP(GEPI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001616 if (!Info.isUnsafe)
Chris Lattner6c95d242011-01-23 07:29:29 +00001617 isSafeForScalarRepl(GEPI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001618 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001619 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001620 if (Length == 0)
1621 return MarkUnsafe(Info, User);
Chris Lattner6c95d242011-01-23 07:29:29 +00001622 isSafeMemAccess(Offset, Length->getZExtValue(), 0,
Chris Lattner145c5322011-01-23 08:27:54 +00001623 UI.getOperandNo() == 0, Info, MI,
1624 true /*AllowWholeAccess*/);
Bob Wilsonb742def2009-12-18 20:14:40 +00001625 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001626 if (LI->isVolatile())
1627 return MarkUnsafe(Info, User);
1628 const Type *LIType = LI->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001629 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001630 LIType, false, Info, LI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001631 Info.hasALoadOrStore = true;
1632
Bob Wilsonb742def2009-12-18 20:14:40 +00001633 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1634 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001635 if (SI->isVolatile() || SI->getOperand(0) == I)
1636 return MarkUnsafe(Info, User);
1637
1638 const Type *SIType = SI->getOperand(0)->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001639 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001640 SIType, true, Info, SI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001641 Info.hasALoadOrStore = true;
Chris Lattner145c5322011-01-23 08:27:54 +00001642 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1643 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1644 } else {
1645 return MarkUnsafe(Info, User);
1646 }
1647 if (Info.isUnsafe) return;
1648 }
1649}
1650
1651
1652/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1653/// derived from the alloca, we can often still split the alloca into elements.
1654/// This is useful if we have a large alloca where one element is phi'd
1655/// together somewhere: we can SRoA and promote all the other elements even if
1656/// we end up not being able to promote this one.
1657///
1658/// All we require is that the uses of the PHI do not index into other parts of
1659/// the alloca. The most important use case for this is single load and stores
1660/// that are PHI'd together, which can happen due to code sinking.
1661void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1662 AllocaInfo &Info) {
1663 // If we've already checked this PHI, don't do it again.
1664 if (PHINode *PN = dyn_cast<PHINode>(I))
1665 if (!Info.CheckedPHIs.insert(PN))
1666 return;
1667
1668 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1669 Instruction *User = cast<Instruction>(*UI);
1670
1671 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1672 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1673 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1674 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1675 // but would have to prove that we're staying inside of an element being
1676 // promoted.
1677 if (!GEPI->hasAllZeroIndices())
1678 return MarkUnsafe(Info, User);
1679 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1680 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1681 if (LI->isVolatile())
1682 return MarkUnsafe(Info, User);
1683 const Type *LIType = LI->getType();
1684 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1685 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1686 Info.hasALoadOrStore = true;
1687
1688 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1689 // Store is ok if storing INTO the pointer, not storing the pointer
1690 if (SI->isVolatile() || SI->getOperand(0) == I)
1691 return MarkUnsafe(Info, User);
1692
1693 const Type *SIType = SI->getOperand(0)->getType();
1694 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1695 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1696 Info.hasALoadOrStore = true;
1697 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1698 isSafePHISelectUseForScalarRepl(User, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001699 } else {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001700 return MarkUnsafe(Info, User);
Bob Wilsonb742def2009-12-18 20:14:40 +00001701 }
1702 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001703 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001704}
Bob Wilson39c88a62009-12-17 18:34:24 +00001705
Bob Wilsonb742def2009-12-18 20:14:40 +00001706/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1707/// replacement. It is safe when all the indices are constant, in-bounds
1708/// references, and when the resulting offset corresponds to an element within
1709/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001710/// return, Offset is adjusted as specified by the GEP indices.
Chris Lattner6c95d242011-01-23 07:29:29 +00001711void SROA::isSafeGEP(GetElementPtrInst *GEPI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001712 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001713 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1714 if (GEPIt == E)
1715 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001716
Chris Lattner88e6dc82008-08-23 05:21:06 +00001717 // Walk through the GEP type indices, checking the types that this indexes
1718 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001719 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001720 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001721 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001722 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001723
Bob Wilsonb742def2009-12-18 20:14:40 +00001724 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1725 if (!IdxVal)
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001726 return MarkUnsafe(Info, GEPI);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001727 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001728
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001729 // Compute the offset due to this GEP and check if the alloca has a
1730 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001731 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1732 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1733 &Indices[0], Indices.size());
Chris Lattner6c95d242011-01-23 07:29:29 +00001734 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001735 MarkUnsafe(Info, GEPI);
Chris Lattner5e062a12003-05-30 04:15:41 +00001736}
1737
Bob Wilson704d1342011-01-13 17:45:11 +00001738/// isHomogeneousAggregate - Check if type T is a struct or array containing
1739/// elements of the same type (which is always true for arrays). If so,
1740/// return true with NumElts and EltTy set to the number of elements and the
1741/// element type, respectively.
1742static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1743 const Type *&EltTy) {
1744 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1745 NumElts = AT->getNumElements();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001746 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
Bob Wilson704d1342011-01-13 17:45:11 +00001747 return true;
1748 }
1749 if (const StructType *ST = dyn_cast<StructType>(T)) {
1750 NumElts = ST->getNumContainedTypes();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001751 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
Bob Wilson704d1342011-01-13 17:45:11 +00001752 for (unsigned n = 1; n < NumElts; ++n) {
1753 if (ST->getContainedType(n) != EltTy)
1754 return false;
1755 }
1756 return true;
1757 }
1758 return false;
1759}
1760
1761/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1762/// "homogeneous" aggregates with the same element type and number of elements.
1763static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1764 if (T1 == T2)
1765 return true;
1766
1767 unsigned NumElts1, NumElts2;
1768 const Type *EltTy1, *EltTy2;
1769 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1770 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1771 NumElts1 == NumElts2 &&
1772 EltTy1 == EltTy2)
1773 return true;
1774
1775 return false;
1776}
1777
Bob Wilsonb742def2009-12-18 20:14:40 +00001778/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1779/// alloca or has an offset and size that corresponds to a component element
1780/// within it. The offset checked here may have been formed from a GEP with a
1781/// pointer bitcasted to a different type.
Chris Lattner145c5322011-01-23 08:27:54 +00001782///
1783/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1784/// unit. If false, it only allows accesses known to be in a single element.
Chris Lattner6c95d242011-01-23 07:29:29 +00001785void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001786 const Type *MemOpType, bool isStore,
Chris Lattner145c5322011-01-23 08:27:54 +00001787 AllocaInfo &Info, Instruction *TheAccess,
1788 bool AllowWholeAccess) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001789 // Check if this is a load/store of the entire alloca.
Chris Lattner145c5322011-01-23 08:27:54 +00001790 if (Offset == 0 && AllowWholeAccess &&
Chris Lattner6c95d242011-01-23 07:29:29 +00001791 MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
Bob Wilson704d1342011-01-13 17:45:11 +00001792 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1793 // loads/stores (which are essentially the same as the MemIntrinsics with
1794 // regard to copying padding between elements). But, if an alloca is
1795 // flagged as both a source and destination of such operations, we'll need
1796 // to check later for padding between elements.
1797 if (!MemOpType || MemOpType->isIntegerTy()) {
1798 if (isStore)
1799 Info.isMemCpyDst = true;
1800 else
1801 Info.isMemCpySrc = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001802 return;
1803 }
Bob Wilson704d1342011-01-13 17:45:11 +00001804 // This is also safe for references using a type that is compatible with
1805 // the type of the alloca, so that loads/stores can be rewritten using
1806 // insertvalue/extractvalue.
Chris Lattner6c95d242011-01-23 07:29:29 +00001807 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
Chris Lattner7e9b4272011-01-16 06:18:28 +00001808 Info.hasSubelementAccess = true;
Bob Wilson704d1342011-01-13 17:45:11 +00001809 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001810 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001811 }
1812 // Check if the offset/size correspond to a component within the alloca type.
Chris Lattner6c95d242011-01-23 07:29:29 +00001813 const Type *T = Info.AI->getAllocatedType();
Chris Lattner7e9b4272011-01-16 06:18:28 +00001814 if (TypeHasComponent(T, Offset, MemSize)) {
1815 Info.hasSubelementAccess = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001816 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001817 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001818
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001819 return MarkUnsafe(Info, TheAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +00001820}
1821
1822/// TypeHasComponent - Return true if T has a component type with the
1823/// specified offset and size. If Size is zero, do not check the size.
1824bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1825 const Type *EltTy;
1826 uint64_t EltSize;
1827 if (const StructType *ST = dyn_cast<StructType>(T)) {
1828 const StructLayout *Layout = TD->getStructLayout(ST);
1829 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1830 EltTy = ST->getContainedType(EltIdx);
1831 EltSize = TD->getTypeAllocSize(EltTy);
1832 Offset -= Layout->getElementOffset(EltIdx);
1833 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1834 EltTy = AT->getElementType();
1835 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001836 if (Offset >= AT->getNumElements() * EltSize)
1837 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001838 Offset %= EltSize;
1839 } else {
1840 return false;
1841 }
1842 if (Offset == 0 && (Size == 0 || EltSize == Size))
1843 return true;
1844 // Check if the component spans multiple elements.
1845 if (Offset + Size > EltSize)
1846 return false;
1847 return TypeHasComponent(EltTy, Offset, Size);
1848}
1849
1850/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1851/// the instruction I, which references it, to use the separate elements.
1852/// Offset indicates the position within AI that is referenced by this
1853/// instruction.
1854void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1855 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner145c5322011-01-23 08:27:54 +00001856 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1857 Use &TheUse = UI.getUse();
1858 Instruction *User = cast<Instruction>(*UI++);
Bob Wilsonb742def2009-12-18 20:14:40 +00001859
1860 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1861 RewriteBitCast(BC, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001862 continue;
1863 }
1864
1865 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001866 RewriteGEP(GEPI, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001867 continue;
1868 }
1869
1870 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001871 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1872 uint64_t MemSize = Length->getZExtValue();
1873 if (Offset == 0 &&
1874 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1875 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001876 // Otherwise the intrinsic can only touch a single element and the
1877 // address operand will be updated, so nothing else needs to be done.
Chris Lattner145c5322011-01-23 08:27:54 +00001878 continue;
1879 }
1880
1881 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001882 const Type *LIType = LI->getType();
Chris Lattner192228e2011-01-16 05:28:59 +00001883
Bob Wilson704d1342011-01-13 17:45:11 +00001884 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001885 // Replace:
1886 // %res = load { i32, i32 }* %alloc
1887 // with:
1888 // %load.0 = load i32* %alloc.0
1889 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1890 // %load.1 = load i32* %alloc.1
1891 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1892 // (Also works for arrays instead of structs)
1893 Value *Insert = UndefValue::get(LIType);
Devang Patelabb25122011-06-03 19:46:19 +00001894 IRBuilder<> Builder(LI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001895 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patelabb25122011-06-03 19:46:19 +00001896 Value *Load = Builder.CreateLoad(NewElts[i], "load");
1897 Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
Bob Wilsonb742def2009-12-18 20:14:40 +00001898 }
1899 LI->replaceAllUsesWith(Insert);
1900 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001901 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001902 TD->getTypeAllocSize(LIType) ==
1903 TD->getTypeAllocSize(AI->getAllocatedType())) {
1904 // If this is a load of the entire alloca to an integer, rewrite it.
1905 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1906 }
Chris Lattner145c5322011-01-23 08:27:54 +00001907 continue;
1908 }
1909
1910 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001911 Value *Val = SI->getOperand(0);
1912 const Type *SIType = Val->getType();
Bob Wilson704d1342011-01-13 17:45:11 +00001913 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001914 // Replace:
1915 // store { i32, i32 } %val, { i32, i32 }* %alloc
1916 // with:
1917 // %val.0 = extractvalue { i32, i32 } %val, 0
1918 // store i32 %val.0, i32* %alloc.0
1919 // %val.1 = extractvalue { i32, i32 } %val, 1
1920 // store i32 %val.1, i32* %alloc.1
1921 // (Also works for arrays instead of structs)
Devang Patelabb25122011-06-03 19:46:19 +00001922 IRBuilder<> Builder(SI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001923 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patelabb25122011-06-03 19:46:19 +00001924 Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1925 Builder.CreateStore(Extract, NewElts[i]);
Bob Wilsonb742def2009-12-18 20:14:40 +00001926 }
1927 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001928 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001929 TD->getTypeAllocSize(SIType) ==
1930 TD->getTypeAllocSize(AI->getAllocatedType())) {
1931 // If this is a store of the entire alloca from an integer, rewrite it.
1932 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1933 }
Chris Lattner145c5322011-01-23 08:27:54 +00001934 continue;
1935 }
1936
1937 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1938 // If we have a PHI user of the alloca itself (as opposed to a GEP or
1939 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1940 // the new pointer.
1941 if (!isa<AllocaInst>(I)) continue;
1942
1943 assert(Offset == 0 && NewElts[0] &&
1944 "Direct alloca use should have a zero offset");
1945
1946 // If we have a use of the alloca, we know the derived uses will be
1947 // utilizing just the first element of the scalarized result. Insert a
1948 // bitcast of the first alloca before the user as required.
1949 AllocaInst *NewAI = NewElts[0];
1950 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1951 NewAI->moveBefore(BCI);
1952 TheUse = BCI;
1953 continue;
Bob Wilsonb742def2009-12-18 20:14:40 +00001954 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001955 }
1956}
1957
Bob Wilsonb742def2009-12-18 20:14:40 +00001958/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1959/// and recursively continue updating all of its uses.
1960void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1961 SmallVector<AllocaInst*, 32> &NewElts) {
1962 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1963 if (BC->getOperand(0) != AI)
1964 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001965
Bob Wilsonb742def2009-12-18 20:14:40 +00001966 // The bitcast references the original alloca. Replace its uses with
1967 // references to the first new element alloca.
1968 Instruction *Val = NewElts[0];
1969 if (Val->getType() != BC->getDestTy()) {
1970 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1971 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001972 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001973 BC->replaceAllUsesWith(Val);
1974 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001975}
1976
Bob Wilsonb742def2009-12-18 20:14:40 +00001977/// FindElementAndOffset - Return the index of the element containing Offset
1978/// within the specified type, which must be either a struct or an array.
1979/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001980/// element. IdxTy is set to the type of the index result to be used in a
1981/// GEP instruction.
1982uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1983 const Type *&IdxTy) {
1984 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001985 if (const StructType *ST = dyn_cast<StructType>(T)) {
1986 const StructLayout *Layout = TD->getStructLayout(ST);
1987 Idx = Layout->getElementContainingOffset(Offset);
1988 T = ST->getContainedType(Idx);
1989 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001990 IdxTy = Type::getInt32Ty(T->getContext());
1991 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001992 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001993 const ArrayType *AT = cast<ArrayType>(T);
1994 T = AT->getElementType();
1995 uint64_t EltSize = TD->getTypeAllocSize(T);
1996 Idx = Offset / EltSize;
1997 Offset -= Idx * EltSize;
1998 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001999 return Idx;
2000}
2001
2002/// RewriteGEP - Check if this GEP instruction moves the pointer across
2003/// elements of the alloca that are being split apart, and if so, rewrite
2004/// the GEP to be relative to the new element.
2005void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
2006 SmallVector<AllocaInst*, 32> &NewElts) {
2007 uint64_t OldOffset = Offset;
2008 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
2009 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
2010 &Indices[0], Indices.size());
2011
2012 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
2013
2014 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00002015 const Type *IdxTy;
2016 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00002017 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00002018 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00002019
2020 T = AI->getAllocatedType();
2021 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00002022 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00002023
2024 // If this GEP does not move the pointer across elements of the alloca
2025 // being split, then it does not needs to be rewritten.
2026 if (Idx == OldIdx)
2027 return;
2028
2029 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
2030 SmallVector<Value*, 8> NewArgs;
2031 NewArgs.push_back(Constant::getNullValue(i32Ty));
2032 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00002033 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
2034 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00002035 }
2036 Instruction *Val = NewElts[Idx];
2037 if (NewArgs.size() > 1) {
2038 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
2039 NewArgs.end(), "", GEPI);
2040 Val->takeName(GEPI);
2041 }
2042 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00002043 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002044 GEPI->replaceAllUsesWith(Val);
2045 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002046}
2047
2048/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2049/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00002050void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00002051 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00002052 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002053 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00002054 // appropriate type. The "Other" pointer is the pointer that goes to memory
2055 // that doesn't have anything to do with the alloca that we are promoting. For
2056 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00002057 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00002058 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00002059 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00002060 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00002061 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00002062 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00002063 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00002064 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00002065 }
2066 }
Bob Wilson78c50b82009-12-08 18:22:03 +00002067
Chris Lattnerd93afec2009-01-07 07:18:45 +00002068 // If there is an other pointer, we want to convert it to the same pointer
2069 // type as AI has, so we can GEP through it safely.
2070 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00002071 unsigned AddrSpace =
2072 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00002073
2074 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2075 // optimization, but it's also required to detect the corner case where
2076 // both pointer operands are referencing the same memory, and where
2077 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2078 // function is only called for mem intrinsics that access the whole
2079 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00002080 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson69743022011-01-13 20:59:44 +00002081
Bob Wilsona756b1d2010-01-19 04:32:48 +00002082 // Copying the alloca to itself is a no-op: just delete it.
2083 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2084 // This code will run twice for a no-op memcpy -- once for each operand.
2085 // Put only one reference to MI on the DeadInsts list.
2086 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
2087 E = DeadInsts.end(); I != E; ++I)
2088 if (*I == MI) return;
2089 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002090 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00002091 }
Bob Wilson69743022011-01-13 20:59:44 +00002092
Chris Lattnerd93afec2009-01-07 07:18:45 +00002093 // If the pointer is not the right type, insert a bitcast to the right
2094 // type.
Chris Lattner0238f8c2010-07-08 00:27:05 +00002095 const Type *NewTy =
2096 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson69743022011-01-13 20:59:44 +00002097
Chris Lattner0238f8c2010-07-08 00:27:05 +00002098 if (OtherPtr->getType() != NewTy)
2099 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002100 }
Bob Wilson69743022011-01-13 20:59:44 +00002101
Chris Lattnerd93afec2009-01-07 07:18:45 +00002102 // Process each element of the aggregate.
Bob Wilsonb742def2009-12-18 20:14:40 +00002103 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson69743022011-01-13 20:59:44 +00002104
Owen Anderson1d0be152009-08-13 21:58:54 +00002105 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00002106
2107 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2108 // If this is a memcpy/memmove, emit a GEP of the other element address.
2109 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002110 unsigned OtherEltAlign = MemAlignment;
Bob Wilson69743022011-01-13 20:59:44 +00002111
Bob Wilsona756b1d2010-01-19 04:32:48 +00002112 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002113 Value *Idx[2] = { Zero,
2114 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00002115 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00002116 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00002117 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00002118 uint64_t EltOffset;
2119 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002120 const Type *OtherTy = OtherPtrTy->getElementType();
2121 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002122 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
2123 } else {
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002124 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002125 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002126 }
Bob Wilson69743022011-01-13 20:59:44 +00002127
Chris Lattner1541e0f2009-03-04 19:20:50 +00002128 // The alignment of the other pointer is the guaranteed alignment of the
2129 // element, which is affected by both the known alignment of the whole
2130 // mem intrinsic and the alignment of the element. If the alignment of
2131 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2132 // known alignment is just 4 bytes.
2133 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00002134 }
Bob Wilson69743022011-01-13 20:59:44 +00002135
Chris Lattnerd93afec2009-01-07 07:18:45 +00002136 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00002137 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson69743022011-01-13 20:59:44 +00002138
Chris Lattnerd93afec2009-01-07 07:18:45 +00002139 // If we got down to a scalar, insert a load or store as appropriate.
2140 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00002141 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002142 if (SROADest) {
2143 // From Other to Alloca.
2144 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2145 new StoreInst(Elt, EltPtr, MI);
2146 } else {
2147 // From Alloca to Other.
2148 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2149 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2150 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00002151 continue;
2152 }
2153 assert(isa<MemSetInst>(MI));
Bob Wilson69743022011-01-13 20:59:44 +00002154
Chris Lattnerd93afec2009-01-07 07:18:45 +00002155 // If the stored element is zero (common case), just store a null
2156 // constant.
2157 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00002158 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002159 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00002160 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00002161 } else {
2162 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00002163 const Type *ValTy = EltTy->getScalarType();
2164
Chris Lattnerd93afec2009-01-07 07:18:45 +00002165 // Construct an integer with the right value.
2166 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2167 APInt OneVal(EltSize, CI->getZExtValue());
2168 APInt TotalVal(OneVal);
2169 // Set each byte.
2170 for (unsigned i = 0; 8*i < EltSize; ++i) {
2171 TotalVal = TotalVal.shl(8);
2172 TotalVal |= OneVal;
2173 }
Bob Wilson69743022011-01-13 20:59:44 +00002174
Chris Lattnerd93afec2009-01-07 07:18:45 +00002175 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002176 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00002177 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002178 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002179 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002180 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002181 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson69743022011-01-13 20:59:44 +00002182
Chris Lattnerd93afec2009-01-07 07:18:45 +00002183 // If the requested value was a vector constant, create it.
2184 if (EltTy != ValTy) {
2185 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
2186 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Chris Lattner2ca5c862011-02-15 00:14:00 +00002187 StoreVal = ConstantVector::get(Elts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002188 }
2189 }
2190 new StoreInst(StoreVal, EltPtr, MI);
2191 continue;
2192 }
2193 // Otherwise, if we're storing a byte variable, use a memset call for
2194 // this element.
2195 }
Bob Wilson69743022011-01-13 20:59:44 +00002196
Duncan Sands777d2302009-05-09 07:06:46 +00002197 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002198
Chris Lattner61db1f52010-12-26 22:57:41 +00002199 IRBuilder<> Builder(MI);
Bob Wilson69743022011-01-13 20:59:44 +00002200
Chris Lattnerd93afec2009-01-07 07:18:45 +00002201 // Finally, insert the meminst for this element.
Chris Lattner61db1f52010-12-26 22:57:41 +00002202 if (isa<MemSetInst>(MI)) {
2203 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2204 MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002205 } else {
Chris Lattner61db1f52010-12-26 22:57:41 +00002206 assert(isa<MemTransferInst>(MI));
2207 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2208 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson69743022011-01-13 20:59:44 +00002209
Chris Lattner61db1f52010-12-26 22:57:41 +00002210 if (isa<MemCpyInst>(MI))
2211 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2212 else
2213 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002214 }
Chris Lattner372dda82007-03-05 07:52:57 +00002215 }
Bob Wilsonb742def2009-12-18 20:14:40 +00002216 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00002217}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002218
Bob Wilson39fdd692009-12-04 21:57:37 +00002219/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002220/// overwrites the entire allocation. Extract out the pieces of the stored
2221/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002222void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002223 SmallVector<AllocaInst*, 32> &NewElts){
2224 // Extract each element out of the integer according to its structure offset
2225 // and store the element value to the individual alloca.
2226 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00002227 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002228 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002229
Chris Lattner70728532011-01-16 05:58:24 +00002230 IRBuilder<> Builder(SI);
2231
Eli Friedman41b33f42009-06-01 09:14:32 +00002232 // Handle tail padding by extending the operand
2233 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002234 SrcVal = Builder.CreateZExt(SrcVal,
2235 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002236
David Greene504c7d82010-01-05 01:27:09 +00002237 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00002238 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002239
2240 // There are two forms here: AI could be an array or struct. Both cases
2241 // have different ways to compute the element offset.
2242 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2243 const StructLayout *Layout = TD->getStructLayout(EltSTy);
Bob Wilson69743022011-01-13 20:59:44 +00002244
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002245 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2246 // Get the number of bits to shift SrcVal to get the value.
2247 const Type *FieldTy = EltSTy->getElementType(i);
2248 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson69743022011-01-13 20:59:44 +00002249
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002250 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00002251 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002252
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002253 Value *EltVal = SrcVal;
2254 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002255 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002256 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002257 }
Bob Wilson69743022011-01-13 20:59:44 +00002258
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002259 // Truncate down to an integer of the right size.
2260 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002261
Chris Lattner583dd602009-01-09 18:18:43 +00002262 // Ignore zero sized fields like {}, they obviously contain no data.
2263 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002264
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002265 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002266 EltVal = Builder.CreateTrunc(EltVal,
2267 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002268 Value *DestField = NewElts[i];
2269 if (EltVal->getType() == FieldTy) {
2270 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00002271 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002272 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002273 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002274 } else {
2275 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002276 DestField = Builder.CreateBitCast(DestField,
2277 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002278 }
2279 new StoreInst(EltVal, DestField, SI);
2280 }
Bob Wilson69743022011-01-13 20:59:44 +00002281
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002282 } else {
2283 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2284 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002285 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002286 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2287
2288 uint64_t Shift;
Bob Wilson69743022011-01-13 20:59:44 +00002289
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002290 if (TD->isBigEndian())
2291 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002292 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002293 Shift = 0;
Bob Wilson69743022011-01-13 20:59:44 +00002294
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002295 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00002296 // Ignore zero sized fields like {}, they obviously contain no data.
2297 if (ElementSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002298
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002299 Value *EltVal = SrcVal;
2300 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002301 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002302 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002303 }
Bob Wilson69743022011-01-13 20:59:44 +00002304
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002305 // Truncate down to an integer of the right size.
2306 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002307 EltVal = Builder.CreateTrunc(EltVal,
2308 IntegerType::get(SI->getContext(),
2309 ElementSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002310 Value *DestField = NewElts[i];
2311 if (EltVal->getType() == ArrayEltTy) {
2312 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002313 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00002314 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002315 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002316 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002317 } else {
2318 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002319 DestField = Builder.CreateBitCast(DestField,
2320 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002321 }
2322 new StoreInst(EltVal, DestField, SI);
Bob Wilson69743022011-01-13 20:59:44 +00002323
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002324 if (TD->isBigEndian())
2325 Shift -= ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002326 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002327 Shift += ElementOffset;
2328 }
2329 }
Bob Wilson69743022011-01-13 20:59:44 +00002330
Bob Wilsonb742def2009-12-18 20:14:40 +00002331 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002332}
2333
Bob Wilson39fdd692009-12-04 21:57:37 +00002334/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002335/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002336void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002337 SmallVector<AllocaInst*, 32> &NewElts) {
2338 // Extract each element out of the NewElts according to its structure offset
2339 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00002340 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002341 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002342
David Greene504c7d82010-01-05 01:27:09 +00002343 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00002344 << '\n');
Bob Wilson69743022011-01-13 20:59:44 +00002345
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002346 // There are two forms here: AI could be an array or struct. Both cases
2347 // have different ways to compute the element offset.
2348 const StructLayout *Layout = 0;
2349 uint64_t ArrayEltBitOffset = 0;
2350 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2351 Layout = TD->getStructLayout(EltSTy);
2352 } else {
2353 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002354 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002355 }
2356
2357 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00002358 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson69743022011-01-13 20:59:44 +00002359
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002360 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2361 // Load the value from the alloca. If the NewElt is an aggregate, cast
2362 // the pointer to an integer of the same size before doing the load.
2363 Value *SrcField = NewElts[i];
2364 const Type *FieldTy =
2365 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00002366 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002367
Chris Lattner583dd602009-01-09 18:18:43 +00002368 // Ignore zero sized fields like {}, they obviously contain no data.
2369 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002370
2371 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +00002372 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00002373 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2374 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00002375 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00002376 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002377 "", LI);
2378 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2379
2380 // If SrcField is a fp or vector of the right size but that isn't an
2381 // integer type, bitcast to an integer so we can shift it.
2382 if (SrcField->getType() != FieldIntTy)
2383 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2384
2385 // Zero extend the field to be the same size as the final alloca so that
2386 // we can shift and insert it.
2387 if (SrcField->getType() != ResultVal->getType())
2388 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson69743022011-01-13 20:59:44 +00002389
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002390 // Determine the number of bits to shift SrcField.
2391 uint64_t Shift;
2392 if (Layout) // Struct case.
2393 Shift = Layout->getElementOffsetInBits(i);
2394 else // Array case.
2395 Shift = i*ArrayEltBitOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002396
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002397 if (TD->isBigEndian())
2398 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson69743022011-01-13 20:59:44 +00002399
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002400 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002401 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002402 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2403 }
2404
Chris Lattner14952472010-06-27 07:58:26 +00002405 // Don't create an 'or x, 0' on the first iteration.
2406 if (!isa<Constant>(ResultVal) ||
2407 !cast<Constant>(ResultVal)->isNullValue())
2408 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2409 else
2410 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002411 }
Eli Friedman41b33f42009-06-01 09:14:32 +00002412
2413 // Handle tail padding by truncating the result
2414 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2415 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2416
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002417 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00002418 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002419}
2420
Duncan Sands3cb36502007-11-04 14:43:57 +00002421/// HasPadding - Return true if the specified type has any structure or
Bob Wilson694a10e2011-01-13 17:45:08 +00002422/// alignment padding in between the elements that would be split apart
2423/// by SROA; return false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00002424static bool HasPadding(const Type *Ty, const TargetData &TD) {
Bob Wilson694a10e2011-01-13 17:45:08 +00002425 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2426 Ty = ATy->getElementType();
2427 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00002428 }
Bob Wilson694a10e2011-01-13 17:45:08 +00002429
2430 // SROA currently handles only Arrays and Structs.
2431 const StructType *STy = cast<StructType>(Ty);
2432 const StructLayout *SL = TD.getStructLayout(STy);
2433 unsigned PrevFieldBitOffset = 0;
2434 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2435 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2436
2437 // Check to see if there is any padding between this element and the
2438 // previous one.
2439 if (i) {
2440 unsigned PrevFieldEnd =
2441 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2442 if (PrevFieldEnd < FieldBitOffset)
2443 return true;
2444 }
2445 PrevFieldBitOffset = FieldBitOffset;
2446 }
2447 // Check for tail padding.
2448 if (unsigned EltCount = STy->getNumElements()) {
2449 unsigned PrevFieldEnd = PrevFieldBitOffset +
2450 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2451 if (PrevFieldEnd < SL->getSizeInBits())
2452 return true;
2453 }
2454 return false;
Chris Lattner39a1c042007-05-30 06:11:23 +00002455}
Chris Lattner372dda82007-03-05 07:52:57 +00002456
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002457/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2458/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2459/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002460bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00002461 // Loop over the use list of the alloca. We can only transform it if all of
2462 // the users are safe to transform.
Chris Lattner6c95d242011-01-23 07:29:29 +00002463 AllocaInfo Info(AI);
Bob Wilson69743022011-01-13 20:59:44 +00002464
Chris Lattner6c95d242011-01-23 07:29:29 +00002465 isSafeForScalarRepl(AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00002466 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00002467 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002468 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002469 }
Bob Wilson69743022011-01-13 20:59:44 +00002470
Chris Lattner39a1c042007-05-30 06:11:23 +00002471 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2472 // source and destination, we have to be careful. In particular, the memcpy
2473 // could be moving around elements that live in structure padding of the LLVM
2474 // types, but may actually be used. In these cases, we refuse to promote the
2475 // struct.
2476 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00002477 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002478 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00002479
Chris Lattner396a0562011-01-16 17:46:19 +00002480 // If the alloca never has an access to just *part* of it, but is accessed
2481 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner7e9b4272011-01-16 06:18:28 +00002482 // the alloca instead of promoting each piece at a time and inserting fission
2483 // and fusion code.
2484 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2485 // If the struct/array just has one element, use basic SRoA.
2486 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2487 if (ST->getNumElements() > 1) return false;
2488 } else {
2489 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2490 return false;
2491 }
2492 }
Chris Lattner145c5322011-01-23 08:27:54 +00002493
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002494 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00002495}
Chris Lattnera1888942005-12-12 07:19:13 +00002496
Chris Lattner800de312008-02-29 07:03:13 +00002497
Chris Lattner79b3bd32007-04-25 06:40:51 +00002498
2499/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2500/// some part of a constant global variable. This intentionally only accepts
2501/// constant expressions because we don't can't rewrite arbitrary instructions.
2502static bool PointsToConstantGlobal(Value *V) {
2503 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2504 return GV->isConstant();
2505 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Bob Wilson69743022011-01-13 20:59:44 +00002506 if (CE->getOpcode() == Instruction::BitCast ||
Chris Lattner79b3bd32007-04-25 06:40:51 +00002507 CE->getOpcode() == Instruction::GetElementPtr)
2508 return PointsToConstantGlobal(CE->getOperand(0));
2509 return false;
2510}
2511
2512/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2513/// pointer to an alloca. Ignore any reads of the pointer, return false if we
2514/// see any stores or other unknown uses. If we see pointer arithmetic, keep
2515/// track of whether it moves the pointer (with isOffset) but otherwise traverse
2516/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
Nick Lewycky081f8002010-11-24 22:04:20 +00002517/// the alloca, and if the source pointer is a pointer to a constant global, we
Chris Lattner79b3bd32007-04-25 06:40:51 +00002518/// can optimize this.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002519static bool
2520isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
2521 bool isOffset,
2522 SmallVector<Instruction *, 4> &LifetimeMarkers) {
2523 // We track lifetime intrinsics as we encounter them. If we decide to go
2524 // ahead and replace the value with the global, this lets the caller quickly
2525 // eliminate the markers.
2526
Chris Lattner79b3bd32007-04-25 06:40:51 +00002527 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00002528 User *U = cast<Instruction>(*UI);
2529
Chris Lattner2e618492010-11-18 06:20:47 +00002530 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00002531 // Ignore non-volatile loads, they are always ok.
Chris Lattner2e618492010-11-18 06:20:47 +00002532 if (LI->isVolatile()) return false;
2533 continue;
2534 }
Bob Wilson69743022011-01-13 20:59:44 +00002535
Gabor Greif8a8a4352010-04-06 19:32:30 +00002536 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002537 // If uses of the bitcast are ok, we are ok.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002538 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset,
2539 LifetimeMarkers))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002540 return false;
2541 continue;
2542 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00002543 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002544 // If the GEP has all zero indices, it doesn't offset the pointer. If it
2545 // doesn't, it does.
2546 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002547 isOffset || !GEP->hasAllZeroIndices(),
2548 LifetimeMarkers))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002549 return false;
2550 continue;
2551 }
Bob Wilson69743022011-01-13 20:59:44 +00002552
Chris Lattner62480652010-11-18 06:41:51 +00002553 if (CallSite CS = U) {
Nick Lewycky081f8002010-11-24 22:04:20 +00002554 // If this is the function being called then we treat it like a load and
2555 // ignore it.
2556 if (CS.isCallee(UI))
2557 continue;
Bob Wilson69743022011-01-13 20:59:44 +00002558
Duncan Sands53892102011-05-06 10:30:37 +00002559 // If this is a readonly/readnone call site, then we know it is just a
2560 // load (but one that potentially returns the value itself), so we can
2561 // ignore it if we know that the value isn't captured.
2562 unsigned ArgNo = CS.getArgumentNo(UI);
2563 if (CS.onlyReadsMemory() &&
2564 (CS.getInstruction()->use_empty() ||
2565 CS.paramHasAttr(ArgNo+1, Attribute::NoCapture)))
2566 continue;
2567
Chris Lattner62480652010-11-18 06:41:51 +00002568 // If this is being passed as a byval argument, the caller is making a
2569 // copy, so it is only a read of the alloca.
Chris Lattner62480652010-11-18 06:41:51 +00002570 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
2571 continue;
2572 }
Bob Wilson69743022011-01-13 20:59:44 +00002573
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002574 // Lifetime intrinsics can be handled by the caller.
2575 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
2576 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2577 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2578 assert(II->use_empty() && "Lifetime markers have no result to use!");
2579 LifetimeMarkers.push_back(II);
2580 continue;
2581 }
2582 }
2583
Chris Lattner79b3bd32007-04-25 06:40:51 +00002584 // If this is isn't our memcpy/memmove, reject it as something we can't
2585 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00002586 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2587 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00002588 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002589
Chris Lattner2e618492010-11-18 06:20:47 +00002590 // If the transfer is using the alloca as a source of the transfer, then
Chris Lattner2e29ebd2010-11-18 07:32:33 +00002591 // ignore it since it is a load (unless the transfer is volatile).
Chris Lattner2e618492010-11-18 06:20:47 +00002592 if (UI.getOperandNo() == 1) {
2593 if (MI->isVolatile()) return false;
2594 continue;
2595 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00002596
2597 // If we already have seen a copy, reject the second one.
2598 if (TheCopy) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002599
Chris Lattner79b3bd32007-04-25 06:40:51 +00002600 // If the pointer has been offset from the start of the alloca, we can't
2601 // safely handle this.
2602 if (isOffset) return false;
2603
2604 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00002605 if (UI.getOperandNo() != 0) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002606
Chris Lattner79b3bd32007-04-25 06:40:51 +00002607 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00002608 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002609 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002610
Chris Lattner79b3bd32007-04-25 06:40:51 +00002611 // Otherwise, the transform is safe. Remember the copy instruction.
2612 TheCopy = MI;
2613 }
2614 return true;
2615}
2616
2617/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2618/// modified by a copy from a constant global. If we can prove this, we can
2619/// replace any uses of the alloca with uses of the global directly.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002620MemTransferInst *
2621SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
2622 SmallVector<Instruction*, 4> &ToDelete) {
Chris Lattner31d80102010-04-15 21:59:20 +00002623 MemTransferInst *TheCopy = 0;
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002624 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false, ToDelete))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002625 return TheCopy;
2626 return 0;
2627}