blob: 46ac9482006142926909cec1b9dfcb70f374caed [file] [log] [blame]
Chris Lattnered7b41e2003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnered7b41e2003-05-27 15:45:27 +00009//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation. This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
Chris Lattner38aec322003-09-11 16:45:55 +000013// each member (if possible). Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17// often interact, especially for C++ programs. As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
Chris Lattnered7b41e2003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
Chris Lattner0e5f4992006-12-19 21:40:18 +000022#define DEBUG_TYPE "scalarrepl"
Chris Lattnered7b41e2003-05-27 15:45:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattner38aec322003-09-11 16:45:55 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnered7b41e2003-05-27 15:45:27 +000026#include "llvm/Function.h"
Chris Lattner79b3bd32007-04-25 06:40:51 +000027#include "llvm/GlobalVariable.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000028#include "llvm/Instructions.h"
Chris Lattner372dda82007-03-05 07:52:57 +000029#include "llvm/IntrinsicInst.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Chris Lattner72eaa0e2010-09-01 23:09:27 +000031#include "llvm/Module.h"
Chris Lattner372dda82007-03-05 07:52:57 +000032#include "llvm/Pass.h"
Cameron Zwarichc8279392011-05-24 03:10:43 +000033#include "llvm/Analysis/DIBuilder.h"
Cameron Zwarichb1686c32011-01-18 03:53:26 +000034#include "llvm/Analysis/Dominators.h"
Chris Lattnerc87c50a2011-01-23 22:04:55 +000035#include "llvm/Analysis/Loads.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000036#include "llvm/Analysis/ValueTracking.h"
Chris Lattner38aec322003-09-11 16:45:55 +000037#include "llvm/Target/TargetData.h"
38#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000039#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere0a1a5b2011-01-14 07:50:47 +000040#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattnera9be1df2010-11-18 06:26:49 +000041#include "llvm/Support/CallSite.h"
Chris Lattner95255282006-06-28 23:17:24 +000042#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000043#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000044#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000045#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000046#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000047#include "llvm/Support/raw_ostream.h"
Chris Lattnerc87c50a2011-01-23 22:04:55 +000048#include "llvm/ADT/SetVector.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000049#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000050#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000051using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000052
Chris Lattner0e5f4992006-12-19 21:40:18 +000053STATISTIC(NumReplaced, "Number of allocas broken up");
54STATISTIC(NumPromoted, "Number of allocas promoted");
Chris Lattnerc87c50a2011-01-23 22:04:55 +000055STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
Chris Lattner0e5f4992006-12-19 21:40:18 +000056STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000057STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000058
Chris Lattner0e5f4992006-12-19 21:40:18 +000059namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000060 struct SROA : public FunctionPass {
Cameron Zwarichb1686c32011-01-18 03:53:26 +000061 SROA(int T, bool hasDT, char &ID)
62 : FunctionPass(ID), HasDomTree(hasDT) {
Devang Patelff366852007-07-09 21:19:23 +000063 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000064 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000065 else
66 SRThreshold = T;
67 }
Devang Patel794fd752007-05-01 21:15:47 +000068
Chris Lattnered7b41e2003-05-27 15:45:27 +000069 bool runOnFunction(Function &F);
70
Chris Lattner38aec322003-09-11 16:45:55 +000071 bool performScalarRepl(Function &F);
72 bool performPromotion(Function &F);
73
Chris Lattnered7b41e2003-05-27 15:45:27 +000074 private:
Cameron Zwarichb1686c32011-01-18 03:53:26 +000075 bool HasDomTree;
Chris Lattner56c38522009-01-07 06:34:28 +000076 TargetData *TD;
Bob Wilson69743022011-01-13 20:59:44 +000077
Bob Wilsonb742def2009-12-18 20:14:40 +000078 /// DeadInsts - Keep track of instructions we have made dead, so that
79 /// we can remove them after we are done working.
80 SmallVector<Value*, 32> DeadInsts;
81
Chris Lattner39a1c042007-05-30 06:11:23 +000082 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
83 /// information about the uses. All these fields are initialized to false
84 /// and set to true when something is learned.
85 struct AllocaInfo {
Chris Lattner6c95d242011-01-23 07:29:29 +000086 /// The alloca to promote.
87 AllocaInst *AI;
88
Chris Lattner145c5322011-01-23 08:27:54 +000089 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
90 /// looping and avoid redundant work.
91 SmallPtrSet<PHINode*, 8> CheckedPHIs;
92
Chris Lattner39a1c042007-05-30 06:11:23 +000093 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
94 bool isUnsafe : 1;
Bob Wilson69743022011-01-13 20:59:44 +000095
Chris Lattner39a1c042007-05-30 06:11:23 +000096 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
97 bool isMemCpySrc : 1;
98
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000099 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +0000100 bool isMemCpyDst : 1;
101
Chris Lattner7e9b4272011-01-16 06:18:28 +0000102 /// hasSubelementAccess - This is true if a subelement of the alloca is
103 /// ever accessed, or false if the alloca is only accessed with mem
104 /// intrinsics or load/store that only access the entire alloca at once.
105 bool hasSubelementAccess : 1;
106
107 /// hasALoadOrStore - This is true if there are any loads or stores to it.
108 /// The alloca may just be accessed with memcpy, for example, which would
109 /// not set this.
110 bool hasALoadOrStore : 1;
111
Chris Lattner6c95d242011-01-23 07:29:29 +0000112 explicit AllocaInfo(AllocaInst *ai)
113 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
Chris Lattner7e9b4272011-01-16 06:18:28 +0000114 hasSubelementAccess(false), hasALoadOrStore(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +0000115 };
Bob Wilson69743022011-01-13 20:59:44 +0000116
Devang Patelff366852007-07-09 21:19:23 +0000117 unsigned SRThreshold;
118
Chris Lattnerd01a0da2011-01-23 07:05:44 +0000119 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
120 I.isUnsafe = true;
121 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
122 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000123
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000124 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000125
Chris Lattner6c95d242011-01-23 07:29:29 +0000126 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
Chris Lattner145c5322011-01-23 08:27:54 +0000127 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
128 AllocaInfo &Info);
Chris Lattner6c95d242011-01-23 07:29:29 +0000129 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
130 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattnerd01a0da2011-01-23 07:05:44 +0000131 const Type *MemOpType, bool isStore, AllocaInfo &Info,
Chris Lattner145c5322011-01-23 08:27:54 +0000132 Instruction *TheAccess, bool AllowWholeAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +0000133 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000134 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
135 const Type *&IdxTy);
Bob Wilson69743022011-01-13 20:59:44 +0000136
137 void DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000138 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000139 void DeleteDeadInstructions();
Bob Wilson69743022011-01-13 20:59:44 +0000140
Bob Wilsonb742def2009-12-18 20:14:40 +0000141 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
142 SmallVector<AllocaInst*, 32> &NewElts);
143 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
144 SmallVector<AllocaInst*, 32> &NewElts);
145 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
146 SmallVector<AllocaInst*, 32> &NewElts);
147 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000148 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000149 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000150 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000151 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000152 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000153 SmallVector<AllocaInst*, 32> &NewElts);
Bob Wilson69743022011-01-13 20:59:44 +0000154
Chris Lattner31d80102010-04-15 21:59:20 +0000155 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000156 };
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000157
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000158 // SROA_DT - SROA that uses DominatorTree.
159 struct SROA_DT : public SROA {
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000160 static char ID;
161 public:
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000162 SROA_DT(int T = -1) : SROA(T, true, ID) {
163 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000164 }
165
166 // getAnalysisUsage - This pass does not require any passes, but we know it
167 // will not alter the CFG, so say so.
168 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
169 AU.addRequired<DominatorTree>();
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000170 AU.setPreservesCFG();
171 }
172 };
173
174 // SROA_SSAUp - SROA that uses SSAUpdater.
175 struct SROA_SSAUp : public SROA {
176 static char ID;
177 public:
178 SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
179 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
180 }
181
182 // getAnalysisUsage - This pass does not require any passes, but we know it
183 // will not alter the CFG, so say so.
184 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
185 AU.setPreservesCFG();
186 }
187 };
188
Chris Lattnered7b41e2003-05-27 15:45:27 +0000189}
190
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000191char SROA_DT::ID = 0;
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000192char SROA_SSAUp::ID = 0;
193
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000194INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
195 "Scalar Replacement of Aggregates (DT)", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000196INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000197INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
198 "Scalar Replacement of Aggregates (DT)", false, false)
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000199
200INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
201 "Scalar Replacement of Aggregates (SSAUp)", false, false)
202INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
203 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000204
Brian Gaeked0fde302003-11-11 22:41:34 +0000205// Public interface to the ScalarReplAggregates pass
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000206FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000207 bool UseDomTree) {
208 if (UseDomTree)
209 return new SROA_DT(Threshold);
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000210 return new SROA_SSAUp(Threshold);
Devang Patelff366852007-07-09 21:19:23 +0000211}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000212
213
Chris Lattner4cc576b2010-04-16 00:24:57 +0000214//===----------------------------------------------------------------------===//
215// Convert To Scalar Optimization.
216//===----------------------------------------------------------------------===//
217
218namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000219/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
220/// optimization, which scans the uses of an alloca and determines if it can
221/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000222class ConvertToScalarInfo {
Cameron Zwarichd4c9c3e2011-03-16 00:13:35 +0000223 /// AllocaSize - The size of the alloca being considered in bytes.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000224 unsigned AllocaSize;
225 const TargetData &TD;
Bob Wilson69743022011-01-13 20:59:44 +0000226
Chris Lattnera0bada72010-04-16 02:32:17 +0000227 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000228 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000229 bool IsNotTrivial;
Bob Wilson69743022011-01-13 20:59:44 +0000230
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000231 /// ScalarKind - Tracks the kind of alloca being considered for promotion,
232 /// computed based on the uses of the alloca rather than the LLVM type system.
233 enum {
234 Unknown,
Cameron Zwarich51797822011-06-13 21:44:40 +0000235
Cameron Zwarich15cd80c2011-06-13 23:39:23 +0000236 // Accesses via GEPs that are consistent with element access of a vector
Cameron Zwarich51797822011-06-13 21:44:40 +0000237 // type. This will not be converted into a vector unless there is a later
238 // access using an actual vector type.
239 ImplicitVector,
240
Cameron Zwarich15cd80c2011-06-13 23:39:23 +0000241 // Accesses via vector operations and GEPs that are consistent with the
242 // layout of a vector type.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000243 Vector,
Cameron Zwarich51797822011-06-13 21:44:40 +0000244
245 // An integer bag-of-bits with bitwise operations for insertion and
246 // extraction. Any combination of types can be converted into this kind
247 // of scalar.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000248 Integer
249 } ScalarKind;
250
Chris Lattnera001b662010-04-16 00:38:19 +0000251 /// VectorTy - This tracks the type that we should promote the vector to if
252 /// it is possible to turn it into a vector. This starts out null, and if it
253 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000254 const VectorType *VectorTy;
Bob Wilson69743022011-01-13 20:59:44 +0000255
Cameron Zwarich1bcdb6f2011-03-16 08:13:42 +0000256 /// HadNonMemTransferAccess - True if there is at least one access to the
257 /// alloca that is not a MemTransferInst. We don't want to turn structs into
258 /// large integers unless there is some potential for optimization.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000259 bool HadNonMemTransferAccess;
260
Chris Lattner4cc576b2010-04-16 00:24:57 +0000261public:
262 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000263 : AllocaSize(Size), TD(td), IsNotTrivial(false), ScalarKind(Unknown),
Cameron Zwarich51797822011-06-13 21:44:40 +0000264 VectorTy(0), HadNonMemTransferAccess(false) { }
Bob Wilson69743022011-01-13 20:59:44 +0000265
Chris Lattnera001b662010-04-16 00:38:19 +0000266 AllocaInst *TryConvert(AllocaInst *AI);
Bob Wilson69743022011-01-13 20:59:44 +0000267
Chris Lattner4cc576b2010-04-16 00:24:57 +0000268private:
269 bool CanConvertToScalar(Value *V, uint64_t Offset);
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000270 void MergeInTypeForLoadOrStore(const Type *In, uint64_t Offset);
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000271 bool MergeInVectorType(const VectorType *VInTy, uint64_t Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000272 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Bob Wilson69743022011-01-13 20:59:44 +0000273
Chris Lattner4cc576b2010-04-16 00:24:57 +0000274 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
275 uint64_t Offset, IRBuilder<> &Builder);
276 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
277 uint64_t Offset, IRBuilder<> &Builder);
278};
279} // end anonymous namespace.
280
Chris Lattner91abace2010-09-01 05:14:33 +0000281
Chris Lattnera001b662010-04-16 00:38:19 +0000282/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
283/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
284/// alloca if possible or null if not.
285AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
286 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
287 // out.
288 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
289 return 0;
Bob Wilson69743022011-01-13 20:59:44 +0000290
Cameron Zwarich51797822011-06-13 21:44:40 +0000291 // If an alloca has only memset / memcpy uses, it may still have an Unknown
292 // ScalarKind. Treat it as an Integer below.
293 if (ScalarKind == Unknown)
294 ScalarKind = Integer;
295
Cameron Zwarich3ebb05d2011-06-18 06:17:51 +0000296 // FIXME: It should be possible to promote the vector type up to the alloca's
297 // size.
298 if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
299 ScalarKind = Integer;
300
Chris Lattnera001b662010-04-16 00:38:19 +0000301 // If we were able to find a vector type that can handle this with
302 // insert/extract elements, and if there was at least one use that had
303 // a vector type, promote this to a vector. We don't want to promote
304 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
305 // we just get a lot of insert/extracts. If at least one vector is
306 // involved, then we probably really do have a union of vector/array.
307 const Type *NewTy;
Cameron Zwarich5b93d3c2011-06-14 06:33:51 +0000308 if (ScalarKind == Vector) {
309 assert(VectorTy && "Missing type for vector scalar.");
Chris Lattnera001b662010-04-16 00:38:19 +0000310 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
311 << *VectorTy << '\n');
312 NewTy = VectorTy; // Use the vector type.
313 } else {
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000314 unsigned BitWidth = AllocaSize * 8;
Cameron Zwarich51797822011-06-13 21:44:40 +0000315 if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
316 !HadNonMemTransferAccess && !TD.fitsInLegalInteger(BitWidth))
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000317 return 0;
318
Chris Lattnera001b662010-04-16 00:38:19 +0000319 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
320 // Create and insert the integer alloca.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000321 NewTy = IntegerType::get(AI->getContext(), BitWidth);
Chris Lattnera001b662010-04-16 00:38:19 +0000322 }
323 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
324 ConvertUsesToScalar(AI, NewAI, 0);
325 return NewAI;
326}
327
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000328/// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
329/// (VectorTy) so far at the offset specified by Offset (which is specified in
330/// bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000331///
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000332/// There are three cases we handle here:
Chris Lattner4cc576b2010-04-16 00:24:57 +0000333/// 1) A union of vector types of the same size and potentially its elements.
334/// Here we turn element accesses into insert/extract element operations.
335/// This promotes a <4 x float> with a store of float to the third element
336/// into a <4 x float> that uses insert element.
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000337/// 2) A union of vector types with power-of-2 size differences, e.g. a float,
338/// <2 x float> and <4 x float>. Here we turn element accesses into insert
339/// and extract element operations, and <2 x float> accesses into a cast to
340/// <2 x double>, an extract, and a cast back to <2 x float>.
341/// 3) 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.
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000345void ConvertToScalarInfo::MergeInTypeForLoadOrStore(const Type *In,
346 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.
356 if (const 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 Zwarichc4f78202011-06-09 01:52:44 +0000372 (!VectorTy || Offset * 8 < VectorTy->getPrimitiveSizeInBits())) {
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000373 if (!VectorTy) {
Cameron Zwarich51797822011-06-13 21:44:40 +0000374 ScalarKind = ImplicitVector;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000375 VectorTy = VectorType::get(In, AllocaSize/EltSize);
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000376 return;
377 }
378
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000379 unsigned CurrentEltSize = VectorTy->getElementType()
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000380 ->getPrimitiveSizeInBits()/8;
381 if (EltSize == CurrentEltSize)
382 return;
Cameron Zwarich344731c2011-04-20 21:48:38 +0000383
384 if (In->isIntegerTy() && isPowerOf2_32(AllocaSize / EltSize))
385 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000386 }
387 }
Bob Wilson69743022011-01-13 20:59:44 +0000388
Chris Lattner4cc576b2010-04-16 00:24:57 +0000389 // Otherwise, we have a case that we can't handle with an optimized vector
390 // form. We can still turn this into a large integer.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000391 ScalarKind = Integer;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000392}
393
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000394/// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
395/// returning true if the type was successfully merged and false otherwise.
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000396bool ConvertToScalarInfo::MergeInVectorType(const VectorType *VInTy,
397 uint64_t Offset) {
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000398 // TODO: Support nonzero offsets?
399 if (Offset != 0)
400 return false;
401
402 // Only allow vectors that are a power-of-2 away from the size of the alloca.
403 if (!isPowerOf2_64(AllocaSize / (VInTy->getBitWidth() / 8)))
404 return false;
405
406 // If this the first vector we see, remember the type so that we know the
407 // element size.
408 if (!VectorTy) {
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000409 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000410 VectorTy = VInTy;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000411 return true;
412 }
413
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000414 unsigned BitWidth = VectorTy->getBitWidth();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000415 unsigned InBitWidth = VInTy->getBitWidth();
416
417 // Vectors of the same size can be converted using a simple bitcast.
Cameron Zwarich51797822011-06-13 21:44:40 +0000418 if (InBitWidth == BitWidth && AllocaSize == (InBitWidth / 8)) {
419 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000420 return true;
Cameron Zwarich51797822011-06-13 21:44:40 +0000421 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000422
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000423 const Type *ElementTy = VectorTy->getElementType();
424 const Type *InElementTy = VInTy->getElementType();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000425
426 // Do not allow mixed integer and floating-point accesses from vectors of
427 // different sizes.
428 if (ElementTy->isFloatingPointTy() != InElementTy->isFloatingPointTy())
429 return false;
430
431 if (ElementTy->isFloatingPointTy()) {
432 // Only allow floating-point vectors of different sizes if they have the
433 // same element type.
434 // TODO: This could be loosened a bit, but would anything benefit?
435 if (ElementTy != InElementTy)
436 return false;
437
438 // There are no arbitrary-precision floating-point types, which limits the
439 // number of legal vector types with larger element types that we can form
440 // to bitcast and extract a subvector.
441 // TODO: We could support some more cases with mixed fp128 and double here.
442 if (!(BitWidth == 64 || BitWidth == 128) ||
443 !(InBitWidth == 64 || InBitWidth == 128))
444 return false;
445 } else {
446 assert(ElementTy->isIntegerTy() && "Vector elements must be either integer "
447 "or floating-point.");
448 unsigned BitWidth = ElementTy->getPrimitiveSizeInBits();
449 unsigned InBitWidth = InElementTy->getPrimitiveSizeInBits();
450
451 // Do not allow integer types smaller than a byte or types whose widths are
452 // not a multiple of a byte.
453 if (BitWidth < 8 || InBitWidth < 8 ||
454 BitWidth % 8 != 0 || InBitWidth % 8 != 0)
455 return false;
456 }
457
458 // Pick the largest of the two vector types.
Cameron Zwarich51797822011-06-13 21:44:40 +0000459 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000460 if (InBitWidth > BitWidth)
461 VectorTy = VInTy;
462
463 return true;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000464}
465
Chris Lattner4cc576b2010-04-16 00:24:57 +0000466/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
467/// its accesses to a single vector type, return true and set VecTy to
468/// the new type. If we could convert the alloca into a single promotable
469/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
470/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
471/// is the current offset from the base of the alloca being analyzed.
472///
473/// If we see at least one access to the value that is as a vector type, set the
474/// SawVec flag.
475bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
476 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
477 Instruction *User = cast<Instruction>(*UI);
Bob Wilson69743022011-01-13 20:59:44 +0000478
Chris Lattner4cc576b2010-04-16 00:24:57 +0000479 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
480 // Don't break volatile loads.
481 if (LI->isVolatile())
482 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000483 // Don't touch MMX operations.
484 if (LI->getType()->isX86_MMXTy())
485 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000486 HadNonMemTransferAccess = true;
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000487 MergeInTypeForLoadOrStore(LI->getType(), Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000488 continue;
489 }
Bob Wilson69743022011-01-13 20:59:44 +0000490
Chris Lattner4cc576b2010-04-16 00:24:57 +0000491 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
492 // Storing the pointer, not into the value?
493 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000494 // Don't touch MMX operations.
495 if (SI->getOperand(0)->getType()->isX86_MMXTy())
496 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000497 HadNonMemTransferAccess = true;
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000498 MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000499 continue;
500 }
Bob Wilson69743022011-01-13 20:59:44 +0000501
Chris Lattner4cc576b2010-04-16 00:24:57 +0000502 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000503 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000504 if (!CanConvertToScalar(BCI, Offset))
505 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000506 continue;
507 }
508
509 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
510 // If this is a GEP with a variable indices, we can't handle it.
511 if (!GEP->hasAllConstantIndices())
512 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000513
Chris Lattner4cc576b2010-04-16 00:24:57 +0000514 // Compute the offset that this GEP adds to the pointer.
515 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
516 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
517 &Indices[0], Indices.size());
518 // See if all uses can be converted.
519 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
520 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000521 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000522 HadNonMemTransferAccess = true;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000523 continue;
524 }
525
526 // If this is a constant sized memset of a constant value (e.g. 0) we can
527 // handle it.
528 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
Cameron Zwarich6be41eb2011-06-18 05:47:49 +0000529 // Store of constant value.
530 if (!isa<ConstantInt>(MSI->getValue()))
Chris Lattnera001b662010-04-16 00:38:19 +0000531 return false;
Cameron Zwarich6be41eb2011-06-18 05:47:49 +0000532
533 // Store of constant size.
534 ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
535 if (!Len)
536 return false;
537
538 // If the size differs from the alloca, we can only convert the alloca to
539 // an integer bag-of-bits.
540 // FIXME: This should handle all of the cases that are currently accepted
541 // as vector element insertions.
542 if (Len->getZExtValue() != AllocaSize || Offset != 0)
543 ScalarKind = Integer;
544
Chris Lattnera001b662010-04-16 00:38:19 +0000545 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000546 HadNonMemTransferAccess = true;
Chris Lattnera001b662010-04-16 00:38:19 +0000547 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000548 }
549
550 // If this is a memcpy or memmove into or out of the whole allocation, we
551 // can handle it like a load or store of the scalar type.
552 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000553 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
554 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
555 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000556
Chris Lattnera001b662010-04-16 00:38:19 +0000557 IsNotTrivial = true; // Can't be mem2reg'd.
558 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000559 }
Bob Wilson69743022011-01-13 20:59:44 +0000560
Chris Lattner4cc576b2010-04-16 00:24:57 +0000561 // Otherwise, we cannot handle this!
562 return false;
563 }
Bob Wilson69743022011-01-13 20:59:44 +0000564
Chris Lattner4cc576b2010-04-16 00:24:57 +0000565 return true;
566}
567
568/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
569/// directly. This happens when we are converting an "integer union" to a
570/// single integer scalar, or when we are converting a "vector union" to a
571/// vector with insert/extractelement instructions.
572///
573/// Offset is an offset from the original alloca, in bits that need to be
574/// shifted to the right. By the end of this, there should be no uses of Ptr.
575void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
576 uint64_t Offset) {
577 while (!Ptr->use_empty()) {
578 Instruction *User = cast<Instruction>(Ptr->use_back());
579
580 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
581 ConvertUsesToScalar(CI, NewAI, Offset);
582 CI->eraseFromParent();
583 continue;
584 }
585
586 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
587 // Compute the offset that this GEP adds to the pointer.
588 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
589 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
590 &Indices[0], Indices.size());
591 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
592 GEP->eraseFromParent();
593 continue;
594 }
Bob Wilson69743022011-01-13 20:59:44 +0000595
Chris Lattner61db1f52010-12-26 22:57:41 +0000596 IRBuilder<> Builder(User);
Bob Wilson69743022011-01-13 20:59:44 +0000597
Chris Lattner4cc576b2010-04-16 00:24:57 +0000598 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
599 // The load is a bit extract from NewAI shifted right by Offset bits.
600 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
601 Value *NewLoadVal
602 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
603 LI->replaceAllUsesWith(NewLoadVal);
604 LI->eraseFromParent();
605 continue;
606 }
Bob Wilson69743022011-01-13 20:59:44 +0000607
Chris Lattner4cc576b2010-04-16 00:24:57 +0000608 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
609 assert(SI->getOperand(0) != Ptr && "Consistency error!");
610 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
611 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
612 Builder);
613 Builder.CreateStore(New, NewAI);
614 SI->eraseFromParent();
Bob Wilson69743022011-01-13 20:59:44 +0000615
Chris Lattner4cc576b2010-04-16 00:24:57 +0000616 // If the load we just inserted is now dead, then the inserted store
617 // overwrote the entire thing.
618 if (Old->use_empty())
619 Old->eraseFromParent();
620 continue;
621 }
Bob Wilson69743022011-01-13 20:59:44 +0000622
Chris Lattner4cc576b2010-04-16 00:24:57 +0000623 // If this is a constant sized memset of a constant value (e.g. 0) we can
624 // transform it into a store of the expanded constant value.
625 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
626 assert(MSI->getRawDest() == Ptr && "Consistency error!");
627 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
628 if (NumBytes != 0) {
629 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson69743022011-01-13 20:59:44 +0000630
Chris Lattner4cc576b2010-04-16 00:24:57 +0000631 // Compute the value replicated the right number of times.
632 APInt APVal(NumBytes*8, Val);
633
634 // Splat the value if non-zero.
635 if (Val)
636 for (unsigned i = 1; i != NumBytes; ++i)
637 APVal |= APVal << 8;
Bob Wilson69743022011-01-13 20:59:44 +0000638
Chris Lattner4cc576b2010-04-16 00:24:57 +0000639 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
640 Value *New = ConvertScalar_InsertValue(
641 ConstantInt::get(User->getContext(), APVal),
642 Old, Offset, Builder);
643 Builder.CreateStore(New, NewAI);
Bob Wilson69743022011-01-13 20:59:44 +0000644
Chris Lattner4cc576b2010-04-16 00:24:57 +0000645 // If the load we just inserted is now dead, then the memset overwrote
646 // the entire thing.
647 if (Old->use_empty())
Bob Wilson69743022011-01-13 20:59:44 +0000648 Old->eraseFromParent();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000649 }
650 MSI->eraseFromParent();
651 continue;
652 }
653
654 // If this is a memcpy or memmove into or out of the whole allocation, we
655 // can handle it like a load or store of the scalar type.
656 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
657 assert(Offset == 0 && "must be store to start of alloca");
Bob Wilson69743022011-01-13 20:59:44 +0000658
Chris Lattner4cc576b2010-04-16 00:24:57 +0000659 // If the source and destination are both to the same alloca, then this is
660 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
661 // as appropriate.
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000662 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
Bob Wilson69743022011-01-13 20:59:44 +0000663
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000664 if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000665 // Dest must be OrigAI, change this to be a load from the original
666 // pointer (bitcasted), then a store to our new alloca.
667 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
668 Value *SrcPtr = MTI->getSource();
Mon P Wange90a6332010-12-23 01:41:32 +0000669 const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
670 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
671 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
672 AIPTy = PointerType::get(AIPTy->getElementType(),
673 SPTy->getAddressSpace());
674 }
675 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
676
Chris Lattner4cc576b2010-04-16 00:24:57 +0000677 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
678 SrcVal->setAlignment(MTI->getAlignment());
679 Builder.CreateStore(SrcVal, NewAI);
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000680 } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000681 // Src must be OrigAI, change this to be a load from NewAI then a store
682 // through the original dest pointer (bitcasted).
683 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
684 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
685
Mon P Wange90a6332010-12-23 01:41:32 +0000686 const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
687 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
688 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
689 AIPTy = PointerType::get(AIPTy->getElementType(),
690 DPTy->getAddressSpace());
691 }
692 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
693
Chris Lattner4cc576b2010-04-16 00:24:57 +0000694 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
695 NewStore->setAlignment(MTI->getAlignment());
696 } else {
697 // Noop transfer. Src == Dst
698 }
699
700 MTI->eraseFromParent();
701 continue;
702 }
Bob Wilson69743022011-01-13 20:59:44 +0000703
Chris Lattner4cc576b2010-04-16 00:24:57 +0000704 llvm_unreachable("Unsupported operation!");
705 }
706}
707
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000708/// getScaledElementType - Gets a scaled element type for a partial vector
Cameron Zwarich344731c2011-04-20 21:48:38 +0000709/// access of an alloca. The input types must be integer or floating-point
710/// scalar or vector types, and the resulting type is an integer, float or
711/// double.
712static const Type *getScaledElementType(const Type *Ty1, const Type *Ty2,
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000713 unsigned NewBitWidth) {
Cameron Zwarich344731c2011-04-20 21:48:38 +0000714 bool IsFP1 = Ty1->isFloatingPointTy() ||
715 (Ty1->isVectorTy() &&
716 cast<VectorType>(Ty1)->getElementType()->isFloatingPointTy());
717 bool IsFP2 = Ty2->isFloatingPointTy() ||
718 (Ty2->isVectorTy() &&
719 cast<VectorType>(Ty2)->getElementType()->isFloatingPointTy());
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000720
Cameron Zwarich344731c2011-04-20 21:48:38 +0000721 LLVMContext &Context = Ty1->getContext();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000722
Cameron Zwarich344731c2011-04-20 21:48:38 +0000723 // Prefer floating-point types over integer types, as integer types may have
724 // been created by earlier scalar replacement.
725 if (IsFP1 || IsFP2) {
726 if (NewBitWidth == 32)
727 return Type::getFloatTy(Context);
728 if (NewBitWidth == 64)
729 return Type::getDoubleTy(Context);
730 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000731
Cameron Zwarich344731c2011-04-20 21:48:38 +0000732 return Type::getIntNTy(Context, NewBitWidth);
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000733}
734
Mon P Wangddf9abf2011-04-14 08:04:01 +0000735/// CreateShuffleVectorCast - Creates a shuffle vector to convert one vector
736/// to another vector of the same element type which has the same allocation
737/// size but different primitive sizes (e.g. <3 x i32> and <4 x i32>).
738static Value *CreateShuffleVectorCast(Value *FromVal, const Type *ToType,
739 IRBuilder<> &Builder) {
740 const Type *FromType = FromVal->getType();
Mon P Wang481823a2011-04-14 19:20:42 +0000741 const VectorType *FromVTy = cast<VectorType>(FromType);
742 const VectorType *ToVTy = cast<VectorType>(ToType);
743 assert((ToVTy->getElementType() == FromVTy->getElementType()) &&
Mon P Wangddf9abf2011-04-14 08:04:01 +0000744 "Vectors must have the same element type");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000745 Value *UnV = UndefValue::get(FromType);
746 unsigned numEltsFrom = FromVTy->getNumElements();
747 unsigned numEltsTo = ToVTy->getNumElements();
748
749 SmallVector<Constant*, 3> Args;
Mon P Wang481823a2011-04-14 19:20:42 +0000750 const Type* Int32Ty = Builder.getInt32Ty();
Mon P Wangddf9abf2011-04-14 08:04:01 +0000751 unsigned minNumElts = std::min(numEltsFrom, numEltsTo);
752 unsigned i;
753 for (i=0; i != minNumElts; ++i)
Mon P Wang481823a2011-04-14 19:20:42 +0000754 Args.push_back(ConstantInt::get(Int32Ty, i));
Mon P Wangddf9abf2011-04-14 08:04:01 +0000755
756 if (i < numEltsTo) {
Mon P Wang481823a2011-04-14 19:20:42 +0000757 Constant* UnC = UndefValue::get(Int32Ty);
Mon P Wangddf9abf2011-04-14 08:04:01 +0000758 for (; i != numEltsTo; ++i)
759 Args.push_back(UnC);
760 }
761 Constant *Mask = ConstantVector::get(Args);
762 return Builder.CreateShuffleVector(FromVal, UnV, Mask, "tmpV");
763}
764
Chris Lattner4cc576b2010-04-16 00:24:57 +0000765/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
766/// or vector value FromVal, extracting the bits from the offset specified by
767/// Offset. This returns the value, which is of type ToType.
768///
769/// This happens when we are converting an "integer union" to a single
770/// integer scalar, or when we are converting a "vector union" to a vector with
771/// insert/extractelement instructions.
772///
773/// Offset is an offset from the original alloca, in bits that need to be
774/// shifted to the right.
775Value *ConvertToScalarInfo::
776ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
777 uint64_t Offset, IRBuilder<> &Builder) {
778 // If the load is of the whole new alloca, no conversion is needed.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000779 const Type *FromType = FromVal->getType();
780 if (FromType == ToType && Offset == 0)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000781 return FromVal;
782
783 // If the result alloca is a vector type, this is either an element
784 // access or a bitcast to another vector type of the same size.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000785 if (const VectorType *VTy = dyn_cast<VectorType>(FromType)) {
Cameron Zwarich0398d612011-06-08 22:08:31 +0000786 unsigned FromTypeSize = TD.getTypeAllocSize(FromType);
Cameron Zwarich9827b782011-03-29 05:19:52 +0000787 unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
Cameron Zwarich0398d612011-06-08 22:08:31 +0000788 if (FromTypeSize == ToTypeSize) {
Mon P Wangddf9abf2011-04-14 08:04:01 +0000789 // If the two types have the same primitive size, use a bit cast.
790 // Otherwise, it is two vectors with the same element type that has
791 // the same allocation size but different number of elements so use
792 // a shuffle vector.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000793 if (FromType->getPrimitiveSizeInBits() ==
794 ToType->getPrimitiveSizeInBits())
795 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000796 else
797 return CreateShuffleVectorCast(FromVal, ToType, Builder);
Mon P Wangbe0761c2011-04-13 21:40:02 +0000798 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000799
Cameron Zwarich0398d612011-06-08 22:08:31 +0000800 if (isPowerOf2_64(FromTypeSize / ToTypeSize)) {
Cameron Zwarich344731c2011-04-20 21:48:38 +0000801 assert(!(ToType->isVectorTy() && Offset != 0) && "Can't extract a value "
802 "of a smaller vector type at a nonzero offset.");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000803
Cameron Zwarich344731c2011-04-20 21:48:38 +0000804 const Type *CastElementTy = getScaledElementType(FromType, ToType,
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000805 ToTypeSize * 8);
Cameron Zwarich0398d612011-06-08 22:08:31 +0000806 unsigned NumCastVectorElements = FromTypeSize / ToTypeSize;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000807
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000808 LLVMContext &Context = FromVal->getContext();
809 const Type *CastTy = VectorType::get(CastElementTy,
810 NumCastVectorElements);
811 Value *Cast = Builder.CreateBitCast(FromVal, CastTy, "tmp");
Cameron Zwarich344731c2011-04-20 21:48:38 +0000812
813 unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
814 unsigned Elt = Offset/EltSize;
815 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000816 Value *Extract = Builder.CreateExtractElement(Cast, ConstantInt::get(
Cameron Zwarich344731c2011-04-20 21:48:38 +0000817 Type::getInt32Ty(Context), Elt), "tmp");
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000818 return Builder.CreateBitCast(Extract, ToType, "tmp");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000819 }
Chris Lattner4cc576b2010-04-16 00:24:57 +0000820
821 // Otherwise it must be an element access.
822 unsigned Elt = 0;
823 if (Offset) {
824 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
825 Elt = Offset/EltSize;
826 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
827 }
828 // Return the element extracted out of it.
829 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
830 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
831 if (V->getType() != ToType)
832 V = Builder.CreateBitCast(V, ToType, "tmp");
833 return V;
834 }
Bob Wilson69743022011-01-13 20:59:44 +0000835
Chris Lattner4cc576b2010-04-16 00:24:57 +0000836 // If ToType is a first class aggregate, extract out each of the pieces and
837 // use insertvalue's to form the FCA.
838 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
839 const StructLayout &Layout = *TD.getStructLayout(ST);
840 Value *Res = UndefValue::get(ST);
841 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
842 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
843 Offset+Layout.getElementOffsetInBits(i),
844 Builder);
845 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
846 }
847 return Res;
848 }
Bob Wilson69743022011-01-13 20:59:44 +0000849
Chris Lattner4cc576b2010-04-16 00:24:57 +0000850 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
851 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
852 Value *Res = UndefValue::get(AT);
853 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
854 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
855 Offset+i*EltSize, Builder);
856 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
857 }
858 return Res;
859 }
860
861 // Otherwise, this must be a union that was converted to an integer value.
862 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
863
864 // If this is a big-endian system and the load is narrower than the
865 // full alloca type, we need to do a shift to get the right bits.
866 int ShAmt = 0;
867 if (TD.isBigEndian()) {
868 // On big-endian machines, the lowest bit is stored at the bit offset
869 // from the pointer given by getTypeStoreSizeInBits. This matters for
870 // integers with a bitwidth that is not a multiple of 8.
871 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
872 TD.getTypeStoreSizeInBits(ToType) - Offset;
873 } else {
874 ShAmt = Offset;
875 }
876
877 // Note: we support negative bitwidths (with shl) which are not defined.
878 // We do this to support (f.e.) loads off the end of a structure where
879 // only some bits are used.
880 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
881 FromVal = Builder.CreateLShr(FromVal,
882 ConstantInt::get(FromVal->getType(),
883 ShAmt), "tmp");
884 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson69743022011-01-13 20:59:44 +0000885 FromVal = Builder.CreateShl(FromVal,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000886 ConstantInt::get(FromVal->getType(),
887 -ShAmt), "tmp");
888
889 // Finally, unconditionally truncate the integer to the right width.
890 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
891 if (LIBitWidth < NTy->getBitWidth())
892 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000893 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000894 LIBitWidth), "tmp");
895 else if (LIBitWidth > NTy->getBitWidth())
896 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000897 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000898 LIBitWidth), "tmp");
899
900 // If the result is an integer, this is a trunc or bitcast.
901 if (ToType->isIntegerTy()) {
902 // Should be done.
903 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
904 // Just do a bitcast, we know the sizes match up.
905 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
906 } else {
907 // Otherwise must be a pointer.
908 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
909 }
910 assert(FromVal->getType() == ToType && "Didn't convert right?");
911 return FromVal;
912}
913
914/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
915/// or vector value "Old" at the offset specified by Offset.
916///
917/// This happens when we are converting an "integer union" to a
918/// single integer scalar, or when we are converting a "vector union" to a
919/// vector with insert/extractelement instructions.
920///
921/// Offset is an offset from the original alloca, in bits that need to be
922/// shifted to the right.
923Value *ConvertToScalarInfo::
924ConvertScalar_InsertValue(Value *SV, Value *Old,
925 uint64_t Offset, IRBuilder<> &Builder) {
926 // Convert the stored type to the actual type, shift it left to insert
927 // then 'or' into place.
928 const Type *AllocaType = Old->getType();
929 LLVMContext &Context = Old->getContext();
930
931 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
932 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
933 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
Bob Wilson69743022011-01-13 20:59:44 +0000934
Chris Lattner4cc576b2010-04-16 00:24:57 +0000935 // Changing the whole vector with memset or with an access of a different
936 // vector type?
Mon P Wangbe0761c2011-04-13 21:40:02 +0000937 if (ValSize == VecSize) {
Mon P Wangddf9abf2011-04-14 08:04:01 +0000938 // If the two types have the same primitive size, use a bit cast.
939 // Otherwise, it is two vectors with the same element type that has
940 // the same allocation size but different number of elements so use
941 // a shuffle vector.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000942 if (VTy->getPrimitiveSizeInBits() ==
943 SV->getType()->getPrimitiveSizeInBits())
944 return Builder.CreateBitCast(SV, AllocaType, "tmp");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000945 else
946 return CreateShuffleVectorCast(SV, VTy, Builder);
Mon P Wangbe0761c2011-04-13 21:40:02 +0000947 }
Chris Lattner4cc576b2010-04-16 00:24:57 +0000948
Cameron Zwarich344731c2011-04-20 21:48:38 +0000949 if (isPowerOf2_64(VecSize / ValSize)) {
950 assert(!(SV->getType()->isVectorTy() && Offset != 0) && "Can't insert a "
951 "value of a smaller vector type at a nonzero offset.");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000952
Cameron Zwarich344731c2011-04-20 21:48:38 +0000953 const Type *CastElementTy = getScaledElementType(VTy, SV->getType(),
954 ValSize);
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000955 unsigned NumCastVectorElements = VecSize / ValSize;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000956
957 LLVMContext &Context = SV->getContext();
958 const Type *OldCastTy = VectorType::get(CastElementTy,
959 NumCastVectorElements);
960 Value *OldCast = Builder.CreateBitCast(Old, OldCastTy, "tmp");
961
962 Value *SVCast = Builder.CreateBitCast(SV, CastElementTy, "tmp");
Cameron Zwarich344731c2011-04-20 21:48:38 +0000963
964 unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
965 unsigned Elt = Offset/EltSize;
966 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000967 Value *Insert =
968 Builder.CreateInsertElement(OldCast, SVCast, ConstantInt::get(
Cameron Zwarich344731c2011-04-20 21:48:38 +0000969 Type::getInt32Ty(Context), Elt), "tmp");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000970 return Builder.CreateBitCast(Insert, AllocaType, "tmp");
971 }
972
Chris Lattner4cc576b2010-04-16 00:24:57 +0000973 // Must be an element insertion.
Cameron Zwarichc5c43b92011-04-20 21:48:34 +0000974 assert(SV->getType() == VTy->getElementType());
975 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner4cc576b2010-04-16 00:24:57 +0000976 unsigned Elt = Offset/EltSize;
Cameron Zwarichc5c43b92011-04-20 21:48:34 +0000977 return Builder.CreateInsertElement(Old, SV,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000978 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
979 "tmp");
Chris Lattner4cc576b2010-04-16 00:24:57 +0000980 }
Bob Wilson69743022011-01-13 20:59:44 +0000981
Chris Lattner4cc576b2010-04-16 00:24:57 +0000982 // If SV is a first-class aggregate value, insert each value recursively.
983 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
984 const StructLayout &Layout = *TD.getStructLayout(ST);
985 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
986 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000987 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000988 Offset+Layout.getElementOffsetInBits(i),
989 Builder);
990 }
991 return Old;
992 }
Bob Wilson69743022011-01-13 20:59:44 +0000993
Chris Lattner4cc576b2010-04-16 00:24:57 +0000994 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
995 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
996 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
997 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
998 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
999 }
1000 return Old;
1001 }
1002
1003 // If SV is a float, convert it to the appropriate integer type.
1004 // If it is a pointer, do the same.
1005 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
1006 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
1007 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
1008 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
1009 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
1010 SV = Builder.CreateBitCast(SV,
1011 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
1012 else if (SV->getType()->isPointerTy())
1013 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
1014
1015 // Zero extend or truncate the value if needed.
1016 if (SV->getType() != AllocaType) {
1017 if (SV->getType()->getPrimitiveSizeInBits() <
1018 AllocaType->getPrimitiveSizeInBits())
1019 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
1020 else {
1021 // Truncation may be needed if storing more than the alloca can hold
1022 // (undefined behavior).
1023 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
1024 SrcWidth = DestWidth;
1025 SrcStoreWidth = DestStoreWidth;
1026 }
1027 }
1028
1029 // If this is a big-endian system and the store is narrower than the
1030 // full alloca type, we need to do a shift to get the right bits.
1031 int ShAmt = 0;
1032 if (TD.isBigEndian()) {
1033 // On big-endian machines, the lowest bit is stored at the bit offset
1034 // from the pointer given by getTypeStoreSizeInBits. This matters for
1035 // integers with a bitwidth that is not a multiple of 8.
1036 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1037 } else {
1038 ShAmt = Offset;
1039 }
1040
1041 // Note: we support negative bitwidths (with shr) which are not defined.
1042 // We do this to support (f.e.) stores off the end of a structure where
1043 // only some bits in the structure are set.
1044 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1045 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1046 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
1047 ShAmt), "tmp");
1048 Mask <<= ShAmt;
1049 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1050 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
1051 -ShAmt), "tmp");
1052 Mask = Mask.lshr(-ShAmt);
1053 }
1054
1055 // Mask out the bits we are about to insert from the old value, and or
1056 // in the new bits.
1057 if (SrcWidth != DestWidth) {
1058 assert(DestWidth > SrcWidth);
1059 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1060 SV = Builder.CreateOr(Old, SV, "ins");
1061 }
1062 return SV;
1063}
1064
1065
1066//===----------------------------------------------------------------------===//
1067// SRoA Driver
1068//===----------------------------------------------------------------------===//
1069
1070
Chris Lattnered7b41e2003-05-27 15:45:27 +00001071bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +00001072 TD = getAnalysisIfAvailable<TargetData>();
1073
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001074 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +00001075
1076 // FIXME: ScalarRepl currently depends on TargetData more than it
1077 // theoretically needs to. It should be refactored in order to support
1078 // target-independent IR. Until this is done, just skip the actual
1079 // scalar-replacement portion of this pass.
1080 if (!TD) return Changed;
1081
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001082 while (1) {
1083 bool LocalChange = performScalarRepl(F);
1084 if (!LocalChange) break; // No need to repromote if no scalarrepl
1085 Changed = true;
1086 LocalChange = performPromotion(F);
1087 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
1088 }
Chris Lattner38aec322003-09-11 16:45:55 +00001089
1090 return Changed;
1091}
1092
Chris Lattnerd0f56132011-01-14 19:50:47 +00001093namespace {
1094class AllocaPromoter : public LoadAndStorePromoter {
1095 AllocaInst *AI;
1096public:
Cameron Zwarichc8279392011-05-24 03:10:43 +00001097 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1098 DbgDeclareInst *DD, DIBuilder *&DB)
1099 : LoadAndStorePromoter(Insts, S, DD, DB), AI(0) {}
Chris Lattnerd0f56132011-01-14 19:50:47 +00001100
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001101 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerd0f56132011-01-14 19:50:47 +00001102 // Remember which alloca we're promoting (for isInstInList).
1103 this->AI = AI;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001104 LoadAndStorePromoter::run(Insts);
Chris Lattnerd0f56132011-01-14 19:50:47 +00001105 AI->eraseFromParent();
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001106 }
1107
Chris Lattnerd0f56132011-01-14 19:50:47 +00001108 virtual bool isInstInList(Instruction *I,
1109 const SmallVectorImpl<Instruction*> &Insts) const {
1110 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1111 return LI->getOperand(0) == AI;
1112 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001113 }
Chris Lattnerd0f56132011-01-14 19:50:47 +00001114};
1115} // end anon namespace
Chris Lattner38aec322003-09-11 16:45:55 +00001116
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001117/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1118/// subsequently loaded can be rewritten to load both input pointers and then
1119/// select between the result, allowing the load of the alloca to be promoted.
1120/// From this:
1121/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1122/// %V = load i32* %P2
1123/// to:
1124/// %V1 = load i32* %Alloca -> will be mem2reg'd
1125/// %V2 = load i32* %Other
Chris Lattnere3357862011-01-24 01:07:11 +00001126/// %V = select i1 %cond, i32 %V1, i32 %V2
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001127///
1128/// We can do this to a select if its only uses are loads and if the operand to
1129/// the select can be loaded unconditionally.
1130static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
1131 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1132 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1133
1134 for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1135 UI != UE; ++UI) {
1136 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1137 if (LI == 0 || LI->isVolatile()) return false;
1138
Chris Lattnere3357862011-01-24 01:07:11 +00001139 // Both operands to the select need to be dereferencable, either absolutely
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001140 // (e.g. allocas) or at this point because we can see other accesses to it.
1141 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1142 LI->getAlignment(), TD))
1143 return false;
1144 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1145 LI->getAlignment(), TD))
1146 return false;
1147 }
1148
1149 return true;
1150}
1151
Chris Lattnere3357862011-01-24 01:07:11 +00001152/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1153/// subsequently loaded can be rewritten to load both input pointers in the pred
1154/// blocks and then PHI the results, allowing the load of the alloca to be
1155/// promoted.
1156/// From this:
1157/// %P2 = phi [i32* %Alloca, i32* %Other]
1158/// %V = load i32* %P2
1159/// to:
1160/// %V1 = load i32* %Alloca -> will be mem2reg'd
1161/// ...
1162/// %V2 = load i32* %Other
1163/// ...
1164/// %V = phi [i32 %V1, i32 %V2]
1165///
1166/// We can do this to a select if its only uses are loads and if the operand to
1167/// the select can be loaded unconditionally.
1168static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
1169 // For now, we can only do this promotion if the load is in the same block as
1170 // the PHI, and if there are no stores between the phi and load.
1171 // TODO: Allow recursive phi users.
1172 // TODO: Allow stores.
1173 BasicBlock *BB = PN->getParent();
1174 unsigned MaxAlign = 0;
1175 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1176 UI != UE; ++UI) {
1177 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1178 if (LI == 0 || LI->isVolatile()) return false;
1179
1180 // For now we only allow loads in the same block as the PHI. This is a
1181 // common case that happens when instcombine merges two loads through a PHI.
1182 if (LI->getParent() != BB) return false;
1183
1184 // Ensure that there are no instructions between the PHI and the load that
1185 // could store.
1186 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1187 if (BBI->mayWriteToMemory())
1188 return false;
1189
1190 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1191 }
1192
1193 // Okay, we know that we have one or more loads in the same block as the PHI.
1194 // We can transform this if it is safe to push the loads into the predecessor
1195 // blocks. The only thing to watch out for is that we can't put a possibly
1196 // trapping load in the predecessor if it is a critical edge.
1197 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1198 BasicBlock *Pred = PN->getIncomingBlock(i);
1199
1200 // If the predecessor has a single successor, then the edge isn't critical.
1201 if (Pred->getTerminator()->getNumSuccessors() == 1)
1202 continue;
1203
1204 Value *InVal = PN->getIncomingValue(i);
1205
1206 // If the InVal is an invoke in the pred, we can't put a load on the edge.
1207 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
1208 if (II->getParent() == Pred)
1209 return false;
1210
1211 // If this pointer is always safe to load, or if we can prove that there is
1212 // already a load in the block, then we can move the load to the pred block.
1213 if (InVal->isDereferenceablePointer() ||
1214 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1215 continue;
1216
1217 return false;
1218 }
1219
1220 return true;
1221}
1222
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001223
1224/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1225/// direct (non-volatile) loads and stores to it. If the alloca is close but
1226/// not quite there, this will transform the code to allow promotion. As such,
1227/// it is a non-pure predicate.
1228static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
1229 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1230 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1231
1232 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1233 UI != UE; ++UI) {
1234 User *U = *UI;
1235 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1236 if (LI->isVolatile())
1237 return false;
1238 continue;
1239 }
1240
1241 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1242 if (SI->getOperand(0) == AI || SI->isVolatile())
1243 return false; // Don't allow a store OF the AI, only INTO the AI.
1244 continue;
1245 }
1246
1247 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1248 // If the condition being selected on is a constant, fold the select, yes
1249 // this does (rarely) happen early on.
1250 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1251 Value *Result = SI->getOperand(1+CI->isZero());
1252 SI->replaceAllUsesWith(Result);
1253 SI->eraseFromParent();
1254
1255 // This is very rare and we just scrambled the use list of AI, start
1256 // over completely.
1257 return tryToMakeAllocaBePromotable(AI, TD);
1258 }
1259
1260 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1261 // loads, then we can transform this by rewriting the select.
1262 if (!isSafeSelectToSpeculate(SI, TD))
1263 return false;
1264
1265 InstsToRewrite.insert(SI);
1266 continue;
1267 }
1268
Chris Lattnere3357862011-01-24 01:07:11 +00001269 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1270 if (PN->use_empty()) { // Dead PHIs can be stripped.
1271 InstsToRewrite.insert(PN);
1272 continue;
1273 }
1274
1275 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1276 // in the pred blocks, then we can transform this by rewriting the PHI.
1277 if (!isSafePHIToSpeculate(PN, TD))
1278 return false;
1279
1280 InstsToRewrite.insert(PN);
1281 continue;
1282 }
1283
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001284 return false;
1285 }
1286
1287 // If there are no instructions to rewrite, then all uses are load/stores and
1288 // we're done!
1289 if (InstsToRewrite.empty())
1290 return true;
1291
1292 // If we have instructions that need to be rewritten for this to be promotable
1293 // take care of it now.
1294 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
Chris Lattnere3357862011-01-24 01:07:11 +00001295 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1296 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1297 // loads with a new select.
1298 while (!SI->use_empty()) {
1299 LoadInst *LI = cast<LoadInst>(SI->use_back());
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001300
Chris Lattnere3357862011-01-24 01:07:11 +00001301 IRBuilder<> Builder(LI);
1302 LoadInst *TrueLoad =
1303 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1304 LoadInst *FalseLoad =
1305 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".t");
1306
1307 // Transfer alignment and TBAA info if present.
1308 TrueLoad->setAlignment(LI->getAlignment());
1309 FalseLoad->setAlignment(LI->getAlignment());
1310 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1311 TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1312 FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1313 }
1314
1315 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1316 V->takeName(LI);
1317 LI->replaceAllUsesWith(V);
1318 LI->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001319 }
Chris Lattnere3357862011-01-24 01:07:11 +00001320
1321 // Now that all the loads are gone, the select is gone too.
1322 SI->eraseFromParent();
1323 continue;
1324 }
1325
1326 // Otherwise, we have a PHI node which allows us to push the loads into the
1327 // predecessors.
1328 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1329 if (PN->use_empty()) {
1330 PN->eraseFromParent();
1331 continue;
1332 }
1333
1334 const Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
Jay Foad3ecfc862011-03-30 11:28:46 +00001335 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1336 PN->getName()+".ld", PN);
Chris Lattnere3357862011-01-24 01:07:11 +00001337
1338 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1339 // matter which one we get and if any differ, it doesn't matter.
1340 LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1341 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1342 unsigned Align = SomeLoad->getAlignment();
1343
1344 // Rewrite all loads of the PN to use the new PHI.
1345 while (!PN->use_empty()) {
1346 LoadInst *LI = cast<LoadInst>(PN->use_back());
1347 LI->replaceAllUsesWith(NewPN);
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001348 LI->eraseFromParent();
1349 }
1350
Chris Lattnere3357862011-01-24 01:07:11 +00001351 // Inject loads into all of the pred blocks. Keep track of which blocks we
1352 // insert them into in case we have multiple edges from the same block.
1353 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1354
1355 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1356 BasicBlock *Pred = PN->getIncomingBlock(i);
1357 LoadInst *&Load = InsertedLoads[Pred];
1358 if (Load == 0) {
1359 Load = new LoadInst(PN->getIncomingValue(i),
1360 PN->getName() + "." + Pred->getName(),
1361 Pred->getTerminator());
1362 Load->setAlignment(Align);
1363 if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1364 }
1365
1366 NewPN->addIncoming(Load, Pred);
1367 }
1368
1369 PN->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001370 }
1371
1372 ++NumAdjusted;
1373 return true;
1374}
1375
Chris Lattner38aec322003-09-11 16:45:55 +00001376bool SROA::performPromotion(Function &F) {
1377 std::vector<AllocaInst*> Allocas;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001378 DominatorTree *DT = 0;
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001379 if (HasDomTree)
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001380 DT = &getAnalysis<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +00001381
Chris Lattner02a3be02003-09-20 14:39:18 +00001382 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +00001383
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001384 bool Changed = false;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001385 SmallVector<Instruction*, 64> Insts;
Cameron Zwarichc8279392011-05-24 03:10:43 +00001386 DIBuilder *DIB = 0;
Chris Lattner38aec322003-09-11 16:45:55 +00001387 while (1) {
1388 Allocas.clear();
1389
1390 // Find allocas that are safe to promote, by looking at all instructions in
1391 // the entry node
1392 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1393 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001394 if (tryToMakeAllocaBePromotable(AI, TD))
Chris Lattner38aec322003-09-11 16:45:55 +00001395 Allocas.push_back(AI);
1396
1397 if (Allocas.empty()) break;
1398
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001399 if (HasDomTree)
Cameron Zwarich419e8a62011-01-17 17:38:41 +00001400 PromoteMemToReg(Allocas, *DT);
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001401 else {
1402 SSAUpdater SSA;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001403 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1404 AllocaInst *AI = Allocas[i];
1405
1406 // Build list of instructions to promote.
1407 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1408 UI != E; ++UI)
1409 Insts.push_back(cast<Instruction>(*UI));
Cameron Zwarichc8279392011-05-24 03:10:43 +00001410
1411 DbgDeclareInst *DDI = FindAllocaDbgDeclare(AI);
Cameron Zwarich13a16082011-05-24 06:00:08 +00001412 if (DDI && !DIB)
1413 DIB = new DIBuilder(*AI->getParent()->getParent()->getParent());
Cameron Zwarichc8279392011-05-24 03:10:43 +00001414 AllocaPromoter(Insts, SSA, DDI, DIB).run(AI, Insts);
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001415 Insts.clear();
1416 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001417 }
Chris Lattner38aec322003-09-11 16:45:55 +00001418 NumPromoted += Allocas.size();
1419 Changed = true;
1420 }
1421
Cameron Zwarichc8279392011-05-24 03:10:43 +00001422 // FIXME: Is there a better way to handle the lazy initialization of DIB
1423 // so that there doesn't need to be an explicit delete?
1424 delete DIB;
1425
Chris Lattner38aec322003-09-11 16:45:55 +00001426 return Changed;
1427}
1428
Chris Lattner4cc576b2010-04-16 00:24:57 +00001429
Bob Wilson3992feb2010-02-03 17:23:56 +00001430/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1431/// SROA. It must be a struct or array type with a small number of elements.
1432static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
1433 const Type *T = AI->getAllocatedType();
1434 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +00001435 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +00001436 return ST->getNumElements() <= 32;
1437 // Arrays are much less likely to be safe for SROA; only consider
1438 // them if they are very small.
1439 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1440 return AT->getNumElements() <= 8;
1441 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +00001442}
1443
Chris Lattnerc4472072010-04-15 23:50:26 +00001444
Chris Lattner38aec322003-09-11 16:45:55 +00001445// performScalarRepl - This algorithm is a simple worklist driven algorithm,
1446// which runs on all of the malloc/alloca instructions in the function, removing
1447// them if they are only used by getelementptr instructions.
1448//
1449bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001450 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +00001451
Chris Lattner31d80102010-04-15 21:59:20 +00001452 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +00001453 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001454 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +00001455 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +00001456 WorkList.push_back(A);
1457
1458 // Process the worklist
1459 bool Changed = false;
1460 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001461 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001462 WorkList.pop_back();
Bob Wilson69743022011-01-13 20:59:44 +00001463
Chris Lattneradd2bd72006-12-22 23:14:42 +00001464 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1465 // with unused elements.
1466 if (AI->use_empty()) {
1467 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +00001468 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +00001469 continue;
1470 }
Chris Lattner7809ecd2009-02-03 01:30:09 +00001471
1472 // If this alloca is impossible for us to promote, reject it early.
1473 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1474 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001475
Chris Lattner79b3bd32007-04-25 06:40:51 +00001476 // Check to see if this allocation is only modified by a memcpy/memmove from
1477 // a constant global. If this is the case, we can change all users to use
1478 // the constant global instead. This is commonly produced by the CFE by
1479 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1480 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +00001481 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +00001482 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
1483 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +00001484 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001485 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +00001486 TheCopy->eraseFromParent(); // Don't mutate the global.
1487 AI->eraseFromParent();
1488 ++NumGlobals;
1489 Changed = true;
1490 continue;
1491 }
Bob Wilson69743022011-01-13 20:59:44 +00001492
Chris Lattner7809ecd2009-02-03 01:30:09 +00001493 // Check to see if we can perform the core SROA transformation. We cannot
1494 // transform the allocation instruction if it is an array allocation
1495 // (allocations OF arrays are ok though), and an allocation of a scalar
1496 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +00001497 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +00001498
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +00001499 // Do not promote [0 x %struct].
1500 if (AllocaSize == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001501
Chris Lattner31d80102010-04-15 21:59:20 +00001502 // Do not promote any struct whose size is too big.
1503 if (AllocaSize > SRThreshold) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001504
Bob Wilson3992feb2010-02-03 17:23:56 +00001505 // If the alloca looks like a good candidate for scalar replacement, and if
1506 // all its users can be transformed, then split up the aggregate into its
1507 // separate elements.
1508 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1509 DoScalarReplacement(AI, WorkList);
1510 Changed = true;
1511 continue;
1512 }
1513
Chris Lattner6e733d32009-01-28 20:16:43 +00001514 // If we can turn this aggregate value (potentially with casts) into a
1515 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001516 // IsNotTrivial tracks whether this is something that mem2reg could have
1517 // promoted itself. If so, we don't want to transform it needlessly. Note
1518 // that we can't just check based on the type: the alloca may be of an i32
1519 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +00001520 if (AllocaInst *NewAI =
1521 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001522 NewAI->takeName(AI);
1523 AI->eraseFromParent();
1524 ++NumConverted;
1525 Changed = true;
1526 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001527 }
1528
Chris Lattner7809ecd2009-02-03 01:30:09 +00001529 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +00001530 }
1531
1532 return Changed;
1533}
Chris Lattner5e062a12003-05-30 04:15:41 +00001534
Chris Lattnera10b29b2007-04-25 05:02:56 +00001535/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1536/// predicate, do SROA now.
Bob Wilson69743022011-01-13 20:59:44 +00001537void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001538 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +00001539 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +00001540 SmallVector<AllocaInst*, 32> ElementAllocas;
1541 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1542 ElementAllocas.reserve(ST->getNumContainedTypes());
1543 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Bob Wilson69743022011-01-13 20:59:44 +00001544 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +00001545 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001546 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001547 ElementAllocas.push_back(NA);
1548 WorkList.push_back(NA); // Add to worklist for recursive processing
1549 }
1550 } else {
1551 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1552 ElementAllocas.reserve(AT->getNumElements());
1553 const Type *ElTy = AT->getElementType();
1554 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +00001555 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001556 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001557 ElementAllocas.push_back(NA);
1558 WorkList.push_back(NA); // Add to worklist for recursive processing
1559 }
1560 }
1561
Bob Wilsonb742def2009-12-18 20:14:40 +00001562 // Now that we have created the new alloca instructions, rewrite all the
1563 // uses of the old alloca.
1564 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +00001565
Bob Wilsonb742def2009-12-18 20:14:40 +00001566 // Now erase any instructions that were made dead while rewriting the alloca.
1567 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +00001568 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +00001569
Dan Gohmanfe601042010-06-22 15:08:57 +00001570 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +00001571}
Chris Lattnera59adc42009-12-14 05:11:02 +00001572
Bob Wilsonb742def2009-12-18 20:14:40 +00001573/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1574/// recursively including all their operands that become trivially dead.
1575void SROA::DeleteDeadInstructions() {
1576 while (!DeadInsts.empty()) {
1577 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +00001578
Bob Wilsonb742def2009-12-18 20:14:40 +00001579 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1580 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1581 // Zero out the operand and see if it becomes trivially dead.
1582 // (But, don't add allocas to the dead instruction list -- they are
1583 // already on the worklist and will be deleted separately.)
1584 *OI = 0;
1585 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1586 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +00001587 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001588
1589 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +00001590 }
Chris Lattnera59adc42009-12-14 05:11:02 +00001591}
Bob Wilson69743022011-01-13 20:59:44 +00001592
Bob Wilsonb742def2009-12-18 20:14:40 +00001593/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1594/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001595/// the Info parameter. Offset indicates the position within AI that is
1596/// referenced by this instruction.
Chris Lattner6c95d242011-01-23 07:29:29 +00001597void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001598 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001599 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1600 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +00001601
Bob Wilsonb742def2009-12-18 20:14:40 +00001602 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Chris Lattner6c95d242011-01-23 07:29:29 +00001603 isSafeForScalarRepl(BC, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001604 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001605 uint64_t GEPOffset = Offset;
Chris Lattner6c95d242011-01-23 07:29:29 +00001606 isSafeGEP(GEPI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001607 if (!Info.isUnsafe)
Chris Lattner6c95d242011-01-23 07:29:29 +00001608 isSafeForScalarRepl(GEPI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001609 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001610 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001611 if (Length == 0)
1612 return MarkUnsafe(Info, User);
Chris Lattner6c95d242011-01-23 07:29:29 +00001613 isSafeMemAccess(Offset, Length->getZExtValue(), 0,
Chris Lattner145c5322011-01-23 08:27:54 +00001614 UI.getOperandNo() == 0, Info, MI,
1615 true /*AllowWholeAccess*/);
Bob Wilsonb742def2009-12-18 20:14:40 +00001616 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001617 if (LI->isVolatile())
1618 return MarkUnsafe(Info, User);
1619 const Type *LIType = LI->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001620 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001621 LIType, false, Info, LI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001622 Info.hasALoadOrStore = true;
1623
Bob Wilsonb742def2009-12-18 20:14:40 +00001624 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1625 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001626 if (SI->isVolatile() || SI->getOperand(0) == I)
1627 return MarkUnsafe(Info, User);
1628
1629 const Type *SIType = SI->getOperand(0)->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001630 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001631 SIType, true, Info, SI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001632 Info.hasALoadOrStore = true;
Chris Lattner145c5322011-01-23 08:27:54 +00001633 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1634 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1635 } else {
1636 return MarkUnsafe(Info, User);
1637 }
1638 if (Info.isUnsafe) return;
1639 }
1640}
1641
1642
1643/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1644/// derived from the alloca, we can often still split the alloca into elements.
1645/// This is useful if we have a large alloca where one element is phi'd
1646/// together somewhere: we can SRoA and promote all the other elements even if
1647/// we end up not being able to promote this one.
1648///
1649/// All we require is that the uses of the PHI do not index into other parts of
1650/// the alloca. The most important use case for this is single load and stores
1651/// that are PHI'd together, which can happen due to code sinking.
1652void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1653 AllocaInfo &Info) {
1654 // If we've already checked this PHI, don't do it again.
1655 if (PHINode *PN = dyn_cast<PHINode>(I))
1656 if (!Info.CheckedPHIs.insert(PN))
1657 return;
1658
1659 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1660 Instruction *User = cast<Instruction>(*UI);
1661
1662 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1663 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1664 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1665 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1666 // but would have to prove that we're staying inside of an element being
1667 // promoted.
1668 if (!GEPI->hasAllZeroIndices())
1669 return MarkUnsafe(Info, User);
1670 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1671 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1672 if (LI->isVolatile())
1673 return MarkUnsafe(Info, User);
1674 const Type *LIType = LI->getType();
1675 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1676 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1677 Info.hasALoadOrStore = true;
1678
1679 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1680 // Store is ok if storing INTO the pointer, not storing the pointer
1681 if (SI->isVolatile() || SI->getOperand(0) == I)
1682 return MarkUnsafe(Info, User);
1683
1684 const Type *SIType = SI->getOperand(0)->getType();
1685 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1686 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1687 Info.hasALoadOrStore = true;
1688 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1689 isSafePHISelectUseForScalarRepl(User, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001690 } else {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001691 return MarkUnsafe(Info, User);
Bob Wilsonb742def2009-12-18 20:14:40 +00001692 }
1693 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001694 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001695}
Bob Wilson39c88a62009-12-17 18:34:24 +00001696
Bob Wilsonb742def2009-12-18 20:14:40 +00001697/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1698/// replacement. It is safe when all the indices are constant, in-bounds
1699/// references, and when the resulting offset corresponds to an element within
1700/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001701/// return, Offset is adjusted as specified by the GEP indices.
Chris Lattner6c95d242011-01-23 07:29:29 +00001702void SROA::isSafeGEP(GetElementPtrInst *GEPI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001703 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001704 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1705 if (GEPIt == E)
1706 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001707
Chris Lattner88e6dc82008-08-23 05:21:06 +00001708 // Walk through the GEP type indices, checking the types that this indexes
1709 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001710 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001711 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001712 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001713 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001714
Bob Wilsonb742def2009-12-18 20:14:40 +00001715 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1716 if (!IdxVal)
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001717 return MarkUnsafe(Info, GEPI);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001718 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001719
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001720 // Compute the offset due to this GEP and check if the alloca has a
1721 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001722 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1723 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1724 &Indices[0], Indices.size());
Chris Lattner6c95d242011-01-23 07:29:29 +00001725 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001726 MarkUnsafe(Info, GEPI);
Chris Lattner5e062a12003-05-30 04:15:41 +00001727}
1728
Bob Wilson704d1342011-01-13 17:45:11 +00001729/// isHomogeneousAggregate - Check if type T is a struct or array containing
1730/// elements of the same type (which is always true for arrays). If so,
1731/// return true with NumElts and EltTy set to the number of elements and the
1732/// element type, respectively.
1733static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1734 const Type *&EltTy) {
1735 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1736 NumElts = AT->getNumElements();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001737 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
Bob Wilson704d1342011-01-13 17:45:11 +00001738 return true;
1739 }
1740 if (const StructType *ST = dyn_cast<StructType>(T)) {
1741 NumElts = ST->getNumContainedTypes();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001742 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
Bob Wilson704d1342011-01-13 17:45:11 +00001743 for (unsigned n = 1; n < NumElts; ++n) {
1744 if (ST->getContainedType(n) != EltTy)
1745 return false;
1746 }
1747 return true;
1748 }
1749 return false;
1750}
1751
1752/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1753/// "homogeneous" aggregates with the same element type and number of elements.
1754static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1755 if (T1 == T2)
1756 return true;
1757
1758 unsigned NumElts1, NumElts2;
1759 const Type *EltTy1, *EltTy2;
1760 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1761 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1762 NumElts1 == NumElts2 &&
1763 EltTy1 == EltTy2)
1764 return true;
1765
1766 return false;
1767}
1768
Bob Wilsonb742def2009-12-18 20:14:40 +00001769/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1770/// alloca or has an offset and size that corresponds to a component element
1771/// within it. The offset checked here may have been formed from a GEP with a
1772/// pointer bitcasted to a different type.
Chris Lattner145c5322011-01-23 08:27:54 +00001773///
1774/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1775/// unit. If false, it only allows accesses known to be in a single element.
Chris Lattner6c95d242011-01-23 07:29:29 +00001776void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001777 const Type *MemOpType, bool isStore,
Chris Lattner145c5322011-01-23 08:27:54 +00001778 AllocaInfo &Info, Instruction *TheAccess,
1779 bool AllowWholeAccess) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001780 // Check if this is a load/store of the entire alloca.
Chris Lattner145c5322011-01-23 08:27:54 +00001781 if (Offset == 0 && AllowWholeAccess &&
Chris Lattner6c95d242011-01-23 07:29:29 +00001782 MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
Bob Wilson704d1342011-01-13 17:45:11 +00001783 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1784 // loads/stores (which are essentially the same as the MemIntrinsics with
1785 // regard to copying padding between elements). But, if an alloca is
1786 // flagged as both a source and destination of such operations, we'll need
1787 // to check later for padding between elements.
1788 if (!MemOpType || MemOpType->isIntegerTy()) {
1789 if (isStore)
1790 Info.isMemCpyDst = true;
1791 else
1792 Info.isMemCpySrc = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001793 return;
1794 }
Bob Wilson704d1342011-01-13 17:45:11 +00001795 // This is also safe for references using a type that is compatible with
1796 // the type of the alloca, so that loads/stores can be rewritten using
1797 // insertvalue/extractvalue.
Chris Lattner6c95d242011-01-23 07:29:29 +00001798 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
Chris Lattner7e9b4272011-01-16 06:18:28 +00001799 Info.hasSubelementAccess = true;
Bob Wilson704d1342011-01-13 17:45:11 +00001800 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001801 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001802 }
1803 // Check if the offset/size correspond to a component within the alloca type.
Chris Lattner6c95d242011-01-23 07:29:29 +00001804 const Type *T = Info.AI->getAllocatedType();
Chris Lattner7e9b4272011-01-16 06:18:28 +00001805 if (TypeHasComponent(T, Offset, MemSize)) {
1806 Info.hasSubelementAccess = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001807 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001808 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001809
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001810 return MarkUnsafe(Info, TheAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +00001811}
1812
1813/// TypeHasComponent - Return true if T has a component type with the
1814/// specified offset and size. If Size is zero, do not check the size.
1815bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1816 const Type *EltTy;
1817 uint64_t EltSize;
1818 if (const StructType *ST = dyn_cast<StructType>(T)) {
1819 const StructLayout *Layout = TD->getStructLayout(ST);
1820 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1821 EltTy = ST->getContainedType(EltIdx);
1822 EltSize = TD->getTypeAllocSize(EltTy);
1823 Offset -= Layout->getElementOffset(EltIdx);
1824 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1825 EltTy = AT->getElementType();
1826 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001827 if (Offset >= AT->getNumElements() * EltSize)
1828 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001829 Offset %= EltSize;
1830 } else {
1831 return false;
1832 }
1833 if (Offset == 0 && (Size == 0 || EltSize == Size))
1834 return true;
1835 // Check if the component spans multiple elements.
1836 if (Offset + Size > EltSize)
1837 return false;
1838 return TypeHasComponent(EltTy, Offset, Size);
1839}
1840
1841/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1842/// the instruction I, which references it, to use the separate elements.
1843/// Offset indicates the position within AI that is referenced by this
1844/// instruction.
1845void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1846 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner145c5322011-01-23 08:27:54 +00001847 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1848 Use &TheUse = UI.getUse();
1849 Instruction *User = cast<Instruction>(*UI++);
Bob Wilsonb742def2009-12-18 20:14:40 +00001850
1851 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1852 RewriteBitCast(BC, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001853 continue;
1854 }
1855
1856 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001857 RewriteGEP(GEPI, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001858 continue;
1859 }
1860
1861 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001862 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1863 uint64_t MemSize = Length->getZExtValue();
1864 if (Offset == 0 &&
1865 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1866 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001867 // Otherwise the intrinsic can only touch a single element and the
1868 // address operand will be updated, so nothing else needs to be done.
Chris Lattner145c5322011-01-23 08:27:54 +00001869 continue;
1870 }
1871
1872 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001873 const Type *LIType = LI->getType();
Chris Lattner192228e2011-01-16 05:28:59 +00001874
Bob Wilson704d1342011-01-13 17:45:11 +00001875 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001876 // Replace:
1877 // %res = load { i32, i32 }* %alloc
1878 // with:
1879 // %load.0 = load i32* %alloc.0
1880 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1881 // %load.1 = load i32* %alloc.1
1882 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1883 // (Also works for arrays instead of structs)
1884 Value *Insert = UndefValue::get(LIType);
Devang Patelabb25122011-06-03 19:46:19 +00001885 IRBuilder<> Builder(LI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001886 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patelabb25122011-06-03 19:46:19 +00001887 Value *Load = Builder.CreateLoad(NewElts[i], "load");
1888 Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
Bob Wilsonb742def2009-12-18 20:14:40 +00001889 }
1890 LI->replaceAllUsesWith(Insert);
1891 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001892 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001893 TD->getTypeAllocSize(LIType) ==
1894 TD->getTypeAllocSize(AI->getAllocatedType())) {
1895 // If this is a load of the entire alloca to an integer, rewrite it.
1896 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1897 }
Chris Lattner145c5322011-01-23 08:27:54 +00001898 continue;
1899 }
1900
1901 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001902 Value *Val = SI->getOperand(0);
1903 const Type *SIType = Val->getType();
Bob Wilson704d1342011-01-13 17:45:11 +00001904 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001905 // Replace:
1906 // store { i32, i32 } %val, { i32, i32 }* %alloc
1907 // with:
1908 // %val.0 = extractvalue { i32, i32 } %val, 0
1909 // store i32 %val.0, i32* %alloc.0
1910 // %val.1 = extractvalue { i32, i32 } %val, 1
1911 // store i32 %val.1, i32* %alloc.1
1912 // (Also works for arrays instead of structs)
Devang Patelabb25122011-06-03 19:46:19 +00001913 IRBuilder<> Builder(SI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001914 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patelabb25122011-06-03 19:46:19 +00001915 Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1916 Builder.CreateStore(Extract, NewElts[i]);
Bob Wilsonb742def2009-12-18 20:14:40 +00001917 }
1918 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001919 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001920 TD->getTypeAllocSize(SIType) ==
1921 TD->getTypeAllocSize(AI->getAllocatedType())) {
1922 // If this is a store of the entire alloca from an integer, rewrite it.
1923 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1924 }
Chris Lattner145c5322011-01-23 08:27:54 +00001925 continue;
1926 }
1927
1928 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1929 // If we have a PHI user of the alloca itself (as opposed to a GEP or
1930 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1931 // the new pointer.
1932 if (!isa<AllocaInst>(I)) continue;
1933
1934 assert(Offset == 0 && NewElts[0] &&
1935 "Direct alloca use should have a zero offset");
1936
1937 // If we have a use of the alloca, we know the derived uses will be
1938 // utilizing just the first element of the scalarized result. Insert a
1939 // bitcast of the first alloca before the user as required.
1940 AllocaInst *NewAI = NewElts[0];
1941 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1942 NewAI->moveBefore(BCI);
1943 TheUse = BCI;
1944 continue;
Bob Wilsonb742def2009-12-18 20:14:40 +00001945 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001946 }
1947}
1948
Bob Wilsonb742def2009-12-18 20:14:40 +00001949/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1950/// and recursively continue updating all of its uses.
1951void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1952 SmallVector<AllocaInst*, 32> &NewElts) {
1953 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1954 if (BC->getOperand(0) != AI)
1955 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001956
Bob Wilsonb742def2009-12-18 20:14:40 +00001957 // The bitcast references the original alloca. Replace its uses with
1958 // references to the first new element alloca.
1959 Instruction *Val = NewElts[0];
1960 if (Val->getType() != BC->getDestTy()) {
1961 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1962 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001963 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001964 BC->replaceAllUsesWith(Val);
1965 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001966}
1967
Bob Wilsonb742def2009-12-18 20:14:40 +00001968/// FindElementAndOffset - Return the index of the element containing Offset
1969/// within the specified type, which must be either a struct or an array.
1970/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001971/// element. IdxTy is set to the type of the index result to be used in a
1972/// GEP instruction.
1973uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1974 const Type *&IdxTy) {
1975 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001976 if (const StructType *ST = dyn_cast<StructType>(T)) {
1977 const StructLayout *Layout = TD->getStructLayout(ST);
1978 Idx = Layout->getElementContainingOffset(Offset);
1979 T = ST->getContainedType(Idx);
1980 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001981 IdxTy = Type::getInt32Ty(T->getContext());
1982 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001983 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001984 const ArrayType *AT = cast<ArrayType>(T);
1985 T = AT->getElementType();
1986 uint64_t EltSize = TD->getTypeAllocSize(T);
1987 Idx = Offset / EltSize;
1988 Offset -= Idx * EltSize;
1989 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001990 return Idx;
1991}
1992
1993/// RewriteGEP - Check if this GEP instruction moves the pointer across
1994/// elements of the alloca that are being split apart, and if so, rewrite
1995/// the GEP to be relative to the new element.
1996void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1997 SmallVector<AllocaInst*, 32> &NewElts) {
1998 uint64_t OldOffset = Offset;
1999 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
2000 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
2001 &Indices[0], Indices.size());
2002
2003 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
2004
2005 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00002006 const Type *IdxTy;
2007 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00002008 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00002009 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00002010
2011 T = AI->getAllocatedType();
2012 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00002013 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00002014
2015 // If this GEP does not move the pointer across elements of the alloca
2016 // being split, then it does not needs to be rewritten.
2017 if (Idx == OldIdx)
2018 return;
2019
2020 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
2021 SmallVector<Value*, 8> NewArgs;
2022 NewArgs.push_back(Constant::getNullValue(i32Ty));
2023 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00002024 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
2025 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00002026 }
2027 Instruction *Val = NewElts[Idx];
2028 if (NewArgs.size() > 1) {
2029 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
2030 NewArgs.end(), "", GEPI);
2031 Val->takeName(GEPI);
2032 }
2033 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00002034 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002035 GEPI->replaceAllUsesWith(Val);
2036 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002037}
2038
2039/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2040/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00002041void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00002042 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00002043 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002044 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00002045 // appropriate type. The "Other" pointer is the pointer that goes to memory
2046 // that doesn't have anything to do with the alloca that we are promoting. For
2047 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00002048 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00002049 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00002050 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00002051 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00002052 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00002053 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00002054 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00002055 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00002056 }
2057 }
Bob Wilson78c50b82009-12-08 18:22:03 +00002058
Chris Lattnerd93afec2009-01-07 07:18:45 +00002059 // If there is an other pointer, we want to convert it to the same pointer
2060 // type as AI has, so we can GEP through it safely.
2061 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00002062 unsigned AddrSpace =
2063 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00002064
2065 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2066 // optimization, but it's also required to detect the corner case where
2067 // both pointer operands are referencing the same memory, and where
2068 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2069 // function is only called for mem intrinsics that access the whole
2070 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00002071 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson69743022011-01-13 20:59:44 +00002072
Bob Wilsona756b1d2010-01-19 04:32:48 +00002073 // Copying the alloca to itself is a no-op: just delete it.
2074 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2075 // This code will run twice for a no-op memcpy -- once for each operand.
2076 // Put only one reference to MI on the DeadInsts list.
2077 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
2078 E = DeadInsts.end(); I != E; ++I)
2079 if (*I == MI) return;
2080 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002081 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00002082 }
Bob Wilson69743022011-01-13 20:59:44 +00002083
Chris Lattnerd93afec2009-01-07 07:18:45 +00002084 // If the pointer is not the right type, insert a bitcast to the right
2085 // type.
Chris Lattner0238f8c2010-07-08 00:27:05 +00002086 const Type *NewTy =
2087 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson69743022011-01-13 20:59:44 +00002088
Chris Lattner0238f8c2010-07-08 00:27:05 +00002089 if (OtherPtr->getType() != NewTy)
2090 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002091 }
Bob Wilson69743022011-01-13 20:59:44 +00002092
Chris Lattnerd93afec2009-01-07 07:18:45 +00002093 // Process each element of the aggregate.
Bob Wilsonb742def2009-12-18 20:14:40 +00002094 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson69743022011-01-13 20:59:44 +00002095
Owen Anderson1d0be152009-08-13 21:58:54 +00002096 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00002097
2098 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2099 // If this is a memcpy/memmove, emit a GEP of the other element address.
2100 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002101 unsigned OtherEltAlign = MemAlignment;
Bob Wilson69743022011-01-13 20:59:44 +00002102
Bob Wilsona756b1d2010-01-19 04:32:48 +00002103 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002104 Value *Idx[2] = { Zero,
2105 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00002106 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00002107 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00002108 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00002109 uint64_t EltOffset;
2110 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002111 const Type *OtherTy = OtherPtrTy->getElementType();
2112 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002113 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
2114 } else {
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002115 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002116 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002117 }
Bob Wilson69743022011-01-13 20:59:44 +00002118
Chris Lattner1541e0f2009-03-04 19:20:50 +00002119 // The alignment of the other pointer is the guaranteed alignment of the
2120 // element, which is affected by both the known alignment of the whole
2121 // mem intrinsic and the alignment of the element. If the alignment of
2122 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2123 // known alignment is just 4 bytes.
2124 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00002125 }
Bob Wilson69743022011-01-13 20:59:44 +00002126
Chris Lattnerd93afec2009-01-07 07:18:45 +00002127 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00002128 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson69743022011-01-13 20:59:44 +00002129
Chris Lattnerd93afec2009-01-07 07:18:45 +00002130 // If we got down to a scalar, insert a load or store as appropriate.
2131 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00002132 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002133 if (SROADest) {
2134 // From Other to Alloca.
2135 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2136 new StoreInst(Elt, EltPtr, MI);
2137 } else {
2138 // From Alloca to Other.
2139 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2140 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2141 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00002142 continue;
2143 }
2144 assert(isa<MemSetInst>(MI));
Bob Wilson69743022011-01-13 20:59:44 +00002145
Chris Lattnerd93afec2009-01-07 07:18:45 +00002146 // If the stored element is zero (common case), just store a null
2147 // constant.
2148 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00002149 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002150 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00002151 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00002152 } else {
2153 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00002154 const Type *ValTy = EltTy->getScalarType();
2155
Chris Lattnerd93afec2009-01-07 07:18:45 +00002156 // Construct an integer with the right value.
2157 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2158 APInt OneVal(EltSize, CI->getZExtValue());
2159 APInt TotalVal(OneVal);
2160 // Set each byte.
2161 for (unsigned i = 0; 8*i < EltSize; ++i) {
2162 TotalVal = TotalVal.shl(8);
2163 TotalVal |= OneVal;
2164 }
Bob Wilson69743022011-01-13 20:59:44 +00002165
Chris Lattnerd93afec2009-01-07 07:18:45 +00002166 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002167 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00002168 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002169 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002170 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002171 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002172 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson69743022011-01-13 20:59:44 +00002173
Chris Lattnerd93afec2009-01-07 07:18:45 +00002174 // If the requested value was a vector constant, create it.
2175 if (EltTy != ValTy) {
2176 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
2177 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Chris Lattner2ca5c862011-02-15 00:14:00 +00002178 StoreVal = ConstantVector::get(Elts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002179 }
2180 }
2181 new StoreInst(StoreVal, EltPtr, MI);
2182 continue;
2183 }
2184 // Otherwise, if we're storing a byte variable, use a memset call for
2185 // this element.
2186 }
Bob Wilson69743022011-01-13 20:59:44 +00002187
Duncan Sands777d2302009-05-09 07:06:46 +00002188 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002189
Chris Lattner61db1f52010-12-26 22:57:41 +00002190 IRBuilder<> Builder(MI);
Bob Wilson69743022011-01-13 20:59:44 +00002191
Chris Lattnerd93afec2009-01-07 07:18:45 +00002192 // Finally, insert the meminst for this element.
Chris Lattner61db1f52010-12-26 22:57:41 +00002193 if (isa<MemSetInst>(MI)) {
2194 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2195 MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002196 } else {
Chris Lattner61db1f52010-12-26 22:57:41 +00002197 assert(isa<MemTransferInst>(MI));
2198 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2199 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson69743022011-01-13 20:59:44 +00002200
Chris Lattner61db1f52010-12-26 22:57:41 +00002201 if (isa<MemCpyInst>(MI))
2202 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2203 else
2204 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002205 }
Chris Lattner372dda82007-03-05 07:52:57 +00002206 }
Bob Wilsonb742def2009-12-18 20:14:40 +00002207 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00002208}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002209
Bob Wilson39fdd692009-12-04 21:57:37 +00002210/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002211/// overwrites the entire allocation. Extract out the pieces of the stored
2212/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002213void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002214 SmallVector<AllocaInst*, 32> &NewElts){
2215 // Extract each element out of the integer according to its structure offset
2216 // and store the element value to the individual alloca.
2217 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00002218 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002219 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002220
Chris Lattner70728532011-01-16 05:58:24 +00002221 IRBuilder<> Builder(SI);
2222
Eli Friedman41b33f42009-06-01 09:14:32 +00002223 // Handle tail padding by extending the operand
2224 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002225 SrcVal = Builder.CreateZExt(SrcVal,
2226 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002227
David Greene504c7d82010-01-05 01:27:09 +00002228 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00002229 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002230
2231 // There are two forms here: AI could be an array or struct. Both cases
2232 // have different ways to compute the element offset.
2233 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2234 const StructLayout *Layout = TD->getStructLayout(EltSTy);
Bob Wilson69743022011-01-13 20:59:44 +00002235
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002236 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2237 // Get the number of bits to shift SrcVal to get the value.
2238 const Type *FieldTy = EltSTy->getElementType(i);
2239 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson69743022011-01-13 20:59:44 +00002240
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002241 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00002242 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002243
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002244 Value *EltVal = SrcVal;
2245 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002246 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002247 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002248 }
Bob Wilson69743022011-01-13 20:59:44 +00002249
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002250 // Truncate down to an integer of the right size.
2251 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002252
Chris Lattner583dd602009-01-09 18:18:43 +00002253 // Ignore zero sized fields like {}, they obviously contain no data.
2254 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002255
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002256 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002257 EltVal = Builder.CreateTrunc(EltVal,
2258 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002259 Value *DestField = NewElts[i];
2260 if (EltVal->getType() == FieldTy) {
2261 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00002262 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002263 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002264 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002265 } else {
2266 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002267 DestField = Builder.CreateBitCast(DestField,
2268 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002269 }
2270 new StoreInst(EltVal, DestField, SI);
2271 }
Bob Wilson69743022011-01-13 20:59:44 +00002272
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002273 } else {
2274 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2275 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002276 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002277 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2278
2279 uint64_t Shift;
Bob Wilson69743022011-01-13 20:59:44 +00002280
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002281 if (TD->isBigEndian())
2282 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002283 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002284 Shift = 0;
Bob Wilson69743022011-01-13 20:59:44 +00002285
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002286 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00002287 // Ignore zero sized fields like {}, they obviously contain no data.
2288 if (ElementSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002289
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002290 Value *EltVal = SrcVal;
2291 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002292 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002293 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002294 }
Bob Wilson69743022011-01-13 20:59:44 +00002295
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002296 // Truncate down to an integer of the right size.
2297 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002298 EltVal = Builder.CreateTrunc(EltVal,
2299 IntegerType::get(SI->getContext(),
2300 ElementSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002301 Value *DestField = NewElts[i];
2302 if (EltVal->getType() == ArrayEltTy) {
2303 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002304 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00002305 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002306 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002307 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002308 } else {
2309 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002310 DestField = Builder.CreateBitCast(DestField,
2311 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002312 }
2313 new StoreInst(EltVal, DestField, SI);
Bob Wilson69743022011-01-13 20:59:44 +00002314
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002315 if (TD->isBigEndian())
2316 Shift -= ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002317 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002318 Shift += ElementOffset;
2319 }
2320 }
Bob Wilson69743022011-01-13 20:59:44 +00002321
Bob Wilsonb742def2009-12-18 20:14:40 +00002322 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002323}
2324
Bob Wilson39fdd692009-12-04 21:57:37 +00002325/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002326/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002327void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002328 SmallVector<AllocaInst*, 32> &NewElts) {
2329 // Extract each element out of the NewElts according to its structure offset
2330 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00002331 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002332 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002333
David Greene504c7d82010-01-05 01:27:09 +00002334 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00002335 << '\n');
Bob Wilson69743022011-01-13 20:59:44 +00002336
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002337 // There are two forms here: AI could be an array or struct. Both cases
2338 // have different ways to compute the element offset.
2339 const StructLayout *Layout = 0;
2340 uint64_t ArrayEltBitOffset = 0;
2341 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2342 Layout = TD->getStructLayout(EltSTy);
2343 } else {
2344 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002345 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002346 }
2347
2348 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00002349 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson69743022011-01-13 20:59:44 +00002350
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002351 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2352 // Load the value from the alloca. If the NewElt is an aggregate, cast
2353 // the pointer to an integer of the same size before doing the load.
2354 Value *SrcField = NewElts[i];
2355 const Type *FieldTy =
2356 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00002357 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002358
Chris Lattner583dd602009-01-09 18:18:43 +00002359 // Ignore zero sized fields like {}, they obviously contain no data.
2360 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002361
2362 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +00002363 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00002364 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2365 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00002366 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00002367 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002368 "", LI);
2369 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2370
2371 // If SrcField is a fp or vector of the right size but that isn't an
2372 // integer type, bitcast to an integer so we can shift it.
2373 if (SrcField->getType() != FieldIntTy)
2374 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2375
2376 // Zero extend the field to be the same size as the final alloca so that
2377 // we can shift and insert it.
2378 if (SrcField->getType() != ResultVal->getType())
2379 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson69743022011-01-13 20:59:44 +00002380
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002381 // Determine the number of bits to shift SrcField.
2382 uint64_t Shift;
2383 if (Layout) // Struct case.
2384 Shift = Layout->getElementOffsetInBits(i);
2385 else // Array case.
2386 Shift = i*ArrayEltBitOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002387
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002388 if (TD->isBigEndian())
2389 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson69743022011-01-13 20:59:44 +00002390
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002391 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002392 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002393 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2394 }
2395
Chris Lattner14952472010-06-27 07:58:26 +00002396 // Don't create an 'or x, 0' on the first iteration.
2397 if (!isa<Constant>(ResultVal) ||
2398 !cast<Constant>(ResultVal)->isNullValue())
2399 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2400 else
2401 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002402 }
Eli Friedman41b33f42009-06-01 09:14:32 +00002403
2404 // Handle tail padding by truncating the result
2405 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2406 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2407
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002408 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00002409 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002410}
2411
Duncan Sands3cb36502007-11-04 14:43:57 +00002412/// HasPadding - Return true if the specified type has any structure or
Bob Wilson694a10e2011-01-13 17:45:08 +00002413/// alignment padding in between the elements that would be split apart
2414/// by SROA; return false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00002415static bool HasPadding(const Type *Ty, const TargetData &TD) {
Bob Wilson694a10e2011-01-13 17:45:08 +00002416 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2417 Ty = ATy->getElementType();
2418 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00002419 }
Bob Wilson694a10e2011-01-13 17:45:08 +00002420
2421 // SROA currently handles only Arrays and Structs.
2422 const StructType *STy = cast<StructType>(Ty);
2423 const StructLayout *SL = TD.getStructLayout(STy);
2424 unsigned PrevFieldBitOffset = 0;
2425 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2426 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2427
2428 // Check to see if there is any padding between this element and the
2429 // previous one.
2430 if (i) {
2431 unsigned PrevFieldEnd =
2432 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2433 if (PrevFieldEnd < FieldBitOffset)
2434 return true;
2435 }
2436 PrevFieldBitOffset = FieldBitOffset;
2437 }
2438 // Check for tail padding.
2439 if (unsigned EltCount = STy->getNumElements()) {
2440 unsigned PrevFieldEnd = PrevFieldBitOffset +
2441 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2442 if (PrevFieldEnd < SL->getSizeInBits())
2443 return true;
2444 }
2445 return false;
Chris Lattner39a1c042007-05-30 06:11:23 +00002446}
Chris Lattner372dda82007-03-05 07:52:57 +00002447
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002448/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2449/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2450/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002451bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00002452 // Loop over the use list of the alloca. We can only transform it if all of
2453 // the users are safe to transform.
Chris Lattner6c95d242011-01-23 07:29:29 +00002454 AllocaInfo Info(AI);
Bob Wilson69743022011-01-13 20:59:44 +00002455
Chris Lattner6c95d242011-01-23 07:29:29 +00002456 isSafeForScalarRepl(AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00002457 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00002458 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002459 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002460 }
Bob Wilson69743022011-01-13 20:59:44 +00002461
Chris Lattner39a1c042007-05-30 06:11:23 +00002462 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2463 // source and destination, we have to be careful. In particular, the memcpy
2464 // could be moving around elements that live in structure padding of the LLVM
2465 // types, but may actually be used. In these cases, we refuse to promote the
2466 // struct.
2467 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00002468 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002469 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00002470
Chris Lattner396a0562011-01-16 17:46:19 +00002471 // If the alloca never has an access to just *part* of it, but is accessed
2472 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner7e9b4272011-01-16 06:18:28 +00002473 // the alloca instead of promoting each piece at a time and inserting fission
2474 // and fusion code.
2475 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2476 // If the struct/array just has one element, use basic SRoA.
2477 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2478 if (ST->getNumElements() > 1) return false;
2479 } else {
2480 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2481 return false;
2482 }
2483 }
Chris Lattner145c5322011-01-23 08:27:54 +00002484
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002485 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00002486}
Chris Lattnera1888942005-12-12 07:19:13 +00002487
Chris Lattner800de312008-02-29 07:03:13 +00002488
Chris Lattner79b3bd32007-04-25 06:40:51 +00002489
2490/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2491/// some part of a constant global variable. This intentionally only accepts
2492/// constant expressions because we don't can't rewrite arbitrary instructions.
2493static bool PointsToConstantGlobal(Value *V) {
2494 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2495 return GV->isConstant();
2496 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Bob Wilson69743022011-01-13 20:59:44 +00002497 if (CE->getOpcode() == Instruction::BitCast ||
Chris Lattner79b3bd32007-04-25 06:40:51 +00002498 CE->getOpcode() == Instruction::GetElementPtr)
2499 return PointsToConstantGlobal(CE->getOperand(0));
2500 return false;
2501}
2502
2503/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2504/// pointer to an alloca. Ignore any reads of the pointer, return false if we
2505/// see any stores or other unknown uses. If we see pointer arithmetic, keep
2506/// track of whether it moves the pointer (with isOffset) but otherwise traverse
2507/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
Nick Lewycky081f8002010-11-24 22:04:20 +00002508/// the alloca, and if the source pointer is a pointer to a constant global, we
Chris Lattner79b3bd32007-04-25 06:40:51 +00002509/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00002510static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00002511 bool isOffset) {
2512 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00002513 User *U = cast<Instruction>(*UI);
2514
Chris Lattner2e618492010-11-18 06:20:47 +00002515 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00002516 // Ignore non-volatile loads, they are always ok.
Chris Lattner2e618492010-11-18 06:20:47 +00002517 if (LI->isVolatile()) return false;
2518 continue;
2519 }
Bob Wilson69743022011-01-13 20:59:44 +00002520
Gabor Greif8a8a4352010-04-06 19:32:30 +00002521 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002522 // If uses of the bitcast are ok, we are ok.
2523 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
2524 return false;
2525 continue;
2526 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00002527 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002528 // If the GEP has all zero indices, it doesn't offset the pointer. If it
2529 // doesn't, it does.
2530 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
2531 isOffset || !GEP->hasAllZeroIndices()))
2532 return false;
2533 continue;
2534 }
Bob Wilson69743022011-01-13 20:59:44 +00002535
Chris Lattner62480652010-11-18 06:41:51 +00002536 if (CallSite CS = U) {
Nick Lewycky081f8002010-11-24 22:04:20 +00002537 // If this is the function being called then we treat it like a load and
2538 // ignore it.
2539 if (CS.isCallee(UI))
2540 continue;
Bob Wilson69743022011-01-13 20:59:44 +00002541
Duncan Sands53892102011-05-06 10:30:37 +00002542 // If this is a readonly/readnone call site, then we know it is just a
2543 // load (but one that potentially returns the value itself), so we can
2544 // ignore it if we know that the value isn't captured.
2545 unsigned ArgNo = CS.getArgumentNo(UI);
2546 if (CS.onlyReadsMemory() &&
2547 (CS.getInstruction()->use_empty() ||
2548 CS.paramHasAttr(ArgNo+1, Attribute::NoCapture)))
2549 continue;
2550
Chris Lattner62480652010-11-18 06:41:51 +00002551 // If this is being passed as a byval argument, the caller is making a
2552 // copy, so it is only a read of the alloca.
Chris Lattner62480652010-11-18 06:41:51 +00002553 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
2554 continue;
2555 }
Bob Wilson69743022011-01-13 20:59:44 +00002556
Chris Lattner79b3bd32007-04-25 06:40:51 +00002557 // If this is isn't our memcpy/memmove, reject it as something we can't
2558 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00002559 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2560 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00002561 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002562
Chris Lattner2e618492010-11-18 06:20:47 +00002563 // If the transfer is using the alloca as a source of the transfer, then
Chris Lattner2e29ebd2010-11-18 07:32:33 +00002564 // ignore it since it is a load (unless the transfer is volatile).
Chris Lattner2e618492010-11-18 06:20:47 +00002565 if (UI.getOperandNo() == 1) {
2566 if (MI->isVolatile()) return false;
2567 continue;
2568 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00002569
2570 // If we already have seen a copy, reject the second one.
2571 if (TheCopy) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002572
Chris Lattner79b3bd32007-04-25 06:40:51 +00002573 // If the pointer has been offset from the start of the alloca, we can't
2574 // safely handle this.
2575 if (isOffset) return false;
2576
2577 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00002578 if (UI.getOperandNo() != 0) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002579
Chris Lattner79b3bd32007-04-25 06:40:51 +00002580 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00002581 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002582 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002583
Chris Lattner79b3bd32007-04-25 06:40:51 +00002584 // Otherwise, the transform is safe. Remember the copy instruction.
2585 TheCopy = MI;
2586 }
2587 return true;
2588}
2589
2590/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2591/// modified by a copy from a constant global. If we can prove this, we can
2592/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00002593MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
2594 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00002595 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
2596 return TheCopy;
2597 return 0;
2598}