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 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/Pass.h"
27 #include "llvm/iMemory.h"
28 #include "llvm/Analysis/Dominators.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
31 #include "Support/Debug.h"
32 #include "Support/Statistic.h"
33 #include "Support/StringExtras.h"
36 Statistic<> NumReplaced("scalarrepl", "Number of allocas broken up");
37 Statistic<> NumPromoted("scalarrepl", "Number of allocas promoted");
39 struct SROA : public FunctionPass {
40 bool runOnFunction(Function &F);
42 bool performScalarRepl(Function &F);
43 bool performPromotion(Function &F);
45 // 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 {
48 AU.addRequired<DominatorTree>();
49 AU.addRequired<DominanceFrontier>();
50 AU.addRequired<TargetData>();
55 bool isSafeElementUse(Value *Ptr);
56 bool isSafeUseOfAllocation(Instruction *User);
57 bool isSafeAllocaToPromote(AllocationInst *AI);
58 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
61 RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
64 Pass *createScalarReplAggregatesPass() { return new SROA(); }
67 bool SROA::runOnFunction(Function &F) {
68 bool Changed = performPromotion(F);
70 bool LocalChange = performScalarRepl(F);
71 if (!LocalChange) break; // No need to repromote if no scalarrepl
73 LocalChange = performPromotion(F);
74 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
81 bool SROA::performPromotion(Function &F) {
82 std::vector<AllocaInst*> Allocas;
83 const TargetData &TD = getAnalysis<TargetData>();
84 DominatorTree &DT = getAnalysis<DominatorTree>();
85 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
87 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
94 // Find allocas that are safe to promote, by looking at all instructions in
96 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
97 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
98 if (isAllocaPromotable(AI, TD))
99 Allocas.push_back(AI);
101 if (Allocas.empty()) break;
103 PromoteMemToReg(Allocas, DT, DF, TD);
104 NumPromoted += Allocas.size();
112 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
113 // which runs on all of the malloc/alloca instructions in the function, removing
114 // them if they are only used by getelementptr instructions.
116 bool SROA::performScalarRepl(Function &F) {
117 std::vector<AllocationInst*> WorkList;
119 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
120 BasicBlock &BB = F.getEntryBlock();
121 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
122 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
123 WorkList.push_back(A);
125 // Process the worklist
126 bool Changed = false;
127 while (!WorkList.empty()) {
128 AllocationInst *AI = WorkList.back();
131 // We cannot transform the allocation instruction if it is an array
132 // allocation (allocations OF arrays are ok though), and an allocation of a
133 // scalar value cannot be decomposed at all.
135 if (AI->isArrayAllocation() ||
136 (!isa<StructType>(AI->getAllocatedType()) &&
137 !isa<ArrayType>(AI->getAllocatedType()))) continue;
139 // Check that all of the users of the allocation are capable of being
141 if (!isSafeAllocaToPromote(AI))
144 DEBUG(std::cerr << "Found inst to xform: " << *AI);
147 std::vector<AllocaInst*> ElementAllocas;
148 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
149 ElementAllocas.reserve(ST->getNumContainedTypes());
150 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
151 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
152 AI->getName() + "." + utostr(i), AI);
153 ElementAllocas.push_back(NA);
154 WorkList.push_back(NA); // Add to worklist for recursive processing
157 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
158 ElementAllocas.reserve(AT->getNumElements());
159 const Type *ElTy = AT->getElementType();
160 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
161 AllocaInst *NA = new AllocaInst(ElTy, 0,
162 AI->getName() + "." + utostr(i), AI);
163 ElementAllocas.push_back(NA);
164 WorkList.push_back(NA); // Add to worklist for recursive processing
168 // Now that we have created the alloca instructions that we want to use,
169 // expand the getelementptr instructions to use them.
171 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
173 Instruction *User = cast<Instruction>(*I);
174 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
175 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
176 uint64_t Idx = cast<ConstantInt>(GEPI->getOperand(2))->getRawValue();
178 assert(Idx < ElementAllocas.size() && "Index out of range?");
179 AllocaInst *AllocaToUse = ElementAllocas[Idx];
182 if (GEPI->getNumOperands() == 3) {
183 // Do not insert a new getelementptr instruction with zero indices,
184 // only to have it optimized out later.
185 RepValue = AllocaToUse;
187 // We are indexing deeply into the structure, so we still need a
188 // getelement ptr instruction to finish the indexing. This may be
189 // expanded itself once the worklist is rerun.
191 std::string OldName = GEPI->getName(); // Steal the old name...
192 std::vector<Value*> NewArgs;
193 NewArgs.push_back(Constant::getNullValue(Type::LongTy));
194 NewArgs.insert(NewArgs.end(), GEPI->op_begin()+3, GEPI->op_end());
197 new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI);
200 // Move all of the users over to the new GEP.
201 GEPI->replaceAllUsesWith(RepValue);
202 // Delete the old GEP
203 GEPI->getParent()->getInstList().erase(GEPI);
205 assert(0 && "Unexpected instruction type!");
209 // Finally, delete the Alloca instruction
210 AI->getParent()->getInstList().erase(AI);
218 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
219 /// aggregate allocation.
221 bool SROA::isSafeUseOfAllocation(Instruction *User) {
222 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
223 // The GEP is safe to transform if it is of the form GEP <ptr>, 0, <cst>
224 if (GEPI->getNumOperands() <= 2 ||
225 GEPI->getOperand(1) != Constant::getNullValue(Type::LongTy) ||
226 !isa<Constant>(GEPI->getOperand(2)) ||
227 isa<ConstantExpr>(GEPI->getOperand(2)))
230 // If this is a use of an array allocation, do a bit more checking for
232 if (GEPI->getOperand(2)->getType() == Type::LongTy) {
233 const PointerType *PTy =cast<PointerType>(GEPI->getOperand(0)->getType());
234 const ArrayType *AT = cast<ArrayType>(PTy->getElementType());
235 int64_t NumElements = AT->getNumElements();
237 // Check to make sure that index falls within the array. If not,
238 // something funny is going on, so we won't do the optimization.
240 if (cast<ConstantSInt>(GEPI->getOperand(2))->getValue() >= NumElements ||
241 cast<ConstantSInt>(GEPI->getOperand(2))->getValue() < 0)
245 // If there are any non-simple uses of this getelementptr, make sure to
247 if (isSafeElementUse(GEPI))
253 /// isSafeElementUse - Check to see if this use is an allowed use for a
254 /// getelementptr instruction of an array aggregate allocation.
256 bool SROA::isSafeElementUse(Value *Ptr) {
257 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
259 Instruction *User = cast<Instruction>(*I);
260 switch (User->getOpcode()) {
261 case Instruction::Load: break;
262 case Instruction::Store:
263 // Store is ok if storing INTO the pointer, not storing the pointer
264 if (User->getOperand(0) == Ptr) return false;
266 case Instruction::GetElementPtr: {
267 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
268 if (GEP->getNumOperands() > 1) {
269 if (!isa<Constant>(GEP->getOperand(1)) ||
270 !cast<Constant>(GEP->getOperand(1))->isNullValue())
271 return false; // Using pointer arithmetic to navigate the array...
273 if (!isSafeElementUse(GEP)) return false;
277 DEBUG(std::cerr << " Transformation preventing inst: " << *User);
281 return true; // All users look ok :)
285 /// isSafeStructAllocaToPromote - Check to see if the specified allocation of a
286 /// structure can be broken down into elements.
288 bool SROA::isSafeAllocaToPromote(AllocationInst *AI) {
289 // Loop over the use list of the alloca. We can only transform it if all of
290 // the users are safe to transform.
292 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
294 if (!isSafeUseOfAllocation(cast<Instruction>(*I))) {
295 DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: "