1 //===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
20 //===----------------------------------------------------------------------===//
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"
43 STATISTIC(NumReplaced, "Number of allocas broken up");
44 STATISTIC(NumPromoted, "Number of allocas promoted");
45 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
46 STATISTIC(NumGlobals, "Number of allocas copied from constant global");
49 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
50 bool runOnFunction(Function &F);
52 bool performScalarRepl(Function &F);
53 bool performPromotion(Function &F);
55 // getAnalysisUsage - This pass does not require any passes, but we know it
56 // will not alter the CFG, so say so.
57 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
58 AU.addRequired<ETForest>();
59 AU.addRequired<DominanceFrontier>();
60 AU.addRequired<TargetData>();
65 int isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI);
66 int isSafeUseOfAllocation(Instruction *User, AllocationInst *AI);
67 bool isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI);
68 bool isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI);
69 int isSafeAllocaToScalarRepl(AllocationInst *AI);
70 void DoScalarReplacement(AllocationInst *AI,
71 std::vector<AllocationInst*> &WorkList);
72 void CanonicalizeAllocaUsers(AllocationInst *AI);
73 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
75 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
76 SmallVector<AllocaInst*, 32> &NewElts);
78 const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
79 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
80 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
81 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
84 RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
87 // Public interface to the ScalarReplAggregates pass
88 FunctionPass *llvm::createScalarReplAggregatesPass() { return new SROA(); }
91 bool SROA::runOnFunction(Function &F) {
92 bool Changed = performPromotion(F);
94 bool LocalChange = performScalarRepl(F);
95 if (!LocalChange) break; // No need to repromote if no scalarrepl
97 LocalChange = performPromotion(F);
98 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
105 bool SROA::performPromotion(Function &F) {
106 std::vector<AllocaInst*> Allocas;
107 ETForest &ET = getAnalysis<ETForest>();
108 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
110 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
112 bool Changed = false;
117 // Find allocas that are safe to promote, by looking at all instructions in
119 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
120 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
121 if (isAllocaPromotable(AI))
122 Allocas.push_back(AI);
124 if (Allocas.empty()) break;
126 PromoteMemToReg(Allocas, ET, DF);
127 NumPromoted += Allocas.size();
134 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
135 // which runs on all of the malloc/alloca instructions in the function, removing
136 // them if they are only used by getelementptr instructions.
138 bool SROA::performScalarRepl(Function &F) {
139 std::vector<AllocationInst*> WorkList;
141 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
142 BasicBlock &BB = F.getEntryBlock();
143 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
144 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
145 WorkList.push_back(A);
147 // Process the worklist
148 bool Changed = false;
149 while (!WorkList.empty()) {
150 AllocationInst *AI = WorkList.back();
153 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
154 // with unused elements.
155 if (AI->use_empty()) {
156 AI->eraseFromParent();
160 // If we can turn this aggregate value (potentially with casts) into a
161 // simple scalar value that can be mem2reg'd into a register value.
162 bool IsNotTrivial = false;
163 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
164 if (IsNotTrivial && ActualType != Type::VoidTy) {
165 ConvertToScalar(AI, ActualType);
170 // Check to see if we can perform the core SROA transformation. We cannot
171 // transform the allocation instruction if it is an array allocation
172 // (allocations OF arrays are ok though), and an allocation of a scalar
173 // value cannot be decomposed at all.
174 if (!AI->isArrayAllocation() &&
175 (isa<StructType>(AI->getAllocatedType()) ||
176 isa<ArrayType>(AI->getAllocatedType()))) {
177 // Check that all of the users of the allocation are capable of being
179 switch (isSafeAllocaToScalarRepl(AI)) {
180 default: assert(0 && "Unexpected value!");
181 case 0: // Not safe to scalar replace.
183 case 1: // Safe, but requires cleanup/canonicalizations first
184 CanonicalizeAllocaUsers(AI);
186 case 3: // Safe to scalar replace.
187 DoScalarReplacement(AI, WorkList);
193 // Check to see if this allocation is only modified by a memcpy/memmove from
194 // a constant global. If this is the case, we can change all users to use
195 // the constant global instead. This is commonly produced by the CFE by
196 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
197 // is only subsequently read.
198 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
199 DOUT << "Found alloca equal to global: " << *AI;
200 DOUT << " memcpy = " << *TheCopy;
201 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
202 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
203 TheCopy->eraseFromParent(); // Don't mutate the global.
204 AI->eraseFromParent();
210 // Otherwise, couldn't process this.
216 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
217 /// predicate, do SROA now.
218 void SROA::DoScalarReplacement(AllocationInst *AI,
219 std::vector<AllocationInst*> &WorkList) {
220 DOUT << "Found inst to SROA: " << *AI;
221 SmallVector<AllocaInst*, 32> ElementAllocas;
222 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
223 ElementAllocas.reserve(ST->getNumContainedTypes());
224 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
225 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
227 AI->getName() + "." + utostr(i), AI);
228 ElementAllocas.push_back(NA);
229 WorkList.push_back(NA); // Add to worklist for recursive processing
232 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
233 ElementAllocas.reserve(AT->getNumElements());
234 const Type *ElTy = AT->getElementType();
235 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
236 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
237 AI->getName() + "." + utostr(i), AI);
238 ElementAllocas.push_back(NA);
239 WorkList.push_back(NA); // Add to worklist for recursive processing
243 // Now that we have created the alloca instructions that we want to use,
244 // expand the getelementptr instructions to use them.
246 while (!AI->use_empty()) {
247 Instruction *User = cast<Instruction>(AI->use_back());
248 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
249 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
250 BCInst->eraseFromParent();
254 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
255 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
257 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
259 assert(Idx < ElementAllocas.size() && "Index out of range?");
260 AllocaInst *AllocaToUse = ElementAllocas[Idx];
263 if (GEPI->getNumOperands() == 3) {
264 // Do not insert a new getelementptr instruction with zero indices, only
265 // to have it optimized out later.
266 RepValue = AllocaToUse;
268 // We are indexing deeply into the structure, so we still need a
269 // getelement ptr instruction to finish the indexing. This may be
270 // expanded itself once the worklist is rerun.
272 SmallVector<Value*, 8> NewArgs;
273 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
274 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
275 RepValue = new GetElementPtrInst(AllocaToUse, &NewArgs[0],
276 NewArgs.size(), "", GEPI);
277 RepValue->takeName(GEPI);
280 // If this GEP is to the start of the aggregate, check for memcpys.
282 bool IsStartOfAggregateGEP = true;
283 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i) {
284 if (!isa<ConstantInt>(GEPI->getOperand(i))) {
285 IsStartOfAggregateGEP = false;
288 if (!cast<ConstantInt>(GEPI->getOperand(i))->isZero()) {
289 IsStartOfAggregateGEP = false;
294 if (IsStartOfAggregateGEP)
295 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
299 // Move all of the users over to the new GEP.
300 GEPI->replaceAllUsesWith(RepValue);
301 // Delete the old GEP
302 GEPI->eraseFromParent();
305 // Finally, delete the Alloca instruction
306 AI->eraseFromParent();
311 /// isSafeElementUse - Check to see if this use is an allowed use for a
312 /// getelementptr instruction of an array aggregate allocation. isFirstElt
313 /// indicates whether Ptr is known to the start of the aggregate.
315 int SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI) {
316 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
318 Instruction *User = cast<Instruction>(*I);
319 switch (User->getOpcode()) {
320 case Instruction::Load: break;
321 case Instruction::Store:
322 // Store is ok if storing INTO the pointer, not storing the pointer
323 if (User->getOperand(0) == Ptr) return 0;
325 case Instruction::GetElementPtr: {
326 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
327 bool AreAllZeroIndices = isFirstElt;
328 if (GEP->getNumOperands() > 1) {
329 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
330 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
331 return 0; // Using pointer arithmetic to navigate the array.
333 if (AreAllZeroIndices) {
334 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
335 if (!isa<ConstantInt>(GEP->getOperand(i)) ||
336 !cast<ConstantInt>(GEP->getOperand(i))->isZero()) {
337 AreAllZeroIndices = false;
343 if (!isSafeElementUse(GEP, AreAllZeroIndices, AI)) return 0;
346 case Instruction::BitCast:
348 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI))
350 DOUT << " Transformation preventing inst: " << *User;
352 case Instruction::Call:
353 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
354 if (isFirstElt && isSafeMemIntrinsicOnAllocation(MI, AI))
357 DOUT << " Transformation preventing inst: " << *User;
360 DOUT << " Transformation preventing inst: " << *User;
364 return 3; // All users look ok :)
367 /// AllUsersAreLoads - Return true if all users of this value are loads.
368 static bool AllUsersAreLoads(Value *Ptr) {
369 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
371 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
376 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
377 /// aggregate allocation.
379 int SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI) {
380 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
381 return isSafeUseOfBitCastedAllocation(C, AI) ? 3 : 0;
382 if (!isa<GetElementPtrInst>(User)) return 0;
384 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
385 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
387 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
389 I.getOperand() != Constant::getNullValue(I.getOperand()->getType()))
393 if (I == E) return 0; // ran out of GEP indices??
395 bool IsAllZeroIndices = true;
397 // If this is a use of an array allocation, do a bit more checking for sanity.
398 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
399 uint64_t NumElements = AT->getNumElements();
401 if (ConstantInt *Idx = dyn_cast<ConstantInt>(I.getOperand())) {
402 IsAllZeroIndices &= Idx->isZero();
404 // Check to make sure that index falls within the array. If not,
405 // something funny is going on, so we won't do the optimization.
407 if (Idx->getZExtValue() >= NumElements)
410 // We cannot scalar repl this level of the array unless any array
411 // sub-indices are in-range constants. In particular, consider:
412 // A[0][i]. We cannot know that the user isn't doing invalid things like
413 // allowing i to index an out-of-range subscript that accesses A[1].
415 // Scalar replacing *just* the outer index of the array is probably not
416 // going to be a win anyway, so just give up.
417 for (++I; I != E && (isa<ArrayType>(*I) || isa<VectorType>(*I)); ++I) {
418 uint64_t NumElements;
419 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*I))
420 NumElements = SubArrayTy->getNumElements();
422 NumElements = cast<VectorType>(*I)->getNumElements();
424 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
425 if (!IdxVal) return 0;
426 if (IdxVal->getZExtValue() >= NumElements)
428 IsAllZeroIndices &= IdxVal->isZero();
432 IsAllZeroIndices = 0;
434 // If this is an array index and the index is not constant, we cannot
435 // promote... that is unless the array has exactly one or two elements in
436 // it, in which case we CAN promote it, but we have to canonicalize this
437 // out if this is the only problem.
438 if ((NumElements == 1 || NumElements == 2) &&
439 AllUsersAreLoads(GEPI))
440 return 1; // Canonicalization required!
445 // If there are any non-simple uses of this getelementptr, make sure to reject
447 return isSafeElementUse(GEPI, IsAllZeroIndices, AI);
450 /// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
451 /// intrinsic can be promoted by SROA. At this point, we know that the operand
452 /// of the memintrinsic is a pointer to the beginning of the allocation.
453 bool SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI){
454 // If not constant length, give up.
455 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
456 if (!Length) return false;
458 // If not the whole aggregate, give up.
459 const TargetData &TD = getAnalysis<TargetData>();
460 if (Length->getZExtValue() != TD.getTypeSize(AI->getType()->getElementType()))
463 // We only know about memcpy/memset/memmove.
464 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
466 // Otherwise, we can transform it.
470 /// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
472 bool SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI) {
473 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
475 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
476 if (!isSafeUseOfBitCastedAllocation(BCU, AI))
478 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
479 if (!isSafeMemIntrinsicOnAllocation(MI, AI))
488 /// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
489 /// to its first element. Transform users of the cast to use the new values
491 void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
492 SmallVector<AllocaInst*, 32> &NewElts) {
493 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
494 const TargetData &TD = getAnalysis<TargetData>();
496 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
498 if (BitCastInst *BCU = dyn_cast<BitCastInst>(*UI)) {
499 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
501 BCU->eraseFromParent();
505 // Otherwise, must be memcpy/memmove/memset of the entire aggregate. Split
506 // into one per element.
507 MemIntrinsic *MI = dyn_cast<MemIntrinsic>(*UI);
509 // If it's not a mem intrinsic, it must be some other user of a gep of the
510 // first pointer. Just leave these alone.
516 // If this is a memcpy/memmove, construct the other pointer as the
519 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
520 if (BCInst == MCI->getRawDest())
521 OtherPtr = MCI->getRawSource();
523 assert(BCInst == MCI->getRawSource());
524 OtherPtr = MCI->getRawDest();
526 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
527 if (BCInst == MMI->getRawDest())
528 OtherPtr = MMI->getRawSource();
530 assert(BCInst == MMI->getRawSource());
531 OtherPtr = MMI->getRawDest();
535 // If there is an other pointer, we want to convert it to the same pointer
536 // type as AI has, so we can GEP through it.
538 // It is likely that OtherPtr is a bitcast, if so, remove it.
539 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
540 OtherPtr = BC->getOperand(0);
541 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
542 if (BCE->getOpcode() == Instruction::BitCast)
543 OtherPtr = BCE->getOperand(0);
545 // If the pointer is not the right type, insert a bitcast to the right
547 if (OtherPtr->getType() != AI->getType())
548 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
552 // Process each element of the aggregate.
553 Value *TheFn = MI->getOperand(0);
554 const Type *BytePtrTy = MI->getRawDest()->getType();
555 bool SROADest = MI->getRawDest() == BCInst;
557 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
558 // If this is a memcpy/memmove, emit a GEP of the other element address.
561 OtherElt = new GetElementPtrInst(OtherPtr, Zero,
562 ConstantInt::get(Type::Int32Ty, i),
563 OtherPtr->getNameStr()+"."+utostr(i),
567 Value *EltPtr = NewElts[i];
568 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
570 // If we got down to a scalar, insert a load or store as appropriate.
571 if (EltTy->isFirstClassType()) {
572 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
573 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
575 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
578 assert(isa<MemSetInst>(MI));
580 // If the stored element is zero (common case), just store a null
583 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
585 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
587 // If EltTy is a packed type, get the element type.
588 const Type *ValTy = EltTy;
589 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
590 ValTy = VTy->getElementType();
592 // Construct an integer with the right value.
593 unsigned EltSize = TD.getTypeSize(ValTy);
594 APInt OneVal(EltSize*8, CI->getZExtValue());
595 APInt TotalVal(OneVal);
597 for (unsigned i = 0; i != EltSize-1; ++i) {
598 TotalVal = TotalVal.shl(8);
602 // Convert the integer value to the appropriate type.
603 StoreVal = ConstantInt::get(TotalVal);
604 if (isa<PointerType>(ValTy))
605 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
606 else if (ValTy->isFloatingPoint())
607 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
608 assert(StoreVal->getType() == ValTy && "Type mismatch!");
610 // If the requested value was a vector constant, create it.
611 if (EltTy != ValTy) {
612 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
613 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
614 StoreVal = ConstantVector::get(&Elts[0], NumElts);
617 new StoreInst(StoreVal, EltPtr, MI);
620 // Otherwise, if we're storing a byte variable, use a memset call for
625 // Cast the element pointer to BytePtrTy.
626 if (EltPtr->getType() != BytePtrTy)
627 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
629 // Cast the other pointer (if we have one) to BytePtrTy.
630 if (OtherElt && OtherElt->getType() != BytePtrTy)
631 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
634 unsigned EltSize = TD.getTypeSize(EltTy);
636 // Finally, insert the meminst for this element.
637 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
639 SROADest ? EltPtr : OtherElt, // Dest ptr
640 SROADest ? OtherElt : EltPtr, // Src ptr
641 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
644 new CallInst(TheFn, Ops, 4, "", MI);
646 assert(isa<MemSetInst>(MI));
648 EltPtr, MI->getOperand(2), // Dest, Value,
649 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
652 new CallInst(TheFn, Ops, 4, "", MI);
656 // Finally, MI is now dead, as we've modified its actions to occur on all of
657 // the elements of the aggregate.
659 MI->eraseFromParent();
664 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
665 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
666 /// or 1 if safe after canonicalization has been performed.
668 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
669 // Loop over the use list of the alloca. We can only transform it if all of
670 // the users are safe to transform.
673 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
675 isSafe &= isSafeUseOfAllocation(cast<Instruction>(*I), AI);
677 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
681 // If we require cleanup, isSafe is now 1, otherwise it is 3.
685 /// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
686 /// allocation, but only if cleaned up, perform the cleanups required.
687 void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
688 // At this point, we know that the end result will be SROA'd and promoted, so
689 // we can insert ugly code if required so long as sroa+mem2reg will clean it
691 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
693 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
695 gep_type_iterator I = gep_type_begin(GEPI);
698 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
699 uint64_t NumElements = AT->getNumElements();
701 if (!isa<ConstantInt>(I.getOperand())) {
702 if (NumElements == 1) {
703 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
705 assert(NumElements == 2 && "Unhandled case!");
706 // All users of the GEP must be loads. At each use of the GEP, insert
707 // two loads of the appropriate indexed GEP and select between them.
708 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
709 Constant::getNullValue(I.getOperand()->getType()),
711 // Insert the new GEP instructions, which are properly indexed.
712 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
713 Indices[1] = Constant::getNullValue(Type::Int32Ty);
714 Value *ZeroIdx = new GetElementPtrInst(GEPI->getOperand(0),
715 &Indices[0], Indices.size(),
716 GEPI->getName()+".0", GEPI);
717 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
718 Value *OneIdx = new GetElementPtrInst(GEPI->getOperand(0),
719 &Indices[0], Indices.size(),
720 GEPI->getName()+".1", GEPI);
721 // Replace all loads of the variable index GEP with loads from both
722 // indexes and a select.
723 while (!GEPI->use_empty()) {
724 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
725 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
726 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
727 Value *R = new SelectInst(IsOne, One, Zero, LI->getName(), LI);
728 LI->replaceAllUsesWith(R);
729 LI->eraseFromParent();
731 GEPI->eraseFromParent();
738 /// MergeInType - Add the 'In' type to the accumulated type so far. If the
739 /// types are incompatible, return true, otherwise update Accum and return
742 /// There are three cases we handle here:
743 /// 1) An effectively-integer union, where the pieces are stored into as
744 /// smaller integers (common with byte swap and other idioms).
745 /// 2) A union of vector types of the same size and potentially its elements.
746 /// Here we turn element accesses into insert/extract element operations.
747 /// 3) A union of scalar types, such as int/float or int/pointer. Here we
748 /// merge together into integers, allowing the xform to work with #1 as
750 static bool MergeInType(const Type *In, const Type *&Accum,
751 const TargetData &TD) {
752 // If this is our first type, just use it.
753 const VectorType *PTy;
754 if (Accum == Type::VoidTy || In == Accum) {
756 } else if (In == Type::VoidTy) {
758 } else if (In->isInteger() && Accum->isInteger()) { // integer union.
759 // Otherwise pick whichever type is larger.
760 if (cast<IntegerType>(In)->getBitWidth() >
761 cast<IntegerType>(Accum)->getBitWidth())
763 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
764 // Pointer unions just stay as one of the pointers.
765 } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
766 if ((PTy = dyn_cast<VectorType>(Accum)) &&
767 PTy->getElementType() == In) {
768 // Accum is a vector, and we are accessing an element: ok.
769 } else if ((PTy = dyn_cast<VectorType>(In)) &&
770 PTy->getElementType() == Accum) {
771 // In is a vector, and accum is an element: ok, remember In.
773 } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
774 PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
775 // Two vectors of the same size: keep Accum.
777 // Cannot insert an short into a <4 x int> or handle
778 // <2 x int> -> <4 x int>
782 // Pointer/FP/Integer unions merge together as integers.
783 switch (Accum->getTypeID()) {
784 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
785 case Type::FloatTyID: Accum = Type::Int32Ty; break;
786 case Type::DoubleTyID: Accum = Type::Int64Ty; break;
788 assert(Accum->isInteger() && "Unknown FP type!");
792 switch (In->getTypeID()) {
793 case Type::PointerTyID: In = TD.getIntPtrType(); break;
794 case Type::FloatTyID: In = Type::Int32Ty; break;
795 case Type::DoubleTyID: In = Type::Int64Ty; break;
797 assert(In->isInteger() && "Unknown FP type!");
800 return MergeInType(In, Accum, TD);
805 /// getUIntAtLeastAsBitAs - Return an unsigned integer type that is at least
806 /// as big as the specified type. If there is no suitable type, this returns
808 const Type *getUIntAtLeastAsBitAs(unsigned NumBits) {
809 if (NumBits > 64) return 0;
810 if (NumBits > 32) return Type::Int64Ty;
811 if (NumBits > 16) return Type::Int32Ty;
812 if (NumBits > 8) return Type::Int16Ty;
816 /// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
817 /// single scalar integer type, return that type. Further, if the use is not
818 /// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
819 /// there are no uses of this pointer, return Type::VoidTy to differentiate from
822 const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
823 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
824 const TargetData &TD = getAnalysis<TargetData>();
825 const PointerType *PTy = cast<PointerType>(V->getType());
827 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
828 Instruction *User = cast<Instruction>(*UI);
830 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
831 if (MergeInType(LI->getType(), UsedType, TD))
834 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
835 // Storing the pointer, not into the value?
836 if (SI->getOperand(0) == V) return 0;
838 // NOTE: We could handle storing of FP imms into integers here!
840 if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD))
842 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
844 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
845 if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0;
846 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
847 // Check to see if this is stepping over an element: GEP Ptr, int C
848 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
849 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
850 unsigned ElSize = TD.getTypeSize(PTy->getElementType());
851 unsigned BitOffset = Idx*ElSize*8;
852 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
855 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
856 if (SubElt == 0) return 0;
857 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
859 getUIntAtLeastAsBitAs(TD.getTypeSize(SubElt)*8+BitOffset);
860 if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0;
863 } else if (GEP->getNumOperands() == 3 &&
864 isa<ConstantInt>(GEP->getOperand(1)) &&
865 isa<ConstantInt>(GEP->getOperand(2)) &&
866 cast<ConstantInt>(GEP->getOperand(1))->isZero()) {
867 // We are stepping into an element, e.g. a structure or an array:
868 // GEP Ptr, int 0, uint C
869 const Type *AggTy = PTy->getElementType();
870 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
872 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
873 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
874 } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
875 // Getting an element of the packed vector.
876 if (Idx >= VectorTy->getNumElements()) return 0; // Out of range.
878 // Merge in the vector type.
879 if (MergeInType(VectorTy, UsedType, TD)) return 0;
881 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
882 if (SubTy == 0) return 0;
884 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
887 // We'll need to change this to an insert/extract element operation.
889 continue; // Everything looks ok
891 } else if (isa<StructType>(AggTy)) {
892 // Structs are always ok.
896 const Type *NTy = getUIntAtLeastAsBitAs(TD.getTypeSize(AggTy)*8);
897 if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0;
898 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
899 if (SubTy == 0) return 0;
900 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
902 continue; // Everything looks ok
906 // Cannot handle this!
914 /// ConvertToScalar - The specified alloca passes the CanConvertToScalar
915 /// predicate and is non-trivial. Convert it to something that can be trivially
916 /// promoted into a register by mem2reg.
917 void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
918 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
919 << *ActualTy << "\n";
922 BasicBlock *EntryBlock = AI->getParent();
923 assert(EntryBlock == &EntryBlock->getParent()->getEntryBlock() &&
924 "Not in the entry block!");
925 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
927 // Create and insert the alloca.
928 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
929 EntryBlock->begin());
930 ConvertUsesToScalar(AI, NewAI, 0);
935 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
936 /// directly. This happens when we are converting an "integer union" to a
937 /// single integer scalar, or when we are converting a "vector union" to a
938 /// vector with insert/extractelement instructions.
940 /// Offset is an offset from the original alloca, in bits that need to be
941 /// shifted to the right. By the end of this, there should be no uses of Ptr.
942 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
943 const TargetData &TD = getAnalysis<TargetData>();
944 while (!Ptr->use_empty()) {
945 Instruction *User = cast<Instruction>(Ptr->use_back());
947 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
948 // The load is a bit extract from NewAI shifted right by Offset bits.
949 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
950 if (NV->getType() == LI->getType()) {
951 // We win, no conversion needed.
952 } else if (const VectorType *PTy = dyn_cast<VectorType>(NV->getType())) {
953 // If the result alloca is a vector type, this is either an element
954 // access or a bitcast to another vector type.
955 if (isa<VectorType>(LI->getType())) {
956 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
958 // Must be an element access.
959 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
960 NV = new ExtractElementInst(
961 NV, ConstantInt::get(Type::Int32Ty, Elt), "tmp", LI);
963 } else if (isa<PointerType>(NV->getType())) {
964 assert(isa<PointerType>(LI->getType()));
965 // Must be ptr->ptr cast. Anything else would result in NV being
967 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
969 const IntegerType *NTy = cast<IntegerType>(NV->getType());
970 unsigned LIBitWidth = TD.getTypeSizeInBits(LI->getType());
972 // If this is a big-endian system and the load is narrower than the
973 // full alloca type, we need to do a shift to get the right bits.
975 if (TD.isBigEndian()) {
976 ShAmt = NTy->getBitWidth()-LIBitWidth-Offset;
981 // Note: we support negative bitwidths (with shl) which are not defined.
982 // We do this to support (f.e.) loads off the end of a structure where
983 // only some bits are used.
984 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
985 NV = BinaryOperator::createLShr(NV,
986 ConstantInt::get(NV->getType(),ShAmt),
988 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
989 NV = BinaryOperator::createShl(NV,
990 ConstantInt::get(NV->getType(),-ShAmt),
993 // Finally, unconditionally truncate the integer to the right width.
994 if (LIBitWidth < NTy->getBitWidth())
995 NV = new TruncInst(NV, IntegerType::get(LIBitWidth),
998 // If the result is an integer, this is a trunc or bitcast.
999 if (isa<IntegerType>(LI->getType())) {
1000 assert(NV->getType() == LI->getType() && "Truncate wasn't enough?");
1001 } else if (LI->getType()->isFloatingPoint()) {
1002 // Just do a bitcast, we know the sizes match up.
1003 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1005 // Otherwise must be a pointer.
1006 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
1009 LI->replaceAllUsesWith(NV);
1010 LI->eraseFromParent();
1011 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1012 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1014 // Convert the stored type to the actual type, shift it left to insert
1015 // then 'or' into place.
1016 Value *SV = SI->getOperand(0);
1017 const Type *AllocaType = NewAI->getType()->getElementType();
1018 if (SV->getType() == AllocaType) {
1020 } else if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
1021 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1023 // If the result alloca is a vector type, this is either an element
1024 // access or a bitcast to another vector type.
1025 if (isa<VectorType>(SV->getType())) {
1026 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1028 // Must be an element insertion.
1029 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
1030 SV = new InsertElementInst(Old, SV,
1031 ConstantInt::get(Type::Int32Ty, Elt),
1034 } else if (isa<PointerType>(AllocaType)) {
1035 // If the alloca type is a pointer, then all the elements must be
1037 if (SV->getType() != AllocaType)
1038 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1040 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1042 // If SV is a float, convert it to the appropriate integer type.
1043 // If it is a pointer, do the same, and also handle ptr->ptr casts
1045 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
1046 unsigned DestWidth = AllocaType->getPrimitiveSizeInBits();
1047 if (SV->getType()->isFloatingPoint())
1048 SV = new BitCastInst(SV, IntegerType::get(SrcWidth),
1050 else if (isa<PointerType>(SV->getType()))
1051 SV = new PtrToIntInst(SV, TD.getIntPtrType(), SV->getName(), SI);
1053 // Always zero extend the value if needed.
1054 if (SV->getType() != AllocaType)
1055 SV = new ZExtInst(SV, AllocaType, SV->getName(), SI);
1057 // If this is a big-endian system and the store is narrower than the
1058 // full alloca type, we need to do a shift to get the right bits.
1060 if (TD.isBigEndian()) {
1061 ShAmt = DestWidth-SrcWidth-Offset;
1066 // Note: we support negative bitwidths (with shr) which are not defined.
1067 // We do this to support (f.e.) stores off the end of a structure where
1068 // only some bits in the structure are set.
1069 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1070 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1071 SV = BinaryOperator::createShl(SV,
1072 ConstantInt::get(SV->getType(), ShAmt),
1075 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1076 SV = BinaryOperator::createLShr(SV,
1077 ConstantInt::get(SV->getType(),-ShAmt),
1079 Mask = Mask.lshr(ShAmt);
1082 // Mask out the bits we are about to insert from the old value, and or
1084 if (SrcWidth != DestWidth) {
1085 assert(DestWidth > SrcWidth);
1086 Old = BinaryOperator::createAnd(Old, ConstantInt::get(~Mask),
1087 Old->getName()+".mask", SI);
1088 SV = BinaryOperator::createOr(Old, SV, SV->getName()+".ins", SI);
1091 new StoreInst(SV, NewAI, SI);
1092 SI->eraseFromParent();
1094 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1095 ConvertUsesToScalar(CI, NewAI, Offset);
1096 CI->eraseFromParent();
1097 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1098 const PointerType *AggPtrTy =
1099 cast<PointerType>(GEP->getOperand(0)->getType());
1100 const TargetData &TD = getAnalysis<TargetData>();
1101 unsigned AggSizeInBits = TD.getTypeSize(AggPtrTy->getElementType())*8;
1103 // Check to see if this is stepping over an element: GEP Ptr, int C
1104 unsigned NewOffset = Offset;
1105 if (GEP->getNumOperands() == 2) {
1106 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1107 unsigned BitOffset = Idx*AggSizeInBits;
1109 NewOffset += BitOffset;
1110 } else if (GEP->getNumOperands() == 3) {
1111 // We know that operand #2 is zero.
1112 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1113 const Type *AggTy = AggPtrTy->getElementType();
1114 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
1115 unsigned ElSizeBits = TD.getTypeSize(SeqTy->getElementType())*8;
1117 NewOffset += ElSizeBits*Idx;
1118 } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
1119 unsigned EltBitOffset =
1120 TD.getStructLayout(STy)->getElementOffset(Idx)*8;
1122 NewOffset += EltBitOffset;
1124 assert(0 && "Unsupported operation!");
1128 assert(0 && "Unsupported operation!");
1131 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1132 GEP->eraseFromParent();
1134 assert(0 && "Unsupported operation!");
1141 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1142 /// some part of a constant global variable. This intentionally only accepts
1143 /// constant expressions because we don't can't rewrite arbitrary instructions.
1144 static bool PointsToConstantGlobal(Value *V) {
1145 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1146 return GV->isConstant();
1147 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1148 if (CE->getOpcode() == Instruction::BitCast ||
1149 CE->getOpcode() == Instruction::GetElementPtr)
1150 return PointsToConstantGlobal(CE->getOperand(0));
1154 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1155 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
1156 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
1157 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
1158 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1159 /// the alloca, and if the source pointer is a pointer to a constant global, we
1160 /// can optimize this.
1161 static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1163 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1164 if (isa<LoadInst>(*UI)) {
1165 // Ignore loads, they are always ok.
1168 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1169 // If uses of the bitcast are ok, we are ok.
1170 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1174 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1175 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1176 // doesn't, it does.
1177 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1178 isOffset || !GEP->hasAllZeroIndices()))
1183 // If this is isn't our memcpy/memmove, reject it as something we can't
1185 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1188 // If we already have seen a copy, reject the second one.
1189 if (TheCopy) return false;
1191 // If the pointer has been offset from the start of the alloca, we can't
1192 // safely handle this.
1193 if (isOffset) return false;
1195 // If the memintrinsic isn't using the alloca as the dest, reject it.
1196 if (UI.getOperandNo() != 1) return false;
1198 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1200 // If the source of the memcpy/move is not a constant global, reject it.
1201 if (!PointsToConstantGlobal(MI->getOperand(2)))
1204 // Otherwise, the transform is safe. Remember the copy instruction.
1210 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1211 /// modified by a copy from a constant global. If we can prove this, we can
1212 /// replace any uses of the alloca with uses of the global directly.
1213 Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1214 Instruction *TheCopy = 0;
1215 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))