blob: beef127ef950f9fb29b3155be1f7e83f7d83bdec [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
Chris Lattnera001b662010-04-16 00:38:19 +0000296 // If we were able to find a vector type that can handle this with
297 // insert/extract elements, and if there was at least one use that had
298 // a vector type, promote this to a vector. We don't want to promote
299 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
300 // we just get a lot of insert/extracts. If at least one vector is
301 // involved, then we probably really do have a union of vector/array.
302 const Type *NewTy;
Cameron Zwarich5b93d3c2011-06-14 06:33:51 +0000303 if (ScalarKind == Vector) {
304 assert(VectorTy && "Missing type for vector scalar.");
Chris Lattnera001b662010-04-16 00:38:19 +0000305 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
306 << *VectorTy << '\n');
307 NewTy = VectorTy; // Use the vector type.
308 } else {
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000309 unsigned BitWidth = AllocaSize * 8;
Cameron Zwarich51797822011-06-13 21:44:40 +0000310 if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
311 !HadNonMemTransferAccess && !TD.fitsInLegalInteger(BitWidth))
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000312 return 0;
313
Chris Lattnera001b662010-04-16 00:38:19 +0000314 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
315 // Create and insert the integer alloca.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000316 NewTy = IntegerType::get(AI->getContext(), BitWidth);
Chris Lattnera001b662010-04-16 00:38:19 +0000317 }
318 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
319 ConvertUsesToScalar(AI, NewAI, 0);
320 return NewAI;
321}
322
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000323/// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
324/// (VectorTy) so far at the offset specified by Offset (which is specified in
325/// bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000326///
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000327/// There are three cases we handle here:
Chris Lattner4cc576b2010-04-16 00:24:57 +0000328/// 1) A union of vector types of the same size and potentially its elements.
329/// Here we turn element accesses into insert/extract element operations.
330/// This promotes a <4 x float> with a store of float to the third element
331/// into a <4 x float> that uses insert element.
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000332/// 2) A union of vector types with power-of-2 size differences, e.g. a float,
333/// <2 x float> and <4 x float>. Here we turn element accesses into insert
334/// and extract element operations, and <2 x float> accesses into a cast to
335/// <2 x double>, an extract, and a cast back to <2 x float>.
336/// 3) A fully general blob of memory, which we turn into some (potentially
Chris Lattner4cc576b2010-04-16 00:24:57 +0000337/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000338/// and stores would mutate the memory. We mark this by setting VectorTy
339/// to VoidTy.
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000340void ConvertToScalarInfo::MergeInTypeForLoadOrStore(const Type *In,
341 uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000342 // If we already decided to turn this into a blob of integer memory, there is
343 // nothing to be done.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000344 if (ScalarKind == Integer)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000345 return;
Bob Wilson69743022011-01-13 20:59:44 +0000346
Chris Lattner4cc576b2010-04-16 00:24:57 +0000347 // If this could be contributing to a vector, analyze it.
348
349 // If the In type is a vector that is the same size as the alloca, see if it
350 // matches the existing VecTy.
351 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000352 if (MergeInVectorType(VInTy, Offset))
Chris Lattner4cc576b2010-04-16 00:24:57 +0000353 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000354 } else if (In->isFloatTy() || In->isDoubleTy() ||
355 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
356 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
Cameron Zwarich9827b782011-03-29 05:19:52 +0000357 // Full width accesses can be ignored, because they can always be turned
358 // into bitcasts.
359 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
Cameron Zwarichdd689122011-06-13 21:44:31 +0000360 if (EltSize == AllocaSize)
Cameron Zwarich9827b782011-03-29 05:19:52 +0000361 return;
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000362
Chris Lattner4cc576b2010-04-16 00:24:57 +0000363 // If we're accessing something that could be an element of a vector, see
364 // if the implied vector agrees with what we already have and if Offset is
365 // compatible with it.
Cameron Zwarich96cc1d02011-06-09 01:45:33 +0000366 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Cameron Zwarichc4f78202011-06-09 01:52:44 +0000367 (!VectorTy || Offset * 8 < VectorTy->getPrimitiveSizeInBits())) {
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000368 if (!VectorTy) {
Cameron Zwarich51797822011-06-13 21:44:40 +0000369 ScalarKind = ImplicitVector;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000370 VectorTy = VectorType::get(In, AllocaSize/EltSize);
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000371 return;
372 }
373
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000374 unsigned CurrentEltSize = VectorTy->getElementType()
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000375 ->getPrimitiveSizeInBits()/8;
376 if (EltSize == CurrentEltSize)
377 return;
Cameron Zwarich344731c2011-04-20 21:48:38 +0000378
379 if (In->isIntegerTy() && isPowerOf2_32(AllocaSize / EltSize))
380 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000381 }
382 }
Bob Wilson69743022011-01-13 20:59:44 +0000383
Chris Lattner4cc576b2010-04-16 00:24:57 +0000384 // Otherwise, we have a case that we can't handle with an optimized vector
385 // form. We can still turn this into a large integer.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000386 ScalarKind = Integer;
387 VectorTy = 0;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000388}
389
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000390/// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
391/// returning true if the type was successfully merged and false otherwise.
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000392bool ConvertToScalarInfo::MergeInVectorType(const VectorType *VInTy,
393 uint64_t Offset) {
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000394 // TODO: Support nonzero offsets?
395 if (Offset != 0)
396 return false;
397
398 // Only allow vectors that are a power-of-2 away from the size of the alloca.
399 if (!isPowerOf2_64(AllocaSize / (VInTy->getBitWidth() / 8)))
400 return false;
401
402 // If this the first vector we see, remember the type so that we know the
403 // element size.
404 if (!VectorTy) {
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000405 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000406 VectorTy = VInTy;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000407 return true;
408 }
409
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000410 unsigned BitWidth = VectorTy->getBitWidth();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000411 unsigned InBitWidth = VInTy->getBitWidth();
412
413 // Vectors of the same size can be converted using a simple bitcast.
Cameron Zwarich51797822011-06-13 21:44:40 +0000414 if (InBitWidth == BitWidth && AllocaSize == (InBitWidth / 8)) {
415 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000416 return true;
Cameron Zwarich51797822011-06-13 21:44:40 +0000417 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000418
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000419 const Type *ElementTy = VectorTy->getElementType();
420 const Type *InElementTy = VInTy->getElementType();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000421
422 // Do not allow mixed integer and floating-point accesses from vectors of
423 // different sizes.
424 if (ElementTy->isFloatingPointTy() != InElementTy->isFloatingPointTy())
425 return false;
426
427 if (ElementTy->isFloatingPointTy()) {
428 // Only allow floating-point vectors of different sizes if they have the
429 // same element type.
430 // TODO: This could be loosened a bit, but would anything benefit?
431 if (ElementTy != InElementTy)
432 return false;
433
434 // There are no arbitrary-precision floating-point types, which limits the
435 // number of legal vector types with larger element types that we can form
436 // to bitcast and extract a subvector.
437 // TODO: We could support some more cases with mixed fp128 and double here.
438 if (!(BitWidth == 64 || BitWidth == 128) ||
439 !(InBitWidth == 64 || InBitWidth == 128))
440 return false;
441 } else {
442 assert(ElementTy->isIntegerTy() && "Vector elements must be either integer "
443 "or floating-point.");
444 unsigned BitWidth = ElementTy->getPrimitiveSizeInBits();
445 unsigned InBitWidth = InElementTy->getPrimitiveSizeInBits();
446
447 // Do not allow integer types smaller than a byte or types whose widths are
448 // not a multiple of a byte.
449 if (BitWidth < 8 || InBitWidth < 8 ||
450 BitWidth % 8 != 0 || InBitWidth % 8 != 0)
451 return false;
452 }
453
454 // Pick the largest of the two vector types.
Cameron Zwarich51797822011-06-13 21:44:40 +0000455 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000456 if (InBitWidth > BitWidth)
457 VectorTy = VInTy;
458
459 return true;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000460}
461
Chris Lattner4cc576b2010-04-16 00:24:57 +0000462/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
463/// its accesses to a single vector type, return true and set VecTy to
464/// the new type. If we could convert the alloca into a single promotable
465/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
466/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
467/// is the current offset from the base of the alloca being analyzed.
468///
469/// If we see at least one access to the value that is as a vector type, set the
470/// SawVec flag.
471bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
472 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
473 Instruction *User = cast<Instruction>(*UI);
Bob Wilson69743022011-01-13 20:59:44 +0000474
Chris Lattner4cc576b2010-04-16 00:24:57 +0000475 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
476 // Don't break volatile loads.
477 if (LI->isVolatile())
478 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000479 // Don't touch MMX operations.
480 if (LI->getType()->isX86_MMXTy())
481 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000482 HadNonMemTransferAccess = true;
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000483 MergeInTypeForLoadOrStore(LI->getType(), Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000484 continue;
485 }
Bob Wilson69743022011-01-13 20:59:44 +0000486
Chris Lattner4cc576b2010-04-16 00:24:57 +0000487 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
488 // Storing the pointer, not into the value?
489 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000490 // Don't touch MMX operations.
491 if (SI->getOperand(0)->getType()->isX86_MMXTy())
492 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000493 HadNonMemTransferAccess = true;
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000494 MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000495 continue;
496 }
Bob Wilson69743022011-01-13 20:59:44 +0000497
Chris Lattner4cc576b2010-04-16 00:24:57 +0000498 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000499 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000500 if (!CanConvertToScalar(BCI, Offset))
501 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000502 continue;
503 }
504
505 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
506 // If this is a GEP with a variable indices, we can't handle it.
507 if (!GEP->hasAllConstantIndices())
508 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000509
Chris Lattner4cc576b2010-04-16 00:24:57 +0000510 // Compute the offset that this GEP adds to the pointer.
511 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
512 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
513 &Indices[0], Indices.size());
514 // See if all uses can be converted.
515 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
516 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000517 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000518 HadNonMemTransferAccess = true;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000519 continue;
520 }
521
522 // If this is a constant sized memset of a constant value (e.g. 0) we can
523 // handle it.
524 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
525 // Store of constant value and constant size.
Chris Lattnera001b662010-04-16 00:38:19 +0000526 if (!isa<ConstantInt>(MSI->getValue()) ||
527 !isa<ConstantInt>(MSI->getLength()))
528 return false;
529 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000530 HadNonMemTransferAccess = true;
Chris Lattnera001b662010-04-16 00:38:19 +0000531 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000532 }
533
534 // If this is a memcpy or memmove into or out of the whole allocation, we
535 // can handle it like a load or store of the scalar type.
536 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000537 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
538 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
539 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000540
Chris Lattnera001b662010-04-16 00:38:19 +0000541 IsNotTrivial = true; // Can't be mem2reg'd.
542 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000543 }
Bob Wilson69743022011-01-13 20:59:44 +0000544
Chris Lattner4cc576b2010-04-16 00:24:57 +0000545 // Otherwise, we cannot handle this!
546 return false;
547 }
Bob Wilson69743022011-01-13 20:59:44 +0000548
Chris Lattner4cc576b2010-04-16 00:24:57 +0000549 return true;
550}
551
552/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
553/// directly. This happens when we are converting an "integer union" to a
554/// single integer scalar, or when we are converting a "vector union" to a
555/// vector with insert/extractelement instructions.
556///
557/// Offset is an offset from the original alloca, in bits that need to be
558/// shifted to the right. By the end of this, there should be no uses of Ptr.
559void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
560 uint64_t Offset) {
561 while (!Ptr->use_empty()) {
562 Instruction *User = cast<Instruction>(Ptr->use_back());
563
564 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
565 ConvertUsesToScalar(CI, NewAI, Offset);
566 CI->eraseFromParent();
567 continue;
568 }
569
570 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
571 // Compute the offset that this GEP adds to the pointer.
572 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
573 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
574 &Indices[0], Indices.size());
575 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
576 GEP->eraseFromParent();
577 continue;
578 }
Bob Wilson69743022011-01-13 20:59:44 +0000579
Chris Lattner61db1f52010-12-26 22:57:41 +0000580 IRBuilder<> Builder(User);
Bob Wilson69743022011-01-13 20:59:44 +0000581
Chris Lattner4cc576b2010-04-16 00:24:57 +0000582 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
583 // The load is a bit extract from NewAI shifted right by Offset bits.
584 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
585 Value *NewLoadVal
586 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
587 LI->replaceAllUsesWith(NewLoadVal);
588 LI->eraseFromParent();
589 continue;
590 }
Bob Wilson69743022011-01-13 20:59:44 +0000591
Chris Lattner4cc576b2010-04-16 00:24:57 +0000592 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
593 assert(SI->getOperand(0) != Ptr && "Consistency error!");
594 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
595 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
596 Builder);
597 Builder.CreateStore(New, NewAI);
598 SI->eraseFromParent();
Bob Wilson69743022011-01-13 20:59:44 +0000599
Chris Lattner4cc576b2010-04-16 00:24:57 +0000600 // If the load we just inserted is now dead, then the inserted store
601 // overwrote the entire thing.
602 if (Old->use_empty())
603 Old->eraseFromParent();
604 continue;
605 }
Bob Wilson69743022011-01-13 20:59:44 +0000606
Chris Lattner4cc576b2010-04-16 00:24:57 +0000607 // If this is a constant sized memset of a constant value (e.g. 0) we can
608 // transform it into a store of the expanded constant value.
609 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
610 assert(MSI->getRawDest() == Ptr && "Consistency error!");
611 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
612 if (NumBytes != 0) {
613 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson69743022011-01-13 20:59:44 +0000614
Chris Lattner4cc576b2010-04-16 00:24:57 +0000615 // Compute the value replicated the right number of times.
616 APInt APVal(NumBytes*8, Val);
617
618 // Splat the value if non-zero.
619 if (Val)
620 for (unsigned i = 1; i != NumBytes; ++i)
621 APVal |= APVal << 8;
Bob Wilson69743022011-01-13 20:59:44 +0000622
Chris Lattner4cc576b2010-04-16 00:24:57 +0000623 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
624 Value *New = ConvertScalar_InsertValue(
625 ConstantInt::get(User->getContext(), APVal),
626 Old, Offset, Builder);
627 Builder.CreateStore(New, NewAI);
Bob Wilson69743022011-01-13 20:59:44 +0000628
Chris Lattner4cc576b2010-04-16 00:24:57 +0000629 // If the load we just inserted is now dead, then the memset overwrote
630 // the entire thing.
631 if (Old->use_empty())
Bob Wilson69743022011-01-13 20:59:44 +0000632 Old->eraseFromParent();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000633 }
634 MSI->eraseFromParent();
635 continue;
636 }
637
638 // If this is a memcpy or memmove into or out of the whole allocation, we
639 // can handle it like a load or store of the scalar type.
640 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
641 assert(Offset == 0 && "must be store to start of alloca");
Bob Wilson69743022011-01-13 20:59:44 +0000642
Chris Lattner4cc576b2010-04-16 00:24:57 +0000643 // If the source and destination are both to the same alloca, then this is
644 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
645 // as appropriate.
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000646 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
Bob Wilson69743022011-01-13 20:59:44 +0000647
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000648 if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000649 // Dest must be OrigAI, change this to be a load from the original
650 // pointer (bitcasted), then a store to our new alloca.
651 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
652 Value *SrcPtr = MTI->getSource();
Mon P Wange90a6332010-12-23 01:41:32 +0000653 const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
654 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
655 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
656 AIPTy = PointerType::get(AIPTy->getElementType(),
657 SPTy->getAddressSpace());
658 }
659 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
660
Chris Lattner4cc576b2010-04-16 00:24:57 +0000661 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
662 SrcVal->setAlignment(MTI->getAlignment());
663 Builder.CreateStore(SrcVal, NewAI);
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000664 } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000665 // Src must be OrigAI, change this to be a load from NewAI then a store
666 // through the original dest pointer (bitcasted).
667 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
668 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
669
Mon P Wange90a6332010-12-23 01:41:32 +0000670 const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
671 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
672 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
673 AIPTy = PointerType::get(AIPTy->getElementType(),
674 DPTy->getAddressSpace());
675 }
676 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
677
Chris Lattner4cc576b2010-04-16 00:24:57 +0000678 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
679 NewStore->setAlignment(MTI->getAlignment());
680 } else {
681 // Noop transfer. Src == Dst
682 }
683
684 MTI->eraseFromParent();
685 continue;
686 }
Bob Wilson69743022011-01-13 20:59:44 +0000687
Chris Lattner4cc576b2010-04-16 00:24:57 +0000688 llvm_unreachable("Unsupported operation!");
689 }
690}
691
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000692/// getScaledElementType - Gets a scaled element type for a partial vector
Cameron Zwarich344731c2011-04-20 21:48:38 +0000693/// access of an alloca. The input types must be integer or floating-point
694/// scalar or vector types, and the resulting type is an integer, float or
695/// double.
696static const Type *getScaledElementType(const Type *Ty1, const Type *Ty2,
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000697 unsigned NewBitWidth) {
Cameron Zwarich344731c2011-04-20 21:48:38 +0000698 bool IsFP1 = Ty1->isFloatingPointTy() ||
699 (Ty1->isVectorTy() &&
700 cast<VectorType>(Ty1)->getElementType()->isFloatingPointTy());
701 bool IsFP2 = Ty2->isFloatingPointTy() ||
702 (Ty2->isVectorTy() &&
703 cast<VectorType>(Ty2)->getElementType()->isFloatingPointTy());
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000704
Cameron Zwarich344731c2011-04-20 21:48:38 +0000705 LLVMContext &Context = Ty1->getContext();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000706
Cameron Zwarich344731c2011-04-20 21:48:38 +0000707 // Prefer floating-point types over integer types, as integer types may have
708 // been created by earlier scalar replacement.
709 if (IsFP1 || IsFP2) {
710 if (NewBitWidth == 32)
711 return Type::getFloatTy(Context);
712 if (NewBitWidth == 64)
713 return Type::getDoubleTy(Context);
714 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000715
Cameron Zwarich344731c2011-04-20 21:48:38 +0000716 return Type::getIntNTy(Context, NewBitWidth);
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000717}
718
Mon P Wangddf9abf2011-04-14 08:04:01 +0000719/// CreateShuffleVectorCast - Creates a shuffle vector to convert one vector
720/// to another vector of the same element type which has the same allocation
721/// size but different primitive sizes (e.g. <3 x i32> and <4 x i32>).
722static Value *CreateShuffleVectorCast(Value *FromVal, const Type *ToType,
723 IRBuilder<> &Builder) {
724 const Type *FromType = FromVal->getType();
Mon P Wang481823a2011-04-14 19:20:42 +0000725 const VectorType *FromVTy = cast<VectorType>(FromType);
726 const VectorType *ToVTy = cast<VectorType>(ToType);
727 assert((ToVTy->getElementType() == FromVTy->getElementType()) &&
Mon P Wangddf9abf2011-04-14 08:04:01 +0000728 "Vectors must have the same element type");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000729 Value *UnV = UndefValue::get(FromType);
730 unsigned numEltsFrom = FromVTy->getNumElements();
731 unsigned numEltsTo = ToVTy->getNumElements();
732
733 SmallVector<Constant*, 3> Args;
Mon P Wang481823a2011-04-14 19:20:42 +0000734 const Type* Int32Ty = Builder.getInt32Ty();
Mon P Wangddf9abf2011-04-14 08:04:01 +0000735 unsigned minNumElts = std::min(numEltsFrom, numEltsTo);
736 unsigned i;
737 for (i=0; i != minNumElts; ++i)
Mon P Wang481823a2011-04-14 19:20:42 +0000738 Args.push_back(ConstantInt::get(Int32Ty, i));
Mon P Wangddf9abf2011-04-14 08:04:01 +0000739
740 if (i < numEltsTo) {
Mon P Wang481823a2011-04-14 19:20:42 +0000741 Constant* UnC = UndefValue::get(Int32Ty);
Mon P Wangddf9abf2011-04-14 08:04:01 +0000742 for (; i != numEltsTo; ++i)
743 Args.push_back(UnC);
744 }
745 Constant *Mask = ConstantVector::get(Args);
746 return Builder.CreateShuffleVector(FromVal, UnV, Mask, "tmpV");
747}
748
Chris Lattner4cc576b2010-04-16 00:24:57 +0000749/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
750/// or vector value FromVal, extracting the bits from the offset specified by
751/// Offset. This returns the value, which is of type ToType.
752///
753/// This happens when we are converting an "integer union" to a single
754/// integer scalar, or when we are converting a "vector union" to a vector with
755/// insert/extractelement instructions.
756///
757/// Offset is an offset from the original alloca, in bits that need to be
758/// shifted to the right.
759Value *ConvertToScalarInfo::
760ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
761 uint64_t Offset, IRBuilder<> &Builder) {
762 // If the load is of the whole new alloca, no conversion is needed.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000763 const Type *FromType = FromVal->getType();
764 if (FromType == ToType && Offset == 0)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000765 return FromVal;
766
767 // If the result alloca is a vector type, this is either an element
768 // access or a bitcast to another vector type of the same size.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000769 if (const VectorType *VTy = dyn_cast<VectorType>(FromType)) {
Cameron Zwarich0398d612011-06-08 22:08:31 +0000770 unsigned FromTypeSize = TD.getTypeAllocSize(FromType);
Cameron Zwarich9827b782011-03-29 05:19:52 +0000771 unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
Cameron Zwarich0398d612011-06-08 22:08:31 +0000772 if (FromTypeSize == ToTypeSize) {
Mon P Wangddf9abf2011-04-14 08:04:01 +0000773 // If the two types have the same primitive size, use a bit cast.
774 // Otherwise, it is two vectors with the same element type that has
775 // the same allocation size but different number of elements so use
776 // a shuffle vector.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000777 if (FromType->getPrimitiveSizeInBits() ==
778 ToType->getPrimitiveSizeInBits())
779 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000780 else
781 return CreateShuffleVectorCast(FromVal, ToType, Builder);
Mon P Wangbe0761c2011-04-13 21:40:02 +0000782 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000783
Cameron Zwarich0398d612011-06-08 22:08:31 +0000784 if (isPowerOf2_64(FromTypeSize / ToTypeSize)) {
Cameron Zwarich344731c2011-04-20 21:48:38 +0000785 assert(!(ToType->isVectorTy() && Offset != 0) && "Can't extract a value "
786 "of a smaller vector type at a nonzero offset.");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000787
Cameron Zwarich344731c2011-04-20 21:48:38 +0000788 const Type *CastElementTy = getScaledElementType(FromType, ToType,
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000789 ToTypeSize * 8);
Cameron Zwarich0398d612011-06-08 22:08:31 +0000790 unsigned NumCastVectorElements = FromTypeSize / ToTypeSize;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000791
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000792 LLVMContext &Context = FromVal->getContext();
793 const Type *CastTy = VectorType::get(CastElementTy,
794 NumCastVectorElements);
795 Value *Cast = Builder.CreateBitCast(FromVal, CastTy, "tmp");
Cameron Zwarich344731c2011-04-20 21:48:38 +0000796
797 unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
798 unsigned Elt = Offset/EltSize;
799 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000800 Value *Extract = Builder.CreateExtractElement(Cast, ConstantInt::get(
Cameron Zwarich344731c2011-04-20 21:48:38 +0000801 Type::getInt32Ty(Context), Elt), "tmp");
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000802 return Builder.CreateBitCast(Extract, ToType, "tmp");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000803 }
Chris Lattner4cc576b2010-04-16 00:24:57 +0000804
805 // Otherwise it must be an element access.
806 unsigned Elt = 0;
807 if (Offset) {
808 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
809 Elt = Offset/EltSize;
810 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
811 }
812 // Return the element extracted out of it.
813 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
814 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
815 if (V->getType() != ToType)
816 V = Builder.CreateBitCast(V, ToType, "tmp");
817 return V;
818 }
Bob Wilson69743022011-01-13 20:59:44 +0000819
Chris Lattner4cc576b2010-04-16 00:24:57 +0000820 // If ToType is a first class aggregate, extract out each of the pieces and
821 // use insertvalue's to form the FCA.
822 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
823 const StructLayout &Layout = *TD.getStructLayout(ST);
824 Value *Res = UndefValue::get(ST);
825 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
826 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
827 Offset+Layout.getElementOffsetInBits(i),
828 Builder);
829 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
830 }
831 return Res;
832 }
Bob Wilson69743022011-01-13 20:59:44 +0000833
Chris Lattner4cc576b2010-04-16 00:24:57 +0000834 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
835 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
836 Value *Res = UndefValue::get(AT);
837 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
838 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
839 Offset+i*EltSize, Builder);
840 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
841 }
842 return Res;
843 }
844
845 // Otherwise, this must be a union that was converted to an integer value.
846 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
847
848 // If this is a big-endian system and the load is narrower than the
849 // full alloca type, we need to do a shift to get the right bits.
850 int ShAmt = 0;
851 if (TD.isBigEndian()) {
852 // On big-endian machines, the lowest bit is stored at the bit offset
853 // from the pointer given by getTypeStoreSizeInBits. This matters for
854 // integers with a bitwidth that is not a multiple of 8.
855 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
856 TD.getTypeStoreSizeInBits(ToType) - Offset;
857 } else {
858 ShAmt = Offset;
859 }
860
861 // Note: we support negative bitwidths (with shl) which are not defined.
862 // We do this to support (f.e.) loads off the end of a structure where
863 // only some bits are used.
864 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
865 FromVal = Builder.CreateLShr(FromVal,
866 ConstantInt::get(FromVal->getType(),
867 ShAmt), "tmp");
868 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson69743022011-01-13 20:59:44 +0000869 FromVal = Builder.CreateShl(FromVal,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000870 ConstantInt::get(FromVal->getType(),
871 -ShAmt), "tmp");
872
873 // Finally, unconditionally truncate the integer to the right width.
874 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
875 if (LIBitWidth < NTy->getBitWidth())
876 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000877 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000878 LIBitWidth), "tmp");
879 else if (LIBitWidth > NTy->getBitWidth())
880 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000881 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000882 LIBitWidth), "tmp");
883
884 // If the result is an integer, this is a trunc or bitcast.
885 if (ToType->isIntegerTy()) {
886 // Should be done.
887 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
888 // Just do a bitcast, we know the sizes match up.
889 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
890 } else {
891 // Otherwise must be a pointer.
892 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
893 }
894 assert(FromVal->getType() == ToType && "Didn't convert right?");
895 return FromVal;
896}
897
898/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
899/// or vector value "Old" at the offset specified by Offset.
900///
901/// This happens when we are converting an "integer union" to a
902/// single integer scalar, or when we are converting a "vector union" to a
903/// vector with insert/extractelement instructions.
904///
905/// Offset is an offset from the original alloca, in bits that need to be
906/// shifted to the right.
907Value *ConvertToScalarInfo::
908ConvertScalar_InsertValue(Value *SV, Value *Old,
909 uint64_t Offset, IRBuilder<> &Builder) {
910 // Convert the stored type to the actual type, shift it left to insert
911 // then 'or' into place.
912 const Type *AllocaType = Old->getType();
913 LLVMContext &Context = Old->getContext();
914
915 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
916 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
917 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
Bob Wilson69743022011-01-13 20:59:44 +0000918
Chris Lattner4cc576b2010-04-16 00:24:57 +0000919 // Changing the whole vector with memset or with an access of a different
920 // vector type?
Mon P Wangbe0761c2011-04-13 21:40:02 +0000921 if (ValSize == VecSize) {
Mon P Wangddf9abf2011-04-14 08:04:01 +0000922 // If the two types have the same primitive size, use a bit cast.
923 // Otherwise, it is two vectors with the same element type that has
924 // the same allocation size but different number of elements so use
925 // a shuffle vector.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000926 if (VTy->getPrimitiveSizeInBits() ==
927 SV->getType()->getPrimitiveSizeInBits())
928 return Builder.CreateBitCast(SV, AllocaType, "tmp");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000929 else
930 return CreateShuffleVectorCast(SV, VTy, Builder);
Mon P Wangbe0761c2011-04-13 21:40:02 +0000931 }
Chris Lattner4cc576b2010-04-16 00:24:57 +0000932
Cameron Zwarich344731c2011-04-20 21:48:38 +0000933 if (isPowerOf2_64(VecSize / ValSize)) {
934 assert(!(SV->getType()->isVectorTy() && Offset != 0) && "Can't insert a "
935 "value of a smaller vector type at a nonzero offset.");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000936
Cameron Zwarich344731c2011-04-20 21:48:38 +0000937 const Type *CastElementTy = getScaledElementType(VTy, SV->getType(),
938 ValSize);
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000939 unsigned NumCastVectorElements = VecSize / ValSize;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000940
941 LLVMContext &Context = SV->getContext();
942 const Type *OldCastTy = VectorType::get(CastElementTy,
943 NumCastVectorElements);
944 Value *OldCast = Builder.CreateBitCast(Old, OldCastTy, "tmp");
945
946 Value *SVCast = Builder.CreateBitCast(SV, CastElementTy, "tmp");
Cameron Zwarich344731c2011-04-20 21:48:38 +0000947
948 unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
949 unsigned Elt = Offset/EltSize;
950 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000951 Value *Insert =
952 Builder.CreateInsertElement(OldCast, SVCast, ConstantInt::get(
Cameron Zwarich344731c2011-04-20 21:48:38 +0000953 Type::getInt32Ty(Context), Elt), "tmp");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000954 return Builder.CreateBitCast(Insert, AllocaType, "tmp");
955 }
956
Chris Lattner4cc576b2010-04-16 00:24:57 +0000957 // Must be an element insertion.
Cameron Zwarichc5c43b92011-04-20 21:48:34 +0000958 assert(SV->getType() == VTy->getElementType());
959 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner4cc576b2010-04-16 00:24:57 +0000960 unsigned Elt = Offset/EltSize;
Cameron Zwarichc5c43b92011-04-20 21:48:34 +0000961 return Builder.CreateInsertElement(Old, SV,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000962 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
963 "tmp");
Chris Lattner4cc576b2010-04-16 00:24:57 +0000964 }
Bob Wilson69743022011-01-13 20:59:44 +0000965
Chris Lattner4cc576b2010-04-16 00:24:57 +0000966 // If SV is a first-class aggregate value, insert each value recursively.
967 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
968 const StructLayout &Layout = *TD.getStructLayout(ST);
969 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
970 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000971 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000972 Offset+Layout.getElementOffsetInBits(i),
973 Builder);
974 }
975 return Old;
976 }
Bob Wilson69743022011-01-13 20:59:44 +0000977
Chris Lattner4cc576b2010-04-16 00:24:57 +0000978 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
979 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
980 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
981 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
982 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
983 }
984 return Old;
985 }
986
987 // If SV is a float, convert it to the appropriate integer type.
988 // If it is a pointer, do the same.
989 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
990 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
991 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
992 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
993 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
994 SV = Builder.CreateBitCast(SV,
995 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
996 else if (SV->getType()->isPointerTy())
997 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
998
999 // Zero extend or truncate the value if needed.
1000 if (SV->getType() != AllocaType) {
1001 if (SV->getType()->getPrimitiveSizeInBits() <
1002 AllocaType->getPrimitiveSizeInBits())
1003 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
1004 else {
1005 // Truncation may be needed if storing more than the alloca can hold
1006 // (undefined behavior).
1007 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
1008 SrcWidth = DestWidth;
1009 SrcStoreWidth = DestStoreWidth;
1010 }
1011 }
1012
1013 // If this is a big-endian system and the store is narrower than the
1014 // full alloca type, we need to do a shift to get the right bits.
1015 int ShAmt = 0;
1016 if (TD.isBigEndian()) {
1017 // On big-endian machines, the lowest bit is stored at the bit offset
1018 // from the pointer given by getTypeStoreSizeInBits. This matters for
1019 // integers with a bitwidth that is not a multiple of 8.
1020 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1021 } else {
1022 ShAmt = Offset;
1023 }
1024
1025 // Note: we support negative bitwidths (with shr) which are not defined.
1026 // We do this to support (f.e.) stores off the end of a structure where
1027 // only some bits in the structure are set.
1028 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1029 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1030 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
1031 ShAmt), "tmp");
1032 Mask <<= ShAmt;
1033 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1034 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
1035 -ShAmt), "tmp");
1036 Mask = Mask.lshr(-ShAmt);
1037 }
1038
1039 // Mask out the bits we are about to insert from the old value, and or
1040 // in the new bits.
1041 if (SrcWidth != DestWidth) {
1042 assert(DestWidth > SrcWidth);
1043 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1044 SV = Builder.CreateOr(Old, SV, "ins");
1045 }
1046 return SV;
1047}
1048
1049
1050//===----------------------------------------------------------------------===//
1051// SRoA Driver
1052//===----------------------------------------------------------------------===//
1053
1054
Chris Lattnered7b41e2003-05-27 15:45:27 +00001055bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +00001056 TD = getAnalysisIfAvailable<TargetData>();
1057
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001058 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +00001059
1060 // FIXME: ScalarRepl currently depends on TargetData more than it
1061 // theoretically needs to. It should be refactored in order to support
1062 // target-independent IR. Until this is done, just skip the actual
1063 // scalar-replacement portion of this pass.
1064 if (!TD) return Changed;
1065
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001066 while (1) {
1067 bool LocalChange = performScalarRepl(F);
1068 if (!LocalChange) break; // No need to repromote if no scalarrepl
1069 Changed = true;
1070 LocalChange = performPromotion(F);
1071 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
1072 }
Chris Lattner38aec322003-09-11 16:45:55 +00001073
1074 return Changed;
1075}
1076
Chris Lattnerd0f56132011-01-14 19:50:47 +00001077namespace {
1078class AllocaPromoter : public LoadAndStorePromoter {
1079 AllocaInst *AI;
1080public:
Cameron Zwarichc8279392011-05-24 03:10:43 +00001081 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1082 DbgDeclareInst *DD, DIBuilder *&DB)
1083 : LoadAndStorePromoter(Insts, S, DD, DB), AI(0) {}
Chris Lattnerd0f56132011-01-14 19:50:47 +00001084
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001085 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerd0f56132011-01-14 19:50:47 +00001086 // Remember which alloca we're promoting (for isInstInList).
1087 this->AI = AI;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001088 LoadAndStorePromoter::run(Insts);
Chris Lattnerd0f56132011-01-14 19:50:47 +00001089 AI->eraseFromParent();
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001090 }
1091
Chris Lattnerd0f56132011-01-14 19:50:47 +00001092 virtual bool isInstInList(Instruction *I,
1093 const SmallVectorImpl<Instruction*> &Insts) const {
1094 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1095 return LI->getOperand(0) == AI;
1096 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001097 }
Chris Lattnerd0f56132011-01-14 19:50:47 +00001098};
1099} // end anon namespace
Chris Lattner38aec322003-09-11 16:45:55 +00001100
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001101/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1102/// subsequently loaded can be rewritten to load both input pointers and then
1103/// select between the result, allowing the load of the alloca to be promoted.
1104/// From this:
1105/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1106/// %V = load i32* %P2
1107/// to:
1108/// %V1 = load i32* %Alloca -> will be mem2reg'd
1109/// %V2 = load i32* %Other
Chris Lattnere3357862011-01-24 01:07:11 +00001110/// %V = select i1 %cond, i32 %V1, i32 %V2
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001111///
1112/// We can do this to a select if its only uses are loads and if the operand to
1113/// the select can be loaded unconditionally.
1114static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
1115 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1116 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1117
1118 for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1119 UI != UE; ++UI) {
1120 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1121 if (LI == 0 || LI->isVolatile()) return false;
1122
Chris Lattnere3357862011-01-24 01:07:11 +00001123 // Both operands to the select need to be dereferencable, either absolutely
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001124 // (e.g. allocas) or at this point because we can see other accesses to it.
1125 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1126 LI->getAlignment(), TD))
1127 return false;
1128 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1129 LI->getAlignment(), TD))
1130 return false;
1131 }
1132
1133 return true;
1134}
1135
Chris Lattnere3357862011-01-24 01:07:11 +00001136/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1137/// subsequently loaded can be rewritten to load both input pointers in the pred
1138/// blocks and then PHI the results, allowing the load of the alloca to be
1139/// promoted.
1140/// From this:
1141/// %P2 = phi [i32* %Alloca, i32* %Other]
1142/// %V = load i32* %P2
1143/// to:
1144/// %V1 = load i32* %Alloca -> will be mem2reg'd
1145/// ...
1146/// %V2 = load i32* %Other
1147/// ...
1148/// %V = phi [i32 %V1, i32 %V2]
1149///
1150/// We can do this to a select if its only uses are loads and if the operand to
1151/// the select can be loaded unconditionally.
1152static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
1153 // For now, we can only do this promotion if the load is in the same block as
1154 // the PHI, and if there are no stores between the phi and load.
1155 // TODO: Allow recursive phi users.
1156 // TODO: Allow stores.
1157 BasicBlock *BB = PN->getParent();
1158 unsigned MaxAlign = 0;
1159 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1160 UI != UE; ++UI) {
1161 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1162 if (LI == 0 || LI->isVolatile()) return false;
1163
1164 // For now we only allow loads in the same block as the PHI. This is a
1165 // common case that happens when instcombine merges two loads through a PHI.
1166 if (LI->getParent() != BB) return false;
1167
1168 // Ensure that there are no instructions between the PHI and the load that
1169 // could store.
1170 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1171 if (BBI->mayWriteToMemory())
1172 return false;
1173
1174 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1175 }
1176
1177 // Okay, we know that we have one or more loads in the same block as the PHI.
1178 // We can transform this if it is safe to push the loads into the predecessor
1179 // blocks. The only thing to watch out for is that we can't put a possibly
1180 // trapping load in the predecessor if it is a critical edge.
1181 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1182 BasicBlock *Pred = PN->getIncomingBlock(i);
1183
1184 // If the predecessor has a single successor, then the edge isn't critical.
1185 if (Pred->getTerminator()->getNumSuccessors() == 1)
1186 continue;
1187
1188 Value *InVal = PN->getIncomingValue(i);
1189
1190 // If the InVal is an invoke in the pred, we can't put a load on the edge.
1191 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
1192 if (II->getParent() == Pred)
1193 return false;
1194
1195 // If this pointer is always safe to load, or if we can prove that there is
1196 // already a load in the block, then we can move the load to the pred block.
1197 if (InVal->isDereferenceablePointer() ||
1198 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1199 continue;
1200
1201 return false;
1202 }
1203
1204 return true;
1205}
1206
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001207
1208/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1209/// direct (non-volatile) loads and stores to it. If the alloca is close but
1210/// not quite there, this will transform the code to allow promotion. As such,
1211/// it is a non-pure predicate.
1212static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
1213 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1214 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1215
1216 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1217 UI != UE; ++UI) {
1218 User *U = *UI;
1219 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1220 if (LI->isVolatile())
1221 return false;
1222 continue;
1223 }
1224
1225 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1226 if (SI->getOperand(0) == AI || SI->isVolatile())
1227 return false; // Don't allow a store OF the AI, only INTO the AI.
1228 continue;
1229 }
1230
1231 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1232 // If the condition being selected on is a constant, fold the select, yes
1233 // this does (rarely) happen early on.
1234 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1235 Value *Result = SI->getOperand(1+CI->isZero());
1236 SI->replaceAllUsesWith(Result);
1237 SI->eraseFromParent();
1238
1239 // This is very rare and we just scrambled the use list of AI, start
1240 // over completely.
1241 return tryToMakeAllocaBePromotable(AI, TD);
1242 }
1243
1244 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1245 // loads, then we can transform this by rewriting the select.
1246 if (!isSafeSelectToSpeculate(SI, TD))
1247 return false;
1248
1249 InstsToRewrite.insert(SI);
1250 continue;
1251 }
1252
Chris Lattnere3357862011-01-24 01:07:11 +00001253 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1254 if (PN->use_empty()) { // Dead PHIs can be stripped.
1255 InstsToRewrite.insert(PN);
1256 continue;
1257 }
1258
1259 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1260 // in the pred blocks, then we can transform this by rewriting the PHI.
1261 if (!isSafePHIToSpeculate(PN, TD))
1262 return false;
1263
1264 InstsToRewrite.insert(PN);
1265 continue;
1266 }
1267
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001268 return false;
1269 }
1270
1271 // If there are no instructions to rewrite, then all uses are load/stores and
1272 // we're done!
1273 if (InstsToRewrite.empty())
1274 return true;
1275
1276 // If we have instructions that need to be rewritten for this to be promotable
1277 // take care of it now.
1278 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
Chris Lattnere3357862011-01-24 01:07:11 +00001279 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1280 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1281 // loads with a new select.
1282 while (!SI->use_empty()) {
1283 LoadInst *LI = cast<LoadInst>(SI->use_back());
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001284
Chris Lattnere3357862011-01-24 01:07:11 +00001285 IRBuilder<> Builder(LI);
1286 LoadInst *TrueLoad =
1287 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1288 LoadInst *FalseLoad =
1289 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".t");
1290
1291 // Transfer alignment and TBAA info if present.
1292 TrueLoad->setAlignment(LI->getAlignment());
1293 FalseLoad->setAlignment(LI->getAlignment());
1294 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1295 TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1296 FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1297 }
1298
1299 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1300 V->takeName(LI);
1301 LI->replaceAllUsesWith(V);
1302 LI->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001303 }
Chris Lattnere3357862011-01-24 01:07:11 +00001304
1305 // Now that all the loads are gone, the select is gone too.
1306 SI->eraseFromParent();
1307 continue;
1308 }
1309
1310 // Otherwise, we have a PHI node which allows us to push the loads into the
1311 // predecessors.
1312 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1313 if (PN->use_empty()) {
1314 PN->eraseFromParent();
1315 continue;
1316 }
1317
1318 const Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
Jay Foad3ecfc862011-03-30 11:28:46 +00001319 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1320 PN->getName()+".ld", PN);
Chris Lattnere3357862011-01-24 01:07:11 +00001321
1322 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1323 // matter which one we get and if any differ, it doesn't matter.
1324 LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1325 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1326 unsigned Align = SomeLoad->getAlignment();
1327
1328 // Rewrite all loads of the PN to use the new PHI.
1329 while (!PN->use_empty()) {
1330 LoadInst *LI = cast<LoadInst>(PN->use_back());
1331 LI->replaceAllUsesWith(NewPN);
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001332 LI->eraseFromParent();
1333 }
1334
Chris Lattnere3357862011-01-24 01:07:11 +00001335 // Inject loads into all of the pred blocks. Keep track of which blocks we
1336 // insert them into in case we have multiple edges from the same block.
1337 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1338
1339 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1340 BasicBlock *Pred = PN->getIncomingBlock(i);
1341 LoadInst *&Load = InsertedLoads[Pred];
1342 if (Load == 0) {
1343 Load = new LoadInst(PN->getIncomingValue(i),
1344 PN->getName() + "." + Pred->getName(),
1345 Pred->getTerminator());
1346 Load->setAlignment(Align);
1347 if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1348 }
1349
1350 NewPN->addIncoming(Load, Pred);
1351 }
1352
1353 PN->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001354 }
1355
1356 ++NumAdjusted;
1357 return true;
1358}
1359
Chris Lattner38aec322003-09-11 16:45:55 +00001360bool SROA::performPromotion(Function &F) {
1361 std::vector<AllocaInst*> Allocas;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001362 DominatorTree *DT = 0;
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001363 if (HasDomTree)
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001364 DT = &getAnalysis<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +00001365
Chris Lattner02a3be02003-09-20 14:39:18 +00001366 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +00001367
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001368 bool Changed = false;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001369 SmallVector<Instruction*, 64> Insts;
Cameron Zwarichc8279392011-05-24 03:10:43 +00001370 DIBuilder *DIB = 0;
Chris Lattner38aec322003-09-11 16:45:55 +00001371 while (1) {
1372 Allocas.clear();
1373
1374 // Find allocas that are safe to promote, by looking at all instructions in
1375 // the entry node
1376 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1377 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001378 if (tryToMakeAllocaBePromotable(AI, TD))
Chris Lattner38aec322003-09-11 16:45:55 +00001379 Allocas.push_back(AI);
1380
1381 if (Allocas.empty()) break;
1382
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001383 if (HasDomTree)
Cameron Zwarich419e8a62011-01-17 17:38:41 +00001384 PromoteMemToReg(Allocas, *DT);
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001385 else {
1386 SSAUpdater SSA;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001387 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1388 AllocaInst *AI = Allocas[i];
1389
1390 // Build list of instructions to promote.
1391 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1392 UI != E; ++UI)
1393 Insts.push_back(cast<Instruction>(*UI));
Cameron Zwarichc8279392011-05-24 03:10:43 +00001394
1395 DbgDeclareInst *DDI = FindAllocaDbgDeclare(AI);
Cameron Zwarich13a16082011-05-24 06:00:08 +00001396 if (DDI && !DIB)
1397 DIB = new DIBuilder(*AI->getParent()->getParent()->getParent());
Cameron Zwarichc8279392011-05-24 03:10:43 +00001398 AllocaPromoter(Insts, SSA, DDI, DIB).run(AI, Insts);
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001399 Insts.clear();
1400 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001401 }
Chris Lattner38aec322003-09-11 16:45:55 +00001402 NumPromoted += Allocas.size();
1403 Changed = true;
1404 }
1405
Cameron Zwarichc8279392011-05-24 03:10:43 +00001406 // FIXME: Is there a better way to handle the lazy initialization of DIB
1407 // so that there doesn't need to be an explicit delete?
1408 delete DIB;
1409
Chris Lattner38aec322003-09-11 16:45:55 +00001410 return Changed;
1411}
1412
Chris Lattner4cc576b2010-04-16 00:24:57 +00001413
Bob Wilson3992feb2010-02-03 17:23:56 +00001414/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1415/// SROA. It must be a struct or array type with a small number of elements.
1416static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
1417 const Type *T = AI->getAllocatedType();
1418 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +00001419 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +00001420 return ST->getNumElements() <= 32;
1421 // Arrays are much less likely to be safe for SROA; only consider
1422 // them if they are very small.
1423 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1424 return AT->getNumElements() <= 8;
1425 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +00001426}
1427
Chris Lattnerc4472072010-04-15 23:50:26 +00001428
Chris Lattner38aec322003-09-11 16:45:55 +00001429// performScalarRepl - This algorithm is a simple worklist driven algorithm,
1430// which runs on all of the malloc/alloca instructions in the function, removing
1431// them if they are only used by getelementptr instructions.
1432//
1433bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001434 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +00001435
Chris Lattner31d80102010-04-15 21:59:20 +00001436 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +00001437 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001438 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +00001439 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +00001440 WorkList.push_back(A);
1441
1442 // Process the worklist
1443 bool Changed = false;
1444 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001445 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001446 WorkList.pop_back();
Bob Wilson69743022011-01-13 20:59:44 +00001447
Chris Lattneradd2bd72006-12-22 23:14:42 +00001448 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1449 // with unused elements.
1450 if (AI->use_empty()) {
1451 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +00001452 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +00001453 continue;
1454 }
Chris Lattner7809ecd2009-02-03 01:30:09 +00001455
1456 // If this alloca is impossible for us to promote, reject it early.
1457 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1458 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001459
Chris Lattner79b3bd32007-04-25 06:40:51 +00001460 // Check to see if this allocation is only modified by a memcpy/memmove from
1461 // a constant global. If this is the case, we can change all users to use
1462 // the constant global instead. This is commonly produced by the CFE by
1463 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1464 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +00001465 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +00001466 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
1467 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +00001468 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001469 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +00001470 TheCopy->eraseFromParent(); // Don't mutate the global.
1471 AI->eraseFromParent();
1472 ++NumGlobals;
1473 Changed = true;
1474 continue;
1475 }
Bob Wilson69743022011-01-13 20:59:44 +00001476
Chris Lattner7809ecd2009-02-03 01:30:09 +00001477 // Check to see if we can perform the core SROA transformation. We cannot
1478 // transform the allocation instruction if it is an array allocation
1479 // (allocations OF arrays are ok though), and an allocation of a scalar
1480 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +00001481 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +00001482
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +00001483 // Do not promote [0 x %struct].
1484 if (AllocaSize == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001485
Chris Lattner31d80102010-04-15 21:59:20 +00001486 // Do not promote any struct whose size is too big.
1487 if (AllocaSize > SRThreshold) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001488
Bob Wilson3992feb2010-02-03 17:23:56 +00001489 // If the alloca looks like a good candidate for scalar replacement, and if
1490 // all its users can be transformed, then split up the aggregate into its
1491 // separate elements.
1492 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1493 DoScalarReplacement(AI, WorkList);
1494 Changed = true;
1495 continue;
1496 }
1497
Chris Lattner6e733d32009-01-28 20:16:43 +00001498 // If we can turn this aggregate value (potentially with casts) into a
1499 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001500 // IsNotTrivial tracks whether this is something that mem2reg could have
1501 // promoted itself. If so, we don't want to transform it needlessly. Note
1502 // that we can't just check based on the type: the alloca may be of an i32
1503 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +00001504 if (AllocaInst *NewAI =
1505 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001506 NewAI->takeName(AI);
1507 AI->eraseFromParent();
1508 ++NumConverted;
1509 Changed = true;
1510 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001511 }
1512
Chris Lattner7809ecd2009-02-03 01:30:09 +00001513 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +00001514 }
1515
1516 return Changed;
1517}
Chris Lattner5e062a12003-05-30 04:15:41 +00001518
Chris Lattnera10b29b2007-04-25 05:02:56 +00001519/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1520/// predicate, do SROA now.
Bob Wilson69743022011-01-13 20:59:44 +00001521void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001522 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +00001523 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +00001524 SmallVector<AllocaInst*, 32> ElementAllocas;
1525 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1526 ElementAllocas.reserve(ST->getNumContainedTypes());
1527 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Bob Wilson69743022011-01-13 20:59:44 +00001528 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +00001529 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001530 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001531 ElementAllocas.push_back(NA);
1532 WorkList.push_back(NA); // Add to worklist for recursive processing
1533 }
1534 } else {
1535 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1536 ElementAllocas.reserve(AT->getNumElements());
1537 const Type *ElTy = AT->getElementType();
1538 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +00001539 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001540 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001541 ElementAllocas.push_back(NA);
1542 WorkList.push_back(NA); // Add to worklist for recursive processing
1543 }
1544 }
1545
Bob Wilsonb742def2009-12-18 20:14:40 +00001546 // Now that we have created the new alloca instructions, rewrite all the
1547 // uses of the old alloca.
1548 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +00001549
Bob Wilsonb742def2009-12-18 20:14:40 +00001550 // Now erase any instructions that were made dead while rewriting the alloca.
1551 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +00001552 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +00001553
Dan Gohmanfe601042010-06-22 15:08:57 +00001554 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +00001555}
Chris Lattnera59adc42009-12-14 05:11:02 +00001556
Bob Wilsonb742def2009-12-18 20:14:40 +00001557/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1558/// recursively including all their operands that become trivially dead.
1559void SROA::DeleteDeadInstructions() {
1560 while (!DeadInsts.empty()) {
1561 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +00001562
Bob Wilsonb742def2009-12-18 20:14:40 +00001563 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1564 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1565 // Zero out the operand and see if it becomes trivially dead.
1566 // (But, don't add allocas to the dead instruction list -- they are
1567 // already on the worklist and will be deleted separately.)
1568 *OI = 0;
1569 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1570 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +00001571 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001572
1573 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +00001574 }
Chris Lattnera59adc42009-12-14 05:11:02 +00001575}
Bob Wilson69743022011-01-13 20:59:44 +00001576
Bob Wilsonb742def2009-12-18 20:14:40 +00001577/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1578/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001579/// the Info parameter. Offset indicates the position within AI that is
1580/// referenced by this instruction.
Chris Lattner6c95d242011-01-23 07:29:29 +00001581void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001582 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001583 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1584 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +00001585
Bob Wilsonb742def2009-12-18 20:14:40 +00001586 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Chris Lattner6c95d242011-01-23 07:29:29 +00001587 isSafeForScalarRepl(BC, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001588 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001589 uint64_t GEPOffset = Offset;
Chris Lattner6c95d242011-01-23 07:29:29 +00001590 isSafeGEP(GEPI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001591 if (!Info.isUnsafe)
Chris Lattner6c95d242011-01-23 07:29:29 +00001592 isSafeForScalarRepl(GEPI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001593 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001594 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001595 if (Length == 0)
1596 return MarkUnsafe(Info, User);
Chris Lattner6c95d242011-01-23 07:29:29 +00001597 isSafeMemAccess(Offset, Length->getZExtValue(), 0,
Chris Lattner145c5322011-01-23 08:27:54 +00001598 UI.getOperandNo() == 0, Info, MI,
1599 true /*AllowWholeAccess*/);
Bob Wilsonb742def2009-12-18 20:14:40 +00001600 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001601 if (LI->isVolatile())
1602 return MarkUnsafe(Info, User);
1603 const Type *LIType = LI->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001604 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001605 LIType, false, Info, LI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001606 Info.hasALoadOrStore = true;
1607
Bob Wilsonb742def2009-12-18 20:14:40 +00001608 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1609 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001610 if (SI->isVolatile() || SI->getOperand(0) == I)
1611 return MarkUnsafe(Info, User);
1612
1613 const Type *SIType = SI->getOperand(0)->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001614 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001615 SIType, true, Info, SI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001616 Info.hasALoadOrStore = true;
Chris Lattner145c5322011-01-23 08:27:54 +00001617 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1618 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1619 } else {
1620 return MarkUnsafe(Info, User);
1621 }
1622 if (Info.isUnsafe) return;
1623 }
1624}
1625
1626
1627/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1628/// derived from the alloca, we can often still split the alloca into elements.
1629/// This is useful if we have a large alloca where one element is phi'd
1630/// together somewhere: we can SRoA and promote all the other elements even if
1631/// we end up not being able to promote this one.
1632///
1633/// All we require is that the uses of the PHI do not index into other parts of
1634/// the alloca. The most important use case for this is single load and stores
1635/// that are PHI'd together, which can happen due to code sinking.
1636void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1637 AllocaInfo &Info) {
1638 // If we've already checked this PHI, don't do it again.
1639 if (PHINode *PN = dyn_cast<PHINode>(I))
1640 if (!Info.CheckedPHIs.insert(PN))
1641 return;
1642
1643 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1644 Instruction *User = cast<Instruction>(*UI);
1645
1646 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1647 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1648 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1649 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1650 // but would have to prove that we're staying inside of an element being
1651 // promoted.
1652 if (!GEPI->hasAllZeroIndices())
1653 return MarkUnsafe(Info, User);
1654 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1655 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1656 if (LI->isVolatile())
1657 return MarkUnsafe(Info, User);
1658 const Type *LIType = LI->getType();
1659 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1660 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1661 Info.hasALoadOrStore = true;
1662
1663 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1664 // Store is ok if storing INTO the pointer, not storing the pointer
1665 if (SI->isVolatile() || SI->getOperand(0) == I)
1666 return MarkUnsafe(Info, User);
1667
1668 const Type *SIType = SI->getOperand(0)->getType();
1669 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1670 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1671 Info.hasALoadOrStore = true;
1672 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1673 isSafePHISelectUseForScalarRepl(User, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001674 } else {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001675 return MarkUnsafe(Info, User);
Bob Wilsonb742def2009-12-18 20:14:40 +00001676 }
1677 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001678 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001679}
Bob Wilson39c88a62009-12-17 18:34:24 +00001680
Bob Wilsonb742def2009-12-18 20:14:40 +00001681/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1682/// replacement. It is safe when all the indices are constant, in-bounds
1683/// references, and when the resulting offset corresponds to an element within
1684/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001685/// return, Offset is adjusted as specified by the GEP indices.
Chris Lattner6c95d242011-01-23 07:29:29 +00001686void SROA::isSafeGEP(GetElementPtrInst *GEPI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001687 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001688 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1689 if (GEPIt == E)
1690 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001691
Chris Lattner88e6dc82008-08-23 05:21:06 +00001692 // Walk through the GEP type indices, checking the types that this indexes
1693 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001694 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001695 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001696 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001697 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001698
Bob Wilsonb742def2009-12-18 20:14:40 +00001699 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1700 if (!IdxVal)
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001701 return MarkUnsafe(Info, GEPI);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001702 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001703
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001704 // Compute the offset due to this GEP and check if the alloca has a
1705 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001706 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1707 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1708 &Indices[0], Indices.size());
Chris Lattner6c95d242011-01-23 07:29:29 +00001709 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001710 MarkUnsafe(Info, GEPI);
Chris Lattner5e062a12003-05-30 04:15:41 +00001711}
1712
Bob Wilson704d1342011-01-13 17:45:11 +00001713/// isHomogeneousAggregate - Check if type T is a struct or array containing
1714/// elements of the same type (which is always true for arrays). If so,
1715/// return true with NumElts and EltTy set to the number of elements and the
1716/// element type, respectively.
1717static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1718 const Type *&EltTy) {
1719 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1720 NumElts = AT->getNumElements();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001721 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
Bob Wilson704d1342011-01-13 17:45:11 +00001722 return true;
1723 }
1724 if (const StructType *ST = dyn_cast<StructType>(T)) {
1725 NumElts = ST->getNumContainedTypes();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001726 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
Bob Wilson704d1342011-01-13 17:45:11 +00001727 for (unsigned n = 1; n < NumElts; ++n) {
1728 if (ST->getContainedType(n) != EltTy)
1729 return false;
1730 }
1731 return true;
1732 }
1733 return false;
1734}
1735
1736/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1737/// "homogeneous" aggregates with the same element type and number of elements.
1738static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1739 if (T1 == T2)
1740 return true;
1741
1742 unsigned NumElts1, NumElts2;
1743 const Type *EltTy1, *EltTy2;
1744 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1745 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1746 NumElts1 == NumElts2 &&
1747 EltTy1 == EltTy2)
1748 return true;
1749
1750 return false;
1751}
1752
Bob Wilsonb742def2009-12-18 20:14:40 +00001753/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1754/// alloca or has an offset and size that corresponds to a component element
1755/// within it. The offset checked here may have been formed from a GEP with a
1756/// pointer bitcasted to a different type.
Chris Lattner145c5322011-01-23 08:27:54 +00001757///
1758/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1759/// unit. If false, it only allows accesses known to be in a single element.
Chris Lattner6c95d242011-01-23 07:29:29 +00001760void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001761 const Type *MemOpType, bool isStore,
Chris Lattner145c5322011-01-23 08:27:54 +00001762 AllocaInfo &Info, Instruction *TheAccess,
1763 bool AllowWholeAccess) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001764 // Check if this is a load/store of the entire alloca.
Chris Lattner145c5322011-01-23 08:27:54 +00001765 if (Offset == 0 && AllowWholeAccess &&
Chris Lattner6c95d242011-01-23 07:29:29 +00001766 MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
Bob Wilson704d1342011-01-13 17:45:11 +00001767 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1768 // loads/stores (which are essentially the same as the MemIntrinsics with
1769 // regard to copying padding between elements). But, if an alloca is
1770 // flagged as both a source and destination of such operations, we'll need
1771 // to check later for padding between elements.
1772 if (!MemOpType || MemOpType->isIntegerTy()) {
1773 if (isStore)
1774 Info.isMemCpyDst = true;
1775 else
1776 Info.isMemCpySrc = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001777 return;
1778 }
Bob Wilson704d1342011-01-13 17:45:11 +00001779 // This is also safe for references using a type that is compatible with
1780 // the type of the alloca, so that loads/stores can be rewritten using
1781 // insertvalue/extractvalue.
Chris Lattner6c95d242011-01-23 07:29:29 +00001782 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
Chris Lattner7e9b4272011-01-16 06:18:28 +00001783 Info.hasSubelementAccess = true;
Bob Wilson704d1342011-01-13 17:45:11 +00001784 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001785 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001786 }
1787 // Check if the offset/size correspond to a component within the alloca type.
Chris Lattner6c95d242011-01-23 07:29:29 +00001788 const Type *T = Info.AI->getAllocatedType();
Chris Lattner7e9b4272011-01-16 06:18:28 +00001789 if (TypeHasComponent(T, Offset, MemSize)) {
1790 Info.hasSubelementAccess = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001791 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001792 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001793
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001794 return MarkUnsafe(Info, TheAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +00001795}
1796
1797/// TypeHasComponent - Return true if T has a component type with the
1798/// specified offset and size. If Size is zero, do not check the size.
1799bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1800 const Type *EltTy;
1801 uint64_t EltSize;
1802 if (const StructType *ST = dyn_cast<StructType>(T)) {
1803 const StructLayout *Layout = TD->getStructLayout(ST);
1804 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1805 EltTy = ST->getContainedType(EltIdx);
1806 EltSize = TD->getTypeAllocSize(EltTy);
1807 Offset -= Layout->getElementOffset(EltIdx);
1808 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1809 EltTy = AT->getElementType();
1810 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001811 if (Offset >= AT->getNumElements() * EltSize)
1812 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001813 Offset %= EltSize;
1814 } else {
1815 return false;
1816 }
1817 if (Offset == 0 && (Size == 0 || EltSize == Size))
1818 return true;
1819 // Check if the component spans multiple elements.
1820 if (Offset + Size > EltSize)
1821 return false;
1822 return TypeHasComponent(EltTy, Offset, Size);
1823}
1824
1825/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1826/// the instruction I, which references it, to use the separate elements.
1827/// Offset indicates the position within AI that is referenced by this
1828/// instruction.
1829void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1830 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner145c5322011-01-23 08:27:54 +00001831 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1832 Use &TheUse = UI.getUse();
1833 Instruction *User = cast<Instruction>(*UI++);
Bob Wilsonb742def2009-12-18 20:14:40 +00001834
1835 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1836 RewriteBitCast(BC, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001837 continue;
1838 }
1839
1840 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001841 RewriteGEP(GEPI, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001842 continue;
1843 }
1844
1845 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001846 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1847 uint64_t MemSize = Length->getZExtValue();
1848 if (Offset == 0 &&
1849 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1850 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001851 // Otherwise the intrinsic can only touch a single element and the
1852 // address operand will be updated, so nothing else needs to be done.
Chris Lattner145c5322011-01-23 08:27:54 +00001853 continue;
1854 }
1855
1856 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001857 const Type *LIType = LI->getType();
Chris Lattner192228e2011-01-16 05:28:59 +00001858
Bob Wilson704d1342011-01-13 17:45:11 +00001859 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001860 // Replace:
1861 // %res = load { i32, i32 }* %alloc
1862 // with:
1863 // %load.0 = load i32* %alloc.0
1864 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1865 // %load.1 = load i32* %alloc.1
1866 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1867 // (Also works for arrays instead of structs)
1868 Value *Insert = UndefValue::get(LIType);
Devang Patelabb25122011-06-03 19:46:19 +00001869 IRBuilder<> Builder(LI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001870 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patelabb25122011-06-03 19:46:19 +00001871 Value *Load = Builder.CreateLoad(NewElts[i], "load");
1872 Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
Bob Wilsonb742def2009-12-18 20:14:40 +00001873 }
1874 LI->replaceAllUsesWith(Insert);
1875 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001876 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001877 TD->getTypeAllocSize(LIType) ==
1878 TD->getTypeAllocSize(AI->getAllocatedType())) {
1879 // If this is a load of the entire alloca to an integer, rewrite it.
1880 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1881 }
Chris Lattner145c5322011-01-23 08:27:54 +00001882 continue;
1883 }
1884
1885 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001886 Value *Val = SI->getOperand(0);
1887 const Type *SIType = Val->getType();
Bob Wilson704d1342011-01-13 17:45:11 +00001888 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001889 // Replace:
1890 // store { i32, i32 } %val, { i32, i32 }* %alloc
1891 // with:
1892 // %val.0 = extractvalue { i32, i32 } %val, 0
1893 // store i32 %val.0, i32* %alloc.0
1894 // %val.1 = extractvalue { i32, i32 } %val, 1
1895 // store i32 %val.1, i32* %alloc.1
1896 // (Also works for arrays instead of structs)
Devang Patelabb25122011-06-03 19:46:19 +00001897 IRBuilder<> Builder(SI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001898 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patelabb25122011-06-03 19:46:19 +00001899 Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1900 Builder.CreateStore(Extract, NewElts[i]);
Bob Wilsonb742def2009-12-18 20:14:40 +00001901 }
1902 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001903 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001904 TD->getTypeAllocSize(SIType) ==
1905 TD->getTypeAllocSize(AI->getAllocatedType())) {
1906 // If this is a store of the entire alloca from an integer, rewrite it.
1907 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1908 }
Chris Lattner145c5322011-01-23 08:27:54 +00001909 continue;
1910 }
1911
1912 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1913 // If we have a PHI user of the alloca itself (as opposed to a GEP or
1914 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1915 // the new pointer.
1916 if (!isa<AllocaInst>(I)) continue;
1917
1918 assert(Offset == 0 && NewElts[0] &&
1919 "Direct alloca use should have a zero offset");
1920
1921 // If we have a use of the alloca, we know the derived uses will be
1922 // utilizing just the first element of the scalarized result. Insert a
1923 // bitcast of the first alloca before the user as required.
1924 AllocaInst *NewAI = NewElts[0];
1925 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1926 NewAI->moveBefore(BCI);
1927 TheUse = BCI;
1928 continue;
Bob Wilsonb742def2009-12-18 20:14:40 +00001929 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001930 }
1931}
1932
Bob Wilsonb742def2009-12-18 20:14:40 +00001933/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1934/// and recursively continue updating all of its uses.
1935void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1936 SmallVector<AllocaInst*, 32> &NewElts) {
1937 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1938 if (BC->getOperand(0) != AI)
1939 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001940
Bob Wilsonb742def2009-12-18 20:14:40 +00001941 // The bitcast references the original alloca. Replace its uses with
1942 // references to the first new element alloca.
1943 Instruction *Val = NewElts[0];
1944 if (Val->getType() != BC->getDestTy()) {
1945 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1946 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001947 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001948 BC->replaceAllUsesWith(Val);
1949 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001950}
1951
Bob Wilsonb742def2009-12-18 20:14:40 +00001952/// FindElementAndOffset - Return the index of the element containing Offset
1953/// within the specified type, which must be either a struct or an array.
1954/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001955/// element. IdxTy is set to the type of the index result to be used in a
1956/// GEP instruction.
1957uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1958 const Type *&IdxTy) {
1959 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001960 if (const StructType *ST = dyn_cast<StructType>(T)) {
1961 const StructLayout *Layout = TD->getStructLayout(ST);
1962 Idx = Layout->getElementContainingOffset(Offset);
1963 T = ST->getContainedType(Idx);
1964 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001965 IdxTy = Type::getInt32Ty(T->getContext());
1966 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001967 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001968 const ArrayType *AT = cast<ArrayType>(T);
1969 T = AT->getElementType();
1970 uint64_t EltSize = TD->getTypeAllocSize(T);
1971 Idx = Offset / EltSize;
1972 Offset -= Idx * EltSize;
1973 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001974 return Idx;
1975}
1976
1977/// RewriteGEP - Check if this GEP instruction moves the pointer across
1978/// elements of the alloca that are being split apart, and if so, rewrite
1979/// the GEP to be relative to the new element.
1980void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1981 SmallVector<AllocaInst*, 32> &NewElts) {
1982 uint64_t OldOffset = Offset;
1983 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1984 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1985 &Indices[0], Indices.size());
1986
1987 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1988
1989 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00001990 const Type *IdxTy;
1991 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001992 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001993 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001994
1995 T = AI->getAllocatedType();
1996 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001997 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001998
1999 // If this GEP does not move the pointer across elements of the alloca
2000 // being split, then it does not needs to be rewritten.
2001 if (Idx == OldIdx)
2002 return;
2003
2004 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
2005 SmallVector<Value*, 8> NewArgs;
2006 NewArgs.push_back(Constant::getNullValue(i32Ty));
2007 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00002008 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
2009 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00002010 }
2011 Instruction *Val = NewElts[Idx];
2012 if (NewArgs.size() > 1) {
2013 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
2014 NewArgs.end(), "", GEPI);
2015 Val->takeName(GEPI);
2016 }
2017 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00002018 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002019 GEPI->replaceAllUsesWith(Val);
2020 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002021}
2022
2023/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2024/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00002025void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00002026 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00002027 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002028 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00002029 // appropriate type. The "Other" pointer is the pointer that goes to memory
2030 // that doesn't have anything to do with the alloca that we are promoting. For
2031 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00002032 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00002033 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00002034 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00002035 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00002036 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00002037 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00002038 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00002039 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00002040 }
2041 }
Bob Wilson78c50b82009-12-08 18:22:03 +00002042
Chris Lattnerd93afec2009-01-07 07:18:45 +00002043 // If there is an other pointer, we want to convert it to the same pointer
2044 // type as AI has, so we can GEP through it safely.
2045 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00002046 unsigned AddrSpace =
2047 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00002048
2049 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2050 // optimization, but it's also required to detect the corner case where
2051 // both pointer operands are referencing the same memory, and where
2052 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2053 // function is only called for mem intrinsics that access the whole
2054 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00002055 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson69743022011-01-13 20:59:44 +00002056
Bob Wilsona756b1d2010-01-19 04:32:48 +00002057 // Copying the alloca to itself is a no-op: just delete it.
2058 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2059 // This code will run twice for a no-op memcpy -- once for each operand.
2060 // Put only one reference to MI on the DeadInsts list.
2061 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
2062 E = DeadInsts.end(); I != E; ++I)
2063 if (*I == MI) return;
2064 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002065 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00002066 }
Bob Wilson69743022011-01-13 20:59:44 +00002067
Chris Lattnerd93afec2009-01-07 07:18:45 +00002068 // If the pointer is not the right type, insert a bitcast to the right
2069 // type.
Chris Lattner0238f8c2010-07-08 00:27:05 +00002070 const Type *NewTy =
2071 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson69743022011-01-13 20:59:44 +00002072
Chris Lattner0238f8c2010-07-08 00:27:05 +00002073 if (OtherPtr->getType() != NewTy)
2074 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002075 }
Bob Wilson69743022011-01-13 20:59:44 +00002076
Chris Lattnerd93afec2009-01-07 07:18:45 +00002077 // Process each element of the aggregate.
Bob Wilsonb742def2009-12-18 20:14:40 +00002078 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson69743022011-01-13 20:59:44 +00002079
Owen Anderson1d0be152009-08-13 21:58:54 +00002080 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00002081
2082 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2083 // If this is a memcpy/memmove, emit a GEP of the other element address.
2084 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002085 unsigned OtherEltAlign = MemAlignment;
Bob Wilson69743022011-01-13 20:59:44 +00002086
Bob Wilsona756b1d2010-01-19 04:32:48 +00002087 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002088 Value *Idx[2] = { Zero,
2089 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00002090 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00002091 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00002092 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00002093 uint64_t EltOffset;
2094 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002095 const Type *OtherTy = OtherPtrTy->getElementType();
2096 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002097 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
2098 } else {
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002099 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002100 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002101 }
Bob Wilson69743022011-01-13 20:59:44 +00002102
Chris Lattner1541e0f2009-03-04 19:20:50 +00002103 // The alignment of the other pointer is the guaranteed alignment of the
2104 // element, which is affected by both the known alignment of the whole
2105 // mem intrinsic and the alignment of the element. If the alignment of
2106 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2107 // known alignment is just 4 bytes.
2108 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00002109 }
Bob Wilson69743022011-01-13 20:59:44 +00002110
Chris Lattnerd93afec2009-01-07 07:18:45 +00002111 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00002112 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson69743022011-01-13 20:59:44 +00002113
Chris Lattnerd93afec2009-01-07 07:18:45 +00002114 // If we got down to a scalar, insert a load or store as appropriate.
2115 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00002116 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002117 if (SROADest) {
2118 // From Other to Alloca.
2119 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2120 new StoreInst(Elt, EltPtr, MI);
2121 } else {
2122 // From Alloca to Other.
2123 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2124 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2125 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00002126 continue;
2127 }
2128 assert(isa<MemSetInst>(MI));
Bob Wilson69743022011-01-13 20:59:44 +00002129
Chris Lattnerd93afec2009-01-07 07:18:45 +00002130 // If the stored element is zero (common case), just store a null
2131 // constant.
2132 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00002133 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002134 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00002135 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00002136 } else {
2137 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00002138 const Type *ValTy = EltTy->getScalarType();
2139
Chris Lattnerd93afec2009-01-07 07:18:45 +00002140 // Construct an integer with the right value.
2141 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2142 APInt OneVal(EltSize, CI->getZExtValue());
2143 APInt TotalVal(OneVal);
2144 // Set each byte.
2145 for (unsigned i = 0; 8*i < EltSize; ++i) {
2146 TotalVal = TotalVal.shl(8);
2147 TotalVal |= OneVal;
2148 }
Bob Wilson69743022011-01-13 20:59:44 +00002149
Chris Lattnerd93afec2009-01-07 07:18:45 +00002150 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002151 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00002152 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002153 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002154 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002155 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002156 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson69743022011-01-13 20:59:44 +00002157
Chris Lattnerd93afec2009-01-07 07:18:45 +00002158 // If the requested value was a vector constant, create it.
2159 if (EltTy != ValTy) {
2160 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
2161 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Chris Lattner2ca5c862011-02-15 00:14:00 +00002162 StoreVal = ConstantVector::get(Elts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002163 }
2164 }
2165 new StoreInst(StoreVal, EltPtr, MI);
2166 continue;
2167 }
2168 // Otherwise, if we're storing a byte variable, use a memset call for
2169 // this element.
2170 }
Bob Wilson69743022011-01-13 20:59:44 +00002171
Duncan Sands777d2302009-05-09 07:06:46 +00002172 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002173
Chris Lattner61db1f52010-12-26 22:57:41 +00002174 IRBuilder<> Builder(MI);
Bob Wilson69743022011-01-13 20:59:44 +00002175
Chris Lattnerd93afec2009-01-07 07:18:45 +00002176 // Finally, insert the meminst for this element.
Chris Lattner61db1f52010-12-26 22:57:41 +00002177 if (isa<MemSetInst>(MI)) {
2178 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2179 MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002180 } else {
Chris Lattner61db1f52010-12-26 22:57:41 +00002181 assert(isa<MemTransferInst>(MI));
2182 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2183 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson69743022011-01-13 20:59:44 +00002184
Chris Lattner61db1f52010-12-26 22:57:41 +00002185 if (isa<MemCpyInst>(MI))
2186 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2187 else
2188 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002189 }
Chris Lattner372dda82007-03-05 07:52:57 +00002190 }
Bob Wilsonb742def2009-12-18 20:14:40 +00002191 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00002192}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002193
Bob Wilson39fdd692009-12-04 21:57:37 +00002194/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002195/// overwrites the entire allocation. Extract out the pieces of the stored
2196/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002197void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002198 SmallVector<AllocaInst*, 32> &NewElts){
2199 // Extract each element out of the integer according to its structure offset
2200 // and store the element value to the individual alloca.
2201 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00002202 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002203 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002204
Chris Lattner70728532011-01-16 05:58:24 +00002205 IRBuilder<> Builder(SI);
2206
Eli Friedman41b33f42009-06-01 09:14:32 +00002207 // Handle tail padding by extending the operand
2208 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002209 SrcVal = Builder.CreateZExt(SrcVal,
2210 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002211
David Greene504c7d82010-01-05 01:27:09 +00002212 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00002213 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002214
2215 // There are two forms here: AI could be an array or struct. Both cases
2216 // have different ways to compute the element offset.
2217 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2218 const StructLayout *Layout = TD->getStructLayout(EltSTy);
Bob Wilson69743022011-01-13 20:59:44 +00002219
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002220 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2221 // Get the number of bits to shift SrcVal to get the value.
2222 const Type *FieldTy = EltSTy->getElementType(i);
2223 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson69743022011-01-13 20:59:44 +00002224
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002225 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00002226 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002227
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002228 Value *EltVal = SrcVal;
2229 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002230 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002231 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002232 }
Bob Wilson69743022011-01-13 20:59:44 +00002233
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002234 // Truncate down to an integer of the right size.
2235 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002236
Chris Lattner583dd602009-01-09 18:18:43 +00002237 // Ignore zero sized fields like {}, they obviously contain no data.
2238 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002239
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002240 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002241 EltVal = Builder.CreateTrunc(EltVal,
2242 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002243 Value *DestField = NewElts[i];
2244 if (EltVal->getType() == FieldTy) {
2245 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00002246 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002247 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002248 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002249 } else {
2250 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002251 DestField = Builder.CreateBitCast(DestField,
2252 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002253 }
2254 new StoreInst(EltVal, DestField, SI);
2255 }
Bob Wilson69743022011-01-13 20:59:44 +00002256
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002257 } else {
2258 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2259 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002260 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002261 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2262
2263 uint64_t Shift;
Bob Wilson69743022011-01-13 20:59:44 +00002264
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002265 if (TD->isBigEndian())
2266 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002267 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002268 Shift = 0;
Bob Wilson69743022011-01-13 20:59:44 +00002269
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002270 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00002271 // Ignore zero sized fields like {}, they obviously contain no data.
2272 if (ElementSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002273
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002274 Value *EltVal = SrcVal;
2275 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002276 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002277 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002278 }
Bob Wilson69743022011-01-13 20:59:44 +00002279
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002280 // Truncate down to an integer of the right size.
2281 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002282 EltVal = Builder.CreateTrunc(EltVal,
2283 IntegerType::get(SI->getContext(),
2284 ElementSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002285 Value *DestField = NewElts[i];
2286 if (EltVal->getType() == ArrayEltTy) {
2287 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002288 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00002289 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002290 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002291 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002292 } else {
2293 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002294 DestField = Builder.CreateBitCast(DestField,
2295 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002296 }
2297 new StoreInst(EltVal, DestField, SI);
Bob Wilson69743022011-01-13 20:59:44 +00002298
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002299 if (TD->isBigEndian())
2300 Shift -= ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002301 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002302 Shift += ElementOffset;
2303 }
2304 }
Bob Wilson69743022011-01-13 20:59:44 +00002305
Bob Wilsonb742def2009-12-18 20:14:40 +00002306 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002307}
2308
Bob Wilson39fdd692009-12-04 21:57:37 +00002309/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002310/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002311void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002312 SmallVector<AllocaInst*, 32> &NewElts) {
2313 // Extract each element out of the NewElts according to its structure offset
2314 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00002315 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002316 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002317
David Greene504c7d82010-01-05 01:27:09 +00002318 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00002319 << '\n');
Bob Wilson69743022011-01-13 20:59:44 +00002320
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002321 // There are two forms here: AI could be an array or struct. Both cases
2322 // have different ways to compute the element offset.
2323 const StructLayout *Layout = 0;
2324 uint64_t ArrayEltBitOffset = 0;
2325 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2326 Layout = TD->getStructLayout(EltSTy);
2327 } else {
2328 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002329 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002330 }
2331
2332 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00002333 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson69743022011-01-13 20:59:44 +00002334
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002335 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2336 // Load the value from the alloca. If the NewElt is an aggregate, cast
2337 // the pointer to an integer of the same size before doing the load.
2338 Value *SrcField = NewElts[i];
2339 const Type *FieldTy =
2340 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00002341 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002342
Chris Lattner583dd602009-01-09 18:18:43 +00002343 // Ignore zero sized fields like {}, they obviously contain no data.
2344 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002345
2346 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +00002347 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00002348 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2349 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00002350 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00002351 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002352 "", LI);
2353 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2354
2355 // If SrcField is a fp or vector of the right size but that isn't an
2356 // integer type, bitcast to an integer so we can shift it.
2357 if (SrcField->getType() != FieldIntTy)
2358 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2359
2360 // Zero extend the field to be the same size as the final alloca so that
2361 // we can shift and insert it.
2362 if (SrcField->getType() != ResultVal->getType())
2363 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson69743022011-01-13 20:59:44 +00002364
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002365 // Determine the number of bits to shift SrcField.
2366 uint64_t Shift;
2367 if (Layout) // Struct case.
2368 Shift = Layout->getElementOffsetInBits(i);
2369 else // Array case.
2370 Shift = i*ArrayEltBitOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002371
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002372 if (TD->isBigEndian())
2373 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson69743022011-01-13 20:59:44 +00002374
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002375 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002376 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002377 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2378 }
2379
Chris Lattner14952472010-06-27 07:58:26 +00002380 // Don't create an 'or x, 0' on the first iteration.
2381 if (!isa<Constant>(ResultVal) ||
2382 !cast<Constant>(ResultVal)->isNullValue())
2383 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2384 else
2385 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002386 }
Eli Friedman41b33f42009-06-01 09:14:32 +00002387
2388 // Handle tail padding by truncating the result
2389 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2390 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2391
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002392 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00002393 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002394}
2395
Duncan Sands3cb36502007-11-04 14:43:57 +00002396/// HasPadding - Return true if the specified type has any structure or
Bob Wilson694a10e2011-01-13 17:45:08 +00002397/// alignment padding in between the elements that would be split apart
2398/// by SROA; return false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00002399static bool HasPadding(const Type *Ty, const TargetData &TD) {
Bob Wilson694a10e2011-01-13 17:45:08 +00002400 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2401 Ty = ATy->getElementType();
2402 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00002403 }
Bob Wilson694a10e2011-01-13 17:45:08 +00002404
2405 // SROA currently handles only Arrays and Structs.
2406 const StructType *STy = cast<StructType>(Ty);
2407 const StructLayout *SL = TD.getStructLayout(STy);
2408 unsigned PrevFieldBitOffset = 0;
2409 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2410 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2411
2412 // Check to see if there is any padding between this element and the
2413 // previous one.
2414 if (i) {
2415 unsigned PrevFieldEnd =
2416 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2417 if (PrevFieldEnd < FieldBitOffset)
2418 return true;
2419 }
2420 PrevFieldBitOffset = FieldBitOffset;
2421 }
2422 // Check for tail padding.
2423 if (unsigned EltCount = STy->getNumElements()) {
2424 unsigned PrevFieldEnd = PrevFieldBitOffset +
2425 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2426 if (PrevFieldEnd < SL->getSizeInBits())
2427 return true;
2428 }
2429 return false;
Chris Lattner39a1c042007-05-30 06:11:23 +00002430}
Chris Lattner372dda82007-03-05 07:52:57 +00002431
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002432/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2433/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2434/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002435bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00002436 // Loop over the use list of the alloca. We can only transform it if all of
2437 // the users are safe to transform.
Chris Lattner6c95d242011-01-23 07:29:29 +00002438 AllocaInfo Info(AI);
Bob Wilson69743022011-01-13 20:59:44 +00002439
Chris Lattner6c95d242011-01-23 07:29:29 +00002440 isSafeForScalarRepl(AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00002441 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00002442 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002443 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002444 }
Bob Wilson69743022011-01-13 20:59:44 +00002445
Chris Lattner39a1c042007-05-30 06:11:23 +00002446 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2447 // source and destination, we have to be careful. In particular, the memcpy
2448 // could be moving around elements that live in structure padding of the LLVM
2449 // types, but may actually be used. In these cases, we refuse to promote the
2450 // struct.
2451 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00002452 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002453 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00002454
Chris Lattner396a0562011-01-16 17:46:19 +00002455 // If the alloca never has an access to just *part* of it, but is accessed
2456 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner7e9b4272011-01-16 06:18:28 +00002457 // the alloca instead of promoting each piece at a time and inserting fission
2458 // and fusion code.
2459 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2460 // If the struct/array just has one element, use basic SRoA.
2461 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2462 if (ST->getNumElements() > 1) return false;
2463 } else {
2464 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2465 return false;
2466 }
2467 }
Chris Lattner145c5322011-01-23 08:27:54 +00002468
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002469 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00002470}
Chris Lattnera1888942005-12-12 07:19:13 +00002471
Chris Lattner800de312008-02-29 07:03:13 +00002472
Chris Lattner79b3bd32007-04-25 06:40:51 +00002473
2474/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2475/// some part of a constant global variable. This intentionally only accepts
2476/// constant expressions because we don't can't rewrite arbitrary instructions.
2477static bool PointsToConstantGlobal(Value *V) {
2478 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2479 return GV->isConstant();
2480 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Bob Wilson69743022011-01-13 20:59:44 +00002481 if (CE->getOpcode() == Instruction::BitCast ||
Chris Lattner79b3bd32007-04-25 06:40:51 +00002482 CE->getOpcode() == Instruction::GetElementPtr)
2483 return PointsToConstantGlobal(CE->getOperand(0));
2484 return false;
2485}
2486
2487/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2488/// pointer to an alloca. Ignore any reads of the pointer, return false if we
2489/// see any stores or other unknown uses. If we see pointer arithmetic, keep
2490/// track of whether it moves the pointer (with isOffset) but otherwise traverse
2491/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
Nick Lewycky081f8002010-11-24 22:04:20 +00002492/// the alloca, and if the source pointer is a pointer to a constant global, we
Chris Lattner79b3bd32007-04-25 06:40:51 +00002493/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00002494static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00002495 bool isOffset) {
2496 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00002497 User *U = cast<Instruction>(*UI);
2498
Chris Lattner2e618492010-11-18 06:20:47 +00002499 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00002500 // Ignore non-volatile loads, they are always ok.
Chris Lattner2e618492010-11-18 06:20:47 +00002501 if (LI->isVolatile()) return false;
2502 continue;
2503 }
Bob Wilson69743022011-01-13 20:59:44 +00002504
Gabor Greif8a8a4352010-04-06 19:32:30 +00002505 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002506 // If uses of the bitcast are ok, we are ok.
2507 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
2508 return false;
2509 continue;
2510 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00002511 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002512 // If the GEP has all zero indices, it doesn't offset the pointer. If it
2513 // doesn't, it does.
2514 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
2515 isOffset || !GEP->hasAllZeroIndices()))
2516 return false;
2517 continue;
2518 }
Bob Wilson69743022011-01-13 20:59:44 +00002519
Chris Lattner62480652010-11-18 06:41:51 +00002520 if (CallSite CS = U) {
Nick Lewycky081f8002010-11-24 22:04:20 +00002521 // If this is the function being called then we treat it like a load and
2522 // ignore it.
2523 if (CS.isCallee(UI))
2524 continue;
Bob Wilson69743022011-01-13 20:59:44 +00002525
Duncan Sands53892102011-05-06 10:30:37 +00002526 // If this is a readonly/readnone call site, then we know it is just a
2527 // load (but one that potentially returns the value itself), so we can
2528 // ignore it if we know that the value isn't captured.
2529 unsigned ArgNo = CS.getArgumentNo(UI);
2530 if (CS.onlyReadsMemory() &&
2531 (CS.getInstruction()->use_empty() ||
2532 CS.paramHasAttr(ArgNo+1, Attribute::NoCapture)))
2533 continue;
2534
Chris Lattner62480652010-11-18 06:41:51 +00002535 // If this is being passed as a byval argument, the caller is making a
2536 // copy, so it is only a read of the alloca.
Chris Lattner62480652010-11-18 06:41:51 +00002537 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
2538 continue;
2539 }
Bob Wilson69743022011-01-13 20:59:44 +00002540
Chris Lattner79b3bd32007-04-25 06:40:51 +00002541 // If this is isn't our memcpy/memmove, reject it as something we can't
2542 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00002543 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2544 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00002545 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002546
Chris Lattner2e618492010-11-18 06:20:47 +00002547 // If the transfer is using the alloca as a source of the transfer, then
Chris Lattner2e29ebd2010-11-18 07:32:33 +00002548 // ignore it since it is a load (unless the transfer is volatile).
Chris Lattner2e618492010-11-18 06:20:47 +00002549 if (UI.getOperandNo() == 1) {
2550 if (MI->isVolatile()) return false;
2551 continue;
2552 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00002553
2554 // If we already have seen a copy, reject the second one.
2555 if (TheCopy) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002556
Chris Lattner79b3bd32007-04-25 06:40:51 +00002557 // If the pointer has been offset from the start of the alloca, we can't
2558 // safely handle this.
2559 if (isOffset) return false;
2560
2561 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00002562 if (UI.getOperandNo() != 0) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002563
Chris Lattner79b3bd32007-04-25 06:40:51 +00002564 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00002565 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002566 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002567
Chris Lattner79b3bd32007-04-25 06:40:51 +00002568 // Otherwise, the transform is safe. Remember the copy instruction.
2569 TheCopy = MI;
2570 }
2571 return true;
2572}
2573
2574/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2575/// modified by a copy from a constant global. If we can prove this, we can
2576/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00002577MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
2578 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00002579 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
2580 return TheCopy;
2581 return 0;
2582}