blob: 884345d4a978bb469824993fc874f1798114d0a3 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
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
13// 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.
19//
20//===----------------------------------------------------------------------===//
21
22#define DEBUG_TYPE "scalarrepl"
23#include "llvm/Transforms/Scalar.h"
24#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
26#include "llvm/Function.h"
27#include "llvm/GlobalVariable.h"
28#include "llvm/Instructions.h"
29#include "llvm/IntrinsicInst.h"
Owen Andersonfa089ab2009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include "llvm/Pass.h"
32#include "llvm/Analysis/Dominators.h"
33#include "llvm/Target/TargetData.h"
34#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel83637b12009-02-10 07:00:59 +000035#include "llvm/Transforms/Utils/Local.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000036#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000037#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000038#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner32c19282009-02-03 19:41:50 +000039#include "llvm/Support/IRBuilder.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/Support/MathExtras.h"
Chris Lattner8a6411c2009-08-23 04:37:46 +000041#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000042#include "llvm/ADT/SmallVector.h"
43#include "llvm/ADT/Statistic.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044using namespace llvm;
45
46STATISTIC(NumReplaced, "Number of allocas broken up");
47STATISTIC(NumPromoted, "Number of allocas promoted");
48STATISTIC(NumConverted, "Number of aggregates converted to scalar");
49STATISTIC(NumGlobals, "Number of allocas copied from constant global");
50
51namespace {
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +000052 struct SROA : public FunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000054 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055 if (T == -1)
Chris Lattner6d7faec2007-08-02 21:33:36 +000056 SRThreshold = 128;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000057 else
58 SRThreshold = T;
59 }
60
61 bool runOnFunction(Function &F);
62
63 bool performScalarRepl(Function &F);
64 bool performPromotion(Function &F);
65
66 // getAnalysisUsage - This pass does not require any passes, but we know it
67 // will not alter the CFG, so say so.
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69 AU.addRequired<DominatorTree>();
70 AU.addRequired<DominanceFrontier>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000071 AU.setPreservesCFG();
72 }
73
74 private:
Chris Lattner3fd59362009-01-07 06:34:28 +000075 TargetData *TD;
76
Bob Wilson11aa9712009-12-18 20:14:40 +000077 /// DeadInsts - Keep track of instructions we have made dead, so that
78 /// we can remove them after we are done working.
79 SmallVector<Value*, 32> DeadInsts;
80
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
82 /// information about the uses. All these fields are initialized to false
83 /// and set to true when something is learned.
84 struct AllocaInfo {
85 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
86 bool isUnsafe : 1;
87
Devang Patel83637b12009-02-10 07:00:59 +000088 /// needsCleanup - This is set to true if there is some use of the alloca
89 /// that requires cleanup.
90 bool needsCleanup : 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000091
92 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
93 bool isMemCpySrc : 1;
94
95 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
96 bool isMemCpyDst : 1;
97
98 AllocaInfo()
Devang Patel83637b12009-02-10 07:00:59 +000099 : isUnsafe(false), needsCleanup(false),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100 isMemCpySrc(false), isMemCpyDst(false) {}
101 };
102
103 unsigned SRThreshold;
104
105 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
106
Victor Hernandezb1687302009-10-23 21:09:37 +0000107 int isSafeAllocaToScalarRepl(AllocaInst *AI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108
Bob Wilson11aa9712009-12-18 20:14:40 +0000109 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson37148982009-12-21 18:39:47 +0000110 AllocaInfo &Info);
Bob Wilson11aa9712009-12-18 20:14:40 +0000111 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
Bob Wilson37148982009-12-21 18:39:47 +0000112 AllocaInfo &Info);
113 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
114 const Type *MemOpType, bool isStore, AllocaInfo &Info);
Bob Wilson11aa9712009-12-18 20:14:40 +0000115 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsonf8934fc2009-12-19 06:53:17 +0000116 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
117 const Type *&IdxTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000118
Victor Hernandezb1687302009-10-23 21:09:37 +0000119 void DoScalarReplacement(AllocaInst *AI,
120 std::vector<AllocaInst*> &WorkList);
Bob Wilson11aa9712009-12-18 20:14:40 +0000121 void DeleteDeadInstructions();
Bob Wilson11aa9712009-12-18 20:14:40 +0000122 void CleanupAllocaUsers(Value *V);
Victor Hernandezb1687302009-10-23 21:09:37 +0000123 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocaInst *Base);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000124
Bob Wilson11aa9712009-12-18 20:14:40 +0000125 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
126 SmallVector<AllocaInst*, 32> &NewElts);
127 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
128 SmallVector<AllocaInst*, 32> &NewElts);
129 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
130 SmallVector<AllocaInst*, 32> &NewElts);
131 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandezb1687302009-10-23 21:09:37 +0000132 AllocaInst *AI,
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000133 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandezb1687302009-10-23 21:09:37 +0000134 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattner71c75342009-01-07 08:11:13 +0000135 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandezb1687302009-10-23 21:09:37 +0000136 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner70ffe572009-01-28 20:16:43 +0000137 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000138
Chris Lattnerf235a322009-02-03 01:30:09 +0000139 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
Chris Lattner38088d12009-02-03 18:15:05 +0000140 bool &SawVec, uint64_t Offset, unsigned AllocaSize);
Chris Lattner4b9c8b72009-01-31 02:28:54 +0000141 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Chris Lattnerf73a10e2009-02-03 21:01:03 +0000142 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
Chris Lattnerececb0c2009-02-03 19:45:44 +0000143 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattnercc0727c2009-02-03 19:30:11 +0000144 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Chris Lattner32c19282009-02-03 19:41:50 +0000145 uint64_t Offset, IRBuilder<> &Builder);
Victor Hernandezb1687302009-10-23 21:09:37 +0000146 static Instruction *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000147 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000148}
149
Dan Gohman089efff2008-05-13 00:00:25 +0000150char SROA::ID = 0;
151static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
152
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153// Public interface to the ScalarReplAggregates pass
154FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
155 return new SROA(Threshold);
156}
157
158
159bool SROA::runOnFunction(Function &F) {
Dan Gohman566d2d12009-08-19 18:22:18 +0000160 TD = getAnalysisIfAvailable<TargetData>();
161
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162 bool Changed = performPromotion(F);
Dan Gohman566d2d12009-08-19 18:22:18 +0000163
164 // FIXME: ScalarRepl currently depends on TargetData more than it
165 // theoretically needs to. It should be refactored in order to support
166 // target-independent IR. Until this is done, just skip the actual
167 // scalar-replacement portion of this pass.
168 if (!TD) return Changed;
169
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170 while (1) {
171 bool LocalChange = performScalarRepl(F);
172 if (!LocalChange) break; // No need to repromote if no scalarrepl
173 Changed = true;
174 LocalChange = performPromotion(F);
175 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
176 }
177
178 return Changed;
179}
180
181
182bool SROA::performPromotion(Function &F) {
183 std::vector<AllocaInst*> Allocas;
184 DominatorTree &DT = getAnalysis<DominatorTree>();
185 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
186
187 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
188
189 bool Changed = false;
190
191 while (1) {
192 Allocas.clear();
193
194 // Find allocas that are safe to promote, by looking at all instructions in
195 // the entry node
196 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
197 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
198 if (isAllocaPromotable(AI))
199 Allocas.push_back(AI);
200
201 if (Allocas.empty()) break;
202
Nick Lewycky1df6ea02009-11-23 03:50:44 +0000203 PromoteMemToReg(Allocas, DT, DF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204 NumPromoted += Allocas.size();
205 Changed = true;
206 }
207
208 return Changed;
209}
210
Chris Lattner0e99e692008-06-22 17:46:21 +0000211/// getNumSAElements - Return the number of elements in the specific struct or
212/// array.
213static uint64_t getNumSAElements(const Type *T) {
214 if (const StructType *ST = dyn_cast<StructType>(T))
215 return ST->getNumElements();
216 return cast<ArrayType>(T)->getNumElements();
217}
218
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219// performScalarRepl - This algorithm is a simple worklist driven algorithm,
220// which runs on all of the malloc/alloca instructions in the function, removing
221// them if they are only used by getelementptr instructions.
222//
223bool SROA::performScalarRepl(Function &F) {
Victor Hernandezb1687302009-10-23 21:09:37 +0000224 std::vector<AllocaInst*> WorkList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225
226 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
227 BasicBlock &BB = F.getEntryBlock();
228 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandezb1687302009-10-23 21:09:37 +0000229 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230 WorkList.push_back(A);
231
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 // Process the worklist
233 bool Changed = false;
234 while (!WorkList.empty()) {
Victor Hernandezb1687302009-10-23 21:09:37 +0000235 AllocaInst *AI = WorkList.back();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 WorkList.pop_back();
237
238 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
239 // with unused elements.
240 if (AI->use_empty()) {
241 AI->eraseFromParent();
242 continue;
243 }
Chris Lattnerf235a322009-02-03 01:30:09 +0000244
245 // If this alloca is impossible for us to promote, reject it early.
246 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
247 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000248
249 // Check to see if this allocation is only modified by a memcpy/memmove from
250 // a constant global. If this is the case, we can change all users to use
251 // the constant global instead. This is commonly produced by the CFE by
252 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
253 // is only subsequently read.
254 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
Nick Lewycky93a8e412009-09-15 07:08:25 +0000255 DEBUG(errs() << "Found alloca equal to global: " << *AI << '\n');
256 DEBUG(errs() << " memcpy = " << *TheCopy << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
Owen Anderson02b48c32009-07-29 18:55:55 +0000258 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259 TheCopy->eraseFromParent(); // Don't mutate the global.
260 AI->eraseFromParent();
261 ++NumGlobals;
262 Changed = true;
263 continue;
264 }
Chris Lattner05ebfd72009-02-02 20:44:45 +0000265
Chris Lattnerf235a322009-02-03 01:30:09 +0000266 // Check to see if we can perform the core SROA transformation. We cannot
267 // transform the allocation instruction if it is an array allocation
268 // (allocations OF arrays are ok though), and an allocation of a scalar
269 // value cannot be decomposed at all.
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000270 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling239da0a2009-03-03 12:12:58 +0000271
Nick Lewycky3db0ba72009-08-17 05:37:31 +0000272 // Do not promote [0 x %struct].
273 if (AllocaSize == 0) continue;
274
Bill Wendling239da0a2009-03-03 12:12:58 +0000275 // Do not promote any struct whose size is too big.
Bill Wendling8a1aae42009-03-03 19:18:49 +0000276 if (AllocaSize > SRThreshold) continue;
Nick Lewycky3db0ba72009-08-17 05:37:31 +0000277
Chris Lattnerf235a322009-02-03 01:30:09 +0000278 if ((isa<StructType>(AI->getAllocatedType()) ||
279 isa<ArrayType>(AI->getAllocatedType())) &&
Chris Lattnerf235a322009-02-03 01:30:09 +0000280 // Do not promote any struct into more than "32" separate vars.
Evan Cheng088b5b42009-03-06 00:56:43 +0000281 getNumSAElements(AI->getAllocatedType()) <= SRThreshold/4) {
Chris Lattnerf235a322009-02-03 01:30:09 +0000282 // Check that all of the users of the allocation are capable of being
283 // transformed.
284 switch (isSafeAllocaToScalarRepl(AI)) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000285 default: llvm_unreachable("Unexpected value!");
Chris Lattnerf235a322009-02-03 01:30:09 +0000286 case 0: // Not safe to scalar replace.
287 break;
288 case 1: // Safe, but requires cleanup/canonicalizations first
Devang Patel83637b12009-02-10 07:00:59 +0000289 CleanupAllocaUsers(AI);
Chris Lattnerf235a322009-02-03 01:30:09 +0000290 // FALL THROUGH.
291 case 3: // Safe to scalar replace.
292 DoScalarReplacement(AI, WorkList);
293 Changed = true;
294 continue;
295 }
296 }
Chris Lattner70ffe572009-01-28 20:16:43 +0000297
298 // If we can turn this aggregate value (potentially with casts) into a
299 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner4b9c8b72009-01-31 02:28:54 +0000300 // IsNotTrivial tracks whether this is something that mem2reg could have
301 // promoted itself. If so, we don't want to transform it needlessly. Note
302 // that we can't just check based on the type: the alloca may be of an i32
303 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner70ffe572009-01-28 20:16:43 +0000304 bool IsNotTrivial = false;
Chris Lattnerf235a322009-02-03 01:30:09 +0000305 const Type *VectorTy = 0;
Chris Lattner38088d12009-02-03 18:15:05 +0000306 bool HadAVector = false;
307 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
Chris Lattner748082f2009-03-04 19:22:30 +0000308 0, unsigned(AllocaSize)) && IsNotTrivial) {
Chris Lattnerf235a322009-02-03 01:30:09 +0000309 AllocaInst *NewAI;
Chris Lattner38088d12009-02-03 18:15:05 +0000310 // If we were able to find a vector type that can handle this with
311 // insert/extract elements, and if there was at least one use that had
312 // a vector type, promote this to a vector. We don't want to promote
313 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
314 // we just get a lot of insert/extracts. If at least one vector is
315 // involved, then we probably really do have a union of vector/array.
316 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
Nick Lewycky93a8e412009-09-15 07:08:25 +0000317 DEBUG(errs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
Chris Lattner8a6411c2009-08-23 04:37:46 +0000318 << *VectorTy << '\n');
Chris Lattner05ebfd72009-02-02 20:44:45 +0000319
Chris Lattnerf235a322009-02-03 01:30:09 +0000320 // Create and insert the vector alloca.
Owen Anderson140166d2009-07-15 23:53:25 +0000321 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
Chris Lattner05ebfd72009-02-02 20:44:45 +0000322 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattnerf235a322009-02-03 01:30:09 +0000323 } else {
Chris Lattner8a6411c2009-08-23 04:37:46 +0000324 DEBUG(errs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
Chris Lattnerf235a322009-02-03 01:30:09 +0000325
326 // Create and insert the integer alloca.
Owen Anderson35b47072009-08-13 21:58:54 +0000327 const Type *NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
Owen Anderson140166d2009-07-15 23:53:25 +0000328 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
Chris Lattnerf235a322009-02-03 01:30:09 +0000329 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner70ffe572009-01-28 20:16:43 +0000330 }
Chris Lattnerf235a322009-02-03 01:30:09 +0000331 NewAI->takeName(AI);
332 AI->eraseFromParent();
333 ++NumConverted;
334 Changed = true;
335 continue;
336 }
Chris Lattner70ffe572009-01-28 20:16:43 +0000337
Chris Lattnerf235a322009-02-03 01:30:09 +0000338 // Otherwise, couldn't process this alloca.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000339 }
340
341 return Changed;
342}
343
344/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
345/// predicate, do SROA now.
Victor Hernandezb1687302009-10-23 21:09:37 +0000346void SROA::DoScalarReplacement(AllocaInst *AI,
347 std::vector<AllocaInst*> &WorkList) {
Chris Lattner5957ef52009-09-15 05:14:57 +0000348 DEBUG(errs() << "Found inst to SROA: " << *AI << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349 SmallVector<AllocaInst*, 32> ElementAllocas;
350 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
351 ElementAllocas.reserve(ST->getNumContainedTypes());
352 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson140166d2009-07-15 23:53:25 +0000353 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000354 AI->getAlignment(),
Daniel Dunbar15676ac2009-07-30 17:37:43 +0000355 AI->getName() + "." + Twine(i), AI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000356 ElementAllocas.push_back(NA);
357 WorkList.push_back(NA); // Add to worklist for recursive processing
358 }
359 } else {
360 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
361 ElementAllocas.reserve(AT->getNumElements());
362 const Type *ElTy = AT->getElementType();
363 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson140166d2009-07-15 23:53:25 +0000364 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbar15676ac2009-07-30 17:37:43 +0000365 AI->getName() + "." + Twine(i), AI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000366 ElementAllocas.push_back(NA);
367 WorkList.push_back(NA); // Add to worklist for recursive processing
368 }
369 }
370
Bob Wilson11aa9712009-12-18 20:14:40 +0000371 // Now that we have created the new alloca instructions, rewrite all the
372 // uses of the old alloca.
373 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattneredf3f1e2009-12-14 05:11:02 +0000374
Bob Wilson11aa9712009-12-18 20:14:40 +0000375 // Now erase any instructions that were made dead while rewriting the alloca.
376 DeleteDeadInstructions();
Bob Wilson0230c882009-12-17 18:34:24 +0000377 AI->eraseFromParent();
Bob Wilson11aa9712009-12-18 20:14:40 +0000378
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000379 NumReplaced++;
380}
Chris Lattneredf3f1e2009-12-14 05:11:02 +0000381
Bob Wilson11aa9712009-12-18 20:14:40 +0000382/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
383/// recursively including all their operands that become trivially dead.
384void SROA::DeleteDeadInstructions() {
385 while (!DeadInsts.empty()) {
386 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattneredf3f1e2009-12-14 05:11:02 +0000387
Bob Wilson11aa9712009-12-18 20:14:40 +0000388 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
389 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
390 // Zero out the operand and see if it becomes trivially dead.
391 // (But, don't add allocas to the dead instruction list -- they are
392 // already on the worklist and will be deleted separately.)
393 *OI = 0;
394 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
395 DeadInsts.push_back(U);
Chris Lattneredf3f1e2009-12-14 05:11:02 +0000396 }
Bob Wilson11aa9712009-12-18 20:14:40 +0000397
398 I->eraseFromParent();
Chris Lattneredf3f1e2009-12-14 05:11:02 +0000399 }
Chris Lattneredf3f1e2009-12-14 05:11:02 +0000400}
Bob Wilson11aa9712009-12-18 20:14:40 +0000401
Bob Wilson11aa9712009-12-18 20:14:40 +0000402/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
403/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson37148982009-12-21 18:39:47 +0000404/// the Info parameter. Offset indicates the position within AI that is
405/// referenced by this instruction.
Bob Wilson11aa9712009-12-18 20:14:40 +0000406void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson37148982009-12-21 18:39:47 +0000407 AllocaInfo &Info) {
Bob Wilson11aa9712009-12-18 20:14:40 +0000408 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
409 Instruction *User = cast<Instruction>(*UI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000410
Bob Wilson11aa9712009-12-18 20:14:40 +0000411 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Bob Wilson37148982009-12-21 18:39:47 +0000412 isSafeForScalarRepl(BC, AI, Offset, Info);
Bob Wilson11aa9712009-12-18 20:14:40 +0000413 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilson11aa9712009-12-18 20:14:40 +0000414 uint64_t GEPOffset = Offset;
Bob Wilson37148982009-12-21 18:39:47 +0000415 isSafeGEP(GEPI, AI, GEPOffset, Info);
Bob Wilson11aa9712009-12-18 20:14:40 +0000416 if (!Info.isUnsafe)
Bob Wilson37148982009-12-21 18:39:47 +0000417 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
Bob Wilson11aa9712009-12-18 20:14:40 +0000418 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
419 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
420 if (Length)
Bob Wilson37148982009-12-21 18:39:47 +0000421 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
Bob Wilson11aa9712009-12-18 20:14:40 +0000422 UI.getOperandNo() == 1, Info);
423 else
424 MarkUnsafe(Info);
425 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
426 if (!LI->isVolatile()) {
427 const Type *LIType = LI->getType();
Bob Wilson37148982009-12-21 18:39:47 +0000428 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
Bob Wilson11aa9712009-12-18 20:14:40 +0000429 LIType, false, Info);
430 } else
431 MarkUnsafe(Info);
432 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
433 // Store is ok if storing INTO the pointer, not storing the pointer
434 if (!SI->isVolatile() && SI->getOperand(0) != I) {
435 const Type *SIType = SI->getOperand(0)->getType();
Bob Wilson37148982009-12-21 18:39:47 +0000436 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
Bob Wilson11aa9712009-12-18 20:14:40 +0000437 SIType, true, Info);
438 } else
439 MarkUnsafe(Info);
440 } else if (isa<DbgInfoIntrinsic>(UI)) {
441 // If one user is DbgInfoIntrinsic then check if all users are
442 // DbgInfoIntrinsics.
443 if (OnlyUsedByDbgInfoIntrinsics(I)) {
444 Info.needsCleanup = true;
445 return;
446 }
447 MarkUnsafe(Info);
448 } else {
449 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
450 MarkUnsafe(Info);
451 }
452 if (Info.isUnsafe) return;
Bob Wilson0230c882009-12-17 18:34:24 +0000453 }
Bob Wilson11aa9712009-12-18 20:14:40 +0000454}
Bob Wilson0230c882009-12-17 18:34:24 +0000455
Bob Wilson11aa9712009-12-18 20:14:40 +0000456/// isSafeGEP - Check if a GEP instruction can be handled for scalar
457/// replacement. It is safe when all the indices are constant, in-bounds
458/// references, and when the resulting offset corresponds to an element within
459/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson37148982009-12-21 18:39:47 +0000460/// return, Offset is adjusted as specified by the GEP indices.
Bob Wilson11aa9712009-12-18 20:14:40 +0000461void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
Bob Wilson37148982009-12-21 18:39:47 +0000462 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilson11aa9712009-12-18 20:14:40 +0000463 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
464 if (GEPIt == E)
465 return;
Bob Wilson0230c882009-12-17 18:34:24 +0000466
Chris Lattnerd324da02008-08-23 05:21:06 +0000467 // Walk through the GEP type indices, checking the types that this indexes
468 // into.
Bob Wilson11aa9712009-12-18 20:14:40 +0000469 for (; GEPIt != E; ++GEPIt) {
Chris Lattnerd324da02008-08-23 05:21:06 +0000470 // Ignore struct elements, no extra checking needed for these.
Bob Wilson11aa9712009-12-18 20:14:40 +0000471 if (isa<StructType>(*GEPIt))
Chris Lattnerd324da02008-08-23 05:21:06 +0000472 continue;
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000473
Bob Wilson11aa9712009-12-18 20:14:40 +0000474 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
475 if (!IdxVal)
476 return MarkUnsafe(Info);
Chris Lattnerd324da02008-08-23 05:21:06 +0000477 }
Bob Wilson11aa9712009-12-18 20:14:40 +0000478
Bob Wilsonc0245212009-12-22 06:57:14 +0000479 // Compute the offset due to this GEP and check if the alloca has a
480 // component element at that offset.
Bob Wilson37148982009-12-21 18:39:47 +0000481 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
482 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
483 &Indices[0], Indices.size());
Bob Wilson11aa9712009-12-18 20:14:40 +0000484 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
485 MarkUnsafe(Info);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000486}
487
Bob Wilson11aa9712009-12-18 20:14:40 +0000488/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
489/// alloca or has an offset and size that corresponds to a component element
490/// within it. The offset checked here may have been formed from a GEP with a
491/// pointer bitcasted to a different type.
Bob Wilson37148982009-12-21 18:39:47 +0000492void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
Bob Wilson11aa9712009-12-18 20:14:40 +0000493 const Type *MemOpType, bool isStore,
494 AllocaInfo &Info) {
495 // Check if this is a load/store of the entire alloca.
Bob Wilson37148982009-12-21 18:39:47 +0000496 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilson11aa9712009-12-18 20:14:40 +0000497 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
498 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
499 // (which are essentially the same as the MemIntrinsics, especially with
500 // regard to copying padding between elements), or references using the
501 // aggregate type of the alloca.
502 if (!MemOpType || isa<IntegerType>(MemOpType) || UsesAggregateType) {
503 if (!UsesAggregateType) {
504 if (isStore)
505 Info.isMemCpyDst = true;
506 else
507 Info.isMemCpySrc = true;
508 }
509 return;
510 }
511 }
512 // Check if the offset/size correspond to a component within the alloca type.
513 const Type *T = AI->getAllocatedType();
Bob Wilson37148982009-12-21 18:39:47 +0000514 if (TypeHasComponent(T, Offset, MemSize))
Bob Wilson11aa9712009-12-18 20:14:40 +0000515 return;
516
517 return MarkUnsafe(Info);
518}
519
520/// TypeHasComponent - Return true if T has a component type with the
521/// specified offset and size. If Size is zero, do not check the size.
522bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
523 const Type *EltTy;
524 uint64_t EltSize;
525 if (const StructType *ST = dyn_cast<StructType>(T)) {
526 const StructLayout *Layout = TD->getStructLayout(ST);
527 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
528 EltTy = ST->getContainedType(EltIdx);
529 EltSize = TD->getTypeAllocSize(EltTy);
530 Offset -= Layout->getElementOffset(EltIdx);
531 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
532 EltTy = AT->getElementType();
533 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonc0245212009-12-22 06:57:14 +0000534 if (Offset >= AT->getNumElements() * EltSize)
535 return false;
Bob Wilson11aa9712009-12-18 20:14:40 +0000536 Offset %= EltSize;
537 } else {
538 return false;
539 }
540 if (Offset == 0 && (Size == 0 || EltSize == Size))
541 return true;
542 // Check if the component spans multiple elements.
543 if (Offset + Size > EltSize)
544 return false;
545 return TypeHasComponent(EltTy, Offset, Size);
546}
547
548/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
549/// the instruction I, which references it, to use the separate elements.
550/// Offset indicates the position within AI that is referenced by this
551/// instruction.
552void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
553 SmallVector<AllocaInst*, 32> &NewElts) {
554 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
555 Instruction *User = cast<Instruction>(*UI);
556
557 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
558 RewriteBitCast(BC, AI, Offset, NewElts);
559 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
560 RewriteGEP(GEPI, AI, Offset, NewElts);
561 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
562 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
563 uint64_t MemSize = Length->getZExtValue();
564 if (Offset == 0 &&
565 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
566 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsonf8934fc2009-12-19 06:53:17 +0000567 // Otherwise the intrinsic can only touch a single element and the
568 // address operand will be updated, so nothing else needs to be done.
Bob Wilson11aa9712009-12-18 20:14:40 +0000569 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
570 const Type *LIType = LI->getType();
571 if (LIType == AI->getAllocatedType()) {
572 // Replace:
573 // %res = load { i32, i32 }* %alloc
574 // with:
575 // %load.0 = load i32* %alloc.0
576 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
577 // %load.1 = load i32* %alloc.1
578 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
579 // (Also works for arrays instead of structs)
580 Value *Insert = UndefValue::get(LIType);
581 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
582 Value *Load = new LoadInst(NewElts[i], "load", LI);
583 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
584 }
585 LI->replaceAllUsesWith(Insert);
586 DeadInsts.push_back(LI);
587 } else if (isa<IntegerType>(LIType) &&
588 TD->getTypeAllocSize(LIType) ==
589 TD->getTypeAllocSize(AI->getAllocatedType())) {
590 // If this is a load of the entire alloca to an integer, rewrite it.
591 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
592 }
593 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
594 Value *Val = SI->getOperand(0);
595 const Type *SIType = Val->getType();
596 if (SIType == AI->getAllocatedType()) {
597 // Replace:
598 // store { i32, i32 } %val, { i32, i32 }* %alloc
599 // with:
600 // %val.0 = extractvalue { i32, i32 } %val, 0
601 // store i32 %val.0, i32* %alloc.0
602 // %val.1 = extractvalue { i32, i32 } %val, 1
603 // store i32 %val.1, i32* %alloc.1
604 // (Also works for arrays instead of structs)
605 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
606 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
607 new StoreInst(Extract, NewElts[i], SI);
608 }
609 DeadInsts.push_back(SI);
610 } else if (isa<IntegerType>(SIType) &&
611 TD->getTypeAllocSize(SIType) ==
612 TD->getTypeAllocSize(AI->getAllocatedType())) {
613 // If this is a store of the entire alloca from an integer, rewrite it.
614 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
615 }
616 }
Bob Wilson0230c882009-12-17 18:34:24 +0000617 }
618}
619
Bob Wilson11aa9712009-12-18 20:14:40 +0000620/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
621/// and recursively continue updating all of its uses.
622void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
623 SmallVector<AllocaInst*, 32> &NewElts) {
624 RewriteForScalarRepl(BC, AI, Offset, NewElts);
625 if (BC->getOperand(0) != AI)
626 return;
Bob Wilson0230c882009-12-17 18:34:24 +0000627
Bob Wilson11aa9712009-12-18 20:14:40 +0000628 // The bitcast references the original alloca. Replace its uses with
629 // references to the first new element alloca.
630 Instruction *Val = NewElts[0];
631 if (Val->getType() != BC->getDestTy()) {
632 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
633 Val->takeName(BC);
Daniel Dunbar53dee552009-12-16 10:56:17 +0000634 }
Bob Wilson11aa9712009-12-18 20:14:40 +0000635 BC->replaceAllUsesWith(Val);
636 DeadInsts.push_back(BC);
Daniel Dunbar53dee552009-12-16 10:56:17 +0000637}
638
Bob Wilson11aa9712009-12-18 20:14:40 +0000639/// FindElementAndOffset - Return the index of the element containing Offset
640/// within the specified type, which must be either a struct or an array.
641/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsonf8934fc2009-12-19 06:53:17 +0000642/// element. IdxTy is set to the type of the index result to be used in a
643/// GEP instruction.
644uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
645 const Type *&IdxTy) {
646 uint64_t Idx = 0;
Bob Wilson11aa9712009-12-18 20:14:40 +0000647 if (const StructType *ST = dyn_cast<StructType>(T)) {
648 const StructLayout *Layout = TD->getStructLayout(ST);
649 Idx = Layout->getElementContainingOffset(Offset);
650 T = ST->getContainedType(Idx);
651 Offset -= Layout->getElementOffset(Idx);
Bob Wilsonf8934fc2009-12-19 06:53:17 +0000652 IdxTy = Type::getInt32Ty(T->getContext());
653 return Idx;
Chris Lattneredf3f1e2009-12-14 05:11:02 +0000654 }
Bob Wilsonf8934fc2009-12-19 06:53:17 +0000655 const ArrayType *AT = cast<ArrayType>(T);
656 T = AT->getElementType();
657 uint64_t EltSize = TD->getTypeAllocSize(T);
658 Idx = Offset / EltSize;
659 Offset -= Idx * EltSize;
660 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilson11aa9712009-12-18 20:14:40 +0000661 return Idx;
662}
663
664/// RewriteGEP - Check if this GEP instruction moves the pointer across
665/// elements of the alloca that are being split apart, and if so, rewrite
666/// the GEP to be relative to the new element.
667void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
668 SmallVector<AllocaInst*, 32> &NewElts) {
669 uint64_t OldOffset = Offset;
670 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
671 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
672 &Indices[0], Indices.size());
673
674 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
675
676 const Type *T = AI->getAllocatedType();
Bob Wilsonf8934fc2009-12-19 06:53:17 +0000677 const Type *IdxTy;
678 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilson11aa9712009-12-18 20:14:40 +0000679 if (GEPI->getOperand(0) == AI)
Bob Wilsonf8934fc2009-12-19 06:53:17 +0000680 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilson11aa9712009-12-18 20:14:40 +0000681
682 T = AI->getAllocatedType();
683 uint64_t EltOffset = Offset;
Bob Wilsonf8934fc2009-12-19 06:53:17 +0000684 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilson11aa9712009-12-18 20:14:40 +0000685
686 // If this GEP does not move the pointer across elements of the alloca
687 // being split, then it does not needs to be rewritten.
688 if (Idx == OldIdx)
689 return;
690
691 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
692 SmallVector<Value*, 8> NewArgs;
693 NewArgs.push_back(Constant::getNullValue(i32Ty));
694 while (EltOffset != 0) {
Bob Wilsonf8934fc2009-12-19 06:53:17 +0000695 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
696 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilson11aa9712009-12-18 20:14:40 +0000697 }
698 Instruction *Val = NewElts[Idx];
699 if (NewArgs.size() > 1) {
700 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
701 NewArgs.end(), "", GEPI);
702 Val->takeName(GEPI);
703 }
704 if (Val->getType() != GEPI->getType())
705 Val = new BitCastInst(Val, GEPI->getType(), Val->getNameStr(), GEPI);
706 GEPI->replaceAllUsesWith(Val);
707 DeadInsts.push_back(GEPI);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000708}
709
710/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
711/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilson11aa9712009-12-18 20:14:40 +0000712void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandezb1687302009-10-23 21:09:37 +0000713 AllocaInst *AI,
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000714 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000715 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner454585f2009-03-04 19:23:25 +0000716 // appropriate type. The "Other" pointer is the pointer that goes to memory
717 // that doesn't have anything to do with the alloca that we are promoting. For
718 // memset, this Value* stays null.
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000719 Value *OtherPtr = 0;
Owen Anderson175b6542009-07-22 00:24:57 +0000720 LLVMContext &Context = MI->getContext();
Chris Lattner3947da72009-03-08 03:59:00 +0000721 unsigned MemAlignment = MI->getAlignment();
Chris Lattnera86628a2009-03-08 03:37:16 +0000722 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilson11aa9712009-12-18 20:14:40 +0000723 if (Inst == MTI->getRawDest())
Chris Lattnera86628a2009-03-08 03:37:16 +0000724 OtherPtr = MTI->getRawSource();
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000725 else {
Bob Wilson11aa9712009-12-18 20:14:40 +0000726 assert(Inst == MTI->getRawSource());
Chris Lattnera86628a2009-03-08 03:37:16 +0000727 OtherPtr = MTI->getRawDest();
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000728 }
729 }
Bob Wilsonbb4b0d52009-12-08 18:22:03 +0000730
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000731 // If there is an other pointer, we want to convert it to the same pointer
732 // type as AI has, so we can GEP through it safely.
733 if (OtherPtr) {
Bob Wilson11aa9712009-12-18 20:14:40 +0000734
735 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
736 // optimization, but it's also required to detect the corner case where
737 // both pointer operands are referencing the same memory, and where
738 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
739 // function is only called for mem intrinsics that access the whole
740 // aggregate, so non-zero GEPs are not an issue here.)
741 while (1) {
742 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr)) {
743 OtherPtr = BC->getOperand(0);
744 continue;
745 }
746 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr)) {
747 // All zero GEPs are effectively bitcasts.
748 if (GEP->hasAllZeroIndices()) {
749 OtherPtr = GEP->getOperand(0);
750 continue;
751 }
752 }
753 break;
754 }
755 // If OtherPtr has already been rewritten, this intrinsic will be dead.
756 if (OtherPtr == NewElts[0])
757 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000758
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000759 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
760 if (BCE->getOpcode() == Instruction::BitCast)
761 OtherPtr = BCE->getOperand(0);
762
763 // If the pointer is not the right type, insert a bitcast to the right
764 // type.
765 if (OtherPtr->getType() != AI->getType())
766 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
767 MI);
768 }
769
770 // Process each element of the aggregate.
771 Value *TheFn = MI->getOperand(0);
772 const Type *BytePtrTy = MI->getRawDest()->getType();
Bob Wilson11aa9712009-12-18 20:14:40 +0000773 bool SROADest = MI->getRawDest() == Inst;
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000774
Owen Anderson35b47072009-08-13 21:58:54 +0000775 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000776
777 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
778 // If this is a memcpy/memmove, emit a GEP of the other element address.
779 Value *OtherElt = 0;
Chris Lattnerf52053c2009-03-04 19:20:50 +0000780 unsigned OtherEltAlign = MemAlignment;
781
Bob Wilson11aa9712009-12-18 20:14:40 +0000782 if (OtherPtr == AI) {
783 OtherElt = NewElts[i];
784 OtherEltAlign = 0;
785 } else if (OtherPtr) {
Owen Anderson35b47072009-08-13 21:58:54 +0000786 Value *Idx[2] = { Zero,
787 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilson11aa9712009-12-18 20:14:40 +0000788 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Daniel Dunbar15676ac2009-07-30 17:37:43 +0000789 OtherPtr->getNameStr()+"."+Twine(i),
Bob Wilson11aa9712009-12-18 20:14:40 +0000790 MI);
Chris Lattnerf52053c2009-03-04 19:20:50 +0000791 uint64_t EltOffset;
792 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
793 if (const StructType *ST =
794 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
795 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
796 } else {
797 const Type *EltTy =
798 cast<SequentialType>(OtherPtr->getType())->getElementType();
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000799 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattnerf52053c2009-03-04 19:20:50 +0000800 }
801
802 // The alignment of the other pointer is the guaranteed alignment of the
803 // element, which is affected by both the known alignment of the whole
804 // mem intrinsic and the alignment of the element. If the alignment of
805 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
806 // known alignment is just 4 bytes.
807 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000808 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000809
810 Value *EltPtr = NewElts[i];
Chris Lattnerf52053c2009-03-04 19:20:50 +0000811 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000812
813 // If we got down to a scalar, insert a load or store as appropriate.
814 if (EltTy->isSingleValueType()) {
Chris Lattnera86628a2009-03-08 03:37:16 +0000815 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf52053c2009-03-04 19:20:50 +0000816 if (SROADest) {
817 // From Other to Alloca.
818 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
819 new StoreInst(Elt, EltPtr, MI);
820 } else {
821 // From Alloca to Other.
822 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
823 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
824 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000825 continue;
826 }
827 assert(isa<MemSetInst>(MI));
828
829 // If the stored element is zero (common case), just store a null
830 // constant.
831 Constant *StoreVal;
832 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
833 if (CI->isZero()) {
Owen Andersonaac28372009-07-31 20:28:14 +0000834 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000835 } else {
836 // If EltTy is a vector type, get the element type.
Dan Gohman33e50dc2009-06-16 00:20:26 +0000837 const Type *ValTy = EltTy->getScalarType();
838
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000839 // Construct an integer with the right value.
840 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
841 APInt OneVal(EltSize, CI->getZExtValue());
842 APInt TotalVal(OneVal);
843 // Set each byte.
844 for (unsigned i = 0; 8*i < EltSize; ++i) {
845 TotalVal = TotalVal.shl(8);
846 TotalVal |= OneVal;
847 }
848
849 // Convert the integer value to the appropriate type.
Owen Andersoneacb44d2009-07-24 23:12:02 +0000850 StoreVal = ConstantInt::get(Context, TotalVal);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000851 if (isa<PointerType>(ValTy))
Owen Anderson02b48c32009-07-29 18:55:55 +0000852 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000853 else if (ValTy->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000854 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000855 assert(StoreVal->getType() == ValTy && "Type mismatch!");
856
857 // If the requested value was a vector constant, create it.
858 if (EltTy != ValTy) {
859 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
860 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Anderson2f422e02009-07-28 21:19:26 +0000861 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000862 }
863 }
864 new StoreInst(StoreVal, EltPtr, MI);
865 continue;
866 }
867 // Otherwise, if we're storing a byte variable, use a memset call for
868 // this element.
869 }
870
871 // Cast the element pointer to BytePtrTy.
872 if (EltPtr->getType() != BytePtrTy)
873 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
874
875 // Cast the other pointer (if we have one) to BytePtrTy.
876 if (OtherElt && OtherElt->getType() != BytePtrTy)
877 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
878 MI);
879
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000880 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000881
882 // Finally, insert the meminst for this element.
Chris Lattnera86628a2009-03-08 03:37:16 +0000883 if (isa<MemTransferInst>(MI)) {
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000884 Value *Ops[] = {
885 SROADest ? EltPtr : OtherElt, // Dest ptr
886 SROADest ? OtherElt : EltPtr, // Src ptr
Owen Andersoneacb44d2009-07-24 23:12:02 +0000887 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Owen Anderson35b47072009-08-13 21:58:54 +0000888 // Align
889 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign)
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000890 };
891 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
892 } else {
893 assert(isa<MemSetInst>(MI));
894 Value *Ops[] = {
895 EltPtr, MI->getOperand(2), // Dest, Value,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000896 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000897 Zero // Align
898 };
899 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
900 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000901 }
Bob Wilson11aa9712009-12-18 20:14:40 +0000902 DeadInsts.push_back(MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000903}
Chris Lattner71c75342009-01-07 08:11:13 +0000904
Bob Wilson17bd7fe2009-12-04 21:57:37 +0000905/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattner71c75342009-01-07 08:11:13 +0000906/// overwrites the entire allocation. Extract out the pieces of the stored
907/// integer and store them individually.
Victor Hernandezb1687302009-10-23 21:09:37 +0000908void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattner71c75342009-01-07 08:11:13 +0000909 SmallVector<AllocaInst*, 32> &NewElts){
910 // Extract each element out of the integer according to its structure offset
911 // and store the element value to the individual alloca.
912 Value *SrcVal = SI->getOperand(0);
Bob Wilson11aa9712009-12-18 20:14:40 +0000913 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000914 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000915
Eli Friedman18a61432009-06-01 09:14:32 +0000916 // Handle tail padding by extending the operand
917 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa089ab2009-07-03 19:42:02 +0000918 SrcVal = new ZExtInst(SrcVal,
Owen Anderson35b47072009-08-13 21:58:54 +0000919 IntegerType::get(SI->getContext(), AllocaSizeBits),
920 "", SI);
Chris Lattner71c75342009-01-07 08:11:13 +0000921
Nick Lewycky93a8e412009-09-15 07:08:25 +0000922 DEBUG(errs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
923 << '\n');
Chris Lattner71c75342009-01-07 08:11:13 +0000924
925 // There are two forms here: AI could be an array or struct. Both cases
926 // have different ways to compute the element offset.
927 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
928 const StructLayout *Layout = TD->getStructLayout(EltSTy);
929
930 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
931 // Get the number of bits to shift SrcVal to get the value.
932 const Type *FieldTy = EltSTy->getElementType(i);
933 uint64_t Shift = Layout->getElementOffsetInBits(i);
934
935 if (TD->isBigEndian())
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000936 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattner71c75342009-01-07 08:11:13 +0000937
938 Value *EltVal = SrcVal;
939 if (Shift) {
Owen Andersoneacb44d2009-07-24 23:12:02 +0000940 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner71c75342009-01-07 08:11:13 +0000941 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
942 "sroa.store.elt", SI);
943 }
944
945 // Truncate down to an integer of the right size.
946 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattnerf7a2f092009-01-09 18:18:43 +0000947
948 // Ignore zero sized fields like {}, they obviously contain no data.
949 if (FieldSizeBits == 0) continue;
950
Chris Lattner71c75342009-01-07 08:11:13 +0000951 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa089ab2009-07-03 19:42:02 +0000952 EltVal = new TruncInst(EltVal,
Owen Anderson35b47072009-08-13 21:58:54 +0000953 IntegerType::get(SI->getContext(), FieldSizeBits),
954 "", SI);
Chris Lattner71c75342009-01-07 08:11:13 +0000955 Value *DestField = NewElts[i];
956 if (EltVal->getType() == FieldTy) {
957 // Storing to an integer field of this size, just do it.
958 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
959 // Bitcast to the right element type (for fp/vector values).
960 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
961 } else {
962 // Otherwise, bitcast the dest pointer (for aggregates).
963 DestField = new BitCastInst(DestField,
Owen Anderson6b6e2d92009-07-29 22:17:13 +0000964 PointerType::getUnqual(EltVal->getType()),
Chris Lattner71c75342009-01-07 08:11:13 +0000965 "", SI);
966 }
967 new StoreInst(EltVal, DestField, SI);
968 }
969
970 } else {
971 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
972 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000973 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner71c75342009-01-07 08:11:13 +0000974 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
975
976 uint64_t Shift;
977
978 if (TD->isBigEndian())
979 Shift = AllocaSizeBits-ElementOffset;
980 else
981 Shift = 0;
982
983 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattnerf7a2f092009-01-09 18:18:43 +0000984 // Ignore zero sized fields like {}, they obviously contain no data.
985 if (ElementSizeBits == 0) continue;
Chris Lattner71c75342009-01-07 08:11:13 +0000986
987 Value *EltVal = SrcVal;
988 if (Shift) {
Owen Andersoneacb44d2009-07-24 23:12:02 +0000989 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner71c75342009-01-07 08:11:13 +0000990 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
991 "sroa.store.elt", SI);
992 }
993
994 // Truncate down to an integer of the right size.
995 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa089ab2009-07-03 19:42:02 +0000996 EltVal = new TruncInst(EltVal,
Owen Anderson35b47072009-08-13 21:58:54 +0000997 IntegerType::get(SI->getContext(),
998 ElementSizeBits),"",SI);
Chris Lattner71c75342009-01-07 08:11:13 +0000999 Value *DestField = NewElts[i];
1000 if (EltVal->getType() == ArrayEltTy) {
1001 // Storing to an integer field of this size, just do it.
1002 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
1003 // Bitcast to the right element type (for fp/vector values).
1004 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1005 } else {
1006 // Otherwise, bitcast the dest pointer (for aggregates).
1007 DestField = new BitCastInst(DestField,
Owen Anderson6b6e2d92009-07-29 22:17:13 +00001008 PointerType::getUnqual(EltVal->getType()),
Chris Lattner71c75342009-01-07 08:11:13 +00001009 "", SI);
1010 }
1011 new StoreInst(EltVal, DestField, SI);
1012
1013 if (TD->isBigEndian())
1014 Shift -= ElementOffset;
1015 else
1016 Shift += ElementOffset;
1017 }
1018 }
1019
Bob Wilson11aa9712009-12-18 20:14:40 +00001020 DeadInsts.push_back(SI);
Chris Lattner71c75342009-01-07 08:11:13 +00001021}
1022
Bob Wilson17bd7fe2009-12-04 21:57:37 +00001023/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner28401db2009-01-08 05:42:05 +00001024/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandezb1687302009-10-23 21:09:37 +00001025void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner28401db2009-01-08 05:42:05 +00001026 SmallVector<AllocaInst*, 32> &NewElts) {
1027 // Extract each element out of the NewElts according to its structure offset
1028 // and form the result value.
Bob Wilson11aa9712009-12-18 20:14:40 +00001029 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sandsec4f97d2009-05-09 07:06:46 +00001030 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner28401db2009-01-08 05:42:05 +00001031
Nick Lewycky93a8e412009-09-15 07:08:25 +00001032 DEBUG(errs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
1033 << '\n');
Chris Lattner28401db2009-01-08 05:42:05 +00001034
1035 // There are two forms here: AI could be an array or struct. Both cases
1036 // have different ways to compute the element offset.
1037 const StructLayout *Layout = 0;
1038 uint64_t ArrayEltBitOffset = 0;
1039 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1040 Layout = TD->getStructLayout(EltSTy);
1041 } else {
1042 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sandsec4f97d2009-05-09 07:06:46 +00001043 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner28401db2009-01-08 05:42:05 +00001044 }
Owen Anderson175b6542009-07-22 00:24:57 +00001045
Owen Anderson175b6542009-07-22 00:24:57 +00001046 Value *ResultVal =
Owen Anderson35b47072009-08-13 21:58:54 +00001047 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Chris Lattner28401db2009-01-08 05:42:05 +00001048
1049 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1050 // Load the value from the alloca. If the NewElt is an aggregate, cast
1051 // the pointer to an integer of the same size before doing the load.
1052 Value *SrcField = NewElts[i];
1053 const Type *FieldTy =
1054 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattnerf7a2f092009-01-09 18:18:43 +00001055 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1056
1057 // Ignore zero sized fields like {}, they obviously contain no data.
1058 if (FieldSizeBits == 0) continue;
1059
Owen Anderson35b47072009-08-13 21:58:54 +00001060 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1061 FieldSizeBits);
Chris Lattner28401db2009-01-08 05:42:05 +00001062 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1063 !isa<VectorType>(FieldTy))
Owen Andersonfa089ab2009-07-03 19:42:02 +00001064 SrcField = new BitCastInst(SrcField,
Owen Anderson6b6e2d92009-07-29 22:17:13 +00001065 PointerType::getUnqual(FieldIntTy),
Chris Lattner28401db2009-01-08 05:42:05 +00001066 "", LI);
1067 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1068
1069 // If SrcField is a fp or vector of the right size but that isn't an
1070 // integer type, bitcast to an integer so we can shift it.
1071 if (SrcField->getType() != FieldIntTy)
1072 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1073
1074 // Zero extend the field to be the same size as the final alloca so that
1075 // we can shift and insert it.
1076 if (SrcField->getType() != ResultVal->getType())
1077 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1078
1079 // Determine the number of bits to shift SrcField.
1080 uint64_t Shift;
1081 if (Layout) // Struct case.
1082 Shift = Layout->getElementOffsetInBits(i);
1083 else // Array case.
1084 Shift = i*ArrayEltBitOffset;
1085
1086 if (TD->isBigEndian())
1087 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1088
1089 if (Shift) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00001090 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner28401db2009-01-08 05:42:05 +00001091 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1092 }
1093
1094 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1095 }
Eli Friedman18a61432009-06-01 09:14:32 +00001096
1097 // Handle tail padding by truncating the result
1098 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1099 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1100
Chris Lattner28401db2009-01-08 05:42:05 +00001101 LI->replaceAllUsesWith(ResultVal);
Bob Wilson11aa9712009-12-18 20:14:40 +00001102 DeadInsts.push_back(LI);
Chris Lattner28401db2009-01-08 05:42:05 +00001103}
1104
Duncan Sandsae5fd622007-11-04 14:43:57 +00001105/// HasPadding - Return true if the specified type has any structure or
1106/// alignment padding, false otherwise.
Duncan Sands4afc5752008-06-04 08:21:45 +00001107static bool HasPadding(const Type *Ty, const TargetData &TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1109 const StructLayout *SL = TD.getStructLayout(STy);
1110 unsigned PrevFieldBitOffset = 0;
1111 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sandsae5fd622007-11-04 14:43:57 +00001112 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1113
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001114 // Padding in sub-elements?
Duncan Sands4afc5752008-06-04 08:21:45 +00001115 if (HasPadding(STy->getElementType(i), TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001116 return true;
Duncan Sandsae5fd622007-11-04 14:43:57 +00001117
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001118 // Check to see if there is any padding between this element and the
1119 // previous one.
1120 if (i) {
Duncan Sandsae5fd622007-11-04 14:43:57 +00001121 unsigned PrevFieldEnd =
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001122 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1123 if (PrevFieldEnd < FieldBitOffset)
1124 return true;
1125 }
Duncan Sandsae5fd622007-11-04 14:43:57 +00001126
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001127 PrevFieldBitOffset = FieldBitOffset;
1128 }
Duncan Sandsae5fd622007-11-04 14:43:57 +00001129
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001130 // Check for tail padding.
1131 if (unsigned EltCount = STy->getNumElements()) {
1132 unsigned PrevFieldEnd = PrevFieldBitOffset +
1133 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sandsae5fd622007-11-04 14:43:57 +00001134 if (PrevFieldEnd < SL->getSizeInBits())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 return true;
1136 }
1137
1138 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sands4afc5752008-06-04 08:21:45 +00001139 return HasPadding(ATy->getElementType(), TD);
Duncan Sandsae5fd622007-11-04 14:43:57 +00001140 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sands4afc5752008-06-04 08:21:45 +00001141 return HasPadding(VTy->getElementType(), TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001142 }
Duncan Sandsec4f97d2009-05-09 07:06:46 +00001143 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001144}
1145
1146/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1147/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1148/// or 1 if safe after canonicalization has been performed.
Victor Hernandezb1687302009-10-23 21:09:37 +00001149int SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001150 // Loop over the use list of the alloca. We can only transform it if all of
1151 // the users are safe to transform.
1152 AllocaInfo Info;
1153
Bob Wilson37148982009-12-21 18:39:47 +00001154 isSafeForScalarRepl(AI, AI, 0, Info);
Bob Wilson11aa9712009-12-18 20:14:40 +00001155 if (Info.isUnsafe) {
1156 DEBUG(errs() << "Cannot transform: " << *AI << '\n');
1157 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158 }
1159
1160 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1161 // source and destination, we have to be careful. In particular, the memcpy
1162 // could be moving around elements that live in structure padding of the LLVM
1163 // types, but may actually be used. In these cases, we refuse to promote the
1164 // struct.
1165 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilson11aa9712009-12-18 20:14:40 +00001166 HasPadding(AI->getAllocatedType(), *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001167 return 0;
Duncan Sandsae5fd622007-11-04 14:43:57 +00001168
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001169 // If we require cleanup, return 1, otherwise return 3.
Devang Patel83637b12009-02-10 07:00:59 +00001170 return Info.needsCleanup ? 1 : 3;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171}
1172
Devang Patel83637b12009-02-10 07:00:59 +00001173/// CleanupAllocaUsers - If SROA reported that it can promote the specified
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001174/// allocation, but only if cleaned up, perform the cleanups required.
Bob Wilson11aa9712009-12-18 20:14:40 +00001175void SROA::CleanupAllocaUsers(Value *V) {
Bob Wilson11aa9712009-12-18 20:14:40 +00001176 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001177 UI != E; ) {
Devang Patel83637b12009-02-10 07:00:59 +00001178 User *U = *UI++;
Bob Wilson37148982009-12-21 18:39:47 +00001179 Instruction *I = cast<Instruction>(U);
1180 SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
1181 if (!isa<StoreInst>(I) && OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
1182 // Safe to remove debug info uses.
1183 while (!DbgInUses.empty()) {
1184 DbgInfoIntrinsic *DI = DbgInUses.back(); DbgInUses.pop_back();
1185 DI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001186 }
Bob Wilson37148982009-12-21 18:39:47 +00001187 I->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001188 }
1189 }
1190}
1191
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001192/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1193/// the offset specified by Offset (which is specified in bytes).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001194///
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001195/// There are two cases we handle here:
1196/// 1) A union of vector types of the same size and potentially its elements.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001197/// Here we turn element accesses into insert/extract element operations.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001198/// This promotes a <4 x float> with a store of float to the third element
1199/// into a <4 x float> that uses insert element.
1200/// 2) A fully general blob of memory, which we turn into some (potentially
1201/// large) integer type with extract and insert operations where the loads
1202/// and stores would mutate the memory.
Chris Lattnerf235a322009-02-03 01:30:09 +00001203static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
Owen Andersonfa089ab2009-07-03 19:42:02 +00001204 unsigned AllocaSize, const TargetData &TD,
Owen Anderson175b6542009-07-22 00:24:57 +00001205 LLVMContext &Context) {
Chris Lattnerf235a322009-02-03 01:30:09 +00001206 // If this could be contributing to a vector, analyze it.
Owen Anderson35b47072009-08-13 21:58:54 +00001207 if (VecTy != Type::getVoidTy(Context)) { // either null or a vector type.
Chris Lattnerc2a5f2a2009-02-02 18:02:59 +00001208
Chris Lattnerf235a322009-02-03 01:30:09 +00001209 // If the In type is a vector that is the same size as the alloca, see if it
1210 // matches the existing VecTy.
1211 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1212 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1213 // If we're storing/loading a vector of the right size, allow it as a
1214 // vector. If this the first vector we see, remember the type so that
1215 // we know the element size.
1216 if (VecTy == 0)
1217 VecTy = VInTy;
1218 return;
1219 }
Chris Lattner82cdc062009-10-05 05:54:46 +00001220 } else if (In->isFloatTy() || In->isDoubleTy() ||
Chris Lattnerf235a322009-02-03 01:30:09 +00001221 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1222 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1223 // If we're accessing something that could be an element of a vector, see
1224 // if the implied vector agrees with what we already have and if Offset is
1225 // compatible with it.
1226 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1227 if (Offset % EltSize == 0 &&
1228 AllocaSize % EltSize == 0 &&
1229 (VecTy == 0 ||
1230 cast<VectorType>(VecTy)->getElementType()
1231 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1232 if (VecTy == 0)
Owen Anderson6b6e2d92009-07-29 22:17:13 +00001233 VecTy = VectorType::get(In, AllocaSize/EltSize);
Chris Lattnerf235a322009-02-03 01:30:09 +00001234 return;
1235 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001236 }
1237 }
1238
Chris Lattnerf235a322009-02-03 01:30:09 +00001239 // Otherwise, we have a case that we can't handle with an optimized vector
1240 // form. We can still turn this into a large integer.
Owen Anderson35b47072009-08-13 21:58:54 +00001241 VecTy = Type::getVoidTy(Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001242}
1243
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001244/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
Bob Wilson39d77062009-12-09 18:05:27 +00001245/// its accesses to a single vector type, return true and set VecTy to
Chris Lattnerf235a322009-02-03 01:30:09 +00001246/// the new type. If we could convert the alloca into a single promotable
1247/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1248/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1249/// is the current offset from the base of the alloca being analyzed.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001250///
Chris Lattner38088d12009-02-03 18:15:05 +00001251/// If we see at least one access to the value that is as a vector type, set the
1252/// SawVec flag.
Chris Lattner38088d12009-02-03 18:15:05 +00001253bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1254 bool &SawVec, uint64_t Offset,
Chris Lattnerf235a322009-02-03 01:30:09 +00001255 unsigned AllocaSize) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001256 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1257 Instruction *User = cast<Instruction>(*UI);
1258
1259 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001260 // Don't break volatile loads.
Chris Lattner70ffe572009-01-28 20:16:43 +00001261 if (LI->isVolatile())
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001262 return false;
Owen Anderson175b6542009-07-22 00:24:57 +00001263 MergeInType(LI->getType(), Offset, VecTy,
1264 AllocaSize, *TD, V->getContext());
Chris Lattner38088d12009-02-03 18:15:05 +00001265 SawVec |= isa<VectorType>(LI->getType());
Chris Lattner7cc97712009-01-07 06:39:58 +00001266 continue;
1267 }
1268
1269 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270 // Storing the pointer, not into the value?
Chris Lattner70ffe572009-01-28 20:16:43 +00001271 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
Owen Andersonfa089ab2009-07-03 19:42:02 +00001272 MergeInType(SI->getOperand(0)->getType(), Offset,
Owen Anderson175b6542009-07-22 00:24:57 +00001273 VecTy, AllocaSize, *TD, V->getContext());
Chris Lattner38088d12009-02-03 18:15:05 +00001274 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
Chris Lattner7cc97712009-01-07 06:39:58 +00001275 continue;
1276 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001277
1278 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattner38088d12009-02-03 18:15:05 +00001279 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1280 AllocaSize))
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001281 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001282 IsNotTrivial = true;
Chris Lattner7cc97712009-01-07 06:39:58 +00001283 continue;
1284 }
1285
1286 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001287 // If this is a GEP with a variable indices, we can't handle it.
1288 if (!GEP->hasAllConstantIndices())
1289 return false;
Chris Lattner7cc97712009-01-07 06:39:58 +00001290
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001291 // Compute the offset that this GEP adds to the pointer.
1292 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Bob Wilson11aa9712009-12-18 20:14:40 +00001293 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001294 &Indices[0], Indices.size());
1295 // See if all uses can be converted.
Chris Lattner38088d12009-02-03 18:15:05 +00001296 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
Chris Lattnerf235a322009-02-03 01:30:09 +00001297 AllocaSize))
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001298 return false;
1299 IsNotTrivial = true;
1300 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001301 }
Chris Lattnera86628a2009-03-08 03:37:16 +00001302
Chris Lattnerfece0da2009-02-03 02:01:43 +00001303 // If this is a constant sized memset of a constant value (e.g. 0) we can
1304 // handle it.
Chris Lattnera86628a2009-03-08 03:37:16 +00001305 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1306 // Store of constant value and constant size.
1307 if (isa<ConstantInt>(MSI->getValue()) &&
1308 isa<ConstantInt>(MSI->getLength())) {
Chris Lattnera86628a2009-03-08 03:37:16 +00001309 IsNotTrivial = true;
1310 continue;
1311 }
Chris Lattnerfece0da2009-02-03 02:01:43 +00001312 }
Chris Lattneracd8c2e2009-03-08 04:04:21 +00001313
1314 // If this is a memcpy or memmove into or out of the whole allocation, we
1315 // can handle it like a load or store of the scalar type.
1316 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1317 if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
1318 if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1319 IsNotTrivial = true;
1320 continue;
1321 }
1322 }
Chris Lattner3947da72009-03-08 03:59:00 +00001323
Devang Patel27705b02009-03-06 07:03:54 +00001324 // Ignore dbg intrinsic.
1325 if (isa<DbgInfoIntrinsic>(User))
1326 continue;
1327
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001328 // Otherwise, we cannot handle this!
1329 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001330 }
1331
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001332 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001333}
1334
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1336/// directly. This happens when we are converting an "integer union" to a
1337/// single integer scalar, or when we are converting a "vector union" to a
1338/// vector with insert/extractelement instructions.
1339///
1340/// Offset is an offset from the original alloca, in bits that need to be
1341/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001342void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001343 while (!Ptr->use_empty()) {
1344 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands641f12c2009-02-02 10:06:20 +00001345
Chris Lattner7cc97712009-01-07 06:39:58 +00001346 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb1534532008-01-30 00:39:15 +00001347 ConvertUsesToScalar(CI, NewAI, Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001348 CI->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001349 continue;
1350 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001351
Chris Lattner7cc97712009-01-07 06:39:58 +00001352 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001353 // Compute the offset that this GEP adds to the pointer.
1354 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Bob Wilson11aa9712009-12-18 20:14:40 +00001355 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001356 &Indices[0], Indices.size());
1357 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001358 GEP->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001359 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001360 }
Chris Lattnerfece0da2009-02-03 02:01:43 +00001361
Chris Lattnerececb0c2009-02-03 19:45:44 +00001362 IRBuilder<> Builder(User->getParent(), User);
1363
1364 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001365 // The load is a bit extract from NewAI shifted right by Offset bits.
1366 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1367 Value *NewLoadVal
1368 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1369 LI->replaceAllUsesWith(NewLoadVal);
Chris Lattnerececb0c2009-02-03 19:45:44 +00001370 LI->eraseFromParent();
1371 continue;
1372 }
1373
1374 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1375 assert(SI->getOperand(0) != Ptr && "Consistency error!");
Chris Lattnercc6a6e22009-12-22 19:23:33 +00001376 Value *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
Chris Lattnerececb0c2009-02-03 19:45:44 +00001377 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1378 Builder);
1379 Builder.CreateStore(New, NewAI);
1380 SI->eraseFromParent();
1381 continue;
1382 }
1383
Chris Lattnerfece0da2009-02-03 02:01:43 +00001384 // If this is a constant sized memset of a constant value (e.g. 0) we can
1385 // transform it into a store of the expanded constant value.
1386 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1387 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1388 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Chris Lattner7af52f72009-04-21 16:52:12 +00001389 if (NumBytes != 0) {
1390 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1391
1392 // Compute the value replicated the right number of times.
1393 APInt APVal(NumBytes*8, Val);
Chris Lattnerfece0da2009-02-03 02:01:43 +00001394
Chris Lattner7af52f72009-04-21 16:52:12 +00001395 // Splat the value if non-zero.
1396 if (Val)
1397 for (unsigned i = 1; i != NumBytes; ++i)
1398 APVal |= APVal << 8;
Benjamin Kramerc04f8ad2009-11-29 21:17:48 +00001399
Chris Lattnercc6a6e22009-12-22 19:23:33 +00001400 Value *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
Owen Anderson175b6542009-07-22 00:24:57 +00001401 Value *New = ConvertScalar_InsertValue(
Owen Andersoneacb44d2009-07-24 23:12:02 +00001402 ConstantInt::get(User->getContext(), APVal),
Owen Andersonfa089ab2009-07-03 19:42:02 +00001403 Old, Offset, Builder);
Chris Lattner7af52f72009-04-21 16:52:12 +00001404 Builder.CreateStore(New, NewAI);
1405 }
Chris Lattnerfece0da2009-02-03 02:01:43 +00001406 MSI->eraseFromParent();
1407 continue;
1408 }
Chris Lattneracd8c2e2009-03-08 04:04:21 +00001409
1410 // If this is a memcpy or memmove into or out of the whole allocation, we
1411 // can handle it like a load or store of the scalar type.
1412 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1413 assert(Offset == 0 && "must be store to start of alloca");
1414
1415 // If the source and destination are both to the same alloca, then this is
1416 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
1417 // as appropriate.
1418 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject());
1419
1420 if (MTI->getSource()->getUnderlyingObject() != OrigAI) {
1421 // Dest must be OrigAI, change this to be a load from the original
1422 // pointer (bitcasted), then a store to our new alloca.
1423 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1424 Value *SrcPtr = MTI->getSource();
1425 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1426
1427 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1428 SrcVal->setAlignment(MTI->getAlignment());
1429 Builder.CreateStore(SrcVal, NewAI);
1430 } else if (MTI->getDest()->getUnderlyingObject() != OrigAI) {
1431 // Src must be OrigAI, change this to be a load from NewAI then a store
1432 // through the original dest pointer (bitcasted).
1433 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1434 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1435
1436 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1437 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1438 NewStore->setAlignment(MTI->getAlignment());
1439 } else {
1440 // Noop transfer. Src == Dst
1441 }
1442
1443
1444 MTI->eraseFromParent();
1445 continue;
1446 }
Chris Lattner3947da72009-03-08 03:59:00 +00001447
Devang Patel27705b02009-03-06 07:03:54 +00001448 // If user is a dbg info intrinsic then it is safe to remove it.
1449 if (isa<DbgInfoIntrinsic>(User)) {
1450 User->eraseFromParent();
1451 continue;
1452 }
1453
Edwin Törökbd448e32009-07-14 16:55:14 +00001454 llvm_unreachable("Unsupported operation!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001455 }
1456}
1457
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001458/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1459/// or vector value FromVal, extracting the bits from the offset specified by
1460/// Offset. This returns the value, which is of type ToType.
1461///
1462/// This happens when we are converting an "integer union" to a single
Duncan Sands641f12c2009-02-02 10:06:20 +00001463/// integer scalar, or when we are converting a "vector union" to a vector with
1464/// insert/extractelement instructions.
Chris Lattner41d58652008-02-29 07:03:13 +00001465///
Duncan Sands641f12c2009-02-02 10:06:20 +00001466/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001467/// shifted to the right.
1468Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1469 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001470 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001471 if (FromVal->getType() == ToType && Offset == 0)
1472 return FromVal;
Chris Lattner5f062542008-02-29 07:12:06 +00001473
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001474 // If the result alloca is a vector type, this is either an element
1475 // access or a bitcast to another vector type of the same size.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001476 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1477 if (isa<VectorType>(ToType))
1478 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner5f062542008-02-29 07:12:06 +00001479
1480 // Otherwise it must be an element access.
Chris Lattner5f062542008-02-29 07:12:06 +00001481 unsigned Elt = 0;
1482 if (Offset) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00001483 unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner5f062542008-02-29 07:12:06 +00001484 Elt = Offset/EltSize;
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001485 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner41d58652008-02-29 07:03:13 +00001486 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001487 // Return the element extracted out of it.
Owen Anderson35b47072009-08-13 21:58:54 +00001488 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
1489 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001490 if (V->getType() != ToType)
1491 V = Builder.CreateBitCast(V, ToType, "tmp");
Chris Lattnerf235a322009-02-03 01:30:09 +00001492 return V;
Chris Lattner5f062542008-02-29 07:12:06 +00001493 }
Chris Lattner7bac66b2009-02-03 21:08:45 +00001494
1495 // If ToType is a first class aggregate, extract out each of the pieces and
1496 // use insertvalue's to form the FCA.
1497 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1498 const StructLayout &Layout = *TD->getStructLayout(ST);
Owen Andersonb99ecca2009-07-30 23:03:37 +00001499 Value *Res = UndefValue::get(ST);
Chris Lattner7bac66b2009-02-03 21:08:45 +00001500 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1501 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
Chris Lattner97e1f382009-02-06 04:34:07 +00001502 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner7bac66b2009-02-03 21:08:45 +00001503 Builder);
1504 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1505 }
1506 return Res;
1507 }
1508
1509 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00001510 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00001511 Value *Res = UndefValue::get(AT);
Chris Lattner7bac66b2009-02-03 21:08:45 +00001512 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1513 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1514 Offset+i*EltSize, Builder);
1515 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1516 }
1517 return Res;
1518 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001519
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001520 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001521 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Duncan Sands641f12c2009-02-02 10:06:20 +00001522
Chris Lattner5f062542008-02-29 07:12:06 +00001523 // If this is a big-endian system and the load is narrower than the
1524 // full alloca type, we need to do a shift to get the right bits.
1525 int ShAmt = 0;
Chris Lattner3fd59362009-01-07 06:34:28 +00001526 if (TD->isBigEndian()) {
Chris Lattner5f062542008-02-29 07:12:06 +00001527 // On big-endian machines, the lowest bit is stored at the bit offset
1528 // from the pointer given by getTypeStoreSizeInBits. This matters for
1529 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner3fd59362009-01-07 06:34:28 +00001530 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001531 TD->getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner5f062542008-02-29 07:12:06 +00001532 } else {
1533 ShAmt = Offset;
1534 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001535
Chris Lattner5f062542008-02-29 07:12:06 +00001536 // Note: we support negative bitwidths (with shl) which are not defined.
1537 // We do this to support (f.e.) loads off the end of a structure where
1538 // only some bits are used.
1539 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Owen Andersonfa089ab2009-07-03 19:42:02 +00001540 FromVal = Builder.CreateLShr(FromVal,
Owen Andersoneacb44d2009-07-24 23:12:02 +00001541 ConstantInt::get(FromVal->getType(),
Chris Lattner7bac66b2009-02-03 21:08:45 +00001542 ShAmt), "tmp");
Chris Lattner5f062542008-02-29 07:12:06 +00001543 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Owen Andersonfa089ab2009-07-03 19:42:02 +00001544 FromVal = Builder.CreateShl(FromVal,
Owen Andersoneacb44d2009-07-24 23:12:02 +00001545 ConstantInt::get(FromVal->getType(),
Chris Lattner7bac66b2009-02-03 21:08:45 +00001546 -ShAmt), "tmp");
Duncan Sands641f12c2009-02-02 10:06:20 +00001547
Chris Lattner5f062542008-02-29 07:12:06 +00001548 // Finally, unconditionally truncate the integer to the right width.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001549 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
Chris Lattner5f062542008-02-29 07:12:06 +00001550 if (LIBitWidth < NTy->getBitWidth())
Owen Andersonfa089ab2009-07-03 19:42:02 +00001551 FromVal =
Owen Anderson35b47072009-08-13 21:58:54 +00001552 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
1553 LIBitWidth), "tmp");
Chris Lattnerb2290a12009-02-03 07:08:57 +00001554 else if (LIBitWidth > NTy->getBitWidth())
Owen Andersonfa089ab2009-07-03 19:42:02 +00001555 FromVal =
Owen Anderson35b47072009-08-13 21:58:54 +00001556 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
1557 LIBitWidth), "tmp");
Duncan Sands641f12c2009-02-02 10:06:20 +00001558
Chris Lattner5f062542008-02-29 07:12:06 +00001559 // If the result is an integer, this is a trunc or bitcast.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001560 if (isa<IntegerType>(ToType)) {
Chris Lattner5f062542008-02-29 07:12:06 +00001561 // Should be done.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001562 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
Chris Lattner5f062542008-02-29 07:12:06 +00001563 // Just do a bitcast, we know the sizes match up.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001564 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner41d58652008-02-29 07:03:13 +00001565 } else {
Chris Lattner5f062542008-02-29 07:12:06 +00001566 // Otherwise must be a pointer.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001567 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
Chris Lattner41d58652008-02-29 07:03:13 +00001568 }
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001569 assert(FromVal->getType() == ToType && "Didn't convert right?");
1570 return FromVal;
Chris Lattner41d58652008-02-29 07:03:13 +00001571}
1572
Chris Lattnercc0727c2009-02-03 19:30:11 +00001573/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1574/// or vector value "Old" at the offset specified by Offset.
1575///
1576/// This happens when we are converting an "integer union" to a
Chris Lattner41d58652008-02-29 07:03:13 +00001577/// single integer scalar, or when we are converting a "vector union" to a
1578/// vector with insert/extractelement instructions.
1579///
1580/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattnercc0727c2009-02-03 19:30:11 +00001581/// shifted to the right.
1582Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
Chris Lattner32c19282009-02-03 19:41:50 +00001583 uint64_t Offset, IRBuilder<> &Builder) {
Duncan Sands641f12c2009-02-02 10:06:20 +00001584
Chris Lattner41d58652008-02-29 07:03:13 +00001585 // Convert the stored type to the actual type, shift it left to insert
1586 // then 'or' into place.
Chris Lattnercc0727c2009-02-03 19:30:11 +00001587 const Type *AllocaType = Old->getType();
Owen Anderson175b6542009-07-22 00:24:57 +00001588 LLVMContext &Context = Old->getContext();
Duncan Sands641f12c2009-02-02 10:06:20 +00001589
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001590 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00001591 uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1592 uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
Chris Lattner6e2bca62009-03-08 04:17:04 +00001593
1594 // Changing the whole vector with memset or with an access of a different
1595 // vector type?
1596 if (ValSize == VecSize)
1597 return Builder.CreateBitCast(SV, AllocaType, "tmp");
1598
Duncan Sandsec4f97d2009-05-09 07:06:46 +00001599 uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner6e2bca62009-03-08 04:17:04 +00001600
1601 // Must be an element insertion.
1602 unsigned Elt = Offset/EltSize;
1603
1604 if (SV->getType() != VTy->getElementType())
1605 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1606
1607 SV = Builder.CreateInsertElement(Old, SV,
Owen Anderson35b47072009-08-13 21:58:54 +00001608 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
Chris Lattner6e2bca62009-03-08 04:17:04 +00001609 "tmp");
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001610 return SV;
1611 }
Chris Lattnercc0727c2009-02-03 19:30:11 +00001612
1613 // If SV is a first-class aggregate value, insert each value recursively.
1614 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1615 const StructLayout &Layout = *TD->getStructLayout(ST);
1616 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Chris Lattner32c19282009-02-03 19:41:50 +00001617 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Chris Lattnercc0727c2009-02-03 19:30:11 +00001618 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner97e1f382009-02-06 04:34:07 +00001619 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner32c19282009-02-03 19:41:50 +00001620 Builder);
Chris Lattnercc0727c2009-02-03 19:30:11 +00001621 }
1622 return Old;
1623 }
1624
1625 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00001626 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Chris Lattnercc0727c2009-02-03 19:30:11 +00001627 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Chris Lattner32c19282009-02-03 19:41:50 +00001628 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1629 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
Chris Lattnercc0727c2009-02-03 19:30:11 +00001630 }
1631 return Old;
1632 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001633
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001634 // If SV is a float, convert it to the appropriate integer type.
Chris Lattnercc0727c2009-02-03 19:30:11 +00001635 // If it is a pointer, do the same.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001636 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1637 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1638 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1639 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1640 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
Owen Anderson35b47072009-08-13 21:58:54 +00001641 SV = Builder.CreateBitCast(SV,
1642 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001643 else if (isa<PointerType>(SV->getType()))
Owen Anderson35b47072009-08-13 21:58:54 +00001644 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(SV->getContext()), "tmp");
Duncan Sands641f12c2009-02-02 10:06:20 +00001645
Chris Lattnerf235a322009-02-03 01:30:09 +00001646 // Zero extend or truncate the value if needed.
1647 if (SV->getType() != AllocaType) {
1648 if (SV->getType()->getPrimitiveSizeInBits() <
1649 AllocaType->getPrimitiveSizeInBits())
Chris Lattner32c19282009-02-03 19:41:50 +00001650 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
Chris Lattnerf235a322009-02-03 01:30:09 +00001651 else {
1652 // Truncation may be needed if storing more than the alloca can hold
1653 // (undefined behavior).
Chris Lattner32c19282009-02-03 19:41:50 +00001654 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
Chris Lattnerf235a322009-02-03 01:30:09 +00001655 SrcWidth = DestWidth;
1656 SrcStoreWidth = DestStoreWidth;
1657 }
1658 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001659
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001660 // If this is a big-endian system and the store is narrower than the
1661 // full alloca type, we need to do a shift to get the right bits.
1662 int ShAmt = 0;
1663 if (TD->isBigEndian()) {
1664 // On big-endian machines, the lowest bit is stored at the bit offset
1665 // from the pointer given by getTypeStoreSizeInBits. This matters for
1666 // integers with a bitwidth that is not a multiple of 8.
1667 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner41d58652008-02-29 07:03:13 +00001668 } else {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001669 ShAmt = Offset;
1670 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001671
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001672 // Note: we support negative bitwidths (with shr) which are not defined.
1673 // We do this to support (f.e.) stores off the end of a structure where
1674 // only some bits in the structure are set.
1675 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1676 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00001677 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa089ab2009-07-03 19:42:02 +00001678 ShAmt), "tmp");
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001679 Mask <<= ShAmt;
1680 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00001681 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa089ab2009-07-03 19:42:02 +00001682 -ShAmt), "tmp");
Duncan Sandsced29632009-02-02 09:53:14 +00001683 Mask = Mask.lshr(-ShAmt);
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001684 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001685
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001686 // Mask out the bits we are about to insert from the old value, and or
1687 // in the new bits.
1688 if (SrcWidth != DestWidth) {
1689 assert(DestWidth > SrcWidth);
Owen Andersoneacb44d2009-07-24 23:12:02 +00001690 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
Chris Lattner32c19282009-02-03 19:41:50 +00001691 SV = Builder.CreateOr(Old, SV, "ins");
Chris Lattner41d58652008-02-29 07:03:13 +00001692 }
1693 return SV;
1694}
1695
1696
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001697
1698/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1699/// some part of a constant global variable. This intentionally only accepts
1700/// constant expressions because we don't can't rewrite arbitrary instructions.
1701static bool PointsToConstantGlobal(Value *V) {
1702 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1703 return GV->isConstant();
1704 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1705 if (CE->getOpcode() == Instruction::BitCast ||
1706 CE->getOpcode() == Instruction::GetElementPtr)
1707 return PointsToConstantGlobal(CE->getOperand(0));
1708 return false;
1709}
1710
1711/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1712/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1713/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1714/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1715/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1716/// the alloca, and if the source pointer is a pointer to a constant global, we
1717/// can optimize this.
1718static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1719 bool isOffset) {
1720 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Chris Lattner70ffe572009-01-28 20:16:43 +00001721 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1722 // Ignore non-volatile loads, they are always ok.
1723 if (!LI->isVolatile())
1724 continue;
1725
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001726 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1727 // If uses of the bitcast are ok, we are ok.
1728 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1729 return false;
1730 continue;
1731 }
1732 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1733 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1734 // doesn't, it does.
1735 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1736 isOffset || !GEP->hasAllZeroIndices()))
1737 return false;
1738 continue;
1739 }
1740
1741 // If this is isn't our memcpy/memmove, reject it as something we can't
1742 // handle.
Chris Lattnera86628a2009-03-08 03:37:16 +00001743 if (!isa<MemTransferInst>(*UI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001744 return false;
1745
1746 // If we already have seen a copy, reject the second one.
1747 if (TheCopy) return false;
1748
1749 // If the pointer has been offset from the start of the alloca, we can't
1750 // safely handle this.
1751 if (isOffset) return false;
1752
1753 // If the memintrinsic isn't using the alloca as the dest, reject it.
1754 if (UI.getOperandNo() != 1) return false;
1755
1756 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1757
1758 // If the source of the memcpy/move is not a constant global, reject it.
1759 if (!PointsToConstantGlobal(MI->getOperand(2)))
1760 return false;
1761
1762 // Otherwise, the transform is safe. Remember the copy instruction.
1763 TheCopy = MI;
1764 }
1765 return true;
1766}
1767
1768/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1769/// modified by a copy from a constant global. If we can prove this, we can
1770/// replace any uses of the alloca with uses of the global directly.
Victor Hernandezb1687302009-10-23 21:09:37 +00001771Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001772 Instruction *TheCopy = 0;
1773 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1774 return TheCopy;
1775 return 0;
1776}