1 //===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
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). Then, if possible, it transforms the individual
7 // alloca instructions into nice clean scalar SSA form.
9 // This combines a simple SRoA algorithm with the Mem2Reg algorithm because
10 // often interact, especially for C++ programs. As such, iterating between
11 // SRoA, then Mem2Reg until we run out of things to promote works well.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Pass.h"
20 #include "llvm/iMemory.h"
21 #include "llvm/Analysis/Dominators.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
24 #include "Support/Debug.h"
25 #include "Support/Statistic.h"
26 #include "Support/StringExtras.h"
29 Statistic<> NumReplaced("scalarrepl", "Number of allocas broken up");
30 Statistic<> NumPromoted("scalarrepl", "Number of allocas promoted");
32 struct SROA : public FunctionPass {
33 bool runOnFunction(Function &F);
35 bool performScalarRepl(Function &F);
36 bool performPromotion(Function &F);
38 // getAnalysisUsage - This pass does not require any passes, but we know it
39 // will not alter the CFG, so say so.
40 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
41 AU.addRequired<DominatorTree>();
42 AU.addRequired<DominanceFrontier>();
43 AU.addRequired<TargetData>();
48 bool isSafeElementUse(Value *Ptr);
49 bool isSafeUseOfAllocation(Instruction *User);
50 bool isSafeStructAllocaToPromote(AllocationInst *AI);
51 bool isSafeArrayAllocaToPromote(AllocationInst *AI);
52 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
55 RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
58 Pass *createScalarReplAggregatesPass() { return new SROA(); }
61 bool SROA::runOnFunction(Function &F) {
62 bool Changed = performPromotion(F);
64 bool LocalChange = performScalarRepl(F);
65 if (!LocalChange) break; // No need to repromote if no scalarrepl
67 LocalChange = performPromotion(F);
68 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
75 bool SROA::performPromotion(Function &F) {
76 std::vector<AllocaInst*> Allocas;
77 const TargetData &TD = getAnalysis<TargetData>();
78 DominatorTree &DT = getAnalysis<DominatorTree>();
79 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
81 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
88 // Find allocas that are safe to promote, by looking at all instructions in
90 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
91 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
92 if (isAllocaPromotable(AI, TD))
93 Allocas.push_back(AI);
95 if (Allocas.empty()) break;
97 PromoteMemToReg(Allocas, DT, DF, TD);
98 NumPromoted += Allocas.size();
106 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
107 // which runs on all of the malloc/alloca instructions in the function, removing
108 // them if they are only used by getelementptr instructions.
110 bool SROA::performScalarRepl(Function &F) {
111 std::vector<AllocationInst*> WorkList;
113 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
114 BasicBlock &BB = F.getEntryBlock();
115 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
116 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
117 WorkList.push_back(A);
119 // Process the worklist
120 bool Changed = false;
121 while (!WorkList.empty()) {
122 AllocationInst *AI = WorkList.back();
125 // We cannot transform the allocation instruction if it is an array
126 // allocation (allocations OF arrays are ok though), and an allocation of a
127 // scalar value cannot be decomposed at all.
129 if (AI->isArrayAllocation() ||
130 (!isa<StructType>(AI->getAllocatedType()) &&
131 !isa<ArrayType>(AI->getAllocatedType()))) continue;
133 // Check that all of the users of the allocation are capable of being
135 if (isa<StructType>(AI->getAllocatedType())) {
136 if (!isSafeStructAllocaToPromote(AI))
138 } else if (!isSafeArrayAllocaToPromote(AI))
141 DEBUG(std::cerr << "Found inst to xform: " << *AI);
144 std::vector<AllocaInst*> ElementAllocas;
145 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
146 ElementAllocas.reserve(ST->getNumContainedTypes());
147 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
148 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
149 AI->getName() + "." + utostr(i), AI);
150 ElementAllocas.push_back(NA);
151 WorkList.push_back(NA); // Add to worklist for recursive processing
154 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
155 ElementAllocas.reserve(AT->getNumElements());
156 const Type *ElTy = AT->getElementType();
157 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
158 AllocaInst *NA = new AllocaInst(ElTy, 0,
159 AI->getName() + "." + utostr(i), AI);
160 ElementAllocas.push_back(NA);
161 WorkList.push_back(NA); // Add to worklist for recursive processing
165 // Now that we have created the alloca instructions that we want to use,
166 // expand the getelementptr instructions to use them.
168 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
170 Instruction *User = cast<Instruction>(*I);
171 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
172 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
173 uint64_t Idx = cast<ConstantInt>(GEPI->getOperand(2))->getRawValue();
175 assert(Idx < ElementAllocas.size() && "Index out of range?");
176 AllocaInst *AllocaToUse = ElementAllocas[Idx];
179 if (GEPI->getNumOperands() == 3) {
180 // Do not insert a new getelementptr instruction with zero indices,
181 // only to have it optimized out later.
182 RepValue = AllocaToUse;
184 // We are indexing deeply into the structure, so we still need a
185 // getelement ptr instruction to finish the indexing. This may be
186 // expanded itself once the worklist is rerun.
188 std::string OldName = GEPI->getName(); // Steal the old name...
189 std::vector<Value*> NewArgs;
190 NewArgs.push_back(Constant::getNullValue(Type::LongTy));
191 NewArgs.insert(NewArgs.end(), GEPI->op_begin()+3, GEPI->op_end());
194 new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI);
197 // Move all of the users over to the new GEP.
198 GEPI->replaceAllUsesWith(RepValue);
199 // Delete the old GEP
200 GEPI->getParent()->getInstList().erase(GEPI);
202 assert(0 && "Unexpected instruction type!");
206 // Finally, delete the Alloca instruction
207 AI->getParent()->getInstList().erase(AI);
215 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
216 /// aggregate allocation.
218 bool SROA::isSafeUseOfAllocation(Instruction *User) {
219 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
220 // The GEP is safe to transform if it is of the form GEP <ptr>, 0, <cst>
221 if (GEPI->getNumOperands() <= 2 ||
222 GEPI->getOperand(1) != Constant::getNullValue(Type::LongTy) ||
223 !isa<Constant>(GEPI->getOperand(2)) ||
224 isa<ConstantExpr>(GEPI->getOperand(2)))
232 /// isSafeElementUse - Check to see if this use is an allowed use for a
233 /// getelementptr instruction of an array aggregate allocation.
235 bool SROA::isSafeElementUse(Value *Ptr) {
236 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
238 Instruction *User = cast<Instruction>(*I);
239 switch (User->getOpcode()) {
240 case Instruction::Load: break;
241 case Instruction::Store:
242 // Store is ok if storing INTO the pointer, not storing the pointer
243 if (User->getOperand(0) == Ptr) return false;
245 case Instruction::GetElementPtr: {
246 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
247 if (GEP->getNumOperands() > 1) {
248 if (!isa<Constant>(GEP->getOperand(1)) ||
249 !cast<Constant>(GEP->getOperand(1))->isNullValue())
250 return false; // Using pointer arithmetic to navigate the array...
252 if (!isSafeElementUse(GEP)) return false;
256 DEBUG(std::cerr << " Transformation preventing inst: " << *User);
260 return true; // All users look ok :)
264 /// isSafeStructAllocaToPromote - Check to see if the specified allocation of a
265 /// structure can be broken down into elements.
267 bool SROA::isSafeStructAllocaToPromote(AllocationInst *AI) {
268 // Loop over the use list of the alloca. We can only transform it if all of
269 // the users are safe to transform.
271 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
273 if (!isSafeUseOfAllocation(cast<Instruction>(*I))) {
274 DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: "
279 // Pedantic check to avoid breaking broken programs...
280 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*I))
281 if (GEPI->getNumOperands() == 3 && !isSafeElementUse(GEPI))
288 /// isSafeArrayAllocaToPromote - Check to see if the specified allocation of a
289 /// structure can be broken down into elements.
291 bool SROA::isSafeArrayAllocaToPromote(AllocationInst *AI) {
292 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
293 int64_t NumElements = AT->getNumElements();
295 // Loop over the use list of the alloca. We can only transform it if all of
296 // the users are safe to transform. Array allocas have extra constraints to
299 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
301 Instruction *User = cast<Instruction>(*I);
302 if (!isSafeUseOfAllocation(User)) {
303 DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: "
308 // Check to make sure that getelementptr follow the extra rules for arrays:
309 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
310 // Check to make sure that index falls within the array. If not,
311 // something funny is going on, so we won't do the optimization.
313 if (cast<ConstantSInt>(GEPI->getOperand(2))->getValue() >= NumElements)
316 // Check to make sure that the only thing that uses the resultant pointer
317 // is safe for an array access. For example, code that looks like:
318 // P = &A[0]; P = P + 1
319 // is legal, and should prevent promotion.
321 if (!isSafeElementUse(GEPI)) {
322 DEBUG(std::cerr << "Cannot transform: " << *AI
323 << " due to uses of user: " << *GEPI);