blob: 113397fc11b7858a6fb48841be4dfb82c1c5d4d9 [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//
Chad Rosierc9f27ee2012-04-11 19:21:58 +000016// This combines a simple SRoA algorithm with the Mem2Reg algorithm because they
Chris Lattner38aec322003-09-11 16:45:55 +000017// 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"
Peter Collingbourne9012c572012-05-19 22:52:10 +000032#include "llvm/Operator.h"
Chris Lattner372dda82007-03-05 07:52:57 +000033#include "llvm/Pass.h"
Devang Patel4fd3c592011-07-06 22:06:11 +000034#include "llvm/Analysis/DebugInfo.h"
Cameron Zwarichc8279392011-05-24 03:10:43 +000035#include "llvm/Analysis/DIBuilder.h"
Cameron Zwarichb1686c32011-01-18 03:53:26 +000036#include "llvm/Analysis/Dominators.h"
Chris Lattnerc87c50a2011-01-23 22:04:55 +000037#include "llvm/Analysis/Loads.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000038#include "llvm/Analysis/ValueTracking.h"
Chris Lattner38aec322003-09-11 16:45:55 +000039#include "llvm/Target/TargetData.h"
40#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000041#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere0a1a5b2011-01-14 07:50:47 +000042#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattnera9be1df2010-11-18 06:26:49 +000043#include "llvm/Support/CallSite.h"
Chris Lattner95255282006-06-28 23:17:24 +000044#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000045#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000046#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000047#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000048#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000049#include "llvm/Support/raw_ostream.h"
Chris Lattnerc87c50a2011-01-23 22:04:55 +000050#include "llvm/ADT/SetVector.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000051#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000053using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000054
Chris Lattner0e5f4992006-12-19 21:40:18 +000055STATISTIC(NumReplaced, "Number of allocas broken up");
56STATISTIC(NumPromoted, "Number of allocas promoted");
Chris Lattnerc87c50a2011-01-23 22:04:55 +000057STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
Chris Lattner0e5f4992006-12-19 21:40:18 +000058STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000059STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000060
Chris Lattner0e5f4992006-12-19 21:40:18 +000061namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000062 struct SROA : public FunctionPass {
Cameron Zwarichb1686c32011-01-18 03:53:26 +000063 SROA(int T, bool hasDT, char &ID)
64 : FunctionPass(ID), HasDomTree(hasDT) {
Devang Patelff366852007-07-09 21:19:23 +000065 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000066 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000067 else
68 SRThreshold = T;
69 }
Devang Patel794fd752007-05-01 21:15:47 +000070
Chris Lattnered7b41e2003-05-27 15:45:27 +000071 bool runOnFunction(Function &F);
72
Chris Lattner38aec322003-09-11 16:45:55 +000073 bool performScalarRepl(Function &F);
74 bool performPromotion(Function &F);
75
Chris Lattnered7b41e2003-05-27 15:45:27 +000076 private:
Cameron Zwarichb1686c32011-01-18 03:53:26 +000077 bool HasDomTree;
Chris Lattner56c38522009-01-07 06:34:28 +000078 TargetData *TD;
Bob Wilson69743022011-01-13 20:59:44 +000079
Bob Wilsonb742def2009-12-18 20:14:40 +000080 /// DeadInsts - Keep track of instructions we have made dead, so that
81 /// we can remove them after we are done working.
82 SmallVector<Value*, 32> DeadInsts;
83
Chris Lattner39a1c042007-05-30 06:11:23 +000084 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
85 /// information about the uses. All these fields are initialized to false
86 /// and set to true when something is learned.
87 struct AllocaInfo {
Chris Lattner6c95d242011-01-23 07:29:29 +000088 /// The alloca to promote.
89 AllocaInst *AI;
90
Chris Lattner145c5322011-01-23 08:27:54 +000091 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
92 /// looping and avoid redundant work.
93 SmallPtrSet<PHINode*, 8> CheckedPHIs;
94
Chris Lattner39a1c042007-05-30 06:11:23 +000095 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
96 bool isUnsafe : 1;
Bob Wilson69743022011-01-13 20:59:44 +000097
Chris Lattner39a1c042007-05-30 06:11:23 +000098 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
99 bool isMemCpySrc : 1;
100
Zhou Sheng33b0b8d2007-07-06 06:01:16 +0000101 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +0000102 bool isMemCpyDst : 1;
103
Chris Lattner7e9b4272011-01-16 06:18:28 +0000104 /// hasSubelementAccess - This is true if a subelement of the alloca is
105 /// ever accessed, or false if the alloca is only accessed with mem
106 /// intrinsics or load/store that only access the entire alloca at once.
107 bool hasSubelementAccess : 1;
108
109 /// hasALoadOrStore - This is true if there are any loads or stores to it.
110 /// The alloca may just be accessed with memcpy, for example, which would
111 /// not set this.
112 bool hasALoadOrStore : 1;
113
Chris Lattner6c95d242011-01-23 07:29:29 +0000114 explicit AllocaInfo(AllocaInst *ai)
115 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
Chris Lattner7e9b4272011-01-16 06:18:28 +0000116 hasSubelementAccess(false), hasALoadOrStore(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +0000117 };
Bob Wilson69743022011-01-13 20:59:44 +0000118
Devang Patelff366852007-07-09 21:19:23 +0000119 unsigned SRThreshold;
120
Chris Lattnerd01a0da2011-01-23 07:05:44 +0000121 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
122 I.isUnsafe = true;
123 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
124 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000125
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000126 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000127
Chris Lattner6c95d242011-01-23 07:29:29 +0000128 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
Chris Lattner145c5322011-01-23 08:27:54 +0000129 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
130 AllocaInfo &Info);
Chris Lattner6c95d242011-01-23 07:29:29 +0000131 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
132 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000133 Type *MemOpType, bool isStore, AllocaInfo &Info,
Chris Lattner145c5322011-01-23 08:27:54 +0000134 Instruction *TheAccess, bool AllowWholeAccess);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000135 bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size);
136 uint64_t FindElementAndOffset(Type *&T, uint64_t &Offset,
137 Type *&IdxTy);
Bob Wilson69743022011-01-13 20:59:44 +0000138
139 void DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000140 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000141 void DeleteDeadInstructions();
Bob Wilson69743022011-01-13 20:59:44 +0000142
Bob Wilsonb742def2009-12-18 20:14:40 +0000143 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
144 SmallVector<AllocaInst*, 32> &NewElts);
145 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
146 SmallVector<AllocaInst*, 32> &NewElts);
147 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
148 SmallVector<AllocaInst*, 32> &NewElts);
Nick Lewycky5a1cb642011-07-25 23:14:22 +0000149 void RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
150 uint64_t Offset,
151 SmallVector<AllocaInst*, 32> &NewElts);
Bob Wilsonb742def2009-12-18 20:14:40 +0000152 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000153 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000154 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000155 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000156 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000157 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000158 SmallVector<AllocaInst*, 32> &NewElts);
Bob Wilson69743022011-01-13 20:59:44 +0000159
Nick Lewycky9174d5c2011-06-27 05:40:02 +0000160 static MemTransferInst *isOnlyCopiedFromConstantGlobal(
161 AllocaInst *AI, SmallVector<Instruction*, 4> &ToDelete);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000162 };
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000163
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000164 // SROA_DT - SROA that uses DominatorTree.
165 struct SROA_DT : public SROA {
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000166 static char ID;
167 public:
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000168 SROA_DT(int T = -1) : SROA(T, true, ID) {
169 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000170 }
171
172 // getAnalysisUsage - This pass does not require any passes, but we know it
173 // will not alter the CFG, so say so.
174 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
175 AU.addRequired<DominatorTree>();
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000176 AU.setPreservesCFG();
177 }
178 };
179
180 // SROA_SSAUp - SROA that uses SSAUpdater.
181 struct SROA_SSAUp : public SROA {
182 static char ID;
183 public:
184 SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
185 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
186 }
187
188 // getAnalysisUsage - This pass does not require any passes, but we know it
189 // will not alter the CFG, so say so.
190 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
191 AU.setPreservesCFG();
192 }
193 };
194
Chris Lattnered7b41e2003-05-27 15:45:27 +0000195}
196
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000197char SROA_DT::ID = 0;
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000198char SROA_SSAUp::ID = 0;
199
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000200INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
201 "Scalar Replacement of Aggregates (DT)", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000202INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000203INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
204 "Scalar Replacement of Aggregates (DT)", false, false)
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000205
206INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
207 "Scalar Replacement of Aggregates (SSAUp)", false, false)
208INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
209 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000210
Brian Gaeked0fde302003-11-11 22:41:34 +0000211// Public interface to the ScalarReplAggregates pass
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000212FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000213 bool UseDomTree) {
214 if (UseDomTree)
215 return new SROA_DT(Threshold);
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000216 return new SROA_SSAUp(Threshold);
Devang Patelff366852007-07-09 21:19:23 +0000217}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000218
219
Chris Lattner4cc576b2010-04-16 00:24:57 +0000220//===----------------------------------------------------------------------===//
221// Convert To Scalar Optimization.
222//===----------------------------------------------------------------------===//
223
224namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000225/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
226/// optimization, which scans the uses of an alloca and determines if it can
227/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000228class ConvertToScalarInfo {
Cameron Zwarichd4c9c3e2011-03-16 00:13:35 +0000229 /// AllocaSize - The size of the alloca being considered in bytes.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000230 unsigned AllocaSize;
231 const TargetData &TD;
Bob Wilson69743022011-01-13 20:59:44 +0000232
Chris Lattnera0bada72010-04-16 02:32:17 +0000233 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000234 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000235 bool IsNotTrivial;
Bob Wilson69743022011-01-13 20:59:44 +0000236
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000237 /// ScalarKind - Tracks the kind of alloca being considered for promotion,
238 /// computed based on the uses of the alloca rather than the LLVM type system.
239 enum {
240 Unknown,
Cameron Zwarich51797822011-06-13 21:44:40 +0000241
Cameron Zwarich15cd80c2011-06-13 23:39:23 +0000242 // Accesses via GEPs that are consistent with element access of a vector
Cameron Zwarich51797822011-06-13 21:44:40 +0000243 // type. This will not be converted into a vector unless there is a later
244 // access using an actual vector type.
245 ImplicitVector,
246
Cameron Zwarich15cd80c2011-06-13 23:39:23 +0000247 // Accesses via vector operations and GEPs that are consistent with the
248 // layout of a vector type.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000249 Vector,
Cameron Zwarich51797822011-06-13 21:44:40 +0000250
251 // An integer bag-of-bits with bitwise operations for insertion and
252 // extraction. Any combination of types can be converted into this kind
253 // of scalar.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000254 Integer
255 } ScalarKind;
256
Chris Lattnera001b662010-04-16 00:38:19 +0000257 /// VectorTy - This tracks the type that we should promote the vector to if
258 /// it is possible to turn it into a vector. This starts out null, and if it
259 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000260 VectorType *VectorTy;
Bob Wilson69743022011-01-13 20:59:44 +0000261
Cameron Zwarich1bcdb6f2011-03-16 08:13:42 +0000262 /// HadNonMemTransferAccess - True if there is at least one access to the
263 /// alloca that is not a MemTransferInst. We don't want to turn structs into
264 /// large integers unless there is some potential for optimization.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000265 bool HadNonMemTransferAccess;
266
Chris Lattner4cc576b2010-04-16 00:24:57 +0000267public:
268 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000269 : AllocaSize(Size), TD(td), IsNotTrivial(false), ScalarKind(Unknown),
Cameron Zwarich51797822011-06-13 21:44:40 +0000270 VectorTy(0), HadNonMemTransferAccess(false) { }
Bob Wilson69743022011-01-13 20:59:44 +0000271
Chris Lattnera001b662010-04-16 00:38:19 +0000272 AllocaInst *TryConvert(AllocaInst *AI);
Bob Wilson69743022011-01-13 20:59:44 +0000273
Chris Lattner4cc576b2010-04-16 00:24:57 +0000274private:
275 bool CanConvertToScalar(Value *V, uint64_t Offset);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000276 void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
277 bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000278 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Bob Wilson69743022011-01-13 20:59:44 +0000279
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000280 Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000281 uint64_t Offset, IRBuilder<> &Builder);
282 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
283 uint64_t Offset, IRBuilder<> &Builder);
284};
285} // end anonymous namespace.
286
Chris Lattner91abace2010-09-01 05:14:33 +0000287
Chris Lattnera001b662010-04-16 00:38:19 +0000288/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
289/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
290/// alloca if possible or null if not.
291AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
292 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
293 // out.
294 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
295 return 0;
Bob Wilson69743022011-01-13 20:59:44 +0000296
Cameron Zwarich51797822011-06-13 21:44:40 +0000297 // If an alloca has only memset / memcpy uses, it may still have an Unknown
298 // ScalarKind. Treat it as an Integer below.
299 if (ScalarKind == Unknown)
300 ScalarKind = Integer;
301
Cameron Zwarich3ebb05d2011-06-18 06:17:51 +0000302 if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
303 ScalarKind = Integer;
304
Chris Lattnera001b662010-04-16 00:38:19 +0000305 // If we were able to find a vector type that can handle this with
306 // insert/extract elements, and if there was at least one use that had
307 // a vector type, promote this to a vector. We don't want to promote
308 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
309 // we just get a lot of insert/extracts. If at least one vector is
310 // involved, then we probably really do have a union of vector/array.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000311 Type *NewTy;
Cameron Zwarich5b93d3c2011-06-14 06:33:51 +0000312 if (ScalarKind == Vector) {
313 assert(VectorTy && "Missing type for vector scalar.");
Chris Lattnera001b662010-04-16 00:38:19 +0000314 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
315 << *VectorTy << '\n');
316 NewTy = VectorTy; // Use the vector type.
317 } else {
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000318 unsigned BitWidth = AllocaSize * 8;
Cameron Zwarich51797822011-06-13 21:44:40 +0000319 if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
320 !HadNonMemTransferAccess && !TD.fitsInLegalInteger(BitWidth))
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000321 return 0;
322
Chris Lattnera001b662010-04-16 00:38:19 +0000323 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
324 // Create and insert the integer alloca.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000325 NewTy = IntegerType::get(AI->getContext(), BitWidth);
Chris Lattnera001b662010-04-16 00:38:19 +0000326 }
327 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
328 ConvertUsesToScalar(AI, NewAI, 0);
329 return NewAI;
330}
331
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000332/// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
333/// (VectorTy) so far at the offset specified by Offset (which is specified in
334/// bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000335///
Cameron Zwarich446d9522011-10-11 06:10:30 +0000336/// There are two cases we handle here:
Chris Lattner4cc576b2010-04-16 00:24:57 +0000337/// 1) A union of vector types of the same size and potentially its elements.
338/// Here we turn element accesses into insert/extract element operations.
339/// This promotes a <4 x float> with a store of float to the third element
340/// into a <4 x float> that uses insert element.
Cameron Zwarich446d9522011-10-11 06:10:30 +0000341/// 2) A fully general blob of memory, which we turn into some (potentially
Chris Lattner4cc576b2010-04-16 00:24:57 +0000342/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000343/// and stores would mutate the memory. We mark this by setting VectorTy
344/// to VoidTy.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000345void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000346 uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000347 // If we already decided to turn this into a blob of integer memory, there is
348 // nothing to be done.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000349 if (ScalarKind == Integer)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000350 return;
Bob Wilson69743022011-01-13 20:59:44 +0000351
Chris Lattner4cc576b2010-04-16 00:24:57 +0000352 // If this could be contributing to a vector, analyze it.
353
354 // If the In type is a vector that is the same size as the alloca, see if it
355 // matches the existing VecTy.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000356 if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000357 if (MergeInVectorType(VInTy, Offset))
Chris Lattner4cc576b2010-04-16 00:24:57 +0000358 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000359 } else if (In->isFloatTy() || In->isDoubleTy() ||
360 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
361 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
Cameron Zwarich9827b782011-03-29 05:19:52 +0000362 // Full width accesses can be ignored, because they can always be turned
363 // into bitcasts.
364 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
Cameron Zwarichdd689122011-06-13 21:44:31 +0000365 if (EltSize == AllocaSize)
Cameron Zwarich9827b782011-03-29 05:19:52 +0000366 return;
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000367
Chris Lattner4cc576b2010-04-16 00:24:57 +0000368 // If we're accessing something that could be an element of a vector, see
369 // if the implied vector agrees with what we already have and if Offset is
370 // compatible with it.
Cameron Zwarich96cc1d02011-06-09 01:45:33 +0000371 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Cameron Zwarich446d9522011-10-11 06:10:30 +0000372 (!VectorTy || EltSize == VectorTy->getElementType()
373 ->getPrimitiveSizeInBits()/8)) {
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 }
Cameron Zwarich446d9522011-10-11 06:10:30 +0000378 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000379 }
380 }
Bob Wilson69743022011-01-13 20:59:44 +0000381
Chris Lattner4cc576b2010-04-16 00:24:57 +0000382 // Otherwise, we have a case that we can't handle with an optimized vector
383 // form. We can still turn this into a large integer.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000384 ScalarKind = Integer;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000385}
386
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000387/// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
388/// returning true if the type was successfully merged and false otherwise.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000389bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000390 uint64_t Offset) {
Cameron Zwarich446d9522011-10-11 06:10:30 +0000391 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
392 // If we're storing/loading a vector of the right size, allow it as a
393 // vector. If this the first vector we see, remember the type so that
394 // we know the element size. If this is a subsequent access, ignore it
395 // even if it is a differing type but the same size. Worst case we can
396 // bitcast the resultant vectors.
397 if (!VectorTy)
398 VectorTy = VInTy;
Cameron Zwarich51797822011-06-13 21:44:40 +0000399 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000400 return true;
Cameron Zwarich51797822011-06-13 21:44:40 +0000401 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000402
Cameron Zwarich446d9522011-10-11 06:10:30 +0000403 return false;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000404}
405
Chris Lattner4cc576b2010-04-16 00:24:57 +0000406/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
407/// its accesses to a single vector type, return true and set VecTy to
408/// the new type. If we could convert the alloca into a single promotable
409/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
410/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
411/// is the current offset from the base of the alloca being analyzed.
412///
413/// If we see at least one access to the value that is as a vector type, set the
414/// SawVec flag.
415bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
416 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
417 Instruction *User = cast<Instruction>(*UI);
Bob Wilson69743022011-01-13 20:59:44 +0000418
Chris Lattner4cc576b2010-04-16 00:24:57 +0000419 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
420 // Don't break volatile loads.
Eli Friedman2bc3d522011-09-12 20:23:13 +0000421 if (!LI->isSimple())
Chris Lattner4cc576b2010-04-16 00:24:57 +0000422 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000423 // Don't touch MMX operations.
424 if (LI->getType()->isX86_MMXTy())
425 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000426 HadNonMemTransferAccess = true;
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000427 MergeInTypeForLoadOrStore(LI->getType(), Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000428 continue;
429 }
Bob Wilson69743022011-01-13 20:59:44 +0000430
Chris Lattner4cc576b2010-04-16 00:24:57 +0000431 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
432 // Storing the pointer, not into the value?
Eli Friedman2bc3d522011-09-12 20:23:13 +0000433 if (SI->getOperand(0) == V || !SI->isSimple()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000434 // Don't touch MMX operations.
435 if (SI->getOperand(0)->getType()->isX86_MMXTy())
436 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000437 HadNonMemTransferAccess = true;
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000438 MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000439 continue;
440 }
Bob Wilson69743022011-01-13 20:59:44 +0000441
Chris Lattner4cc576b2010-04-16 00:24:57 +0000442 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Nick Lewycky5a1cb642011-07-25 23:14:22 +0000443 if (!onlyUsedByLifetimeMarkers(BCI))
444 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000445 if (!CanConvertToScalar(BCI, Offset))
446 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000447 continue;
448 }
449
450 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
451 // If this is a GEP with a variable indices, we can't handle it.
452 if (!GEP->hasAllConstantIndices())
453 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000454
Chris Lattner4cc576b2010-04-16 00:24:57 +0000455 // Compute the offset that this GEP adds to the pointer.
456 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Nadav Rotem16087692011-12-05 06:29:09 +0000457 if (!GEP->getPointerOperandType()->isPointerTy())
458 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000459 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
Jay Foad8fbbb392011-07-19 14:01:37 +0000460 Indices);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000461 // See if all uses can be converted.
462 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
463 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000464 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000465 HadNonMemTransferAccess = true;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000466 continue;
467 }
468
469 // If this is a constant sized memset of a constant value (e.g. 0) we can
470 // handle it.
471 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
Cameron Zwarich6be41eb2011-06-18 05:47:49 +0000472 // Store of constant value.
473 if (!isa<ConstantInt>(MSI->getValue()))
Chris Lattnera001b662010-04-16 00:38:19 +0000474 return false;
Cameron Zwarich6be41eb2011-06-18 05:47:49 +0000475
476 // Store of constant size.
477 ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
478 if (!Len)
479 return false;
480
481 // If the size differs from the alloca, we can only convert the alloca to
482 // an integer bag-of-bits.
483 // FIXME: This should handle all of the cases that are currently accepted
484 // as vector element insertions.
485 if (Len->getZExtValue() != AllocaSize || Offset != 0)
486 ScalarKind = Integer;
487
Chris Lattnera001b662010-04-16 00:38:19 +0000488 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000489 HadNonMemTransferAccess = true;
Chris Lattnera001b662010-04-16 00:38:19 +0000490 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000491 }
492
493 // If this is a memcpy or memmove into or out of the whole allocation, we
494 // can handle it like a load or store of the scalar type.
495 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000496 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
497 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
498 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000499
Chris Lattnera001b662010-04-16 00:38:19 +0000500 IsNotTrivial = true; // Can't be mem2reg'd.
501 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000502 }
Bob Wilson69743022011-01-13 20:59:44 +0000503
Nick Lewycky5a1cb642011-07-25 23:14:22 +0000504 // If this is a lifetime intrinsic, we can handle it.
505 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
506 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
507 II->getIntrinsicID() == Intrinsic::lifetime_end) {
508 continue;
509 }
510 }
511
Chris Lattner4cc576b2010-04-16 00:24:57 +0000512 // Otherwise, we cannot handle this!
513 return false;
514 }
Bob Wilson69743022011-01-13 20:59:44 +0000515
Chris Lattner4cc576b2010-04-16 00:24:57 +0000516 return true;
517}
518
519/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
520/// directly. This happens when we are converting an "integer union" to a
521/// single integer scalar, or when we are converting a "vector union" to a
522/// vector with insert/extractelement instructions.
523///
524/// Offset is an offset from the original alloca, in bits that need to be
525/// shifted to the right. By the end of this, there should be no uses of Ptr.
526void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
527 uint64_t Offset) {
528 while (!Ptr->use_empty()) {
529 Instruction *User = cast<Instruction>(Ptr->use_back());
530
531 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
532 ConvertUsesToScalar(CI, NewAI, Offset);
533 CI->eraseFromParent();
534 continue;
535 }
536
537 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
538 // Compute the offset that this GEP adds to the pointer.
539 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
540 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
Jay Foad8fbbb392011-07-19 14:01:37 +0000541 Indices);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000542 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
543 GEP->eraseFromParent();
544 continue;
545 }
Bob Wilson69743022011-01-13 20:59:44 +0000546
Chris Lattner61db1f52010-12-26 22:57:41 +0000547 IRBuilder<> Builder(User);
Bob Wilson69743022011-01-13 20:59:44 +0000548
Chris Lattner4cc576b2010-04-16 00:24:57 +0000549 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
550 // The load is a bit extract from NewAI shifted right by Offset bits.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000551 Value *LoadedVal = Builder.CreateLoad(NewAI);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000552 Value *NewLoadVal
553 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
554 LI->replaceAllUsesWith(NewLoadVal);
555 LI->eraseFromParent();
556 continue;
557 }
Bob Wilson69743022011-01-13 20:59:44 +0000558
Chris Lattner4cc576b2010-04-16 00:24:57 +0000559 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
560 assert(SI->getOperand(0) != Ptr && "Consistency error!");
561 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
562 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
563 Builder);
564 Builder.CreateStore(New, NewAI);
565 SI->eraseFromParent();
Bob Wilson69743022011-01-13 20:59:44 +0000566
Chris Lattner4cc576b2010-04-16 00:24:57 +0000567 // If the load we just inserted is now dead, then the inserted store
568 // overwrote the entire thing.
569 if (Old->use_empty())
570 Old->eraseFromParent();
571 continue;
572 }
Bob Wilson69743022011-01-13 20:59:44 +0000573
Chris Lattner4cc576b2010-04-16 00:24:57 +0000574 // If this is a constant sized memset of a constant value (e.g. 0) we can
575 // transform it into a store of the expanded constant value.
576 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
577 assert(MSI->getRawDest() == Ptr && "Consistency error!");
Duncan Sands01b305f2012-03-23 08:29:04 +0000578 int64_t SNumBytes = cast<ConstantInt>(MSI->getLength())->getSExtValue();
Chris Lattner1fe6bfc2012-03-22 03:46:58 +0000579 if (SNumBytes > 0 && (SNumBytes >> 32) == 0) {
Aaron Ballman7e2fa312012-03-15 00:05:31 +0000580 unsigned NumBytes = static_cast<unsigned>(SNumBytes);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000581 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson69743022011-01-13 20:59:44 +0000582
Chris Lattner4cc576b2010-04-16 00:24:57 +0000583 // Compute the value replicated the right number of times.
584 APInt APVal(NumBytes*8, Val);
585
586 // Splat the value if non-zero.
587 if (Val)
588 for (unsigned i = 1; i != NumBytes; ++i)
589 APVal |= APVal << 8;
Bob Wilson69743022011-01-13 20:59:44 +0000590
Chris Lattner4cc576b2010-04-16 00:24:57 +0000591 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
592 Value *New = ConvertScalar_InsertValue(
593 ConstantInt::get(User->getContext(), APVal),
594 Old, Offset, Builder);
595 Builder.CreateStore(New, NewAI);
Bob Wilson69743022011-01-13 20:59:44 +0000596
Chris Lattner4cc576b2010-04-16 00:24:57 +0000597 // If the load we just inserted is now dead, then the memset overwrote
598 // the entire thing.
599 if (Old->use_empty())
Bob Wilson69743022011-01-13 20:59:44 +0000600 Old->eraseFromParent();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000601 }
602 MSI->eraseFromParent();
603 continue;
604 }
605
606 // If this is a memcpy or memmove into or out of the whole allocation, we
607 // can handle it like a load or store of the scalar type.
608 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
609 assert(Offset == 0 && "must be store to start of alloca");
Bob Wilson69743022011-01-13 20:59:44 +0000610
Chris Lattner4cc576b2010-04-16 00:24:57 +0000611 // If the source and destination are both to the same alloca, then this is
612 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
613 // as appropriate.
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000614 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
Bob Wilson69743022011-01-13 20:59:44 +0000615
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000616 if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000617 // Dest must be OrigAI, change this to be a load from the original
618 // pointer (bitcasted), then a store to our new alloca.
619 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
620 Value *SrcPtr = MTI->getSource();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000621 PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
622 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
Mon P Wange90a6332010-12-23 01:41:32 +0000623 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
624 AIPTy = PointerType::get(AIPTy->getElementType(),
625 SPTy->getAddressSpace());
626 }
627 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
628
Chris Lattner4cc576b2010-04-16 00:24:57 +0000629 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
630 SrcVal->setAlignment(MTI->getAlignment());
631 Builder.CreateStore(SrcVal, NewAI);
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000632 } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000633 // Src must be OrigAI, change this to be a load from NewAI then a store
634 // through the original dest pointer (bitcasted).
635 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
636 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
637
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000638 PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
639 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
Mon P Wange90a6332010-12-23 01:41:32 +0000640 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
641 AIPTy = PointerType::get(AIPTy->getElementType(),
642 DPTy->getAddressSpace());
643 }
644 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
645
Chris Lattner4cc576b2010-04-16 00:24:57 +0000646 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
647 NewStore->setAlignment(MTI->getAlignment());
648 } else {
649 // Noop transfer. Src == Dst
650 }
651
652 MTI->eraseFromParent();
653 continue;
654 }
Bob Wilson69743022011-01-13 20:59:44 +0000655
Nick Lewycky5a1cb642011-07-25 23:14:22 +0000656 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
657 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
658 II->getIntrinsicID() == Intrinsic::lifetime_end) {
659 // There's no need to preserve these, as the resulting alloca will be
660 // converted to a register anyways.
661 II->eraseFromParent();
662 continue;
663 }
664 }
665
Chris Lattner4cc576b2010-04-16 00:24:57 +0000666 llvm_unreachable("Unsupported operation!");
667 }
668}
669
670/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
671/// or vector value FromVal, extracting the bits from the offset specified by
672/// Offset. This returns the value, which is of type ToType.
673///
674/// This happens when we are converting an "integer union" to a single
675/// integer scalar, or when we are converting a "vector union" to a vector with
676/// insert/extractelement instructions.
677///
678/// Offset is an offset from the original alloca, in bits that need to be
679/// shifted to the right.
680Value *ConvertToScalarInfo::
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000681ConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000682 uint64_t Offset, IRBuilder<> &Builder) {
683 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000684 Type *FromType = FromVal->getType();
Mon P Wangbe0761c2011-04-13 21:40:02 +0000685 if (FromType == ToType && Offset == 0)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000686 return FromVal;
687
688 // If the result alloca is a vector type, this is either an element
689 // access or a bitcast to another vector type of the same size.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000690 if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
Cameron Zwarich0398d612011-06-08 22:08:31 +0000691 unsigned FromTypeSize = TD.getTypeAllocSize(FromType);
Cameron Zwarich9827b782011-03-29 05:19:52 +0000692 unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
Cameron Zwarich446d9522011-10-11 06:10:30 +0000693 if (FromTypeSize == ToTypeSize)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000694 return Builder.CreateBitCast(FromVal, ToType);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000695
696 // Otherwise it must be an element access.
697 unsigned Elt = 0;
698 if (Offset) {
699 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
700 Elt = Offset/EltSize;
701 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
702 }
703 // Return the element extracted out of it.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000704 Value *V = Builder.CreateExtractElement(FromVal, Builder.getInt32(Elt));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000705 if (V->getType() != ToType)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000706 V = Builder.CreateBitCast(V, ToType);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000707 return V;
708 }
Bob Wilson69743022011-01-13 20:59:44 +0000709
Chris Lattner4cc576b2010-04-16 00:24:57 +0000710 // If ToType is a first class aggregate, extract out each of the pieces and
711 // use insertvalue's to form the FCA.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000712 if (StructType *ST = dyn_cast<StructType>(ToType)) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000713 const StructLayout &Layout = *TD.getStructLayout(ST);
714 Value *Res = UndefValue::get(ST);
715 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
716 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
717 Offset+Layout.getElementOffsetInBits(i),
718 Builder);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000719 Res = Builder.CreateInsertValue(Res, Elt, i);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000720 }
721 return Res;
722 }
Bob Wilson69743022011-01-13 20:59:44 +0000723
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000724 if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000725 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
726 Value *Res = UndefValue::get(AT);
727 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
728 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
729 Offset+i*EltSize, Builder);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000730 Res = Builder.CreateInsertValue(Res, Elt, i);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000731 }
732 return Res;
733 }
734
735 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000736 IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Chris Lattner4cc576b2010-04-16 00:24:57 +0000737
738 // If this is a big-endian system and the load is narrower than the
739 // full alloca type, we need to do a shift to get the right bits.
740 int ShAmt = 0;
741 if (TD.isBigEndian()) {
742 // On big-endian machines, the lowest bit is stored at the bit offset
743 // from the pointer given by getTypeStoreSizeInBits. This matters for
744 // integers with a bitwidth that is not a multiple of 8.
745 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
746 TD.getTypeStoreSizeInBits(ToType) - Offset;
747 } else {
748 ShAmt = Offset;
749 }
750
751 // Note: we support negative bitwidths (with shl) which are not defined.
752 // We do this to support (f.e.) loads off the end of a structure where
753 // only some bits are used.
754 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
755 FromVal = Builder.CreateLShr(FromVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +0000756 ConstantInt::get(FromVal->getType(), ShAmt));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000757 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson69743022011-01-13 20:59:44 +0000758 FromVal = Builder.CreateShl(FromVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +0000759 ConstantInt::get(FromVal->getType(), -ShAmt));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000760
761 // Finally, unconditionally truncate the integer to the right width.
762 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
763 if (LIBitWidth < NTy->getBitWidth())
764 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000765 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Benjamin Kramera9390a42011-09-27 20:39:19 +0000766 LIBitWidth));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000767 else if (LIBitWidth > NTy->getBitWidth())
768 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000769 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Benjamin Kramera9390a42011-09-27 20:39:19 +0000770 LIBitWidth));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000771
772 // If the result is an integer, this is a trunc or bitcast.
773 if (ToType->isIntegerTy()) {
774 // Should be done.
775 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
776 // Just do a bitcast, we know the sizes match up.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000777 FromVal = Builder.CreateBitCast(FromVal, ToType);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000778 } else {
779 // Otherwise must be a pointer.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000780 FromVal = Builder.CreateIntToPtr(FromVal, ToType);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000781 }
782 assert(FromVal->getType() == ToType && "Didn't convert right?");
783 return FromVal;
784}
785
786/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
787/// or vector value "Old" at the offset specified by Offset.
788///
789/// This happens when we are converting an "integer union" to a
790/// single integer scalar, or when we are converting a "vector union" to a
791/// vector with insert/extractelement instructions.
792///
793/// Offset is an offset from the original alloca, in bits that need to be
794/// shifted to the right.
795Value *ConvertToScalarInfo::
796ConvertScalar_InsertValue(Value *SV, Value *Old,
797 uint64_t Offset, IRBuilder<> &Builder) {
798 // Convert the stored type to the actual type, shift it left to insert
799 // then 'or' into place.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000800 Type *AllocaType = Old->getType();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000801 LLVMContext &Context = Old->getContext();
802
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000803 if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000804 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
805 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
Bob Wilson69743022011-01-13 20:59:44 +0000806
Chris Lattner4cc576b2010-04-16 00:24:57 +0000807 // Changing the whole vector with memset or with an access of a different
808 // vector type?
Cameron Zwarich446d9522011-10-11 06:10:30 +0000809 if (ValSize == VecSize)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000810 return Builder.CreateBitCast(SV, AllocaType);
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000811
Chris Lattner4cc576b2010-04-16 00:24:57 +0000812 // Must be an element insertion.
Cameron Zwarich90747e32011-10-23 07:02:10 +0000813 Type *EltTy = VTy->getElementType();
814 if (SV->getType() != EltTy)
815 SV = Builder.CreateBitCast(SV, EltTy);
816 uint64_t EltSize = TD.getTypeAllocSizeInBits(EltTy);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000817 unsigned Elt = Offset/EltSize;
Benjamin Kramera9390a42011-09-27 20:39:19 +0000818 return Builder.CreateInsertElement(Old, SV, Builder.getInt32(Elt));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000819 }
Bob Wilson69743022011-01-13 20:59:44 +0000820
Chris Lattner4cc576b2010-04-16 00:24:57 +0000821 // If SV is a first-class aggregate value, insert each value recursively.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000822 if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000823 const StructLayout &Layout = *TD.getStructLayout(ST);
824 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000825 Value *Elt = Builder.CreateExtractValue(SV, i);
Bob Wilson69743022011-01-13 20:59:44 +0000826 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000827 Offset+Layout.getElementOffsetInBits(i),
828 Builder);
829 }
830 return Old;
831 }
Bob Wilson69743022011-01-13 20:59:44 +0000832
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000833 if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000834 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
835 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000836 Value *Elt = Builder.CreateExtractValue(SV, i);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000837 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
838 }
839 return Old;
840 }
841
842 // If SV is a float, convert it to the appropriate integer type.
843 // If it is a pointer, do the same.
844 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
845 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
846 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
847 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
848 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000849 SV = Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(),SrcWidth));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000850 else if (SV->getType()->isPointerTy())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000851 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000852
853 // Zero extend or truncate the value if needed.
854 if (SV->getType() != AllocaType) {
855 if (SV->getType()->getPrimitiveSizeInBits() <
856 AllocaType->getPrimitiveSizeInBits())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000857 SV = Builder.CreateZExt(SV, AllocaType);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000858 else {
859 // Truncation may be needed if storing more than the alloca can hold
860 // (undefined behavior).
Benjamin Kramera9390a42011-09-27 20:39:19 +0000861 SV = Builder.CreateTrunc(SV, AllocaType);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000862 SrcWidth = DestWidth;
863 SrcStoreWidth = DestStoreWidth;
864 }
865 }
866
867 // If this is a big-endian system and the store is narrower than the
868 // full alloca type, we need to do a shift to get the right bits.
869 int ShAmt = 0;
870 if (TD.isBigEndian()) {
871 // On big-endian machines, the lowest bit is stored at the bit offset
872 // from the pointer given by getTypeStoreSizeInBits. This matters for
873 // integers with a bitwidth that is not a multiple of 8.
874 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
875 } else {
876 ShAmt = Offset;
877 }
878
879 // Note: we support negative bitwidths (with shr) which are not defined.
880 // We do this to support (f.e.) stores off the end of a structure where
881 // only some bits in the structure are set.
882 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
883 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000884 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000885 Mask <<= ShAmt;
886 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000887 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000888 Mask = Mask.lshr(-ShAmt);
889 }
890
891 // Mask out the bits we are about to insert from the old value, and or
892 // in the new bits.
893 if (SrcWidth != DestWidth) {
894 assert(DestWidth > SrcWidth);
895 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
896 SV = Builder.CreateOr(Old, SV, "ins");
897 }
898 return SV;
899}
900
901
902//===----------------------------------------------------------------------===//
903// SRoA Driver
904//===----------------------------------------------------------------------===//
905
906
Chris Lattnered7b41e2003-05-27 15:45:27 +0000907bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000908 TD = getAnalysisIfAvailable<TargetData>();
909
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000910 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000911
912 // FIXME: ScalarRepl currently depends on TargetData more than it
913 // theoretically needs to. It should be refactored in order to support
914 // target-independent IR. Until this is done, just skip the actual
915 // scalar-replacement portion of this pass.
916 if (!TD) return Changed;
917
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000918 while (1) {
919 bool LocalChange = performScalarRepl(F);
920 if (!LocalChange) break; // No need to repromote if no scalarrepl
921 Changed = true;
922 LocalChange = performPromotion(F);
923 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
924 }
Chris Lattner38aec322003-09-11 16:45:55 +0000925
926 return Changed;
927}
928
Chris Lattnerd0f56132011-01-14 19:50:47 +0000929namespace {
930class AllocaPromoter : public LoadAndStorePromoter {
931 AllocaInst *AI;
Devang Patel231a5ab2011-07-06 21:09:55 +0000932 DIBuilder *DIB;
Devang Patel4fd3c592011-07-06 22:06:11 +0000933 SmallVector<DbgDeclareInst *, 4> DDIs;
934 SmallVector<DbgValueInst *, 4> DVIs;
Chris Lattnerd0f56132011-01-14 19:50:47 +0000935public:
Cameron Zwarichc8279392011-05-24 03:10:43 +0000936 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
Devang Patel231a5ab2011-07-06 21:09:55 +0000937 DIBuilder *DB)
Devang Patel4fd3c592011-07-06 22:06:11 +0000938 : LoadAndStorePromoter(Insts, S), AI(0), DIB(DB) {}
Chris Lattnerd0f56132011-01-14 19:50:47 +0000939
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000940 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerd0f56132011-01-14 19:50:47 +0000941 // Remember which alloca we're promoting (for isInstInList).
942 this->AI = AI;
Rafael Espindola125ef762011-12-26 23:12:42 +0000943 if (MDNode *DebugNode = MDNode::getIfExists(AI->getContext(), AI)) {
Devang Patel4fd3c592011-07-06 22:06:11 +0000944 for (Value::use_iterator UI = DebugNode->use_begin(),
945 E = DebugNode->use_end(); UI != E; ++UI)
946 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
947 DDIs.push_back(DDI);
948 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
949 DVIs.push_back(DVI);
Rafael Espindola125ef762011-12-26 23:12:42 +0000950 }
Devang Patel4fd3c592011-07-06 22:06:11 +0000951
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000952 LoadAndStorePromoter::run(Insts);
Chris Lattnerd0f56132011-01-14 19:50:47 +0000953 AI->eraseFromParent();
Devang Patel4fd3c592011-07-06 22:06:11 +0000954 for (SmallVector<DbgDeclareInst *, 4>::iterator I = DDIs.begin(),
955 E = DDIs.end(); I != E; ++I) {
956 DbgDeclareInst *DDI = *I;
Devang Patel231a5ab2011-07-06 21:09:55 +0000957 DDI->eraseFromParent();
Devang Patel4fd3c592011-07-06 22:06:11 +0000958 }
959 for (SmallVector<DbgValueInst *, 4>::iterator I = DVIs.begin(),
960 E = DVIs.end(); I != E; ++I) {
961 DbgValueInst *DVI = *I;
962 DVI->eraseFromParent();
963 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000964 }
965
Chris Lattnerd0f56132011-01-14 19:50:47 +0000966 virtual bool isInstInList(Instruction *I,
967 const SmallVectorImpl<Instruction*> &Insts) const {
968 if (LoadInst *LI = dyn_cast<LoadInst>(I))
969 return LI->getOperand(0) == AI;
970 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000971 }
Devang Patel231a5ab2011-07-06 21:09:55 +0000972
Devang Patel4fd3c592011-07-06 22:06:11 +0000973 virtual void updateDebugInfo(Instruction *Inst) const {
974 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
975 E = DDIs.end(); I != E; ++I) {
976 DbgDeclareInst *DDI = *I;
977 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
978 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
979 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
980 ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
981 }
982 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
983 E = DVIs.end(); I != E; ++I) {
984 DbgValueInst *DVI = *I;
Benjamin Kramer6a1c7792012-02-23 17:42:19 +0000985 Value *Arg = NULL;
Devang Patel4fd3c592011-07-06 22:06:11 +0000986 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Devang Patel4fd3c592011-07-06 22:06:11 +0000987 // If an argument is zero extended then use argument directly. The ZExt
988 // may be zapped by an optimization pass in future.
Devang Patel4fd3c592011-07-06 22:06:11 +0000989 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
Benjamin Kramer6a1c7792012-02-23 17:42:19 +0000990 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Devang Patel4fd3c592011-07-06 22:06:11 +0000991 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Benjamin Kramer6a1c7792012-02-23 17:42:19 +0000992 Arg = dyn_cast<Argument>(SExt->getOperand(0));
993 if (!Arg)
994 Arg = SI->getOperand(0);
Devang Patel4fd3c592011-07-06 22:06:11 +0000995 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Benjamin Kramer6a1c7792012-02-23 17:42:19 +0000996 Arg = LI->getOperand(0);
997 } else {
998 continue;
Devang Patel4fd3c592011-07-06 22:06:11 +0000999 }
Benjamin Kramer6a1c7792012-02-23 17:42:19 +00001000 Instruction *DbgVal =
1001 DIB->insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1002 Inst);
1003 DbgVal->setDebugLoc(DVI->getDebugLoc());
Devang Patel4fd3c592011-07-06 22:06:11 +00001004 }
Devang Patel231a5ab2011-07-06 21:09:55 +00001005 }
Chris Lattnerd0f56132011-01-14 19:50:47 +00001006};
1007} // end anon namespace
Chris Lattner38aec322003-09-11 16:45:55 +00001008
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001009/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1010/// subsequently loaded can be rewritten to load both input pointers and then
1011/// select between the result, allowing the load of the alloca to be promoted.
1012/// From this:
1013/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1014/// %V = load i32* %P2
1015/// to:
1016/// %V1 = load i32* %Alloca -> will be mem2reg'd
1017/// %V2 = load i32* %Other
Chris Lattnere3357862011-01-24 01:07:11 +00001018/// %V = select i1 %cond, i32 %V1, i32 %V2
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001019///
1020/// We can do this to a select if its only uses are loads and if the operand to
1021/// the select can be loaded unconditionally.
1022static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
1023 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1024 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1025
1026 for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1027 UI != UE; ++UI) {
1028 LoadInst *LI = dyn_cast<LoadInst>(*UI);
Eli Friedman2bc3d522011-09-12 20:23:13 +00001029 if (LI == 0 || !LI->isSimple()) return false;
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001030
Chris Lattnere3357862011-01-24 01:07:11 +00001031 // Both operands to the select need to be dereferencable, either absolutely
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001032 // (e.g. allocas) or at this point because we can see other accesses to it.
1033 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1034 LI->getAlignment(), TD))
1035 return false;
1036 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1037 LI->getAlignment(), TD))
1038 return false;
1039 }
1040
1041 return true;
1042}
1043
Chris Lattnere3357862011-01-24 01:07:11 +00001044/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1045/// subsequently loaded can be rewritten to load both input pointers in the pred
1046/// blocks and then PHI the results, allowing the load of the alloca to be
1047/// promoted.
1048/// From this:
1049/// %P2 = phi [i32* %Alloca, i32* %Other]
1050/// %V = load i32* %P2
1051/// to:
1052/// %V1 = load i32* %Alloca -> will be mem2reg'd
1053/// ...
1054/// %V2 = load i32* %Other
1055/// ...
1056/// %V = phi [i32 %V1, i32 %V2]
1057///
1058/// We can do this to a select if its only uses are loads and if the operand to
1059/// the select can be loaded unconditionally.
1060static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
1061 // For now, we can only do this promotion if the load is in the same block as
1062 // the PHI, and if there are no stores between the phi and load.
1063 // TODO: Allow recursive phi users.
1064 // TODO: Allow stores.
1065 BasicBlock *BB = PN->getParent();
1066 unsigned MaxAlign = 0;
1067 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1068 UI != UE; ++UI) {
1069 LoadInst *LI = dyn_cast<LoadInst>(*UI);
Eli Friedman2bc3d522011-09-12 20:23:13 +00001070 if (LI == 0 || !LI->isSimple()) return false;
Chris Lattnere3357862011-01-24 01:07:11 +00001071
1072 // For now we only allow loads in the same block as the PHI. This is a
1073 // common case that happens when instcombine merges two loads through a PHI.
1074 if (LI->getParent() != BB) return false;
1075
1076 // Ensure that there are no instructions between the PHI and the load that
1077 // could store.
1078 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1079 if (BBI->mayWriteToMemory())
1080 return false;
1081
1082 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1083 }
1084
1085 // Okay, we know that we have one or more loads in the same block as the PHI.
1086 // We can transform this if it is safe to push the loads into the predecessor
1087 // blocks. The only thing to watch out for is that we can't put a possibly
1088 // trapping load in the predecessor if it is a critical edge.
1089 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1090 BasicBlock *Pred = PN->getIncomingBlock(i);
Eli Friedmand102a032011-09-22 18:56:30 +00001091 Value *InVal = PN->getIncomingValue(i);
1092
1093 // If the terminator of the predecessor has side-effects (an invoke),
1094 // there is no safe place to put a load in the predecessor.
1095 if (Pred->getTerminator()->mayHaveSideEffects())
1096 return false;
1097
1098 // If the value is produced by the terminator of the predecessor
1099 // (an invoke), there is no valid place to put a load in the predecessor.
1100 if (Pred->getTerminator() == InVal)
1101 return false;
Chris Lattnere3357862011-01-24 01:07:11 +00001102
1103 // If the predecessor has a single successor, then the edge isn't critical.
1104 if (Pred->getTerminator()->getNumSuccessors() == 1)
1105 continue;
Chris Lattnere3357862011-01-24 01:07:11 +00001106
1107 // If this pointer is always safe to load, or if we can prove that there is
1108 // already a load in the block, then we can move the load to the pred block.
1109 if (InVal->isDereferenceablePointer() ||
1110 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1111 continue;
1112
1113 return false;
1114 }
1115
1116 return true;
1117}
1118
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001119
1120/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1121/// direct (non-volatile) loads and stores to it. If the alloca is close but
1122/// not quite there, this will transform the code to allow promotion. As such,
1123/// it is a non-pure predicate.
1124static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
1125 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1126 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1127
1128 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1129 UI != UE; ++UI) {
1130 User *U = *UI;
1131 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Eli Friedman2bc3d522011-09-12 20:23:13 +00001132 if (!LI->isSimple())
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001133 return false;
1134 continue;
1135 }
1136
1137 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Eli Friedman2bc3d522011-09-12 20:23:13 +00001138 if (SI->getOperand(0) == AI || !SI->isSimple())
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001139 return false; // Don't allow a store OF the AI, only INTO the AI.
1140 continue;
1141 }
1142
1143 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1144 // If the condition being selected on is a constant, fold the select, yes
1145 // this does (rarely) happen early on.
1146 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1147 Value *Result = SI->getOperand(1+CI->isZero());
1148 SI->replaceAllUsesWith(Result);
1149 SI->eraseFromParent();
1150
1151 // This is very rare and we just scrambled the use list of AI, start
1152 // over completely.
1153 return tryToMakeAllocaBePromotable(AI, TD);
1154 }
1155
1156 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1157 // loads, then we can transform this by rewriting the select.
1158 if (!isSafeSelectToSpeculate(SI, TD))
1159 return false;
1160
1161 InstsToRewrite.insert(SI);
1162 continue;
1163 }
1164
Chris Lattnere3357862011-01-24 01:07:11 +00001165 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1166 if (PN->use_empty()) { // Dead PHIs can be stripped.
1167 InstsToRewrite.insert(PN);
1168 continue;
1169 }
1170
1171 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1172 // in the pred blocks, then we can transform this by rewriting the PHI.
1173 if (!isSafePHIToSpeculate(PN, TD))
1174 return false;
1175
1176 InstsToRewrite.insert(PN);
1177 continue;
1178 }
1179
Nick Lewycky5a1cb642011-07-25 23:14:22 +00001180 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1181 if (onlyUsedByLifetimeMarkers(BCI)) {
1182 InstsToRewrite.insert(BCI);
1183 continue;
1184 }
1185 }
1186
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001187 return false;
1188 }
1189
1190 // If there are no instructions to rewrite, then all uses are load/stores and
1191 // we're done!
1192 if (InstsToRewrite.empty())
1193 return true;
1194
1195 // If we have instructions that need to be rewritten for this to be promotable
1196 // take care of it now.
1197 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
Nick Lewycky5a1cb642011-07-25 23:14:22 +00001198 if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
1199 // This could only be a bitcast used by nothing but lifetime intrinsics.
1200 for (BitCastInst::use_iterator I = BCI->use_begin(), E = BCI->use_end();
1201 I != E;) {
1202 Use &U = I.getUse();
1203 ++I;
1204 cast<Instruction>(U.getUser())->eraseFromParent();
1205 }
1206 BCI->eraseFromParent();
1207 continue;
1208 }
1209
Chris Lattnere3357862011-01-24 01:07:11 +00001210 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1211 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1212 // loads with a new select.
1213 while (!SI->use_empty()) {
1214 LoadInst *LI = cast<LoadInst>(SI->use_back());
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001215
Chris Lattnere3357862011-01-24 01:07:11 +00001216 IRBuilder<> Builder(LI);
1217 LoadInst *TrueLoad =
1218 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1219 LoadInst *FalseLoad =
Nick Lewycky394d1f12011-07-01 06:27:03 +00001220 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
Chris Lattnere3357862011-01-24 01:07:11 +00001221
1222 // Transfer alignment and TBAA info if present.
1223 TrueLoad->setAlignment(LI->getAlignment());
1224 FalseLoad->setAlignment(LI->getAlignment());
1225 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1226 TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1227 FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1228 }
1229
1230 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1231 V->takeName(LI);
1232 LI->replaceAllUsesWith(V);
1233 LI->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001234 }
Chris Lattnere3357862011-01-24 01:07:11 +00001235
1236 // Now that all the loads are gone, the select is gone too.
1237 SI->eraseFromParent();
1238 continue;
1239 }
1240
1241 // Otherwise, we have a PHI node which allows us to push the loads into the
1242 // predecessors.
1243 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1244 if (PN->use_empty()) {
1245 PN->eraseFromParent();
1246 continue;
1247 }
1248
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001249 Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
Jay Foad3ecfc862011-03-30 11:28:46 +00001250 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1251 PN->getName()+".ld", PN);
Chris Lattnere3357862011-01-24 01:07:11 +00001252
1253 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1254 // matter which one we get and if any differ, it doesn't matter.
1255 LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1256 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1257 unsigned Align = SomeLoad->getAlignment();
1258
1259 // Rewrite all loads of the PN to use the new PHI.
1260 while (!PN->use_empty()) {
1261 LoadInst *LI = cast<LoadInst>(PN->use_back());
1262 LI->replaceAllUsesWith(NewPN);
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001263 LI->eraseFromParent();
1264 }
1265
Chris Lattnere3357862011-01-24 01:07:11 +00001266 // Inject loads into all of the pred blocks. Keep track of which blocks we
1267 // insert them into in case we have multiple edges from the same block.
1268 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1269
1270 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1271 BasicBlock *Pred = PN->getIncomingBlock(i);
1272 LoadInst *&Load = InsertedLoads[Pred];
1273 if (Load == 0) {
1274 Load = new LoadInst(PN->getIncomingValue(i),
1275 PN->getName() + "." + Pred->getName(),
1276 Pred->getTerminator());
1277 Load->setAlignment(Align);
1278 if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1279 }
1280
1281 NewPN->addIncoming(Load, Pred);
1282 }
1283
1284 PN->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001285 }
1286
1287 ++NumAdjusted;
1288 return true;
1289}
1290
Chris Lattner38aec322003-09-11 16:45:55 +00001291bool SROA::performPromotion(Function &F) {
1292 std::vector<AllocaInst*> Allocas;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001293 DominatorTree *DT = 0;
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001294 if (HasDomTree)
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001295 DT = &getAnalysis<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +00001296
Chris Lattner02a3be02003-09-20 14:39:18 +00001297 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Devang Patel231a5ab2011-07-06 21:09:55 +00001298 DIBuilder DIB(*F.getParent());
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001299 bool Changed = false;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001300 SmallVector<Instruction*, 64> Insts;
Chris Lattner38aec322003-09-11 16:45:55 +00001301 while (1) {
1302 Allocas.clear();
1303
1304 // Find allocas that are safe to promote, by looking at all instructions in
1305 // the entry node
1306 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1307 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001308 if (tryToMakeAllocaBePromotable(AI, TD))
Chris Lattner38aec322003-09-11 16:45:55 +00001309 Allocas.push_back(AI);
1310
1311 if (Allocas.empty()) break;
1312
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001313 if (HasDomTree)
Cameron Zwarich419e8a62011-01-17 17:38:41 +00001314 PromoteMemToReg(Allocas, *DT);
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001315 else {
1316 SSAUpdater SSA;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001317 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1318 AllocaInst *AI = Allocas[i];
1319
1320 // Build list of instructions to promote.
1321 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1322 UI != E; ++UI)
1323 Insts.push_back(cast<Instruction>(*UI));
Devang Patel231a5ab2011-07-06 21:09:55 +00001324 AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001325 Insts.clear();
1326 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001327 }
Chris Lattner38aec322003-09-11 16:45:55 +00001328 NumPromoted += Allocas.size();
1329 Changed = true;
1330 }
1331
1332 return Changed;
1333}
1334
Chris Lattner4cc576b2010-04-16 00:24:57 +00001335
Bob Wilson3992feb2010-02-03 17:23:56 +00001336/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1337/// SROA. It must be a struct or array type with a small number of elements.
1338static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001339 Type *T = AI->getAllocatedType();
Bob Wilson3992feb2010-02-03 17:23:56 +00001340 // Do not promote any struct into more than 32 separate vars.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001341 if (StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +00001342 return ST->getNumElements() <= 32;
1343 // Arrays are much less likely to be safe for SROA; only consider
1344 // them if they are very small.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001345 if (ArrayType *AT = dyn_cast<ArrayType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +00001346 return AT->getNumElements() <= 8;
1347 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +00001348}
1349
Peter Collingbourne9012c572012-05-19 22:52:10 +00001350/// getPointeeAlignment - Compute the minimum alignment of the value pointed
1351/// to by the given pointer.
1352static unsigned getPointeeAlignment(Value *V, const TargetData &TD) {
1353 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1354 if (CE->getOpcode() == Instruction::BitCast ||
1355 (CE->getOpcode() == Instruction::GetElementPtr &&
1356 cast<GEPOperator>(CE)->hasAllZeroIndices()))
1357 return getPointeeAlignment(CE->getOperand(0), TD);
1358
1359 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1360 if (!GV->isDeclaration())
1361 return TD.getPreferredAlignment(GV);
1362
1363 if (PointerType *PT = dyn_cast<PointerType>(V->getType()))
1364 return TD.getABITypeAlignment(PT->getElementType());
1365
1366 return 0;
1367}
1368
Chris Lattnerc4472072010-04-15 23:50:26 +00001369
Chris Lattner38aec322003-09-11 16:45:55 +00001370// performScalarRepl - This algorithm is a simple worklist driven algorithm,
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001371// which runs on all of the alloca instructions in the function, removing them
1372// if they are only used by getelementptr instructions.
Chris Lattner38aec322003-09-11 16:45:55 +00001373//
1374bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001375 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +00001376
Chris Lattner31d80102010-04-15 21:59:20 +00001377 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +00001378 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001379 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +00001380 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +00001381 WorkList.push_back(A);
1382
1383 // Process the worklist
1384 bool Changed = false;
1385 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001386 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001387 WorkList.pop_back();
Bob Wilson69743022011-01-13 20:59:44 +00001388
Chris Lattneradd2bd72006-12-22 23:14:42 +00001389 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1390 // with unused elements.
1391 if (AI->use_empty()) {
1392 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +00001393 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +00001394 continue;
1395 }
Chris Lattner7809ecd2009-02-03 01:30:09 +00001396
1397 // If this alloca is impossible for us to promote, reject it early.
1398 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1399 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001400
Chris Lattner79b3bd32007-04-25 06:40:51 +00001401 // Check to see if this allocation is only modified by a memcpy/memmove from
Peter Collingbourne9012c572012-05-19 22:52:10 +00001402 // a constant global whose alignment is equal to or exceeds that of the
1403 // allocation. If this is the case, we can change all users to use
Chris Lattner79b3bd32007-04-25 06:40:51 +00001404 // the constant global instead. This is commonly produced by the CFE by
1405 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1406 // is only subsequently read.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001407 SmallVector<Instruction *, 4> ToDelete;
1408 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(AI, ToDelete)) {
Peter Collingbourne9012c572012-05-19 22:52:10 +00001409 if (AI->getAlignment() <= getPointeeAlignment(Copy->getSource(), *TD)) {
1410 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
1411 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
1412 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
1413 ToDelete[i]->eraseFromParent();
1414 Constant *TheSrc = cast<Constant>(Copy->getSource());
1415 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
1416 Copy->eraseFromParent(); // Don't mutate the global.
1417 AI->eraseFromParent();
1418 ++NumGlobals;
1419 Changed = true;
1420 continue;
1421 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00001422 }
Bob Wilson69743022011-01-13 20:59:44 +00001423
Chris Lattner7809ecd2009-02-03 01:30:09 +00001424 // Check to see if we can perform the core SROA transformation. We cannot
1425 // transform the allocation instruction if it is an array allocation
1426 // (allocations OF arrays are ok though), and an allocation of a scalar
1427 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +00001428 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +00001429
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +00001430 // Do not promote [0 x %struct].
1431 if (AllocaSize == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001432
Chris Lattner31d80102010-04-15 21:59:20 +00001433 // Do not promote any struct whose size is too big.
1434 if (AllocaSize > SRThreshold) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001435
Bob Wilson3992feb2010-02-03 17:23:56 +00001436 // If the alloca looks like a good candidate for scalar replacement, and if
1437 // all its users can be transformed, then split up the aggregate into its
1438 // separate elements.
1439 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1440 DoScalarReplacement(AI, WorkList);
1441 Changed = true;
1442 continue;
1443 }
1444
Chris Lattner6e733d32009-01-28 20:16:43 +00001445 // If we can turn this aggregate value (potentially with casts) into a
1446 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001447 // IsNotTrivial tracks whether this is something that mem2reg could have
1448 // promoted itself. If so, we don't want to transform it needlessly. Note
1449 // that we can't just check based on the type: the alloca may be of an i32
1450 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +00001451 if (AllocaInst *NewAI =
1452 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001453 NewAI->takeName(AI);
1454 AI->eraseFromParent();
1455 ++NumConverted;
1456 Changed = true;
1457 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001458 }
1459
Chris Lattner7809ecd2009-02-03 01:30:09 +00001460 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +00001461 }
1462
1463 return Changed;
1464}
Chris Lattner5e062a12003-05-30 04:15:41 +00001465
Chris Lattnera10b29b2007-04-25 05:02:56 +00001466/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1467/// predicate, do SROA now.
Bob Wilson69743022011-01-13 20:59:44 +00001468void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001469 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +00001470 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +00001471 SmallVector<AllocaInst*, 32> ElementAllocas;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001472 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
Chris Lattnera10b29b2007-04-25 05:02:56 +00001473 ElementAllocas.reserve(ST->getNumContainedTypes());
1474 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Bob Wilson69743022011-01-13 20:59:44 +00001475 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +00001476 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001477 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001478 ElementAllocas.push_back(NA);
1479 WorkList.push_back(NA); // Add to worklist for recursive processing
1480 }
1481 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001482 ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
Chris Lattnera10b29b2007-04-25 05:02:56 +00001483 ElementAllocas.reserve(AT->getNumElements());
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001484 Type *ElTy = AT->getElementType();
Chris Lattnera10b29b2007-04-25 05:02:56 +00001485 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +00001486 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001487 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001488 ElementAllocas.push_back(NA);
1489 WorkList.push_back(NA); // Add to worklist for recursive processing
1490 }
1491 }
1492
Bob Wilsonb742def2009-12-18 20:14:40 +00001493 // Now that we have created the new alloca instructions, rewrite all the
1494 // uses of the old alloca.
1495 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +00001496
Bob Wilsonb742def2009-12-18 20:14:40 +00001497 // Now erase any instructions that were made dead while rewriting the alloca.
1498 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +00001499 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +00001500
Dan Gohmanfe601042010-06-22 15:08:57 +00001501 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +00001502}
Chris Lattnera59adc42009-12-14 05:11:02 +00001503
Bob Wilsonb742def2009-12-18 20:14:40 +00001504/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1505/// recursively including all their operands that become trivially dead.
1506void SROA::DeleteDeadInstructions() {
1507 while (!DeadInsts.empty()) {
1508 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +00001509
Bob Wilsonb742def2009-12-18 20:14:40 +00001510 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1511 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1512 // Zero out the operand and see if it becomes trivially dead.
1513 // (But, don't add allocas to the dead instruction list -- they are
1514 // already on the worklist and will be deleted separately.)
1515 *OI = 0;
1516 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1517 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +00001518 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001519
1520 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +00001521 }
Chris Lattnera59adc42009-12-14 05:11:02 +00001522}
Bob Wilson69743022011-01-13 20:59:44 +00001523
Bob Wilsonb742def2009-12-18 20:14:40 +00001524/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1525/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001526/// the Info parameter. Offset indicates the position within AI that is
1527/// referenced by this instruction.
Chris Lattner6c95d242011-01-23 07:29:29 +00001528void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001529 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001530 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1531 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +00001532
Bob Wilsonb742def2009-12-18 20:14:40 +00001533 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Chris Lattner6c95d242011-01-23 07:29:29 +00001534 isSafeForScalarRepl(BC, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001535 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001536 uint64_t GEPOffset = Offset;
Chris Lattner6c95d242011-01-23 07:29:29 +00001537 isSafeGEP(GEPI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001538 if (!Info.isUnsafe)
Chris Lattner6c95d242011-01-23 07:29:29 +00001539 isSafeForScalarRepl(GEPI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001540 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001541 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001542 if (Length == 0)
1543 return MarkUnsafe(Info, User);
Aaron Ballman7e2fa312012-03-15 00:05:31 +00001544 if (Length->isNegative())
1545 return MarkUnsafe(Info, User);
1546
Chris Lattner6c95d242011-01-23 07:29:29 +00001547 isSafeMemAccess(Offset, Length->getZExtValue(), 0,
Chris Lattner145c5322011-01-23 08:27:54 +00001548 UI.getOperandNo() == 0, Info, MI,
1549 true /*AllowWholeAccess*/);
Bob Wilsonb742def2009-12-18 20:14:40 +00001550 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Eli Friedman2bc3d522011-09-12 20:23:13 +00001551 if (!LI->isSimple())
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001552 return MarkUnsafe(Info, User);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001553 Type *LIType = LI->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001554 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001555 LIType, false, Info, LI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001556 Info.hasALoadOrStore = true;
1557
Bob Wilsonb742def2009-12-18 20:14:40 +00001558 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1559 // Store is ok if storing INTO the pointer, not storing the pointer
Eli Friedman2bc3d522011-09-12 20:23:13 +00001560 if (!SI->isSimple() || SI->getOperand(0) == I)
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001561 return MarkUnsafe(Info, User);
1562
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001563 Type *SIType = SI->getOperand(0)->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001564 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001565 SIType, true, Info, SI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001566 Info.hasALoadOrStore = true;
Nick Lewycky5a1cb642011-07-25 23:14:22 +00001567 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1568 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1569 II->getIntrinsicID() != Intrinsic::lifetime_end)
1570 return MarkUnsafe(Info, User);
Chris Lattner145c5322011-01-23 08:27:54 +00001571 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1572 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1573 } else {
1574 return MarkUnsafe(Info, User);
1575 }
1576 if (Info.isUnsafe) return;
1577 }
1578}
1579
1580
1581/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1582/// derived from the alloca, we can often still split the alloca into elements.
1583/// This is useful if we have a large alloca where one element is phi'd
1584/// together somewhere: we can SRoA and promote all the other elements even if
1585/// we end up not being able to promote this one.
1586///
1587/// All we require is that the uses of the PHI do not index into other parts of
1588/// the alloca. The most important use case for this is single load and stores
1589/// that are PHI'd together, which can happen due to code sinking.
1590void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1591 AllocaInfo &Info) {
1592 // If we've already checked this PHI, don't do it again.
1593 if (PHINode *PN = dyn_cast<PHINode>(I))
1594 if (!Info.CheckedPHIs.insert(PN))
1595 return;
1596
1597 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1598 Instruction *User = cast<Instruction>(*UI);
1599
1600 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1601 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1602 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1603 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1604 // but would have to prove that we're staying inside of an element being
1605 // promoted.
1606 if (!GEPI->hasAllZeroIndices())
1607 return MarkUnsafe(Info, User);
1608 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1609 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Eli Friedman2bc3d522011-09-12 20:23:13 +00001610 if (!LI->isSimple())
Chris Lattner145c5322011-01-23 08:27:54 +00001611 return MarkUnsafe(Info, User);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001612 Type *LIType = LI->getType();
Chris Lattner145c5322011-01-23 08:27:54 +00001613 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1614 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1615 Info.hasALoadOrStore = true;
1616
1617 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1618 // Store is ok if storing INTO the pointer, not storing the pointer
Eli Friedman2bc3d522011-09-12 20:23:13 +00001619 if (!SI->isSimple() || SI->getOperand(0) == I)
Chris Lattner145c5322011-01-23 08:27:54 +00001620 return MarkUnsafe(Info, User);
1621
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001622 Type *SIType = SI->getOperand(0)->getType();
Chris Lattner145c5322011-01-23 08:27:54 +00001623 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1624 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1625 Info.hasALoadOrStore = true;
1626 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1627 isSafePHISelectUseForScalarRepl(User, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001628 } else {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001629 return MarkUnsafe(Info, User);
Bob Wilsonb742def2009-12-18 20:14:40 +00001630 }
1631 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001632 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001633}
Bob Wilson39c88a62009-12-17 18:34:24 +00001634
Bob Wilsonb742def2009-12-18 20:14:40 +00001635/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1636/// replacement. It is safe when all the indices are constant, in-bounds
1637/// references, and when the resulting offset corresponds to an element within
1638/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001639/// return, Offset is adjusted as specified by the GEP indices.
Chris Lattner6c95d242011-01-23 07:29:29 +00001640void SROA::isSafeGEP(GetElementPtrInst *GEPI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001641 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001642 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1643 if (GEPIt == E)
1644 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001645
Chris Lattner88e6dc82008-08-23 05:21:06 +00001646 // Walk through the GEP type indices, checking the types that this indexes
1647 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001648 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001649 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001650 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001651 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001652
Bob Wilsonb742def2009-12-18 20:14:40 +00001653 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1654 if (!IdxVal)
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001655 return MarkUnsafe(Info, GEPI);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001656 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001657
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001658 // Compute the offset due to this GEP and check if the alloca has a
1659 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001660 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
Jay Foad8fbbb392011-07-19 14:01:37 +00001661 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
Chris Lattner6c95d242011-01-23 07:29:29 +00001662 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001663 MarkUnsafe(Info, GEPI);
Chris Lattner5e062a12003-05-30 04:15:41 +00001664}
1665
Bob Wilson704d1342011-01-13 17:45:11 +00001666/// isHomogeneousAggregate - Check if type T is a struct or array containing
1667/// elements of the same type (which is always true for arrays). If so,
1668/// return true with NumElts and EltTy set to the number of elements and the
1669/// element type, respectively.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001670static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
1671 Type *&EltTy) {
1672 if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
Bob Wilson704d1342011-01-13 17:45:11 +00001673 NumElts = AT->getNumElements();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001674 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
Bob Wilson704d1342011-01-13 17:45:11 +00001675 return true;
1676 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001677 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilson704d1342011-01-13 17:45:11 +00001678 NumElts = ST->getNumContainedTypes();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001679 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
Bob Wilson704d1342011-01-13 17:45:11 +00001680 for (unsigned n = 1; n < NumElts; ++n) {
1681 if (ST->getContainedType(n) != EltTy)
1682 return false;
1683 }
1684 return true;
1685 }
1686 return false;
1687}
1688
1689/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1690/// "homogeneous" aggregates with the same element type and number of elements.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001691static bool isCompatibleAggregate(Type *T1, Type *T2) {
Bob Wilson704d1342011-01-13 17:45:11 +00001692 if (T1 == T2)
1693 return true;
1694
1695 unsigned NumElts1, NumElts2;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001696 Type *EltTy1, *EltTy2;
Bob Wilson704d1342011-01-13 17:45:11 +00001697 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1698 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1699 NumElts1 == NumElts2 &&
1700 EltTy1 == EltTy2)
1701 return true;
1702
1703 return false;
1704}
1705
Bob Wilsonb742def2009-12-18 20:14:40 +00001706/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1707/// alloca or has an offset and size that corresponds to a component element
1708/// within it. The offset checked here may have been formed from a GEP with a
1709/// pointer bitcasted to a different type.
Chris Lattner145c5322011-01-23 08:27:54 +00001710///
1711/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1712/// unit. If false, it only allows accesses known to be in a single element.
Chris Lattner6c95d242011-01-23 07:29:29 +00001713void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001714 Type *MemOpType, bool isStore,
Chris Lattner145c5322011-01-23 08:27:54 +00001715 AllocaInfo &Info, Instruction *TheAccess,
1716 bool AllowWholeAccess) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001717 // Check if this is a load/store of the entire alloca.
Chris Lattner145c5322011-01-23 08:27:54 +00001718 if (Offset == 0 && AllowWholeAccess &&
Chris Lattner6c95d242011-01-23 07:29:29 +00001719 MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
Bob Wilson704d1342011-01-13 17:45:11 +00001720 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1721 // loads/stores (which are essentially the same as the MemIntrinsics with
1722 // regard to copying padding between elements). But, if an alloca is
1723 // flagged as both a source and destination of such operations, we'll need
1724 // to check later for padding between elements.
1725 if (!MemOpType || MemOpType->isIntegerTy()) {
1726 if (isStore)
1727 Info.isMemCpyDst = true;
1728 else
1729 Info.isMemCpySrc = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001730 return;
1731 }
Bob Wilson704d1342011-01-13 17:45:11 +00001732 // This is also safe for references using a type that is compatible with
1733 // the type of the alloca, so that loads/stores can be rewritten using
1734 // insertvalue/extractvalue.
Chris Lattner6c95d242011-01-23 07:29:29 +00001735 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
Chris Lattner7e9b4272011-01-16 06:18:28 +00001736 Info.hasSubelementAccess = true;
Bob Wilson704d1342011-01-13 17:45:11 +00001737 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001738 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001739 }
1740 // Check if the offset/size correspond to a component within the alloca type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001741 Type *T = Info.AI->getAllocatedType();
Chris Lattner7e9b4272011-01-16 06:18:28 +00001742 if (TypeHasComponent(T, Offset, MemSize)) {
1743 Info.hasSubelementAccess = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001744 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001745 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001746
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001747 return MarkUnsafe(Info, TheAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +00001748}
1749
1750/// TypeHasComponent - Return true if T has a component type with the
1751/// specified offset and size. If Size is zero, do not check the size.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001752bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) {
1753 Type *EltTy;
Bob Wilsonb742def2009-12-18 20:14:40 +00001754 uint64_t EltSize;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001755 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001756 const StructLayout *Layout = TD->getStructLayout(ST);
1757 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1758 EltTy = ST->getContainedType(EltIdx);
1759 EltSize = TD->getTypeAllocSize(EltTy);
1760 Offset -= Layout->getElementOffset(EltIdx);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001761 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001762 EltTy = AT->getElementType();
1763 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001764 if (Offset >= AT->getNumElements() * EltSize)
1765 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001766 Offset %= EltSize;
1767 } else {
1768 return false;
1769 }
1770 if (Offset == 0 && (Size == 0 || EltSize == Size))
1771 return true;
1772 // Check if the component spans multiple elements.
1773 if (Offset + Size > EltSize)
1774 return false;
1775 return TypeHasComponent(EltTy, Offset, Size);
1776}
1777
1778/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1779/// the instruction I, which references it, to use the separate elements.
1780/// Offset indicates the position within AI that is referenced by this
1781/// instruction.
1782void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1783 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner145c5322011-01-23 08:27:54 +00001784 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1785 Use &TheUse = UI.getUse();
1786 Instruction *User = cast<Instruction>(*UI++);
Bob Wilsonb742def2009-12-18 20:14:40 +00001787
1788 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1789 RewriteBitCast(BC, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001790 continue;
1791 }
1792
1793 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001794 RewriteGEP(GEPI, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001795 continue;
1796 }
1797
1798 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001799 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1800 uint64_t MemSize = Length->getZExtValue();
1801 if (Offset == 0 &&
1802 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1803 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001804 // Otherwise the intrinsic can only touch a single element and the
1805 // address operand will be updated, so nothing else needs to be done.
Chris Lattner145c5322011-01-23 08:27:54 +00001806 continue;
1807 }
Nick Lewycky5a1cb642011-07-25 23:14:22 +00001808
1809 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1810 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1811 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1812 RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
1813 }
1814 continue;
1815 }
Chris Lattner145c5322011-01-23 08:27:54 +00001816
1817 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001818 Type *LIType = LI->getType();
Chris Lattner192228e2011-01-16 05:28:59 +00001819
Bob Wilson704d1342011-01-13 17:45:11 +00001820 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001821 // Replace:
1822 // %res = load { i32, i32 }* %alloc
1823 // with:
1824 // %load.0 = load i32* %alloc.0
1825 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1826 // %load.1 = load i32* %alloc.1
1827 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1828 // (Also works for arrays instead of structs)
1829 Value *Insert = UndefValue::get(LIType);
Devang Patelabb25122011-06-03 19:46:19 +00001830 IRBuilder<> Builder(LI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001831 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patelabb25122011-06-03 19:46:19 +00001832 Value *Load = Builder.CreateLoad(NewElts[i], "load");
1833 Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
Bob Wilsonb742def2009-12-18 20:14:40 +00001834 }
1835 LI->replaceAllUsesWith(Insert);
1836 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001837 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001838 TD->getTypeAllocSize(LIType) ==
1839 TD->getTypeAllocSize(AI->getAllocatedType())) {
1840 // If this is a load of the entire alloca to an integer, rewrite it.
1841 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1842 }
Chris Lattner145c5322011-01-23 08:27:54 +00001843 continue;
1844 }
1845
1846 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001847 Value *Val = SI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001848 Type *SIType = Val->getType();
Bob Wilson704d1342011-01-13 17:45:11 +00001849 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001850 // Replace:
1851 // store { i32, i32 } %val, { i32, i32 }* %alloc
1852 // with:
1853 // %val.0 = extractvalue { i32, i32 } %val, 0
1854 // store i32 %val.0, i32* %alloc.0
1855 // %val.1 = extractvalue { i32, i32 } %val, 1
1856 // store i32 %val.1, i32* %alloc.1
1857 // (Also works for arrays instead of structs)
Devang Patelabb25122011-06-03 19:46:19 +00001858 IRBuilder<> Builder(SI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001859 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patelabb25122011-06-03 19:46:19 +00001860 Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1861 Builder.CreateStore(Extract, NewElts[i]);
Bob Wilsonb742def2009-12-18 20:14:40 +00001862 }
1863 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001864 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001865 TD->getTypeAllocSize(SIType) ==
1866 TD->getTypeAllocSize(AI->getAllocatedType())) {
1867 // If this is a store of the entire alloca from an integer, rewrite it.
1868 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1869 }
Chris Lattner145c5322011-01-23 08:27:54 +00001870 continue;
1871 }
1872
1873 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1874 // If we have a PHI user of the alloca itself (as opposed to a GEP or
1875 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1876 // the new pointer.
1877 if (!isa<AllocaInst>(I)) continue;
1878
1879 assert(Offset == 0 && NewElts[0] &&
1880 "Direct alloca use should have a zero offset");
1881
1882 // If we have a use of the alloca, we know the derived uses will be
1883 // utilizing just the first element of the scalarized result. Insert a
1884 // bitcast of the first alloca before the user as required.
1885 AllocaInst *NewAI = NewElts[0];
1886 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1887 NewAI->moveBefore(BCI);
1888 TheUse = BCI;
1889 continue;
Bob Wilsonb742def2009-12-18 20:14:40 +00001890 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001891 }
1892}
1893
Bob Wilsonb742def2009-12-18 20:14:40 +00001894/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1895/// and recursively continue updating all of its uses.
1896void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1897 SmallVector<AllocaInst*, 32> &NewElts) {
1898 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1899 if (BC->getOperand(0) != AI)
1900 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001901
Bob Wilsonb742def2009-12-18 20:14:40 +00001902 // The bitcast references the original alloca. Replace its uses with
Eli Friedman75f69e32011-11-12 02:07:50 +00001903 // references to the alloca containing offset zero (which is normally at
1904 // index zero, but might not be in cases involving structs with elements
1905 // of size zero).
1906 Type *T = AI->getAllocatedType();
1907 uint64_t EltOffset = 0;
1908 Type *IdxTy;
1909 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1910 Instruction *Val = NewElts[Idx];
Bob Wilsonb742def2009-12-18 20:14:40 +00001911 if (Val->getType() != BC->getDestTy()) {
1912 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1913 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001914 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001915 BC->replaceAllUsesWith(Val);
1916 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001917}
1918
Bob Wilsonb742def2009-12-18 20:14:40 +00001919/// FindElementAndOffset - Return the index of the element containing Offset
1920/// within the specified type, which must be either a struct or an array.
1921/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001922/// element. IdxTy is set to the type of the index result to be used in a
1923/// GEP instruction.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001924uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset,
1925 Type *&IdxTy) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001926 uint64_t Idx = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001927 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001928 const StructLayout *Layout = TD->getStructLayout(ST);
1929 Idx = Layout->getElementContainingOffset(Offset);
1930 T = ST->getContainedType(Idx);
1931 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001932 IdxTy = Type::getInt32Ty(T->getContext());
1933 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001934 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001935 ArrayType *AT = cast<ArrayType>(T);
Bob Wilsone88728d2009-12-19 06:53:17 +00001936 T = AT->getElementType();
1937 uint64_t EltSize = TD->getTypeAllocSize(T);
1938 Idx = Offset / EltSize;
1939 Offset -= Idx * EltSize;
1940 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001941 return Idx;
1942}
1943
1944/// RewriteGEP - Check if this GEP instruction moves the pointer across
1945/// elements of the alloca that are being split apart, and if so, rewrite
1946/// the GEP to be relative to the new element.
1947void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1948 SmallVector<AllocaInst*, 32> &NewElts) {
1949 uint64_t OldOffset = Offset;
1950 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
Jay Foad8fbbb392011-07-19 14:01:37 +00001951 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
Bob Wilsonb742def2009-12-18 20:14:40 +00001952
1953 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1954
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001955 Type *T = AI->getAllocatedType();
1956 Type *IdxTy;
Bob Wilsone88728d2009-12-19 06:53:17 +00001957 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001958 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001959 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001960
1961 T = AI->getAllocatedType();
1962 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001963 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001964
1965 // If this GEP does not move the pointer across elements of the alloca
1966 // being split, then it does not needs to be rewritten.
1967 if (Idx == OldIdx)
1968 return;
1969
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001970 Type *i32Ty = Type::getInt32Ty(AI->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001971 SmallVector<Value*, 8> NewArgs;
1972 NewArgs.push_back(Constant::getNullValue(i32Ty));
1973 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001974 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1975 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00001976 }
1977 Instruction *Val = NewElts[Idx];
1978 if (NewArgs.size() > 1) {
Jay Foada9203102011-07-25 09:48:08 +00001979 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001980 Val->takeName(GEPI);
1981 }
1982 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001983 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001984 GEPI->replaceAllUsesWith(Val);
1985 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001986}
1987
Nick Lewycky5a1cb642011-07-25 23:14:22 +00001988/// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
1989/// to mark the lifetime of the scalarized memory.
1990void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
1991 uint64_t Offset,
1992 SmallVector<AllocaInst*, 32> &NewElts) {
1993 ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
1994 // Put matching lifetime markers on everything from Offset up to
1995 // Offset+OldSize.
1996 Type *AIType = AI->getAllocatedType();
1997 uint64_t NewOffset = Offset;
1998 Type *IdxTy;
1999 uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy);
2000
2001 IRBuilder<> Builder(II);
2002 uint64_t Size = OldSize->getLimitedValue();
2003
2004 if (NewOffset) {
2005 // Splice the first element and index 'NewOffset' bytes in. SROA will
2006 // split the alloca again later.
2007 Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy());
2008 V = Builder.CreateGEP(V, Builder.getInt64(NewOffset));
2009
2010 IdxTy = NewElts[Idx]->getAllocatedType();
2011 uint64_t EltSize = TD->getTypeAllocSize(IdxTy) - NewOffset;
2012 if (EltSize > Size) {
2013 EltSize = Size;
2014 Size = 0;
2015 } else {
2016 Size -= EltSize;
2017 }
2018 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2019 Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
2020 else
2021 Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
2022 ++Idx;
2023 }
2024
2025 for (; Idx != NewElts.size() && Size; ++Idx) {
2026 IdxTy = NewElts[Idx]->getAllocatedType();
2027 uint64_t EltSize = TD->getTypeAllocSize(IdxTy);
2028 if (EltSize > Size) {
2029 EltSize = Size;
2030 Size = 0;
2031 } else {
2032 Size -= EltSize;
2033 }
2034 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2035 Builder.CreateLifetimeStart(NewElts[Idx],
2036 Builder.getInt64(EltSize));
2037 else
2038 Builder.CreateLifetimeEnd(NewElts[Idx],
2039 Builder.getInt64(EltSize));
2040 }
2041 DeadInsts.push_back(II);
2042}
2043
Chris Lattnerd93afec2009-01-07 07:18:45 +00002044/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2045/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00002046void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00002047 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00002048 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002049 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00002050 // appropriate type. The "Other" pointer is the pointer that goes to memory
2051 // that doesn't have anything to do with the alloca that we are promoting. For
2052 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00002053 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00002054 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00002055 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00002056 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00002057 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00002058 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00002059 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00002060 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00002061 }
2062 }
Bob Wilson78c50b82009-12-08 18:22:03 +00002063
Chris Lattnerd93afec2009-01-07 07:18:45 +00002064 // If there is an other pointer, we want to convert it to the same pointer
2065 // type as AI has, so we can GEP through it safely.
2066 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00002067 unsigned AddrSpace =
2068 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00002069
2070 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2071 // optimization, but it's also required to detect the corner case where
2072 // both pointer operands are referencing the same memory, and where
2073 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2074 // function is only called for mem intrinsics that access the whole
2075 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00002076 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson69743022011-01-13 20:59:44 +00002077
Bob Wilsona756b1d2010-01-19 04:32:48 +00002078 // Copying the alloca to itself is a no-op: just delete it.
2079 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2080 // This code will run twice for a no-op memcpy -- once for each operand.
2081 // Put only one reference to MI on the DeadInsts list.
2082 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
2083 E = DeadInsts.end(); I != E; ++I)
2084 if (*I == MI) return;
2085 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002086 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00002087 }
Bob Wilson69743022011-01-13 20:59:44 +00002088
Chris Lattnerd93afec2009-01-07 07:18:45 +00002089 // If the pointer is not the right type, insert a bitcast to the right
2090 // type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002091 Type *NewTy =
Chris Lattner0238f8c2010-07-08 00:27:05 +00002092 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson69743022011-01-13 20:59:44 +00002093
Chris Lattner0238f8c2010-07-08 00:27:05 +00002094 if (OtherPtr->getType() != NewTy)
2095 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002096 }
Bob Wilson69743022011-01-13 20:59:44 +00002097
Chris Lattnerd93afec2009-01-07 07:18:45 +00002098 // Process each element of the aggregate.
Bob Wilsonb742def2009-12-18 20:14:40 +00002099 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson69743022011-01-13 20:59:44 +00002100
Owen Anderson1d0be152009-08-13 21:58:54 +00002101 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00002102
2103 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2104 // If this is a memcpy/memmove, emit a GEP of the other element address.
2105 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002106 unsigned OtherEltAlign = MemAlignment;
Bob Wilson69743022011-01-13 20:59:44 +00002107
Bob Wilsona756b1d2010-01-19 04:32:48 +00002108 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002109 Value *Idx[2] = { Zero,
2110 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Jay Foada9203102011-07-25 09:48:08 +00002111 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00002112 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00002113 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00002114 uint64_t EltOffset;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002115 PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2116 Type *OtherTy = OtherPtrTy->getElementType();
2117 if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002118 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
2119 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002120 Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002121 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002122 }
Bob Wilson69743022011-01-13 20:59:44 +00002123
Chris Lattner1541e0f2009-03-04 19:20:50 +00002124 // The alignment of the other pointer is the guaranteed alignment of the
2125 // element, which is affected by both the known alignment of the whole
2126 // mem intrinsic and the alignment of the element. If the alignment of
2127 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2128 // known alignment is just 4 bytes.
2129 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00002130 }
Bob Wilson69743022011-01-13 20:59:44 +00002131
Chris Lattnerd93afec2009-01-07 07:18:45 +00002132 Value *EltPtr = NewElts[i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002133 Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson69743022011-01-13 20:59:44 +00002134
Chris Lattnerd93afec2009-01-07 07:18:45 +00002135 // If we got down to a scalar, insert a load or store as appropriate.
2136 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00002137 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002138 if (SROADest) {
2139 // From Other to Alloca.
2140 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2141 new StoreInst(Elt, EltPtr, MI);
2142 } else {
2143 // From Alloca to Other.
2144 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2145 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2146 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00002147 continue;
2148 }
2149 assert(isa<MemSetInst>(MI));
Bob Wilson69743022011-01-13 20:59:44 +00002150
Chris Lattnerd93afec2009-01-07 07:18:45 +00002151 // If the stored element is zero (common case), just store a null
2152 // constant.
2153 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00002154 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002155 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00002156 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00002157 } else {
2158 // If EltTy is a vector type, get the element type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002159 Type *ValTy = EltTy->getScalarType();
Dan Gohman44118f02009-06-16 00:20:26 +00002160
Chris Lattnerd93afec2009-01-07 07:18:45 +00002161 // Construct an integer with the right value.
2162 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2163 APInt OneVal(EltSize, CI->getZExtValue());
2164 APInt TotalVal(OneVal);
2165 // Set each byte.
2166 for (unsigned i = 0; 8*i < EltSize; ++i) {
2167 TotalVal = TotalVal.shl(8);
2168 TotalVal |= OneVal;
2169 }
Bob Wilson69743022011-01-13 20:59:44 +00002170
Chris Lattnerd93afec2009-01-07 07:18:45 +00002171 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002172 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00002173 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002174 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002175 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002176 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002177 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson69743022011-01-13 20:59:44 +00002178
Chris Lattnerd93afec2009-01-07 07:18:45 +00002179 // If the requested value was a vector constant, create it.
Cameron Zwarichc055a872011-10-11 21:26:40 +00002180 if (EltTy->isVectorTy()) {
2181 unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
Chris Lattner4ca829e2012-01-25 06:02:56 +00002182 StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002183 }
2184 }
2185 new StoreInst(StoreVal, EltPtr, MI);
2186 continue;
2187 }
2188 // Otherwise, if we're storing a byte variable, use a memset call for
2189 // this element.
2190 }
Bob Wilson69743022011-01-13 20:59:44 +00002191
Duncan Sands777d2302009-05-09 07:06:46 +00002192 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Eli Friedman75f69e32011-11-12 02:07:50 +00002193 if (!EltSize)
2194 continue;
Bob Wilson69743022011-01-13 20:59:44 +00002195
Chris Lattner61db1f52010-12-26 22:57:41 +00002196 IRBuilder<> Builder(MI);
Bob Wilson69743022011-01-13 20:59:44 +00002197
Chris Lattnerd93afec2009-01-07 07:18:45 +00002198 // Finally, insert the meminst for this element.
Chris Lattner61db1f52010-12-26 22:57:41 +00002199 if (isa<MemSetInst>(MI)) {
2200 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2201 MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002202 } else {
Chris Lattner61db1f52010-12-26 22:57:41 +00002203 assert(isa<MemTransferInst>(MI));
2204 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2205 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson69743022011-01-13 20:59:44 +00002206
Chris Lattner61db1f52010-12-26 22:57:41 +00002207 if (isa<MemCpyInst>(MI))
2208 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2209 else
2210 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002211 }
Chris Lattner372dda82007-03-05 07:52:57 +00002212 }
Bob Wilsonb742def2009-12-18 20:14:40 +00002213 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00002214}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002215
Bob Wilson39fdd692009-12-04 21:57:37 +00002216/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002217/// overwrites the entire allocation. Extract out the pieces of the stored
2218/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002219void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002220 SmallVector<AllocaInst*, 32> &NewElts){
2221 // Extract each element out of the integer according to its structure offset
2222 // and store the element value to the individual alloca.
2223 Value *SrcVal = SI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002224 Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002225 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002226
Chris Lattner70728532011-01-16 05:58:24 +00002227 IRBuilder<> Builder(SI);
2228
Eli Friedman41b33f42009-06-01 09:14:32 +00002229 // Handle tail padding by extending the operand
2230 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002231 SrcVal = Builder.CreateZExt(SrcVal,
2232 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002233
David Greene504c7d82010-01-05 01:27:09 +00002234 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00002235 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002236
2237 // There are two forms here: AI could be an array or struct. Both cases
2238 // have different ways to compute the element offset.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002239 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002240 const StructLayout *Layout = TD->getStructLayout(EltSTy);
Bob Wilson69743022011-01-13 20:59:44 +00002241
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002242 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2243 // Get the number of bits to shift SrcVal to get the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002244 Type *FieldTy = EltSTy->getElementType(i);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002245 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson69743022011-01-13 20:59:44 +00002246
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002247 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00002248 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002249
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002250 Value *EltVal = SrcVal;
2251 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002252 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002253 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002254 }
Bob Wilson69743022011-01-13 20:59:44 +00002255
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002256 // Truncate down to an integer of the right size.
2257 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002258
Chris Lattner583dd602009-01-09 18:18:43 +00002259 // Ignore zero sized fields like {}, they obviously contain no data.
2260 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002261
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002262 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002263 EltVal = Builder.CreateTrunc(EltVal,
2264 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002265 Value *DestField = NewElts[i];
2266 if (EltVal->getType() == FieldTy) {
2267 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00002268 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002269 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002270 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002271 } else {
2272 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002273 DestField = Builder.CreateBitCast(DestField,
2274 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002275 }
2276 new StoreInst(EltVal, DestField, SI);
2277 }
Bob Wilson69743022011-01-13 20:59:44 +00002278
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002279 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002280 ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2281 Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002282 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002283 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2284
2285 uint64_t Shift;
Bob Wilson69743022011-01-13 20:59:44 +00002286
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002287 if (TD->isBigEndian())
2288 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002289 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002290 Shift = 0;
Bob Wilson69743022011-01-13 20:59:44 +00002291
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002292 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00002293 // Ignore zero sized fields like {}, they obviously contain no data.
2294 if (ElementSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002295
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002296 Value *EltVal = SrcVal;
2297 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002298 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002299 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002300 }
Bob Wilson69743022011-01-13 20:59:44 +00002301
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002302 // Truncate down to an integer of the right size.
2303 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002304 EltVal = Builder.CreateTrunc(EltVal,
2305 IntegerType::get(SI->getContext(),
2306 ElementSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002307 Value *DestField = NewElts[i];
2308 if (EltVal->getType() == ArrayEltTy) {
2309 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002310 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00002311 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002312 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002313 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002314 } else {
2315 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002316 DestField = Builder.CreateBitCast(DestField,
2317 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002318 }
2319 new StoreInst(EltVal, DestField, SI);
Bob Wilson69743022011-01-13 20:59:44 +00002320
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002321 if (TD->isBigEndian())
2322 Shift -= ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002323 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002324 Shift += ElementOffset;
2325 }
2326 }
Bob Wilson69743022011-01-13 20:59:44 +00002327
Bob Wilsonb742def2009-12-18 20:14:40 +00002328 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002329}
2330
Bob Wilson39fdd692009-12-04 21:57:37 +00002331/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002332/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002333void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002334 SmallVector<AllocaInst*, 32> &NewElts) {
2335 // Extract each element out of the NewElts according to its structure offset
2336 // and form the result value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002337 Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002338 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002339
David Greene504c7d82010-01-05 01:27:09 +00002340 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00002341 << '\n');
Bob Wilson69743022011-01-13 20:59:44 +00002342
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002343 // There are two forms here: AI could be an array or struct. Both cases
2344 // have different ways to compute the element offset.
2345 const StructLayout *Layout = 0;
2346 uint64_t ArrayEltBitOffset = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002347 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002348 Layout = TD->getStructLayout(EltSTy);
2349 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002350 Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002351 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002352 }
2353
2354 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00002355 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson69743022011-01-13 20:59:44 +00002356
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002357 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2358 // Load the value from the alloca. If the NewElt is an aggregate, cast
2359 // the pointer to an integer of the same size before doing the load.
2360 Value *SrcField = NewElts[i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002361 Type *FieldTy =
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002362 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00002363 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002364
Chris Lattner583dd602009-01-09 18:18:43 +00002365 // Ignore zero sized fields like {}, they obviously contain no data.
2366 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002367
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002368 IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +00002369 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00002370 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2371 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00002372 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00002373 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002374 "", LI);
2375 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2376
2377 // If SrcField is a fp or vector of the right size but that isn't an
2378 // integer type, bitcast to an integer so we can shift it.
2379 if (SrcField->getType() != FieldIntTy)
2380 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2381
2382 // Zero extend the field to be the same size as the final alloca so that
2383 // we can shift and insert it.
2384 if (SrcField->getType() != ResultVal->getType())
2385 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson69743022011-01-13 20:59:44 +00002386
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002387 // Determine the number of bits to shift SrcField.
2388 uint64_t Shift;
2389 if (Layout) // Struct case.
2390 Shift = Layout->getElementOffsetInBits(i);
2391 else // Array case.
2392 Shift = i*ArrayEltBitOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002393
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002394 if (TD->isBigEndian())
2395 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson69743022011-01-13 20:59:44 +00002396
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002397 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002398 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002399 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2400 }
2401
Chris Lattner14952472010-06-27 07:58:26 +00002402 // Don't create an 'or x, 0' on the first iteration.
2403 if (!isa<Constant>(ResultVal) ||
2404 !cast<Constant>(ResultVal)->isNullValue())
2405 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2406 else
2407 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002408 }
Eli Friedman41b33f42009-06-01 09:14:32 +00002409
2410 // Handle tail padding by truncating the result
2411 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2412 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2413
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002414 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00002415 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002416}
2417
Duncan Sands3cb36502007-11-04 14:43:57 +00002418/// HasPadding - Return true if the specified type has any structure or
Bob Wilson694a10e2011-01-13 17:45:08 +00002419/// alignment padding in between the elements that would be split apart
2420/// by SROA; return false otherwise.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002421static bool HasPadding(Type *Ty, const TargetData &TD) {
2422 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Bob Wilson694a10e2011-01-13 17:45:08 +00002423 Ty = ATy->getElementType();
2424 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00002425 }
Bob Wilson694a10e2011-01-13 17:45:08 +00002426
2427 // SROA currently handles only Arrays and Structs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002428 StructType *STy = cast<StructType>(Ty);
Bob Wilson694a10e2011-01-13 17:45:08 +00002429 const StructLayout *SL = TD.getStructLayout(STy);
2430 unsigned PrevFieldBitOffset = 0;
2431 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2432 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2433
2434 // Check to see if there is any padding between this element and the
2435 // previous one.
2436 if (i) {
2437 unsigned PrevFieldEnd =
2438 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2439 if (PrevFieldEnd < FieldBitOffset)
2440 return true;
2441 }
2442 PrevFieldBitOffset = FieldBitOffset;
2443 }
2444 // Check for tail padding.
2445 if (unsigned EltCount = STy->getNumElements()) {
2446 unsigned PrevFieldEnd = PrevFieldBitOffset +
2447 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2448 if (PrevFieldEnd < SL->getSizeInBits())
2449 return true;
2450 }
2451 return false;
Chris Lattner39a1c042007-05-30 06:11:23 +00002452}
Chris Lattner372dda82007-03-05 07:52:57 +00002453
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002454/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2455/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2456/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002457bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00002458 // Loop over the use list of the alloca. We can only transform it if all of
2459 // the users are safe to transform.
Chris Lattner6c95d242011-01-23 07:29:29 +00002460 AllocaInfo Info(AI);
Bob Wilson69743022011-01-13 20:59:44 +00002461
Chris Lattner6c95d242011-01-23 07:29:29 +00002462 isSafeForScalarRepl(AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00002463 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00002464 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002465 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002466 }
Bob Wilson69743022011-01-13 20:59:44 +00002467
Chris Lattner39a1c042007-05-30 06:11:23 +00002468 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2469 // source and destination, we have to be careful. In particular, the memcpy
2470 // could be moving around elements that live in structure padding of the LLVM
2471 // types, but may actually be used. In these cases, we refuse to promote the
2472 // struct.
2473 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00002474 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002475 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00002476
Chris Lattner396a0562011-01-16 17:46:19 +00002477 // If the alloca never has an access to just *part* of it, but is accessed
2478 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner7e9b4272011-01-16 06:18:28 +00002479 // the alloca instead of promoting each piece at a time and inserting fission
2480 // and fusion code.
2481 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2482 // If the struct/array just has one element, use basic SRoA.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002483 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
Chris Lattner7e9b4272011-01-16 06:18:28 +00002484 if (ST->getNumElements() > 1) return false;
2485 } else {
2486 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2487 return false;
2488 }
2489 }
Chris Lattner145c5322011-01-23 08:27:54 +00002490
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002491 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00002492}
Chris Lattnera1888942005-12-12 07:19:13 +00002493
Chris Lattner800de312008-02-29 07:03:13 +00002494
Chris Lattner79b3bd32007-04-25 06:40:51 +00002495
2496/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2497/// some part of a constant global variable. This intentionally only accepts
2498/// constant expressions because we don't can't rewrite arbitrary instructions.
2499static bool PointsToConstantGlobal(Value *V) {
2500 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2501 return GV->isConstant();
2502 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Bob Wilson69743022011-01-13 20:59:44 +00002503 if (CE->getOpcode() == Instruction::BitCast ||
Chris Lattner79b3bd32007-04-25 06:40:51 +00002504 CE->getOpcode() == Instruction::GetElementPtr)
2505 return PointsToConstantGlobal(CE->getOperand(0));
2506 return false;
2507}
2508
2509/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2510/// pointer to an alloca. Ignore any reads of the pointer, return false if we
2511/// see any stores or other unknown uses. If we see pointer arithmetic, keep
2512/// track of whether it moves the pointer (with isOffset) but otherwise traverse
2513/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
Nick Lewycky081f8002010-11-24 22:04:20 +00002514/// the alloca, and if the source pointer is a pointer to a constant global, we
Chris Lattner79b3bd32007-04-25 06:40:51 +00002515/// can optimize this.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002516static bool
2517isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
2518 bool isOffset,
2519 SmallVector<Instruction *, 4> &LifetimeMarkers) {
2520 // We track lifetime intrinsics as we encounter them. If we decide to go
2521 // ahead and replace the value with the global, this lets the caller quickly
2522 // eliminate the markers.
2523
Chris Lattner79b3bd32007-04-25 06:40:51 +00002524 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00002525 User *U = cast<Instruction>(*UI);
2526
Chris Lattner2e618492010-11-18 06:20:47 +00002527 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00002528 // Ignore non-volatile loads, they are always ok.
Eli Friedman2bc3d522011-09-12 20:23:13 +00002529 if (!LI->isSimple()) return false;
Chris Lattner2e618492010-11-18 06:20:47 +00002530 continue;
2531 }
Bob Wilson69743022011-01-13 20:59:44 +00002532
Gabor Greif8a8a4352010-04-06 19:32:30 +00002533 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002534 // If uses of the bitcast are ok, we are ok.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002535 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset,
2536 LifetimeMarkers))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002537 return false;
2538 continue;
2539 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00002540 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002541 // If the GEP has all zero indices, it doesn't offset the pointer. If it
2542 // doesn't, it does.
2543 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002544 isOffset || !GEP->hasAllZeroIndices(),
2545 LifetimeMarkers))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002546 return false;
2547 continue;
2548 }
Bob Wilson69743022011-01-13 20:59:44 +00002549
Chris Lattner62480652010-11-18 06:41:51 +00002550 if (CallSite CS = U) {
Nick Lewycky081f8002010-11-24 22:04:20 +00002551 // If this is the function being called then we treat it like a load and
2552 // ignore it.
2553 if (CS.isCallee(UI))
2554 continue;
Bob Wilson69743022011-01-13 20:59:44 +00002555
Duncan Sands53892102011-05-06 10:30:37 +00002556 // If this is a readonly/readnone call site, then we know it is just a
2557 // load (but one that potentially returns the value itself), so we can
2558 // ignore it if we know that the value isn't captured.
2559 unsigned ArgNo = CS.getArgumentNo(UI);
2560 if (CS.onlyReadsMemory() &&
Nick Lewycky173862e2011-11-20 19:09:04 +00002561 (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
Duncan Sands53892102011-05-06 10:30:37 +00002562 continue;
2563
Chris Lattner62480652010-11-18 06:41:51 +00002564 // If this is being passed as a byval argument, the caller is making a
2565 // copy, so it is only a read of the alloca.
Nick Lewycky173862e2011-11-20 19:09:04 +00002566 if (CS.isByValArgument(ArgNo))
Chris Lattner62480652010-11-18 06:41:51 +00002567 continue;
2568 }
Bob Wilson69743022011-01-13 20:59:44 +00002569
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002570 // Lifetime intrinsics can be handled by the caller.
2571 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
2572 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2573 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2574 assert(II->use_empty() && "Lifetime markers have no result to use!");
2575 LifetimeMarkers.push_back(II);
2576 continue;
2577 }
2578 }
2579
Chris Lattner79b3bd32007-04-25 06:40:51 +00002580 // If this is isn't our memcpy/memmove, reject it as something we can't
2581 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00002582 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2583 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00002584 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002585
Chris Lattner2e618492010-11-18 06:20:47 +00002586 // If the transfer is using the alloca as a source of the transfer, then
Chris Lattner2e29ebd2010-11-18 07:32:33 +00002587 // ignore it since it is a load (unless the transfer is volatile).
Chris Lattner2e618492010-11-18 06:20:47 +00002588 if (UI.getOperandNo() == 1) {
2589 if (MI->isVolatile()) return false;
2590 continue;
2591 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00002592
2593 // If we already have seen a copy, reject the second one.
2594 if (TheCopy) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002595
Chris Lattner79b3bd32007-04-25 06:40:51 +00002596 // If the pointer has been offset from the start of the alloca, we can't
2597 // safely handle this.
2598 if (isOffset) return false;
2599
2600 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00002601 if (UI.getOperandNo() != 0) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002602
Chris Lattner79b3bd32007-04-25 06:40:51 +00002603 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00002604 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002605 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002606
Chris Lattner79b3bd32007-04-25 06:40:51 +00002607 // Otherwise, the transform is safe. Remember the copy instruction.
2608 TheCopy = MI;
2609 }
2610 return true;
2611}
2612
2613/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2614/// modified by a copy from a constant global. If we can prove this, we can
2615/// replace any uses of the alloca with uses of the global directly.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002616MemTransferInst *
2617SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
2618 SmallVector<Instruction*, 4> &ToDelete) {
Chris Lattner31d80102010-04-15 21:59:20 +00002619 MemTransferInst *TheCopy = 0;
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002620 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false, ToDelete))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002621 return TheCopy;
2622 return 0;
2623}