ScalarRepl does not modify the CFG. Say so!
[oota-llvm.git] / lib / Transforms / Scalar / ScalarReplAggregates.cpp
1 //===- 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/Debug.h"
17 #include "Support/Statistic.h"
18 #include "Support/StringExtras.h"
19
20 namespace {
21   Statistic<> NumReplaced("scalarrepl", "Number of alloca's broken up");
22
23   struct SROA : public FunctionPass {
24     bool runOnFunction(Function &F);
25
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 {
29       AU.setPreservesCFG();
30     }
31
32   private:
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);
38   };
39
40   RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
41 }
42
43 Pass *createScalarReplAggregatesPass() { return new SROA(); }
44
45
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.
49 //
50 bool SROA::runOnFunction(Function &F) {
51   std::vector<AllocationInst*> WorkList;
52
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);
58
59   // Process the worklist
60   bool Changed = false;
61   while (!WorkList.empty()) {
62     AllocationInst *AI = WorkList.back();
63     WorkList.pop_back();
64
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.
68     //
69     if (AI->isArrayAllocation() ||
70         (!isa<StructType>(AI->getAllocatedType()) &&
71          !isa<ArrayType>(AI->getAllocatedType()))) continue;
72
73     // Check that all of the users of the allocation are capable of being
74     // transformed.
75     if (isa<StructType>(AI->getAllocatedType())) {
76       if (!isSafeStructAllocaToPromote(AI))
77         continue;
78     } else if (!isSafeArrayAllocaToPromote(AI))
79       continue;
80
81     DEBUG(std::cerr << "Found inst to xform: " << *AI);
82     Changed = true;
83     
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
92       }
93     } else {
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
102       }
103     }
104     
105     // Now that we have created the alloca instructions that we want to use,
106     // expand the getelementptr instructions to use them.
107     //
108     for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
109          I != E; ++I) {
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();
114         
115         assert(Idx < ElementAllocas.size() && "Index out of range?");
116         AllocaInst *AllocaToUse = ElementAllocas[Idx];
117
118         Value *RepValue;
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;
123         } else {
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.
127           //
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());
132           GEPI->setName("");
133           RepValue =
134             new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI);
135         }
136
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);
141       } else {
142         assert(0 && "Unexpected instruction type!");
143       }
144     }
145
146     // Finally, delete the Alloca instruction
147     AI->getParent()->getInstList().erase(AI);
148     NumReplaced++;
149   }
150
151   return Changed;
152 }
153
154
155 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
156 /// aggregate allocation.
157 ///
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)))
165       return false;
166   } else {
167     return false;
168   }
169   return true;
170 }
171
172 /// isSafeElementUse - Check to see if this use is an allowed use for a
173 /// getelementptr instruction of an array aggregate allocation.
174 ///
175 bool SROA::isSafeElementUse(Value *Ptr) {
176   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
177        I != E; ++I) {
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...
188       }
189       return isSafeElementUse(GEP);
190     }
191     default:
192       DEBUG(std::cerr << "  Transformation preventing inst: " << *User);
193       return false;
194     }
195   }
196   return true;  // All users look ok :)
197 }
198
199
200 /// isSafeStructAllocaToPromote - Check to see if the specified allocation of a
201 /// structure can be broken down into elements.
202 ///
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.
206   //
207   for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
208        I != E; ++I) {
209     if (!isSafeUseOfAllocation(cast<Instruction>(*I))) {
210       DEBUG(std::cerr << "Cannot transform: " << *AI << "  due to user: "
211                       << *I);
212       return false;
213     }
214
215     // Pedantic check to avoid breaking broken programs...
216     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*I))
217       if (GEPI->getNumOperands() == 3 && !isSafeElementUse(GEPI))
218         return false;
219   }
220   return true;
221 }
222
223
224 /// isSafeArrayAllocaToPromote - Check to see if the specified allocation of a
225 /// structure can be broken down into elements.
226 ///
227 bool SROA::isSafeArrayAllocaToPromote(AllocationInst *AI) {
228   const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
229   int64_t NumElements = AT->getNumElements();
230
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
233   // meet though.
234   //
235   for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
236        I != E; ++I) {
237     Instruction *User = cast<Instruction>(*I);
238     if (!isSafeUseOfAllocation(User)) {
239       DEBUG(std::cerr << "Cannot transform: " << *AI << "  due to user: "
240                       << User);
241       return false;
242     }
243
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.
248       //
249       if (cast<ConstantSInt>(GEPI->getOperand(2))->getValue() >= NumElements)
250         return false;
251
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.
256       //
257       if (!isSafeElementUse(GEPI)) {
258         DEBUG(std::cerr << "Cannot transform: " << *AI
259                         << "  due to uses of user: " << *GEPI);
260         return false;
261       }
262     }
263   }
264   return true;
265 }
266