Make order of argument addition deterministic. In particular, the layout
[oota-llvm.git] / lib / Transforms / IPO / ArgumentPromotion.cpp
1 //===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
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 pass promotes "by reference" arguments to be "by value" arguments.  In
11 // practice, this means looking for internal functions that have pointer
12 // arguments.  If we can prove, through the use of alias analysis, that that an
13 // argument is *only* loaded, then we can pass the value into the function
14 // instead of the address of the value.  This can cause recursive simplification
15 // of code and lead to the elimination of allocas (especially in C++ template
16 // code like the STL).
17 //
18 // This pass also handles aggregate arguments that are passed into a function,
19 // scalarizing them if the elements of the aggregate are only loaded.  Note that
20 // we refuse to scalarize aggregates which would require passing in more than
21 // three operands to the function, because we don't want to pass thousands of
22 // operands for a large array or structure!
23 //
24 // Note that this transformation could also be done for arguments that are only
25 // stored to (returning the value instead), but we do not currently handle that
26 // case.  This case would be best handled when and if we start supporting
27 // multiple return values from functions.
28 //
29 //===----------------------------------------------------------------------===//
30
31 #define DEBUG_TYPE "argpromotion"
32 #include "llvm/Transforms/IPO.h"
33 #include "llvm/Constants.h"
34 #include "llvm/DerivedTypes.h"
35 #include "llvm/Module.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Instructions.h"
38 #include "llvm/Analysis/AliasAnalysis.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Support/CallSite.h"
41 #include "llvm/Support/CFG.h"
42 #include "Support/Debug.h"
43 #include "Support/DepthFirstIterator.h"
44 #include "Support/Statistic.h"
45 #include "Support/StringExtras.h"
46 #include <set>
47 using namespace llvm;
48
49 namespace {
50   Statistic<> NumArgumentsPromoted("argpromotion",
51                                    "Number of pointer arguments promoted");
52   Statistic<> NumAggregatesPromoted("argpromotion",
53                                     "Number of aggregate arguments promoted");
54   Statistic<> NumArgumentsDead("argpromotion",
55                                "Number of dead pointer args eliminated");
56
57   /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
58   ///
59   class ArgPromotion : public Pass {
60     // WorkList - The set of internal functions that we have yet to process.  As
61     // we eliminate arguments from a function, we push all callers into this set
62     // so that the by-reference argument can be bubbled out as far as possible.
63     // This set contains only internal functions.
64     std::set<Function*> WorkList;
65   public:
66     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67       AU.addRequired<AliasAnalysis>();
68       AU.addRequired<TargetData>();
69     }
70
71     virtual bool run(Module &M);
72   private:
73     bool PromoteArguments(Function *F);
74     bool isSafeToPromoteArgument(Argument *Arg) const;  
75     void DoPromotion(Function *F, std::vector<Argument*> &ArgsToPromote);
76   };
77
78   RegisterOpt<ArgPromotion> X("argpromotion",
79                               "Promote 'by reference' arguments to scalars");
80 }
81
82 Pass *llvm::createArgumentPromotionPass() {
83   return new ArgPromotion();
84 }
85
86 bool ArgPromotion::run(Module &M) {
87   bool Changed = false;
88   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
89     if (I->hasInternalLinkage()) {
90       WorkList.insert(I);
91
92       // If there are any constant pointer refs pointing to this function,
93       // eliminate them now if possible.
94       ConstantPointerRef *CPR = 0;
95       for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
96            ++UI)
97         if ((CPR = dyn_cast<ConstantPointerRef>(*UI)))
98           break;  // Found one!
99       if (CPR) {
100         // See if we can transform all users to use the function directly.
101         while (!CPR->use_empty()) {
102           User *TheUser = CPR->use_back();
103           if (!isa<Constant>(TheUser) && !isa<GlobalVariable>(TheUser)) {
104             Changed = true;
105             TheUser->replaceUsesOfWith(CPR, I);
106           } else {
107             // We won't be able to eliminate all users.  :(
108             WorkList.erase(I);  // Minor efficiency win.
109             break;
110           }
111         }
112
113         // If we nuked all users of the CPR, kill the CPR now!
114         if (CPR->use_empty()) {
115           CPR->destroyConstant();
116           Changed = true;
117         }
118       }
119     }
120   
121   while (!WorkList.empty()) {
122     Function *F = *WorkList.begin();
123     WorkList.erase(WorkList.begin());
124
125     if (PromoteArguments(F))    // Attempt to promote an argument.
126       Changed = true;           // Remember that we changed something.
127   }
128   
129   return Changed;
130 }
131
132 /// PromoteArguments - This method checks the specified function to see if there
133 /// are any promotable arguments and if it is safe to promote the function (for
134 /// example, all callers are direct).  If safe to promote some arguments, it
135 /// calls the DoPromotion method.
136 ///
137 bool ArgPromotion::PromoteArguments(Function *F) {
138   assert(F->hasInternalLinkage() && "We can only process internal functions!");
139
140   // First check: see if there are any pointer arguments!  If not, quick exit.
141   std::vector<Argument*> PointerArgs;
142   for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
143     if (isa<PointerType>(I->getType()))
144       PointerArgs.push_back(I);
145   if (PointerArgs.empty()) return false;
146
147   // Second check: make sure that all callers are direct callers.  We can't
148   // transform functions that have indirect callers.
149   for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
150        UI != E; ++UI) {
151     CallSite CS = CallSite::get(*UI);
152     if (!CS.getInstruction())       // "Taking the address" of the function
153       return false;
154
155     // Ensure that this call site is CALLING the function, not passing it as
156     // an argument.
157     for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
158          AI != E; ++AI)
159       if (*AI == F) return false;   // Passing the function address in!
160   }
161
162   // Check to see which arguments are promotable.  If an argument is not
163   // promotable, remove it from the PointerArgs vector.
164   for (unsigned i = 0; i != PointerArgs.size(); ++i)
165     if (!isSafeToPromoteArgument(PointerArgs[i])) {
166       std::swap(PointerArgs[i--], PointerArgs.back());
167       PointerArgs.pop_back();
168     }
169
170   // No promotable pointer arguments.
171   if (PointerArgs.empty()) return false;
172
173   // Okay, promote all of the arguments are rewrite the callees!
174   DoPromotion(F, PointerArgs);
175   return true;
176 }
177
178
179 /// isSafeToPromoteArgument - As you might guess from the name of this method,
180 /// it checks to see if it is both safe and useful to promote the argument.
181 /// This method limits promotion of aggregates to only promote up to three
182 /// elements of the aggregate in order to avoid exploding the number of
183 /// arguments passed in.
184 bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg) const {
185   // We can only promote this argument if all of the uses are loads, or are GEP
186   // instructions (with constant indices) that are subsequently loaded.
187   std::vector<LoadInst*> Loads;
188   std::vector<std::vector<ConstantInt*> > GEPIndices;
189   for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
190        UI != E; ++UI)
191     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
192       if (LI->isVolatile()) return false;  // Don't hack volatile loads
193       Loads.push_back(LI);
194     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
195       if (GEP->use_empty()) {
196         // Dead GEP's cause trouble later.  Just remove them if we run into
197         // them.
198         getAnalysis<AliasAnalysis>().deleteValue(GEP);
199         GEP->getParent()->getInstList().erase(GEP);
200         return isSafeToPromoteArgument(Arg);
201       }
202       // Ensure that all of the indices are constants.
203       std::vector<ConstantInt*> Operands;
204       for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
205         if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
206           Operands.push_back(C);
207         else
208           return false;  // Not a constant operand GEP!
209
210       // Ensure that the only users of the GEP are load instructions.
211       for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
212            UI != E; ++UI)
213         if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
214           if (LI->isVolatile()) return false;  // Don't hack volatile loads
215           Loads.push_back(LI);
216         } else {
217           return false;
218         }
219
220       // See if there is already a GEP with these indices.  If not, check to
221       // make sure that we aren't promoting too many elements.  If so, nothing
222       // to do.
223       if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
224           GEPIndices.end()) {
225         if (GEPIndices.size() == 3) {
226           DEBUG(std::cerr << "argpromotion disable promoting argument '"
227                 << Arg->getName() << "' because it would require adding more "
228                 << "than 3 arguments to the function.\n");
229           // We limit aggregate promotion to only promoting up to three elements
230           // of the aggregate.
231           return false;
232         }
233         GEPIndices.push_back(Operands);
234       }
235     } else {
236       return false;  // Not a load or a GEP.
237     }
238
239   if (Loads.empty()) return true;  // No users, this is a dead argument.
240
241   // Okay, now we know that the argument is only used by load instructions.  Use
242   // alias analysis to check to see if the pointer is guaranteed to not be
243   // modified from entry of the function to each of the load instructions.
244   Function &F = *Arg->getParent();
245
246   // Because there could be several/many load instructions, remember which
247   // blocks we know to be transparent to the load.
248   std::set<BasicBlock*> TranspBlocks;
249
250   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
251   TargetData &TD = getAnalysis<TargetData>();
252
253   for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
254     // Check to see if the load is invalidated from the start of the block to
255     // the load itself.
256     LoadInst *Load = Loads[i];
257     BasicBlock *BB = Load->getParent();
258
259     const PointerType *LoadTy =
260       cast<PointerType>(Load->getOperand(0)->getType());
261     unsigned LoadSize = TD.getTypeSize(LoadTy->getElementType());
262
263     if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
264       return false;  // Pointer is invalidated!
265
266     // Now check every path from the entry block to the load for transparency.
267     // To do this, we perform a depth first search on the inverse CFG from the
268     // loading block.
269     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
270       for (idf_ext_iterator<BasicBlock*> I = idf_ext_begin(*PI, TranspBlocks),
271              E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
272         if (AA.canBasicBlockModify(**I, Arg, LoadSize))
273           return false;
274   }
275
276   // If the path from the entry of the function to each load is free of
277   // instructions that potentially invalidate the load, we can make the
278   // transformation!
279   return true;
280 }
281
282 namespace {
283   /// GEPIdxComparator - Provide a strong ordering for GEP indices.  All Value*
284   /// elements are instances of ConstantInt.
285   ///
286   struct GEPIdxComparator {
287     bool operator()(const std::vector<Value*> &LHS,
288                     const std::vector<Value*> &RHS) const {
289       unsigned idx = 0;
290       for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
291         if (LHS[idx] != RHS[idx]) {
292           return cast<ConstantInt>(LHS[idx])->getRawValue() < 
293                  cast<ConstantInt>(RHS[idx])->getRawValue();
294         }
295       }
296
297       // Return less than if we ran out of stuff in LHS and we didn't run out of
298       // stuff in RHS.
299       return idx == LHS.size() && idx != RHS.size();
300     }
301   };
302 }
303
304
305 /// DoPromotion - This method actually performs the promotion of the specified
306 /// arguments.  At this point, we know that it's safe to do so.
307 void ArgPromotion::DoPromotion(Function *F, std::vector<Argument*> &Args2Prom) {
308   std::set<Argument*> ArgsToPromote(Args2Prom.begin(), Args2Prom.end());
309   
310   // Start by computing a new prototype for the function, which is the same as
311   // the old function, but has modified arguments.
312   const FunctionType *FTy = F->getFunctionType();
313   std::vector<const Type*> Params;
314
315   typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
316
317   // ScalarizedElements - If we are promoting a pointer that has elements
318   // accessed out of it, keep track of which elements are accessed so that we
319   // can add one argument for each.
320   //
321   // Arguments that are directly loaded will have a zero element value here, to
322   // handle cases where there are both a direct load and GEP accesses.
323   //
324   std::map<Argument*, ScalarizeTable> ScalarizedElements;
325
326   // OriginalLoads - Keep track of a representative load instruction from the
327   // original function so that we can tell the alias analysis implementation
328   // what the new GEP/Load instructions we are inserting look like.
329   std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
330
331   for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
332     if (!ArgsToPromote.count(I)) {
333       Params.push_back(I->getType());
334     } else if (I->use_empty()) {
335       ++NumArgumentsDead;
336     } else {
337       // Okay, this is being promoted.  Check to see if there are any GEP uses
338       // of the argument.
339       ScalarizeTable &ArgIndices = ScalarizedElements[I];
340       for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
341            ++UI) {
342         Instruction *User = cast<Instruction>(*UI);
343         assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
344         std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
345         ArgIndices.insert(Indices);
346         LoadInst *OrigLoad;
347         if (LoadInst *L = dyn_cast<LoadInst>(User))
348           OrigLoad = L;
349         else
350           OrigLoad = cast<LoadInst>(User->use_back());
351         OriginalLoads[Indices] = OrigLoad;
352       }
353
354       // Add a parameter to the function for each element passed in.
355       for (ScalarizeTable::iterator SI = ArgIndices.begin(),
356              E = ArgIndices.end(); SI != E; ++SI)
357         Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI));
358
359       if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
360         ++NumArgumentsPromoted;
361       else
362         ++NumAggregatesPromoted;
363     }
364
365   const Type *RetTy = FTy->getReturnType();
366
367   // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
368   // have zero fixed arguments.
369   bool ExtraArgHack = false;
370   if (Params.empty() && FTy->isVarArg()) {
371     ExtraArgHack = true;
372     Params.push_back(Type::IntTy);
373   }
374   FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
375   
376    // Create the new function body and insert it into the module...
377   Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
378   F->getParent()->getFunctionList().insert(F, NF);
379
380   // Get the alias analysis information that we need to update to reflect our
381   // changes.
382   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
383
384   // Loop over all of the callers of the function, transforming the call sites
385   // to pass in the loaded pointers.
386   //
387   std::vector<Value*> Args;
388   while (!F->use_empty()) {
389     CallSite CS = CallSite::get(F->use_back());
390     Instruction *Call = CS.getInstruction();
391
392     // Make sure the caller of this function is revisited now that we promoted
393     // arguments in a callee of it.
394     if (Call->getParent()->getParent()->hasInternalLinkage())
395       WorkList.insert(Call->getParent()->getParent());
396     
397     // Loop over the operands, inserting GEP and loads in the caller as
398     // appropriate.
399     CallSite::arg_iterator AI = CS.arg_begin();
400     for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++AI)
401       if (!ArgsToPromote.count(I))
402         Args.push_back(*AI);          // Unmodified argument
403       else if (!I->use_empty()) {
404         // Non-dead argument: insert GEPs and loads as appropriate.
405         ScalarizeTable &ArgIndices = ScalarizedElements[I];
406         for (ScalarizeTable::iterator SI = ArgIndices.begin(),
407                E = ArgIndices.end(); SI != E; ++SI) {
408           Value *V = *AI;
409           LoadInst *OrigLoad = OriginalLoads[*SI];
410           if (!SI->empty()) {
411             V = new GetElementPtrInst(V, *SI, V->getName()+".idx", Call);
412             AA.copyValue(OrigLoad->getOperand(0), V);
413           }
414           Args.push_back(new LoadInst(V, V->getName()+".val", Call));
415           AA.copyValue(OrigLoad, Args.back());
416         }
417       }
418
419     if (ExtraArgHack)
420       Args.push_back(Constant::getNullValue(Type::IntTy));
421
422     // Push any varargs arguments on the list
423     for (; AI != CS.arg_end(); ++AI)
424       Args.push_back(*AI);
425
426     Instruction *New;
427     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
428       New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
429                            Args, "", Call);
430     } else {
431       New = new CallInst(NF, Args, "", Call);
432     }
433     Args.clear();
434
435     // Update the alias analysis implementation to know that we are replacing
436     // the old call with a new one.
437     AA.replaceWithNewValue(Call, New);
438
439     if (!Call->use_empty()) {
440       Call->replaceAllUsesWith(New);
441       std::string Name = Call->getName();
442       Call->setName("");
443       New->setName(Name);
444     }
445     
446     // Finally, remove the old call from the program, reducing the use-count of
447     // F.
448     Call->getParent()->getInstList().erase(Call);
449   }
450
451   // Since we have now created the new function, splice the body of the old
452   // function right into the new function, leaving the old rotting hulk of the
453   // function empty.
454   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
455
456   // Loop over the argument list, transfering uses of the old arguments over to
457   // the new arguments, also transfering over the names as well.
458   //
459   for (Function::aiterator I = F->abegin(), E = F->aend(), I2 = NF->abegin();
460        I != E; ++I)
461     if (!ArgsToPromote.count(I)) {
462       // If this is an unmodified argument, move the name and users over to the
463       // new version.
464       I->replaceAllUsesWith(I2);
465       I2->setName(I->getName());
466       AA.replaceWithNewValue(I, I2);
467       ++I2;
468     } else if (I->use_empty()) {
469       AA.deleteValue(I);
470     } else {
471       // Otherwise, if we promoted this argument, then all users are load
472       // instructions, and all loads should be using the new argument that we
473       // added.
474       ScalarizeTable &ArgIndices = ScalarizedElements[I];
475
476       while (!I->use_empty()) {
477         if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
478           assert(ArgIndices.begin()->empty() &&
479                  "Load element should sort to front!");
480           I2->setName(I->getName()+".val");
481           LI->replaceAllUsesWith(I2);
482           AA.replaceWithNewValue(LI, I2);
483           LI->getParent()->getInstList().erase(LI);
484           DEBUG(std::cerr << "*** Promoted load of argument '" << I->getName()
485                           << "' in function '" << F->getName() << "'\n");
486         } else {
487           GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
488           std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
489
490           unsigned ArgNo = 0;
491           Function::aiterator TheArg = I2;
492           for (ScalarizeTable::iterator It = ArgIndices.begin();
493                *It != Operands; ++It, ++TheArg) {
494             assert(It != ArgIndices.end() && "GEP not handled??");
495           }
496
497           std::string NewName = I->getName();
498           for (unsigned i = 0, e = Operands.size(); i != e; ++i)
499             if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
500               NewName += "."+itostr((int64_t)CI->getRawValue());
501             else
502               NewName += ".x";
503           TheArg->setName(NewName+".val");
504
505           DEBUG(std::cerr << "*** Promoted agg argument '" << TheArg->getName()
506                           << "' of function '" << F->getName() << "'\n");
507
508           // All of the uses must be load instructions.  Replace them all with
509           // the argument specified by ArgNo.
510           while (!GEP->use_empty()) {
511             LoadInst *L = cast<LoadInst>(GEP->use_back());
512             L->replaceAllUsesWith(TheArg);
513             AA.replaceWithNewValue(L, TheArg);
514             L->getParent()->getInstList().erase(L);
515           }
516           AA.deleteValue(GEP);
517           GEP->getParent()->getInstList().erase(GEP);
518         }
519       }
520
521       // If we inserted a new pointer type, it's possible that IT could be
522       // promoted too.  Also, increment I2 past all of the arguments added for
523       // this promoted pointer.
524       for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i, ++I2)
525         if (isa<PointerType>(I2->getType()))
526           WorkList.insert(NF);
527     }
528
529   // Notify the alias analysis implementation that we inserted a new argument.
530   if (ExtraArgHack)
531     AA.copyValue(Constant::getNullValue(Type::IntTy), NF->abegin());
532
533
534   // Tell the alias analysis that the old function is about to disappear.
535   AA.replaceWithNewValue(F, NF);
536
537   // Now that the old function is dead, delete it.
538   F->getParent()->getFunctionList().erase(F);
539 }