blob: 041fd4917b4b19d91e3b4e1d9d1d30133d20149e [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"
30#include "llvm/Pass.h"
31#include "llvm/Analysis/Dominators.h"
32#include "llvm/Target/TargetData.h"
33#include "llvm/Transforms/Utils/PromoteMemToReg.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/GetElementPtrTypeIterator.h"
36#include "llvm/Support/MathExtras.h"
37#include "llvm/Support/Compiler.h"
38#include "llvm/ADT/SmallVector.h"
39#include "llvm/ADT/Statistic.h"
40#include "llvm/ADT/StringExtras.h"
41using namespace llvm;
42
43STATISTIC(NumReplaced, "Number of allocas broken up");
44STATISTIC(NumPromoted, "Number of allocas promoted");
45STATISTIC(NumConverted, "Number of aggregates converted to scalar");
46STATISTIC(NumGlobals, "Number of allocas copied from constant global");
47
48namespace {
49 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
50 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000051 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052 if (T == -1)
Chris Lattner6d7faec2007-08-02 21:33:36 +000053 SRThreshold = 128;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000054 else
55 SRThreshold = T;
56 }
57
58 bool runOnFunction(Function &F);
59
60 bool performScalarRepl(Function &F);
61 bool performPromotion(Function &F);
62
63 // getAnalysisUsage - This pass does not require any passes, but we know it
64 // will not alter the CFG, so say so.
65 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
66 AU.addRequired<DominatorTree>();
67 AU.addRequired<DominanceFrontier>();
68 AU.addRequired<TargetData>();
69 AU.setPreservesCFG();
70 }
71
72 private:
Chris Lattner3fd59362009-01-07 06:34:28 +000073 TargetData *TD;
74
Dan Gohmanf17a25c2007-07-18 16:29:46 +000075 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
76 /// information about the uses. All these fields are initialized to false
77 /// and set to true when something is learned.
78 struct AllocaInfo {
79 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
80 bool isUnsafe : 1;
81
82 /// needsCanon - This is set to true if there is some use of the alloca
83 /// that requires canonicalization.
84 bool needsCanon : 1;
85
86 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
87 bool isMemCpySrc : 1;
88
89 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
90 bool isMemCpyDst : 1;
91
92 AllocaInfo()
93 : isUnsafe(false), needsCanon(false),
94 isMemCpySrc(false), isMemCpyDst(false) {}
95 };
96
97 unsigned SRThreshold;
98
99 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
100
101 int isSafeAllocaToScalarRepl(AllocationInst *AI);
102
103 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
104 AllocaInfo &Info);
105 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
106 AllocaInfo &Info);
107 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
108 unsigned OpNo, AllocaInfo &Info);
109 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
110 AllocaInfo &Info);
111
112 void DoScalarReplacement(AllocationInst *AI,
113 std::vector<AllocationInst*> &WorkList);
114 void CanonicalizeAllocaUsers(AllocationInst *AI);
115 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
116
117 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
118 SmallVector<AllocaInst*, 32> &NewElts);
119
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000120 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
121 AllocationInst *AI,
122 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner71c75342009-01-07 08:11:13 +0000123 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocationInst *AI,
124 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner28401db2009-01-08 05:42:05 +0000125 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
126 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000127
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128 const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
129 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
130 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
Chris Lattner41d58652008-02-29 07:03:13 +0000131 Value *ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
132 unsigned Offset);
133 Value *ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
134 unsigned Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000135 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
136 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000137}
138
Dan Gohman089efff2008-05-13 00:00:25 +0000139char SROA::ID = 0;
140static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
141
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000142// Public interface to the ScalarReplAggregates pass
143FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
144 return new SROA(Threshold);
145}
146
147
148bool SROA::runOnFunction(Function &F) {
Chris Lattner3fd59362009-01-07 06:34:28 +0000149 TD = &getAnalysis<TargetData>();
150
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151 bool Changed = performPromotion(F);
152 while (1) {
153 bool LocalChange = performScalarRepl(F);
154 if (!LocalChange) break; // No need to repromote if no scalarrepl
155 Changed = true;
156 LocalChange = performPromotion(F);
157 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
158 }
159
160 return Changed;
161}
162
163
164bool SROA::performPromotion(Function &F) {
165 std::vector<AllocaInst*> Allocas;
166 DominatorTree &DT = getAnalysis<DominatorTree>();
167 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
168
169 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
170
171 bool Changed = false;
172
173 while (1) {
174 Allocas.clear();
175
176 // Find allocas that are safe to promote, by looking at all instructions in
177 // the entry node
178 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
179 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
180 if (isAllocaPromotable(AI))
181 Allocas.push_back(AI);
182
183 if (Allocas.empty()) break;
184
185 PromoteMemToReg(Allocas, DT, DF);
186 NumPromoted += Allocas.size();
187 Changed = true;
188 }
189
190 return Changed;
191}
192
Chris Lattner0e99e692008-06-22 17:46:21 +0000193/// getNumSAElements - Return the number of elements in the specific struct or
194/// array.
195static uint64_t getNumSAElements(const Type *T) {
196 if (const StructType *ST = dyn_cast<StructType>(T))
197 return ST->getNumElements();
198 return cast<ArrayType>(T)->getNumElements();
199}
200
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201// performScalarRepl - This algorithm is a simple worklist driven algorithm,
202// which runs on all of the malloc/alloca instructions in the function, removing
203// them if they are only used by getelementptr instructions.
204//
205bool SROA::performScalarRepl(Function &F) {
206 std::vector<AllocationInst*> WorkList;
207
208 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
209 BasicBlock &BB = F.getEntryBlock();
210 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
211 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
212 WorkList.push_back(A);
213
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 // Process the worklist
215 bool Changed = false;
216 while (!WorkList.empty()) {
217 AllocationInst *AI = WorkList.back();
218 WorkList.pop_back();
219
220 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
221 // with unused elements.
222 if (AI->use_empty()) {
223 AI->eraseFromParent();
224 continue;
225 }
226
227 // If we can turn this aggregate value (potentially with casts) into a
228 // simple scalar value that can be mem2reg'd into a register value.
229 bool IsNotTrivial = false;
230 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
231 if (IsNotTrivial && ActualType != Type::VoidTy) {
232 ConvertToScalar(AI, ActualType);
233 Changed = true;
234 continue;
235 }
236
237 // Check to see if we can perform the core SROA transformation. We cannot
238 // transform the allocation instruction if it is an array allocation
239 // (allocations OF arrays are ok though), and an allocation of a scalar
240 // value cannot be decomposed at all.
241 if (!AI->isArrayAllocation() &&
242 (isa<StructType>(AI->getAllocatedType()) ||
243 isa<ArrayType>(AI->getAllocatedType())) &&
244 AI->getAllocatedType()->isSized() &&
Chris Lattner0e99e692008-06-22 17:46:21 +0000245 // Do not promote any struct whose size is larger than "128" bytes.
Chris Lattner3fd59362009-01-07 06:34:28 +0000246 TD->getABITypeSize(AI->getAllocatedType()) < SRThreshold &&
Chris Lattner0e99e692008-06-22 17:46:21 +0000247 // Do not promote any struct into more than "32" separate vars.
248 getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249 // Check that all of the users of the allocation are capable of being
250 // transformed.
251 switch (isSafeAllocaToScalarRepl(AI)) {
252 default: assert(0 && "Unexpected value!");
253 case 0: // Not safe to scalar replace.
254 break;
255 case 1: // Safe, but requires cleanup/canonicalizations first
256 CanonicalizeAllocaUsers(AI);
257 // FALL THROUGH.
258 case 3: // Safe to scalar replace.
259 DoScalarReplacement(AI, WorkList);
260 Changed = true;
261 continue;
262 }
263 }
264
265 // Check to see if this allocation is only modified by a memcpy/memmove from
266 // a constant global. If this is the case, we can change all users to use
267 // the constant global instead. This is commonly produced by the CFE by
268 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
269 // is only subsequently read.
270 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
271 DOUT << "Found alloca equal to global: " << *AI;
272 DOUT << " memcpy = " << *TheCopy;
273 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
274 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
275 TheCopy->eraseFromParent(); // Don't mutate the global.
276 AI->eraseFromParent();
277 ++NumGlobals;
278 Changed = true;
279 continue;
280 }
281
282 // Otherwise, couldn't process this.
283 }
284
285 return Changed;
286}
287
288/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
289/// predicate, do SROA now.
290void SROA::DoScalarReplacement(AllocationInst *AI,
291 std::vector<AllocationInst*> &WorkList) {
292 DOUT << "Found inst to SROA: " << *AI;
293 SmallVector<AllocaInst*, 32> ElementAllocas;
294 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
295 ElementAllocas.reserve(ST->getNumContainedTypes());
296 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
297 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
298 AI->getAlignment(),
299 AI->getName() + "." + utostr(i), AI);
300 ElementAllocas.push_back(NA);
301 WorkList.push_back(NA); // Add to worklist for recursive processing
302 }
303 } else {
304 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
305 ElementAllocas.reserve(AT->getNumElements());
306 const Type *ElTy = AT->getElementType();
307 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
308 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
309 AI->getName() + "." + utostr(i), AI);
310 ElementAllocas.push_back(NA);
311 WorkList.push_back(NA); // Add to worklist for recursive processing
312 }
313 }
314
315 // Now that we have created the alloca instructions that we want to use,
316 // expand the getelementptr instructions to use them.
317 //
318 while (!AI->use_empty()) {
319 Instruction *User = cast<Instruction>(AI->use_back());
320 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
321 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
322 BCInst->eraseFromParent();
323 continue;
324 }
325
Chris Lattner19e61a42008-06-23 17:11:23 +0000326 // Replace:
327 // %res = load { i32, i32 }* %alloc
328 // with:
329 // %load.0 = load i32* %alloc.0
330 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
331 // %load.1 = load i32* %alloc.1
332 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000333 // (Also works for arrays instead of structs)
334 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
335 Value *Insert = UndefValue::get(LI->getType());
336 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
337 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
338 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
339 }
340 LI->replaceAllUsesWith(Insert);
341 LI->eraseFromParent();
342 continue;
343 }
344
Chris Lattner19e61a42008-06-23 17:11:23 +0000345 // Replace:
346 // store { i32, i32 } %val, { i32, i32 }* %alloc
347 // with:
348 // %val.0 = extractvalue { i32, i32 } %val, 0
349 // store i32 %val.0, i32* %alloc.0
350 // %val.1 = extractvalue { i32, i32 } %val, 1
351 // store i32 %val.1, i32* %alloc.1
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000352 // (Also works for arrays instead of structs)
353 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
354 Value *Val = SI->getOperand(0);
355 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
356 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
357 new StoreInst(Extract, ElementAllocas[i], SI);
358 }
359 SI->eraseFromParent();
360 continue;
361 }
362
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
364 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
365 unsigned Idx =
366 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
367
368 assert(Idx < ElementAllocas.size() && "Index out of range?");
369 AllocaInst *AllocaToUse = ElementAllocas[Idx];
370
371 Value *RepValue;
372 if (GEPI->getNumOperands() == 3) {
373 // Do not insert a new getelementptr instruction with zero indices, only
374 // to have it optimized out later.
375 RepValue = AllocaToUse;
376 } else {
377 // We are indexing deeply into the structure, so we still need a
378 // getelement ptr instruction to finish the indexing. This may be
379 // expanded itself once the worklist is rerun.
380 //
381 SmallVector<Value*, 8> NewArgs;
382 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
383 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
Gabor Greifd6da1d02008-04-06 20:25:17 +0000384 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
385 NewArgs.end(), "", GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386 RepValue->takeName(GEPI);
387 }
388
389 // If this GEP is to the start of the aggregate, check for memcpys.
Chris Lattner85591c62009-01-07 06:25:07 +0000390 if (Idx == 0 && GEPI->hasAllZeroIndices())
391 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392
393 // Move all of the users over to the new GEP.
394 GEPI->replaceAllUsesWith(RepValue);
395 // Delete the old GEP
396 GEPI->eraseFromParent();
397 }
398
399 // Finally, delete the Alloca instruction
400 AI->eraseFromParent();
401 NumReplaced++;
402}
403
404
405/// isSafeElementUse - Check to see if this use is an allowed use for a
406/// getelementptr instruction of an array aggregate allocation. isFirstElt
407/// indicates whether Ptr is known to the start of the aggregate.
408///
409void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
410 AllocaInfo &Info) {
411 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
412 I != E; ++I) {
413 Instruction *User = cast<Instruction>(*I);
414 switch (User->getOpcode()) {
415 case Instruction::Load: break;
416 case Instruction::Store:
417 // Store is ok if storing INTO the pointer, not storing the pointer
418 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
419 break;
420 case Instruction::GetElementPtr: {
421 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
422 bool AreAllZeroIndices = isFirstElt;
423 if (GEP->getNumOperands() > 1) {
424 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
425 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
426 // Using pointer arithmetic to navigate the array.
427 return MarkUnsafe(Info);
428
Chris Lattner85591c62009-01-07 06:25:07 +0000429 if (AreAllZeroIndices)
430 AreAllZeroIndices = GEP->hasAllZeroIndices();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000431 }
432 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
433 if (Info.isUnsafe) return;
434 break;
435 }
436 case Instruction::BitCast:
437 if (isFirstElt) {
438 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
439 if (Info.isUnsafe) return;
440 break;
441 }
442 DOUT << " Transformation preventing inst: " << *User;
443 return MarkUnsafe(Info);
444 case Instruction::Call:
445 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
446 if (isFirstElt) {
447 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
448 if (Info.isUnsafe) return;
449 break;
450 }
451 }
452 DOUT << " Transformation preventing inst: " << *User;
453 return MarkUnsafe(Info);
454 default:
455 DOUT << " Transformation preventing inst: " << *User;
456 return MarkUnsafe(Info);
457 }
458 }
459 return; // All users look ok :)
460}
461
462/// AllUsersAreLoads - Return true if all users of this value are loads.
463static bool AllUsersAreLoads(Value *Ptr) {
464 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
465 I != E; ++I)
466 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
467 return false;
468 return true;
469}
470
471/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
472/// aggregate allocation.
473///
474void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
475 AllocaInfo &Info) {
476 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
477 return isSafeUseOfBitCastedAllocation(C, AI, Info);
478
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000479 if (isa<LoadInst>(User))
480 return; // Loads (returning a first class aggregrate) are always rewritable
481
482 if (isa<StoreInst>(User) && User->getOperand(0) != AI)
483 return; // Store is ok if storing INTO the pointer, not storing the pointer
484
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000485 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
486 if (GEPI == 0)
487 return MarkUnsafe(Info);
488
489 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
490
491 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
492 if (I == E ||
493 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
494 return MarkUnsafe(Info);
495 }
496
497 ++I;
498 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
499
500 bool IsAllZeroIndices = true;
501
Chris Lattnerd324da02008-08-23 05:21:06 +0000502 // If the first index is a non-constant index into an array, see if we can
503 // handle it as a special case.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000504 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
Chris Lattnerd324da02008-08-23 05:21:06 +0000505 if (!isa<ConstantInt>(I.getOperand())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000506 IsAllZeroIndices = 0;
Chris Lattnerd324da02008-08-23 05:21:06 +0000507 uint64_t NumElements = AT->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000508
509 // If this is an array index and the index is not constant, we cannot
510 // promote... that is unless the array has exactly one or two elements in
511 // it, in which case we CAN promote it, but we have to canonicalize this
512 // out if this is the only problem.
513 if ((NumElements == 1 || NumElements == 2) &&
514 AllUsersAreLoads(GEPI)) {
515 Info.needsCanon = true;
516 return; // Canonicalization required!
517 }
518 return MarkUnsafe(Info);
519 }
520 }
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000521
Chris Lattnerd324da02008-08-23 05:21:06 +0000522 // Walk through the GEP type indices, checking the types that this indexes
523 // into.
524 for (; I != E; ++I) {
525 // Ignore struct elements, no extra checking needed for these.
526 if (isa<StructType>(*I))
527 continue;
528
Chris Lattnerd324da02008-08-23 05:21:06 +0000529 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
530 if (!IdxVal) return MarkUnsafe(Info);
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000531
532 // Are all indices still zero?
Chris Lattnerd324da02008-08-23 05:21:06 +0000533 IsAllZeroIndices &= IdxVal->isZero();
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000534
535 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
536 // This GEP indexes an array. Verify that this is an in-range constant
537 // integer. Specifically, consider A[0][i]. We cannot know that the user
538 // isn't doing invalid things like allowing i to index an out-of-range
539 // subscript that accesses A[1]. Because of this, we have to reject SROA
Dale Johannesen1f9b1862008-11-04 20:54:03 +0000540 // of any accesses into structs where any of the components are variables.
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000541 if (IdxVal->getZExtValue() >= AT->getNumElements())
542 return MarkUnsafe(Info);
Dale Johannesen1f9b1862008-11-04 20:54:03 +0000543 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
544 if (IdxVal->getZExtValue() >= VT->getNumElements())
545 return MarkUnsafe(Info);
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000546 }
Chris Lattnerd324da02008-08-23 05:21:06 +0000547 }
548
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000549 // If there are any non-simple uses of this getelementptr, make sure to reject
550 // them.
551 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
552}
553
554/// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
555/// intrinsic can be promoted by SROA. At this point, we know that the operand
556/// of the memintrinsic is a pointer to the beginning of the allocation.
557void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
558 unsigned OpNo, AllocaInfo &Info) {
559 // If not constant length, give up.
560 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
561 if (!Length) return MarkUnsafe(Info);
562
563 // If not the whole aggregate, give up.
Duncan Sandsae5fd622007-11-04 14:43:57 +0000564 if (Length->getZExtValue() !=
Chris Lattner3fd59362009-01-07 06:34:28 +0000565 TD->getABITypeSize(AI->getType()->getElementType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000566 return MarkUnsafe(Info);
567
568 // We only know about memcpy/memset/memmove.
569 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
570 return MarkUnsafe(Info);
571
572 // Otherwise, we can transform it. Determine whether this is a memcpy/set
573 // into or out of the aggregate.
574 if (OpNo == 1)
575 Info.isMemCpyDst = true;
576 else {
577 assert(OpNo == 2);
578 Info.isMemCpySrc = true;
579 }
580}
581
582/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
583/// are
584void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
585 AllocaInfo &Info) {
586 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
587 UI != E; ++UI) {
588 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
589 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
590 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
591 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
Chris Lattner71c75342009-01-07 08:11:13 +0000592 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
593 // If storing the entire alloca in one chunk through a bitcasted pointer
594 // to integer, we can transform it. This happens (for example) when you
595 // cast a {i32,i32}* to i64* and store through it. This is similar to the
596 // memcpy case and occurs in various "byval" cases and emulated memcpys.
597 if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
598 TD->getABITypeSize(SI->getOperand(0)->getType()) ==
599 TD->getABITypeSize(AI->getType()->getElementType())) {
600 Info.isMemCpyDst = true;
601 continue;
602 }
603 return MarkUnsafe(Info);
Chris Lattner28401db2009-01-08 05:42:05 +0000604 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
605 // If loading the entire alloca in one chunk through a bitcasted pointer
606 // to integer, we can transform it. This happens (for example) when you
607 // cast a {i32,i32}* to i64* and load through it. This is similar to the
608 // memcpy case and occurs in various "byval" cases and emulated memcpys.
609 if (isa<IntegerType>(LI->getType()) &&
610 TD->getABITypeSize(LI->getType()) ==
611 TD->getABITypeSize(AI->getType()->getElementType())) {
612 Info.isMemCpySrc = true;
613 continue;
614 }
615 return MarkUnsafe(Info);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000616 } else {
617 return MarkUnsafe(Info);
618 }
619 if (Info.isUnsafe) return;
620 }
621}
622
623/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
624/// to its first element. Transform users of the cast to use the new values
625/// instead.
626void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
627 SmallVector<AllocaInst*, 32> &NewElts) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
629 while (UI != UE) {
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000630 Instruction *User = cast<Instruction>(*UI++);
631 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
Chris Lattner71c75342009-01-07 08:11:13 +0000633 if (BCU->use_empty()) BCU->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000634 continue;
635 }
636
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000637 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
638 // This must be memcpy/memmove/memset of the entire aggregate.
639 // Split into one per element.
640 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641 continue;
642 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000643
Chris Lattner71c75342009-01-07 08:11:13 +0000644 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Chris Lattner28401db2009-01-08 05:42:05 +0000645 // If this is a store of the entire alloca from an integer, rewrite it.
Chris Lattner71c75342009-01-07 08:11:13 +0000646 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
647 continue;
648 }
Chris Lattner28401db2009-01-08 05:42:05 +0000649
650 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
651 // If this is a load of the entire alloca to an integer, rewrite it.
652 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
653 continue;
654 }
Chris Lattner71c75342009-01-07 08:11:13 +0000655
656 // Otherwise it must be some other user of a gep of the first pointer. Just
657 // leave these alone.
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000658 continue;
Chris Lattner28401db2009-01-08 05:42:05 +0000659 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000660}
661
662/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
663/// Rewrite it to copy or set the elements of the scalarized memory.
664void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
665 AllocationInst *AI,
666 SmallVector<AllocaInst*, 32> &NewElts) {
667
668 // If this is a memcpy/memmove, construct the other pointer as the
669 // appropriate type.
670 Value *OtherPtr = 0;
671 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
672 if (BCInst == MCI->getRawDest())
673 OtherPtr = MCI->getRawSource();
674 else {
675 assert(BCInst == MCI->getRawSource());
676 OtherPtr = MCI->getRawDest();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000678 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
679 if (BCInst == MMI->getRawDest())
680 OtherPtr = MMI->getRawSource();
681 else {
682 assert(BCInst == MMI->getRawSource());
683 OtherPtr = MMI->getRawDest();
684 }
685 }
686
687 // If there is an other pointer, we want to convert it to the same pointer
688 // type as AI has, so we can GEP through it safely.
689 if (OtherPtr) {
690 // It is likely that OtherPtr is a bitcast, if so, remove it.
691 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
692 OtherPtr = BC->getOperand(0);
693 // All zero GEPs are effectively bitcasts.
694 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
695 if (GEP->hasAllZeroIndices())
696 OtherPtr = GEP->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000697
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000698 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
699 if (BCE->getOpcode() == Instruction::BitCast)
700 OtherPtr = BCE->getOperand(0);
701
702 // If the pointer is not the right type, insert a bitcast to the right
703 // type.
704 if (OtherPtr->getType() != AI->getType())
705 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
706 MI);
707 }
708
709 // Process each element of the aggregate.
710 Value *TheFn = MI->getOperand(0);
711 const Type *BytePtrTy = MI->getRawDest()->getType();
712 bool SROADest = MI->getRawDest() == BCInst;
713
714 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
715
716 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
717 // If this is a memcpy/memmove, emit a GEP of the other element address.
718 Value *OtherElt = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000719 if (OtherPtr) {
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000720 Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
721 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
Chris Lattner0e99e692008-06-22 17:46:21 +0000722 OtherPtr->getNameStr()+"."+utostr(i),
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000723 MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000724 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000725
726 Value *EltPtr = NewElts[i];
727 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
728
729 // If we got down to a scalar, insert a load or store as appropriate.
730 if (EltTy->isSingleValueType()) {
731 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
732 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
733 MI);
734 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
735 continue;
736 }
737 assert(isa<MemSetInst>(MI));
738
739 // If the stored element is zero (common case), just store a null
740 // constant.
741 Constant *StoreVal;
742 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
743 if (CI->isZero()) {
744 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
745 } else {
746 // If EltTy is a vector type, get the element type.
747 const Type *ValTy = EltTy;
748 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
749 ValTy = VTy->getElementType();
750
751 // Construct an integer with the right value.
752 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
753 APInt OneVal(EltSize, CI->getZExtValue());
754 APInt TotalVal(OneVal);
755 // Set each byte.
756 for (unsigned i = 0; 8*i < EltSize; ++i) {
757 TotalVal = TotalVal.shl(8);
758 TotalVal |= OneVal;
759 }
760
761 // Convert the integer value to the appropriate type.
762 StoreVal = ConstantInt::get(TotalVal);
763 if (isa<PointerType>(ValTy))
764 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
765 else if (ValTy->isFloatingPoint())
766 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
767 assert(StoreVal->getType() == ValTy && "Type mismatch!");
768
769 // If the requested value was a vector constant, create it.
770 if (EltTy != ValTy) {
771 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
772 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
773 StoreVal = ConstantVector::get(&Elts[0], NumElts);
774 }
775 }
776 new StoreInst(StoreVal, EltPtr, MI);
777 continue;
778 }
779 // Otherwise, if we're storing a byte variable, use a memset call for
780 // this element.
781 }
782
783 // Cast the element pointer to BytePtrTy.
784 if (EltPtr->getType() != BytePtrTy)
785 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
786
787 // Cast the other pointer (if we have one) to BytePtrTy.
788 if (OtherElt && OtherElt->getType() != BytePtrTy)
789 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
790 MI);
791
792 unsigned EltSize = TD->getABITypeSize(EltTy);
793
794 // Finally, insert the meminst for this element.
795 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
796 Value *Ops[] = {
797 SROADest ? EltPtr : OtherElt, // Dest ptr
798 SROADest ? OtherElt : EltPtr, // Src ptr
799 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
800 Zero // Align
801 };
802 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
803 } else {
804 assert(isa<MemSetInst>(MI));
805 Value *Ops[] = {
806 EltPtr, MI->getOperand(2), // Dest, Value,
807 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
808 Zero // Align
809 };
810 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
811 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000812 }
Chris Lattner71c75342009-01-07 08:11:13 +0000813 MI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000814}
Chris Lattner71c75342009-01-07 08:11:13 +0000815
816/// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
817/// overwrites the entire allocation. Extract out the pieces of the stored
818/// integer and store them individually.
819void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
820 AllocationInst *AI,
821 SmallVector<AllocaInst*, 32> &NewElts){
822 // Extract each element out of the integer according to its structure offset
823 // and store the element value to the individual alloca.
824 Value *SrcVal = SI->getOperand(0);
825 const Type *AllocaEltTy = AI->getType()->getElementType();
826 uint64_t AllocaSizeBits = TD->getABITypeSizeInBits(AllocaEltTy);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000827
Chris Lattner71c75342009-01-07 08:11:13 +0000828 // If this isn't a store of an integer to the whole alloca, it may be a store
829 // to the first element. Just ignore the store in this case and normal SROA
830 // will handle it.
831 if (!isa<IntegerType>(SrcVal->getType()) ||
832 TD->getABITypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
833 return;
834
835 DOUT << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI;
836
837 // There are two forms here: AI could be an array or struct. Both cases
838 // have different ways to compute the element offset.
839 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
840 const StructLayout *Layout = TD->getStructLayout(EltSTy);
841
842 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
843 // Get the number of bits to shift SrcVal to get the value.
844 const Type *FieldTy = EltSTy->getElementType(i);
845 uint64_t Shift = Layout->getElementOffsetInBits(i);
846
847 if (TD->isBigEndian())
848 Shift = AllocaSizeBits-Shift-TD->getABITypeSizeInBits(FieldTy);
849
850 Value *EltVal = SrcVal;
851 if (Shift) {
852 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
853 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
854 "sroa.store.elt", SI);
855 }
856
857 // Truncate down to an integer of the right size.
858 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
859 if (FieldSizeBits != AllocaSizeBits)
860 EltVal = new TruncInst(EltVal, IntegerType::get(FieldSizeBits), "", SI);
861 Value *DestField = NewElts[i];
862 if (EltVal->getType() == FieldTy) {
863 // Storing to an integer field of this size, just do it.
864 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
865 // Bitcast to the right element type (for fp/vector values).
866 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
867 } else {
868 // Otherwise, bitcast the dest pointer (for aggregates).
869 DestField = new BitCastInst(DestField,
870 PointerType::getUnqual(EltVal->getType()),
871 "", SI);
872 }
873 new StoreInst(EltVal, DestField, SI);
874 }
875
876 } else {
877 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
878 const Type *ArrayEltTy = ATy->getElementType();
879 uint64_t ElementOffset = TD->getABITypeSizeInBits(ArrayEltTy);
880 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
881
882 uint64_t Shift;
883
884 if (TD->isBigEndian())
885 Shift = AllocaSizeBits-ElementOffset;
886 else
887 Shift = 0;
888
889 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
890
891 Value *EltVal = SrcVal;
892 if (Shift) {
893 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
894 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
895 "sroa.store.elt", SI);
896 }
897
898 // Truncate down to an integer of the right size.
899 if (ElementSizeBits != AllocaSizeBits)
900 EltVal = new TruncInst(EltVal, IntegerType::get(ElementSizeBits),"",SI);
901 Value *DestField = NewElts[i];
902 if (EltVal->getType() == ArrayEltTy) {
903 // Storing to an integer field of this size, just do it.
904 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
905 // Bitcast to the right element type (for fp/vector values).
906 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
907 } else {
908 // Otherwise, bitcast the dest pointer (for aggregates).
909 DestField = new BitCastInst(DestField,
910 PointerType::getUnqual(EltVal->getType()),
911 "", SI);
912 }
913 new StoreInst(EltVal, DestField, SI);
914
915 if (TD->isBigEndian())
916 Shift -= ElementOffset;
917 else
918 Shift += ElementOffset;
919 }
920 }
921
922 SI->eraseFromParent();
923}
924
Chris Lattner28401db2009-01-08 05:42:05 +0000925/// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to
926/// an integer. Load the individual pieces to form the aggregate value.
927void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
928 SmallVector<AllocaInst*, 32> &NewElts) {
929 // Extract each element out of the NewElts according to its structure offset
930 // and form the result value.
931 const Type *AllocaEltTy = AI->getType()->getElementType();
932 uint64_t AllocaSizeBits = TD->getABITypeSizeInBits(AllocaEltTy);
933
934 // If this isn't a load of the whole alloca to an integer, it may be a load
935 // of the first element. Just ignore the load in this case and normal SROA
936 // will handle it.
937 if (!isa<IntegerType>(LI->getType()) ||
938 TD->getABITypeSizeInBits(LI->getType()) != AllocaSizeBits)
939 return;
940
941 DOUT << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << *LI;
942
943 // There are two forms here: AI could be an array or struct. Both cases
944 // have different ways to compute the element offset.
945 const StructLayout *Layout = 0;
946 uint64_t ArrayEltBitOffset = 0;
947 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
948 Layout = TD->getStructLayout(EltSTy);
949 } else {
950 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
951 ArrayEltBitOffset = TD->getABITypeSizeInBits(ArrayEltTy);
952 }
953
954 Value *ResultVal = Constant::getNullValue(LI->getType());
955
956 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
957 // Load the value from the alloca. If the NewElt is an aggregate, cast
958 // the pointer to an integer of the same size before doing the load.
959 Value *SrcField = NewElts[i];
960 const Type *FieldTy =
961 cast<PointerType>(SrcField->getType())->getElementType();
962 const IntegerType *FieldIntTy =
963 IntegerType::get(TD->getTypeSizeInBits(FieldTy));
964 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
965 !isa<VectorType>(FieldTy))
966 SrcField = new BitCastInst(SrcField, PointerType::getUnqual(FieldIntTy),
967 "", LI);
968 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
969
970 // If SrcField is a fp or vector of the right size but that isn't an
971 // integer type, bitcast to an integer so we can shift it.
972 if (SrcField->getType() != FieldIntTy)
973 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
974
975 // Zero extend the field to be the same size as the final alloca so that
976 // we can shift and insert it.
977 if (SrcField->getType() != ResultVal->getType())
978 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
979
980 // Determine the number of bits to shift SrcField.
981 uint64_t Shift;
982 if (Layout) // Struct case.
983 Shift = Layout->getElementOffsetInBits(i);
984 else // Array case.
985 Shift = i*ArrayEltBitOffset;
986
987 if (TD->isBigEndian())
988 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
989
990 if (Shift) {
991 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
992 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
993 }
994
995 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
996 }
997
998 LI->replaceAllUsesWith(ResultVal);
999 LI->eraseFromParent();
1000}
1001
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002
Duncan Sandsae5fd622007-11-04 14:43:57 +00001003/// HasPadding - Return true if the specified type has any structure or
1004/// alignment padding, false otherwise.
Duncan Sands4afc5752008-06-04 08:21:45 +00001005static bool HasPadding(const Type *Ty, const TargetData &TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001006 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1007 const StructLayout *SL = TD.getStructLayout(STy);
1008 unsigned PrevFieldBitOffset = 0;
1009 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sandsae5fd622007-11-04 14:43:57 +00001010 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1011
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012 // Padding in sub-elements?
Duncan Sands4afc5752008-06-04 08:21:45 +00001013 if (HasPadding(STy->getElementType(i), TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001014 return true;
Duncan Sandsae5fd622007-11-04 14:43:57 +00001015
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001016 // Check to see if there is any padding between this element and the
1017 // previous one.
1018 if (i) {
Duncan Sandsae5fd622007-11-04 14:43:57 +00001019 unsigned PrevFieldEnd =
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001020 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1021 if (PrevFieldEnd < FieldBitOffset)
1022 return true;
1023 }
Duncan Sandsae5fd622007-11-04 14:43:57 +00001024
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001025 PrevFieldBitOffset = FieldBitOffset;
1026 }
Duncan Sandsae5fd622007-11-04 14:43:57 +00001027
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001028 // Check for tail padding.
1029 if (unsigned EltCount = STy->getNumElements()) {
1030 unsigned PrevFieldEnd = PrevFieldBitOffset +
1031 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sandsae5fd622007-11-04 14:43:57 +00001032 if (PrevFieldEnd < SL->getSizeInBits())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001033 return true;
1034 }
1035
1036 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sands4afc5752008-06-04 08:21:45 +00001037 return HasPadding(ATy->getElementType(), TD);
Duncan Sandsae5fd622007-11-04 14:43:57 +00001038 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sands4afc5752008-06-04 08:21:45 +00001039 return HasPadding(VTy->getElementType(), TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001040 }
Duncan Sands4afc5752008-06-04 08:21:45 +00001041 return TD.getTypeSizeInBits(Ty) != TD.getABITypeSizeInBits(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001042}
1043
1044/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1045/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1046/// or 1 if safe after canonicalization has been performed.
1047///
1048int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
1049 // Loop over the use list of the alloca. We can only transform it if all of
1050 // the users are safe to transform.
1051 AllocaInfo Info;
1052
1053 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
1054 I != E; ++I) {
1055 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1056 if (Info.isUnsafe) {
1057 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
1058 return 0;
1059 }
1060 }
1061
1062 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1063 // source and destination, we have to be careful. In particular, the memcpy
1064 // could be moving around elements that live in structure padding of the LLVM
1065 // types, but may actually be used. In these cases, we refuse to promote the
1066 // struct.
1067 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Chris Lattner3fd59362009-01-07 06:34:28 +00001068 HasPadding(AI->getType()->getElementType(), *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001069 return 0;
Duncan Sandsae5fd622007-11-04 14:43:57 +00001070
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001071 // If we require cleanup, return 1, otherwise return 3.
1072 return Info.needsCanon ? 1 : 3;
1073}
1074
1075/// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
1076/// allocation, but only if cleaned up, perform the cleanups required.
1077void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
1078 // At this point, we know that the end result will be SROA'd and promoted, so
1079 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1080 // up.
1081 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1082 UI != E; ) {
1083 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
1084 if (!GEPI) continue;
1085 gep_type_iterator I = gep_type_begin(GEPI);
1086 ++I;
1087
1088 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
1089 uint64_t NumElements = AT->getNumElements();
1090
1091 if (!isa<ConstantInt>(I.getOperand())) {
1092 if (NumElements == 1) {
1093 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
1094 } else {
1095 assert(NumElements == 2 && "Unhandled case!");
1096 // All users of the GEP must be loads. At each use of the GEP, insert
1097 // two loads of the appropriate indexed GEP and select between them.
1098 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
1099 Constant::getNullValue(I.getOperand()->getType()),
1100 "isone", GEPI);
1101 // Insert the new GEP instructions, which are properly indexed.
1102 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
1103 Indices[1] = Constant::getNullValue(Type::Int32Ty);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001104 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1105 Indices.begin(),
1106 Indices.end(),
1107 GEPI->getName()+".0", GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001109 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1110 Indices.begin(),
1111 Indices.end(),
1112 GEPI->getName()+".1", GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001113 // Replace all loads of the variable index GEP with loads from both
1114 // indexes and a select.
1115 while (!GEPI->use_empty()) {
1116 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1117 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1118 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001119 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001120 LI->replaceAllUsesWith(R);
1121 LI->eraseFromParent();
1122 }
1123 GEPI->eraseFromParent();
1124 }
1125 }
1126 }
1127 }
1128}
1129
1130/// MergeInType - Add the 'In' type to the accumulated type so far. If the
1131/// types are incompatible, return true, otherwise update Accum and return
1132/// false.
1133///
1134/// There are three cases we handle here:
1135/// 1) An effectively-integer union, where the pieces are stored into as
1136/// smaller integers (common with byte swap and other idioms).
1137/// 2) A union of vector types of the same size and potentially its elements.
1138/// Here we turn element accesses into insert/extract element operations.
1139/// 3) A union of scalar types, such as int/float or int/pointer. Here we
1140/// merge together into integers, allowing the xform to work with #1 as
1141/// well.
1142static bool MergeInType(const Type *In, const Type *&Accum,
1143 const TargetData &TD) {
1144 // If this is our first type, just use it.
1145 const VectorType *PTy;
1146 if (Accum == Type::VoidTy || In == Accum) {
1147 Accum = In;
1148 } else if (In == Type::VoidTy) {
1149 // Noop.
1150 } else if (In->isInteger() && Accum->isInteger()) { // integer union.
1151 // Otherwise pick whichever type is larger.
1152 if (cast<IntegerType>(In)->getBitWidth() >
1153 cast<IntegerType>(Accum)->getBitWidth())
1154 Accum = In;
1155 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
1156 // Pointer unions just stay as one of the pointers.
1157 } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
1158 if ((PTy = dyn_cast<VectorType>(Accum)) &&
1159 PTy->getElementType() == In) {
1160 // Accum is a vector, and we are accessing an element: ok.
1161 } else if ((PTy = dyn_cast<VectorType>(In)) &&
1162 PTy->getElementType() == Accum) {
1163 // In is a vector, and accum is an element: ok, remember In.
1164 Accum = In;
1165 } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
1166 PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
1167 // Two vectors of the same size: keep Accum.
1168 } else {
1169 // Cannot insert an short into a <4 x int> or handle
1170 // <2 x int> -> <4 x int>
1171 return true;
1172 }
1173 } else {
1174 // Pointer/FP/Integer unions merge together as integers.
1175 switch (Accum->getTypeID()) {
1176 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
1177 case Type::FloatTyID: Accum = Type::Int32Ty; break;
1178 case Type::DoubleTyID: Accum = Type::Int64Ty; break;
Dale Johannesen4c839d02007-09-28 00:21:38 +00001179 case Type::X86_FP80TyID: return true;
1180 case Type::FP128TyID: return true;
1181 case Type::PPC_FP128TyID: return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001182 default:
1183 assert(Accum->isInteger() && "Unknown FP type!");
1184 break;
1185 }
1186
1187 switch (In->getTypeID()) {
1188 case Type::PointerTyID: In = TD.getIntPtrType(); break;
1189 case Type::FloatTyID: In = Type::Int32Ty; break;
1190 case Type::DoubleTyID: In = Type::Int64Ty; break;
Dale Johannesen4c839d02007-09-28 00:21:38 +00001191 case Type::X86_FP80TyID: return true;
1192 case Type::FP128TyID: return true;
1193 case Type::PPC_FP128TyID: return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001194 default:
1195 assert(In->isInteger() && "Unknown FP type!");
1196 break;
1197 }
1198 return MergeInType(In, Accum, TD);
1199 }
1200 return false;
1201}
1202
Chris Lattner3fd59362009-01-07 06:34:28 +00001203/// getIntAtLeastAsBigAs - Return an integer type that is at least as big as the
1204/// specified type. If there is no suitable type, this returns null.
1205const Type *getIntAtLeastAsBigAs(unsigned NumBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001206 if (NumBits > 64) return 0;
1207 if (NumBits > 32) return Type::Int64Ty;
1208 if (NumBits > 16) return Type::Int32Ty;
1209 if (NumBits > 8) return Type::Int16Ty;
1210 return Type::Int8Ty;
1211}
1212
1213/// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
1214/// single scalar integer type, return that type. Further, if the use is not
1215/// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
1216/// there are no uses of this pointer, return Type::VoidTy to differentiate from
1217/// failure.
1218///
1219const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
1220 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001221 const PointerType *PTy = cast<PointerType>(V->getType());
1222
1223 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1224 Instruction *User = cast<Instruction>(*UI);
1225
1226 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Matthijs Kooijman001006a2008-06-05 12:51:53 +00001227 // FIXME: Loads of a first class aggregrate value could be converted to a
1228 // series of loads and insertvalues
1229 if (!LI->getType()->isSingleValueType())
1230 return 0;
1231
Chris Lattner3fd59362009-01-07 06:34:28 +00001232 if (MergeInType(LI->getType(), UsedType, *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001233 return 0;
Chris Lattner7cc97712009-01-07 06:39:58 +00001234 continue;
1235 }
1236
1237 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001238 // Storing the pointer, not into the value?
1239 if (SI->getOperand(0) == V) return 0;
Matthijs Kooijman001006a2008-06-05 12:51:53 +00001240
1241 // FIXME: Stores of a first class aggregrate value could be converted to a
1242 // series of extractvalues and stores
1243 if (!SI->getOperand(0)->getType()->isSingleValueType())
1244 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001245
1246 // NOTE: We could handle storing of FP imms into integers here!
1247
Chris Lattner3fd59362009-01-07 06:34:28 +00001248 if (MergeInType(SI->getOperand(0)->getType(), UsedType, *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001249 return 0;
Chris Lattner7cc97712009-01-07 06:39:58 +00001250 continue;
1251 }
1252 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001253 IsNotTrivial = true;
1254 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
Chris Lattner3fd59362009-01-07 06:34:28 +00001255 if (!SubTy || MergeInType(SubTy, UsedType, *TD)) return 0;
Chris Lattner7cc97712009-01-07 06:39:58 +00001256 continue;
1257 }
1258
1259 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001260 // Check to see if this is stepping over an element: GEP Ptr, int C
1261 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
1262 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
Chris Lattner3fd59362009-01-07 06:34:28 +00001263 unsigned ElSize = TD->getABITypeSize(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264 unsigned BitOffset = Idx*ElSize*8;
1265 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
1266
1267 IsNotTrivial = true;
1268 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
1269 if (SubElt == 0) return 0;
1270 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
1271 const Type *NewTy =
Chris Lattner3fd59362009-01-07 06:34:28 +00001272 getIntAtLeastAsBigAs(TD->getABITypeSizeInBits(SubElt)+BitOffset);
1273 if (NewTy == 0 || MergeInType(NewTy, UsedType, *TD)) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 continue;
1275 }
Chris Lattner7cc97712009-01-07 06:39:58 +00001276 // Cannot handle this!
1277 return 0;
1278 }
1279
1280 if (GEP->getNumOperands() == 3 &&
1281 isa<ConstantInt>(GEP->getOperand(1)) &&
1282 isa<ConstantInt>(GEP->getOperand(2)) &&
1283 cast<ConstantInt>(GEP->getOperand(1))->isZero()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001284 // We are stepping into an element, e.g. a structure or an array:
Chris Lattner85591c62009-01-07 06:25:07 +00001285 // GEP Ptr, i32 0, i32 Cst
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001286 const Type *AggTy = PTy->getElementType();
1287 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1288
1289 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
1290 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
1291 } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
1292 // Getting an element of the vector.
1293 if (Idx >= VectorTy->getNumElements()) return 0; // Out of range.
1294
1295 // Merge in the vector type.
Chris Lattner3fd59362009-01-07 06:34:28 +00001296 if (MergeInType(VectorTy, UsedType, *TD)) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001297
1298 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1299 if (SubTy == 0) return 0;
1300
Chris Lattner3fd59362009-01-07 06:34:28 +00001301 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001302 return 0;
1303
1304 // We'll need to change this to an insert/extract element operation.
1305 IsNotTrivial = true;
1306 continue; // Everything looks ok
1307
1308 } else if (isa<StructType>(AggTy)) {
1309 // Structs are always ok.
1310 } else {
1311 return 0;
1312 }
Chris Lattner3fd59362009-01-07 06:34:28 +00001313 const Type *NTy = getIntAtLeastAsBigAs(TD->getABITypeSizeInBits(AggTy));
1314 if (NTy == 0 || MergeInType(NTy, UsedType, *TD)) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001315 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1316 if (SubTy == 0) return 0;
Chris Lattner3fd59362009-01-07 06:34:28 +00001317 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318 return 0;
1319 continue; // Everything looks ok
1320 }
1321 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322 }
Chris Lattner7cc97712009-01-07 06:39:58 +00001323
1324 // Cannot handle this!
1325 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001326 }
1327
1328 return UsedType;
1329}
1330
1331/// ConvertToScalar - The specified alloca passes the CanConvertToScalar
1332/// predicate and is non-trivial. Convert it to something that can be trivially
1333/// promoted into a register by mem2reg.
1334void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
1335 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
1336 << *ActualTy << "\n";
1337 ++NumConverted;
1338
1339 BasicBlock *EntryBlock = AI->getParent();
1340 assert(EntryBlock == &EntryBlock->getParent()->getEntryBlock() &&
1341 "Not in the entry block!");
1342 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
1343
1344 // Create and insert the alloca.
1345 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
1346 EntryBlock->begin());
1347 ConvertUsesToScalar(AI, NewAI, 0);
1348 delete AI;
1349}
1350
1351
1352/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1353/// directly. This happens when we are converting an "integer union" to a
1354/// single integer scalar, or when we are converting a "vector union" to a
1355/// vector with insert/extractelement instructions.
1356///
1357/// Offset is an offset from the original alloca, in bits that need to be
1358/// shifted to the right. By the end of this, there should be no uses of Ptr.
1359void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001360 while (!Ptr->use_empty()) {
1361 Instruction *User = cast<Instruction>(Ptr->use_back());
1362
1363 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner41d58652008-02-29 07:03:13 +00001364 Value *NV = ConvertUsesOfLoadToScalar(LI, NewAI, Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001365 LI->replaceAllUsesWith(NV);
1366 LI->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001367 continue;
1368 }
1369
1370 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001371 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1372
Chris Lattner41d58652008-02-29 07:03:13 +00001373 Value *SV = ConvertUsesOfStoreToScalar(SI, NewAI, Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001374 new StoreInst(SV, NewAI, SI);
1375 SI->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001376 continue;
1377 }
1378
1379 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb1534532008-01-30 00:39:15 +00001380 ConvertUsesToScalar(CI, NewAI, Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001381 CI->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001382 continue;
1383 }
1384
1385 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001386 const PointerType *AggPtrTy =
1387 cast<PointerType>(GEP->getOperand(0)->getType());
Duncan Sandsae5fd622007-11-04 14:43:57 +00001388 unsigned AggSizeInBits =
Chris Lattner3fd59362009-01-07 06:34:28 +00001389 TD->getABITypeSizeInBits(AggPtrTy->getElementType());
Duncan Sandsae5fd622007-11-04 14:43:57 +00001390
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001391 // Check to see if this is stepping over an element: GEP Ptr, int C
1392 unsigned NewOffset = Offset;
1393 if (GEP->getNumOperands() == 2) {
1394 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1395 unsigned BitOffset = Idx*AggSizeInBits;
1396
1397 NewOffset += BitOffset;
Chris Lattner7cc97712009-01-07 06:39:58 +00001398 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1399 GEP->eraseFromParent();
1400 continue;
1401 }
1402
1403 assert(GEP->getNumOperands() == 3 && "Unsupported operation");
1404
1405 // We know that operand #2 is zero.
1406 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1407 const Type *AggTy = AggPtrTy->getElementType();
1408 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
1409 unsigned ElSizeBits =
1410 TD->getABITypeSizeInBits(SeqTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001411
Chris Lattner7cc97712009-01-07 06:39:58 +00001412 NewOffset += ElSizeBits*Idx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001413 } else {
Chris Lattner7cc97712009-01-07 06:39:58 +00001414 const StructType *STy = cast<StructType>(AggTy);
1415 unsigned EltBitOffset =
1416 TD->getStructLayout(STy)->getElementOffsetInBits(Idx);
1417
1418 NewOffset += EltBitOffset;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001419 }
1420 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1421 GEP->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001422 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001423 }
Chris Lattner7cc97712009-01-07 06:39:58 +00001424
1425 assert(0 && "Unsupported operation!");
1426 abort();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001427 }
1428}
1429
Chris Lattner41d58652008-02-29 07:03:13 +00001430/// ConvertUsesOfLoadToScalar - Convert all of the users the specified load to
1431/// use the new alloca directly, returning the value that should replace the
1432/// load. This happens when we are converting an "integer union" to a
1433/// single integer scalar, or when we are converting a "vector union" to a
1434/// vector with insert/extractelement instructions.
1435///
1436/// Offset is an offset from the original alloca, in bits that need to be
1437/// shifted to the right. By the end of this, there should be no uses of Ptr.
1438Value *SROA::ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
1439 unsigned Offset) {
1440 // The load is a bit extract from NewAI shifted right by Offset bits.
1441 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
1442
1443 if (NV->getType() == LI->getType() && Offset == 0) {
1444 // We win, no conversion needed.
1445 return NV;
1446 }
Chris Lattner5f062542008-02-29 07:12:06 +00001447
1448 // If the result type of the 'union' is a pointer, then this must be ptr->ptr
1449 // cast. Anything else would result in NV being an integer.
1450 if (isa<PointerType>(NV->getType())) {
1451 assert(isa<PointerType>(LI->getType()));
1452 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1453 }
Chris Lattner41d58652008-02-29 07:03:13 +00001454
Chris Lattner5f062542008-02-29 07:12:06 +00001455 if (const VectorType *VTy = dyn_cast<VectorType>(NV->getType())) {
Chris Lattner41d58652008-02-29 07:03:13 +00001456 // If the result alloca is a vector type, this is either an element
1457 // access or a bitcast to another vector type.
Chris Lattner5f062542008-02-29 07:12:06 +00001458 if (isa<VectorType>(LI->getType()))
1459 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1460
1461 // Otherwise it must be an element access.
Chris Lattner5f062542008-02-29 07:12:06 +00001462 unsigned Elt = 0;
1463 if (Offset) {
Chris Lattner3fd59362009-01-07 06:34:28 +00001464 unsigned EltSize = TD->getABITypeSizeInBits(VTy->getElementType());
Chris Lattner5f062542008-02-29 07:12:06 +00001465 Elt = Offset/EltSize;
1466 Offset -= EltSize*Elt;
Chris Lattner41d58652008-02-29 07:03:13 +00001467 }
Chris Lattner5f062542008-02-29 07:12:06 +00001468 NV = new ExtractElementInst(NV, ConstantInt::get(Type::Int32Ty, Elt),
1469 "tmp", LI);
1470
1471 // If we're done, return this element.
1472 if (NV->getType() == LI->getType() && Offset == 0)
1473 return NV;
1474 }
1475
1476 const IntegerType *NTy = cast<IntegerType>(NV->getType());
1477
1478 // If this is a big-endian system and the load is narrower than the
1479 // full alloca type, we need to do a shift to get the right bits.
1480 int ShAmt = 0;
Chris Lattner3fd59362009-01-07 06:34:28 +00001481 if (TD->isBigEndian()) {
Chris Lattner5f062542008-02-29 07:12:06 +00001482 // On big-endian machines, the lowest bit is stored at the bit offset
1483 // from the pointer given by getTypeStoreSizeInBits. This matters for
1484 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner3fd59362009-01-07 06:34:28 +00001485 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
1486 TD->getTypeStoreSizeInBits(LI->getType()) - Offset;
Chris Lattner5f062542008-02-29 07:12:06 +00001487 } else {
1488 ShAmt = Offset;
1489 }
1490
1491 // Note: we support negative bitwidths (with shl) which are not defined.
1492 // We do this to support (f.e.) loads off the end of a structure where
1493 // only some bits are used.
1494 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Gabor Greifa645dd32008-05-16 19:29:10 +00001495 NV = BinaryOperator::CreateLShr(NV,
Chris Lattner5f062542008-02-29 07:12:06 +00001496 ConstantInt::get(NV->getType(),ShAmt),
1497 LI->getName(), LI);
1498 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Gabor Greifa645dd32008-05-16 19:29:10 +00001499 NV = BinaryOperator::CreateShl(NV,
Chris Lattner5f062542008-02-29 07:12:06 +00001500 ConstantInt::get(NV->getType(),-ShAmt),
1501 LI->getName(), LI);
1502
1503 // Finally, unconditionally truncate the integer to the right width.
Chris Lattner3fd59362009-01-07 06:34:28 +00001504 unsigned LIBitWidth = TD->getTypeSizeInBits(LI->getType());
Chris Lattner5f062542008-02-29 07:12:06 +00001505 if (LIBitWidth < NTy->getBitWidth())
1506 NV = new TruncInst(NV, IntegerType::get(LIBitWidth),
1507 LI->getName(), LI);
1508
1509 // If the result is an integer, this is a trunc or bitcast.
1510 if (isa<IntegerType>(LI->getType())) {
1511 // Should be done.
1512 } else if (LI->getType()->isFloatingPoint()) {
1513 // Just do a bitcast, we know the sizes match up.
Chris Lattner41d58652008-02-29 07:03:13 +00001514 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1515 } else {
Chris Lattner5f062542008-02-29 07:12:06 +00001516 // Otherwise must be a pointer.
1517 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
Chris Lattner41d58652008-02-29 07:03:13 +00001518 }
Chris Lattner5f062542008-02-29 07:12:06 +00001519 assert(NV->getType() == LI->getType() && "Didn't convert right?");
Chris Lattner41d58652008-02-29 07:03:13 +00001520 return NV;
1521}
1522
1523
1524/// ConvertUsesOfStoreToScalar - Convert the specified store to a load+store
1525/// pair of the new alloca directly, returning the value that should be stored
1526/// to the alloca. This happens when we are converting an "integer union" to a
1527/// single integer scalar, or when we are converting a "vector union" to a
1528/// vector with insert/extractelement instructions.
1529///
1530/// Offset is an offset from the original alloca, in bits that need to be
1531/// shifted to the right. By the end of this, there should be no uses of Ptr.
1532Value *SROA::ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
1533 unsigned Offset) {
1534
1535 // Convert the stored type to the actual type, shift it left to insert
1536 // then 'or' into place.
1537 Value *SV = SI->getOperand(0);
1538 const Type *AllocaType = NewAI->getType()->getElementType();
1539 if (SV->getType() == AllocaType && Offset == 0) {
1540 // All is well.
1541 } else if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
1542 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1543
1544 // If the result alloca is a vector type, this is either an element
1545 // access or a bitcast to another vector type.
1546 if (isa<VectorType>(SV->getType())) {
1547 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1548 } else {
1549 // Must be an element insertion.
Chris Lattner3fd59362009-01-07 06:34:28 +00001550 unsigned Elt = Offset/TD->getABITypeSizeInBits(PTy->getElementType());
Gabor Greifd6da1d02008-04-06 20:25:17 +00001551 SV = InsertElementInst::Create(Old, SV,
1552 ConstantInt::get(Type::Int32Ty, Elt),
1553 "tmp", SI);
Chris Lattner41d58652008-02-29 07:03:13 +00001554 }
1555 } else if (isa<PointerType>(AllocaType)) {
1556 // If the alloca type is a pointer, then all the elements must be
1557 // pointers.
1558 if (SV->getType() != AllocaType)
1559 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1560 } else {
1561 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1562
1563 // If SV is a float, convert it to the appropriate integer type.
1564 // If it is a pointer, do the same, and also handle ptr->ptr casts
1565 // here.
Chris Lattner3fd59362009-01-07 06:34:28 +00001566 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1567 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1568 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1569 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
Chris Lattner41d58652008-02-29 07:03:13 +00001570 if (SV->getType()->isFloatingPoint())
1571 SV = new BitCastInst(SV, IntegerType::get(SrcWidth),
1572 SV->getName(), SI);
1573 else if (isa<PointerType>(SV->getType()))
Chris Lattner3fd59362009-01-07 06:34:28 +00001574 SV = new PtrToIntInst(SV, TD->getIntPtrType(), SV->getName(), SI);
Chris Lattner41d58652008-02-29 07:03:13 +00001575
1576 // Always zero extend the value if needed.
1577 if (SV->getType() != AllocaType)
1578 SV = new ZExtInst(SV, AllocaType, SV->getName(), SI);
1579
1580 // If this is a big-endian system and the store is narrower than the
1581 // full alloca type, we need to do a shift to get the right bits.
1582 int ShAmt = 0;
Chris Lattner3fd59362009-01-07 06:34:28 +00001583 if (TD->isBigEndian()) {
Chris Lattner41d58652008-02-29 07:03:13 +00001584 // On big-endian machines, the lowest bit is stored at the bit offset
1585 // from the pointer given by getTypeStoreSizeInBits. This matters for
1586 // integers with a bitwidth that is not a multiple of 8.
1587 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1588 } else {
1589 ShAmt = Offset;
1590 }
1591
1592 // Note: we support negative bitwidths (with shr) which are not defined.
1593 // We do this to support (f.e.) stores off the end of a structure where
1594 // only some bits in the structure are set.
1595 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1596 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Gabor Greifa645dd32008-05-16 19:29:10 +00001597 SV = BinaryOperator::CreateShl(SV,
Chris Lattner41d58652008-02-29 07:03:13 +00001598 ConstantInt::get(SV->getType(), ShAmt),
1599 SV->getName(), SI);
1600 Mask <<= ShAmt;
1601 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Gabor Greifa645dd32008-05-16 19:29:10 +00001602 SV = BinaryOperator::CreateLShr(SV,
Chris Lattner41d58652008-02-29 07:03:13 +00001603 ConstantInt::get(SV->getType(),-ShAmt),
1604 SV->getName(), SI);
1605 Mask = Mask.lshr(ShAmt);
1606 }
1607
1608 // Mask out the bits we are about to insert from the old value, and or
1609 // in the new bits.
1610 if (SrcWidth != DestWidth) {
1611 assert(DestWidth > SrcWidth);
Gabor Greifa645dd32008-05-16 19:29:10 +00001612 Old = BinaryOperator::CreateAnd(Old, ConstantInt::get(~Mask),
Chris Lattner41d58652008-02-29 07:03:13 +00001613 Old->getName()+".mask", SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00001614 SV = BinaryOperator::CreateOr(Old, SV, SV->getName()+".ins", SI);
Chris Lattner41d58652008-02-29 07:03:13 +00001615 }
1616 }
1617 return SV;
1618}
1619
1620
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001621
1622/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1623/// some part of a constant global variable. This intentionally only accepts
1624/// constant expressions because we don't can't rewrite arbitrary instructions.
1625static bool PointsToConstantGlobal(Value *V) {
1626 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1627 return GV->isConstant();
1628 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1629 if (CE->getOpcode() == Instruction::BitCast ||
1630 CE->getOpcode() == Instruction::GetElementPtr)
1631 return PointsToConstantGlobal(CE->getOperand(0));
1632 return false;
1633}
1634
1635/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1636/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1637/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1638/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1639/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1640/// the alloca, and if the source pointer is a pointer to a constant global, we
1641/// can optimize this.
1642static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1643 bool isOffset) {
1644 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1645 if (isa<LoadInst>(*UI)) {
1646 // Ignore loads, they are always ok.
1647 continue;
1648 }
1649 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1650 // If uses of the bitcast are ok, we are ok.
1651 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1652 return false;
1653 continue;
1654 }
1655 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1656 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1657 // doesn't, it does.
1658 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1659 isOffset || !GEP->hasAllZeroIndices()))
1660 return false;
1661 continue;
1662 }
1663
1664 // If this is isn't our memcpy/memmove, reject it as something we can't
1665 // handle.
1666 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1667 return false;
1668
1669 // If we already have seen a copy, reject the second one.
1670 if (TheCopy) return false;
1671
1672 // If the pointer has been offset from the start of the alloca, we can't
1673 // safely handle this.
1674 if (isOffset) return false;
1675
1676 // If the memintrinsic isn't using the alloca as the dest, reject it.
1677 if (UI.getOperandNo() != 1) return false;
1678
1679 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1680
1681 // If the source of the memcpy/move is not a constant global, reject it.
1682 if (!PointsToConstantGlobal(MI->getOperand(2)))
1683 return false;
1684
1685 // Otherwise, the transform is safe. Remember the copy instruction.
1686 TheCopy = MI;
1687 }
1688 return true;
1689}
1690
1691/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1692/// modified by a copy from a constant global. If we can prove this, we can
1693/// replace any uses of the alloca with uses of the global directly.
1694Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1695 Instruction *TheCopy = 0;
1696 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1697 return TheCopy;
1698 return 0;
1699}