blob: abd4a77d3438e3147c5086266f1ff530dcdb9a62 [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 Lattner372dda82007-03-05 07:52:57 +000031#include "llvm/Pass.h"
Chris Lattner38aec322003-09-11 16:45:55 +000032#include "llvm/Analysis/Dominators.h"
33#include "llvm/Target/TargetData.h"
34#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000035#include "llvm/Transforms/Utils/Local.h"
Chris Lattner95255282006-06-28 23:17:24 +000036#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000037#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000038#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000039#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000040#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000041#include "llvm/Support/raw_ostream.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000042#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000043#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000044using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000045
Chris Lattner0e5f4992006-12-19 21:40:18 +000046STATISTIC(NumReplaced, "Number of allocas broken up");
47STATISTIC(NumPromoted, "Number of allocas promoted");
48STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000049STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000050
Chris Lattner0e5f4992006-12-19 21:40:18 +000051namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000052 struct SROA : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000053 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000054 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Devang Patelff366852007-07-09 21:19:23 +000055 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000056 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000057 else
58 SRThreshold = T;
59 }
Devang Patel794fd752007-05-01 21:15:47 +000060
Chris Lattnered7b41e2003-05-27 15:45:27 +000061 bool runOnFunction(Function &F);
62
Chris Lattner38aec322003-09-11 16:45:55 +000063 bool performScalarRepl(Function &F);
64 bool performPromotion(Function &F);
65
Chris Lattnera15854c2003-08-31 00:45:13 +000066 // getAnalysisUsage - This pass does not require any passes, but we know it
67 // will not alter the CFG, so say so.
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel326821e2007-06-07 21:57:03 +000069 AU.addRequired<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +000070 AU.addRequired<DominanceFrontier>();
Chris Lattnera15854c2003-08-31 00:45:13 +000071 AU.setPreservesCFG();
72 }
73
Chris Lattnered7b41e2003-05-27 15:45:27 +000074 private:
Chris Lattner56c38522009-01-07 06:34:28 +000075 TargetData *TD;
76
Chris Lattner39a1c042007-05-30 06:11:23 +000077 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
78 /// information about the uses. All these fields are initialized to false
79 /// and set to true when something is learned.
80 struct AllocaInfo {
81 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
82 bool isUnsafe : 1;
83
Devang Patel4afc90d2009-02-10 07:00:59 +000084 /// needsCleanup - This is set to true if there is some use of the alloca
85 /// that requires cleanup.
86 bool needsCleanup : 1;
Chris Lattner39a1c042007-05-30 06:11:23 +000087
88 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
89 bool isMemCpySrc : 1;
90
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000091 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000092 bool isMemCpyDst : 1;
93
94 AllocaInfo()
Devang Patel4afc90d2009-02-10 07:00:59 +000095 : isUnsafe(false), needsCleanup(false),
Chris Lattner39a1c042007-05-30 06:11:23 +000096 isMemCpySrc(false), isMemCpyDst(false) {}
97 };
98
Devang Patelff366852007-07-09 21:19:23 +000099 unsigned SRThreshold;
100
Chris Lattner39a1c042007-05-30 06:11:23 +0000101 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
102
Victor Hernandez7b929da2009-10-23 21:09:37 +0000103 int isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000104
Victor Hernandez7b929da2009-10-23 21:09:37 +0000105 void isSafeUseOfAllocation(Instruction *User, AllocaInst *AI,
Chris Lattner39a1c042007-05-30 06:11:23 +0000106 AllocaInfo &Info);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000107 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocaInst *AI,
Chris Lattner39a1c042007-05-30 06:11:23 +0000108 AllocaInfo &Info);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000109 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocaInst *AI,
Chris Lattner39a1c042007-05-30 06:11:23 +0000110 unsigned OpNo, AllocaInfo &Info);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000111 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocaInst *AI,
Chris Lattner39a1c042007-05-30 06:11:23 +0000112 AllocaInfo &Info);
113
Victor Hernandez7b929da2009-10-23 21:09:37 +0000114 void DoScalarReplacement(AllocaInst *AI,
115 std::vector<AllocaInst*> &WorkList);
Devang Patel4afc90d2009-02-10 07:00:59 +0000116 void CleanupGEP(GetElementPtrInst *GEP);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000117 void CleanupAllocaUsers(AllocaInst *AI);
118 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocaInst *Base);
Chris Lattnera1888942005-12-12 07:19:13 +0000119
Victor Hernandez7b929da2009-10-23 21:09:37 +0000120 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocaInst *AI,
Chris Lattner372dda82007-03-05 07:52:57 +0000121 SmallVector<AllocaInst*, 32> &NewElts);
122
Chris Lattnerd93afec2009-01-07 07:18:45 +0000123 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000124 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000125 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000126 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000127 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000128 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000129 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000130
Chris Lattner7809ecd2009-02-03 01:30:09 +0000131 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
Chris Lattner1a3257b2009-02-03 18:15:05 +0000132 bool &SawVec, uint64_t Offset, unsigned AllocaSize);
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000133 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Chris Lattner6e011152009-02-03 21:01:03 +0000134 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
Chris Lattner9bc67da2009-02-03 19:45:44 +0000135 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +0000136 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Chris Lattner65a65022009-02-03 19:41:50 +0000137 uint64_t Offset, IRBuilder<> &Builder);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000138 static Instruction *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000139 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000140}
141
Dan Gohman844731a2008-05-13 00:00:25 +0000142char SROA::ID = 0;
143static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
144
Brian Gaeked0fde302003-11-11 22:41:34 +0000145// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000146FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
147 return new SROA(Threshold);
148}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000149
150
Chris Lattnered7b41e2003-05-27 15:45:27 +0000151bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000152 TD = getAnalysisIfAvailable<TargetData>();
153
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000154 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000155
156 // FIXME: ScalarRepl currently depends on TargetData more than it
157 // theoretically needs to. It should be refactored in order to support
158 // target-independent IR. Until this is done, just skip the actual
159 // scalar-replacement portion of this pass.
160 if (!TD) return Changed;
161
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000162 while (1) {
163 bool LocalChange = performScalarRepl(F);
164 if (!LocalChange) break; // No need to repromote if no scalarrepl
165 Changed = true;
166 LocalChange = performPromotion(F);
167 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
168 }
Chris Lattner38aec322003-09-11 16:45:55 +0000169
170 return Changed;
171}
172
173
174bool SROA::performPromotion(Function &F) {
175 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000176 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000177 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000178
Chris Lattner02a3be02003-09-20 14:39:18 +0000179 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000180
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000181 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000182
Chris Lattner38aec322003-09-11 16:45:55 +0000183 while (1) {
184 Allocas.clear();
185
186 // Find allocas that are safe to promote, by looking at all instructions in
187 // the entry node
188 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
189 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000190 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000191 Allocas.push_back(AI);
192
193 if (Allocas.empty()) break;
194
Nick Lewyckyce2c51b2009-11-23 03:50:44 +0000195 PromoteMemToReg(Allocas, DT, DF);
Chris Lattner38aec322003-09-11 16:45:55 +0000196 NumPromoted += Allocas.size();
197 Changed = true;
198 }
199
200 return Changed;
201}
202
Chris Lattner963a97f2008-06-22 17:46:21 +0000203/// getNumSAElements - Return the number of elements in the specific struct or
204/// array.
205static uint64_t getNumSAElements(const Type *T) {
206 if (const StructType *ST = dyn_cast<StructType>(T))
207 return ST->getNumElements();
208 return cast<ArrayType>(T)->getNumElements();
209}
210
Chris Lattner38aec322003-09-11 16:45:55 +0000211// performScalarRepl - This algorithm is a simple worklist driven algorithm,
212// which runs on all of the malloc/alloca instructions in the function, removing
213// them if they are only used by getelementptr instructions.
214//
215bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000216 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000217
218 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner02a3be02003-09-20 14:39:18 +0000219 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000220 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000221 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000222 WorkList.push_back(A);
223
224 // Process the worklist
225 bool Changed = false;
226 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000227 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000228 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000229
Chris Lattneradd2bd72006-12-22 23:14:42 +0000230 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
231 // with unused elements.
232 if (AI->use_empty()) {
233 AI->eraseFromParent();
234 continue;
235 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000236
237 // If this alloca is impossible for us to promote, reject it early.
238 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
239 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000240
241 // Check to see if this allocation is only modified by a memcpy/memmove from
242 // a constant global. If this is the case, we can change all users to use
243 // the constant global instead. This is commonly produced by the CFE by
244 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
245 // is only subsequently read.
246 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
Nick Lewycky59136252009-09-15 07:08:25 +0000247 DEBUG(errs() << "Found alloca equal to global: " << *AI << '\n');
248 DEBUG(errs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner79b3bd32007-04-25 06:40:51 +0000249 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000250 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000251 TheCopy->eraseFromParent(); // Don't mutate the global.
252 AI->eraseFromParent();
253 ++NumGlobals;
254 Changed = true;
255 continue;
256 }
Chris Lattner15c82772009-02-02 20:44:45 +0000257
Chris Lattner7809ecd2009-02-03 01:30:09 +0000258 // Check to see if we can perform the core SROA transformation. We cannot
259 // transform the allocation instruction if it is an array allocation
260 // (allocations OF arrays are ok though), and an allocation of a scalar
261 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000262 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000263
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000264 // Do not promote [0 x %struct].
265 if (AllocaSize == 0) continue;
266
Bill Wendling5a377cb2009-03-03 12:12:58 +0000267 // Do not promote any struct whose size is too big.
Bill Wendling3aaf5d92009-03-03 19:18:49 +0000268 if (AllocaSize > SRThreshold) continue;
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000269
Chris Lattner7809ecd2009-02-03 01:30:09 +0000270 if ((isa<StructType>(AI->getAllocatedType()) ||
271 isa<ArrayType>(AI->getAllocatedType())) &&
Chris Lattner7809ecd2009-02-03 01:30:09 +0000272 // Do not promote any struct into more than "32" separate vars.
Evan Cheng67fca632009-03-06 00:56:43 +0000273 getNumSAElements(AI->getAllocatedType()) <= SRThreshold/4) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000274 // Check that all of the users of the allocation are capable of being
275 // transformed.
276 switch (isSafeAllocaToScalarRepl(AI)) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000277 default: llvm_unreachable("Unexpected value!");
Chris Lattner7809ecd2009-02-03 01:30:09 +0000278 case 0: // Not safe to scalar replace.
279 break;
280 case 1: // Safe, but requires cleanup/canonicalizations first
Devang Patel4afc90d2009-02-10 07:00:59 +0000281 CleanupAllocaUsers(AI);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000282 // FALL THROUGH.
283 case 3: // Safe to scalar replace.
284 DoScalarReplacement(AI, WorkList);
285 Changed = true;
286 continue;
287 }
288 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000289
290 // If we can turn this aggregate value (potentially with casts) into a
291 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000292 // IsNotTrivial tracks whether this is something that mem2reg could have
293 // promoted itself. If so, we don't want to transform it needlessly. Note
294 // that we can't just check based on the type: the alloca may be of an i32
295 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner6e733d32009-01-28 20:16:43 +0000296 bool IsNotTrivial = false;
Chris Lattner7809ecd2009-02-03 01:30:09 +0000297 const Type *VectorTy = 0;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000298 bool HadAVector = false;
299 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
Chris Lattner0ff83ab2009-03-04 19:22:30 +0000300 0, unsigned(AllocaSize)) && IsNotTrivial) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000301 AllocaInst *NewAI;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000302 // If we were able to find a vector type that can handle this with
303 // insert/extract elements, and if there was at least one use that had
304 // a vector type, promote this to a vector. We don't want to promote
305 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
306 // we just get a lot of insert/extracts. If at least one vector is
307 // involved, then we probably really do have a union of vector/array.
308 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
Nick Lewycky59136252009-09-15 07:08:25 +0000309 DEBUG(errs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
Chris Lattnerbdff5482009-08-23 04:37:46 +0000310 << *VectorTy << '\n');
Chris Lattner15c82772009-02-02 20:44:45 +0000311
Chris Lattner7809ecd2009-02-03 01:30:09 +0000312 // Create and insert the vector alloca.
Owen Anderson50dead02009-07-15 23:53:25 +0000313 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
Chris Lattner15c82772009-02-02 20:44:45 +0000314 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000315 } else {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000316 DEBUG(errs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
Chris Lattner7809ecd2009-02-03 01:30:09 +0000317
318 // Create and insert the integer alloca.
Owen Anderson1d0be152009-08-13 21:58:54 +0000319 const Type *NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
Owen Anderson50dead02009-07-15 23:53:25 +0000320 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
Chris Lattner7809ecd2009-02-03 01:30:09 +0000321 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner6e733d32009-01-28 20:16:43 +0000322 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000323 NewAI->takeName(AI);
324 AI->eraseFromParent();
325 ++NumConverted;
326 Changed = true;
327 continue;
328 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000329
Chris Lattner7809ecd2009-02-03 01:30:09 +0000330 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000331 }
332
333 return Changed;
334}
Chris Lattner5e062a12003-05-30 04:15:41 +0000335
Chris Lattnera10b29b2007-04-25 05:02:56 +0000336/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
337/// predicate, do SROA now.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000338void SROA::DoScalarReplacement(AllocaInst *AI,
339 std::vector<AllocaInst*> &WorkList) {
Chris Lattnerff114702009-09-15 05:14:57 +0000340 DEBUG(errs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +0000341 SmallVector<AllocaInst*, 32> ElementAllocas;
342 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
343 ElementAllocas.reserve(ST->getNumContainedTypes());
344 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000345 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +0000346 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000347 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000348 ElementAllocas.push_back(NA);
349 WorkList.push_back(NA); // Add to worklist for recursive processing
350 }
351 } else {
352 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
353 ElementAllocas.reserve(AT->getNumElements());
354 const Type *ElTy = AT->getElementType();
355 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000356 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000357 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000358 ElementAllocas.push_back(NA);
359 WorkList.push_back(NA); // Add to worklist for recursive processing
360 }
361 }
362
363 // Now that we have created the alloca instructions that we want to use,
364 // expand the getelementptr instructions to use them.
365 //
366 while (!AI->use_empty()) {
367 Instruction *User = cast<Instruction>(AI->use_back());
368 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
369 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
370 BCInst->eraseFromParent();
371 continue;
372 }
373
Chris Lattner2a6a6452008-06-23 17:11:23 +0000374 // Replace:
375 // %res = load { i32, i32 }* %alloc
376 // with:
377 // %load.0 = load i32* %alloc.0
378 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
379 // %load.1 = load i32* %alloc.1
380 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
Matthijs Kooijman02518142008-06-05 12:51:53 +0000381 // (Also works for arrays instead of structs)
382 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000383 Value *Insert = UndefValue::get(LI->getType());
Matthijs Kooijman02518142008-06-05 12:51:53 +0000384 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
385 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
386 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
387 }
388 LI->replaceAllUsesWith(Insert);
389 LI->eraseFromParent();
390 continue;
391 }
392
Chris Lattner2a6a6452008-06-23 17:11:23 +0000393 // Replace:
394 // store { i32, i32 } %val, { i32, i32 }* %alloc
395 // with:
396 // %val.0 = extractvalue { i32, i32 } %val, 0
397 // store i32 %val.0, i32* %alloc.0
398 // %val.1 = extractvalue { i32, i32 } %val, 1
399 // store i32 %val.1, i32* %alloc.1
Matthijs Kooijman02518142008-06-05 12:51:53 +0000400 // (Also works for arrays instead of structs)
401 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
402 Value *Val = SI->getOperand(0);
403 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
404 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
405 new StoreInst(Extract, ElementAllocas[i], SI);
406 }
407 SI->eraseFromParent();
408 continue;
409 }
410
Chris Lattnera10b29b2007-04-25 05:02:56 +0000411 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
412 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
413 unsigned Idx =
414 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
415
416 assert(Idx < ElementAllocas.size() && "Index out of range?");
417 AllocaInst *AllocaToUse = ElementAllocas[Idx];
418
419 Value *RepValue;
420 if (GEPI->getNumOperands() == 3) {
421 // Do not insert a new getelementptr instruction with zero indices, only
422 // to have it optimized out later.
423 RepValue = AllocaToUse;
424 } else {
425 // We are indexing deeply into the structure, so we still need a
426 // getelement ptr instruction to finish the indexing. This may be
427 // expanded itself once the worklist is rerun.
428 //
429 SmallVector<Value*, 8> NewArgs;
Owen Anderson1d0be152009-08-13 21:58:54 +0000430 NewArgs.push_back(Constant::getNullValue(
431 Type::getInt32Ty(AI->getContext())));
Chris Lattnera10b29b2007-04-25 05:02:56 +0000432 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
Gabor Greif051a9502008-04-06 20:25:17 +0000433 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
434 NewArgs.end(), "", GEPI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000435 RepValue->takeName(GEPI);
436 }
437
438 // If this GEP is to the start of the aggregate, check for memcpys.
Chris Lattnerd356a7e2009-01-07 06:25:07 +0000439 if (Idx == 0 && GEPI->hasAllZeroIndices())
440 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000441
442 // Move all of the users over to the new GEP.
443 GEPI->replaceAllUsesWith(RepValue);
444 // Delete the old GEP
445 GEPI->eraseFromParent();
446 }
447
448 // Finally, delete the Alloca instruction
449 AI->eraseFromParent();
450 NumReplaced++;
451}
452
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000453/// isSafeElementUse - Check to see if this use is an allowed use for a
Chris Lattner8bf99112007-03-19 00:16:43 +0000454/// getelementptr instruction of an array aggregate allocation. isFirstElt
455/// indicates whether Ptr is known to the start of the aggregate.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000456void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocaInst *AI,
Chris Lattner39a1c042007-05-30 06:11:23 +0000457 AllocaInfo &Info) {
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000458 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
459 I != E; ++I) {
460 Instruction *User = cast<Instruction>(*I);
461 switch (User->getOpcode()) {
462 case Instruction::Load: break;
463 case Instruction::Store:
464 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattner39a1c042007-05-30 06:11:23 +0000465 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000466 break;
467 case Instruction::GetElementPtr: {
468 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
Chris Lattner8bf99112007-03-19 00:16:43 +0000469 bool AreAllZeroIndices = isFirstElt;
Chris Lattner8976e592009-11-27 16:37:41 +0000470 if (GEP->getNumOperands() > 1 &&
471 (!isa<ConstantInt>(GEP->getOperand(1)) ||
472 !cast<ConstantInt>(GEP->getOperand(1))->isZero()))
473 // Using pointer arithmetic to navigate the array.
474 return MarkUnsafe(Info);
475
476 // Verify that any array subscripts are in range.
477 for (gep_type_iterator GEPIt = gep_type_begin(GEP),
478 E = gep_type_end(GEP); GEPIt != E; ++GEPIt) {
479 // Ignore struct elements, no extra checking needed for these.
480 if (isa<StructType>(*GEPIt))
481 continue;
482
483 // This GEP indexes an array. Verify that this is an in-range
484 // constant integer. Specifically, consider A[0][i]. We cannot know that
485 // the user isn't doing invalid things like allowing i to index an
486 // out-of-range subscript that accesses A[1]. Because of this, we have
487 // to reject SROA of any accesses into structs where any of the
488 // components are variables.
489 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
490 if (!IdxVal) return MarkUnsafe(Info);
491
492 // Are all indices still zero?
493 AreAllZeroIndices &= IdxVal->isZero();
494
495 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPIt)) {
496 if (IdxVal->getZExtValue() >= AT->getNumElements())
497 return MarkUnsafe(Info);
498 } else if (const VectorType *VT = dyn_cast<VectorType>(*GEPIt)) {
499 if (IdxVal->getZExtValue() >= VT->getNumElements())
500 return MarkUnsafe(Info);
501 }
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000502 }
Chris Lattner8976e592009-11-27 16:37:41 +0000503
Chris Lattner39a1c042007-05-30 06:11:23 +0000504 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
505 if (Info.isUnsafe) return;
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000506 break;
507 }
Chris Lattner8bf99112007-03-19 00:16:43 +0000508 case Instruction::BitCast:
Chris Lattner39a1c042007-05-30 06:11:23 +0000509 if (isFirstElt) {
510 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
511 if (Info.isUnsafe) return;
Chris Lattner8bf99112007-03-19 00:16:43 +0000512 break;
Chris Lattner8bf99112007-03-19 00:16:43 +0000513 }
Nick Lewycky59136252009-09-15 07:08:25 +0000514 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
Chris Lattner39a1c042007-05-30 06:11:23 +0000515 return MarkUnsafe(Info);
516 case Instruction::Call:
517 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
518 if (isFirstElt) {
519 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
520 if (Info.isUnsafe) return;
521 break;
522 }
523 }
Nick Lewycky59136252009-09-15 07:08:25 +0000524 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
Chris Lattner39a1c042007-05-30 06:11:23 +0000525 return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000526 default:
Nick Lewycky59136252009-09-15 07:08:25 +0000527 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
Chris Lattner39a1c042007-05-30 06:11:23 +0000528 return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000529 }
530 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000531 return; // All users look ok :)
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000532}
533
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000534/// AllUsersAreLoads - Return true if all users of this value are loads.
535static bool AllUsersAreLoads(Value *Ptr) {
536 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
537 I != E; ++I)
538 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
539 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000540 return true;
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000541}
542
Chris Lattner5e062a12003-05-30 04:15:41 +0000543/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
544/// aggregate allocation.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000545void SROA::isSafeUseOfAllocation(Instruction *User, AllocaInst *AI,
Chris Lattner39a1c042007-05-30 06:11:23 +0000546 AllocaInfo &Info) {
Chris Lattner372dda82007-03-05 07:52:57 +0000547 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
Chris Lattner39a1c042007-05-30 06:11:23 +0000548 return isSafeUseOfBitCastedAllocation(C, AI, Info);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000549
Chris Lattner6e733d32009-01-28 20:16:43 +0000550 if (LoadInst *LI = dyn_cast<LoadInst>(User))
551 if (!LI->isVolatile())
552 return;// Loads (returning a first class aggregrate) are always rewritable
Matthijs Kooijman02518142008-06-05 12:51:53 +0000553
Chris Lattner6e733d32009-01-28 20:16:43 +0000554 if (StoreInst *SI = dyn_cast<StoreInst>(User))
555 if (!SI->isVolatile() && SI->getOperand(0) != AI)
556 return;// Store is ok if storing INTO the pointer, not storing the pointer
Matthijs Kooijman02518142008-06-05 12:51:53 +0000557
Chris Lattner39a1c042007-05-30 06:11:23 +0000558 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
559 if (GEPI == 0)
560 return MarkUnsafe(Info);
561
Chris Lattnerbe883a22003-11-25 21:09:18 +0000562 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
563
Chris Lattner25de4862006-03-08 01:05:29 +0000564 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
Chris Lattnerbe883a22003-11-25 21:09:18 +0000565 if (I == E ||
Owen Andersona7235ea2009-07-31 20:28:14 +0000566 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000567 return MarkUnsafe(Info);
568 }
Chris Lattnerbe883a22003-11-25 21:09:18 +0000569
570 ++I;
Chris Lattner39a1c042007-05-30 06:11:23 +0000571 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
Chris Lattnerbe883a22003-11-25 21:09:18 +0000572
Chris Lattner8bf99112007-03-19 00:16:43 +0000573 bool IsAllZeroIndices = true;
574
Chris Lattner88e6dc82008-08-23 05:21:06 +0000575 // If the first index is a non-constant index into an array, see if we can
576 // handle it as a special case.
Chris Lattnerbe883a22003-11-25 21:09:18 +0000577 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
Chris Lattner88e6dc82008-08-23 05:21:06 +0000578 if (!isa<ConstantInt>(I.getOperand())) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000579 IsAllZeroIndices = 0;
Chris Lattner88e6dc82008-08-23 05:21:06 +0000580 uint64_t NumElements = AT->getNumElements();
Chris Lattner8bf99112007-03-19 00:16:43 +0000581
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000582 // If this is an array index and the index is not constant, we cannot
583 // promote... that is unless the array has exactly one or two elements in
584 // it, in which case we CAN promote it, but we have to canonicalize this
585 // out if this is the only problem.
Chris Lattner25de4862006-03-08 01:05:29 +0000586 if ((NumElements == 1 || NumElements == 2) &&
Chris Lattner39a1c042007-05-30 06:11:23 +0000587 AllUsersAreLoads(GEPI)) {
Devang Patel4afc90d2009-02-10 07:00:59 +0000588 Info.needsCleanup = true;
Chris Lattner39a1c042007-05-30 06:11:23 +0000589 return; // Canonicalization required!
590 }
591 return MarkUnsafe(Info);
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000592 }
Chris Lattner5e062a12003-05-30 04:15:41 +0000593 }
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000594
Chris Lattner88e6dc82008-08-23 05:21:06 +0000595 // Walk through the GEP type indices, checking the types that this indexes
596 // into.
597 for (; I != E; ++I) {
598 // Ignore struct elements, no extra checking needed for these.
599 if (isa<StructType>(*I))
600 continue;
601
Chris Lattner88e6dc82008-08-23 05:21:06 +0000602 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
603 if (!IdxVal) return MarkUnsafe(Info);
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000604
605 // Are all indices still zero?
Chris Lattner88e6dc82008-08-23 05:21:06 +0000606 IsAllZeroIndices &= IdxVal->isZero();
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000607
608 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
609 // This GEP indexes an array. Verify that this is an in-range constant
610 // integer. Specifically, consider A[0][i]. We cannot know that the user
611 // isn't doing invalid things like allowing i to index an out-of-range
612 // subscript that accesses A[1]. Because of this, we have to reject SROA
Bob Wilsond614a1f2009-12-04 21:51:35 +0000613 // of any accesses into structs where any of the components are variables.
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000614 if (IdxVal->getZExtValue() >= AT->getNumElements())
615 return MarkUnsafe(Info);
Dale Johannesenc0bc5472008-11-04 20:54:03 +0000616 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
617 if (IdxVal->getZExtValue() >= VT->getNumElements())
618 return MarkUnsafe(Info);
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000619 }
Chris Lattner88e6dc82008-08-23 05:21:06 +0000620 }
621
Chris Lattnerbe883a22003-11-25 21:09:18 +0000622 // If there are any non-simple uses of this getelementptr, make sure to reject
623 // them.
Chris Lattner39a1c042007-05-30 06:11:23 +0000624 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000625}
626
Bob Wilson39fdd692009-12-04 21:57:37 +0000627/// isSafeMemIntrinsicOnAllocation - Check if the specified memory
Chris Lattner8bf99112007-03-19 00:16:43 +0000628/// intrinsic can be promoted by SROA. At this point, we know that the operand
629/// of the memintrinsic is a pointer to the beginning of the allocation.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000630void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocaInst *AI,
Chris Lattner39a1c042007-05-30 06:11:23 +0000631 unsigned OpNo, AllocaInfo &Info) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000632 // If not constant length, give up.
633 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattner39a1c042007-05-30 06:11:23 +0000634 if (!Length) return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000635
636 // If not the whole aggregate, give up.
Duncan Sands3cb36502007-11-04 14:43:57 +0000637 if (Length->getZExtValue() !=
Duncan Sands777d2302009-05-09 07:06:46 +0000638 TD->getTypeAllocSize(AI->getType()->getElementType()))
Chris Lattner39a1c042007-05-30 06:11:23 +0000639 return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000640
641 // We only know about memcpy/memset/memmove.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000642 if (!isa<MemIntrinsic>(MI))
Chris Lattner39a1c042007-05-30 06:11:23 +0000643 return MarkUnsafe(Info);
644
645 // Otherwise, we can transform it. Determine whether this is a memcpy/set
646 // into or out of the aggregate.
647 if (OpNo == 1)
648 Info.isMemCpyDst = true;
649 else {
650 assert(OpNo == 2);
651 Info.isMemCpySrc = true;
652 }
Chris Lattner5e062a12003-05-30 04:15:41 +0000653}
654
Bob Wilson39fdd692009-12-04 21:57:37 +0000655/// isSafeUseOfBitCastedAllocation - Check if all users of this bitcast
656/// from an alloca are safe for SROA of that alloca.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000657void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocaInst *AI,
Chris Lattner39a1c042007-05-30 06:11:23 +0000658 AllocaInfo &Info) {
Chris Lattner372dda82007-03-05 07:52:57 +0000659 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
660 UI != E; ++UI) {
661 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000662 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
Chris Lattner372dda82007-03-05 07:52:57 +0000663 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000664 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000665 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner6e733d32009-01-28 20:16:43 +0000666 if (SI->isVolatile())
667 return MarkUnsafe(Info);
668
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000669 // If storing the entire alloca in one chunk through a bitcasted pointer
670 // to integer, we can transform it. This happens (for example) when you
671 // cast a {i32,i32}* to i64* and store through it. This is similar to the
672 // memcpy case and occurs in various "byval" cases and emulated memcpys.
673 if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
Duncan Sands777d2302009-05-09 07:06:46 +0000674 TD->getTypeAllocSize(SI->getOperand(0)->getType()) ==
675 TD->getTypeAllocSize(AI->getType()->getElementType())) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000676 Info.isMemCpyDst = true;
677 continue;
678 }
679 return MarkUnsafe(Info);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000680 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
Chris Lattner6e733d32009-01-28 20:16:43 +0000681 if (LI->isVolatile())
682 return MarkUnsafe(Info);
683
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000684 // If loading the entire alloca in one chunk through a bitcasted pointer
685 // to integer, we can transform it. This happens (for example) when you
686 // cast a {i32,i32}* to i64* and load through it. This is similar to the
687 // memcpy case and occurs in various "byval" cases and emulated memcpys.
688 if (isa<IntegerType>(LI->getType()) &&
Duncan Sands777d2302009-05-09 07:06:46 +0000689 TD->getTypeAllocSize(LI->getType()) ==
690 TD->getTypeAllocSize(AI->getType()->getElementType())) {
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000691 Info.isMemCpySrc = true;
692 continue;
693 }
694 return MarkUnsafe(Info);
Devang Patel4afc90d2009-02-10 07:00:59 +0000695 } else if (isa<DbgInfoIntrinsic>(UI)) {
696 // If one user is DbgInfoIntrinsic then check if all users are
697 // DbgInfoIntrinsics.
698 if (OnlyUsedByDbgInfoIntrinsics(BC)) {
699 Info.needsCleanup = true;
700 return;
701 }
702 else
703 MarkUnsafe(Info);
704 }
705 else {
Chris Lattner39a1c042007-05-30 06:11:23 +0000706 return MarkUnsafe(Info);
Chris Lattner372dda82007-03-05 07:52:57 +0000707 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000708 if (Info.isUnsafe) return;
Chris Lattner372dda82007-03-05 07:52:57 +0000709 }
Chris Lattner372dda82007-03-05 07:52:57 +0000710}
711
Chris Lattner8bf99112007-03-19 00:16:43 +0000712/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
713/// to its first element. Transform users of the cast to use the new values
714/// instead.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000715void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocaInst *AI,
Chris Lattner372dda82007-03-05 07:52:57 +0000716 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000717 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
718 while (UI != UE) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000719 Instruction *User = cast<Instruction>(*UI++);
720 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
Chris Lattner372dda82007-03-05 07:52:57 +0000721 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000722 if (BCU->use_empty()) BCU->eraseFromParent();
Chris Lattner372dda82007-03-05 07:52:57 +0000723 continue;
724 }
725
Chris Lattnerd93afec2009-01-07 07:18:45 +0000726 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
727 // This must be memcpy/memmove/memset of the entire aggregate.
728 // Split into one per element.
729 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
Chris Lattner8bf99112007-03-19 00:16:43 +0000730 continue;
731 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000732
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000733 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000734 // If this is a store of the entire alloca from an integer, rewrite it.
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000735 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
736 continue;
737 }
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000738
739 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
740 // If this is a load of the entire alloca to an integer, rewrite it.
741 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
742 continue;
743 }
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000744
745 // Otherwise it must be some other user of a gep of the first pointer. Just
746 // leave these alone.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000747 continue;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000748 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000749}
750
751/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
752/// Rewrite it to copy or set the elements of the scalarized memory.
753void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000754 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000755 SmallVector<AllocaInst*, 32> &NewElts) {
756
757 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +0000758 // appropriate type. The "Other" pointer is the pointer that goes to memory
759 // that doesn't have anything to do with the alloca that we are promoting. For
760 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000761 Value *OtherPtr = 0;
Owen Andersone922c022009-07-22 00:24:57 +0000762 LLVMContext &Context = MI->getContext();
Chris Lattnerdfe964c2009-03-08 03:59:00 +0000763 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +0000764 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
765 if (BCInst == MTI->getRawDest())
766 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000767 else {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000768 assert(BCInst == MTI->getRawSource());
769 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000770 }
771 }
Bob Wilson78c50b82009-12-08 18:22:03 +0000772
773 // Keep track of the other intrinsic argument, so it can be removed if it
774 // is dead when the intrinsic is replaced.
775 Value *PossiblyDead = OtherPtr;
Chris Lattnerd93afec2009-01-07 07:18:45 +0000776
777 // If there is an other pointer, we want to convert it to the same pointer
778 // type as AI has, so we can GEP through it safely.
779 if (OtherPtr) {
780 // It is likely that OtherPtr is a bitcast, if so, remove it.
781 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
782 OtherPtr = BC->getOperand(0);
783 // All zero GEPs are effectively bitcasts.
784 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
785 if (GEP->hasAllZeroIndices())
786 OtherPtr = GEP->getOperand(0);
Chris Lattner372dda82007-03-05 07:52:57 +0000787
Chris Lattnerd93afec2009-01-07 07:18:45 +0000788 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
789 if (BCE->getOpcode() == Instruction::BitCast)
790 OtherPtr = BCE->getOperand(0);
791
792 // If the pointer is not the right type, insert a bitcast to the right
793 // type.
794 if (OtherPtr->getType() != AI->getType())
795 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
796 MI);
797 }
798
799 // Process each element of the aggregate.
800 Value *TheFn = MI->getOperand(0);
801 const Type *BytePtrTy = MI->getRawDest()->getType();
802 bool SROADest = MI->getRawDest() == BCInst;
803
Owen Anderson1d0be152009-08-13 21:58:54 +0000804 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +0000805
806 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
807 // If this is a memcpy/memmove, emit a GEP of the other element address.
808 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000809 unsigned OtherEltAlign = MemAlignment;
810
Chris Lattner372dda82007-03-05 07:52:57 +0000811 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000812 Value *Idx[2] = { Zero,
813 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Chris Lattnerd93afec2009-01-07 07:18:45 +0000814 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000815 OtherPtr->getNameStr()+"."+Twine(i),
Chris Lattnerd93afec2009-01-07 07:18:45 +0000816 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +0000817 uint64_t EltOffset;
818 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
819 if (const StructType *ST =
820 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
821 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
822 } else {
823 const Type *EltTy =
824 cast<SequentialType>(OtherPtr->getType())->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000825 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000826 }
827
828 // The alignment of the other pointer is the guaranteed alignment of the
829 // element, which is affected by both the known alignment of the whole
830 // mem intrinsic and the alignment of the element. If the alignment of
831 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
832 // known alignment is just 4 bytes.
833 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000834 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000835
836 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +0000837 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000838
839 // If we got down to a scalar, insert a load or store as appropriate.
840 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000841 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +0000842 if (SROADest) {
843 // From Other to Alloca.
844 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
845 new StoreInst(Elt, EltPtr, MI);
846 } else {
847 // From Alloca to Other.
848 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
849 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
850 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000851 continue;
852 }
853 assert(isa<MemSetInst>(MI));
854
855 // If the stored element is zero (common case), just store a null
856 // constant.
857 Constant *StoreVal;
858 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
859 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000860 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +0000861 } else {
862 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +0000863 const Type *ValTy = EltTy->getScalarType();
864
Chris Lattnerd93afec2009-01-07 07:18:45 +0000865 // Construct an integer with the right value.
866 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
867 APInt OneVal(EltSize, CI->getZExtValue());
868 APInt TotalVal(OneVal);
869 // Set each byte.
870 for (unsigned i = 0; 8*i < EltSize; ++i) {
871 TotalVal = TotalVal.shl(8);
872 TotalVal |= OneVal;
873 }
874
875 // Convert the integer value to the appropriate type.
Owen Andersoneed707b2009-07-24 23:12:02 +0000876 StoreVal = ConstantInt::get(Context, TotalVal);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000877 if (isa<PointerType>(ValTy))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000878 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000879 else if (ValTy->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000880 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000881 assert(StoreVal->getType() == ValTy && "Type mismatch!");
882
883 // If the requested value was a vector constant, create it.
884 if (EltTy != ValTy) {
885 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
886 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +0000887 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000888 }
889 }
890 new StoreInst(StoreVal, EltPtr, MI);
891 continue;
892 }
893 // Otherwise, if we're storing a byte variable, use a memset call for
894 // this element.
895 }
896
897 // Cast the element pointer to BytePtrTy.
898 if (EltPtr->getType() != BytePtrTy)
899 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
900
901 // Cast the other pointer (if we have one) to BytePtrTy.
902 if (OtherElt && OtherElt->getType() != BytePtrTy)
903 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
904 MI);
905
Duncan Sands777d2302009-05-09 07:06:46 +0000906 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000907
908 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000909 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000910 Value *Ops[] = {
911 SROADest ? EltPtr : OtherElt, // Dest ptr
912 SROADest ? OtherElt : EltPtr, // Src ptr
Owen Andersoneed707b2009-07-24 23:12:02 +0000913 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Owen Anderson1d0be152009-08-13 21:58:54 +0000914 // Align
915 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign)
Chris Lattnerd93afec2009-01-07 07:18:45 +0000916 };
917 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
918 } else {
919 assert(isa<MemSetInst>(MI));
920 Value *Ops[] = {
921 EltPtr, MI->getOperand(2), // Dest, Value,
Owen Andersoneed707b2009-07-24 23:12:02 +0000922 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Chris Lattnerd93afec2009-01-07 07:18:45 +0000923 Zero // Align
924 };
925 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
926 }
Chris Lattner372dda82007-03-05 07:52:57 +0000927 }
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000928 MI->eraseFromParent();
Bob Wilson78c50b82009-12-08 18:22:03 +0000929 if (PossiblyDead)
930 RecursivelyDeleteTriviallyDeadInstructions(PossiblyDead);
Chris Lattner372dda82007-03-05 07:52:57 +0000931}
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000932
Bob Wilson39fdd692009-12-04 21:57:37 +0000933/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000934/// overwrites the entire allocation. Extract out the pieces of the stored
935/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000936void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000937 SmallVector<AllocaInst*, 32> &NewElts){
938 // Extract each element out of the integer according to its structure offset
939 // and store the element value to the individual alloca.
940 Value *SrcVal = SI->getOperand(0);
941 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000942 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000943
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000944 // If this isn't a store of an integer to the whole alloca, it may be a store
945 // to the first element. Just ignore the store in this case and normal SROA
Eli Friedman41b33f42009-06-01 09:14:32 +0000946 // will handle it.
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000947 if (!isa<IntegerType>(SrcVal->getType()) ||
Eli Friedman41b33f42009-06-01 09:14:32 +0000948 TD->getTypeAllocSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000949 return;
Eli Friedman41b33f42009-06-01 09:14:32 +0000950 // Handle tail padding by extending the operand
951 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000952 SrcVal = new ZExtInst(SrcVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000953 IntegerType::get(SI->getContext(), AllocaSizeBits),
954 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000955
Nick Lewycky59136252009-09-15 07:08:25 +0000956 DEBUG(errs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
957 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000958
959 // There are two forms here: AI could be an array or struct. Both cases
960 // have different ways to compute the element offset.
961 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
962 const StructLayout *Layout = TD->getStructLayout(EltSTy);
963
964 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
965 // Get the number of bits to shift SrcVal to get the value.
966 const Type *FieldTy = EltSTy->getElementType(i);
967 uint64_t Shift = Layout->getElementOffsetInBits(i);
968
969 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +0000970 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000971
972 Value *EltVal = SrcVal;
973 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000974 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000975 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
976 "sroa.store.elt", SI);
977 }
978
979 // Truncate down to an integer of the right size.
980 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +0000981
982 // Ignore zero sized fields like {}, they obviously contain no data.
983 if (FieldSizeBits == 0) continue;
984
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000985 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000986 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000987 IntegerType::get(SI->getContext(), FieldSizeBits),
988 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000989 Value *DestField = NewElts[i];
990 if (EltVal->getType() == FieldTy) {
991 // Storing to an integer field of this size, just do it.
992 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
993 // Bitcast to the right element type (for fp/vector values).
994 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
995 } else {
996 // Otherwise, bitcast the dest pointer (for aggregates).
997 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +0000998 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000999 "", SI);
1000 }
1001 new StoreInst(EltVal, DestField, SI);
1002 }
1003
1004 } else {
1005 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1006 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001007 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001008 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1009
1010 uint64_t Shift;
1011
1012 if (TD->isBigEndian())
1013 Shift = AllocaSizeBits-ElementOffset;
1014 else
1015 Shift = 0;
1016
1017 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00001018 // Ignore zero sized fields like {}, they obviously contain no data.
1019 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001020
1021 Value *EltVal = SrcVal;
1022 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001023 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001024 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1025 "sroa.store.elt", SI);
1026 }
1027
1028 // Truncate down to an integer of the right size.
1029 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001030 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001031 IntegerType::get(SI->getContext(),
1032 ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001033 Value *DestField = NewElts[i];
1034 if (EltVal->getType() == ArrayEltTy) {
1035 // Storing to an integer field of this size, just do it.
1036 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
1037 // Bitcast to the right element type (for fp/vector values).
1038 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1039 } else {
1040 // Otherwise, bitcast the dest pointer (for aggregates).
1041 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001042 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001043 "", SI);
1044 }
1045 new StoreInst(EltVal, DestField, SI);
1046
1047 if (TD->isBigEndian())
1048 Shift -= ElementOffset;
1049 else
1050 Shift += ElementOffset;
1051 }
1052 }
1053
1054 SI->eraseFromParent();
1055}
1056
Bob Wilson39fdd692009-12-04 21:57:37 +00001057/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001058/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001059void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001060 SmallVector<AllocaInst*, 32> &NewElts) {
1061 // Extract each element out of the NewElts according to its structure offset
1062 // and form the result value.
1063 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001064 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001065
1066 // If this isn't a load of the whole alloca to an integer, it may be a load
1067 // of the first element. Just ignore the load in this case and normal SROA
Eli Friedman41b33f42009-06-01 09:14:32 +00001068 // will handle it.
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001069 if (!isa<IntegerType>(LI->getType()) ||
Eli Friedman41b33f42009-06-01 09:14:32 +00001070 TD->getTypeAllocSizeInBits(LI->getType()) != AllocaSizeBits)
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001071 return;
1072
Nick Lewycky59136252009-09-15 07:08:25 +00001073 DEBUG(errs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
1074 << '\n');
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001075
1076 // There are two forms here: AI could be an array or struct. Both cases
1077 // have different ways to compute the element offset.
1078 const StructLayout *Layout = 0;
1079 uint64_t ArrayEltBitOffset = 0;
1080 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1081 Layout = TD->getStructLayout(EltSTy);
1082 } else {
1083 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001084 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001085 }
Owen Andersone922c022009-07-22 00:24:57 +00001086
Owen Andersone922c022009-07-22 00:24:57 +00001087 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001088 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001089
1090 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1091 // Load the value from the alloca. If the NewElt is an aggregate, cast
1092 // the pointer to an integer of the same size before doing the load.
1093 Value *SrcField = NewElts[i];
1094 const Type *FieldTy =
1095 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001096 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1097
1098 // Ignore zero sized fields like {}, they obviously contain no data.
1099 if (FieldSizeBits == 0) continue;
1100
Owen Anderson1d0be152009-08-13 21:58:54 +00001101 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1102 FieldSizeBits);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001103 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1104 !isa<VectorType>(FieldTy))
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001105 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001106 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001107 "", LI);
1108 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1109
1110 // If SrcField is a fp or vector of the right size but that isn't an
1111 // integer type, bitcast to an integer so we can shift it.
1112 if (SrcField->getType() != FieldIntTy)
1113 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1114
1115 // Zero extend the field to be the same size as the final alloca so that
1116 // we can shift and insert it.
1117 if (SrcField->getType() != ResultVal->getType())
1118 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1119
1120 // Determine the number of bits to shift SrcField.
1121 uint64_t Shift;
1122 if (Layout) // Struct case.
1123 Shift = Layout->getElementOffsetInBits(i);
1124 else // Array case.
1125 Shift = i*ArrayEltBitOffset;
1126
1127 if (TD->isBigEndian())
1128 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1129
1130 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001131 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001132 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1133 }
1134
1135 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1136 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001137
1138 // Handle tail padding by truncating the result
1139 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1140 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1141
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001142 LI->replaceAllUsesWith(ResultVal);
1143 LI->eraseFromParent();
1144}
1145
Chris Lattner372dda82007-03-05 07:52:57 +00001146
Duncan Sands3cb36502007-11-04 14:43:57 +00001147/// HasPadding - Return true if the specified type has any structure or
1148/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001149static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001150 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1151 const StructLayout *SL = TD.getStructLayout(STy);
1152 unsigned PrevFieldBitOffset = 0;
1153 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001154 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1155
Chris Lattner39a1c042007-05-30 06:11:23 +00001156 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001157 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001158 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001159
Chris Lattner39a1c042007-05-30 06:11:23 +00001160 // Check to see if there is any padding between this element and the
1161 // previous one.
1162 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001163 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001164 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1165 if (PrevFieldEnd < FieldBitOffset)
1166 return true;
1167 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001168
Chris Lattner39a1c042007-05-30 06:11:23 +00001169 PrevFieldBitOffset = FieldBitOffset;
1170 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001171
Chris Lattner39a1c042007-05-30 06:11:23 +00001172 // Check for tail padding.
1173 if (unsigned EltCount = STy->getNumElements()) {
1174 unsigned PrevFieldEnd = PrevFieldBitOffset +
1175 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001176 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001177 return true;
1178 }
1179
1180 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001181 return HasPadding(ATy->getElementType(), TD);
Duncan Sands3cb36502007-11-04 14:43:57 +00001182 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001183 return HasPadding(VTy->getElementType(), TD);
Chris Lattner39a1c042007-05-30 06:11:23 +00001184 }
Duncan Sands777d2302009-05-09 07:06:46 +00001185 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001186}
Chris Lattner372dda82007-03-05 07:52:57 +00001187
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001188/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1189/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1190/// or 1 if safe after canonicalization has been performed.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001191int SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001192 // Loop over the use list of the alloca. We can only transform it if all of
1193 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001194 AllocaInfo Info;
1195
Chris Lattner5e062a12003-05-30 04:15:41 +00001196 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001197 I != E; ++I) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001198 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1199 if (Info.isUnsafe) {
Nick Lewycky59136252009-09-15 07:08:25 +00001200 DEBUG(errs() << "Cannot transform: " << *AI << "\n due to user: "
1201 << **I << '\n');
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001202 return 0;
Chris Lattner5e062a12003-05-30 04:15:41 +00001203 }
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001204 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001205
1206 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1207 // source and destination, we have to be careful. In particular, the memcpy
1208 // could be moving around elements that live in structure padding of the LLVM
1209 // types, but may actually be used. In these cases, we refuse to promote the
1210 // struct.
1211 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Chris Lattner56c38522009-01-07 06:34:28 +00001212 HasPadding(AI->getType()->getElementType(), *TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001213 return 0;
Duncan Sands3cb36502007-11-04 14:43:57 +00001214
Chris Lattner39a1c042007-05-30 06:11:23 +00001215 // If we require cleanup, return 1, otherwise return 3.
Devang Patel4afc90d2009-02-10 07:00:59 +00001216 return Info.needsCleanup ? 1 : 3;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001217}
1218
Devang Patel4afc90d2009-02-10 07:00:59 +00001219/// CleanupGEP - GEP is used by an Alloca, which can be prompted after the GEP
1220/// is canonicalized here.
1221void SROA::CleanupGEP(GetElementPtrInst *GEPI) {
1222 gep_type_iterator I = gep_type_begin(GEPI);
1223 ++I;
1224
Devang Patel7afe8fa2009-02-10 19:28:07 +00001225 const ArrayType *AT = dyn_cast<ArrayType>(*I);
1226 if (!AT)
1227 return;
1228
1229 uint64_t NumElements = AT->getNumElements();
1230
1231 if (isa<ConstantInt>(I.getOperand()))
1232 return;
1233
1234 if (NumElements == 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001235 GEPI->setOperand(2,
1236 Constant::getNullValue(Type::getInt32Ty(GEPI->getContext())));
Devang Patel7afe8fa2009-02-10 19:28:07 +00001237 return;
1238 }
Devang Patel4afc90d2009-02-10 07:00:59 +00001239
Devang Patel7afe8fa2009-02-10 19:28:07 +00001240 assert(NumElements == 2 && "Unhandled case!");
1241 // All users of the GEP must be loads. At each use of the GEP, insert
1242 // two loads of the appropriate indexed GEP and select between them.
Owen Anderson333c4002009-07-09 23:48:35 +00001243 Value *IsOne = new ICmpInst(GEPI, ICmpInst::ICMP_NE, I.getOperand(),
Owen Andersona7235ea2009-07-31 20:28:14 +00001244 Constant::getNullValue(I.getOperand()->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001245 "isone");
Devang Patel7afe8fa2009-02-10 19:28:07 +00001246 // Insert the new GEP instructions, which are properly indexed.
1247 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
Owen Anderson1d0be152009-08-13 21:58:54 +00001248 Indices[1] = Constant::getNullValue(Type::getInt32Ty(GEPI->getContext()));
Devang Patel7afe8fa2009-02-10 19:28:07 +00001249 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1250 Indices.begin(),
1251 Indices.end(),
1252 GEPI->getName()+".0", GEPI);
Owen Anderson1d0be152009-08-13 21:58:54 +00001253 Indices[1] = ConstantInt::get(Type::getInt32Ty(GEPI->getContext()), 1);
Devang Patel7afe8fa2009-02-10 19:28:07 +00001254 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1255 Indices.begin(),
1256 Indices.end(),
1257 GEPI->getName()+".1", GEPI);
1258 // Replace all loads of the variable index GEP with loads from both
1259 // indexes and a select.
1260 while (!GEPI->use_empty()) {
1261 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1262 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1263 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
1264 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
1265 LI->replaceAllUsesWith(R);
1266 LI->eraseFromParent();
Devang Patel4afc90d2009-02-10 07:00:59 +00001267 }
Devang Patel7afe8fa2009-02-10 19:28:07 +00001268 GEPI->eraseFromParent();
Devang Patel4afc90d2009-02-10 07:00:59 +00001269}
1270
Devang Patel7afe8fa2009-02-10 19:28:07 +00001271
Devang Patel4afc90d2009-02-10 07:00:59 +00001272/// CleanupAllocaUsers - If SROA reported that it can promote the specified
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001273/// allocation, but only if cleaned up, perform the cleanups required.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001274void SROA::CleanupAllocaUsers(AllocaInst *AI) {
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001275 // At this point, we know that the end result will be SROA'd and promoted, so
1276 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1277 // up.
1278 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1279 UI != E; ) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001280 User *U = *UI++;
1281 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
1282 CleanupGEP(GEPI);
Jay Foad0906b1b2009-06-06 17:49:35 +00001283 else {
1284 Instruction *I = cast<Instruction>(U);
Devang Patel4afc90d2009-02-10 07:00:59 +00001285 SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
Zhou Shengb0c41992009-03-18 12:48:48 +00001286 if (!isa<StoreInst>(I) && OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001287 // Safe to remove debug info uses.
1288 while (!DbgInUses.empty()) {
1289 DbgInfoIntrinsic *DI = DbgInUses.back(); DbgInUses.pop_back();
1290 DI->eraseFromParent();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001291 }
Devang Patel4afc90d2009-02-10 07:00:59 +00001292 I->eraseFromParent();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001293 }
1294 }
1295 }
Chris Lattner5e062a12003-05-30 04:15:41 +00001296}
Chris Lattnera1888942005-12-12 07:19:13 +00001297
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001298/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1299/// the offset specified by Offset (which is specified in bytes).
Chris Lattnerde6df882006-04-14 21:42:41 +00001300///
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001301/// There are two cases we handle here:
1302/// 1) A union of vector types of the same size and potentially its elements.
Chris Lattnerd22dbdf2006-12-15 07:32:38 +00001303/// Here we turn element accesses into insert/extract element operations.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001304/// This promotes a <4 x float> with a store of float to the third element
1305/// into a <4 x float> that uses insert element.
1306/// 2) A fully general blob of memory, which we turn into some (potentially
1307/// large) integer type with extract and insert operations where the loads
1308/// and stores would mutate the memory.
Chris Lattner7809ecd2009-02-03 01:30:09 +00001309static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001310 unsigned AllocaSize, const TargetData &TD,
Owen Andersone922c022009-07-22 00:24:57 +00001311 LLVMContext &Context) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001312 // If this could be contributing to a vector, analyze it.
Owen Anderson1d0be152009-08-13 21:58:54 +00001313 if (VecTy != Type::getVoidTy(Context)) { // either null or a vector type.
Chris Lattner996d7a92009-02-02 18:02:59 +00001314
Chris Lattner7809ecd2009-02-03 01:30:09 +00001315 // If the In type is a vector that is the same size as the alloca, see if it
1316 // matches the existing VecTy.
1317 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1318 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1319 // If we're storing/loading a vector of the right size, allow it as a
1320 // vector. If this the first vector we see, remember the type so that
1321 // we know the element size.
1322 if (VecTy == 0)
1323 VecTy = VInTy;
1324 return;
1325 }
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001326 } else if (In->isFloatTy() || In->isDoubleTy() ||
Chris Lattner7809ecd2009-02-03 01:30:09 +00001327 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1328 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1329 // If we're accessing something that could be an element of a vector, see
1330 // if the implied vector agrees with what we already have and if Offset is
1331 // compatible with it.
1332 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1333 if (Offset % EltSize == 0 &&
1334 AllocaSize % EltSize == 0 &&
1335 (VecTy == 0 ||
1336 cast<VectorType>(VecTy)->getElementType()
1337 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1338 if (VecTy == 0)
Owen Andersondebcb012009-07-29 22:17:13 +00001339 VecTy = VectorType::get(In, AllocaSize/EltSize);
Chris Lattner7809ecd2009-02-03 01:30:09 +00001340 return;
1341 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001342 }
1343 }
1344
Chris Lattner7809ecd2009-02-03 01:30:09 +00001345 // Otherwise, we have a case that we can't handle with an optimized vector
1346 // form. We can still turn this into a large integer.
Owen Anderson1d0be152009-08-13 21:58:54 +00001347 VecTy = Type::getVoidTy(Context);
Chris Lattnera1888942005-12-12 07:19:13 +00001348}
1349
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001350/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
Chris Lattner7809ecd2009-02-03 01:30:09 +00001351/// its accesses to use a to single vector type, return true, and set VecTy to
1352/// the new type. If we could convert the alloca into a single promotable
1353/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1354/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1355/// is the current offset from the base of the alloca being analyzed.
Chris Lattnera1888942005-12-12 07:19:13 +00001356///
Chris Lattner1a3257b2009-02-03 18:15:05 +00001357/// If we see at least one access to the value that is as a vector type, set the
1358/// SawVec flag.
Chris Lattner1a3257b2009-02-03 18:15:05 +00001359bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1360 bool &SawVec, uint64_t Offset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001361 unsigned AllocaSize) {
Chris Lattnera1888942005-12-12 07:19:13 +00001362 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1363 Instruction *User = cast<Instruction>(*UI);
1364
1365 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001366 // Don't break volatile loads.
Chris Lattner6e733d32009-01-28 20:16:43 +00001367 if (LI->isVolatile())
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001368 return false;
Owen Andersone922c022009-07-22 00:24:57 +00001369 MergeInType(LI->getType(), Offset, VecTy,
1370 AllocaSize, *TD, V->getContext());
Chris Lattner1a3257b2009-02-03 18:15:05 +00001371 SawVec |= isa<VectorType>(LI->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001372 continue;
1373 }
1374
1375 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001376 // Storing the pointer, not into the value?
Chris Lattner6e733d32009-01-28 20:16:43 +00001377 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001378 MergeInType(SI->getOperand(0)->getType(), Offset,
Owen Andersone922c022009-07-22 00:24:57 +00001379 VecTy, AllocaSize, *TD, V->getContext());
Chris Lattner1a3257b2009-02-03 18:15:05 +00001380 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001381 continue;
1382 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001383
1384 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattner1a3257b2009-02-03 18:15:05 +00001385 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1386 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001387 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001388 IsNotTrivial = true;
Chris Lattnercf321862009-01-07 06:39:58 +00001389 continue;
1390 }
1391
1392 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001393 // If this is a GEP with a variable indices, we can't handle it.
1394 if (!GEP->hasAllConstantIndices())
1395 return false;
Chris Lattnercf321862009-01-07 06:39:58 +00001396
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001397 // Compute the offset that this GEP adds to the pointer.
1398 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1399 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1400 &Indices[0], Indices.size());
1401 // See if all uses can be converted.
Chris Lattner1a3257b2009-02-03 18:15:05 +00001402 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001403 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001404 return false;
1405 IsNotTrivial = true;
1406 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001407 }
Chris Lattner3ce5e882009-03-08 03:37:16 +00001408
Chris Lattner3d730f72009-02-03 02:01:43 +00001409 // If this is a constant sized memset of a constant value (e.g. 0) we can
1410 // handle it.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001411 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1412 // Store of constant value and constant size.
1413 if (isa<ConstantInt>(MSI->getValue()) &&
1414 isa<ConstantInt>(MSI->getLength())) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001415 IsNotTrivial = true;
1416 continue;
1417 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001418 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001419
1420 // If this is a memcpy or memmove into or out of the whole allocation, we
1421 // can handle it like a load or store of the scalar type.
1422 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1423 if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
1424 if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1425 IsNotTrivial = true;
1426 continue;
1427 }
1428 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001429
Devang Patel00e389c2009-03-06 07:03:54 +00001430 // Ignore dbg intrinsic.
1431 if (isa<DbgInfoIntrinsic>(User))
1432 continue;
1433
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001434 // Otherwise, we cannot handle this!
1435 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001436 }
1437
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001438 return true;
Chris Lattnera1888942005-12-12 07:19:13 +00001439}
1440
Chris Lattnera1888942005-12-12 07:19:13 +00001441/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattnerde6df882006-04-14 21:42:41 +00001442/// directly. This happens when we are converting an "integer union" to a
1443/// single integer scalar, or when we are converting a "vector union" to a
1444/// vector with insert/extractelement instructions.
1445///
1446/// Offset is an offset from the original alloca, in bits that need to be
1447/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001448void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
Chris Lattnera1888942005-12-12 07:19:13 +00001449 while (!Ptr->use_empty()) {
1450 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001451
Chris Lattnercf321862009-01-07 06:39:58 +00001452 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb10e0da2008-01-30 00:39:15 +00001453 ConvertUsesToScalar(CI, NewAI, Offset);
Chris Lattnera1888942005-12-12 07:19:13 +00001454 CI->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001455 continue;
1456 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001457
Chris Lattnercf321862009-01-07 06:39:58 +00001458 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001459 // Compute the offset that this GEP adds to the pointer.
1460 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1461 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1462 &Indices[0], Indices.size());
1463 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Chris Lattnera1888942005-12-12 07:19:13 +00001464 GEP->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001465 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001466 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001467
Chris Lattner9bc67da2009-02-03 19:45:44 +00001468 IRBuilder<> Builder(User->getParent(), User);
1469
1470 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner6e011152009-02-03 21:01:03 +00001471 // The load is a bit extract from NewAI shifted right by Offset bits.
1472 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1473 Value *NewLoadVal
1474 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1475 LI->replaceAllUsesWith(NewLoadVal);
Chris Lattner9bc67da2009-02-03 19:45:44 +00001476 LI->eraseFromParent();
1477 continue;
1478 }
1479
1480 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1481 assert(SI->getOperand(0) != Ptr && "Consistency error!");
Benjamin Kramere6f32942009-11-29 21:17:48 +00001482 // FIXME: Remove once builder has Twine API.
Bob Wilsond614a1f2009-12-04 21:51:35 +00001483 Value *Old = Builder.CreateLoad(NewAI,
1484 (NewAI->getName()+".in").str().c_str());
Chris Lattner9bc67da2009-02-03 19:45:44 +00001485 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1486 Builder);
1487 Builder.CreateStore(New, NewAI);
1488 SI->eraseFromParent();
1489 continue;
1490 }
1491
Chris Lattner3d730f72009-02-03 02:01:43 +00001492 // If this is a constant sized memset of a constant value (e.g. 0) we can
1493 // transform it into a store of the expanded constant value.
1494 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1495 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1496 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Chris Lattner33e24ad2009-04-21 16:52:12 +00001497 if (NumBytes != 0) {
1498 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1499
1500 // Compute the value replicated the right number of times.
1501 APInt APVal(NumBytes*8, Val);
Chris Lattner3d730f72009-02-03 02:01:43 +00001502
Chris Lattner33e24ad2009-04-21 16:52:12 +00001503 // Splat the value if non-zero.
1504 if (Val)
1505 for (unsigned i = 1; i != NumBytes; ++i)
1506 APVal |= APVal << 8;
Benjamin Kramere6f32942009-11-29 21:17:48 +00001507
1508 // FIXME: Remove once builder has Twine API.
Bob Wilsond614a1f2009-12-04 21:51:35 +00001509 Value *Old = Builder.CreateLoad(NewAI,
1510 (NewAI->getName()+".in").str().c_str());
Owen Andersone922c022009-07-22 00:24:57 +00001511 Value *New = ConvertScalar_InsertValue(
Owen Andersoneed707b2009-07-24 23:12:02 +00001512 ConstantInt::get(User->getContext(), APVal),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001513 Old, Offset, Builder);
Chris Lattner33e24ad2009-04-21 16:52:12 +00001514 Builder.CreateStore(New, NewAI);
1515 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001516 MSI->eraseFromParent();
1517 continue;
1518 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001519
1520 // If this is a memcpy or memmove into or out of the whole allocation, we
1521 // can handle it like a load or store of the scalar type.
1522 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1523 assert(Offset == 0 && "must be store to start of alloca");
1524
1525 // If the source and destination are both to the same alloca, then this is
1526 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
1527 // as appropriate.
1528 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject());
1529
1530 if (MTI->getSource()->getUnderlyingObject() != OrigAI) {
1531 // Dest must be OrigAI, change this to be a load from the original
1532 // pointer (bitcasted), then a store to our new alloca.
1533 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1534 Value *SrcPtr = MTI->getSource();
1535 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1536
1537 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1538 SrcVal->setAlignment(MTI->getAlignment());
1539 Builder.CreateStore(SrcVal, NewAI);
1540 } else if (MTI->getDest()->getUnderlyingObject() != OrigAI) {
1541 // Src must be OrigAI, change this to be a load from NewAI then a store
1542 // through the original dest pointer (bitcasted).
1543 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1544 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1545
1546 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1547 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1548 NewStore->setAlignment(MTI->getAlignment());
1549 } else {
1550 // Noop transfer. Src == Dst
1551 }
1552
1553
1554 MTI->eraseFromParent();
1555 continue;
1556 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001557
Devang Patel00e389c2009-03-06 07:03:54 +00001558 // If user is a dbg info intrinsic then it is safe to remove it.
1559 if (isa<DbgInfoIntrinsic>(User)) {
1560 User->eraseFromParent();
1561 continue;
1562 }
1563
Torok Edwinc23197a2009-07-14 16:55:14 +00001564 llvm_unreachable("Unsupported operation!");
Chris Lattnera1888942005-12-12 07:19:13 +00001565 }
1566}
Chris Lattner79b3bd32007-04-25 06:40:51 +00001567
Chris Lattner6e011152009-02-03 21:01:03 +00001568/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1569/// or vector value FromVal, extracting the bits from the offset specified by
1570/// Offset. This returns the value, which is of type ToType.
1571///
1572/// This happens when we are converting an "integer union" to a single
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001573/// integer scalar, or when we are converting a "vector union" to a vector with
1574/// insert/extractelement instructions.
Chris Lattner800de312008-02-29 07:03:13 +00001575///
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001576/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner6e011152009-02-03 21:01:03 +00001577/// shifted to the right.
1578Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1579 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001580 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattner6e011152009-02-03 21:01:03 +00001581 if (FromVal->getType() == ToType && Offset == 0)
1582 return FromVal;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001583
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001584 // If the result alloca is a vector type, this is either an element
1585 // access or a bitcast to another vector type of the same size.
Chris Lattner6e011152009-02-03 21:01:03 +00001586 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1587 if (isa<VectorType>(ToType))
1588 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001589
1590 // Otherwise it must be an element access.
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001591 unsigned Elt = 0;
1592 if (Offset) {
Duncan Sands777d2302009-05-09 07:06:46 +00001593 unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001594 Elt = Offset/EltSize;
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001595 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner800de312008-02-29 07:03:13 +00001596 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001597 // Return the element extracted out of it.
Owen Anderson1d0be152009-08-13 21:58:54 +00001598 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
1599 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
Chris Lattner6e011152009-02-03 21:01:03 +00001600 if (V->getType() != ToType)
1601 V = Builder.CreateBitCast(V, ToType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001602 return V;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001603 }
Chris Lattner1aa70562009-02-03 21:08:45 +00001604
1605 // If ToType is a first class aggregate, extract out each of the pieces and
1606 // use insertvalue's to form the FCA.
1607 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1608 const StructLayout &Layout = *TD->getStructLayout(ST);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001609 Value *Res = UndefValue::get(ST);
Chris Lattner1aa70562009-02-03 21:08:45 +00001610 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1611 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
Chris Lattnere991ced2009-02-06 04:34:07 +00001612 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner1aa70562009-02-03 21:08:45 +00001613 Builder);
1614 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1615 }
1616 return Res;
1617 }
1618
1619 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001620 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001621 Value *Res = UndefValue::get(AT);
Chris Lattner1aa70562009-02-03 21:08:45 +00001622 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1623 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1624 Offset+i*EltSize, Builder);
1625 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1626 }
1627 return Res;
1628 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001629
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001630 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattner6e011152009-02-03 21:01:03 +00001631 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001632
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001633 // If this is a big-endian system and the load is narrower than the
1634 // full alloca type, we need to do a shift to get the right bits.
1635 int ShAmt = 0;
Chris Lattner56c38522009-01-07 06:34:28 +00001636 if (TD->isBigEndian()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001637 // On big-endian machines, the lowest bit is stored at the bit offset
1638 // from the pointer given by getTypeStoreSizeInBits. This matters for
1639 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner56c38522009-01-07 06:34:28 +00001640 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
Chris Lattner6e011152009-02-03 21:01:03 +00001641 TD->getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001642 } else {
1643 ShAmt = Offset;
1644 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001645
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001646 // Note: we support negative bitwidths (with shl) which are not defined.
1647 // We do this to support (f.e.) loads off the end of a structure where
1648 // only some bits are used.
1649 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001650 FromVal = Builder.CreateLShr(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001651 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001652 ShAmt), "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001653 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001654 FromVal = Builder.CreateShl(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001655 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001656 -ShAmt), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001657
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001658 // Finally, unconditionally truncate the integer to the right width.
Chris Lattner6e011152009-02-03 21:01:03 +00001659 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001660 if (LIBitWidth < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001661 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001662 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
1663 LIBitWidth), "tmp");
Chris Lattner55a683d2009-02-03 07:08:57 +00001664 else if (LIBitWidth > NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001665 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001666 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
1667 LIBitWidth), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001668
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001669 // If the result is an integer, this is a trunc or bitcast.
Chris Lattner6e011152009-02-03 21:01:03 +00001670 if (isa<IntegerType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001671 // Should be done.
Chris Lattner6e011152009-02-03 21:01:03 +00001672 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001673 // Just do a bitcast, we know the sizes match up.
Chris Lattner6e011152009-02-03 21:01:03 +00001674 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001675 } else {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001676 // Otherwise must be a pointer.
Chris Lattner6e011152009-02-03 21:01:03 +00001677 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001678 }
Chris Lattner6e011152009-02-03 21:01:03 +00001679 assert(FromVal->getType() == ToType && "Didn't convert right?");
1680 return FromVal;
Chris Lattner800de312008-02-29 07:03:13 +00001681}
1682
Chris Lattner9b872db2009-02-03 19:30:11 +00001683/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1684/// or vector value "Old" at the offset specified by Offset.
1685///
1686/// This happens when we are converting an "integer union" to a
Chris Lattner800de312008-02-29 07:03:13 +00001687/// single integer scalar, or when we are converting a "vector union" to a
1688/// vector with insert/extractelement instructions.
1689///
1690/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner9b872db2009-02-03 19:30:11 +00001691/// shifted to the right.
1692Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
Chris Lattner65a65022009-02-03 19:41:50 +00001693 uint64_t Offset, IRBuilder<> &Builder) {
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001694
Chris Lattner800de312008-02-29 07:03:13 +00001695 // Convert the stored type to the actual type, shift it left to insert
1696 // then 'or' into place.
Chris Lattner9b872db2009-02-03 19:30:11 +00001697 const Type *AllocaType = Old->getType();
Owen Andersone922c022009-07-22 00:24:57 +00001698 LLVMContext &Context = Old->getContext();
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001699
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001700 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001701 uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1702 uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
Chris Lattner29e64172009-03-08 04:17:04 +00001703
1704 // Changing the whole vector with memset or with an access of a different
1705 // vector type?
1706 if (ValSize == VecSize)
1707 return Builder.CreateBitCast(SV, AllocaType, "tmp");
1708
Duncan Sands777d2302009-05-09 07:06:46 +00001709 uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner29e64172009-03-08 04:17:04 +00001710
1711 // Must be an element insertion.
1712 unsigned Elt = Offset/EltSize;
1713
1714 if (SV->getType() != VTy->getElementType())
1715 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1716
1717 SV = Builder.CreateInsertElement(Old, SV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001718 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
Chris Lattner29e64172009-03-08 04:17:04 +00001719 "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001720 return SV;
1721 }
Chris Lattner9b872db2009-02-03 19:30:11 +00001722
1723 // If SV is a first-class aggregate value, insert each value recursively.
1724 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1725 const StructLayout &Layout = *TD->getStructLayout(ST);
1726 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001727 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Chris Lattner9b872db2009-02-03 19:30:11 +00001728 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattnere991ced2009-02-06 04:34:07 +00001729 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner65a65022009-02-03 19:41:50 +00001730 Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001731 }
1732 return Old;
1733 }
1734
1735 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Duncan Sands777d2302009-05-09 07:06:46 +00001736 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner9b872db2009-02-03 19:30:11 +00001737 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001738 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1739 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001740 }
1741 return Old;
1742 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001743
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001744 // If SV is a float, convert it to the appropriate integer type.
Chris Lattner9b872db2009-02-03 19:30:11 +00001745 // If it is a pointer, do the same.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001746 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1747 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1748 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1749 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1750 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
Owen Anderson1d0be152009-08-13 21:58:54 +00001751 SV = Builder.CreateBitCast(SV,
1752 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001753 else if (isa<PointerType>(SV->getType()))
Owen Anderson1d0be152009-08-13 21:58:54 +00001754 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(SV->getContext()), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001755
Chris Lattner7809ecd2009-02-03 01:30:09 +00001756 // Zero extend or truncate the value if needed.
1757 if (SV->getType() != AllocaType) {
1758 if (SV->getType()->getPrimitiveSizeInBits() <
1759 AllocaType->getPrimitiveSizeInBits())
Chris Lattner65a65022009-02-03 19:41:50 +00001760 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001761 else {
1762 // Truncation may be needed if storing more than the alloca can hold
1763 // (undefined behavior).
Chris Lattner65a65022009-02-03 19:41:50 +00001764 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001765 SrcWidth = DestWidth;
1766 SrcStoreWidth = DestStoreWidth;
1767 }
1768 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001769
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001770 // If this is a big-endian system and the store is narrower than the
1771 // full alloca type, we need to do a shift to get the right bits.
1772 int ShAmt = 0;
1773 if (TD->isBigEndian()) {
1774 // On big-endian machines, the lowest bit is stored at the bit offset
1775 // from the pointer given by getTypeStoreSizeInBits. This matters for
1776 // integers with a bitwidth that is not a multiple of 8.
1777 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner800de312008-02-29 07:03:13 +00001778 } else {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001779 ShAmt = Offset;
1780 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001781
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001782 // Note: we support negative bitwidths (with shr) which are not defined.
1783 // We do this to support (f.e.) stores off the end of a structure where
1784 // only some bits in the structure are set.
1785 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1786 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001787 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001788 ShAmt), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001789 Mask <<= ShAmt;
1790 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001791 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001792 -ShAmt), "tmp");
Duncan Sands0e7c46b2009-02-02 09:53:14 +00001793 Mask = Mask.lshr(-ShAmt);
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001794 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001795
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001796 // Mask out the bits we are about to insert from the old value, and or
1797 // in the new bits.
1798 if (SrcWidth != DestWidth) {
1799 assert(DestWidth > SrcWidth);
Owen Andersoneed707b2009-07-24 23:12:02 +00001800 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
Chris Lattner65a65022009-02-03 19:41:50 +00001801 SV = Builder.CreateOr(Old, SV, "ins");
Chris Lattner800de312008-02-29 07:03:13 +00001802 }
1803 return SV;
1804}
1805
1806
Chris Lattner79b3bd32007-04-25 06:40:51 +00001807
1808/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1809/// some part of a constant global variable. This intentionally only accepts
1810/// constant expressions because we don't can't rewrite arbitrary instructions.
1811static bool PointsToConstantGlobal(Value *V) {
1812 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1813 return GV->isConstant();
1814 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1815 if (CE->getOpcode() == Instruction::BitCast ||
1816 CE->getOpcode() == Instruction::GetElementPtr)
1817 return PointsToConstantGlobal(CE->getOperand(0));
1818 return false;
1819}
1820
1821/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1822/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1823/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1824/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1825/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1826/// the alloca, and if the source pointer is a pointer to a constant global, we
1827/// can optimize this.
1828static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1829 bool isOffset) {
1830 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Chris Lattner6e733d32009-01-28 20:16:43 +00001831 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1832 // Ignore non-volatile loads, they are always ok.
1833 if (!LI->isVolatile())
1834 continue;
1835
Chris Lattner79b3bd32007-04-25 06:40:51 +00001836 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1837 // If uses of the bitcast are ok, we are ok.
1838 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1839 return false;
1840 continue;
1841 }
1842 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1843 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1844 // doesn't, it does.
1845 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1846 isOffset || !GEP->hasAllZeroIndices()))
1847 return false;
1848 continue;
1849 }
1850
1851 // If this is isn't our memcpy/memmove, reject it as something we can't
1852 // handle.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001853 if (!isa<MemTransferInst>(*UI))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001854 return false;
1855
1856 // If we already have seen a copy, reject the second one.
1857 if (TheCopy) return false;
1858
1859 // If the pointer has been offset from the start of the alloca, we can't
1860 // safely handle this.
1861 if (isOffset) return false;
1862
1863 // If the memintrinsic isn't using the alloca as the dest, reject it.
1864 if (UI.getOperandNo() != 1) return false;
1865
1866 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1867
1868 // If the source of the memcpy/move is not a constant global, reject it.
1869 if (!PointsToConstantGlobal(MI->getOperand(2)))
1870 return false;
1871
1872 // Otherwise, the transform is safe. Remember the copy instruction.
1873 TheCopy = MI;
1874 }
1875 return true;
1876}
1877
1878/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1879/// modified by a copy from a constant global. If we can prove this, we can
1880/// replace any uses of the alloca with uses of the global directly.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001881Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001882 Instruction *TheCopy = 0;
1883 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1884 return TheCopy;
1885 return 0;
1886}