Implement transmogriphication of allocation instructions
[oota-llvm.git] / lib / Transforms / Scalar / ScalarReplAggregates.cpp
1 //===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
2 // 
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 //===----------------------------------------------------------------------===//
9 //
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.
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.
19 //
20 //===----------------------------------------------------------------------===//
21
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"
34
35 namespace {
36   Statistic<> NumReplaced("scalarrepl", "Number of allocas broken up");
37   Statistic<> NumPromoted("scalarrepl", "Number of allocas promoted");
38
39   struct SROA : public FunctionPass {
40     bool runOnFunction(Function &F);
41
42     bool performScalarRepl(Function &F);
43     bool performPromotion(Function &F);
44
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>();
51       AU.setPreservesCFG();
52     }
53
54   private:
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);
59   };
60
61   RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
62 }
63
64 Pass *createScalarReplAggregatesPass() { return new SROA(); }
65
66
67 bool SROA::runOnFunction(Function &F) {
68   bool Changed = performPromotion(F);
69   while (1) {
70     bool LocalChange = performScalarRepl(F);
71     if (!LocalChange) break;   // No need to repromote if no scalarrepl
72     Changed = true;
73     LocalChange = performPromotion(F);
74     if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
75   }
76
77   return Changed;
78 }
79
80
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>();
86
87   BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
88
89   bool Changed = false;
90   
91   while (1) {
92     Allocas.clear();
93
94     // Find allocas that are safe to promote, by looking at all instructions in
95     // the entry node
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);
100
101     if (Allocas.empty()) break;
102
103     PromoteMemToReg(Allocas, DT, DF, TD);
104     NumPromoted += Allocas.size();
105     Changed = true;
106   }
107
108   return Changed;
109 }
110
111
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.
115 //
116 bool SROA::performScalarRepl(Function &F) {
117   std::vector<AllocationInst*> WorkList;
118
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);
124
125   // Process the worklist
126   bool Changed = false;
127   while (!WorkList.empty()) {
128     AllocationInst *AI = WorkList.back();
129     WorkList.pop_back();
130
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.
134     //
135     if (AI->isArrayAllocation() ||
136         (!isa<StructType>(AI->getAllocatedType()) &&
137          !isa<ArrayType>(AI->getAllocatedType()))) continue;
138
139     // Check that all of the users of the allocation are capable of being
140     // transformed.
141     if (!isSafeAllocaToPromote(AI))
142       continue;
143
144     DEBUG(std::cerr << "Found inst to xform: " << *AI);
145     Changed = true;
146     
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
155       }
156     } else {
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
165       }
166     }
167     
168     // Now that we have created the alloca instructions that we want to use,
169     // expand the getelementptr instructions to use them.
170     //
171     for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
172          I != E; ++I) {
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();
177         
178         assert(Idx < ElementAllocas.size() && "Index out of range?");
179         AllocaInst *AllocaToUse = ElementAllocas[Idx];
180
181         Value *RepValue;
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;
186         } else {
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.
190           //
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());
195           GEPI->setName("");
196           RepValue =
197             new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI);
198         }
199
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);
204       } else {
205         assert(0 && "Unexpected instruction type!");
206       }
207     }
208
209     // Finally, delete the Alloca instruction
210     AI->getParent()->getInstList().erase(AI);
211     NumReplaced++;
212   }
213
214   return Changed;
215 }
216
217
218 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
219 /// aggregate allocation.
220 ///
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)))
228       return false;
229
230     // If this is a use of an array allocation, do a bit more checking for
231     // sanity.
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();
236
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.
239       //
240       if (cast<ConstantSInt>(GEPI->getOperand(2))->getValue() >= NumElements ||
241           cast<ConstantSInt>(GEPI->getOperand(2))->getValue() < 0)
242         return false;
243     }
244
245     // If there are any non-simple uses of this getelementptr, make sure to
246     // reject them.
247     if (isSafeElementUse(GEPI))
248       return true;
249   }
250   return false;
251 }
252
253 /// isSafeElementUse - Check to see if this use is an allowed use for a
254 /// getelementptr instruction of an array aggregate allocation.
255 ///
256 bool SROA::isSafeElementUse(Value *Ptr) {
257   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
258        I != E; ++I) {
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;
265       break;
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...
272       }
273       if (!isSafeElementUse(GEP)) return false;
274       break;
275     }
276     default:
277       DEBUG(std::cerr << "  Transformation preventing inst: " << *User);
278       return false;
279     }
280   }
281   return true;  // All users look ok :)
282 }
283
284
285 /// isSafeStructAllocaToPromote - Check to see if the specified allocation of a
286 /// structure can be broken down into elements.
287 ///
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.
291   //
292   for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
293        I != E; ++I)
294     if (!isSafeUseOfAllocation(cast<Instruction>(*I))) {
295       DEBUG(std::cerr << "Cannot transform: " << *AI << "  due to user: "
296                       << *I);
297       return false;
298     }
299   return true;
300 }