blob: a941d5760d0371b548b3277c01e0cf708bd094e4 [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
Bob Wilsonb742def2009-12-18 20:14:40 +000077 /// DeadInsts - Keep track of instructions we have made dead, so that
78 /// we can remove them after we are done working.
79 SmallVector<Value*, 32> DeadInsts;
80
Chris Lattner39a1c042007-05-30 06:11:23 +000081 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
82 /// information about the uses. All these fields are initialized to false
83 /// and set to true when something is learned.
84 struct AllocaInfo {
85 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
86 bool isUnsafe : 1;
87
Devang Patel4afc90d2009-02-10 07:00:59 +000088 /// needsCleanup - This is set to true if there is some use of the alloca
89 /// that requires cleanup.
90 bool needsCleanup : 1;
Chris Lattner39a1c042007-05-30 06:11:23 +000091
92 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
93 bool isMemCpySrc : 1;
94
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000095 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000096 bool isMemCpyDst : 1;
97
98 AllocaInfo()
Devang Patel4afc90d2009-02-10 07:00:59 +000099 : isUnsafe(false), needsCleanup(false),
Chris Lattner39a1c042007-05-30 06:11:23 +0000100 isMemCpySrc(false), isMemCpyDst(false) {}
101 };
102
Devang Patelff366852007-07-09 21:19:23 +0000103 unsigned SRThreshold;
104
Chris Lattner39a1c042007-05-30 06:11:23 +0000105 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
106
Victor Hernandez7b929da2009-10-23 21:09:37 +0000107 int isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000108
Bob Wilsonb742def2009-12-18 20:14:40 +0000109 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
110 uint64_t ArrayOffset, AllocaInfo &Info);
111 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
112 uint64_t &ArrayOffset, AllocaInfo &Info);
113 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t ArrayOffset,
114 uint64_t MemSize, const Type *MemOpType, bool isStore,
115 AllocaInfo &Info);
116 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000117 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
118 const Type *&IdxTy);
Chris Lattner39a1c042007-05-30 06:11:23 +0000119
Victor Hernandez7b929da2009-10-23 21:09:37 +0000120 void DoScalarReplacement(AllocaInst *AI,
121 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000122 void DeleteDeadInstructions();
Devang Patel4afc90d2009-02-10 07:00:59 +0000123 void CleanupGEP(GetElementPtrInst *GEP);
Bob Wilsonb742def2009-12-18 20:14:40 +0000124 void CleanupAllocaUsers(Value *V);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000125 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocaInst *Base);
Chris Lattnera1888942005-12-12 07:19:13 +0000126
Bob Wilsonb742def2009-12-18 20:14:40 +0000127 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
128 SmallVector<AllocaInst*, 32> &NewElts);
129 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
130 SmallVector<AllocaInst*, 32> &NewElts);
131 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
132 SmallVector<AllocaInst*, 32> &NewElts);
133 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000134 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000135 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000136 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000137 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000138 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000139 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000140
Chris Lattner7809ecd2009-02-03 01:30:09 +0000141 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
Chris Lattner1a3257b2009-02-03 18:15:05 +0000142 bool &SawVec, uint64_t Offset, unsigned AllocaSize);
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000143 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Chris Lattner6e011152009-02-03 21:01:03 +0000144 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
Chris Lattner9bc67da2009-02-03 19:45:44 +0000145 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +0000146 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Chris Lattner65a65022009-02-03 19:41:50 +0000147 uint64_t Offset, IRBuilder<> &Builder);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000148 static Instruction *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000149 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000150}
151
Dan Gohman844731a2008-05-13 00:00:25 +0000152char SROA::ID = 0;
153static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
154
Brian Gaeked0fde302003-11-11 22:41:34 +0000155// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000156FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
157 return new SROA(Threshold);
158}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000159
160
Chris Lattnered7b41e2003-05-27 15:45:27 +0000161bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000162 TD = getAnalysisIfAvailable<TargetData>();
163
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000164 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000165
166 // FIXME: ScalarRepl currently depends on TargetData more than it
167 // theoretically needs to. It should be refactored in order to support
168 // target-independent IR. Until this is done, just skip the actual
169 // scalar-replacement portion of this pass.
170 if (!TD) return Changed;
171
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000172 while (1) {
173 bool LocalChange = performScalarRepl(F);
174 if (!LocalChange) break; // No need to repromote if no scalarrepl
175 Changed = true;
176 LocalChange = performPromotion(F);
177 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
178 }
Chris Lattner38aec322003-09-11 16:45:55 +0000179
180 return Changed;
181}
182
183
184bool SROA::performPromotion(Function &F) {
185 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000186 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000187 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000188
Chris Lattner02a3be02003-09-20 14:39:18 +0000189 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000190
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000191 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000192
Chris Lattner38aec322003-09-11 16:45:55 +0000193 while (1) {
194 Allocas.clear();
195
196 // Find allocas that are safe to promote, by looking at all instructions in
197 // the entry node
198 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
199 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000200 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000201 Allocas.push_back(AI);
202
203 if (Allocas.empty()) break;
204
Nick Lewyckyce2c51b2009-11-23 03:50:44 +0000205 PromoteMemToReg(Allocas, DT, DF);
Chris Lattner38aec322003-09-11 16:45:55 +0000206 NumPromoted += Allocas.size();
207 Changed = true;
208 }
209
210 return Changed;
211}
212
Chris Lattner963a97f2008-06-22 17:46:21 +0000213/// getNumSAElements - Return the number of elements in the specific struct or
214/// array.
215static uint64_t getNumSAElements(const Type *T) {
216 if (const StructType *ST = dyn_cast<StructType>(T))
217 return ST->getNumElements();
218 return cast<ArrayType>(T)->getNumElements();
219}
220
Chris Lattner38aec322003-09-11 16:45:55 +0000221// performScalarRepl - This algorithm is a simple worklist driven algorithm,
222// which runs on all of the malloc/alloca instructions in the function, removing
223// them if they are only used by getelementptr instructions.
224//
225bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000226 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000227
228 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner02a3be02003-09-20 14:39:18 +0000229 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000230 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000231 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000232 WorkList.push_back(A);
233
234 // Process the worklist
235 bool Changed = false;
236 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000237 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000238 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000239
Chris Lattneradd2bd72006-12-22 23:14:42 +0000240 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
241 // with unused elements.
242 if (AI->use_empty()) {
243 AI->eraseFromParent();
244 continue;
245 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000246
247 // If this alloca is impossible for us to promote, reject it early.
248 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
249 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000250
251 // Check to see if this allocation is only modified by a memcpy/memmove from
252 // a constant global. If this is the case, we can change all users to use
253 // the constant global instead. This is commonly produced by the CFE by
254 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
255 // is only subsequently read.
256 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
Nick Lewycky59136252009-09-15 07:08:25 +0000257 DEBUG(errs() << "Found alloca equal to global: " << *AI << '\n');
258 DEBUG(errs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner79b3bd32007-04-25 06:40:51 +0000259 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000260 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000261 TheCopy->eraseFromParent(); // Don't mutate the global.
262 AI->eraseFromParent();
263 ++NumGlobals;
264 Changed = true;
265 continue;
266 }
Chris Lattner15c82772009-02-02 20:44:45 +0000267
Chris Lattner7809ecd2009-02-03 01:30:09 +0000268 // Check to see if we can perform the core SROA transformation. We cannot
269 // transform the allocation instruction if it is an array allocation
270 // (allocations OF arrays are ok though), and an allocation of a scalar
271 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000272 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000273
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000274 // Do not promote [0 x %struct].
275 if (AllocaSize == 0) continue;
276
Bill Wendling5a377cb2009-03-03 12:12:58 +0000277 // Do not promote any struct whose size is too big.
Bill Wendling3aaf5d92009-03-03 19:18:49 +0000278 if (AllocaSize > SRThreshold) continue;
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000279
Chris Lattner7809ecd2009-02-03 01:30:09 +0000280 if ((isa<StructType>(AI->getAllocatedType()) ||
281 isa<ArrayType>(AI->getAllocatedType())) &&
Chris Lattner7809ecd2009-02-03 01:30:09 +0000282 // Do not promote any struct into more than "32" separate vars.
Evan Cheng67fca632009-03-06 00:56:43 +0000283 getNumSAElements(AI->getAllocatedType()) <= SRThreshold/4) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000284 // Check that all of the users of the allocation are capable of being
285 // transformed.
286 switch (isSafeAllocaToScalarRepl(AI)) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000287 default: llvm_unreachable("Unexpected value!");
Chris Lattner7809ecd2009-02-03 01:30:09 +0000288 case 0: // Not safe to scalar replace.
289 break;
290 case 1: // Safe, but requires cleanup/canonicalizations first
Devang Patel4afc90d2009-02-10 07:00:59 +0000291 CleanupAllocaUsers(AI);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000292 // FALL THROUGH.
293 case 3: // Safe to scalar replace.
294 DoScalarReplacement(AI, WorkList);
295 Changed = true;
296 continue;
297 }
298 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000299
300 // If we can turn this aggregate value (potentially with casts) into a
301 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000302 // IsNotTrivial tracks whether this is something that mem2reg could have
303 // promoted itself. If so, we don't want to transform it needlessly. Note
304 // that we can't just check based on the type: the alloca may be of an i32
305 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner6e733d32009-01-28 20:16:43 +0000306 bool IsNotTrivial = false;
Chris Lattner7809ecd2009-02-03 01:30:09 +0000307 const Type *VectorTy = 0;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000308 bool HadAVector = false;
309 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
Chris Lattner0ff83ab2009-03-04 19:22:30 +0000310 0, unsigned(AllocaSize)) && IsNotTrivial) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000311 AllocaInst *NewAI;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000312 // If we were able to find a vector type that can handle this with
313 // insert/extract elements, and if there was at least one use that had
314 // a vector type, promote this to a vector. We don't want to promote
315 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
316 // we just get a lot of insert/extracts. If at least one vector is
317 // involved, then we probably really do have a union of vector/array.
318 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
Nick Lewycky59136252009-09-15 07:08:25 +0000319 DEBUG(errs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
Chris Lattnerbdff5482009-08-23 04:37:46 +0000320 << *VectorTy << '\n');
Chris Lattner15c82772009-02-02 20:44:45 +0000321
Chris Lattner7809ecd2009-02-03 01:30:09 +0000322 // Create and insert the vector alloca.
Owen Anderson50dead02009-07-15 23:53:25 +0000323 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
Chris Lattner15c82772009-02-02 20:44:45 +0000324 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000325 } else {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000326 DEBUG(errs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
Chris Lattner7809ecd2009-02-03 01:30:09 +0000327
328 // Create and insert the integer alloca.
Owen Anderson1d0be152009-08-13 21:58:54 +0000329 const Type *NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
Owen Anderson50dead02009-07-15 23:53:25 +0000330 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
Chris Lattner7809ecd2009-02-03 01:30:09 +0000331 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner6e733d32009-01-28 20:16:43 +0000332 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000333 NewAI->takeName(AI);
334 AI->eraseFromParent();
335 ++NumConverted;
336 Changed = true;
337 continue;
338 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000339
Chris Lattner7809ecd2009-02-03 01:30:09 +0000340 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000341 }
342
343 return Changed;
344}
Chris Lattner5e062a12003-05-30 04:15:41 +0000345
Chris Lattnera10b29b2007-04-25 05:02:56 +0000346/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
347/// predicate, do SROA now.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000348void SROA::DoScalarReplacement(AllocaInst *AI,
349 std::vector<AllocaInst*> &WorkList) {
Chris Lattnerff114702009-09-15 05:14:57 +0000350 DEBUG(errs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +0000351 SmallVector<AllocaInst*, 32> ElementAllocas;
352 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
353 ElementAllocas.reserve(ST->getNumContainedTypes());
354 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000355 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +0000356 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 } else {
362 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
363 ElementAllocas.reserve(AT->getNumElements());
364 const Type *ElTy = AT->getElementType();
365 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000366 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000367 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000368 ElementAllocas.push_back(NA);
369 WorkList.push_back(NA); // Add to worklist for recursive processing
370 }
371 }
372
Bob Wilsonb742def2009-12-18 20:14:40 +0000373 // Now that we have created the new alloca instructions, rewrite all the
374 // uses of the old alloca.
375 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +0000376
Bob Wilsonb742def2009-12-18 20:14:40 +0000377 // Now erase any instructions that were made dead while rewriting the alloca.
378 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +0000379 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +0000380
Chris Lattnera10b29b2007-04-25 05:02:56 +0000381 NumReplaced++;
382}
Chris Lattnera59adc42009-12-14 05:11:02 +0000383
Bob Wilsonb742def2009-12-18 20:14:40 +0000384/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
385/// recursively including all their operands that become trivially dead.
386void SROA::DeleteDeadInstructions() {
387 while (!DeadInsts.empty()) {
388 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +0000389
Bob Wilsonb742def2009-12-18 20:14:40 +0000390 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
391 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
392 // Zero out the operand and see if it becomes trivially dead.
393 // (But, don't add allocas to the dead instruction list -- they are
394 // already on the worklist and will be deleted separately.)
395 *OI = 0;
396 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
397 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +0000398 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000399
400 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +0000401 }
Chris Lattnera59adc42009-12-14 05:11:02 +0000402}
Bob Wilsonb742def2009-12-18 20:14:40 +0000403
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000404/// AllUsersAreLoads - Return true if all users of this value are loads.
405static bool AllUsersAreLoads(Value *Ptr) {
406 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
407 I != E; ++I)
408 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
409 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000410 return true;
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000411}
412
Bob Wilsonb742def2009-12-18 20:14:40 +0000413/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
414/// performing scalar replacement of alloca AI. The results are flagged in
415/// the Info parameter. Offset and ArrayOffset indicate the position within
416/// AI that is referenced by this instruction.
417void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
418 uint64_t ArrayOffset, AllocaInfo &Info) {
419 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
420 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000421
Bob Wilsonb742def2009-12-18 20:14:40 +0000422 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
423 isSafeForScalarRepl(BC, AI, Offset, ArrayOffset, Info);
424 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
425 uint64_t GEPArrayOffset = ArrayOffset;
426 uint64_t GEPOffset = Offset;
427 isSafeGEP(GEPI, AI, GEPOffset, GEPArrayOffset, Info);
428 if (!Info.isUnsafe)
429 isSafeForScalarRepl(GEPI, AI, GEPOffset, GEPArrayOffset, Info);
430 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
431 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
432 if (Length)
433 isSafeMemAccess(AI, Offset, ArrayOffset, Length->getZExtValue(), 0,
434 UI.getOperandNo() == 1, Info);
435 else
436 MarkUnsafe(Info);
437 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
438 if (!LI->isVolatile()) {
439 const Type *LIType = LI->getType();
440 isSafeMemAccess(AI, Offset, ArrayOffset, TD->getTypeAllocSize(LIType),
441 LIType, false, Info);
442 } else
443 MarkUnsafe(Info);
444 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
445 // Store is ok if storing INTO the pointer, not storing the pointer
446 if (!SI->isVolatile() && SI->getOperand(0) != I) {
447 const Type *SIType = SI->getOperand(0)->getType();
448 isSafeMemAccess(AI, Offset, ArrayOffset, TD->getTypeAllocSize(SIType),
449 SIType, true, Info);
450 } else
451 MarkUnsafe(Info);
452 } else if (isa<DbgInfoIntrinsic>(UI)) {
453 // If one user is DbgInfoIntrinsic then check if all users are
454 // DbgInfoIntrinsics.
455 if (OnlyUsedByDbgInfoIntrinsics(I)) {
456 Info.needsCleanup = true;
457 return;
458 }
459 MarkUnsafe(Info);
460 } else {
461 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
462 MarkUnsafe(Info);
463 }
464 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000465 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000466}
Bob Wilson39c88a62009-12-17 18:34:24 +0000467
Bob Wilsonb742def2009-12-18 20:14:40 +0000468/// isSafeGEP - Check if a GEP instruction can be handled for scalar
469/// replacement. It is safe when all the indices are constant, in-bounds
470/// references, and when the resulting offset corresponds to an element within
471/// the alloca type. The results are flagged in the Info parameter. Upon
472/// return, Offset is adjusted as specified by the GEP indices. For the
473/// special case of a variable index to a 2-element array, ArrayOffset is set
474/// to the array element size.
475void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
476 uint64_t &Offset, uint64_t &ArrayOffset,
477 AllocaInfo &Info) {
478 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
479 if (GEPIt == E)
480 return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000481
Bob Wilsonb742def2009-12-18 20:14:40 +0000482 // The first GEP index must be zero.
483 if (!isa<ConstantInt>(GEPIt.getOperand()) ||
484 !cast<ConstantInt>(GEPIt.getOperand())->isZero())
485 return MarkUnsafe(Info);
486 if (++GEPIt == E)
487 return;
488
Chris Lattner88e6dc82008-08-23 05:21:06 +0000489 // If the first index is a non-constant index into an array, see if we can
490 // handle it as a special case.
Bob Wilsonb742def2009-12-18 20:14:40 +0000491 const Type *ArrayEltTy = 0;
Bob Wilsone88728d2009-12-19 06:53:17 +0000492 if (!isa<ConstantInt>(GEPIt.getOperand()) &&
493 ArrayOffset == 0 && Offset == 0) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000494 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPIt)) {
Bob Wilsone88728d2009-12-19 06:53:17 +0000495 uint64_t NumElements = AT->getNumElements();
Bob Wilsonb742def2009-12-18 20:14:40 +0000496
Bob Wilsone88728d2009-12-19 06:53:17 +0000497 // If this is an array index and the index is not constant, we cannot
498 // promote... that is unless the array has exactly one or two elements
499 // in it, in which case we CAN promote it, but we have to canonicalize
500 // this out if this is the only problem.
501 if ((NumElements != 1 && NumElements != 2) || !AllUsersAreLoads(GEPI))
502 return MarkUnsafe(Info);
503 Info.needsCleanup = true;
504 ArrayOffset = TD->getTypeAllocSizeInBits(AT->getElementType());
505 ArrayEltTy = AT->getElementType();
506 ++GEPIt;
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000507 }
Chris Lattner5e062a12003-05-30 04:15:41 +0000508 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000509
Chris Lattner88e6dc82008-08-23 05:21:06 +0000510 // Walk through the GEP type indices, checking the types that this indexes
511 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +0000512 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +0000513 // Ignore struct elements, no extra checking needed for these.
Bob Wilsonb742def2009-12-18 20:14:40 +0000514 if (isa<StructType>(*GEPIt))
Chris Lattner88e6dc82008-08-23 05:21:06 +0000515 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000516
Bob Wilsonb742def2009-12-18 20:14:40 +0000517 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
518 if (!IdxVal)
519 return MarkUnsafe(Info);
520
521 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPIt)) {
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000522 // This GEP indexes an array. Verify that this is an in-range constant
523 // integer. Specifically, consider A[0][i]. We cannot know that the user
524 // isn't doing invalid things like allowing i to index an out-of-range
525 // subscript that accesses A[1]. Because of this, we have to reject SROA
Bob Wilsond614a1f2009-12-04 21:51:35 +0000526 // of any accesses into structs where any of the components are variables.
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000527 if (IdxVal->getZExtValue() >= AT->getNumElements())
528 return MarkUnsafe(Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000529 } else {
Bob Wilsone88728d2009-12-19 06:53:17 +0000530 const VectorType *VT = cast<VectorType>(*GEPIt);
Dale Johannesenc0bc5472008-11-04 20:54:03 +0000531 if (IdxVal->getZExtValue() >= VT->getNumElements())
532 return MarkUnsafe(Info);
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000533 }
Chris Lattner88e6dc82008-08-23 05:21:06 +0000534 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000535
536 // All the indices are safe. Now compute the offset due to this GEP and
537 // check if the alloca has a component element at that offset.
538 if (ArrayOffset == 0) {
539 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
540 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
541 &Indices[0], Indices.size());
542 } else {
543 // Both array elements have the same type, so it suffices to check one of
544 // them. Copy the GEP indices starting from the array index, but replace
545 // that variable index with a constant zero.
546 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 2, GEPI->op_end());
547 Indices[0] = Constant::getNullValue(Type::getInt32Ty(GEPI->getContext()));
548 const Type *ArrayEltPtr = PointerType::getUnqual(ArrayEltTy);
549 Offset += TD->getIndexedOffset(ArrayEltPtr, &Indices[0], Indices.size());
550 }
551 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
552 MarkUnsafe(Info);
Chris Lattner5e062a12003-05-30 04:15:41 +0000553}
554
Bob Wilsonb742def2009-12-18 20:14:40 +0000555/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
556/// alloca or has an offset and size that corresponds to a component element
557/// within it. The offset checked here may have been formed from a GEP with a
558/// pointer bitcasted to a different type.
559void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset,
560 uint64_t ArrayOffset, uint64_t MemSize,
561 const Type *MemOpType, bool isStore,
562 AllocaInfo &Info) {
563 // Check if this is a load/store of the entire alloca.
564 if (Offset == 0 && ArrayOffset == 0 &&
565 MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
566 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
567 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
568 // (which are essentially the same as the MemIntrinsics, especially with
569 // regard to copying padding between elements), or references using the
570 // aggregate type of the alloca.
571 if (!MemOpType || isa<IntegerType>(MemOpType) || UsesAggregateType) {
572 if (!UsesAggregateType) {
573 if (isStore)
574 Info.isMemCpyDst = true;
575 else
576 Info.isMemCpySrc = true;
577 }
578 return;
579 }
580 }
581 // Check if the offset/size correspond to a component within the alloca type.
582 const Type *T = AI->getAllocatedType();
583 if (TypeHasComponent(T, Offset, MemSize) &&
584 (ArrayOffset == 0 || TypeHasComponent(T, Offset + ArrayOffset, MemSize)))
585 return;
586
587 return MarkUnsafe(Info);
588}
589
590/// TypeHasComponent - Return true if T has a component type with the
591/// specified offset and size. If Size is zero, do not check the size.
592bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
593 const Type *EltTy;
594 uint64_t EltSize;
595 if (const StructType *ST = dyn_cast<StructType>(T)) {
596 const StructLayout *Layout = TD->getStructLayout(ST);
597 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
598 EltTy = ST->getContainedType(EltIdx);
599 EltSize = TD->getTypeAllocSize(EltTy);
600 Offset -= Layout->getElementOffset(EltIdx);
601 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
602 EltTy = AT->getElementType();
603 EltSize = TD->getTypeAllocSize(EltTy);
604 Offset %= EltSize;
605 } else {
606 return false;
607 }
608 if (Offset == 0 && (Size == 0 || EltSize == Size))
609 return true;
610 // Check if the component spans multiple elements.
611 if (Offset + Size > EltSize)
612 return false;
613 return TypeHasComponent(EltTy, Offset, Size);
614}
615
616/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
617/// the instruction I, which references it, to use the separate elements.
618/// Offset indicates the position within AI that is referenced by this
619/// instruction.
620void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
621 SmallVector<AllocaInst*, 32> &NewElts) {
622 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
623 Instruction *User = cast<Instruction>(*UI);
624
625 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
626 RewriteBitCast(BC, AI, Offset, NewElts);
627 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
628 RewriteGEP(GEPI, AI, Offset, NewElts);
629 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
630 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
631 uint64_t MemSize = Length->getZExtValue();
632 if (Offset == 0 &&
633 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
634 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +0000635 // Otherwise the intrinsic can only touch a single element and the
636 // address operand will be updated, so nothing else needs to be done.
Bob Wilsonb742def2009-12-18 20:14:40 +0000637 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
638 const Type *LIType = LI->getType();
639 if (LIType == AI->getAllocatedType()) {
640 // Replace:
641 // %res = load { i32, i32 }* %alloc
642 // with:
643 // %load.0 = load i32* %alloc.0
644 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
645 // %load.1 = load i32* %alloc.1
646 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
647 // (Also works for arrays instead of structs)
648 Value *Insert = UndefValue::get(LIType);
649 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
650 Value *Load = new LoadInst(NewElts[i], "load", LI);
651 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
652 }
653 LI->replaceAllUsesWith(Insert);
654 DeadInsts.push_back(LI);
655 } else if (isa<IntegerType>(LIType) &&
656 TD->getTypeAllocSize(LIType) ==
657 TD->getTypeAllocSize(AI->getAllocatedType())) {
658 // If this is a load of the entire alloca to an integer, rewrite it.
659 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
660 }
661 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
662 Value *Val = SI->getOperand(0);
663 const Type *SIType = Val->getType();
664 if (SIType == AI->getAllocatedType()) {
665 // Replace:
666 // store { i32, i32 } %val, { i32, i32 }* %alloc
667 // with:
668 // %val.0 = extractvalue { i32, i32 } %val, 0
669 // store i32 %val.0, i32* %alloc.0
670 // %val.1 = extractvalue { i32, i32 } %val, 1
671 // store i32 %val.1, i32* %alloc.1
672 // (Also works for arrays instead of structs)
673 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
674 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
675 new StoreInst(Extract, NewElts[i], SI);
676 }
677 DeadInsts.push_back(SI);
678 } else if (isa<IntegerType>(SIType) &&
679 TD->getTypeAllocSize(SIType) ==
680 TD->getTypeAllocSize(AI->getAllocatedType())) {
681 // If this is a store of the entire alloca from an integer, rewrite it.
682 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
683 }
684 }
Bob Wilson39c88a62009-12-17 18:34:24 +0000685 }
686}
687
Bob Wilsonb742def2009-12-18 20:14:40 +0000688/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
689/// and recursively continue updating all of its uses.
690void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
691 SmallVector<AllocaInst*, 32> &NewElts) {
692 RewriteForScalarRepl(BC, AI, Offset, NewElts);
693 if (BC->getOperand(0) != AI)
694 return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000695
Bob Wilsonb742def2009-12-18 20:14:40 +0000696 // The bitcast references the original alloca. Replace its uses with
697 // references to the first new element alloca.
698 Instruction *Val = NewElts[0];
699 if (Val->getType() != BC->getDestTy()) {
700 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
701 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +0000702 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000703 BC->replaceAllUsesWith(Val);
704 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +0000705}
706
Bob Wilsonb742def2009-12-18 20:14:40 +0000707/// FindElementAndOffset - Return the index of the element containing Offset
708/// within the specified type, which must be either a struct or an array.
709/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +0000710/// element. IdxTy is set to the type of the index result to be used in a
711/// GEP instruction.
712uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
713 const Type *&IdxTy) {
714 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +0000715 if (const StructType *ST = dyn_cast<StructType>(T)) {
716 const StructLayout *Layout = TD->getStructLayout(ST);
717 Idx = Layout->getElementContainingOffset(Offset);
718 T = ST->getContainedType(Idx);
719 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +0000720 IdxTy = Type::getInt32Ty(T->getContext());
721 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +0000722 }
Bob Wilsone88728d2009-12-19 06:53:17 +0000723 const ArrayType *AT = cast<ArrayType>(T);
724 T = AT->getElementType();
725 uint64_t EltSize = TD->getTypeAllocSize(T);
726 Idx = Offset / EltSize;
727 Offset -= Idx * EltSize;
728 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +0000729 return Idx;
730}
731
732/// RewriteGEP - Check if this GEP instruction moves the pointer across
733/// elements of the alloca that are being split apart, and if so, rewrite
734/// the GEP to be relative to the new element.
735void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
736 SmallVector<AllocaInst*, 32> &NewElts) {
737 uint64_t OldOffset = Offset;
738 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
739 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
740 &Indices[0], Indices.size());
741
742 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
743
744 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +0000745 const Type *IdxTy;
746 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +0000747 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +0000748 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +0000749
750 T = AI->getAllocatedType();
751 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +0000752 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +0000753
754 // If this GEP does not move the pointer across elements of the alloca
755 // being split, then it does not needs to be rewritten.
756 if (Idx == OldIdx)
757 return;
758
759 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
760 SmallVector<Value*, 8> NewArgs;
761 NewArgs.push_back(Constant::getNullValue(i32Ty));
762 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +0000763 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
764 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +0000765 }
766 Instruction *Val = NewElts[Idx];
767 if (NewArgs.size() > 1) {
768 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
769 NewArgs.end(), "", GEPI);
770 Val->takeName(GEPI);
771 }
772 if (Val->getType() != GEPI->getType())
773 Val = new BitCastInst(Val, GEPI->getType(), Val->getNameStr(), GEPI);
774 GEPI->replaceAllUsesWith(Val);
775 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000776}
777
778/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
779/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +0000780void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000781 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000782 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000783 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +0000784 // appropriate type. The "Other" pointer is the pointer that goes to memory
785 // that doesn't have anything to do with the alloca that we are promoting. For
786 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000787 Value *OtherPtr = 0;
Owen Andersone922c022009-07-22 00:24:57 +0000788 LLVMContext &Context = MI->getContext();
Chris Lattnerdfe964c2009-03-08 03:59:00 +0000789 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +0000790 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +0000791 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +0000792 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000793 else {
Bob Wilsonb742def2009-12-18 20:14:40 +0000794 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +0000795 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000796 }
797 }
Bob Wilson78c50b82009-12-08 18:22:03 +0000798
Chris Lattnerd93afec2009-01-07 07:18:45 +0000799 // If there is an other pointer, we want to convert it to the same pointer
800 // type as AI has, so we can GEP through it safely.
801 if (OtherPtr) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000802
803 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
804 // optimization, but it's also required to detect the corner case where
805 // both pointer operands are referencing the same memory, and where
806 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
807 // function is only called for mem intrinsics that access the whole
808 // aggregate, so non-zero GEPs are not an issue here.)
809 while (1) {
810 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr)) {
811 OtherPtr = BC->getOperand(0);
812 continue;
813 }
814 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr)) {
815 // All zero GEPs are effectively bitcasts.
816 if (GEP->hasAllZeroIndices()) {
817 OtherPtr = GEP->getOperand(0);
818 continue;
819 }
820 }
821 break;
822 }
823 // If OtherPtr has already been rewritten, this intrinsic will be dead.
824 if (OtherPtr == NewElts[0])
825 return;
Chris Lattner372dda82007-03-05 07:52:57 +0000826
Chris Lattnerd93afec2009-01-07 07:18:45 +0000827 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
828 if (BCE->getOpcode() == Instruction::BitCast)
829 OtherPtr = BCE->getOperand(0);
830
831 // If the pointer is not the right type, insert a bitcast to the right
832 // type.
833 if (OtherPtr->getType() != AI->getType())
834 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
835 MI);
836 }
837
838 // Process each element of the aggregate.
839 Value *TheFn = MI->getOperand(0);
840 const Type *BytePtrTy = MI->getRawDest()->getType();
Bob Wilsonb742def2009-12-18 20:14:40 +0000841 bool SROADest = MI->getRawDest() == Inst;
Chris Lattnerd93afec2009-01-07 07:18:45 +0000842
Owen Anderson1d0be152009-08-13 21:58:54 +0000843 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +0000844
845 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
846 // If this is a memcpy/memmove, emit a GEP of the other element address.
847 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000848 unsigned OtherEltAlign = MemAlignment;
849
Bob Wilsonb742def2009-12-18 20:14:40 +0000850 if (OtherPtr == AI) {
851 OtherElt = NewElts[i];
852 OtherEltAlign = 0;
853 } else if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000854 Value *Idx[2] = { Zero,
855 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +0000856 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000857 OtherPtr->getNameStr()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +0000858 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +0000859 uint64_t EltOffset;
860 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
861 if (const StructType *ST =
862 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
863 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
864 } else {
865 const Type *EltTy =
866 cast<SequentialType>(OtherPtr->getType())->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000867 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000868 }
869
870 // The alignment of the other pointer is the guaranteed alignment of the
871 // element, which is affected by both the known alignment of the whole
872 // mem intrinsic and the alignment of the element. If the alignment of
873 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
874 // known alignment is just 4 bytes.
875 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000876 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000877
878 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +0000879 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000880
881 // If we got down to a scalar, insert a load or store as appropriate.
882 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000883 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +0000884 if (SROADest) {
885 // From Other to Alloca.
886 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
887 new StoreInst(Elt, EltPtr, MI);
888 } else {
889 // From Alloca to Other.
890 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
891 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
892 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000893 continue;
894 }
895 assert(isa<MemSetInst>(MI));
896
897 // If the stored element is zero (common case), just store a null
898 // constant.
899 Constant *StoreVal;
900 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
901 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000902 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +0000903 } else {
904 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +0000905 const Type *ValTy = EltTy->getScalarType();
906
Chris Lattnerd93afec2009-01-07 07:18:45 +0000907 // Construct an integer with the right value.
908 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
909 APInt OneVal(EltSize, CI->getZExtValue());
910 APInt TotalVal(OneVal);
911 // Set each byte.
912 for (unsigned i = 0; 8*i < EltSize; ++i) {
913 TotalVal = TotalVal.shl(8);
914 TotalVal |= OneVal;
915 }
916
917 // Convert the integer value to the appropriate type.
Owen Andersoneed707b2009-07-24 23:12:02 +0000918 StoreVal = ConstantInt::get(Context, TotalVal);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000919 if (isa<PointerType>(ValTy))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000920 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000921 else if (ValTy->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000922 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000923 assert(StoreVal->getType() == ValTy && "Type mismatch!");
924
925 // If the requested value was a vector constant, create it.
926 if (EltTy != ValTy) {
927 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
928 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +0000929 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000930 }
931 }
932 new StoreInst(StoreVal, EltPtr, MI);
933 continue;
934 }
935 // Otherwise, if we're storing a byte variable, use a memset call for
936 // this element.
937 }
938
939 // Cast the element pointer to BytePtrTy.
940 if (EltPtr->getType() != BytePtrTy)
941 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
942
943 // Cast the other pointer (if we have one) to BytePtrTy.
944 if (OtherElt && OtherElt->getType() != BytePtrTy)
945 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
946 MI);
947
Duncan Sands777d2302009-05-09 07:06:46 +0000948 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000949
950 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000951 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000952 Value *Ops[] = {
953 SROADest ? EltPtr : OtherElt, // Dest ptr
954 SROADest ? OtherElt : EltPtr, // Src ptr
Owen Andersoneed707b2009-07-24 23:12:02 +0000955 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Owen Anderson1d0be152009-08-13 21:58:54 +0000956 // Align
957 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign)
Chris Lattnerd93afec2009-01-07 07:18:45 +0000958 };
959 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
960 } else {
961 assert(isa<MemSetInst>(MI));
962 Value *Ops[] = {
963 EltPtr, MI->getOperand(2), // Dest, Value,
Owen Andersoneed707b2009-07-24 23:12:02 +0000964 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Chris Lattnerd93afec2009-01-07 07:18:45 +0000965 Zero // Align
966 };
967 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
968 }
Chris Lattner372dda82007-03-05 07:52:57 +0000969 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000970 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +0000971}
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000972
Bob Wilson39fdd692009-12-04 21:57:37 +0000973/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000974/// overwrites the entire allocation. Extract out the pieces of the stored
975/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000976void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000977 SmallVector<AllocaInst*, 32> &NewElts){
978 // Extract each element out of the integer according to its structure offset
979 // and store the element value to the individual alloca.
980 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +0000981 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +0000982 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000983
Eli Friedman41b33f42009-06-01 09:14:32 +0000984 // Handle tail padding by extending the operand
985 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000986 SrcVal = new ZExtInst(SrcVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000987 IntegerType::get(SI->getContext(), AllocaSizeBits),
988 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000989
Nick Lewycky59136252009-09-15 07:08:25 +0000990 DEBUG(errs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
991 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000992
993 // There are two forms here: AI could be an array or struct. Both cases
994 // have different ways to compute the element offset.
995 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
996 const StructLayout *Layout = TD->getStructLayout(EltSTy);
997
998 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
999 // Get the number of bits to shift SrcVal to get the value.
1000 const Type *FieldTy = EltSTy->getElementType(i);
1001 uint64_t Shift = Layout->getElementOffsetInBits(i);
1002
1003 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00001004 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001005
1006 Value *EltVal = SrcVal;
1007 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001008 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001009 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1010 "sroa.store.elt", SI);
1011 }
1012
1013 // Truncate down to an integer of the right size.
1014 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +00001015
1016 // Ignore zero sized fields like {}, they obviously contain no data.
1017 if (FieldSizeBits == 0) continue;
1018
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001019 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001020 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001021 IntegerType::get(SI->getContext(), FieldSizeBits),
1022 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001023 Value *DestField = NewElts[i];
1024 if (EltVal->getType() == FieldTy) {
1025 // Storing to an integer field of this size, just do it.
1026 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
1027 // Bitcast to the right element type (for fp/vector values).
1028 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
1029 } else {
1030 // Otherwise, bitcast the dest pointer (for aggregates).
1031 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001032 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001033 "", SI);
1034 }
1035 new StoreInst(EltVal, DestField, SI);
1036 }
1037
1038 } else {
1039 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1040 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001041 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001042 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1043
1044 uint64_t Shift;
1045
1046 if (TD->isBigEndian())
1047 Shift = AllocaSizeBits-ElementOffset;
1048 else
1049 Shift = 0;
1050
1051 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00001052 // Ignore zero sized fields like {}, they obviously contain no data.
1053 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001054
1055 Value *EltVal = SrcVal;
1056 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001057 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001058 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1059 "sroa.store.elt", SI);
1060 }
1061
1062 // Truncate down to an integer of the right size.
1063 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001064 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001065 IntegerType::get(SI->getContext(),
1066 ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001067 Value *DestField = NewElts[i];
1068 if (EltVal->getType() == ArrayEltTy) {
1069 // Storing to an integer field of this size, just do it.
1070 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
1071 // Bitcast to the right element type (for fp/vector values).
1072 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1073 } else {
1074 // Otherwise, bitcast the dest pointer (for aggregates).
1075 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001076 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001077 "", SI);
1078 }
1079 new StoreInst(EltVal, DestField, SI);
1080
1081 if (TD->isBigEndian())
1082 Shift -= ElementOffset;
1083 else
1084 Shift += ElementOffset;
1085 }
1086 }
1087
Bob Wilsonb742def2009-12-18 20:14:40 +00001088 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001089}
1090
Bob Wilson39fdd692009-12-04 21:57:37 +00001091/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001092/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001093void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001094 SmallVector<AllocaInst*, 32> &NewElts) {
1095 // Extract each element out of the NewElts according to its structure offset
1096 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00001097 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001098 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001099
Nick Lewycky59136252009-09-15 07:08:25 +00001100 DEBUG(errs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
1101 << '\n');
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001102
1103 // There are two forms here: AI could be an array or struct. Both cases
1104 // have different ways to compute the element offset.
1105 const StructLayout *Layout = 0;
1106 uint64_t ArrayEltBitOffset = 0;
1107 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1108 Layout = TD->getStructLayout(EltSTy);
1109 } else {
1110 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001111 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001112 }
Owen Andersone922c022009-07-22 00:24:57 +00001113
Owen Andersone922c022009-07-22 00:24:57 +00001114 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001115 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001116
1117 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1118 // Load the value from the alloca. If the NewElt is an aggregate, cast
1119 // the pointer to an integer of the same size before doing the load.
1120 Value *SrcField = NewElts[i];
1121 const Type *FieldTy =
1122 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001123 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1124
1125 // Ignore zero sized fields like {}, they obviously contain no data.
1126 if (FieldSizeBits == 0) continue;
1127
Owen Anderson1d0be152009-08-13 21:58:54 +00001128 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1129 FieldSizeBits);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001130 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1131 !isa<VectorType>(FieldTy))
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001132 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001133 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001134 "", LI);
1135 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1136
1137 // If SrcField is a fp or vector of the right size but that isn't an
1138 // integer type, bitcast to an integer so we can shift it.
1139 if (SrcField->getType() != FieldIntTy)
1140 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1141
1142 // Zero extend the field to be the same size as the final alloca so that
1143 // we can shift and insert it.
1144 if (SrcField->getType() != ResultVal->getType())
1145 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1146
1147 // Determine the number of bits to shift SrcField.
1148 uint64_t Shift;
1149 if (Layout) // Struct case.
1150 Shift = Layout->getElementOffsetInBits(i);
1151 else // Array case.
1152 Shift = i*ArrayEltBitOffset;
1153
1154 if (TD->isBigEndian())
1155 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1156
1157 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001158 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001159 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1160 }
1161
1162 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1163 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001164
1165 // Handle tail padding by truncating the result
1166 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1167 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1168
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001169 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00001170 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001171}
1172
Duncan Sands3cb36502007-11-04 14:43:57 +00001173/// HasPadding - Return true if the specified type has any structure or
1174/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001175static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001176 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1177 const StructLayout *SL = TD.getStructLayout(STy);
1178 unsigned PrevFieldBitOffset = 0;
1179 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001180 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1181
Chris Lattner39a1c042007-05-30 06:11:23 +00001182 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001183 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001184 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001185
Chris Lattner39a1c042007-05-30 06:11:23 +00001186 // Check to see if there is any padding between this element and the
1187 // previous one.
1188 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001189 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001190 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1191 if (PrevFieldEnd < FieldBitOffset)
1192 return true;
1193 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001194
Chris Lattner39a1c042007-05-30 06:11:23 +00001195 PrevFieldBitOffset = FieldBitOffset;
1196 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001197
Chris Lattner39a1c042007-05-30 06:11:23 +00001198 // Check for tail padding.
1199 if (unsigned EltCount = STy->getNumElements()) {
1200 unsigned PrevFieldEnd = PrevFieldBitOffset +
1201 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001202 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001203 return true;
1204 }
1205
1206 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001207 return HasPadding(ATy->getElementType(), TD);
Duncan Sands3cb36502007-11-04 14:43:57 +00001208 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001209 return HasPadding(VTy->getElementType(), TD);
Chris Lattner39a1c042007-05-30 06:11:23 +00001210 }
Duncan Sands777d2302009-05-09 07:06:46 +00001211 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001212}
Chris Lattner372dda82007-03-05 07:52:57 +00001213
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001214/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1215/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1216/// or 1 if safe after canonicalization has been performed.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001217int SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001218 // Loop over the use list of the alloca. We can only transform it if all of
1219 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001220 AllocaInfo Info;
1221
Bob Wilsonb742def2009-12-18 20:14:40 +00001222 isSafeForScalarRepl(AI, AI, 0, 0, Info);
1223 if (Info.isUnsafe) {
1224 DEBUG(errs() << "Cannot transform: " << *AI << '\n');
1225 return 0;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001226 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001227
1228 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1229 // source and destination, we have to be careful. In particular, the memcpy
1230 // could be moving around elements that live in structure padding of the LLVM
1231 // types, but may actually be used. In these cases, we refuse to promote the
1232 // struct.
1233 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001234 HasPadding(AI->getAllocatedType(), *TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001235 return 0;
Duncan Sands3cb36502007-11-04 14:43:57 +00001236
Chris Lattner39a1c042007-05-30 06:11:23 +00001237 // If we require cleanup, return 1, otherwise return 3.
Devang Patel4afc90d2009-02-10 07:00:59 +00001238 return Info.needsCleanup ? 1 : 3;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001239}
1240
Bob Wilson65ab34f2009-12-08 18:27:03 +00001241/// CleanupGEP - GEP is used by an Alloca, which can be promoted after the GEP
Devang Patel4afc90d2009-02-10 07:00:59 +00001242/// is canonicalized here.
1243void SROA::CleanupGEP(GetElementPtrInst *GEPI) {
1244 gep_type_iterator I = gep_type_begin(GEPI);
1245 ++I;
1246
Devang Patel7afe8fa2009-02-10 19:28:07 +00001247 const ArrayType *AT = dyn_cast<ArrayType>(*I);
1248 if (!AT)
1249 return;
1250
1251 uint64_t NumElements = AT->getNumElements();
1252
1253 if (isa<ConstantInt>(I.getOperand()))
1254 return;
1255
1256 if (NumElements == 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001257 GEPI->setOperand(2,
1258 Constant::getNullValue(Type::getInt32Ty(GEPI->getContext())));
Devang Patel7afe8fa2009-02-10 19:28:07 +00001259 return;
1260 }
Devang Patel4afc90d2009-02-10 07:00:59 +00001261
Devang Patel7afe8fa2009-02-10 19:28:07 +00001262 assert(NumElements == 2 && "Unhandled case!");
1263 // All users of the GEP must be loads. At each use of the GEP, insert
1264 // two loads of the appropriate indexed GEP and select between them.
Owen Anderson333c4002009-07-09 23:48:35 +00001265 Value *IsOne = new ICmpInst(GEPI, ICmpInst::ICMP_NE, I.getOperand(),
Owen Andersona7235ea2009-07-31 20:28:14 +00001266 Constant::getNullValue(I.getOperand()->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001267 "isone");
Devang Patel7afe8fa2009-02-10 19:28:07 +00001268 // Insert the new GEP instructions, which are properly indexed.
1269 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
Owen Anderson1d0be152009-08-13 21:58:54 +00001270 Indices[1] = Constant::getNullValue(Type::getInt32Ty(GEPI->getContext()));
Bob Wilsonb742def2009-12-18 20:14:40 +00001271 Value *ZeroIdx = GetElementPtrInst::CreateInBounds(GEPI->getOperand(0),
1272 Indices.begin(),
1273 Indices.end(),
1274 GEPI->getName()+".0",GEPI);
Owen Anderson1d0be152009-08-13 21:58:54 +00001275 Indices[1] = ConstantInt::get(Type::getInt32Ty(GEPI->getContext()), 1);
Bob Wilsonb742def2009-12-18 20:14:40 +00001276 Value *OneIdx = GetElementPtrInst::CreateInBounds(GEPI->getOperand(0),
1277 Indices.begin(),
1278 Indices.end(),
1279 GEPI->getName()+".1", GEPI);
Devang Patel7afe8fa2009-02-10 19:28:07 +00001280 // Replace all loads of the variable index GEP with loads from both
1281 // indexes and a select.
1282 while (!GEPI->use_empty()) {
1283 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1284 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1285 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
1286 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
1287 LI->replaceAllUsesWith(R);
1288 LI->eraseFromParent();
Devang Patel4afc90d2009-02-10 07:00:59 +00001289 }
1290}
1291
1292/// CleanupAllocaUsers - If SROA reported that it can promote the specified
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001293/// allocation, but only if cleaned up, perform the cleanups required.
Bob Wilsonb742def2009-12-18 20:14:40 +00001294void SROA::CleanupAllocaUsers(Value *V) {
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001295 // At this point, we know that the end result will be SROA'd and promoted, so
1296 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1297 // up.
Bob Wilsonb742def2009-12-18 20:14:40 +00001298 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001299 UI != E; ) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001300 User *U = *UI++;
Bob Wilsonb742def2009-12-18 20:14:40 +00001301 if (isa<BitCastInst>(U)) {
1302 CleanupAllocaUsers(U);
1303 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001304 CleanupGEP(GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001305 CleanupAllocaUsers(GEPI);
1306 if (GEPI->use_empty()) GEPI->eraseFromParent();
1307 } else {
Jay Foad0906b1b2009-06-06 17:49:35 +00001308 Instruction *I = cast<Instruction>(U);
Devang Patel4afc90d2009-02-10 07:00:59 +00001309 SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
Zhou Shengb0c41992009-03-18 12:48:48 +00001310 if (!isa<StoreInst>(I) && OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001311 // Safe to remove debug info uses.
1312 while (!DbgInUses.empty()) {
1313 DbgInfoIntrinsic *DI = DbgInUses.back(); DbgInUses.pop_back();
1314 DI->eraseFromParent();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001315 }
Devang Patel4afc90d2009-02-10 07:00:59 +00001316 I->eraseFromParent();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001317 }
1318 }
1319 }
Chris Lattner5e062a12003-05-30 04:15:41 +00001320}
Chris Lattnera1888942005-12-12 07:19:13 +00001321
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001322/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1323/// the offset specified by Offset (which is specified in bytes).
Chris Lattnerde6df882006-04-14 21:42:41 +00001324///
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001325/// There are two cases we handle here:
1326/// 1) A union of vector types of the same size and potentially its elements.
Chris Lattnerd22dbdf2006-12-15 07:32:38 +00001327/// Here we turn element accesses into insert/extract element operations.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001328/// This promotes a <4 x float> with a store of float to the third element
1329/// into a <4 x float> that uses insert element.
1330/// 2) A fully general blob of memory, which we turn into some (potentially
1331/// large) integer type with extract and insert operations where the loads
1332/// and stores would mutate the memory.
Chris Lattner7809ecd2009-02-03 01:30:09 +00001333static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001334 unsigned AllocaSize, const TargetData &TD,
Owen Andersone922c022009-07-22 00:24:57 +00001335 LLVMContext &Context) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001336 // If this could be contributing to a vector, analyze it.
Owen Anderson1d0be152009-08-13 21:58:54 +00001337 if (VecTy != Type::getVoidTy(Context)) { // either null or a vector type.
Chris Lattner996d7a92009-02-02 18:02:59 +00001338
Chris Lattner7809ecd2009-02-03 01:30:09 +00001339 // If the In type is a vector that is the same size as the alloca, see if it
1340 // matches the existing VecTy.
1341 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1342 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1343 // If we're storing/loading a vector of the right size, allow it as a
1344 // vector. If this the first vector we see, remember the type so that
1345 // we know the element size.
1346 if (VecTy == 0)
1347 VecTy = VInTy;
1348 return;
1349 }
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001350 } else if (In->isFloatTy() || In->isDoubleTy() ||
Chris Lattner7809ecd2009-02-03 01:30:09 +00001351 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1352 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1353 // If we're accessing something that could be an element of a vector, see
1354 // if the implied vector agrees with what we already have and if Offset is
1355 // compatible with it.
1356 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1357 if (Offset % EltSize == 0 &&
1358 AllocaSize % EltSize == 0 &&
1359 (VecTy == 0 ||
1360 cast<VectorType>(VecTy)->getElementType()
1361 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1362 if (VecTy == 0)
Owen Andersondebcb012009-07-29 22:17:13 +00001363 VecTy = VectorType::get(In, AllocaSize/EltSize);
Chris Lattner7809ecd2009-02-03 01:30:09 +00001364 return;
1365 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001366 }
1367 }
1368
Chris Lattner7809ecd2009-02-03 01:30:09 +00001369 // Otherwise, we have a case that we can't handle with an optimized vector
1370 // form. We can still turn this into a large integer.
Owen Anderson1d0be152009-08-13 21:58:54 +00001371 VecTy = Type::getVoidTy(Context);
Chris Lattnera1888942005-12-12 07:19:13 +00001372}
1373
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001374/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
Bob Wilsonefc58e72009-12-09 18:05:27 +00001375/// its accesses to a single vector type, return true and set VecTy to
Chris Lattner7809ecd2009-02-03 01:30:09 +00001376/// the new type. If we could convert the alloca into a single promotable
1377/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1378/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1379/// is the current offset from the base of the alloca being analyzed.
Chris Lattnera1888942005-12-12 07:19:13 +00001380///
Chris Lattner1a3257b2009-02-03 18:15:05 +00001381/// If we see at least one access to the value that is as a vector type, set the
1382/// SawVec flag.
Chris Lattner1a3257b2009-02-03 18:15:05 +00001383bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1384 bool &SawVec, uint64_t Offset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001385 unsigned AllocaSize) {
Chris Lattnera1888942005-12-12 07:19:13 +00001386 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1387 Instruction *User = cast<Instruction>(*UI);
1388
1389 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001390 // Don't break volatile loads.
Chris Lattner6e733d32009-01-28 20:16:43 +00001391 if (LI->isVolatile())
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001392 return false;
Owen Andersone922c022009-07-22 00:24:57 +00001393 MergeInType(LI->getType(), Offset, VecTy,
1394 AllocaSize, *TD, V->getContext());
Chris Lattner1a3257b2009-02-03 18:15:05 +00001395 SawVec |= isa<VectorType>(LI->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001396 continue;
1397 }
1398
1399 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001400 // Storing the pointer, not into the value?
Chris Lattner6e733d32009-01-28 20:16:43 +00001401 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001402 MergeInType(SI->getOperand(0)->getType(), Offset,
Owen Andersone922c022009-07-22 00:24:57 +00001403 VecTy, AllocaSize, *TD, V->getContext());
Chris Lattner1a3257b2009-02-03 18:15:05 +00001404 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001405 continue;
1406 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001407
1408 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattner1a3257b2009-02-03 18:15:05 +00001409 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1410 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001411 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001412 IsNotTrivial = true;
Chris Lattnercf321862009-01-07 06:39:58 +00001413 continue;
1414 }
1415
1416 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001417 // If this is a GEP with a variable indices, we can't handle it.
1418 if (!GEP->hasAllConstantIndices())
1419 return false;
Chris Lattnercf321862009-01-07 06:39:58 +00001420
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001421 // Compute the offset that this GEP adds to the pointer.
1422 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Bob Wilsonb742def2009-12-18 20:14:40 +00001423 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001424 &Indices[0], Indices.size());
1425 // See if all uses can be converted.
Chris Lattner1a3257b2009-02-03 18:15:05 +00001426 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001427 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001428 return false;
1429 IsNotTrivial = true;
1430 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001431 }
Chris Lattner3ce5e882009-03-08 03:37:16 +00001432
Chris Lattner3d730f72009-02-03 02:01:43 +00001433 // If this is a constant sized memset of a constant value (e.g. 0) we can
1434 // handle it.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001435 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1436 // Store of constant value and constant size.
1437 if (isa<ConstantInt>(MSI->getValue()) &&
1438 isa<ConstantInt>(MSI->getLength())) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001439 IsNotTrivial = true;
1440 continue;
1441 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001442 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001443
1444 // If this is a memcpy or memmove into or out of the whole allocation, we
1445 // can handle it like a load or store of the scalar type.
1446 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1447 if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
1448 if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1449 IsNotTrivial = true;
1450 continue;
1451 }
1452 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001453
Devang Patel00e389c2009-03-06 07:03:54 +00001454 // Ignore dbg intrinsic.
1455 if (isa<DbgInfoIntrinsic>(User))
1456 continue;
1457
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001458 // Otherwise, we cannot handle this!
1459 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001460 }
1461
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001462 return true;
Chris Lattnera1888942005-12-12 07:19:13 +00001463}
1464
Chris Lattnera1888942005-12-12 07:19:13 +00001465/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattnerde6df882006-04-14 21:42:41 +00001466/// directly. This happens when we are converting an "integer union" to a
1467/// single integer scalar, or when we are converting a "vector union" to a
1468/// vector with insert/extractelement instructions.
1469///
1470/// Offset is an offset from the original alloca, in bits that need to be
1471/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001472void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
Chris Lattnera1888942005-12-12 07:19:13 +00001473 while (!Ptr->use_empty()) {
1474 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001475
Chris Lattnercf321862009-01-07 06:39:58 +00001476 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb10e0da2008-01-30 00:39:15 +00001477 ConvertUsesToScalar(CI, NewAI, Offset);
Chris Lattnera1888942005-12-12 07:19:13 +00001478 CI->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001479 continue;
1480 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001481
Chris Lattnercf321862009-01-07 06:39:58 +00001482 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001483 // Compute the offset that this GEP adds to the pointer.
1484 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Bob Wilsonb742def2009-12-18 20:14:40 +00001485 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001486 &Indices[0], Indices.size());
1487 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Chris Lattnera1888942005-12-12 07:19:13 +00001488 GEP->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001489 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001490 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001491
Chris Lattner9bc67da2009-02-03 19:45:44 +00001492 IRBuilder<> Builder(User->getParent(), User);
1493
1494 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner6e011152009-02-03 21:01:03 +00001495 // The load is a bit extract from NewAI shifted right by Offset bits.
1496 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1497 Value *NewLoadVal
1498 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1499 LI->replaceAllUsesWith(NewLoadVal);
Chris Lattner9bc67da2009-02-03 19:45:44 +00001500 LI->eraseFromParent();
1501 continue;
1502 }
1503
1504 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1505 assert(SI->getOperand(0) != Ptr && "Consistency error!");
Benjamin Kramere6f32942009-11-29 21:17:48 +00001506 // FIXME: Remove once builder has Twine API.
Bob Wilsond614a1f2009-12-04 21:51:35 +00001507 Value *Old = Builder.CreateLoad(NewAI,
1508 (NewAI->getName()+".in").str().c_str());
Chris Lattner9bc67da2009-02-03 19:45:44 +00001509 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1510 Builder);
1511 Builder.CreateStore(New, NewAI);
1512 SI->eraseFromParent();
1513 continue;
1514 }
1515
Chris Lattner3d730f72009-02-03 02:01:43 +00001516 // If this is a constant sized memset of a constant value (e.g. 0) we can
1517 // transform it into a store of the expanded constant value.
1518 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1519 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1520 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Chris Lattner33e24ad2009-04-21 16:52:12 +00001521 if (NumBytes != 0) {
1522 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1523
1524 // Compute the value replicated the right number of times.
1525 APInt APVal(NumBytes*8, Val);
Chris Lattner3d730f72009-02-03 02:01:43 +00001526
Chris Lattner33e24ad2009-04-21 16:52:12 +00001527 // Splat the value if non-zero.
1528 if (Val)
1529 for (unsigned i = 1; i != NumBytes; ++i)
1530 APVal |= APVal << 8;
Benjamin Kramere6f32942009-11-29 21:17:48 +00001531
1532 // FIXME: Remove once builder has Twine API.
Bob Wilsond614a1f2009-12-04 21:51:35 +00001533 Value *Old = Builder.CreateLoad(NewAI,
1534 (NewAI->getName()+".in").str().c_str());
Owen Andersone922c022009-07-22 00:24:57 +00001535 Value *New = ConvertScalar_InsertValue(
Owen Andersoneed707b2009-07-24 23:12:02 +00001536 ConstantInt::get(User->getContext(), APVal),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001537 Old, Offset, Builder);
Chris Lattner33e24ad2009-04-21 16:52:12 +00001538 Builder.CreateStore(New, NewAI);
1539 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001540 MSI->eraseFromParent();
1541 continue;
1542 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001543
1544 // If this is a memcpy or memmove into or out of the whole allocation, we
1545 // can handle it like a load or store of the scalar type.
1546 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1547 assert(Offset == 0 && "must be store to start of alloca");
1548
1549 // If the source and destination are both to the same alloca, then this is
1550 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
1551 // as appropriate.
1552 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject());
1553
1554 if (MTI->getSource()->getUnderlyingObject() != OrigAI) {
1555 // Dest must be OrigAI, change this to be a load from the original
1556 // pointer (bitcasted), then a store to our new alloca.
1557 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1558 Value *SrcPtr = MTI->getSource();
1559 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1560
1561 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1562 SrcVal->setAlignment(MTI->getAlignment());
1563 Builder.CreateStore(SrcVal, NewAI);
1564 } else if (MTI->getDest()->getUnderlyingObject() != OrigAI) {
1565 // Src must be OrigAI, change this to be a load from NewAI then a store
1566 // through the original dest pointer (bitcasted).
1567 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1568 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1569
1570 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1571 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1572 NewStore->setAlignment(MTI->getAlignment());
1573 } else {
1574 // Noop transfer. Src == Dst
1575 }
1576
1577
1578 MTI->eraseFromParent();
1579 continue;
1580 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001581
Devang Patel00e389c2009-03-06 07:03:54 +00001582 // If user is a dbg info intrinsic then it is safe to remove it.
1583 if (isa<DbgInfoIntrinsic>(User)) {
1584 User->eraseFromParent();
1585 continue;
1586 }
1587
Torok Edwinc23197a2009-07-14 16:55:14 +00001588 llvm_unreachable("Unsupported operation!");
Chris Lattnera1888942005-12-12 07:19:13 +00001589 }
1590}
Chris Lattner79b3bd32007-04-25 06:40:51 +00001591
Chris Lattner6e011152009-02-03 21:01:03 +00001592/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1593/// or vector value FromVal, extracting the bits from the offset specified by
1594/// Offset. This returns the value, which is of type ToType.
1595///
1596/// This happens when we are converting an "integer union" to a single
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001597/// integer scalar, or when we are converting a "vector union" to a vector with
1598/// insert/extractelement instructions.
Chris Lattner800de312008-02-29 07:03:13 +00001599///
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001600/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner6e011152009-02-03 21:01:03 +00001601/// shifted to the right.
1602Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1603 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001604 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattner6e011152009-02-03 21:01:03 +00001605 if (FromVal->getType() == ToType && Offset == 0)
1606 return FromVal;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001607
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001608 // If the result alloca is a vector type, this is either an element
1609 // access or a bitcast to another vector type of the same size.
Chris Lattner6e011152009-02-03 21:01:03 +00001610 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1611 if (isa<VectorType>(ToType))
1612 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001613
1614 // Otherwise it must be an element access.
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001615 unsigned Elt = 0;
1616 if (Offset) {
Duncan Sands777d2302009-05-09 07:06:46 +00001617 unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001618 Elt = Offset/EltSize;
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001619 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner800de312008-02-29 07:03:13 +00001620 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001621 // Return the element extracted out of it.
Owen Anderson1d0be152009-08-13 21:58:54 +00001622 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
1623 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
Chris Lattner6e011152009-02-03 21:01:03 +00001624 if (V->getType() != ToType)
1625 V = Builder.CreateBitCast(V, ToType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001626 return V;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001627 }
Chris Lattner1aa70562009-02-03 21:08:45 +00001628
1629 // If ToType is a first class aggregate, extract out each of the pieces and
1630 // use insertvalue's to form the FCA.
1631 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1632 const StructLayout &Layout = *TD->getStructLayout(ST);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001633 Value *Res = UndefValue::get(ST);
Chris Lattner1aa70562009-02-03 21:08:45 +00001634 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1635 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
Chris Lattnere991ced2009-02-06 04:34:07 +00001636 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner1aa70562009-02-03 21:08:45 +00001637 Builder);
1638 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1639 }
1640 return Res;
1641 }
1642
1643 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001644 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001645 Value *Res = UndefValue::get(AT);
Chris Lattner1aa70562009-02-03 21:08:45 +00001646 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1647 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1648 Offset+i*EltSize, Builder);
1649 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1650 }
1651 return Res;
1652 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001653
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001654 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattner6e011152009-02-03 21:01:03 +00001655 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001656
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001657 // If this is a big-endian system and the load is narrower than the
1658 // full alloca type, we need to do a shift to get the right bits.
1659 int ShAmt = 0;
Chris Lattner56c38522009-01-07 06:34:28 +00001660 if (TD->isBigEndian()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001661 // On big-endian machines, the lowest bit is stored at the bit offset
1662 // from the pointer given by getTypeStoreSizeInBits. This matters for
1663 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner56c38522009-01-07 06:34:28 +00001664 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
Chris Lattner6e011152009-02-03 21:01:03 +00001665 TD->getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001666 } else {
1667 ShAmt = Offset;
1668 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001669
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001670 // Note: we support negative bitwidths (with shl) which are not defined.
1671 // We do this to support (f.e.) loads off the end of a structure where
1672 // only some bits are used.
1673 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001674 FromVal = Builder.CreateLShr(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001675 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001676 ShAmt), "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001677 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001678 FromVal = Builder.CreateShl(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001679 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001680 -ShAmt), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001681
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001682 // Finally, unconditionally truncate the integer to the right width.
Chris Lattner6e011152009-02-03 21:01:03 +00001683 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001684 if (LIBitWidth < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001685 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001686 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
1687 LIBitWidth), "tmp");
Chris Lattner55a683d2009-02-03 07:08:57 +00001688 else if (LIBitWidth > NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001689 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001690 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
1691 LIBitWidth), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001692
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001693 // If the result is an integer, this is a trunc or bitcast.
Chris Lattner6e011152009-02-03 21:01:03 +00001694 if (isa<IntegerType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001695 // Should be done.
Chris Lattner6e011152009-02-03 21:01:03 +00001696 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001697 // Just do a bitcast, we know the sizes match up.
Chris Lattner6e011152009-02-03 21:01:03 +00001698 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001699 } else {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001700 // Otherwise must be a pointer.
Chris Lattner6e011152009-02-03 21:01:03 +00001701 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001702 }
Chris Lattner6e011152009-02-03 21:01:03 +00001703 assert(FromVal->getType() == ToType && "Didn't convert right?");
1704 return FromVal;
Chris Lattner800de312008-02-29 07:03:13 +00001705}
1706
Chris Lattner9b872db2009-02-03 19:30:11 +00001707/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1708/// or vector value "Old" at the offset specified by Offset.
1709///
1710/// This happens when we are converting an "integer union" to a
Chris Lattner800de312008-02-29 07:03:13 +00001711/// single integer scalar, or when we are converting a "vector union" to a
1712/// vector with insert/extractelement instructions.
1713///
1714/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner9b872db2009-02-03 19:30:11 +00001715/// shifted to the right.
1716Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
Chris Lattner65a65022009-02-03 19:41:50 +00001717 uint64_t Offset, IRBuilder<> &Builder) {
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001718
Chris Lattner800de312008-02-29 07:03:13 +00001719 // Convert the stored type to the actual type, shift it left to insert
1720 // then 'or' into place.
Chris Lattner9b872db2009-02-03 19:30:11 +00001721 const Type *AllocaType = Old->getType();
Owen Andersone922c022009-07-22 00:24:57 +00001722 LLVMContext &Context = Old->getContext();
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001723
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001724 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001725 uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1726 uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
Chris Lattner29e64172009-03-08 04:17:04 +00001727
1728 // Changing the whole vector with memset or with an access of a different
1729 // vector type?
1730 if (ValSize == VecSize)
1731 return Builder.CreateBitCast(SV, AllocaType, "tmp");
1732
Duncan Sands777d2302009-05-09 07:06:46 +00001733 uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner29e64172009-03-08 04:17:04 +00001734
1735 // Must be an element insertion.
1736 unsigned Elt = Offset/EltSize;
1737
1738 if (SV->getType() != VTy->getElementType())
1739 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1740
1741 SV = Builder.CreateInsertElement(Old, SV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001742 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
Chris Lattner29e64172009-03-08 04:17:04 +00001743 "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001744 return SV;
1745 }
Chris Lattner9b872db2009-02-03 19:30:11 +00001746
1747 // If SV is a first-class aggregate value, insert each value recursively.
1748 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1749 const StructLayout &Layout = *TD->getStructLayout(ST);
1750 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001751 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Chris Lattner9b872db2009-02-03 19:30:11 +00001752 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattnere991ced2009-02-06 04:34:07 +00001753 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner65a65022009-02-03 19:41:50 +00001754 Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001755 }
1756 return Old;
1757 }
1758
1759 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Duncan Sands777d2302009-05-09 07:06:46 +00001760 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner9b872db2009-02-03 19:30:11 +00001761 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001762 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1763 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001764 }
1765 return Old;
1766 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001767
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001768 // If SV is a float, convert it to the appropriate integer type.
Chris Lattner9b872db2009-02-03 19:30:11 +00001769 // If it is a pointer, do the same.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001770 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1771 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1772 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1773 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1774 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
Owen Anderson1d0be152009-08-13 21:58:54 +00001775 SV = Builder.CreateBitCast(SV,
1776 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001777 else if (isa<PointerType>(SV->getType()))
Owen Anderson1d0be152009-08-13 21:58:54 +00001778 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(SV->getContext()), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001779
Chris Lattner7809ecd2009-02-03 01:30:09 +00001780 // Zero extend or truncate the value if needed.
1781 if (SV->getType() != AllocaType) {
1782 if (SV->getType()->getPrimitiveSizeInBits() <
1783 AllocaType->getPrimitiveSizeInBits())
Chris Lattner65a65022009-02-03 19:41:50 +00001784 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001785 else {
1786 // Truncation may be needed if storing more than the alloca can hold
1787 // (undefined behavior).
Chris Lattner65a65022009-02-03 19:41:50 +00001788 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001789 SrcWidth = DestWidth;
1790 SrcStoreWidth = DestStoreWidth;
1791 }
1792 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001793
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001794 // If this is a big-endian system and the store is narrower than the
1795 // full alloca type, we need to do a shift to get the right bits.
1796 int ShAmt = 0;
1797 if (TD->isBigEndian()) {
1798 // On big-endian machines, the lowest bit is stored at the bit offset
1799 // from the pointer given by getTypeStoreSizeInBits. This matters for
1800 // integers with a bitwidth that is not a multiple of 8.
1801 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner800de312008-02-29 07:03:13 +00001802 } else {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001803 ShAmt = Offset;
1804 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001805
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001806 // Note: we support negative bitwidths (with shr) which are not defined.
1807 // We do this to support (f.e.) stores off the end of a structure where
1808 // only some bits in the structure are set.
1809 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1810 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001811 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001812 ShAmt), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001813 Mask <<= ShAmt;
1814 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001815 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001816 -ShAmt), "tmp");
Duncan Sands0e7c46b2009-02-02 09:53:14 +00001817 Mask = Mask.lshr(-ShAmt);
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001818 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001819
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001820 // Mask out the bits we are about to insert from the old value, and or
1821 // in the new bits.
1822 if (SrcWidth != DestWidth) {
1823 assert(DestWidth > SrcWidth);
Owen Andersoneed707b2009-07-24 23:12:02 +00001824 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
Chris Lattner65a65022009-02-03 19:41:50 +00001825 SV = Builder.CreateOr(Old, SV, "ins");
Chris Lattner800de312008-02-29 07:03:13 +00001826 }
1827 return SV;
1828}
1829
1830
Chris Lattner79b3bd32007-04-25 06:40:51 +00001831
1832/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1833/// some part of a constant global variable. This intentionally only accepts
1834/// constant expressions because we don't can't rewrite arbitrary instructions.
1835static bool PointsToConstantGlobal(Value *V) {
1836 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1837 return GV->isConstant();
1838 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1839 if (CE->getOpcode() == Instruction::BitCast ||
1840 CE->getOpcode() == Instruction::GetElementPtr)
1841 return PointsToConstantGlobal(CE->getOperand(0));
1842 return false;
1843}
1844
1845/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1846/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1847/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1848/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1849/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1850/// the alloca, and if the source pointer is a pointer to a constant global, we
1851/// can optimize this.
1852static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1853 bool isOffset) {
1854 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Chris Lattner6e733d32009-01-28 20:16:43 +00001855 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1856 // Ignore non-volatile loads, they are always ok.
1857 if (!LI->isVolatile())
1858 continue;
1859
Chris Lattner79b3bd32007-04-25 06:40:51 +00001860 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1861 // If uses of the bitcast are ok, we are ok.
1862 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1863 return false;
1864 continue;
1865 }
1866 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1867 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1868 // doesn't, it does.
1869 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1870 isOffset || !GEP->hasAllZeroIndices()))
1871 return false;
1872 continue;
1873 }
1874
1875 // If this is isn't our memcpy/memmove, reject it as something we can't
1876 // handle.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001877 if (!isa<MemTransferInst>(*UI))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001878 return false;
1879
1880 // If we already have seen a copy, reject the second one.
1881 if (TheCopy) return false;
1882
1883 // If the pointer has been offset from the start of the alloca, we can't
1884 // safely handle this.
1885 if (isOffset) return false;
1886
1887 // If the memintrinsic isn't using the alloca as the dest, reject it.
1888 if (UI.getOperandNo() != 1) return false;
1889
1890 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1891
1892 // If the source of the memcpy/move is not a constant global, reject it.
1893 if (!PointsToConstantGlobal(MI->getOperand(2)))
1894 return false;
1895
1896 // Otherwise, the transform is safe. Remember the copy instruction.
1897 TheCopy = MI;
1898 }
1899 return true;
1900}
1901
1902/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1903/// modified by a copy from a constant global. If we can prove this, we can
1904/// replace any uses of the alloca with uses of the global directly.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001905Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001906 Instruction *TheCopy = 0;
1907 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1908 return TheCopy;
1909 return 0;
1910}