blob: f0e51e589d7bfa5f375e992eeddba0f2704ee891 [file] [log] [blame]
Chris Lattnered7b41e2003-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:
Chris Lattnerb37923f2003-05-30 19:22:14 +000026 bool isSafeElementUse(Value *Ptr);
Chris Lattner5e062a12003-05-30 04:15:41 +000027 bool isSafeUseOfAllocation(Instruction *User);
28 bool isSafeStructAllocaToPromote(AllocationInst *AI);
29 bool isSafeArrayAllocaToPromote(AllocationInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +000030 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
31 };
32
33 RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
34}
35
36Pass *createScalarReplAggregatesPass() { return new SROA(); }
37
38
39// runOnFunction - This algorithm is a simple worklist driven algorithm, which
40// runs on all of the malloc/alloca instructions in the function, removing them
41// if they are only used by getelementptr instructions.
42//
43bool SROA::runOnFunction(Function &F) {
44 std::vector<AllocationInst*> WorkList;
45
46 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
47 BasicBlock &BB = F.getEntryNode();
48 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
49 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
50 WorkList.push_back(A);
51
52 // Process the worklist
53 bool Changed = false;
54 while (!WorkList.empty()) {
55 AllocationInst *AI = WorkList.back();
56 WorkList.pop_back();
57
58 // We cannot transform the allocation instruction if it is an array
Chris Lattnerd10376b2003-05-27 16:09:27 +000059 // allocation (allocations OF arrays are ok though), and an allocation of a
60 // scalar value cannot be decomposed at all.
61 //
Chris Lattnered7b41e2003-05-27 15:45:27 +000062 if (AI->isArrayAllocation() ||
Chris Lattnerd10376b2003-05-27 16:09:27 +000063 (!isa<StructType>(AI->getAllocatedType()) &&
64 !isa<ArrayType>(AI->getAllocatedType()))) continue;
65
Chris Lattner5e062a12003-05-30 04:15:41 +000066 // Check that all of the users of the allocation are capable of being
67 // transformed.
68 if (isa<StructType>(AI->getAllocatedType())) {
69 if (!isSafeStructAllocaToPromote(AI))
70 continue;
71 } else if (!isSafeArrayAllocaToPromote(AI))
72 continue;
Chris Lattnered7b41e2003-05-27 15:45:27 +000073
74 DEBUG(std::cerr << "Found inst to xform: " << *AI);
75 Changed = true;
76
77 std::vector<AllocaInst*> ElementAllocas;
78 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
79 ElementAllocas.reserve(ST->getNumContainedTypes());
80 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
81 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
82 AI->getName() + "." + utostr(i), AI);
83 ElementAllocas.push_back(NA);
84 WorkList.push_back(NA); // Add to worklist for recursive processing
85 }
86 } else {
Chris Lattner5e062a12003-05-30 04:15:41 +000087 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
Chris Lattnered7b41e2003-05-27 15:45:27 +000088 ElementAllocas.reserve(AT->getNumElements());
89 const Type *ElTy = AT->getElementType();
90 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
91 AllocaInst *NA = new AllocaInst(ElTy, 0,
92 AI->getName() + "." + utostr(i), AI);
93 ElementAllocas.push_back(NA);
94 WorkList.push_back(NA); // Add to worklist for recursive processing
95 }
96 }
97
98 // Now that we have created the alloca instructions that we want to use,
99 // expand the getelementptr instructions to use them.
100 //
101 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
102 I != E; ++I) {
103 Instruction *User = cast<Instruction>(*I);
104 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
105 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
106 uint64_t Idx;
107 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(GEPI->getOperand(2)))
108 Idx = CSI->getValue();
109 else
110 Idx = cast<ConstantUInt>(GEPI->getOperand(2))->getValue();
111
112 assert(Idx < ElementAllocas.size() && "Index out of range?");
113 AllocaInst *AllocaToUse = ElementAllocas[Idx];
114
115 Value *RepValue;
116 if (GEPI->getNumOperands() == 3) {
117 // Do not insert a new getelementptr instruction with zero indices,
118 // only to have it optimized out later.
119 RepValue = AllocaToUse;
120 } else {
121 // We are indexing deeply into the structure, so we still need a
122 // getelement ptr instruction to finish the indexing. This may be
123 // expanded itself once the worklist is rerun.
124 //
125 std::string OldName = GEPI->getName(); // Steal the old name...
Chris Lattner261d6862003-05-30 05:26:30 +0000126 std::vector<Value*> NewArgs;
127 NewArgs.push_back(Constant::getNullValue(Type::LongTy));
128 NewArgs.insert(NewArgs.end(), GEPI->op_begin()+3, GEPI->op_end());
Chris Lattnered7b41e2003-05-27 15:45:27 +0000129 GEPI->setName("");
130 RepValue =
Chris Lattner261d6862003-05-30 05:26:30 +0000131 new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000132 }
133
134 // Move all of the users over to the new GEP.
135 GEPI->replaceAllUsesWith(RepValue);
136 // Delete the old GEP
137 GEPI->getParent()->getInstList().erase(GEPI);
138 } else {
139 assert(0 && "Unexpected instruction type!");
140 }
141 }
142
143 // Finally, delete the Alloca instruction
144 AI->getParent()->getInstList().erase(AI);
Chris Lattnerd10376b2003-05-27 16:09:27 +0000145 NumReplaced++;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000146 }
147
148 return Changed;
149}
Chris Lattner5e062a12003-05-30 04:15:41 +0000150
151
152/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
153/// aggregate allocation.
154///
155bool SROA::isSafeUseOfAllocation(Instruction *User) {
156 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
157 // The GEP is safe to transform if it is of the form GEP <ptr>, 0, <cst>
158 if (GEPI->getNumOperands() <= 2 ||
159 GEPI->getOperand(1) != Constant::getNullValue(Type::LongTy) ||
160 !isa<Constant>(GEPI->getOperand(2)) ||
161 isa<ConstantExpr>(GEPI->getOperand(2)))
162 return false;
163 } else {
164 return false;
165 }
166 return true;
167}
168
Chris Lattnerb37923f2003-05-30 19:22:14 +0000169/// isSafeElementUse - Check to see if this use is an allowed use for a
Chris Lattner5e062a12003-05-30 04:15:41 +0000170/// getelementptr instruction of an array aggregate allocation.
171///
Chris Lattnerb37923f2003-05-30 19:22:14 +0000172bool SROA::isSafeElementUse(Value *Ptr) {
Chris Lattner5e062a12003-05-30 04:15:41 +0000173 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
174 I != E; ++I) {
175 Instruction *User = cast<Instruction>(*I);
176 switch (User->getOpcode()) {
177 case Instruction::Load: return true;
178 case Instruction::Store: return User->getOperand(0) != Ptr;
179 case Instruction::GetElementPtr: {
180 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
181 if (GEP->getNumOperands() > 1) {
182 if (!isa<Constant>(GEP->getOperand(1)) ||
183 !cast<Constant>(GEP->getOperand(1))->isNullValue())
184 return false; // Using pointer arithmetic to navigate the array...
Chris Lattner5e062a12003-05-30 04:15:41 +0000185 }
Chris Lattnerb37923f2003-05-30 19:22:14 +0000186 return isSafeElementUse(GEP);
Chris Lattner5e062a12003-05-30 04:15:41 +0000187 }
188 default:
189 DEBUG(std::cerr << " Transformation preventing inst: " << *User);
190 return false;
191 }
192 }
193 return true; // All users look ok :)
194}
195
196
197/// isSafeStructAllocaToPromote - Check to see if the specified allocation of a
198/// structure can be broken down into elements.
199///
200bool SROA::isSafeStructAllocaToPromote(AllocationInst *AI) {
201 // Loop over the use list of the alloca. We can only transform it if all of
202 // the users are safe to transform.
203 //
204 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
Chris Lattner26d2ca12003-05-30 18:09:57 +0000205 I != E; ++I) {
Chris Lattner5e062a12003-05-30 04:15:41 +0000206 if (!isSafeUseOfAllocation(cast<Instruction>(*I))) {
207 DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: "
208 << *I);
209 return false;
210 }
Chris Lattner26d2ca12003-05-30 18:09:57 +0000211
212 // Pedantic check to avoid breaking broken programs...
213 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*I))
Chris Lattnerb37923f2003-05-30 19:22:14 +0000214 if (GEPI->getNumOperands() == 3 && !isSafeElementUse(GEPI))
Chris Lattner26d2ca12003-05-30 18:09:57 +0000215 return false;
216 }
Chris Lattner5e062a12003-05-30 04:15:41 +0000217 return true;
218}
219
220
221/// isSafeArrayAllocaToPromote - Check to see if the specified allocation of a
222/// structure can be broken down into elements.
223///
224bool SROA::isSafeArrayAllocaToPromote(AllocationInst *AI) {
225 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
226 int64_t NumElements = AT->getNumElements();
227
228 // Loop over the use list of the alloca. We can only transform it if all of
229 // the users are safe to transform. Array allocas have extra constraints to
230 // meet though.
231 //
232 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
233 I != E; ++I) {
234 Instruction *User = cast<Instruction>(*I);
235 if (!isSafeUseOfAllocation(User)) {
236 DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: "
237 << User);
238 return false;
239 }
240
241 // Check to make sure that getelementptr follow the extra rules for arrays:
242 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
243 // Check to make sure that index falls within the array. If not,
244 // something funny is going on, so we won't do the optimization.
245 //
246 if (cast<ConstantSInt>(GEPI->getOperand(2))->getValue() >= NumElements)
247 return false;
248
249 // Check to make sure that the only thing that uses the resultant pointer
250 // is safe for an array access. For example, code that looks like:
251 // P = &A[0]; P = P + 1
252 // is legal, and should prevent promotion.
253 //
Chris Lattnerb37923f2003-05-30 19:22:14 +0000254 if (!isSafeElementUse(GEPI)) {
Chris Lattner5e062a12003-05-30 04:15:41 +0000255 DEBUG(std::cerr << "Cannot transform: " << *AI
256 << " due to uses of user: " << *GEPI);
257 return false;
258 }
259 }
260 }
261 return true;
262}
263