blob: 70f4dae3fd47ee235742a48397c6e967b3ee0f68 [file] [log] [blame]
Chris Lattnerfb41a502003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerfb41a502003-05-27 15:45:27 +00009//
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
Chris Lattner5d8a12e2003-09-11 16:45:55 +000013// 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.
Chris Lattnerfb41a502003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
22#include "llvm/Transforms/Scalar.h"
Chris Lattner5d8a12e2003-09-11 16:45:55 +000023#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
Chris Lattnerfb41a502003-05-27 15:45:27 +000025#include "llvm/Function.h"
26#include "llvm/Pass.h"
27#include "llvm/iMemory.h"
Chris Lattner5d8a12e2003-09-11 16:45:55 +000028#include "llvm/Analysis/Dominators.h"
29#include "llvm/Target/TargetData.h"
30#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Chris Lattner8abcd562003-08-01 22:15:03 +000031#include "Support/Debug.h"
Chris Lattnerfb41a502003-05-27 15:45:27 +000032#include "Support/Statistic.h"
Chris Lattner8abcd562003-08-01 22:15:03 +000033#include "Support/StringExtras.h"
Chris Lattnerfb41a502003-05-27 15:45:27 +000034
35namespace {
Misha Brukman217ca0b2003-09-11 16:58:31 +000036 Statistic<> NumReplaced("scalarrepl", "Number of allocas broken up");
37 Statistic<> NumPromoted("scalarrepl", "Number of allocas promoted");
Chris Lattnerfb41a502003-05-27 15:45:27 +000038
39 struct SROA : public FunctionPass {
40 bool runOnFunction(Function &F);
41
Chris Lattner5d8a12e2003-09-11 16:45:55 +000042 bool performScalarRepl(Function &F);
43 bool performPromotion(Function &F);
44
Chris Lattnerc8174582003-08-31 00:45:13 +000045 // getAnalysisUsage - This pass does not require any passes, but we know it
46 // will not alter the CFG, so say so.
47 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnera906bac2003-10-05 21:20:13 +000048 AU.addRequired<DominatorTree>();
Chris Lattner5d8a12e2003-09-11 16:45:55 +000049 AU.addRequired<DominanceFrontier>();
50 AU.addRequired<TargetData>();
Chris Lattnerc8174582003-08-31 00:45:13 +000051 AU.setPreservesCFG();
52 }
53
Chris Lattnerfb41a502003-05-27 15:45:27 +000054 private:
Chris Lattner0078d9c2003-05-30 19:22:14 +000055 bool isSafeElementUse(Value *Ptr);
Chris Lattner6e5398d2003-05-30 04:15:41 +000056 bool isSafeUseOfAllocation(Instruction *User);
57 bool isSafeStructAllocaToPromote(AllocationInst *AI);
58 bool isSafeArrayAllocaToPromote(AllocationInst *AI);
Chris Lattnerfb41a502003-05-27 15:45:27 +000059 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
60 };
61
62 RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
63}
64
65Pass *createScalarReplAggregatesPass() { return new SROA(); }
66
67
Chris Lattnerfb41a502003-05-27 15:45:27 +000068bool SROA::runOnFunction(Function &F) {
Chris Lattner9a95f2a2003-09-12 15:36:03 +000069 bool Changed = performPromotion(F);
70 while (1) {
71 bool LocalChange = performScalarRepl(F);
72 if (!LocalChange) break; // No need to repromote if no scalarrepl
73 Changed = true;
74 LocalChange = performPromotion(F);
75 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
76 }
Chris Lattner5d8a12e2003-09-11 16:45:55 +000077
78 return Changed;
79}
80
81
82bool SROA::performPromotion(Function &F) {
83 std::vector<AllocaInst*> Allocas;
84 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattnera906bac2003-10-05 21:20:13 +000085 DominatorTree &DT = getAnalysis<DominatorTree>();
86 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner5d8a12e2003-09-11 16:45:55 +000087
Chris Lattner5dac64f2003-09-20 14:39:18 +000088 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner5d8a12e2003-09-11 16:45:55 +000089
Chris Lattner9a95f2a2003-09-12 15:36:03 +000090 bool Changed = false;
Chris Lattner5d8a12e2003-09-11 16:45:55 +000091
92 while (1) {
93 Allocas.clear();
94
95 // Find allocas that are safe to promote, by looking at all instructions in
96 // the entry node
97 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
98 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
99 if (isAllocaPromotable(AI, TD))
100 Allocas.push_back(AI);
101
102 if (Allocas.empty()) break;
103
Chris Lattnera906bac2003-10-05 21:20:13 +0000104 PromoteMemToReg(Allocas, DT, DF, TD);
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000105 NumPromoted += Allocas.size();
106 Changed = true;
107 }
108
109 return Changed;
110}
111
112
113// performScalarRepl - This algorithm is a simple worklist driven algorithm,
114// which runs on all of the malloc/alloca instructions in the function, removing
115// them if they are only used by getelementptr instructions.
116//
117bool SROA::performScalarRepl(Function &F) {
Chris Lattnerfb41a502003-05-27 15:45:27 +0000118 std::vector<AllocationInst*> WorkList;
119
120 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner5dac64f2003-09-20 14:39:18 +0000121 BasicBlock &BB = F.getEntryBlock();
Chris Lattnerfb41a502003-05-27 15:45:27 +0000122 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
123 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
124 WorkList.push_back(A);
125
126 // Process the worklist
127 bool Changed = false;
128 while (!WorkList.empty()) {
129 AllocationInst *AI = WorkList.back();
130 WorkList.pop_back();
131
132 // We cannot transform the allocation instruction if it is an array
Chris Lattnerc16b2102003-05-27 16:09:27 +0000133 // allocation (allocations OF arrays are ok though), and an allocation of a
134 // scalar value cannot be decomposed at all.
135 //
Chris Lattnerfb41a502003-05-27 15:45:27 +0000136 if (AI->isArrayAllocation() ||
Chris Lattnerc16b2102003-05-27 16:09:27 +0000137 (!isa<StructType>(AI->getAllocatedType()) &&
138 !isa<ArrayType>(AI->getAllocatedType()))) continue;
139
Chris Lattner6e5398d2003-05-30 04:15:41 +0000140 // Check that all of the users of the allocation are capable of being
141 // transformed.
142 if (isa<StructType>(AI->getAllocatedType())) {
143 if (!isSafeStructAllocaToPromote(AI))
144 continue;
145 } else if (!isSafeArrayAllocaToPromote(AI))
146 continue;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000147
148 DEBUG(std::cerr << "Found inst to xform: " << *AI);
149 Changed = true;
150
151 std::vector<AllocaInst*> ElementAllocas;
152 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
153 ElementAllocas.reserve(ST->getNumContainedTypes());
154 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
155 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
156 AI->getName() + "." + utostr(i), AI);
157 ElementAllocas.push_back(NA);
158 WorkList.push_back(NA); // Add to worklist for recursive processing
159 }
160 } else {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000161 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
Chris Lattnerfb41a502003-05-27 15:45:27 +0000162 ElementAllocas.reserve(AT->getNumElements());
163 const Type *ElTy = AT->getElementType();
164 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
165 AllocaInst *NA = new AllocaInst(ElTy, 0,
166 AI->getName() + "." + utostr(i), AI);
167 ElementAllocas.push_back(NA);
168 WorkList.push_back(NA); // Add to worklist for recursive processing
169 }
170 }
171
172 // Now that we have created the alloca instructions that we want to use,
173 // expand the getelementptr instructions to use them.
174 //
175 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
176 I != E; ++I) {
177 Instruction *User = cast<Instruction>(*I);
178 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
179 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
Chris Lattner6077c312003-07-23 15:22:26 +0000180 uint64_t Idx = cast<ConstantInt>(GEPI->getOperand(2))->getRawValue();
Chris Lattnerfb41a502003-05-27 15:45:27 +0000181
182 assert(Idx < ElementAllocas.size() && "Index out of range?");
183 AllocaInst *AllocaToUse = ElementAllocas[Idx];
184
185 Value *RepValue;
186 if (GEPI->getNumOperands() == 3) {
187 // Do not insert a new getelementptr instruction with zero indices,
188 // only to have it optimized out later.
189 RepValue = AllocaToUse;
190 } else {
191 // We are indexing deeply into the structure, so we still need a
192 // getelement ptr instruction to finish the indexing. This may be
193 // expanded itself once the worklist is rerun.
194 //
195 std::string OldName = GEPI->getName(); // Steal the old name...
Chris Lattner38d88c02003-05-30 05:26:30 +0000196 std::vector<Value*> NewArgs;
197 NewArgs.push_back(Constant::getNullValue(Type::LongTy));
198 NewArgs.insert(NewArgs.end(), GEPI->op_begin()+3, GEPI->op_end());
Chris Lattnerfb41a502003-05-27 15:45:27 +0000199 GEPI->setName("");
200 RepValue =
Chris Lattner38d88c02003-05-30 05:26:30 +0000201 new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI);
Chris Lattnerfb41a502003-05-27 15:45:27 +0000202 }
203
204 // Move all of the users over to the new GEP.
205 GEPI->replaceAllUsesWith(RepValue);
206 // Delete the old GEP
207 GEPI->getParent()->getInstList().erase(GEPI);
208 } else {
209 assert(0 && "Unexpected instruction type!");
210 }
211 }
212
213 // Finally, delete the Alloca instruction
214 AI->getParent()->getInstList().erase(AI);
Chris Lattnerc16b2102003-05-27 16:09:27 +0000215 NumReplaced++;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000216 }
217
218 return Changed;
219}
Chris Lattner6e5398d2003-05-30 04:15:41 +0000220
221
222/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
223/// aggregate allocation.
224///
225bool SROA::isSafeUseOfAllocation(Instruction *User) {
226 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
227 // The GEP is safe to transform if it is of the form GEP <ptr>, 0, <cst>
228 if (GEPI->getNumOperands() <= 2 ||
229 GEPI->getOperand(1) != Constant::getNullValue(Type::LongTy) ||
230 !isa<Constant>(GEPI->getOperand(2)) ||
231 isa<ConstantExpr>(GEPI->getOperand(2)))
232 return false;
233 } else {
234 return false;
235 }
236 return true;
237}
238
Chris Lattner0078d9c2003-05-30 19:22:14 +0000239/// isSafeElementUse - Check to see if this use is an allowed use for a
Chris Lattner6e5398d2003-05-30 04:15:41 +0000240/// getelementptr instruction of an array aggregate allocation.
241///
Chris Lattner0078d9c2003-05-30 19:22:14 +0000242bool SROA::isSafeElementUse(Value *Ptr) {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000243 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
244 I != E; ++I) {
245 Instruction *User = cast<Instruction>(*I);
246 switch (User->getOpcode()) {
Chris Lattner7fdde922003-09-12 16:02:12 +0000247 case Instruction::Load: break;
248 case Instruction::Store:
249 // Store is ok if storing INTO the pointer, not storing the pointer
250 if (User->getOperand(0) == Ptr) return false;
251 break;
Chris Lattner6e5398d2003-05-30 04:15:41 +0000252 case Instruction::GetElementPtr: {
253 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
254 if (GEP->getNumOperands() > 1) {
255 if (!isa<Constant>(GEP->getOperand(1)) ||
256 !cast<Constant>(GEP->getOperand(1))->isNullValue())
257 return false; // Using pointer arithmetic to navigate the array...
Chris Lattner6e5398d2003-05-30 04:15:41 +0000258 }
Chris Lattner7fdde922003-09-12 16:02:12 +0000259 if (!isSafeElementUse(GEP)) return false;
260 break;
Chris Lattner6e5398d2003-05-30 04:15:41 +0000261 }
262 default:
263 DEBUG(std::cerr << " Transformation preventing inst: " << *User);
264 return false;
265 }
266 }
267 return true; // All users look ok :)
268}
269
270
271/// isSafeStructAllocaToPromote - Check to see if the specified allocation of a
272/// structure can be broken down into elements.
273///
274bool SROA::isSafeStructAllocaToPromote(AllocationInst *AI) {
275 // Loop over the use list of the alloca. We can only transform it if all of
276 // the users are safe to transform.
277 //
278 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
Chris Lattnerd847be02003-05-30 18:09:57 +0000279 I != E; ++I) {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000280 if (!isSafeUseOfAllocation(cast<Instruction>(*I))) {
281 DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: "
282 << *I);
283 return false;
284 }
Chris Lattnerd847be02003-05-30 18:09:57 +0000285
286 // Pedantic check to avoid breaking broken programs...
287 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*I))
Chris Lattner0078d9c2003-05-30 19:22:14 +0000288 if (GEPI->getNumOperands() == 3 && !isSafeElementUse(GEPI))
Chris Lattnerd847be02003-05-30 18:09:57 +0000289 return false;
290 }
Chris Lattner6e5398d2003-05-30 04:15:41 +0000291 return true;
292}
293
294
295/// isSafeArrayAllocaToPromote - Check to see if the specified allocation of a
296/// structure can be broken down into elements.
297///
298bool SROA::isSafeArrayAllocaToPromote(AllocationInst *AI) {
299 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
300 int64_t NumElements = AT->getNumElements();
301
302 // Loop over the use list of the alloca. We can only transform it if all of
303 // the users are safe to transform. Array allocas have extra constraints to
304 // meet though.
305 //
306 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
307 I != E; ++I) {
308 Instruction *User = cast<Instruction>(*I);
309 if (!isSafeUseOfAllocation(User)) {
310 DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: "
311 << User);
312 return false;
313 }
314
315 // Check to make sure that getelementptr follow the extra rules for arrays:
316 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
317 // Check to make sure that index falls within the array. If not,
318 // something funny is going on, so we won't do the optimization.
319 //
320 if (cast<ConstantSInt>(GEPI->getOperand(2))->getValue() >= NumElements)
321 return false;
322
323 // Check to make sure that the only thing that uses the resultant pointer
324 // is safe for an array access. For example, code that looks like:
325 // P = &A[0]; P = P + 1
326 // is legal, and should prevent promotion.
327 //
Chris Lattner0078d9c2003-05-30 19:22:14 +0000328 if (!isSafeElementUse(GEPI)) {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000329 DEBUG(std::cerr << "Cannot transform: " << *AI
330 << " due to uses of user: " << *GEPI);
331 return false;
332 }
333 }
334 }
335 return true;
336}
337