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).
8 //===----------------------------------------------------------------------===//
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/Debug.h"
17 #include "Support/Statistic.h"
18 #include "Support/StringExtras.h"
21 Statistic<> NumReplaced("scalarrepl", "Number of alloca's broken up");
23 struct SROA : public FunctionPass {
24 bool runOnFunction(Function &F);
26 // getAnalysisUsage - This pass does not require any passes, but we know it
27 // will not alter the CFG, so say so.
28 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
33 bool isSafeElementUse(Value *Ptr);
34 bool isSafeUseOfAllocation(Instruction *User);
35 bool isSafeStructAllocaToPromote(AllocationInst *AI);
36 bool isSafeArrayAllocaToPromote(AllocationInst *AI);
37 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
40 RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
43 Pass *createScalarReplAggregatesPass() { return new SROA(); }
46 // runOnFunction - This algorithm is a simple worklist driven algorithm, which
47 // runs on all of the malloc/alloca instructions in the function, removing them
48 // if they are only used by getelementptr instructions.
50 bool SROA::runOnFunction(Function &F) {
51 std::vector<AllocationInst*> WorkList;
53 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
54 BasicBlock &BB = F.getEntryNode();
55 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
56 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
57 WorkList.push_back(A);
59 // Process the worklist
61 while (!WorkList.empty()) {
62 AllocationInst *AI = WorkList.back();
65 // We cannot transform the allocation instruction if it is an array
66 // allocation (allocations OF arrays are ok though), and an allocation of a
67 // scalar value cannot be decomposed at all.
69 if (AI->isArrayAllocation() ||
70 (!isa<StructType>(AI->getAllocatedType()) &&
71 !isa<ArrayType>(AI->getAllocatedType()))) continue;
73 // Check that all of the users of the allocation are capable of being
75 if (isa<StructType>(AI->getAllocatedType())) {
76 if (!isSafeStructAllocaToPromote(AI))
78 } else if (!isSafeArrayAllocaToPromote(AI))
81 DEBUG(std::cerr << "Found inst to xform: " << *AI);
84 std::vector<AllocaInst*> ElementAllocas;
85 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
86 ElementAllocas.reserve(ST->getNumContainedTypes());
87 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
88 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
89 AI->getName() + "." + utostr(i), AI);
90 ElementAllocas.push_back(NA);
91 WorkList.push_back(NA); // Add to worklist for recursive processing
94 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
95 ElementAllocas.reserve(AT->getNumElements());
96 const Type *ElTy = AT->getElementType();
97 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
98 AllocaInst *NA = new AllocaInst(ElTy, 0,
99 AI->getName() + "." + utostr(i), AI);
100 ElementAllocas.push_back(NA);
101 WorkList.push_back(NA); // Add to worklist for recursive processing
105 // Now that we have created the alloca instructions that we want to use,
106 // expand the getelementptr instructions to use them.
108 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
110 Instruction *User = cast<Instruction>(*I);
111 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
112 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
113 uint64_t Idx = cast<ConstantInt>(GEPI->getOperand(2))->getRawValue();
115 assert(Idx < ElementAllocas.size() && "Index out of range?");
116 AllocaInst *AllocaToUse = ElementAllocas[Idx];
119 if (GEPI->getNumOperands() == 3) {
120 // Do not insert a new getelementptr instruction with zero indices,
121 // only to have it optimized out later.
122 RepValue = AllocaToUse;
124 // We are indexing deeply into the structure, so we still need a
125 // getelement ptr instruction to finish the indexing. This may be
126 // expanded itself once the worklist is rerun.
128 std::string OldName = GEPI->getName(); // Steal the old name...
129 std::vector<Value*> NewArgs;
130 NewArgs.push_back(Constant::getNullValue(Type::LongTy));
131 NewArgs.insert(NewArgs.end(), GEPI->op_begin()+3, GEPI->op_end());
134 new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI);
137 // Move all of the users over to the new GEP.
138 GEPI->replaceAllUsesWith(RepValue);
139 // Delete the old GEP
140 GEPI->getParent()->getInstList().erase(GEPI);
142 assert(0 && "Unexpected instruction type!");
146 // Finally, delete the Alloca instruction
147 AI->getParent()->getInstList().erase(AI);
155 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
156 /// aggregate allocation.
158 bool SROA::isSafeUseOfAllocation(Instruction *User) {
159 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
160 // The GEP is safe to transform if it is of the form GEP <ptr>, 0, <cst>
161 if (GEPI->getNumOperands() <= 2 ||
162 GEPI->getOperand(1) != Constant::getNullValue(Type::LongTy) ||
163 !isa<Constant>(GEPI->getOperand(2)) ||
164 isa<ConstantExpr>(GEPI->getOperand(2)))
172 /// isSafeElementUse - Check to see if this use is an allowed use for a
173 /// getelementptr instruction of an array aggregate allocation.
175 bool SROA::isSafeElementUse(Value *Ptr) {
176 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
178 Instruction *User = cast<Instruction>(*I);
179 switch (User->getOpcode()) {
180 case Instruction::Load: return true;
181 case Instruction::Store: return User->getOperand(0) != Ptr;
182 case Instruction::GetElementPtr: {
183 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
184 if (GEP->getNumOperands() > 1) {
185 if (!isa<Constant>(GEP->getOperand(1)) ||
186 !cast<Constant>(GEP->getOperand(1))->isNullValue())
187 return false; // Using pointer arithmetic to navigate the array...
189 return isSafeElementUse(GEP);
192 DEBUG(std::cerr << " Transformation preventing inst: " << *User);
196 return true; // All users look ok :)
200 /// isSafeStructAllocaToPromote - Check to see if the specified allocation of a
201 /// structure can be broken down into elements.
203 bool SROA::isSafeStructAllocaToPromote(AllocationInst *AI) {
204 // Loop over the use list of the alloca. We can only transform it if all of
205 // the users are safe to transform.
207 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
209 if (!isSafeUseOfAllocation(cast<Instruction>(*I))) {
210 DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: "
215 // Pedantic check to avoid breaking broken programs...
216 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*I))
217 if (GEPI->getNumOperands() == 3 && !isSafeElementUse(GEPI))
224 /// isSafeArrayAllocaToPromote - Check to see if the specified allocation of a
225 /// structure can be broken down into elements.
227 bool SROA::isSafeArrayAllocaToPromote(AllocationInst *AI) {
228 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
229 int64_t NumElements = AT->getNumElements();
231 // Loop over the use list of the alloca. We can only transform it if all of
232 // the users are safe to transform. Array allocas have extra constraints to
235 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
237 Instruction *User = cast<Instruction>(*I);
238 if (!isSafeUseOfAllocation(User)) {
239 DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: "
244 // Check to make sure that getelementptr follow the extra rules for arrays:
245 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
246 // Check to make sure that index falls within the array. If not,
247 // something funny is going on, so we won't do the optimization.
249 if (cast<ConstantSInt>(GEPI->getOperand(2))->getValue() >= NumElements)
252 // Check to make sure that the only thing that uses the resultant pointer
253 // is safe for an array access. For example, code that looks like:
254 // P = &A[0]; P = P + 1
255 // is legal, and should prevent promotion.
257 if (!isSafeElementUse(GEPI)) {
258 DEBUG(std::cerr << "Cannot transform: " << *AI
259 << " due to uses of user: " << *GEPI);