Add support alignment 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/Instructions.h"
28 #include "llvm/Analysis/Dominators.h"
29 #include "llvm/Support/GetElementPtrTypeIterator.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/StringExtras.h"
35 using namespace llvm;
36
37 namespace {
38   Statistic<> NumReplaced("scalarrepl", "Number of allocas broken up");
39   Statistic<> NumPromoted("scalarrepl", "Number of allocas promoted");
40
41   struct SROA : public FunctionPass {
42     bool runOnFunction(Function &F);
43
44     bool performScalarRepl(Function &F);
45     bool performPromotion(Function &F);
46
47     // getAnalysisUsage - This pass does not require any passes, but we know it
48     // will not alter the CFG, so say so.
49     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
50       AU.addRequired<DominatorTree>();
51       AU.addRequired<DominanceFrontier>();
52       AU.addRequired<TargetData>();
53       AU.setPreservesCFG();
54     }
55
56   private:
57     int isSafeElementUse(Value *Ptr);
58     int isSafeUseOfAllocation(Instruction *User);
59     int isSafeAllocaToScalarRepl(AllocationInst *AI);
60     void CanonicalizeAllocaUsers(AllocationInst *AI);
61     AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
62   };
63
64   RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
65 }
66
67 // Public interface to the ScalarReplAggregates pass
68 FunctionPass *llvm::createScalarReplAggregatesPass() { return new SROA(); }
69
70
71 bool SROA::runOnFunction(Function &F) {
72   bool Changed = performPromotion(F);
73   while (1) {
74     bool LocalChange = performScalarRepl(F);
75     if (!LocalChange) break;   // No need to repromote if no scalarrepl
76     Changed = true;
77     LocalChange = performPromotion(F);
78     if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
79   }
80
81   return Changed;
82 }
83
84
85 bool SROA::performPromotion(Function &F) {
86   std::vector<AllocaInst*> Allocas;
87   const TargetData &TD = getAnalysis<TargetData>();
88   DominatorTree     &DT = getAnalysis<DominatorTree>();
89   DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
90
91   BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
92
93   bool Changed = false;
94
95   while (1) {
96     Allocas.clear();
97
98     // Find allocas that are safe to promote, by looking at all instructions in
99     // the entry node
100     for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
101       if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
102         if (isAllocaPromotable(AI, TD))
103           Allocas.push_back(AI);
104
105     if (Allocas.empty()) break;
106
107     PromoteMemToReg(Allocas, DT, DF, TD);
108     NumPromoted += Allocas.size();
109     Changed = true;
110   }
111
112   return Changed;
113 }
114
115
116 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
117 // which runs on all of the malloc/alloca instructions in the function, removing
118 // them if they are only used by getelementptr instructions.
119 //
120 bool SROA::performScalarRepl(Function &F) {
121   std::vector<AllocationInst*> WorkList;
122
123   // Scan the entry basic block, adding any alloca's and mallocs to the worklist
124   BasicBlock &BB = F.getEntryBlock();
125   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
126     if (AllocationInst *A = dyn_cast<AllocationInst>(I))
127       WorkList.push_back(A);
128
129   // Process the worklist
130   bool Changed = false;
131   while (!WorkList.empty()) {
132     AllocationInst *AI = WorkList.back();
133     WorkList.pop_back();
134
135     // We cannot transform the allocation instruction if it is an array
136     // allocation (allocations OF arrays are ok though), and an allocation of a
137     // scalar value cannot be decomposed at all.
138     //
139     if (AI->isArrayAllocation() ||
140         (!isa<StructType>(AI->getAllocatedType()) &&
141          !isa<ArrayType>(AI->getAllocatedType()))) continue;
142
143     // Check that all of the users of the allocation are capable of being
144     // transformed.
145     switch (isSafeAllocaToScalarRepl(AI)) {
146     default: assert(0 && "Unexpected value!");
147     case 0:  // Not safe to scalar replace.
148       continue;
149     case 1:  // Safe, but requires cleanup/canonicalizations first
150       CanonicalizeAllocaUsers(AI);
151     case 3:  // Safe to scalar replace.
152       break;
153     }
154
155     DEBUG(std::cerr << "Found inst to xform: " << *AI);
156     Changed = true;
157
158     std::vector<AllocaInst*> ElementAllocas;
159     if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
160       ElementAllocas.reserve(ST->getNumContainedTypes());
161       for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
162         AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0, 
163                                         AI->getAlignment(),
164                                         AI->getName() + "." + utostr(i), AI);
165         ElementAllocas.push_back(NA);
166         WorkList.push_back(NA);  // Add to worklist for recursive processing
167       }
168     } else {
169       const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
170       ElementAllocas.reserve(AT->getNumElements());
171       const Type *ElTy = AT->getElementType();
172       for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
173         AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
174                                         AI->getName() + "." + utostr(i), AI);
175         ElementAllocas.push_back(NA);
176         WorkList.push_back(NA);  // Add to worklist for recursive processing
177       }
178     }
179
180     // Now that we have created the alloca instructions that we want to use,
181     // expand the getelementptr instructions to use them.
182     //
183     while (!AI->use_empty()) {
184       Instruction *User = cast<Instruction>(AI->use_back());
185       GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
186       // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
187       unsigned Idx =
188          (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getRawValue();
189
190       assert(Idx < ElementAllocas.size() && "Index out of range?");
191       AllocaInst *AllocaToUse = ElementAllocas[Idx];
192
193       Value *RepValue;
194       if (GEPI->getNumOperands() == 3) {
195         // Do not insert a new getelementptr instruction with zero indices, only
196         // to have it optimized out later.
197         RepValue = AllocaToUse;
198       } else {
199         // We are indexing deeply into the structure, so we still need a
200         // getelement ptr instruction to finish the indexing.  This may be
201         // expanded itself once the worklist is rerun.
202         //
203         std::string OldName = GEPI->getName();  // Steal the old name.
204         std::vector<Value*> NewArgs;
205         NewArgs.push_back(Constant::getNullValue(Type::IntTy));
206         NewArgs.insert(NewArgs.end(), GEPI->op_begin()+3, GEPI->op_end());
207         GEPI->setName("");
208         RepValue = new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI);
209       }
210
211       // Move all of the users over to the new GEP.
212       GEPI->replaceAllUsesWith(RepValue);
213       // Delete the old GEP
214       GEPI->eraseFromParent();
215     }
216
217     // Finally, delete the Alloca instruction
218     AI->getParent()->getInstList().erase(AI);
219     NumReplaced++;
220   }
221
222   return Changed;
223 }
224
225
226 /// isSafeElementUse - Check to see if this use is an allowed use for a
227 /// getelementptr instruction of an array aggregate allocation.
228 ///
229 int SROA::isSafeElementUse(Value *Ptr) {
230   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
231        I != E; ++I) {
232     Instruction *User = cast<Instruction>(*I);
233     switch (User->getOpcode()) {
234     case Instruction::Load:  break;
235     case Instruction::Store:
236       // Store is ok if storing INTO the pointer, not storing the pointer
237       if (User->getOperand(0) == Ptr) return 0;
238       break;
239     case Instruction::GetElementPtr: {
240       GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
241       if (GEP->getNumOperands() > 1) {
242         if (!isa<Constant>(GEP->getOperand(1)) ||
243             !cast<Constant>(GEP->getOperand(1))->isNullValue())
244           return 0;  // Using pointer arithmetic to navigate the array...
245       }
246       if (!isSafeElementUse(GEP)) return 0;
247       break;
248     }
249     default:
250       DEBUG(std::cerr << "  Transformation preventing inst: " << *User);
251       return 0;
252     }
253   }
254   return 3;  // All users look ok :)
255 }
256
257 /// AllUsersAreLoads - Return true if all users of this value are loads.
258 static bool AllUsersAreLoads(Value *Ptr) {
259   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
260        I != E; ++I)
261     if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
262       return false;
263   return true;
264 }
265
266 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
267 /// aggregate allocation.
268 ///
269 int SROA::isSafeUseOfAllocation(Instruction *User) {
270   if (!isa<GetElementPtrInst>(User)) return 0;
271
272   GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
273   gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
274
275   // The GEP is safe to transform if it is of the form GEP <ptr>, 0, <cst>
276   if (I == E ||
277       I.getOperand() != Constant::getNullValue(I.getOperand()->getType()))
278     return 0;
279
280   ++I;
281   if (I == E) return 0;  // ran out of GEP indices??
282
283   // If this is a use of an array allocation, do a bit more checking for sanity.
284   if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
285     uint64_t NumElements = AT->getNumElements();
286
287     if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
288       // Check to make sure that index falls within the array.  If not,
289       // something funny is going on, so we won't do the optimization.
290       //
291       if (cast<ConstantInt>(GEPI->getOperand(2))->getRawValue() >= NumElements)
292         return 0;
293
294     } else {
295       // If this is an array index and the index is not constant, we cannot
296       // promote... that is unless the array has exactly one or two elements in
297       // it, in which case we CAN promote it, but we have to canonicalize this
298       // out if this is the only problem.
299       if (NumElements == 1 || NumElements == 2)
300         return AllUsersAreLoads(GEPI) ? 1 : 0;  // Canonicalization required!
301       return 0;
302     }
303   }
304
305   // If there are any non-simple uses of this getelementptr, make sure to reject
306   // them.
307   return isSafeElementUse(GEPI);
308 }
309
310 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
311 /// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
312 /// or 1 if safe after canonicalization has been performed.
313 ///
314 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
315   // Loop over the use list of the alloca.  We can only transform it if all of
316   // the users are safe to transform.
317   //
318   int isSafe = 3;
319   for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
320        I != E; ++I) {
321     isSafe &= isSafeUseOfAllocation(cast<Instruction>(*I));
322     if (isSafe == 0) {
323       DEBUG(std::cerr << "Cannot transform: " << *AI << "  due to user: "
324             << **I);
325       return 0;
326     }
327   }
328   // If we require cleanup, isSafe is now 1, otherwise it is 3.
329   return isSafe;
330 }
331
332 /// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
333 /// allocation, but only if cleaned up, perform the cleanups required.
334 void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
335   // At this point, we know that the end result will be SROA'd and promoted, so
336   // we can insert ugly code if required so long as sroa+mem2reg will clean it
337   // up.
338   for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
339        UI != E; ) {
340     GetElementPtrInst *GEPI = cast<GetElementPtrInst>(*UI++);
341     gep_type_iterator I = gep_type_begin(GEPI);
342     ++I;
343
344     if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
345       uint64_t NumElements = AT->getNumElements();
346
347       if (!isa<ConstantInt>(I.getOperand())) {
348         if (NumElements == 1) {
349           GEPI->setOperand(2, Constant::getNullValue(Type::IntTy));
350         } else {
351           assert(NumElements == 2 && "Unhandled case!");
352           // All users of the GEP must be loads.  At each use of the GEP, insert
353           // two loads of the appropriate indexed GEP and select between them.
354           Value *IsOne = BinaryOperator::createSetNE(I.getOperand(),
355                               Constant::getNullValue(I.getOperand()->getType()),
356                                                      "isone", GEPI);
357           // Insert the new GEP instructions, which are properly indexed.
358           std::vector<Value*> Indices(GEPI->op_begin()+1, GEPI->op_end());
359           Indices[1] = Constant::getNullValue(Type::IntTy);
360           Value *ZeroIdx = new GetElementPtrInst(GEPI->getOperand(0), Indices,
361                                                  GEPI->getName()+".0", GEPI);
362           Indices[1] = ConstantInt::get(Type::IntTy, 1);
363           Value *OneIdx = new GetElementPtrInst(GEPI->getOperand(0), Indices,
364                                                 GEPI->getName()+".1", GEPI);
365           // Replace all loads of the variable index GEP with loads from both
366           // indexes and a select.
367           while (!GEPI->use_empty()) {
368             LoadInst *LI = cast<LoadInst>(GEPI->use_back());
369             Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
370             Value *One  = new LoadInst(OneIdx , LI->getName()+".1", LI);
371             Value *R = new SelectInst(IsOne, One, Zero, LI->getName(), LI);
372             LI->replaceAllUsesWith(R);
373             LI->eraseFromParent();
374           }
375           GEPI->eraseFromParent();
376         }
377       }
378     }
379   }
380 }