blob: 83db90da763c9357bc41b0d13a6af94a7e4be3ec [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 Lattnera4f0b3a2006-08-27 12:54:02 +000041#include "llvm/Support/Compiler.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"
44#include "llvm/ADT/StringExtras.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000045using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000046
Chris Lattner0e5f4992006-12-19 21:40:18 +000047STATISTIC(NumReplaced, "Number of allocas broken up");
48STATISTIC(NumPromoted, "Number of allocas promoted");
49STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000050STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000051
Chris Lattner0e5f4992006-12-19 21:40:18 +000052namespace {
Chris Lattner95255282006-06-28 23:17:24 +000053 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000054 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000055 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Devang Patelff366852007-07-09 21:19:23 +000056 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000057 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000058 else
59 SRThreshold = T;
60 }
Devang Patel794fd752007-05-01 21:15:47 +000061
Chris Lattnered7b41e2003-05-27 15:45:27 +000062 bool runOnFunction(Function &F);
63
Chris Lattner38aec322003-09-11 16:45:55 +000064 bool performScalarRepl(Function &F);
65 bool performPromotion(Function &F);
66
Chris Lattnera15854c2003-08-31 00:45:13 +000067 // getAnalysisUsage - This pass does not require any passes, but we know it
68 // will not alter the CFG, so say so.
69 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel326821e2007-06-07 21:57:03 +000070 AU.addRequired<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +000071 AU.addRequired<DominanceFrontier>();
72 AU.addRequired<TargetData>();
Chris Lattnera15854c2003-08-31 00:45:13 +000073 AU.setPreservesCFG();
74 }
75
Chris Lattnered7b41e2003-05-27 15:45:27 +000076 private:
Chris Lattner56c38522009-01-07 06:34:28 +000077 TargetData *TD;
78
Chris Lattner39a1c042007-05-30 06:11:23 +000079 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
80 /// information about the uses. All these fields are initialized to false
81 /// and set to true when something is learned.
82 struct AllocaInfo {
83 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
84 bool isUnsafe : 1;
85
Devang Patel4afc90d2009-02-10 07:00:59 +000086 /// needsCleanup - This is set to true if there is some use of the alloca
87 /// that requires cleanup.
88 bool needsCleanup : 1;
Chris Lattner39a1c042007-05-30 06:11:23 +000089
90 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
91 bool isMemCpySrc : 1;
92
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000093 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000094 bool isMemCpyDst : 1;
95
96 AllocaInfo()
Devang Patel4afc90d2009-02-10 07:00:59 +000097 : isUnsafe(false), needsCleanup(false),
Chris Lattner39a1c042007-05-30 06:11:23 +000098 isMemCpySrc(false), isMemCpyDst(false) {}
99 };
100
Devang Patelff366852007-07-09 21:19:23 +0000101 unsigned SRThreshold;
102
Chris Lattner39a1c042007-05-30 06:11:23 +0000103 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
104
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000105 int isSafeAllocaToScalarRepl(AllocationInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000106
107 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
108 AllocaInfo &Info);
109 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
110 AllocaInfo &Info);
111 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
112 unsigned OpNo, AllocaInfo &Info);
113 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
114 AllocaInfo &Info);
115
Chris Lattnera10b29b2007-04-25 05:02:56 +0000116 void DoScalarReplacement(AllocationInst *AI,
117 std::vector<AllocationInst*> &WorkList);
Devang Patel4afc90d2009-02-10 07:00:59 +0000118 void CleanupGEP(GetElementPtrInst *GEP);
119 void CleanupAllocaUsers(AllocationInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000120 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
Chris Lattnera1888942005-12-12 07:19:13 +0000121
Chris Lattner8bf99112007-03-19 00:16:43 +0000122 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
Chris Lattner372dda82007-03-05 07:52:57 +0000123 SmallVector<AllocaInst*, 32> &NewElts);
124
Chris Lattnerd93afec2009-01-07 07:18:45 +0000125 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
126 AllocationInst *AI,
127 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000128 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocationInst *AI,
129 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000130 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000131 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000132
Chris Lattner7809ecd2009-02-03 01:30:09 +0000133 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
Chris Lattner1a3257b2009-02-03 18:15:05 +0000134 bool &SawVec, uint64_t Offset, unsigned AllocaSize);
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000135 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Chris Lattner6e011152009-02-03 21:01:03 +0000136 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
Chris Lattner9bc67da2009-02-03 19:45:44 +0000137 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +0000138 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Chris Lattner65a65022009-02-03 19:41:50 +0000139 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner79b3bd32007-04-25 06:40:51 +0000140 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000141 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000142}
143
Dan Gohman844731a2008-05-13 00:00:25 +0000144char SROA::ID = 0;
145static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
146
Brian Gaeked0fde302003-11-11 22:41:34 +0000147// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000148FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
149 return new SROA(Threshold);
150}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000151
152
Chris Lattnered7b41e2003-05-27 15:45:27 +0000153bool SROA::runOnFunction(Function &F) {
Chris Lattner56c38522009-01-07 06:34:28 +0000154 TD = &getAnalysis<TargetData>();
155
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000156 bool Changed = performPromotion(F);
157 while (1) {
158 bool LocalChange = performScalarRepl(F);
159 if (!LocalChange) break; // No need to repromote if no scalarrepl
160 Changed = true;
161 LocalChange = performPromotion(F);
162 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
163 }
Chris Lattner38aec322003-09-11 16:45:55 +0000164
165 return Changed;
166}
167
168
169bool SROA::performPromotion(Function &F) {
170 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000171 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000172 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000173
Chris Lattner02a3be02003-09-20 14:39:18 +0000174 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000175
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000176 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000177
Chris Lattner38aec322003-09-11 16:45:55 +0000178 while (1) {
179 Allocas.clear();
180
181 // Find allocas that are safe to promote, by looking at all instructions in
182 // the entry node
183 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
184 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000185 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000186 Allocas.push_back(AI);
187
188 if (Allocas.empty()) break;
189
Owen Anderson0a205a42009-07-05 22:41:43 +0000190 PromoteMemToReg(Allocas, DT, DF, Context);
Chris Lattner38aec322003-09-11 16:45:55 +0000191 NumPromoted += Allocas.size();
192 Changed = true;
193 }
194
195 return Changed;
196}
197
Chris Lattner963a97f2008-06-22 17:46:21 +0000198/// getNumSAElements - Return the number of elements in the specific struct or
199/// array.
200static uint64_t getNumSAElements(const Type *T) {
201 if (const StructType *ST = dyn_cast<StructType>(T))
202 return ST->getNumElements();
203 return cast<ArrayType>(T)->getNumElements();
204}
205
Chris Lattner38aec322003-09-11 16:45:55 +0000206// performScalarRepl - This algorithm is a simple worklist driven algorithm,
207// which runs on all of the malloc/alloca instructions in the function, removing
208// them if they are only used by getelementptr instructions.
209//
210bool SROA::performScalarRepl(Function &F) {
Chris Lattnered7b41e2003-05-27 15:45:27 +0000211 std::vector<AllocationInst*> WorkList;
212
213 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner02a3be02003-09-20 14:39:18 +0000214 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000215 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
216 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
217 WorkList.push_back(A);
218
219 // Process the worklist
220 bool Changed = false;
221 while (!WorkList.empty()) {
222 AllocationInst *AI = WorkList.back();
223 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000224
Chris Lattneradd2bd72006-12-22 23:14:42 +0000225 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
226 // with unused elements.
227 if (AI->use_empty()) {
228 AI->eraseFromParent();
229 continue;
230 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000231
232 // If this alloca is impossible for us to promote, reject it early.
233 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
234 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000235
236 // Check to see if this allocation is only modified by a memcpy/memmove from
237 // a constant global. If this is the case, we can change all users to use
238 // the constant global instead. This is commonly produced by the CFE by
239 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
240 // is only subsequently read.
241 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
242 DOUT << "Found alloca equal to global: " << *AI;
243 DOUT << " memcpy = " << *TheCopy;
244 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000245 AI->replaceAllUsesWith(
246 Context->getConstantExprBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000247 TheCopy->eraseFromParent(); // Don't mutate the global.
248 AI->eraseFromParent();
249 ++NumGlobals;
250 Changed = true;
251 continue;
252 }
Chris Lattner15c82772009-02-02 20:44:45 +0000253
Chris Lattner7809ecd2009-02-03 01:30:09 +0000254 // Check to see if we can perform the core SROA transformation. We cannot
255 // transform the allocation instruction if it is an array allocation
256 // (allocations OF arrays are ok though), and an allocation of a scalar
257 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000258 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000259
260 // Do not promote any struct whose size is too big.
Bill Wendling3aaf5d92009-03-03 19:18:49 +0000261 if (AllocaSize > SRThreshold) continue;
Bill Wendling8fe40812009-03-01 03:55:12 +0000262
Chris Lattner7809ecd2009-02-03 01:30:09 +0000263 if ((isa<StructType>(AI->getAllocatedType()) ||
264 isa<ArrayType>(AI->getAllocatedType())) &&
Chris Lattner7809ecd2009-02-03 01:30:09 +0000265 // Do not promote any struct into more than "32" separate vars.
Evan Cheng67fca632009-03-06 00:56:43 +0000266 getNumSAElements(AI->getAllocatedType()) <= SRThreshold/4) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000267 // Check that all of the users of the allocation are capable of being
268 // transformed.
269 switch (isSafeAllocaToScalarRepl(AI)) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000270 default: llvm_unreachable("Unexpected value!");
Chris Lattner7809ecd2009-02-03 01:30:09 +0000271 case 0: // Not safe to scalar replace.
272 break;
273 case 1: // Safe, but requires cleanup/canonicalizations first
Devang Patel4afc90d2009-02-10 07:00:59 +0000274 CleanupAllocaUsers(AI);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000275 // FALL THROUGH.
276 case 3: // Safe to scalar replace.
277 DoScalarReplacement(AI, WorkList);
278 Changed = true;
279 continue;
280 }
281 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000282
283 // If we can turn this aggregate value (potentially with casts) into a
284 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000285 // IsNotTrivial tracks whether this is something that mem2reg could have
286 // promoted itself. If so, we don't want to transform it needlessly. Note
287 // that we can't just check based on the type: the alloca may be of an i32
288 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner6e733d32009-01-28 20:16:43 +0000289 bool IsNotTrivial = false;
Chris Lattner7809ecd2009-02-03 01:30:09 +0000290 const Type *VectorTy = 0;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000291 bool HadAVector = false;
292 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
Chris Lattner0ff83ab2009-03-04 19:22:30 +0000293 0, unsigned(AllocaSize)) && IsNotTrivial) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000294 AllocaInst *NewAI;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000295 // If we were able to find a vector type that can handle this with
296 // insert/extract elements, and if there was at least one use that had
297 // a vector type, promote this to a vector. We don't want to promote
298 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
299 // we just get a lot of insert/extracts. If at least one vector is
300 // involved, then we probably really do have a union of vector/array.
301 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000302 DOUT << "CONVERT TO VECTOR: " << *AI << " TYPE = " << *VectorTy <<"\n";
Chris Lattner15c82772009-02-02 20:44:45 +0000303
Chris Lattner7809ecd2009-02-03 01:30:09 +0000304 // Create and insert the vector alloca.
305 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
Chris Lattner15c82772009-02-02 20:44:45 +0000306 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000307 } else {
308 DOUT << "CONVERT TO SCALAR INTEGER: " << *AI << "\n";
309
310 // Create and insert the integer alloca.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000311 const Type *NewTy = Context->getIntegerType(AllocaSize*8);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000312 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
313 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner6e733d32009-01-28 20:16:43 +0000314 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000315 NewAI->takeName(AI);
316 AI->eraseFromParent();
317 ++NumConverted;
318 Changed = true;
319 continue;
320 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000321
Chris Lattner7809ecd2009-02-03 01:30:09 +0000322 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000323 }
324
325 return Changed;
326}
Chris Lattner5e062a12003-05-30 04:15:41 +0000327
Chris Lattnera10b29b2007-04-25 05:02:56 +0000328/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
329/// predicate, do SROA now.
330void SROA::DoScalarReplacement(AllocationInst *AI,
331 std::vector<AllocationInst*> &WorkList) {
Chris Lattner79b3bd32007-04-25 06:40:51 +0000332 DOUT << "Found inst to SROA: " << *AI;
Chris Lattnera10b29b2007-04-25 05:02:56 +0000333 SmallVector<AllocaInst*, 32> ElementAllocas;
334 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
335 ElementAllocas.reserve(ST->getNumContainedTypes());
336 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
337 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
338 AI->getAlignment(),
339 AI->getName() + "." + utostr(i), AI);
340 ElementAllocas.push_back(NA);
341 WorkList.push_back(NA); // Add to worklist for recursive processing
342 }
343 } else {
344 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
345 ElementAllocas.reserve(AT->getNumElements());
346 const Type *ElTy = AT->getElementType();
347 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
348 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
349 AI->getName() + "." + utostr(i), AI);
350 ElementAllocas.push_back(NA);
351 WorkList.push_back(NA); // Add to worklist for recursive processing
352 }
353 }
354
355 // Now that we have created the alloca instructions that we want to use,
356 // expand the getelementptr instructions to use them.
357 //
358 while (!AI->use_empty()) {
359 Instruction *User = cast<Instruction>(AI->use_back());
360 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
361 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
362 BCInst->eraseFromParent();
363 continue;
364 }
365
Chris Lattner2a6a6452008-06-23 17:11:23 +0000366 // Replace:
367 // %res = load { i32, i32 }* %alloc
368 // with:
369 // %load.0 = load i32* %alloc.0
370 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
371 // %load.1 = load i32* %alloc.1
372 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
Matthijs Kooijman02518142008-06-05 12:51:53 +0000373 // (Also works for arrays instead of structs)
374 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000375 Value *Insert = Context->getUndef(LI->getType());
Matthijs Kooijman02518142008-06-05 12:51:53 +0000376 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
377 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
378 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
379 }
380 LI->replaceAllUsesWith(Insert);
381 LI->eraseFromParent();
382 continue;
383 }
384
Chris Lattner2a6a6452008-06-23 17:11:23 +0000385 // Replace:
386 // store { i32, i32 } %val, { i32, i32 }* %alloc
387 // with:
388 // %val.0 = extractvalue { i32, i32 } %val, 0
389 // store i32 %val.0, i32* %alloc.0
390 // %val.1 = extractvalue { i32, i32 } %val, 1
391 // store i32 %val.1, i32* %alloc.1
Matthijs Kooijman02518142008-06-05 12:51:53 +0000392 // (Also works for arrays instead of structs)
393 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
394 Value *Val = SI->getOperand(0);
395 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
396 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
397 new StoreInst(Extract, ElementAllocas[i], SI);
398 }
399 SI->eraseFromParent();
400 continue;
401 }
402
Chris Lattnera10b29b2007-04-25 05:02:56 +0000403 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
404 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
405 unsigned Idx =
406 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
407
408 assert(Idx < ElementAllocas.size() && "Index out of range?");
409 AllocaInst *AllocaToUse = ElementAllocas[Idx];
410
411 Value *RepValue;
412 if (GEPI->getNumOperands() == 3) {
413 // Do not insert a new getelementptr instruction with zero indices, only
414 // to have it optimized out later.
415 RepValue = AllocaToUse;
416 } else {
417 // We are indexing deeply into the structure, so we still need a
418 // getelement ptr instruction to finish the indexing. This may be
419 // expanded itself once the worklist is rerun.
420 //
421 SmallVector<Value*, 8> NewArgs;
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000422 NewArgs.push_back(Context->getNullValue(Type::Int32Ty));
Chris Lattnera10b29b2007-04-25 05:02:56 +0000423 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
Gabor Greif051a9502008-04-06 20:25:17 +0000424 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
425 NewArgs.end(), "", GEPI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000426 RepValue->takeName(GEPI);
427 }
428
429 // If this GEP is to the start of the aggregate, check for memcpys.
Chris Lattnerd356a7e2009-01-07 06:25:07 +0000430 if (Idx == 0 && GEPI->hasAllZeroIndices())
431 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000432
433 // Move all of the users over to the new GEP.
434 GEPI->replaceAllUsesWith(RepValue);
435 // Delete the old GEP
436 GEPI->eraseFromParent();
437 }
438
439 // Finally, delete the Alloca instruction
440 AI->eraseFromParent();
441 NumReplaced++;
442}
443
Chris Lattner5e062a12003-05-30 04:15:41 +0000444
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000445/// isSafeElementUse - Check to see if this use is an allowed use for a
Chris Lattner8bf99112007-03-19 00:16:43 +0000446/// getelementptr instruction of an array aggregate allocation. isFirstElt
447/// indicates whether Ptr is known to the start of the aggregate.
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000448///
Chris Lattner39a1c042007-05-30 06:11:23 +0000449void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
450 AllocaInfo &Info) {
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000451 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
452 I != E; ++I) {
453 Instruction *User = cast<Instruction>(*I);
454 switch (User->getOpcode()) {
455 case Instruction::Load: break;
456 case Instruction::Store:
457 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattner39a1c042007-05-30 06:11:23 +0000458 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000459 break;
460 case Instruction::GetElementPtr: {
461 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
Chris Lattner8bf99112007-03-19 00:16:43 +0000462 bool AreAllZeroIndices = isFirstElt;
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000463 if (GEP->getNumOperands() > 1) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000464 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
465 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
Chris Lattner39a1c042007-05-30 06:11:23 +0000466 // Using pointer arithmetic to navigate the array.
467 return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000468
Chris Lattnerd356a7e2009-01-07 06:25:07 +0000469 if (AreAllZeroIndices)
470 AreAllZeroIndices = GEP->hasAllZeroIndices();
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000471 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000472 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
473 if (Info.isUnsafe) return;
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000474 break;
475 }
Chris Lattner8bf99112007-03-19 00:16:43 +0000476 case Instruction::BitCast:
Chris Lattner39a1c042007-05-30 06:11:23 +0000477 if (isFirstElt) {
478 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
479 if (Info.isUnsafe) return;
Chris Lattner8bf99112007-03-19 00:16:43 +0000480 break;
Chris Lattner8bf99112007-03-19 00:16:43 +0000481 }
482 DOUT << " Transformation preventing inst: " << *User;
Chris Lattner39a1c042007-05-30 06:11:23 +0000483 return MarkUnsafe(Info);
484 case Instruction::Call:
485 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
486 if (isFirstElt) {
487 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
488 if (Info.isUnsafe) return;
489 break;
490 }
491 }
492 DOUT << " Transformation preventing inst: " << *User;
493 return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000494 default:
Bill Wendlingb7427032006-11-26 09:46:52 +0000495 DOUT << " Transformation preventing inst: " << *User;
Chris Lattner39a1c042007-05-30 06:11:23 +0000496 return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000497 }
498 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000499 return; // All users look ok :)
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000500}
501
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000502/// AllUsersAreLoads - Return true if all users of this value are loads.
503static bool AllUsersAreLoads(Value *Ptr) {
504 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
505 I != E; ++I)
506 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
507 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000508 return true;
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000509}
510
Chris Lattner5e062a12003-05-30 04:15:41 +0000511/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
512/// aggregate allocation.
513///
Chris Lattner39a1c042007-05-30 06:11:23 +0000514void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
515 AllocaInfo &Info) {
Chris Lattner372dda82007-03-05 07:52:57 +0000516 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
Chris Lattner39a1c042007-05-30 06:11:23 +0000517 return isSafeUseOfBitCastedAllocation(C, AI, Info);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000518
Chris Lattner6e733d32009-01-28 20:16:43 +0000519 if (LoadInst *LI = dyn_cast<LoadInst>(User))
520 if (!LI->isVolatile())
521 return;// Loads (returning a first class aggregrate) are always rewritable
Matthijs Kooijman02518142008-06-05 12:51:53 +0000522
Chris Lattner6e733d32009-01-28 20:16:43 +0000523 if (StoreInst *SI = dyn_cast<StoreInst>(User))
524 if (!SI->isVolatile() && SI->getOperand(0) != AI)
525 return;// Store is ok if storing INTO the pointer, not storing the pointer
Matthijs Kooijman02518142008-06-05 12:51:53 +0000526
Chris Lattner39a1c042007-05-30 06:11:23 +0000527 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
528 if (GEPI == 0)
529 return MarkUnsafe(Info);
530
Chris Lattnerbe883a22003-11-25 21:09:18 +0000531 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
532
Chris Lattner25de4862006-03-08 01:05:29 +0000533 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
Chris Lattnerbe883a22003-11-25 21:09:18 +0000534 if (I == E ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000535 I.getOperand() != Context->getNullValue(I.getOperand()->getType())) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000536 return MarkUnsafe(Info);
537 }
Chris Lattnerbe883a22003-11-25 21:09:18 +0000538
539 ++I;
Chris Lattner39a1c042007-05-30 06:11:23 +0000540 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
Chris Lattnerbe883a22003-11-25 21:09:18 +0000541
Chris Lattner8bf99112007-03-19 00:16:43 +0000542 bool IsAllZeroIndices = true;
543
Chris Lattner88e6dc82008-08-23 05:21:06 +0000544 // If the first index is a non-constant index into an array, see if we can
545 // handle it as a special case.
Chris Lattnerbe883a22003-11-25 21:09:18 +0000546 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
Chris Lattner88e6dc82008-08-23 05:21:06 +0000547 if (!isa<ConstantInt>(I.getOperand())) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000548 IsAllZeroIndices = 0;
Chris Lattner88e6dc82008-08-23 05:21:06 +0000549 uint64_t NumElements = AT->getNumElements();
Chris Lattner8bf99112007-03-19 00:16:43 +0000550
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000551 // If this is an array index and the index is not constant, we cannot
552 // promote... that is unless the array has exactly one or two elements in
553 // it, in which case we CAN promote it, but we have to canonicalize this
554 // out if this is the only problem.
Chris Lattner25de4862006-03-08 01:05:29 +0000555 if ((NumElements == 1 || NumElements == 2) &&
Chris Lattner39a1c042007-05-30 06:11:23 +0000556 AllUsersAreLoads(GEPI)) {
Devang Patel4afc90d2009-02-10 07:00:59 +0000557 Info.needsCleanup = true;
Chris Lattner39a1c042007-05-30 06:11:23 +0000558 return; // Canonicalization required!
559 }
560 return MarkUnsafe(Info);
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000561 }
Chris Lattner5e062a12003-05-30 04:15:41 +0000562 }
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000563
Chris Lattner88e6dc82008-08-23 05:21:06 +0000564 // Walk through the GEP type indices, checking the types that this indexes
565 // into.
566 for (; I != E; ++I) {
567 // Ignore struct elements, no extra checking needed for these.
568 if (isa<StructType>(*I))
569 continue;
570
Chris Lattner88e6dc82008-08-23 05:21:06 +0000571 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
572 if (!IdxVal) return MarkUnsafe(Info);
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000573
574 // Are all indices still zero?
Chris Lattner88e6dc82008-08-23 05:21:06 +0000575 IsAllZeroIndices &= IdxVal->isZero();
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000576
577 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
578 // This GEP indexes an array. Verify that this is an in-range constant
579 // integer. Specifically, consider A[0][i]. We cannot know that the user
580 // isn't doing invalid things like allowing i to index an out-of-range
581 // subscript that accesses A[1]. Because of this, we have to reject SROA
Dale Johannesenc0bc5472008-11-04 20:54:03 +0000582 // of any accesses into structs where any of the components are variables.
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000583 if (IdxVal->getZExtValue() >= AT->getNumElements())
584 return MarkUnsafe(Info);
Dale Johannesenc0bc5472008-11-04 20:54:03 +0000585 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
586 if (IdxVal->getZExtValue() >= VT->getNumElements())
587 return MarkUnsafe(Info);
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000588 }
Chris Lattner88e6dc82008-08-23 05:21:06 +0000589 }
590
Chris Lattnerbe883a22003-11-25 21:09:18 +0000591 // If there are any non-simple uses of this getelementptr, make sure to reject
592 // them.
Chris Lattner39a1c042007-05-30 06:11:23 +0000593 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000594}
595
596/// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
597/// intrinsic can be promoted by SROA. At this point, we know that the operand
598/// of the memintrinsic is a pointer to the beginning of the allocation.
Chris Lattner39a1c042007-05-30 06:11:23 +0000599void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
600 unsigned OpNo, AllocaInfo &Info) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000601 // If not constant length, give up.
602 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattner39a1c042007-05-30 06:11:23 +0000603 if (!Length) return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000604
605 // If not the whole aggregate, give up.
Duncan Sands3cb36502007-11-04 14:43:57 +0000606 if (Length->getZExtValue() !=
Duncan Sands777d2302009-05-09 07:06:46 +0000607 TD->getTypeAllocSize(AI->getType()->getElementType()))
Chris Lattner39a1c042007-05-30 06:11:23 +0000608 return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000609
610 // We only know about memcpy/memset/memmove.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000611 if (!isa<MemIntrinsic>(MI))
Chris Lattner39a1c042007-05-30 06:11:23 +0000612 return MarkUnsafe(Info);
613
614 // Otherwise, we can transform it. Determine whether this is a memcpy/set
615 // into or out of the aggregate.
616 if (OpNo == 1)
617 Info.isMemCpyDst = true;
618 else {
619 assert(OpNo == 2);
620 Info.isMemCpySrc = true;
621 }
Chris Lattner5e062a12003-05-30 04:15:41 +0000622}
623
Chris Lattner372dda82007-03-05 07:52:57 +0000624/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
625/// are
Chris Lattner39a1c042007-05-30 06:11:23 +0000626void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
627 AllocaInfo &Info) {
Chris Lattner372dda82007-03-05 07:52:57 +0000628 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
629 UI != E; ++UI) {
630 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000631 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
Chris Lattner372dda82007-03-05 07:52:57 +0000632 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000633 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000634 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner6e733d32009-01-28 20:16:43 +0000635 if (SI->isVolatile())
636 return MarkUnsafe(Info);
637
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000638 // If storing the entire alloca in one chunk through a bitcasted pointer
639 // to integer, we can transform it. This happens (for example) when you
640 // cast a {i32,i32}* to i64* and store through it. This is similar to the
641 // memcpy case and occurs in various "byval" cases and emulated memcpys.
642 if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
Duncan Sands777d2302009-05-09 07:06:46 +0000643 TD->getTypeAllocSize(SI->getOperand(0)->getType()) ==
644 TD->getTypeAllocSize(AI->getType()->getElementType())) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000645 Info.isMemCpyDst = true;
646 continue;
647 }
648 return MarkUnsafe(Info);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000649 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
Chris Lattner6e733d32009-01-28 20:16:43 +0000650 if (LI->isVolatile())
651 return MarkUnsafe(Info);
652
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000653 // If loading the entire alloca in one chunk through a bitcasted pointer
654 // to integer, we can transform it. This happens (for example) when you
655 // cast a {i32,i32}* to i64* and load through it. This is similar to the
656 // memcpy case and occurs in various "byval" cases and emulated memcpys.
657 if (isa<IntegerType>(LI->getType()) &&
Duncan Sands777d2302009-05-09 07:06:46 +0000658 TD->getTypeAllocSize(LI->getType()) ==
659 TD->getTypeAllocSize(AI->getType()->getElementType())) {
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000660 Info.isMemCpySrc = true;
661 continue;
662 }
663 return MarkUnsafe(Info);
Devang Patel4afc90d2009-02-10 07:00:59 +0000664 } else if (isa<DbgInfoIntrinsic>(UI)) {
665 // If one user is DbgInfoIntrinsic then check if all users are
666 // DbgInfoIntrinsics.
667 if (OnlyUsedByDbgInfoIntrinsics(BC)) {
668 Info.needsCleanup = true;
669 return;
670 }
671 else
672 MarkUnsafe(Info);
673 }
674 else {
Chris Lattner39a1c042007-05-30 06:11:23 +0000675 return MarkUnsafe(Info);
Chris Lattner372dda82007-03-05 07:52:57 +0000676 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000677 if (Info.isUnsafe) return;
Chris Lattner372dda82007-03-05 07:52:57 +0000678 }
Chris Lattner372dda82007-03-05 07:52:57 +0000679}
680
Chris Lattner8bf99112007-03-19 00:16:43 +0000681/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
682/// to its first element. Transform users of the cast to use the new values
683/// instead.
684void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
Chris Lattner372dda82007-03-05 07:52:57 +0000685 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000686 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
687 while (UI != UE) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000688 Instruction *User = cast<Instruction>(*UI++);
689 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
Chris Lattner372dda82007-03-05 07:52:57 +0000690 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000691 if (BCU->use_empty()) BCU->eraseFromParent();
Chris Lattner372dda82007-03-05 07:52:57 +0000692 continue;
693 }
694
Chris Lattnerd93afec2009-01-07 07:18:45 +0000695 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
696 // This must be memcpy/memmove/memset of the entire aggregate.
697 // Split into one per element.
698 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
Chris Lattner8bf99112007-03-19 00:16:43 +0000699 continue;
700 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000701
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000702 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000703 // If this is a store of the entire alloca from an integer, rewrite it.
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000704 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
705 continue;
706 }
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000707
708 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
709 // If this is a load of the entire alloca to an integer, rewrite it.
710 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
711 continue;
712 }
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000713
714 // Otherwise it must be some other user of a gep of the first pointer. Just
715 // leave these alone.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000716 continue;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000717 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000718}
719
720/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
721/// Rewrite it to copy or set the elements of the scalarized memory.
722void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
723 AllocationInst *AI,
724 SmallVector<AllocaInst*, 32> &NewElts) {
725
726 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +0000727 // appropriate type. The "Other" pointer is the pointer that goes to memory
728 // that doesn't have anything to do with the alloca that we are promoting. For
729 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000730 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +0000731 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +0000732 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
733 if (BCInst == MTI->getRawDest())
734 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000735 else {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000736 assert(BCInst == MTI->getRawSource());
737 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000738 }
739 }
740
741 // If there is an other pointer, we want to convert it to the same pointer
742 // type as AI has, so we can GEP through it safely.
743 if (OtherPtr) {
744 // It is likely that OtherPtr is a bitcast, if so, remove it.
745 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
746 OtherPtr = BC->getOperand(0);
747 // All zero GEPs are effectively bitcasts.
748 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
749 if (GEP->hasAllZeroIndices())
750 OtherPtr = GEP->getOperand(0);
Chris Lattner372dda82007-03-05 07:52:57 +0000751
Chris Lattnerd93afec2009-01-07 07:18:45 +0000752 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
753 if (BCE->getOpcode() == Instruction::BitCast)
754 OtherPtr = BCE->getOperand(0);
755
756 // If the pointer is not the right type, insert a bitcast to the right
757 // type.
758 if (OtherPtr->getType() != AI->getType())
759 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
760 MI);
761 }
762
763 // Process each element of the aggregate.
764 Value *TheFn = MI->getOperand(0);
765 const Type *BytePtrTy = MI->getRawDest()->getType();
766 bool SROADest = MI->getRawDest() == BCInst;
767
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000768 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000769
770 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
771 // If this is a memcpy/memmove, emit a GEP of the other element address.
772 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000773 unsigned OtherEltAlign = MemAlignment;
774
Chris Lattner372dda82007-03-05 07:52:57 +0000775 if (OtherPtr) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000776 Value *Idx[2] = { Zero, Context->getConstantInt(Type::Int32Ty, i) };
Chris Lattnerd93afec2009-01-07 07:18:45 +0000777 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
Chris Lattner963a97f2008-06-22 17:46:21 +0000778 OtherPtr->getNameStr()+"."+utostr(i),
Chris Lattnerd93afec2009-01-07 07:18:45 +0000779 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +0000780 uint64_t EltOffset;
781 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
782 if (const StructType *ST =
783 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
784 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
785 } else {
786 const Type *EltTy =
787 cast<SequentialType>(OtherPtr->getType())->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000788 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000789 }
790
791 // The alignment of the other pointer is the guaranteed alignment of the
792 // element, which is affected by both the known alignment of the whole
793 // mem intrinsic and the alignment of the element. If the alignment of
794 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
795 // known alignment is just 4 bytes.
796 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000797 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000798
799 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +0000800 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000801
802 // If we got down to a scalar, insert a load or store as appropriate.
803 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000804 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +0000805 if (SROADest) {
806 // From Other to Alloca.
807 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
808 new StoreInst(Elt, EltPtr, MI);
809 } else {
810 // From Alloca to Other.
811 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
812 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
813 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000814 continue;
815 }
816 assert(isa<MemSetInst>(MI));
817
818 // If the stored element is zero (common case), just store a null
819 // constant.
820 Constant *StoreVal;
821 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
822 if (CI->isZero()) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000823 StoreVal = Context->getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +0000824 } else {
825 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +0000826 const Type *ValTy = EltTy->getScalarType();
827
Chris Lattnerd93afec2009-01-07 07:18:45 +0000828 // Construct an integer with the right value.
829 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
830 APInt OneVal(EltSize, CI->getZExtValue());
831 APInt TotalVal(OneVal);
832 // Set each byte.
833 for (unsigned i = 0; 8*i < EltSize; ++i) {
834 TotalVal = TotalVal.shl(8);
835 TotalVal |= OneVal;
836 }
837
838 // Convert the integer value to the appropriate type.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000839 StoreVal = Context->getConstantInt(TotalVal);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000840 if (isa<PointerType>(ValTy))
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000841 StoreVal = Context->getConstantExprIntToPtr(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000842 else if (ValTy->isFloatingPoint())
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000843 StoreVal = Context->getConstantExprBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000844 assert(StoreVal->getType() == ValTy && "Type mismatch!");
845
846 // If the requested value was a vector constant, create it.
847 if (EltTy != ValTy) {
848 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
849 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000850 StoreVal = Context->getConstantVector(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000851 }
852 }
853 new StoreInst(StoreVal, EltPtr, MI);
854 continue;
855 }
856 // Otherwise, if we're storing a byte variable, use a memset call for
857 // this element.
858 }
859
860 // Cast the element pointer to BytePtrTy.
861 if (EltPtr->getType() != BytePtrTy)
862 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
863
864 // Cast the other pointer (if we have one) to BytePtrTy.
865 if (OtherElt && OtherElt->getType() != BytePtrTy)
866 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
867 MI);
868
Duncan Sands777d2302009-05-09 07:06:46 +0000869 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000870
871 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000872 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000873 Value *Ops[] = {
874 SROADest ? EltPtr : OtherElt, // Dest ptr
875 SROADest ? OtherElt : EltPtr, // Src ptr
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000876 Context->getConstantInt(MI->getOperand(3)->getType(), EltSize), // Size
877 Context->getConstantInt(Type::Int32Ty, OtherEltAlign) // Align
Chris Lattnerd93afec2009-01-07 07:18:45 +0000878 };
879 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
880 } else {
881 assert(isa<MemSetInst>(MI));
882 Value *Ops[] = {
883 EltPtr, MI->getOperand(2), // Dest, Value,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000884 Context->getConstantInt(MI->getOperand(3)->getType(), EltSize), // Size
Chris Lattnerd93afec2009-01-07 07:18:45 +0000885 Zero // Align
886 };
887 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
888 }
Chris Lattner372dda82007-03-05 07:52:57 +0000889 }
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000890 MI->eraseFromParent();
Chris Lattner372dda82007-03-05 07:52:57 +0000891}
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000892
893/// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
894/// overwrites the entire allocation. Extract out the pieces of the stored
895/// integer and store them individually.
896void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
897 AllocationInst *AI,
898 SmallVector<AllocaInst*, 32> &NewElts){
899 // Extract each element out of the integer according to its structure offset
900 // and store the element value to the individual alloca.
901 Value *SrcVal = SI->getOperand(0);
902 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000903 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000904
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000905 // If this isn't a store of an integer to the whole alloca, it may be a store
906 // to the first element. Just ignore the store in this case and normal SROA
Eli Friedman41b33f42009-06-01 09:14:32 +0000907 // will handle it.
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000908 if (!isa<IntegerType>(SrcVal->getType()) ||
Eli Friedman41b33f42009-06-01 09:14:32 +0000909 TD->getTypeAllocSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000910 return;
Eli Friedman41b33f42009-06-01 09:14:32 +0000911 // Handle tail padding by extending the operand
912 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000913 SrcVal = new ZExtInst(SrcVal,
914 Context->getIntegerType(AllocaSizeBits), "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000915
916 DOUT << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI;
917
918 // There are two forms here: AI could be an array or struct. Both cases
919 // have different ways to compute the element offset.
920 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
921 const StructLayout *Layout = TD->getStructLayout(EltSTy);
922
923 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
924 // Get the number of bits to shift SrcVal to get the value.
925 const Type *FieldTy = EltSTy->getElementType(i);
926 uint64_t Shift = Layout->getElementOffsetInBits(i);
927
928 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +0000929 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000930
931 Value *EltVal = SrcVal;
932 if (Shift) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000933 Value *ShiftVal = Context->getConstantInt(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000934 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
935 "sroa.store.elt", SI);
936 }
937
938 // Truncate down to an integer of the right size.
939 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +0000940
941 // Ignore zero sized fields like {}, they obviously contain no data.
942 if (FieldSizeBits == 0) continue;
943
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000944 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000945 EltVal = new TruncInst(EltVal,
946 Context->getIntegerType(FieldSizeBits), "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000947 Value *DestField = NewElts[i];
948 if (EltVal->getType() == FieldTy) {
949 // Storing to an integer field of this size, just do it.
950 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
951 // Bitcast to the right element type (for fp/vector values).
952 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
953 } else {
954 // Otherwise, bitcast the dest pointer (for aggregates).
955 DestField = new BitCastInst(DestField,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000956 Context->getPointerTypeUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000957 "", SI);
958 }
959 new StoreInst(EltVal, DestField, SI);
960 }
961
962 } else {
963 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
964 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000965 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000966 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
967
968 uint64_t Shift;
969
970 if (TD->isBigEndian())
971 Shift = AllocaSizeBits-ElementOffset;
972 else
973 Shift = 0;
974
975 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +0000976 // Ignore zero sized fields like {}, they obviously contain no data.
977 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000978
979 Value *EltVal = SrcVal;
980 if (Shift) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000981 Value *ShiftVal = Context->getConstantInt(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000982 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
983 "sroa.store.elt", SI);
984 }
985
986 // Truncate down to an integer of the right size.
987 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000988 EltVal = new TruncInst(EltVal,
989 Context->getIntegerType(ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000990 Value *DestField = NewElts[i];
991 if (EltVal->getType() == ArrayEltTy) {
992 // Storing to an integer field of this size, just do it.
993 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
994 // Bitcast to the right element type (for fp/vector values).
995 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
996 } else {
997 // Otherwise, bitcast the dest pointer (for aggregates).
998 DestField = new BitCastInst(DestField,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000999 Context->getPointerTypeUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001000 "", SI);
1001 }
1002 new StoreInst(EltVal, DestField, SI);
1003
1004 if (TD->isBigEndian())
1005 Shift -= ElementOffset;
1006 else
1007 Shift += ElementOffset;
1008 }
1009 }
1010
1011 SI->eraseFromParent();
1012}
1013
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001014/// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to
1015/// an integer. Load the individual pieces to form the aggregate value.
1016void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
1017 SmallVector<AllocaInst*, 32> &NewElts) {
1018 // Extract each element out of the NewElts according to its structure offset
1019 // and form the result value.
1020 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001021 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001022
1023 // If this isn't a load of the whole alloca to an integer, it may be a load
1024 // of the first element. Just ignore the load in this case and normal SROA
Eli Friedman41b33f42009-06-01 09:14:32 +00001025 // will handle it.
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001026 if (!isa<IntegerType>(LI->getType()) ||
Eli Friedman41b33f42009-06-01 09:14:32 +00001027 TD->getTypeAllocSizeInBits(LI->getType()) != AllocaSizeBits)
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001028 return;
1029
1030 DOUT << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << *LI;
1031
1032 // There are two forms here: AI could be an array or struct. Both cases
1033 // have different ways to compute the element offset.
1034 const StructLayout *Layout = 0;
1035 uint64_t ArrayEltBitOffset = 0;
1036 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1037 Layout = TD->getStructLayout(EltSTy);
1038 } else {
1039 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001040 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001041 }
1042
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001043 Value *ResultVal =
1044 Context->getNullValue(Context->getIntegerType(AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001045
1046 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1047 // Load the value from the alloca. If the NewElt is an aggregate, cast
1048 // the pointer to an integer of the same size before doing the load.
1049 Value *SrcField = NewElts[i];
1050 const Type *FieldTy =
1051 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001052 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1053
1054 // Ignore zero sized fields like {}, they obviously contain no data.
1055 if (FieldSizeBits == 0) continue;
1056
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001057 const IntegerType *FieldIntTy = Context->getIntegerType(FieldSizeBits);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001058 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1059 !isa<VectorType>(FieldTy))
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001060 SrcField = new BitCastInst(SrcField,
1061 Context->getPointerTypeUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001062 "", LI);
1063 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1064
1065 // If SrcField is a fp or vector of the right size but that isn't an
1066 // integer type, bitcast to an integer so we can shift it.
1067 if (SrcField->getType() != FieldIntTy)
1068 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1069
1070 // Zero extend the field to be the same size as the final alloca so that
1071 // we can shift and insert it.
1072 if (SrcField->getType() != ResultVal->getType())
1073 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1074
1075 // Determine the number of bits to shift SrcField.
1076 uint64_t Shift;
1077 if (Layout) // Struct case.
1078 Shift = Layout->getElementOffsetInBits(i);
1079 else // Array case.
1080 Shift = i*ArrayEltBitOffset;
1081
1082 if (TD->isBigEndian())
1083 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1084
1085 if (Shift) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001086 Value *ShiftVal = Context->getConstantInt(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001087 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1088 }
1089
1090 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1091 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001092
1093 // Handle tail padding by truncating the result
1094 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1095 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1096
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001097 LI->replaceAllUsesWith(ResultVal);
1098 LI->eraseFromParent();
1099}
1100
Chris Lattner372dda82007-03-05 07:52:57 +00001101
Duncan Sands3cb36502007-11-04 14:43:57 +00001102/// HasPadding - Return true if the specified type has any structure or
1103/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001104static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001105 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1106 const StructLayout *SL = TD.getStructLayout(STy);
1107 unsigned PrevFieldBitOffset = 0;
1108 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001109 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1110
Chris Lattner39a1c042007-05-30 06:11:23 +00001111 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001112 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001113 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001114
Chris Lattner39a1c042007-05-30 06:11:23 +00001115 // Check to see if there is any padding between this element and the
1116 // previous one.
1117 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001118 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001119 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1120 if (PrevFieldEnd < FieldBitOffset)
1121 return true;
1122 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001123
Chris Lattner39a1c042007-05-30 06:11:23 +00001124 PrevFieldBitOffset = FieldBitOffset;
1125 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001126
Chris Lattner39a1c042007-05-30 06:11:23 +00001127 // Check for tail padding.
1128 if (unsigned EltCount = STy->getNumElements()) {
1129 unsigned PrevFieldEnd = PrevFieldBitOffset +
1130 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001131 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001132 return true;
1133 }
1134
1135 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001136 return HasPadding(ATy->getElementType(), TD);
Duncan Sands3cb36502007-11-04 14:43:57 +00001137 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001138 return HasPadding(VTy->getElementType(), TD);
Chris Lattner39a1c042007-05-30 06:11:23 +00001139 }
Duncan Sands777d2302009-05-09 07:06:46 +00001140 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001141}
Chris Lattner372dda82007-03-05 07:52:57 +00001142
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001143/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1144/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1145/// or 1 if safe after canonicalization has been performed.
Chris Lattner5e062a12003-05-30 04:15:41 +00001146///
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001147int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001148 // Loop over the use list of the alloca. We can only transform it if all of
1149 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001150 AllocaInfo Info;
1151
Chris Lattner5e062a12003-05-30 04:15:41 +00001152 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001153 I != E; ++I) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001154 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1155 if (Info.isUnsafe) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001156 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001157 return 0;
Chris Lattner5e062a12003-05-30 04:15:41 +00001158 }
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001159 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001160
1161 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1162 // source and destination, we have to be careful. In particular, the memcpy
1163 // could be moving around elements that live in structure padding of the LLVM
1164 // types, but may actually be used. In these cases, we refuse to promote the
1165 // struct.
1166 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Chris Lattner56c38522009-01-07 06:34:28 +00001167 HasPadding(AI->getType()->getElementType(), *TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001168 return 0;
Duncan Sands3cb36502007-11-04 14:43:57 +00001169
Chris Lattner39a1c042007-05-30 06:11:23 +00001170 // If we require cleanup, return 1, otherwise return 3.
Devang Patel4afc90d2009-02-10 07:00:59 +00001171 return Info.needsCleanup ? 1 : 3;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001172}
1173
Devang Patel4afc90d2009-02-10 07:00:59 +00001174/// CleanupGEP - GEP is used by an Alloca, which can be prompted after the GEP
1175/// is canonicalized here.
1176void SROA::CleanupGEP(GetElementPtrInst *GEPI) {
1177 gep_type_iterator I = gep_type_begin(GEPI);
1178 ++I;
1179
Devang Patel7afe8fa2009-02-10 19:28:07 +00001180 const ArrayType *AT = dyn_cast<ArrayType>(*I);
1181 if (!AT)
1182 return;
1183
1184 uint64_t NumElements = AT->getNumElements();
1185
1186 if (isa<ConstantInt>(I.getOperand()))
1187 return;
1188
1189 if (NumElements == 1) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001190 GEPI->setOperand(2, Context->getNullValue(Type::Int32Ty));
Devang Patel7afe8fa2009-02-10 19:28:07 +00001191 return;
1192 }
Devang Patel4afc90d2009-02-10 07:00:59 +00001193
Devang Patel7afe8fa2009-02-10 19:28:07 +00001194 assert(NumElements == 2 && "Unhandled case!");
1195 // All users of the GEP must be loads. At each use of the GEP, insert
1196 // two loads of the appropriate indexed GEP and select between them.
Owen Anderson333c4002009-07-09 23:48:35 +00001197 Value *IsOne = new ICmpInst(GEPI, ICmpInst::ICMP_NE, I.getOperand(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001198 Context->getNullValue(I.getOperand()->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001199 "isone");
Devang Patel7afe8fa2009-02-10 19:28:07 +00001200 // Insert the new GEP instructions, which are properly indexed.
1201 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001202 Indices[1] = Context->getNullValue(Type::Int32Ty);
Devang Patel7afe8fa2009-02-10 19:28:07 +00001203 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1204 Indices.begin(),
1205 Indices.end(),
1206 GEPI->getName()+".0", GEPI);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001207 Indices[1] = Context->getConstantInt(Type::Int32Ty, 1);
Devang Patel7afe8fa2009-02-10 19:28:07 +00001208 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1209 Indices.begin(),
1210 Indices.end(),
1211 GEPI->getName()+".1", GEPI);
1212 // Replace all loads of the variable index GEP with loads from both
1213 // indexes and a select.
1214 while (!GEPI->use_empty()) {
1215 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1216 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1217 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
1218 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
1219 LI->replaceAllUsesWith(R);
1220 LI->eraseFromParent();
Devang Patel4afc90d2009-02-10 07:00:59 +00001221 }
Devang Patel7afe8fa2009-02-10 19:28:07 +00001222 GEPI->eraseFromParent();
Devang Patel4afc90d2009-02-10 07:00:59 +00001223}
1224
Devang Patel7afe8fa2009-02-10 19:28:07 +00001225
Devang Patel4afc90d2009-02-10 07:00:59 +00001226/// CleanupAllocaUsers - If SROA reported that it can promote the specified
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001227/// allocation, but only if cleaned up, perform the cleanups required.
Devang Patel4afc90d2009-02-10 07:00:59 +00001228void SROA::CleanupAllocaUsers(AllocationInst *AI) {
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001229 // At this point, we know that the end result will be SROA'd and promoted, so
1230 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1231 // up.
1232 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1233 UI != E; ) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001234 User *U = *UI++;
1235 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
1236 CleanupGEP(GEPI);
Jay Foad0906b1b2009-06-06 17:49:35 +00001237 else {
1238 Instruction *I = cast<Instruction>(U);
Devang Patel4afc90d2009-02-10 07:00:59 +00001239 SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
Zhou Shengb0c41992009-03-18 12:48:48 +00001240 if (!isa<StoreInst>(I) && OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001241 // Safe to remove debug info uses.
1242 while (!DbgInUses.empty()) {
1243 DbgInfoIntrinsic *DI = DbgInUses.back(); DbgInUses.pop_back();
1244 DI->eraseFromParent();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001245 }
Devang Patel4afc90d2009-02-10 07:00:59 +00001246 I->eraseFromParent();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001247 }
1248 }
1249 }
Chris Lattner5e062a12003-05-30 04:15:41 +00001250}
Chris Lattnera1888942005-12-12 07:19:13 +00001251
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001252/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1253/// the offset specified by Offset (which is specified in bytes).
Chris Lattnerde6df882006-04-14 21:42:41 +00001254///
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001255/// There are two cases we handle here:
1256/// 1) A union of vector types of the same size and potentially its elements.
Chris Lattnerd22dbdf2006-12-15 07:32:38 +00001257/// Here we turn element accesses into insert/extract element operations.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001258/// This promotes a <4 x float> with a store of float to the third element
1259/// into a <4 x float> that uses insert element.
1260/// 2) A fully general blob of memory, which we turn into some (potentially
1261/// large) integer type with extract and insert operations where the loads
1262/// and stores would mutate the memory.
Chris Lattner7809ecd2009-02-03 01:30:09 +00001263static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001264 unsigned AllocaSize, const TargetData &TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001265 LLVMContext *Context) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001266 // If this could be contributing to a vector, analyze it.
1267 if (VecTy != Type::VoidTy) { // either null or a vector type.
Chris Lattner996d7a92009-02-02 18:02:59 +00001268
Chris Lattner7809ecd2009-02-03 01:30:09 +00001269 // If the In type is a vector that is the same size as the alloca, see if it
1270 // matches the existing VecTy.
1271 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1272 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1273 // If we're storing/loading a vector of the right size, allow it as a
1274 // vector. If this the first vector we see, remember the type so that
1275 // we know the element size.
1276 if (VecTy == 0)
1277 VecTy = VInTy;
1278 return;
1279 }
1280 } else if (In == Type::FloatTy || In == Type::DoubleTy ||
1281 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1282 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1283 // If we're accessing something that could be an element of a vector, see
1284 // if the implied vector agrees with what we already have and if Offset is
1285 // compatible with it.
1286 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1287 if (Offset % EltSize == 0 &&
1288 AllocaSize % EltSize == 0 &&
1289 (VecTy == 0 ||
1290 cast<VectorType>(VecTy)->getElementType()
1291 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1292 if (VecTy == 0)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001293 VecTy = Context->getVectorType(In, AllocaSize/EltSize);
Chris Lattner7809ecd2009-02-03 01:30:09 +00001294 return;
1295 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001296 }
1297 }
1298
Chris Lattner7809ecd2009-02-03 01:30:09 +00001299 // Otherwise, we have a case that we can't handle with an optimized vector
1300 // form. We can still turn this into a large integer.
1301 VecTy = Type::VoidTy;
Chris Lattnera1888942005-12-12 07:19:13 +00001302}
1303
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001304/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
Chris Lattner7809ecd2009-02-03 01:30:09 +00001305/// its accesses to use a to single vector type, return true, and set VecTy to
1306/// the new type. If we could convert the alloca into a single promotable
1307/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1308/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1309/// is the current offset from the base of the alloca being analyzed.
Chris Lattnera1888942005-12-12 07:19:13 +00001310///
Chris Lattner1a3257b2009-02-03 18:15:05 +00001311/// If we see at least one access to the value that is as a vector type, set the
1312/// SawVec flag.
1313///
1314bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1315 bool &SawVec, uint64_t Offset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001316 unsigned AllocaSize) {
Chris Lattnera1888942005-12-12 07:19:13 +00001317 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1318 Instruction *User = cast<Instruction>(*UI);
1319
1320 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001321 // Don't break volatile loads.
Chris Lattner6e733d32009-01-28 20:16:43 +00001322 if (LI->isVolatile())
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001323 return false;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001324 MergeInType(LI->getType(), Offset, VecTy, AllocaSize, *TD, Context);
Chris Lattner1a3257b2009-02-03 18:15:05 +00001325 SawVec |= isa<VectorType>(LI->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001326 continue;
1327 }
1328
1329 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001330 // Storing the pointer, not into the value?
Chris Lattner6e733d32009-01-28 20:16:43 +00001331 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001332 MergeInType(SI->getOperand(0)->getType(), Offset,
1333 VecTy, AllocaSize, *TD, Context);
Chris Lattner1a3257b2009-02-03 18:15:05 +00001334 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001335 continue;
1336 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001337
1338 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattner1a3257b2009-02-03 18:15:05 +00001339 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1340 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001341 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001342 IsNotTrivial = true;
Chris Lattnercf321862009-01-07 06:39:58 +00001343 continue;
1344 }
1345
1346 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001347 // If this is a GEP with a variable indices, we can't handle it.
1348 if (!GEP->hasAllConstantIndices())
1349 return false;
Chris Lattnercf321862009-01-07 06:39:58 +00001350
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001351 // Compute the offset that this GEP adds to the pointer.
1352 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1353 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1354 &Indices[0], Indices.size());
1355 // See if all uses can be converted.
Chris Lattner1a3257b2009-02-03 18:15:05 +00001356 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001357 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001358 return false;
1359 IsNotTrivial = true;
1360 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001361 }
Chris Lattner3ce5e882009-03-08 03:37:16 +00001362
Chris Lattner3d730f72009-02-03 02:01:43 +00001363 // If this is a constant sized memset of a constant value (e.g. 0) we can
1364 // handle it.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001365 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1366 // Store of constant value and constant size.
1367 if (isa<ConstantInt>(MSI->getValue()) &&
1368 isa<ConstantInt>(MSI->getLength())) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001369 IsNotTrivial = true;
1370 continue;
1371 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001372 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001373
1374 // If this is a memcpy or memmove into or out of the whole allocation, we
1375 // can handle it like a load or store of the scalar type.
1376 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1377 if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
1378 if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1379 IsNotTrivial = true;
1380 continue;
1381 }
1382 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001383
Devang Patel00e389c2009-03-06 07:03:54 +00001384 // Ignore dbg intrinsic.
1385 if (isa<DbgInfoIntrinsic>(User))
1386 continue;
1387
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001388 // Otherwise, we cannot handle this!
1389 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001390 }
1391
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001392 return true;
Chris Lattnera1888942005-12-12 07:19:13 +00001393}
1394
Chris Lattnera1888942005-12-12 07:19:13 +00001395
1396/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattnerde6df882006-04-14 21:42:41 +00001397/// directly. This happens when we are converting an "integer union" to a
1398/// single integer scalar, or when we are converting a "vector union" to a
1399/// vector with insert/extractelement instructions.
1400///
1401/// Offset is an offset from the original alloca, in bits that need to be
1402/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001403void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
Chris Lattnera1888942005-12-12 07:19:13 +00001404 while (!Ptr->use_empty()) {
1405 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001406
Chris Lattnercf321862009-01-07 06:39:58 +00001407 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb10e0da2008-01-30 00:39:15 +00001408 ConvertUsesToScalar(CI, NewAI, Offset);
Chris Lattnera1888942005-12-12 07:19:13 +00001409 CI->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001410 continue;
1411 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001412
Chris Lattnercf321862009-01-07 06:39:58 +00001413 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001414 // Compute the offset that this GEP adds to the pointer.
1415 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1416 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1417 &Indices[0], Indices.size());
1418 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Chris Lattnera1888942005-12-12 07:19:13 +00001419 GEP->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001420 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001421 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001422
Chris Lattner9bc67da2009-02-03 19:45:44 +00001423 IRBuilder<> Builder(User->getParent(), User);
1424
1425 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner6e011152009-02-03 21:01:03 +00001426 // The load is a bit extract from NewAI shifted right by Offset bits.
1427 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1428 Value *NewLoadVal
1429 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1430 LI->replaceAllUsesWith(NewLoadVal);
Chris Lattner9bc67da2009-02-03 19:45:44 +00001431 LI->eraseFromParent();
1432 continue;
1433 }
1434
1435 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1436 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1437 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").c_str());
1438 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1439 Builder);
1440 Builder.CreateStore(New, NewAI);
1441 SI->eraseFromParent();
1442 continue;
1443 }
1444
Chris Lattner3d730f72009-02-03 02:01:43 +00001445 // If this is a constant sized memset of a constant value (e.g. 0) we can
1446 // transform it into a store of the expanded constant value.
1447 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1448 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1449 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Chris Lattner33e24ad2009-04-21 16:52:12 +00001450 if (NumBytes != 0) {
1451 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1452
1453 // Compute the value replicated the right number of times.
1454 APInt APVal(NumBytes*8, Val);
Chris Lattner3d730f72009-02-03 02:01:43 +00001455
Chris Lattner33e24ad2009-04-21 16:52:12 +00001456 // Splat the value if non-zero.
1457 if (Val)
1458 for (unsigned i = 1; i != NumBytes; ++i)
1459 APVal |= APVal << 8;
1460
1461 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").c_str());
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001462 Value *New = ConvertScalar_InsertValue(Context->getConstantInt(APVal),
1463 Old, Offset, Builder);
Chris Lattner33e24ad2009-04-21 16:52:12 +00001464 Builder.CreateStore(New, NewAI);
1465 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001466 MSI->eraseFromParent();
1467 continue;
1468 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001469
1470 // If this is a memcpy or memmove into or out of the whole allocation, we
1471 // can handle it like a load or store of the scalar type.
1472 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1473 assert(Offset == 0 && "must be store to start of alloca");
1474
1475 // If the source and destination are both to the same alloca, then this is
1476 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
1477 // as appropriate.
1478 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject());
1479
1480 if (MTI->getSource()->getUnderlyingObject() != OrigAI) {
1481 // Dest must be OrigAI, change this to be a load from the original
1482 // pointer (bitcasted), then a store to our new alloca.
1483 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1484 Value *SrcPtr = MTI->getSource();
1485 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1486
1487 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1488 SrcVal->setAlignment(MTI->getAlignment());
1489 Builder.CreateStore(SrcVal, NewAI);
1490 } else if (MTI->getDest()->getUnderlyingObject() != OrigAI) {
1491 // Src must be OrigAI, change this to be a load from NewAI then a store
1492 // through the original dest pointer (bitcasted).
1493 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1494 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1495
1496 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1497 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1498 NewStore->setAlignment(MTI->getAlignment());
1499 } else {
1500 // Noop transfer. Src == Dst
1501 }
1502
1503
1504 MTI->eraseFromParent();
1505 continue;
1506 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001507
Devang Patel00e389c2009-03-06 07:03:54 +00001508 // If user is a dbg info intrinsic then it is safe to remove it.
1509 if (isa<DbgInfoIntrinsic>(User)) {
1510 User->eraseFromParent();
1511 continue;
1512 }
1513
Torok Edwinc23197a2009-07-14 16:55:14 +00001514 llvm_unreachable("Unsupported operation!");
Chris Lattnera1888942005-12-12 07:19:13 +00001515 }
1516}
Chris Lattner79b3bd32007-04-25 06:40:51 +00001517
Chris Lattner6e011152009-02-03 21:01:03 +00001518/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1519/// or vector value FromVal, extracting the bits from the offset specified by
1520/// Offset. This returns the value, which is of type ToType.
1521///
1522/// This happens when we are converting an "integer union" to a single
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001523/// integer scalar, or when we are converting a "vector union" to a vector with
1524/// insert/extractelement instructions.
Chris Lattner800de312008-02-29 07:03:13 +00001525///
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001526/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner6e011152009-02-03 21:01:03 +00001527/// shifted to the right.
1528Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1529 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001530 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattner6e011152009-02-03 21:01:03 +00001531 if (FromVal->getType() == ToType && Offset == 0)
1532 return FromVal;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001533
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001534 // If the result alloca is a vector type, this is either an element
1535 // access or a bitcast to another vector type of the same size.
Chris Lattner6e011152009-02-03 21:01:03 +00001536 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1537 if (isa<VectorType>(ToType))
1538 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001539
1540 // Otherwise it must be an element access.
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001541 unsigned Elt = 0;
1542 if (Offset) {
Duncan Sands777d2302009-05-09 07:06:46 +00001543 unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001544 Elt = Offset/EltSize;
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001545 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner800de312008-02-29 07:03:13 +00001546 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001547 // Return the element extracted out of it.
Chris Lattner6e011152009-02-03 21:01:03 +00001548 Value *V = Builder.CreateExtractElement(FromVal,
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001549 Context->getConstantInt(Type::Int32Ty,Elt),
Chris Lattner9bc67da2009-02-03 19:45:44 +00001550 "tmp");
Chris Lattner6e011152009-02-03 21:01:03 +00001551 if (V->getType() != ToType)
1552 V = Builder.CreateBitCast(V, ToType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001553 return V;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001554 }
Chris Lattner1aa70562009-02-03 21:08:45 +00001555
1556 // If ToType is a first class aggregate, extract out each of the pieces and
1557 // use insertvalue's to form the FCA.
1558 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1559 const StructLayout &Layout = *TD->getStructLayout(ST);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001560 Value *Res = Context->getUndef(ST);
Chris Lattner1aa70562009-02-03 21:08:45 +00001561 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1562 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
Chris Lattnere991ced2009-02-06 04:34:07 +00001563 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner1aa70562009-02-03 21:08:45 +00001564 Builder);
1565 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1566 }
1567 return Res;
1568 }
1569
1570 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001571 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001572 Value *Res = Context->getUndef(AT);
Chris Lattner1aa70562009-02-03 21:08:45 +00001573 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1574 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1575 Offset+i*EltSize, Builder);
1576 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1577 }
1578 return Res;
1579 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001580
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001581 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattner6e011152009-02-03 21:01:03 +00001582 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001583
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001584 // If this is a big-endian system and the load is narrower than the
1585 // full alloca type, we need to do a shift to get the right bits.
1586 int ShAmt = 0;
Chris Lattner56c38522009-01-07 06:34:28 +00001587 if (TD->isBigEndian()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001588 // On big-endian machines, the lowest bit is stored at the bit offset
1589 // from the pointer given by getTypeStoreSizeInBits. This matters for
1590 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner56c38522009-01-07 06:34:28 +00001591 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
Chris Lattner6e011152009-02-03 21:01:03 +00001592 TD->getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001593 } else {
1594 ShAmt = Offset;
1595 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001596
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001597 // Note: we support negative bitwidths (with shl) which are not defined.
1598 // We do this to support (f.e.) loads off the end of a structure where
1599 // only some bits are used.
1600 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001601 FromVal = Builder.CreateLShr(FromVal,
1602 Context->getConstantInt(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001603 ShAmt), "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001604 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001605 FromVal = Builder.CreateShl(FromVal,
1606 Context->getConstantInt(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001607 -ShAmt), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001608
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001609 // Finally, unconditionally truncate the integer to the right width.
Chris Lattner6e011152009-02-03 21:01:03 +00001610 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001611 if (LIBitWidth < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001612 FromVal =
1613 Builder.CreateTrunc(FromVal, Context->getIntegerType(LIBitWidth), "tmp");
Chris Lattner55a683d2009-02-03 07:08:57 +00001614 else if (LIBitWidth > NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001615 FromVal =
1616 Builder.CreateZExt(FromVal, Context->getIntegerType(LIBitWidth), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001617
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001618 // If the result is an integer, this is a trunc or bitcast.
Chris Lattner6e011152009-02-03 21:01:03 +00001619 if (isa<IntegerType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001620 // Should be done.
Chris Lattner6e011152009-02-03 21:01:03 +00001621 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001622 // Just do a bitcast, we know the sizes match up.
Chris Lattner6e011152009-02-03 21:01:03 +00001623 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001624 } else {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001625 // Otherwise must be a pointer.
Chris Lattner6e011152009-02-03 21:01:03 +00001626 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001627 }
Chris Lattner6e011152009-02-03 21:01:03 +00001628 assert(FromVal->getType() == ToType && "Didn't convert right?");
1629 return FromVal;
Chris Lattner800de312008-02-29 07:03:13 +00001630}
1631
1632
Chris Lattner9b872db2009-02-03 19:30:11 +00001633/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1634/// or vector value "Old" at the offset specified by Offset.
1635///
1636/// This happens when we are converting an "integer union" to a
Chris Lattner800de312008-02-29 07:03:13 +00001637/// single integer scalar, or when we are converting a "vector union" to a
1638/// vector with insert/extractelement instructions.
1639///
1640/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner9b872db2009-02-03 19:30:11 +00001641/// shifted to the right.
1642Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
Chris Lattner65a65022009-02-03 19:41:50 +00001643 uint64_t Offset, IRBuilder<> &Builder) {
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001644
Chris Lattner800de312008-02-29 07:03:13 +00001645 // Convert the stored type to the actual type, shift it left to insert
1646 // then 'or' into place.
Chris Lattner9b872db2009-02-03 19:30:11 +00001647 const Type *AllocaType = Old->getType();
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001648
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001649 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001650 uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1651 uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
Chris Lattner29e64172009-03-08 04:17:04 +00001652
1653 // Changing the whole vector with memset or with an access of a different
1654 // vector type?
1655 if (ValSize == VecSize)
1656 return Builder.CreateBitCast(SV, AllocaType, "tmp");
1657
Duncan Sands777d2302009-05-09 07:06:46 +00001658 uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner29e64172009-03-08 04:17:04 +00001659
1660 // Must be an element insertion.
1661 unsigned Elt = Offset/EltSize;
1662
1663 if (SV->getType() != VTy->getElementType())
1664 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1665
1666 SV = Builder.CreateInsertElement(Old, SV,
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001667 Context->getConstantInt(Type::Int32Ty, Elt),
Chris Lattner29e64172009-03-08 04:17:04 +00001668 "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001669 return SV;
1670 }
Chris Lattner9b872db2009-02-03 19:30:11 +00001671
1672 // If SV is a first-class aggregate value, insert each value recursively.
1673 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1674 const StructLayout &Layout = *TD->getStructLayout(ST);
1675 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001676 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Chris Lattner9b872db2009-02-03 19:30:11 +00001677 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattnere991ced2009-02-06 04:34:07 +00001678 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner65a65022009-02-03 19:41:50 +00001679 Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001680 }
1681 return Old;
1682 }
1683
1684 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Duncan Sands777d2302009-05-09 07:06:46 +00001685 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner9b872db2009-02-03 19:30:11 +00001686 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001687 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1688 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001689 }
1690 return Old;
1691 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001692
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001693 // If SV is a float, convert it to the appropriate integer type.
Chris Lattner9b872db2009-02-03 19:30:11 +00001694 // If it is a pointer, do the same.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001695 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1696 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1697 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1698 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1699 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001700 SV = Builder.CreateBitCast(SV, Context->getIntegerType(SrcWidth), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001701 else if (isa<PointerType>(SV->getType()))
Chris Lattner65a65022009-02-03 19:41:50 +00001702 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001703
Chris Lattner7809ecd2009-02-03 01:30:09 +00001704 // Zero extend or truncate the value if needed.
1705 if (SV->getType() != AllocaType) {
1706 if (SV->getType()->getPrimitiveSizeInBits() <
1707 AllocaType->getPrimitiveSizeInBits())
Chris Lattner65a65022009-02-03 19:41:50 +00001708 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001709 else {
1710 // Truncation may be needed if storing more than the alloca can hold
1711 // (undefined behavior).
Chris Lattner65a65022009-02-03 19:41:50 +00001712 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001713 SrcWidth = DestWidth;
1714 SrcStoreWidth = DestStoreWidth;
1715 }
1716 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001717
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001718 // If this is a big-endian system and the store is narrower than the
1719 // full alloca type, we need to do a shift to get the right bits.
1720 int ShAmt = 0;
1721 if (TD->isBigEndian()) {
1722 // On big-endian machines, the lowest bit is stored at the bit offset
1723 // from the pointer given by getTypeStoreSizeInBits. This matters for
1724 // integers with a bitwidth that is not a multiple of 8.
1725 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner800de312008-02-29 07:03:13 +00001726 } else {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001727 ShAmt = Offset;
1728 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001729
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001730 // Note: we support negative bitwidths (with shr) which are not defined.
1731 // We do this to support (f.e.) stores off the end of a structure where
1732 // only some bits in the structure are set.
1733 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1734 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001735 SV = Builder.CreateShl(SV, Context->getConstantInt(SV->getType(),
1736 ShAmt), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001737 Mask <<= ShAmt;
1738 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001739 SV = Builder.CreateLShr(SV, Context->getConstantInt(SV->getType(),
1740 -ShAmt), "tmp");
Duncan Sands0e7c46b2009-02-02 09:53:14 +00001741 Mask = Mask.lshr(-ShAmt);
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001742 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001743
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001744 // Mask out the bits we are about to insert from the old value, and or
1745 // in the new bits.
1746 if (SrcWidth != DestWidth) {
1747 assert(DestWidth > SrcWidth);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001748 Old = Builder.CreateAnd(Old, Context->getConstantInt(~Mask), "mask");
Chris Lattner65a65022009-02-03 19:41:50 +00001749 SV = Builder.CreateOr(Old, SV, "ins");
Chris Lattner800de312008-02-29 07:03:13 +00001750 }
1751 return SV;
1752}
1753
1754
Chris Lattner79b3bd32007-04-25 06:40:51 +00001755
1756/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1757/// some part of a constant global variable. This intentionally only accepts
1758/// constant expressions because we don't can't rewrite arbitrary instructions.
1759static bool PointsToConstantGlobal(Value *V) {
1760 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1761 return GV->isConstant();
1762 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1763 if (CE->getOpcode() == Instruction::BitCast ||
1764 CE->getOpcode() == Instruction::GetElementPtr)
1765 return PointsToConstantGlobal(CE->getOperand(0));
1766 return false;
1767}
1768
1769/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1770/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1771/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1772/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1773/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1774/// the alloca, and if the source pointer is a pointer to a constant global, we
1775/// can optimize this.
1776static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1777 bool isOffset) {
1778 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Chris Lattner6e733d32009-01-28 20:16:43 +00001779 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1780 // Ignore non-volatile loads, they are always ok.
1781 if (!LI->isVolatile())
1782 continue;
1783
Chris Lattner79b3bd32007-04-25 06:40:51 +00001784 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1785 // If uses of the bitcast are ok, we are ok.
1786 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1787 return false;
1788 continue;
1789 }
1790 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1791 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1792 // doesn't, it does.
1793 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1794 isOffset || !GEP->hasAllZeroIndices()))
1795 return false;
1796 continue;
1797 }
1798
1799 // If this is isn't our memcpy/memmove, reject it as something we can't
1800 // handle.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001801 if (!isa<MemTransferInst>(*UI))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001802 return false;
1803
1804 // If we already have seen a copy, reject the second one.
1805 if (TheCopy) return false;
1806
1807 // If the pointer has been offset from the start of the alloca, we can't
1808 // safely handle this.
1809 if (isOffset) return false;
1810
1811 // If the memintrinsic isn't using the alloca as the dest, reject it.
1812 if (UI.getOperandNo() != 1) return false;
1813
1814 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1815
1816 // If the source of the memcpy/move is not a constant global, reject it.
1817 if (!PointsToConstantGlobal(MI->getOperand(2)))
1818 return false;
1819
1820 // Otherwise, the transform is safe. Remember the copy instruction.
1821 TheCopy = MI;
1822 }
1823 return true;
1824}
1825
1826/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1827/// modified by a copy from a constant global. If we can prove this, we can
1828/// replace any uses of the alloca with uses of the global directly.
1829Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1830 Instruction *TheCopy = 0;
1831 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1832 return TheCopy;
1833 return 0;
1834}