blob: 589aa35d9c605501e3569b581a7936fa944065c4 [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,
Chris Lattner70ffe572009-01-28 20:16:43 +0000126 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
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227 // Check to see if we can perform the core SROA transformation. We cannot
228 // transform the allocation instruction if it is an array allocation
229 // (allocations OF arrays are ok though), and an allocation of a scalar
230 // value cannot be decomposed at all.
231 if (!AI->isArrayAllocation() &&
232 (isa<StructType>(AI->getAllocatedType()) ||
233 isa<ArrayType>(AI->getAllocatedType())) &&
234 AI->getAllocatedType()->isSized() &&
Chris Lattner0e99e692008-06-22 17:46:21 +0000235 // Do not promote any struct whose size is larger than "128" bytes.
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000236 TD->getTypePaddedSize(AI->getAllocatedType()) < SRThreshold &&
Chris Lattner0e99e692008-06-22 17:46:21 +0000237 // Do not promote any struct into more than "32" separate vars.
238 getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 // Check that all of the users of the allocation are capable of being
240 // transformed.
241 switch (isSafeAllocaToScalarRepl(AI)) {
242 default: assert(0 && "Unexpected value!");
243 case 0: // Not safe to scalar replace.
244 break;
245 case 1: // Safe, but requires cleanup/canonicalizations first
246 CanonicalizeAllocaUsers(AI);
247 // FALL THROUGH.
248 case 3: // Safe to scalar replace.
249 DoScalarReplacement(AI, WorkList);
250 Changed = true;
251 continue;
252 }
253 }
254
255 // Check to see if this allocation is only modified by a memcpy/memmove from
256 // a constant global. If this is the case, we can change all users to use
257 // the constant global instead. This is commonly produced by the CFE by
258 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
259 // is only subsequently read.
260 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
261 DOUT << "Found alloca equal to global: " << *AI;
262 DOUT << " memcpy = " << *TheCopy;
263 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
264 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
265 TheCopy->eraseFromParent(); // Don't mutate the global.
266 AI->eraseFromParent();
267 ++NumGlobals;
268 Changed = true;
269 continue;
270 }
Chris Lattner70ffe572009-01-28 20:16:43 +0000271
272 // If we can turn this aggregate value (potentially with casts) into a
273 // simple scalar value that can be mem2reg'd into a register value.
274 bool IsNotTrivial = false;
275 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
276 if (IsNotTrivial && ActualType != Type::VoidTy) {
277 ConvertToScalar(AI, ActualType);
278 Changed = true;
279 continue;
280 }
281
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000282 // 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
Chris Lattner70ffe572009-01-28 20:16:43 +0000479 if (LoadInst *LI = dyn_cast<LoadInst>(User))
480 if (!LI->isVolatile())
481 return;// Loads (returning a first class aggregrate) are always rewritable
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000482
Chris Lattner70ffe572009-01-28 20:16:43 +0000483 if (StoreInst *SI = dyn_cast<StoreInst>(User))
484 if (!SI->isVolatile() && SI->getOperand(0) != AI)
485 return;// Store is ok if storing INTO the pointer, not storing the pointer
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000486
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000487 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
488 if (GEPI == 0)
489 return MarkUnsafe(Info);
490
491 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
492
493 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
494 if (I == E ||
495 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
496 return MarkUnsafe(Info);
497 }
498
499 ++I;
500 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
501
502 bool IsAllZeroIndices = true;
503
Chris Lattnerd324da02008-08-23 05:21:06 +0000504 // If the first index is a non-constant index into an array, see if we can
505 // handle it as a special case.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000506 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
Chris Lattnerd324da02008-08-23 05:21:06 +0000507 if (!isa<ConstantInt>(I.getOperand())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000508 IsAllZeroIndices = 0;
Chris Lattnerd324da02008-08-23 05:21:06 +0000509 uint64_t NumElements = AT->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000510
511 // If this is an array index and the index is not constant, we cannot
512 // promote... that is unless the array has exactly one or two elements in
513 // it, in which case we CAN promote it, but we have to canonicalize this
514 // out if this is the only problem.
515 if ((NumElements == 1 || NumElements == 2) &&
516 AllUsersAreLoads(GEPI)) {
517 Info.needsCanon = true;
518 return; // Canonicalization required!
519 }
520 return MarkUnsafe(Info);
521 }
522 }
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000523
Chris Lattnerd324da02008-08-23 05:21:06 +0000524 // Walk through the GEP type indices, checking the types that this indexes
525 // into.
526 for (; I != E; ++I) {
527 // Ignore struct elements, no extra checking needed for these.
528 if (isa<StructType>(*I))
529 continue;
530
Chris Lattnerd324da02008-08-23 05:21:06 +0000531 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
532 if (!IdxVal) return MarkUnsafe(Info);
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000533
534 // Are all indices still zero?
Chris Lattnerd324da02008-08-23 05:21:06 +0000535 IsAllZeroIndices &= IdxVal->isZero();
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000536
537 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
538 // This GEP indexes an array. Verify that this is an in-range constant
539 // integer. Specifically, consider A[0][i]. We cannot know that the user
540 // isn't doing invalid things like allowing i to index an out-of-range
541 // subscript that accesses A[1]. Because of this, we have to reject SROA
Dale Johannesen1f9b1862008-11-04 20:54:03 +0000542 // of any accesses into structs where any of the components are variables.
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000543 if (IdxVal->getZExtValue() >= AT->getNumElements())
544 return MarkUnsafe(Info);
Dale Johannesen1f9b1862008-11-04 20:54:03 +0000545 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
546 if (IdxVal->getZExtValue() >= VT->getNumElements())
547 return MarkUnsafe(Info);
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000548 }
Chris Lattnerd324da02008-08-23 05:21:06 +0000549 }
550
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000551 // If there are any non-simple uses of this getelementptr, make sure to reject
552 // them.
553 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
554}
555
556/// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
557/// intrinsic can be promoted by SROA. At this point, we know that the operand
558/// of the memintrinsic is a pointer to the beginning of the allocation.
559void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
560 unsigned OpNo, AllocaInfo &Info) {
561 // If not constant length, give up.
562 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
563 if (!Length) return MarkUnsafe(Info);
564
565 // If not the whole aggregate, give up.
Duncan Sandsae5fd622007-11-04 14:43:57 +0000566 if (Length->getZExtValue() !=
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000567 TD->getTypePaddedSize(AI->getType()->getElementType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000568 return MarkUnsafe(Info);
569
570 // We only know about memcpy/memset/memmove.
571 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
572 return MarkUnsafe(Info);
573
574 // Otherwise, we can transform it. Determine whether this is a memcpy/set
575 // into or out of the aggregate.
576 if (OpNo == 1)
577 Info.isMemCpyDst = true;
578 else {
579 assert(OpNo == 2);
580 Info.isMemCpySrc = true;
581 }
582}
583
584/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
585/// are
586void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
587 AllocaInfo &Info) {
588 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
589 UI != E; ++UI) {
590 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
591 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
592 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
593 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
Chris Lattner71c75342009-01-07 08:11:13 +0000594 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner70ffe572009-01-28 20:16:43 +0000595 if (SI->isVolatile())
596 return MarkUnsafe(Info);
597
Chris Lattner71c75342009-01-07 08:11:13 +0000598 // If storing the entire alloca in one chunk through a bitcasted pointer
599 // to integer, we can transform it. This happens (for example) when you
600 // cast a {i32,i32}* to i64* and store through it. This is similar to the
601 // memcpy case and occurs in various "byval" cases and emulated memcpys.
602 if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000603 TD->getTypePaddedSize(SI->getOperand(0)->getType()) ==
604 TD->getTypePaddedSize(AI->getType()->getElementType())) {
Chris Lattner71c75342009-01-07 08:11:13 +0000605 Info.isMemCpyDst = true;
606 continue;
607 }
608 return MarkUnsafe(Info);
Chris Lattner28401db2009-01-08 05:42:05 +0000609 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
Chris Lattner70ffe572009-01-28 20:16:43 +0000610 if (LI->isVolatile())
611 return MarkUnsafe(Info);
612
Chris Lattner28401db2009-01-08 05:42:05 +0000613 // If loading the entire alloca in one chunk through a bitcasted pointer
614 // to integer, we can transform it. This happens (for example) when you
615 // cast a {i32,i32}* to i64* and load through it. This is similar to the
616 // memcpy case and occurs in various "byval" cases and emulated memcpys.
617 if (isa<IntegerType>(LI->getType()) &&
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000618 TD->getTypePaddedSize(LI->getType()) ==
619 TD->getTypePaddedSize(AI->getType()->getElementType())) {
Chris Lattner28401db2009-01-08 05:42:05 +0000620 Info.isMemCpySrc = true;
621 continue;
622 }
623 return MarkUnsafe(Info);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624 } else {
625 return MarkUnsafe(Info);
626 }
627 if (Info.isUnsafe) return;
628 }
629}
630
631/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
632/// to its first element. Transform users of the cast to use the new values
633/// instead.
634void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
635 SmallVector<AllocaInst*, 32> &NewElts) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000636 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
637 while (UI != UE) {
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000638 Instruction *User = cast<Instruction>(*UI++);
639 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
Chris Lattner71c75342009-01-07 08:11:13 +0000641 if (BCU->use_empty()) BCU->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000642 continue;
643 }
644
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000645 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
646 // This must be memcpy/memmove/memset of the entire aggregate.
647 // Split into one per element.
648 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000649 continue;
650 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000651
Chris Lattner71c75342009-01-07 08:11:13 +0000652 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Chris Lattner28401db2009-01-08 05:42:05 +0000653 // If this is a store of the entire alloca from an integer, rewrite it.
Chris Lattner71c75342009-01-07 08:11:13 +0000654 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
655 continue;
656 }
Chris Lattner28401db2009-01-08 05:42:05 +0000657
658 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
659 // If this is a load of the entire alloca to an integer, rewrite it.
660 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
661 continue;
662 }
Chris Lattner71c75342009-01-07 08:11:13 +0000663
664 // Otherwise it must be some other user of a gep of the first pointer. Just
665 // leave these alone.
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000666 continue;
Chris Lattner28401db2009-01-08 05:42:05 +0000667 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000668}
669
670/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
671/// Rewrite it to copy or set the elements of the scalarized memory.
672void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
673 AllocationInst *AI,
674 SmallVector<AllocaInst*, 32> &NewElts) {
675
676 // If this is a memcpy/memmove, construct the other pointer as the
677 // appropriate type.
678 Value *OtherPtr = 0;
679 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
680 if (BCInst == MCI->getRawDest())
681 OtherPtr = MCI->getRawSource();
682 else {
683 assert(BCInst == MCI->getRawSource());
684 OtherPtr = MCI->getRawDest();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000685 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000686 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
687 if (BCInst == MMI->getRawDest())
688 OtherPtr = MMI->getRawSource();
689 else {
690 assert(BCInst == MMI->getRawSource());
691 OtherPtr = MMI->getRawDest();
692 }
693 }
694
695 // If there is an other pointer, we want to convert it to the same pointer
696 // type as AI has, so we can GEP through it safely.
697 if (OtherPtr) {
698 // It is likely that OtherPtr is a bitcast, if so, remove it.
699 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
700 OtherPtr = BC->getOperand(0);
701 // All zero GEPs are effectively bitcasts.
702 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
703 if (GEP->hasAllZeroIndices())
704 OtherPtr = GEP->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000705
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000706 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
707 if (BCE->getOpcode() == Instruction::BitCast)
708 OtherPtr = BCE->getOperand(0);
709
710 // If the pointer is not the right type, insert a bitcast to the right
711 // type.
712 if (OtherPtr->getType() != AI->getType())
713 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
714 MI);
715 }
716
717 // Process each element of the aggregate.
718 Value *TheFn = MI->getOperand(0);
719 const Type *BytePtrTy = MI->getRawDest()->getType();
720 bool SROADest = MI->getRawDest() == BCInst;
721
722 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
723
724 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
725 // If this is a memcpy/memmove, emit a GEP of the other element address.
726 Value *OtherElt = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000727 if (OtherPtr) {
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000728 Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
729 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
Chris Lattner0e99e692008-06-22 17:46:21 +0000730 OtherPtr->getNameStr()+"."+utostr(i),
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000731 MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000732 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000733
734 Value *EltPtr = NewElts[i];
735 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
736
737 // If we got down to a scalar, insert a load or store as appropriate.
738 if (EltTy->isSingleValueType()) {
739 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
740 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
741 MI);
742 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
743 continue;
744 }
745 assert(isa<MemSetInst>(MI));
746
747 // If the stored element is zero (common case), just store a null
748 // constant.
749 Constant *StoreVal;
750 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
751 if (CI->isZero()) {
752 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
753 } else {
754 // If EltTy is a vector type, get the element type.
755 const Type *ValTy = EltTy;
756 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
757 ValTy = VTy->getElementType();
758
759 // Construct an integer with the right value.
760 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
761 APInt OneVal(EltSize, CI->getZExtValue());
762 APInt TotalVal(OneVal);
763 // Set each byte.
764 for (unsigned i = 0; 8*i < EltSize; ++i) {
765 TotalVal = TotalVal.shl(8);
766 TotalVal |= OneVal;
767 }
768
769 // Convert the integer value to the appropriate type.
770 StoreVal = ConstantInt::get(TotalVal);
771 if (isa<PointerType>(ValTy))
772 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
773 else if (ValTy->isFloatingPoint())
774 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
775 assert(StoreVal->getType() == ValTy && "Type mismatch!");
776
777 // If the requested value was a vector constant, create it.
778 if (EltTy != ValTy) {
779 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
780 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
781 StoreVal = ConstantVector::get(&Elts[0], NumElts);
782 }
783 }
784 new StoreInst(StoreVal, EltPtr, MI);
785 continue;
786 }
787 // Otherwise, if we're storing a byte variable, use a memset call for
788 // this element.
789 }
790
791 // Cast the element pointer to BytePtrTy.
792 if (EltPtr->getType() != BytePtrTy)
793 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
794
795 // Cast the other pointer (if we have one) to BytePtrTy.
796 if (OtherElt && OtherElt->getType() != BytePtrTy)
797 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
798 MI);
799
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000800 unsigned EltSize = TD->getTypePaddedSize(EltTy);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000801
802 // Finally, insert the meminst for this element.
803 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
804 Value *Ops[] = {
805 SROADest ? EltPtr : OtherElt, // Dest ptr
806 SROADest ? OtherElt : EltPtr, // Src ptr
807 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
808 Zero // Align
809 };
810 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
811 } else {
812 assert(isa<MemSetInst>(MI));
813 Value *Ops[] = {
814 EltPtr, MI->getOperand(2), // Dest, Value,
815 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
816 Zero // Align
817 };
818 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
819 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000820 }
Chris Lattner71c75342009-01-07 08:11:13 +0000821 MI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000822}
Chris Lattner71c75342009-01-07 08:11:13 +0000823
824/// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
825/// overwrites the entire allocation. Extract out the pieces of the stored
826/// integer and store them individually.
827void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
828 AllocationInst *AI,
829 SmallVector<AllocaInst*, 32> &NewElts){
830 // Extract each element out of the integer according to its structure offset
831 // and store the element value to the individual alloca.
832 Value *SrcVal = SI->getOperand(0);
833 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000834 uint64_t AllocaSizeBits = TD->getTypePaddedSizeInBits(AllocaEltTy);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000835
Chris Lattner71c75342009-01-07 08:11:13 +0000836 // If this isn't a store of an integer to the whole alloca, it may be a store
837 // to the first element. Just ignore the store in this case and normal SROA
838 // will handle it.
839 if (!isa<IntegerType>(SrcVal->getType()) ||
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000840 TD->getTypePaddedSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner71c75342009-01-07 08:11:13 +0000841 return;
842
843 DOUT << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI;
844
845 // There are two forms here: AI could be an array or struct. Both cases
846 // have different ways to compute the element offset.
847 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
848 const StructLayout *Layout = TD->getStructLayout(EltSTy);
849
850 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
851 // Get the number of bits to shift SrcVal to get the value.
852 const Type *FieldTy = EltSTy->getElementType(i);
853 uint64_t Shift = Layout->getElementOffsetInBits(i);
854
855 if (TD->isBigEndian())
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000856 Shift = AllocaSizeBits-Shift-TD->getTypePaddedSizeInBits(FieldTy);
Chris Lattner71c75342009-01-07 08:11:13 +0000857
858 Value *EltVal = SrcVal;
859 if (Shift) {
860 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
861 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
862 "sroa.store.elt", SI);
863 }
864
865 // Truncate down to an integer of the right size.
866 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattnerf7a2f092009-01-09 18:18:43 +0000867
868 // Ignore zero sized fields like {}, they obviously contain no data.
869 if (FieldSizeBits == 0) continue;
870
Chris Lattner71c75342009-01-07 08:11:13 +0000871 if (FieldSizeBits != AllocaSizeBits)
872 EltVal = new TruncInst(EltVal, IntegerType::get(FieldSizeBits), "", SI);
873 Value *DestField = NewElts[i];
874 if (EltVal->getType() == FieldTy) {
875 // Storing to an integer field of this size, just do it.
876 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
877 // Bitcast to the right element type (for fp/vector values).
878 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
879 } else {
880 // Otherwise, bitcast the dest pointer (for aggregates).
881 DestField = new BitCastInst(DestField,
882 PointerType::getUnqual(EltVal->getType()),
883 "", SI);
884 }
885 new StoreInst(EltVal, DestField, SI);
886 }
887
888 } else {
889 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
890 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000891 uint64_t ElementOffset = TD->getTypePaddedSizeInBits(ArrayEltTy);
Chris Lattner71c75342009-01-07 08:11:13 +0000892 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
893
894 uint64_t Shift;
895
896 if (TD->isBigEndian())
897 Shift = AllocaSizeBits-ElementOffset;
898 else
899 Shift = 0;
900
901 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattnerf7a2f092009-01-09 18:18:43 +0000902 // Ignore zero sized fields like {}, they obviously contain no data.
903 if (ElementSizeBits == 0) continue;
Chris Lattner71c75342009-01-07 08:11:13 +0000904
905 Value *EltVal = SrcVal;
906 if (Shift) {
907 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
908 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
909 "sroa.store.elt", SI);
910 }
911
912 // Truncate down to an integer of the right size.
913 if (ElementSizeBits != AllocaSizeBits)
914 EltVal = new TruncInst(EltVal, IntegerType::get(ElementSizeBits),"",SI);
915 Value *DestField = NewElts[i];
916 if (EltVal->getType() == ArrayEltTy) {
917 // Storing to an integer field of this size, just do it.
918 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
919 // Bitcast to the right element type (for fp/vector values).
920 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
921 } else {
922 // Otherwise, bitcast the dest pointer (for aggregates).
923 DestField = new BitCastInst(DestField,
924 PointerType::getUnqual(EltVal->getType()),
925 "", SI);
926 }
927 new StoreInst(EltVal, DestField, SI);
928
929 if (TD->isBigEndian())
930 Shift -= ElementOffset;
931 else
932 Shift += ElementOffset;
933 }
934 }
935
936 SI->eraseFromParent();
937}
938
Chris Lattner28401db2009-01-08 05:42:05 +0000939/// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to
940/// an integer. Load the individual pieces to form the aggregate value.
941void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
942 SmallVector<AllocaInst*, 32> &NewElts) {
943 // Extract each element out of the NewElts according to its structure offset
944 // and form the result value.
945 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000946 uint64_t AllocaSizeBits = TD->getTypePaddedSizeInBits(AllocaEltTy);
Chris Lattner28401db2009-01-08 05:42:05 +0000947
948 // If this isn't a load of the whole alloca to an integer, it may be a load
949 // of the first element. Just ignore the load in this case and normal SROA
950 // will handle it.
951 if (!isa<IntegerType>(LI->getType()) ||
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000952 TD->getTypePaddedSizeInBits(LI->getType()) != AllocaSizeBits)
Chris Lattner28401db2009-01-08 05:42:05 +0000953 return;
954
955 DOUT << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << *LI;
956
957 // There are two forms here: AI could be an array or struct. Both cases
958 // have different ways to compute the element offset.
959 const StructLayout *Layout = 0;
960 uint64_t ArrayEltBitOffset = 0;
961 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
962 Layout = TD->getStructLayout(EltSTy);
963 } else {
964 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000965 ArrayEltBitOffset = TD->getTypePaddedSizeInBits(ArrayEltTy);
Chris Lattner28401db2009-01-08 05:42:05 +0000966 }
967
968 Value *ResultVal = Constant::getNullValue(LI->getType());
969
970 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
971 // Load the value from the alloca. If the NewElt is an aggregate, cast
972 // the pointer to an integer of the same size before doing the load.
973 Value *SrcField = NewElts[i];
974 const Type *FieldTy =
975 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattnerf7a2f092009-01-09 18:18:43 +0000976 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
977
978 // Ignore zero sized fields like {}, they obviously contain no data.
979 if (FieldSizeBits == 0) continue;
980
981 const IntegerType *FieldIntTy = IntegerType::get(FieldSizeBits);
Chris Lattner28401db2009-01-08 05:42:05 +0000982 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
983 !isa<VectorType>(FieldTy))
984 SrcField = new BitCastInst(SrcField, PointerType::getUnqual(FieldIntTy),
985 "", LI);
986 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
987
988 // If SrcField is a fp or vector of the right size but that isn't an
989 // integer type, bitcast to an integer so we can shift it.
990 if (SrcField->getType() != FieldIntTy)
991 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
992
993 // Zero extend the field to be the same size as the final alloca so that
994 // we can shift and insert it.
995 if (SrcField->getType() != ResultVal->getType())
996 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
997
998 // Determine the number of bits to shift SrcField.
999 uint64_t Shift;
1000 if (Layout) // Struct case.
1001 Shift = Layout->getElementOffsetInBits(i);
1002 else // Array case.
1003 Shift = i*ArrayEltBitOffset;
1004
1005 if (TD->isBigEndian())
1006 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1007
1008 if (Shift) {
1009 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1010 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1011 }
1012
1013 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1014 }
1015
1016 LI->replaceAllUsesWith(ResultVal);
1017 LI->eraseFromParent();
1018}
1019
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001020
Duncan Sandsae5fd622007-11-04 14:43:57 +00001021/// HasPadding - Return true if the specified type has any structure or
1022/// alignment padding, false otherwise.
Duncan Sands4afc5752008-06-04 08:21:45 +00001023static bool HasPadding(const Type *Ty, const TargetData &TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001024 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1025 const StructLayout *SL = TD.getStructLayout(STy);
1026 unsigned PrevFieldBitOffset = 0;
1027 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sandsae5fd622007-11-04 14:43:57 +00001028 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1029
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001030 // Padding in sub-elements?
Duncan Sands4afc5752008-06-04 08:21:45 +00001031 if (HasPadding(STy->getElementType(i), TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001032 return true;
Duncan Sandsae5fd622007-11-04 14:43:57 +00001033
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001034 // Check to see if there is any padding between this element and the
1035 // previous one.
1036 if (i) {
Duncan Sandsae5fd622007-11-04 14:43:57 +00001037 unsigned PrevFieldEnd =
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001038 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1039 if (PrevFieldEnd < FieldBitOffset)
1040 return true;
1041 }
Duncan Sandsae5fd622007-11-04 14:43:57 +00001042
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043 PrevFieldBitOffset = FieldBitOffset;
1044 }
Duncan Sandsae5fd622007-11-04 14:43:57 +00001045
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001046 // Check for tail padding.
1047 if (unsigned EltCount = STy->getNumElements()) {
1048 unsigned PrevFieldEnd = PrevFieldBitOffset +
1049 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sandsae5fd622007-11-04 14:43:57 +00001050 if (PrevFieldEnd < SL->getSizeInBits())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001051 return true;
1052 }
1053
1054 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sands4afc5752008-06-04 08:21:45 +00001055 return HasPadding(ATy->getElementType(), TD);
Duncan Sandsae5fd622007-11-04 14:43:57 +00001056 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sands4afc5752008-06-04 08:21:45 +00001057 return HasPadding(VTy->getElementType(), TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058 }
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001059 return TD.getTypeSizeInBits(Ty) != TD.getTypePaddedSizeInBits(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001060}
1061
1062/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1063/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1064/// or 1 if safe after canonicalization has been performed.
1065///
1066int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
1067 // Loop over the use list of the alloca. We can only transform it if all of
1068 // the users are safe to transform.
1069 AllocaInfo Info;
1070
1071 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
1072 I != E; ++I) {
1073 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1074 if (Info.isUnsafe) {
1075 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
1076 return 0;
1077 }
1078 }
1079
1080 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1081 // source and destination, we have to be careful. In particular, the memcpy
1082 // could be moving around elements that live in structure padding of the LLVM
1083 // types, but may actually be used. In these cases, we refuse to promote the
1084 // struct.
1085 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Chris Lattner3fd59362009-01-07 06:34:28 +00001086 HasPadding(AI->getType()->getElementType(), *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001087 return 0;
Duncan Sandsae5fd622007-11-04 14:43:57 +00001088
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001089 // If we require cleanup, return 1, otherwise return 3.
1090 return Info.needsCanon ? 1 : 3;
1091}
1092
1093/// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
1094/// allocation, but only if cleaned up, perform the cleanups required.
1095void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
1096 // At this point, we know that the end result will be SROA'd and promoted, so
1097 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1098 // up.
1099 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1100 UI != E; ) {
1101 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
1102 if (!GEPI) continue;
1103 gep_type_iterator I = gep_type_begin(GEPI);
1104 ++I;
1105
1106 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
1107 uint64_t NumElements = AT->getNumElements();
1108
1109 if (!isa<ConstantInt>(I.getOperand())) {
1110 if (NumElements == 1) {
1111 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
1112 } else {
1113 assert(NumElements == 2 && "Unhandled case!");
1114 // All users of the GEP must be loads. At each use of the GEP, insert
1115 // two loads of the appropriate indexed GEP and select between them.
1116 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
1117 Constant::getNullValue(I.getOperand()->getType()),
1118 "isone", GEPI);
1119 // Insert the new GEP instructions, which are properly indexed.
1120 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
1121 Indices[1] = Constant::getNullValue(Type::Int32Ty);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001122 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1123 Indices.begin(),
1124 Indices.end(),
1125 GEPI->getName()+".0", GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001126 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001127 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1128 Indices.begin(),
1129 Indices.end(),
1130 GEPI->getName()+".1", GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001131 // Replace all loads of the variable index GEP with loads from both
1132 // indexes and a select.
1133 while (!GEPI->use_empty()) {
1134 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1135 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1136 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001137 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001138 LI->replaceAllUsesWith(R);
1139 LI->eraseFromParent();
1140 }
1141 GEPI->eraseFromParent();
1142 }
1143 }
1144 }
1145 }
1146}
1147
1148/// MergeInType - Add the 'In' type to the accumulated type so far. If the
1149/// types are incompatible, return true, otherwise update Accum and return
1150/// false.
1151///
1152/// There are three cases we handle here:
1153/// 1) An effectively-integer union, where the pieces are stored into as
1154/// smaller integers (common with byte swap and other idioms).
1155/// 2) A union of vector types of the same size and potentially its elements.
1156/// Here we turn element accesses into insert/extract element operations.
1157/// 3) A union of scalar types, such as int/float or int/pointer. Here we
1158/// merge together into integers, allowing the xform to work with #1 as
1159/// well.
1160static bool MergeInType(const Type *In, const Type *&Accum,
1161 const TargetData &TD) {
1162 // If this is our first type, just use it.
1163 const VectorType *PTy;
1164 if (Accum == Type::VoidTy || In == Accum) {
1165 Accum = In;
1166 } else if (In == Type::VoidTy) {
1167 // Noop.
1168 } else if (In->isInteger() && Accum->isInteger()) { // integer union.
1169 // Otherwise pick whichever type is larger.
1170 if (cast<IntegerType>(In)->getBitWidth() >
1171 cast<IntegerType>(Accum)->getBitWidth())
1172 Accum = In;
1173 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
1174 // Pointer unions just stay as one of the pointers.
1175 } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
1176 if ((PTy = dyn_cast<VectorType>(Accum)) &&
1177 PTy->getElementType() == In) {
1178 // Accum is a vector, and we are accessing an element: ok.
1179 } else if ((PTy = dyn_cast<VectorType>(In)) &&
1180 PTy->getElementType() == Accum) {
1181 // In is a vector, and accum is an element: ok, remember In.
1182 Accum = In;
1183 } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
1184 PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
1185 // Two vectors of the same size: keep Accum.
1186 } else {
1187 // Cannot insert an short into a <4 x int> or handle
1188 // <2 x int> -> <4 x int>
1189 return true;
1190 }
1191 } else {
1192 // Pointer/FP/Integer unions merge together as integers.
1193 switch (Accum->getTypeID()) {
1194 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
1195 case Type::FloatTyID: Accum = Type::Int32Ty; break;
1196 case Type::DoubleTyID: Accum = Type::Int64Ty; break;
Dale Johannesen4c839d02007-09-28 00:21:38 +00001197 case Type::X86_FP80TyID: return true;
1198 case Type::FP128TyID: return true;
1199 case Type::PPC_FP128TyID: return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001200 default:
1201 assert(Accum->isInteger() && "Unknown FP type!");
1202 break;
1203 }
1204
1205 switch (In->getTypeID()) {
1206 case Type::PointerTyID: In = TD.getIntPtrType(); break;
1207 case Type::FloatTyID: In = Type::Int32Ty; break;
1208 case Type::DoubleTyID: In = Type::Int64Ty; break;
Dale Johannesen4c839d02007-09-28 00:21:38 +00001209 case Type::X86_FP80TyID: return true;
1210 case Type::FP128TyID: return true;
1211 case Type::PPC_FP128TyID: return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001212 default:
1213 assert(In->isInteger() && "Unknown FP type!");
1214 break;
1215 }
1216 return MergeInType(In, Accum, TD);
1217 }
1218 return false;
1219}
1220
Chris Lattner3fd59362009-01-07 06:34:28 +00001221/// getIntAtLeastAsBigAs - Return an integer type that is at least as big as the
1222/// specified type. If there is no suitable type, this returns null.
1223const Type *getIntAtLeastAsBigAs(unsigned NumBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001224 if (NumBits > 64) return 0;
1225 if (NumBits > 32) return Type::Int64Ty;
1226 if (NumBits > 16) return Type::Int32Ty;
1227 if (NumBits > 8) return Type::Int16Ty;
1228 return Type::Int8Ty;
1229}
1230
1231/// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
1232/// single scalar integer type, return that type. Further, if the use is not
1233/// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
1234/// there are no uses of this pointer, return Type::VoidTy to differentiate from
1235/// failure.
1236///
1237const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
1238 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001239 const PointerType *PTy = cast<PointerType>(V->getType());
1240
1241 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1242 Instruction *User = cast<Instruction>(*UI);
1243
1244 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner70ffe572009-01-28 20:16:43 +00001245 if (LI->isVolatile())
1246 return 0;
1247
Matthijs Kooijman001006a2008-06-05 12:51:53 +00001248 // FIXME: Loads of a first class aggregrate value could be converted to a
1249 // series of loads and insertvalues
1250 if (!LI->getType()->isSingleValueType())
1251 return 0;
1252
Chris Lattner3fd59362009-01-07 06:34:28 +00001253 if (MergeInType(LI->getType(), UsedType, *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001254 return 0;
Chris Lattner7cc97712009-01-07 06:39:58 +00001255 continue;
1256 }
1257
1258 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259 // Storing the pointer, not into the value?
Chris Lattner70ffe572009-01-28 20:16:43 +00001260 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
Matthijs Kooijman001006a2008-06-05 12:51:53 +00001261
1262 // FIXME: Stores of a first class aggregrate value could be converted to a
1263 // series of extractvalues and stores
1264 if (!SI->getOperand(0)->getType()->isSingleValueType())
1265 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001266
1267 // NOTE: We could handle storing of FP imms into integers here!
1268
Chris Lattner3fd59362009-01-07 06:34:28 +00001269 if (MergeInType(SI->getOperand(0)->getType(), UsedType, *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270 return 0;
Chris Lattner7cc97712009-01-07 06:39:58 +00001271 continue;
1272 }
1273 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 IsNotTrivial = true;
1275 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
Chris Lattner3fd59362009-01-07 06:34:28 +00001276 if (!SubTy || MergeInType(SubTy, UsedType, *TD)) return 0;
Chris Lattner7cc97712009-01-07 06:39:58 +00001277 continue;
1278 }
1279
1280 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001281 // Check to see if this is stepping over an element: GEP Ptr, int C
1282 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
1283 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001284 unsigned ElSize = TD->getTypePaddedSize(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285 unsigned BitOffset = Idx*ElSize*8;
1286 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
1287
1288 IsNotTrivial = true;
1289 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
1290 if (SubElt == 0) return 0;
1291 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
1292 const Type *NewTy =
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001293 getIntAtLeastAsBigAs(TD->getTypePaddedSizeInBits(SubElt)+BitOffset);
Chris Lattner3fd59362009-01-07 06:34:28 +00001294 if (NewTy == 0 || MergeInType(NewTy, UsedType, *TD)) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001295 continue;
1296 }
Chris Lattner7cc97712009-01-07 06:39:58 +00001297 // Cannot handle this!
1298 return 0;
1299 }
1300
1301 if (GEP->getNumOperands() == 3 &&
1302 isa<ConstantInt>(GEP->getOperand(1)) &&
1303 isa<ConstantInt>(GEP->getOperand(2)) &&
1304 cast<ConstantInt>(GEP->getOperand(1))->isZero()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001305 // We are stepping into an element, e.g. a structure or an array:
Chris Lattner85591c62009-01-07 06:25:07 +00001306 // GEP Ptr, i32 0, i32 Cst
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001307 const Type *AggTy = PTy->getElementType();
1308 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1309
1310 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
1311 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
1312 } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
1313 // Getting an element of the vector.
1314 if (Idx >= VectorTy->getNumElements()) return 0; // Out of range.
1315
1316 // Merge in the vector type.
Chris Lattner3fd59362009-01-07 06:34:28 +00001317 if (MergeInType(VectorTy, UsedType, *TD)) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318
1319 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1320 if (SubTy == 0) return 0;
1321
Chris Lattner3fd59362009-01-07 06:34:28 +00001322 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001323 return 0;
1324
1325 // We'll need to change this to an insert/extract element operation.
1326 IsNotTrivial = true;
1327 continue; // Everything looks ok
1328
1329 } else if (isa<StructType>(AggTy)) {
1330 // Structs are always ok.
1331 } else {
1332 return 0;
1333 }
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001334 const Type *NTy =
1335 getIntAtLeastAsBigAs(TD->getTypePaddedSizeInBits(AggTy));
Chris Lattner3fd59362009-01-07 06:34:28 +00001336 if (NTy == 0 || MergeInType(NTy, UsedType, *TD)) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001337 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1338 if (SubTy == 0) return 0;
Chris Lattner3fd59362009-01-07 06:34:28 +00001339 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001340 return 0;
1341 continue; // Everything looks ok
1342 }
1343 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001344 }
Chris Lattner7cc97712009-01-07 06:39:58 +00001345
1346 // Cannot handle this!
1347 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001348 }
1349
1350 return UsedType;
1351}
1352
1353/// ConvertToScalar - The specified alloca passes the CanConvertToScalar
1354/// predicate and is non-trivial. Convert it to something that can be trivially
1355/// promoted into a register by mem2reg.
1356void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
1357 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
1358 << *ActualTy << "\n";
1359 ++NumConverted;
1360
1361 BasicBlock *EntryBlock = AI->getParent();
1362 assert(EntryBlock == &EntryBlock->getParent()->getEntryBlock() &&
1363 "Not in the entry block!");
1364 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
1365
1366 // Create and insert the alloca.
1367 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
1368 EntryBlock->begin());
1369 ConvertUsesToScalar(AI, NewAI, 0);
1370 delete AI;
1371}
1372
1373
1374/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1375/// directly. This happens when we are converting an "integer union" to a
1376/// single integer scalar, or when we are converting a "vector union" to a
1377/// vector with insert/extractelement instructions.
1378///
1379/// Offset is an offset from the original alloca, in bits that need to be
1380/// shifted to the right. By the end of this, there should be no uses of Ptr.
1381void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001382 while (!Ptr->use_empty()) {
1383 Instruction *User = cast<Instruction>(Ptr->use_back());
1384
1385 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner41d58652008-02-29 07:03:13 +00001386 Value *NV = ConvertUsesOfLoadToScalar(LI, NewAI, Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001387 LI->replaceAllUsesWith(NV);
1388 LI->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001389 continue;
1390 }
1391
1392 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001393 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1394
Chris Lattner41d58652008-02-29 07:03:13 +00001395 Value *SV = ConvertUsesOfStoreToScalar(SI, NewAI, Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001396 new StoreInst(SV, NewAI, SI);
1397 SI->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001398 continue;
1399 }
1400
1401 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb1534532008-01-30 00:39:15 +00001402 ConvertUsesToScalar(CI, NewAI, Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001403 CI->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001404 continue;
1405 }
1406
1407 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001408 const PointerType *AggPtrTy =
1409 cast<PointerType>(GEP->getOperand(0)->getType());
Duncan Sandsae5fd622007-11-04 14:43:57 +00001410 unsigned AggSizeInBits =
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001411 TD->getTypePaddedSizeInBits(AggPtrTy->getElementType());
Duncan Sandsae5fd622007-11-04 14:43:57 +00001412
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001413 // Check to see if this is stepping over an element: GEP Ptr, int C
1414 unsigned NewOffset = Offset;
1415 if (GEP->getNumOperands() == 2) {
1416 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1417 unsigned BitOffset = Idx*AggSizeInBits;
1418
1419 NewOffset += BitOffset;
Chris Lattner7cc97712009-01-07 06:39:58 +00001420 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1421 GEP->eraseFromParent();
1422 continue;
1423 }
1424
1425 assert(GEP->getNumOperands() == 3 && "Unsupported operation");
1426
1427 // We know that operand #2 is zero.
1428 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1429 const Type *AggTy = AggPtrTy->getElementType();
1430 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
1431 unsigned ElSizeBits =
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001432 TD->getTypePaddedSizeInBits(SeqTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001433
Chris Lattner7cc97712009-01-07 06:39:58 +00001434 NewOffset += ElSizeBits*Idx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001435 } else {
Chris Lattner7cc97712009-01-07 06:39:58 +00001436 const StructType *STy = cast<StructType>(AggTy);
1437 unsigned EltBitOffset =
1438 TD->getStructLayout(STy)->getElementOffsetInBits(Idx);
1439
1440 NewOffset += EltBitOffset;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001441 }
1442 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1443 GEP->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001444 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001445 }
Chris Lattner7cc97712009-01-07 06:39:58 +00001446
1447 assert(0 && "Unsupported operation!");
1448 abort();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001449 }
1450}
1451
Chris Lattner41d58652008-02-29 07:03:13 +00001452/// ConvertUsesOfLoadToScalar - Convert all of the users the specified load to
1453/// use the new alloca directly, returning the value that should replace the
1454/// load. This happens when we are converting an "integer union" to a
1455/// single integer scalar, or when we are converting a "vector union" to a
1456/// vector with insert/extractelement instructions.
1457///
1458/// Offset is an offset from the original alloca, in bits that need to be
1459/// shifted to the right. By the end of this, there should be no uses of Ptr.
1460Value *SROA::ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
1461 unsigned Offset) {
1462 // The load is a bit extract from NewAI shifted right by Offset bits.
1463 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
1464
1465 if (NV->getType() == LI->getType() && Offset == 0) {
1466 // We win, no conversion needed.
1467 return NV;
1468 }
Chris Lattner5f062542008-02-29 07:12:06 +00001469
1470 // If the result type of the 'union' is a pointer, then this must be ptr->ptr
1471 // cast. Anything else would result in NV being an integer.
1472 if (isa<PointerType>(NV->getType())) {
1473 assert(isa<PointerType>(LI->getType()));
1474 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1475 }
Chris Lattner41d58652008-02-29 07:03:13 +00001476
Chris Lattner5f062542008-02-29 07:12:06 +00001477 if (const VectorType *VTy = dyn_cast<VectorType>(NV->getType())) {
Chris Lattner41d58652008-02-29 07:03:13 +00001478 // If the result alloca is a vector type, this is either an element
1479 // access or a bitcast to another vector type.
Chris Lattner5f062542008-02-29 07:12:06 +00001480 if (isa<VectorType>(LI->getType()))
1481 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1482
1483 // Otherwise it must be an element access.
Chris Lattner5f062542008-02-29 07:12:06 +00001484 unsigned Elt = 0;
1485 if (Offset) {
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001486 unsigned EltSize = TD->getTypePaddedSizeInBits(VTy->getElementType());
Chris Lattner5f062542008-02-29 07:12:06 +00001487 Elt = Offset/EltSize;
1488 Offset -= EltSize*Elt;
Chris Lattner41d58652008-02-29 07:03:13 +00001489 }
Chris Lattner5f062542008-02-29 07:12:06 +00001490 NV = new ExtractElementInst(NV, ConstantInt::get(Type::Int32Ty, Elt),
1491 "tmp", LI);
1492
1493 // If we're done, return this element.
1494 if (NV->getType() == LI->getType() && Offset == 0)
1495 return NV;
1496 }
1497
1498 const IntegerType *NTy = cast<IntegerType>(NV->getType());
1499
1500 // If this is a big-endian system and the load is narrower than the
1501 // full alloca type, we need to do a shift to get the right bits.
1502 int ShAmt = 0;
Chris Lattner3fd59362009-01-07 06:34:28 +00001503 if (TD->isBigEndian()) {
Chris Lattner5f062542008-02-29 07:12:06 +00001504 // On big-endian machines, the lowest bit is stored at the bit offset
1505 // from the pointer given by getTypeStoreSizeInBits. This matters for
1506 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner3fd59362009-01-07 06:34:28 +00001507 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
1508 TD->getTypeStoreSizeInBits(LI->getType()) - Offset;
Chris Lattner5f062542008-02-29 07:12:06 +00001509 } else {
1510 ShAmt = Offset;
1511 }
1512
1513 // Note: we support negative bitwidths (with shl) which are not defined.
1514 // We do this to support (f.e.) loads off the end of a structure where
1515 // only some bits are used.
1516 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Gabor Greifa645dd32008-05-16 19:29:10 +00001517 NV = BinaryOperator::CreateLShr(NV,
Chris Lattner5f062542008-02-29 07:12:06 +00001518 ConstantInt::get(NV->getType(),ShAmt),
1519 LI->getName(), LI);
1520 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Gabor Greifa645dd32008-05-16 19:29:10 +00001521 NV = BinaryOperator::CreateShl(NV,
Chris Lattner5f062542008-02-29 07:12:06 +00001522 ConstantInt::get(NV->getType(),-ShAmt),
1523 LI->getName(), LI);
1524
1525 // Finally, unconditionally truncate the integer to the right width.
Chris Lattner3fd59362009-01-07 06:34:28 +00001526 unsigned LIBitWidth = TD->getTypeSizeInBits(LI->getType());
Chris Lattner5f062542008-02-29 07:12:06 +00001527 if (LIBitWidth < NTy->getBitWidth())
1528 NV = new TruncInst(NV, IntegerType::get(LIBitWidth),
1529 LI->getName(), LI);
1530
1531 // If the result is an integer, this is a trunc or bitcast.
1532 if (isa<IntegerType>(LI->getType())) {
1533 // Should be done.
1534 } else if (LI->getType()->isFloatingPoint()) {
1535 // Just do a bitcast, we know the sizes match up.
Chris Lattner41d58652008-02-29 07:03:13 +00001536 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1537 } else {
Chris Lattner5f062542008-02-29 07:12:06 +00001538 // Otherwise must be a pointer.
1539 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
Chris Lattner41d58652008-02-29 07:03:13 +00001540 }
Chris Lattner5f062542008-02-29 07:12:06 +00001541 assert(NV->getType() == LI->getType() && "Didn't convert right?");
Chris Lattner41d58652008-02-29 07:03:13 +00001542 return NV;
1543}
1544
1545
1546/// ConvertUsesOfStoreToScalar - Convert the specified store to a load+store
1547/// pair of the new alloca directly, returning the value that should be stored
1548/// to the alloca. This happens when we are converting an "integer union" to a
1549/// single integer scalar, or when we are converting a "vector union" to a
1550/// vector with insert/extractelement instructions.
1551///
1552/// Offset is an offset from the original alloca, in bits that need to be
1553/// shifted to the right. By the end of this, there should be no uses of Ptr.
1554Value *SROA::ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
1555 unsigned Offset) {
1556
1557 // Convert the stored type to the actual type, shift it left to insert
1558 // then 'or' into place.
1559 Value *SV = SI->getOperand(0);
1560 const Type *AllocaType = NewAI->getType()->getElementType();
1561 if (SV->getType() == AllocaType && Offset == 0) {
1562 // All is well.
1563 } else if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
1564 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1565
1566 // If the result alloca is a vector type, this is either an element
1567 // access or a bitcast to another vector type.
1568 if (isa<VectorType>(SV->getType())) {
1569 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1570 } else {
1571 // Must be an element insertion.
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001572 unsigned Elt = Offset/TD->getTypePaddedSizeInBits(PTy->getElementType());
Gabor Greifd6da1d02008-04-06 20:25:17 +00001573 SV = InsertElementInst::Create(Old, SV,
1574 ConstantInt::get(Type::Int32Ty, Elt),
1575 "tmp", SI);
Chris Lattner41d58652008-02-29 07:03:13 +00001576 }
1577 } else if (isa<PointerType>(AllocaType)) {
1578 // If the alloca type is a pointer, then all the elements must be
1579 // pointers.
1580 if (SV->getType() != AllocaType)
1581 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1582 } else {
1583 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1584
1585 // If SV is a float, convert it to the appropriate integer type.
1586 // If it is a pointer, do the same, and also handle ptr->ptr casts
1587 // here.
Chris Lattner3fd59362009-01-07 06:34:28 +00001588 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1589 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1590 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1591 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
Chris Lattner41d58652008-02-29 07:03:13 +00001592 if (SV->getType()->isFloatingPoint())
1593 SV = new BitCastInst(SV, IntegerType::get(SrcWidth),
1594 SV->getName(), SI);
1595 else if (isa<PointerType>(SV->getType()))
Chris Lattner3fd59362009-01-07 06:34:28 +00001596 SV = new PtrToIntInst(SV, TD->getIntPtrType(), SV->getName(), SI);
Chris Lattner41d58652008-02-29 07:03:13 +00001597
1598 // Always zero extend the value if needed.
1599 if (SV->getType() != AllocaType)
1600 SV = new ZExtInst(SV, AllocaType, SV->getName(), SI);
1601
1602 // If this is a big-endian system and the store is narrower than the
1603 // full alloca type, we need to do a shift to get the right bits.
1604 int ShAmt = 0;
Chris Lattner3fd59362009-01-07 06:34:28 +00001605 if (TD->isBigEndian()) {
Chris Lattner41d58652008-02-29 07:03:13 +00001606 // On big-endian machines, the lowest bit is stored at the bit offset
1607 // from the pointer given by getTypeStoreSizeInBits. This matters for
1608 // integers with a bitwidth that is not a multiple of 8.
1609 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1610 } else {
1611 ShAmt = Offset;
1612 }
1613
1614 // Note: we support negative bitwidths (with shr) which are not defined.
1615 // We do this to support (f.e.) stores off the end of a structure where
1616 // only some bits in the structure are set.
1617 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1618 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Gabor Greifa645dd32008-05-16 19:29:10 +00001619 SV = BinaryOperator::CreateShl(SV,
Chris Lattner41d58652008-02-29 07:03:13 +00001620 ConstantInt::get(SV->getType(), ShAmt),
1621 SV->getName(), SI);
1622 Mask <<= ShAmt;
1623 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Gabor Greifa645dd32008-05-16 19:29:10 +00001624 SV = BinaryOperator::CreateLShr(SV,
Chris Lattner41d58652008-02-29 07:03:13 +00001625 ConstantInt::get(SV->getType(),-ShAmt),
1626 SV->getName(), SI);
1627 Mask = Mask.lshr(ShAmt);
1628 }
1629
1630 // Mask out the bits we are about to insert from the old value, and or
1631 // in the new bits.
1632 if (SrcWidth != DestWidth) {
1633 assert(DestWidth > SrcWidth);
Gabor Greifa645dd32008-05-16 19:29:10 +00001634 Old = BinaryOperator::CreateAnd(Old, ConstantInt::get(~Mask),
Chris Lattner41d58652008-02-29 07:03:13 +00001635 Old->getName()+".mask", SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00001636 SV = BinaryOperator::CreateOr(Old, SV, SV->getName()+".ins", SI);
Chris Lattner41d58652008-02-29 07:03:13 +00001637 }
1638 }
1639 return SV;
1640}
1641
1642
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001643
1644/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1645/// some part of a constant global variable. This intentionally only accepts
1646/// constant expressions because we don't can't rewrite arbitrary instructions.
1647static bool PointsToConstantGlobal(Value *V) {
1648 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1649 return GV->isConstant();
1650 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1651 if (CE->getOpcode() == Instruction::BitCast ||
1652 CE->getOpcode() == Instruction::GetElementPtr)
1653 return PointsToConstantGlobal(CE->getOperand(0));
1654 return false;
1655}
1656
1657/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1658/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1659/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1660/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1661/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1662/// the alloca, and if the source pointer is a pointer to a constant global, we
1663/// can optimize this.
1664static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1665 bool isOffset) {
1666 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Chris Lattner70ffe572009-01-28 20:16:43 +00001667 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1668 // Ignore non-volatile loads, they are always ok.
1669 if (!LI->isVolatile())
1670 continue;
1671
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001672 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1673 // If uses of the bitcast are ok, we are ok.
1674 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1675 return false;
1676 continue;
1677 }
1678 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1679 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1680 // doesn't, it does.
1681 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1682 isOffset || !GEP->hasAllZeroIndices()))
1683 return false;
1684 continue;
1685 }
1686
1687 // If this is isn't our memcpy/memmove, reject it as something we can't
1688 // handle.
1689 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1690 return false;
1691
1692 // If we already have seen a copy, reject the second one.
1693 if (TheCopy) return false;
1694
1695 // If the pointer has been offset from the start of the alloca, we can't
1696 // safely handle this.
1697 if (isOffset) return false;
1698
1699 // If the memintrinsic isn't using the alloca as the dest, reject it.
1700 if (UI.getOperandNo() != 1) return false;
1701
1702 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1703
1704 // If the source of the memcpy/move is not a constant global, reject it.
1705 if (!PointsToConstantGlobal(MI->getOperand(2)))
1706 return false;
1707
1708 // Otherwise, the transform is safe. Remember the copy instruction.
1709 TheCopy = MI;
1710 }
1711 return true;
1712}
1713
1714/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1715/// modified by a copy from a constant global. If we can prove this, we can
1716/// replace any uses of the alloca with uses of the global directly.
1717Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1718 Instruction *TheCopy = 0;
1719 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1720 return TheCopy;
1721 return 0;
1722}