blob: c540bba2703679b461dcb0f9c2744ad9ed0404c1 [file] [log] [blame]
Chris Lattnerfb41a502003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
2//
3// This transformation implements the well known scalar replacement of
4// aggregates transformation. This xform breaks up alloca instructions of
5// aggregate type (structure or array) into individual alloca instructions for
6// each member (if possible).
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/Transforms/Scalar.h"
11#include "llvm/Function.h"
12#include "llvm/Pass.h"
13#include "llvm/iMemory.h"
14#include "llvm/DerivedTypes.h"
15#include "llvm/Constants.h"
16#include "Support/StringExtras.h"
17#include "Support/Statistic.h"
18
19namespace {
20 Statistic<> NumReplaced("scalarrepl", "Number of alloca's broken up");
21
22 struct SROA : public FunctionPass {
23 bool runOnFunction(Function &F);
24
25 private:
26 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
27 };
28
29 RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
30}
31
32Pass *createScalarReplAggregatesPass() { return new SROA(); }
33
34
35// runOnFunction - This algorithm is a simple worklist driven algorithm, which
36// runs on all of the malloc/alloca instructions in the function, removing them
37// if they are only used by getelementptr instructions.
38//
39bool SROA::runOnFunction(Function &F) {
40 std::vector<AllocationInst*> WorkList;
41
42 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
43 BasicBlock &BB = F.getEntryNode();
44 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
45 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
46 WorkList.push_back(A);
47
48 // Process the worklist
49 bool Changed = false;
50 while (!WorkList.empty()) {
51 AllocationInst *AI = WorkList.back();
52 WorkList.pop_back();
53
54 // We cannot transform the allocation instruction if it is an array
Chris Lattnerc16b2102003-05-27 16:09:27 +000055 // allocation (allocations OF arrays are ok though), and an allocation of a
56 // scalar value cannot be decomposed at all.
57 //
Chris Lattnerfb41a502003-05-27 15:45:27 +000058 if (AI->isArrayAllocation() ||
Chris Lattnerc16b2102003-05-27 16:09:27 +000059 (!isa<StructType>(AI->getAllocatedType()) &&
60 !isa<ArrayType>(AI->getAllocatedType()))) continue;
61
62 const ArrayType *AT = dyn_cast<ArrayType>(AI->getAllocatedType());
63
Chris Lattnerfb41a502003-05-27 15:45:27 +000064 // Loop over the use list of the alloca. We can only transform it if there
65 // are only getelementptr instructions (with a zero first index) and free
66 // instructions.
67 //
68 bool CannotTransform = false;
69 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
70 I != E; ++I) {
71 Instruction *User = cast<Instruction>(*I);
72 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
73 // The GEP is safe to transform if it is of the form GEP <ptr>, 0, <cst>
74 if (GEPI->getNumOperands() <= 2 ||
75 GEPI->getOperand(1) != Constant::getNullValue(Type::LongTy) ||
76 !isa<Constant>(GEPI->getOperand(2)) ||
77 isa<ConstantExpr>(GEPI->getOperand(2))) {
78 DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: "
79 << User);
80 CannotTransform = true;
81 break;
82 }
Chris Lattnerc16b2102003-05-27 16:09:27 +000083
84 // If this is an array access, check to make sure that index falls
85 // within the array. If not, something funny is going on, so we won't
86 // do the optimization.
87 if (AT && cast<ConstantSInt>(GEPI->getOperand(2))->getValue() >=
88 AT->getNumElements()) {
89 DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: "
90 << User);
91 CannotTransform = true;
92 break;
93 }
94
Chris Lattnerfb41a502003-05-27 15:45:27 +000095 } else {
96 DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: "
97 << User);
98 CannotTransform = true;
99 break;
100 }
101 }
102
103 if (CannotTransform) continue;
104
105 DEBUG(std::cerr << "Found inst to xform: " << *AI);
106 Changed = true;
107
108 std::vector<AllocaInst*> ElementAllocas;
109 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
110 ElementAllocas.reserve(ST->getNumContainedTypes());
111 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
112 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
113 AI->getName() + "." + utostr(i), AI);
114 ElementAllocas.push_back(NA);
115 WorkList.push_back(NA); // Add to worklist for recursive processing
116 }
117 } else {
Chris Lattnerfb41a502003-05-27 15:45:27 +0000118 ElementAllocas.reserve(AT->getNumElements());
119 const Type *ElTy = AT->getElementType();
120 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
121 AllocaInst *NA = new AllocaInst(ElTy, 0,
122 AI->getName() + "." + utostr(i), AI);
123 ElementAllocas.push_back(NA);
124 WorkList.push_back(NA); // Add to worklist for recursive processing
125 }
126 }
127
128 // Now that we have created the alloca instructions that we want to use,
129 // expand the getelementptr instructions to use them.
130 //
131 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
132 I != E; ++I) {
133 Instruction *User = cast<Instruction>(*I);
134 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
135 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
136 uint64_t Idx;
137 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(GEPI->getOperand(2)))
138 Idx = CSI->getValue();
139 else
140 Idx = cast<ConstantUInt>(GEPI->getOperand(2))->getValue();
141
142 assert(Idx < ElementAllocas.size() && "Index out of range?");
143 AllocaInst *AllocaToUse = ElementAllocas[Idx];
144
145 Value *RepValue;
146 if (GEPI->getNumOperands() == 3) {
147 // Do not insert a new getelementptr instruction with zero indices,
148 // only to have it optimized out later.
149 RepValue = AllocaToUse;
150 } else {
151 // We are indexing deeply into the structure, so we still need a
152 // getelement ptr instruction to finish the indexing. This may be
153 // expanded itself once the worklist is rerun.
154 //
155 std::string OldName = GEPI->getName(); // Steal the old name...
156 GEPI->setName("");
157 RepValue =
158 new GetElementPtrInst(AllocaToUse,
159 std::vector<Value*>(GEPI->op_begin()+3,
160 GEPI->op_end()),
161 OldName, GEPI);
162 }
163
164 // Move all of the users over to the new GEP.
165 GEPI->replaceAllUsesWith(RepValue);
166 // Delete the old GEP
167 GEPI->getParent()->getInstList().erase(GEPI);
168 } else {
169 assert(0 && "Unexpected instruction type!");
170 }
171 }
172
173 // Finally, delete the Alloca instruction
174 AI->getParent()->getInstList().erase(AI);
Chris Lattnerc16b2102003-05-27 16:09:27 +0000175 NumReplaced++;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000176 }
177
178 return Changed;
179}