Fix a ton of comment typos found by codespell. Patch by
[oota-llvm.git] / lib / Transforms / IPO / DeadArgumentElimination.cpp
1 //===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass deletes dead arguments from internal functions.  Dead argument
11 // elimination removes arguments which are directly dead, as well as arguments
12 // only passed into function calls as dead arguments of other functions.  This
13 // pass also deletes dead return values in a similar way.
14 //
15 // This pass is often useful as a cleanup pass to run after aggressive
16 // interprocedural passes, which add possibly-dead arguments or return values.
17 //
18 //===----------------------------------------------------------------------===//
19
20 #define DEBUG_TYPE "deadargelim"
21 #include "llvm/Transforms/IPO.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constant.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/LLVMContext.h"
28 #include "llvm/Module.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/CallSite.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringExtras.h"
36 #include <map>
37 #include <set>
38 using namespace llvm;
39
40 STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
41 STATISTIC(NumRetValsEliminated  , "Number of unused return values removed");
42 STATISTIC(NumArgumentsReplacedWithUndef, 
43           "Number of unread args replaced with undef");
44 namespace {
45   /// DAE - The dead argument elimination pass.
46   ///
47   class DAE : public ModulePass {
48   public:
49
50     /// Struct that represents (part of) either a return value or a function
51     /// argument.  Used so that arguments and return values can be used
52     /// interchangeably.
53     struct RetOrArg {
54       RetOrArg(const Function *F, unsigned Idx, bool IsArg) : F(F), Idx(Idx),
55                IsArg(IsArg) {}
56       const Function *F;
57       unsigned Idx;
58       bool IsArg;
59
60       /// Make RetOrArg comparable, so we can put it into a map.
61       bool operator<(const RetOrArg &O) const {
62         if (F != O.F)
63           return F < O.F;
64         else if (Idx != O.Idx)
65           return Idx < O.Idx;
66         else
67           return IsArg < O.IsArg;
68       }
69
70       /// Make RetOrArg comparable, so we can easily iterate the multimap.
71       bool operator==(const RetOrArg &O) const {
72         return F == O.F && Idx == O.Idx && IsArg == O.IsArg;
73       }
74
75       std::string getDescription() const {
76         return std::string((IsArg ? "Argument #" : "Return value #"))
77                + utostr(Idx) + " of function " + F->getNameStr();
78       }
79     };
80
81     /// Liveness enum - During our initial pass over the program, we determine
82     /// that things are either alive or maybe alive. We don't mark anything
83     /// explicitly dead (even if we know they are), since anything not alive
84     /// with no registered uses (in Uses) will never be marked alive and will
85     /// thus become dead in the end.
86     enum Liveness { Live, MaybeLive };
87
88     /// Convenience wrapper
89     RetOrArg CreateRet(const Function *F, unsigned Idx) {
90       return RetOrArg(F, Idx, false);
91     }
92     /// Convenience wrapper
93     RetOrArg CreateArg(const Function *F, unsigned Idx) {
94       return RetOrArg(F, Idx, true);
95     }
96
97     typedef std::multimap<RetOrArg, RetOrArg> UseMap;
98     /// This maps a return value or argument to any MaybeLive return values or
99     /// arguments it uses. This allows the MaybeLive values to be marked live
100     /// when any of its users is marked live.
101     /// For example (indices are left out for clarity):
102     ///  - Uses[ret F] = ret G
103     ///    This means that F calls G, and F returns the value returned by G.
104     ///  - Uses[arg F] = ret G
105     ///    This means that some function calls G and passes its result as an
106     ///    argument to F.
107     ///  - Uses[ret F] = arg F
108     ///    This means that F returns one of its own arguments.
109     ///  - Uses[arg F] = arg G
110     ///    This means that G calls F and passes one of its own (G's) arguments
111     ///    directly to F.
112     UseMap Uses;
113
114     typedef std::set<RetOrArg> LiveSet;
115     typedef std::set<const Function*> LiveFuncSet;
116
117     /// This set contains all values that have been determined to be live.
118     LiveSet LiveValues;
119     /// This set contains all values that are cannot be changed in any way.
120     LiveFuncSet LiveFunctions;
121
122     typedef SmallVector<RetOrArg, 5> UseVector;
123
124   protected:
125     // DAH uses this to specify a different ID.
126     explicit DAE(char &ID) : ModulePass(ID) {}
127
128   public:
129     static char ID; // Pass identification, replacement for typeid
130     DAE() : ModulePass(ID) {
131       initializeDAEPass(*PassRegistry::getPassRegistry());
132     }
133
134     bool runOnModule(Module &M);
135
136     virtual bool ShouldHackArguments() const { return false; }
137
138   private:
139     Liveness MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses);
140     Liveness SurveyUse(Value::const_use_iterator U, UseVector &MaybeLiveUses,
141                        unsigned RetValNum = 0);
142     Liveness SurveyUses(const Value *V, UseVector &MaybeLiveUses);
143
144     void SurveyFunction(const Function &F);
145     void MarkValue(const RetOrArg &RA, Liveness L,
146                    const UseVector &MaybeLiveUses);
147     void MarkLive(const RetOrArg &RA);
148     void MarkLive(const Function &F);
149     void PropagateLiveness(const RetOrArg &RA);
150     bool RemoveDeadStuffFromFunction(Function *F);
151     bool DeleteDeadVarargs(Function &Fn);
152     bool RemoveDeadArgumentsFromCallers(Function &Fn);
153   };
154 }
155
156
157 char DAE::ID = 0;
158 INITIALIZE_PASS(DAE, "deadargelim", "Dead Argument Elimination", false, false)
159
160 namespace {
161   /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
162   /// deletes arguments to functions which are external.  This is only for use
163   /// by bugpoint.
164   struct DAH : public DAE {
165     static char ID;
166     DAH() : DAE(ID) {}
167
168     virtual bool ShouldHackArguments() const { return true; }
169   };
170 }
171
172 char DAH::ID = 0;
173 INITIALIZE_PASS(DAH, "deadarghaX0r", 
174                 "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)",
175                 false, false)
176
177 /// createDeadArgEliminationPass - This pass removes arguments from functions
178 /// which are not used by the body of the function.
179 ///
180 ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
181 ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
182
183 /// DeleteDeadVarargs - If this is an function that takes a ... list, and if
184 /// llvm.vastart is never called, the varargs list is dead for the function.
185 bool DAE::DeleteDeadVarargs(Function &Fn) {
186   assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
187   if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false;
188
189   // Ensure that the function is only directly called.
190   if (Fn.hasAddressTaken())
191     return false;
192
193   // Okay, we know we can transform this function if safe.  Scan its body
194   // looking for calls to llvm.vastart.
195   for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
196     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
197       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
198         if (II->getIntrinsicID() == Intrinsic::vastart)
199           return false;
200       }
201     }
202   }
203
204   // If we get here, there are no calls to llvm.vastart in the function body,
205   // remove the "..." and adjust all the calls.
206
207   // Start by computing a new prototype for the function, which is the same as
208   // the old function, but doesn't have isVarArg set.
209   const FunctionType *FTy = Fn.getFunctionType();
210
211   std::vector<const Type*> Params(FTy->param_begin(), FTy->param_end());
212   FunctionType *NFTy = FunctionType::get(FTy->getReturnType(),
213                                                 Params, false);
214   unsigned NumArgs = Params.size();
215
216   // Create the new function body and insert it into the module...
217   Function *NF = Function::Create(NFTy, Fn.getLinkage());
218   NF->copyAttributesFrom(&Fn);
219   Fn.getParent()->getFunctionList().insert(&Fn, NF);
220   NF->takeName(&Fn);
221
222   // Loop over all of the callers of the function, transforming the call sites
223   // to pass in a smaller number of arguments into the new function.
224   //
225   std::vector<Value*> Args;
226   while (!Fn.use_empty()) {
227     CallSite CS(Fn.use_back());
228     Instruction *Call = CS.getInstruction();
229
230     // Pass all the same arguments.
231     Args.assign(CS.arg_begin(), CS.arg_begin() + NumArgs);
232
233     // Drop any attributes that were on the vararg arguments.
234     AttrListPtr PAL = CS.getAttributes();
235     if (!PAL.isEmpty() && PAL.getSlot(PAL.getNumSlots() - 1).Index > NumArgs) {
236       SmallVector<AttributeWithIndex, 8> AttributesVec;
237       for (unsigned i = 0; PAL.getSlot(i).Index <= NumArgs; ++i)
238         AttributesVec.push_back(PAL.getSlot(i));
239       if (Attributes FnAttrs = PAL.getFnAttributes())
240         AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
241       PAL = AttrListPtr::get(AttributesVec.begin(), AttributesVec.end());
242     }
243
244     Instruction *New;
245     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
246       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
247                                Args.begin(), Args.end(), "", Call);
248       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
249       cast<InvokeInst>(New)->setAttributes(PAL);
250     } else {
251       New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
252       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
253       cast<CallInst>(New)->setAttributes(PAL);
254       if (cast<CallInst>(Call)->isTailCall())
255         cast<CallInst>(New)->setTailCall();
256     }
257     New->setDebugLoc(Call->getDebugLoc());
258
259     Args.clear();
260
261     if (!Call->use_empty())
262       Call->replaceAllUsesWith(New);
263
264     New->takeName(Call);
265
266     // Finally, remove the old call from the program, reducing the use-count of
267     // F.
268     Call->eraseFromParent();
269   }
270
271   // Since we have now created the new function, splice the body of the old
272   // function right into the new function, leaving the old rotting hulk of the
273   // function empty.
274   NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
275
276   // Loop over the argument list, transferring uses of the old arguments over to
277   // the new arguments, also transferring over the names as well.  While we're at
278   // it, remove the dead arguments from the DeadArguments list.
279   //
280   for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
281        I2 = NF->arg_begin(); I != E; ++I, ++I2) {
282     // Move the name and users over to the new version.
283     I->replaceAllUsesWith(I2);
284     I2->takeName(I);
285   }
286
287   // Finally, nuke the old function.
288   Fn.eraseFromParent();
289   return true;
290 }
291
292 /// RemoveDeadArgumentsFromCallers - Checks if the given function has any 
293 /// arguments that are unused, and changes the caller parameters to be undefined
294 /// instead.
295 bool DAE::RemoveDeadArgumentsFromCallers(Function &Fn)
296 {
297   if (Fn.isDeclaration() || Fn.mayBeOverridden())
298     return false;
299
300   // Functions with local linkage should already have been handled.
301   if (Fn.hasLocalLinkage())
302     return false;
303
304   if (Fn.use_empty())
305     return false;
306
307   llvm::SmallVector<unsigned, 8> UnusedArgs;
308   for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(); 
309        I != E; ++I) {
310     Argument *Arg = I;
311
312     if (Arg->use_empty() && !Arg->hasByValAttr())
313       UnusedArgs.push_back(Arg->getArgNo());
314   }
315
316   if (UnusedArgs.empty())
317     return false;
318
319   bool Changed = false;
320
321   for (Function::use_iterator I = Fn.use_begin(), E = Fn.use_end(); 
322        I != E; ++I) {
323     CallSite CS(*I);
324     if (!CS || !CS.isCallee(I))
325       continue;
326
327     // Now go through all unused args and replace them with "undef".
328     for (unsigned I = 0, E = UnusedArgs.size(); I != E; ++I) {
329       unsigned ArgNo = UnusedArgs[I];
330
331       Value *Arg = CS.getArgument(ArgNo);
332       CS.setArgument(ArgNo, UndefValue::get(Arg->getType()));
333       ++NumArgumentsReplacedWithUndef;
334       Changed = true;
335     }
336   }
337
338   return Changed;
339 }
340
341 /// Convenience function that returns the number of return values. It returns 0
342 /// for void functions and 1 for functions not returning a struct. It returns
343 /// the number of struct elements for functions returning a struct.
344 static unsigned NumRetVals(const Function *F) {
345   if (F->getReturnType()->isVoidTy())
346     return 0;
347   else if (const StructType *STy = dyn_cast<StructType>(F->getReturnType()))
348     return STy->getNumElements();
349   else
350     return 1;
351 }
352
353 /// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
354 /// live, it adds Use to the MaybeLiveUses argument. Returns the determined
355 /// liveness of Use.
356 DAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) {
357   // We're live if our use or its Function is already marked as live.
358   if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
359     return Live;
360
361   // We're maybe live otherwise, but remember that we must become live if
362   // Use becomes live.
363   MaybeLiveUses.push_back(Use);
364   return MaybeLive;
365 }
366
367
368 /// SurveyUse - This looks at a single use of an argument or return value
369 /// and determines if it should be alive or not. Adds this use to MaybeLiveUses
370 /// if it causes the used value to become MaybeLive.
371 ///
372 /// RetValNum is the return value number to use when this use is used in a
373 /// return instruction. This is used in the recursion, you should always leave
374 /// it at 0.
375 DAE::Liveness DAE::SurveyUse(Value::const_use_iterator U,
376                              UseVector &MaybeLiveUses, unsigned RetValNum) {
377     const User *V = *U;
378     if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
379       // The value is returned from a function. It's only live when the
380       // function's return value is live. We use RetValNum here, for the case
381       // that U is really a use of an insertvalue instruction that uses the
382       // original Use.
383       RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum);
384       // We might be live, depending on the liveness of Use.
385       return MarkIfNotLive(Use, MaybeLiveUses);
386     }
387     if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
388       if (U.getOperandNo() != InsertValueInst::getAggregateOperandIndex()
389           && IV->hasIndices())
390         // The use we are examining is inserted into an aggregate. Our liveness
391         // depends on all uses of that aggregate, but if it is used as a return
392         // value, only index at which we were inserted counts.
393         RetValNum = *IV->idx_begin();
394
395       // Note that if we are used as the aggregate operand to the insertvalue,
396       // we don't change RetValNum, but do survey all our uses.
397
398       Liveness Result = MaybeLive;
399       for (Value::const_use_iterator I = IV->use_begin(),
400            E = V->use_end(); I != E; ++I) {
401         Result = SurveyUse(I, MaybeLiveUses, RetValNum);
402         if (Result == Live)
403           break;
404       }
405       return Result;
406     }
407
408     if (ImmutableCallSite CS = V) {
409       const Function *F = CS.getCalledFunction();
410       if (F) {
411         // Used in a direct call.
412
413         // Find the argument number. We know for sure that this use is an
414         // argument, since if it was the function argument this would be an
415         // indirect call and the we know can't be looking at a value of the
416         // label type (for the invoke instruction).
417         unsigned ArgNo = CS.getArgumentNo(U);
418
419         if (ArgNo >= F->getFunctionType()->getNumParams())
420           // The value is passed in through a vararg! Must be live.
421           return Live;
422
423         assert(CS.getArgument(ArgNo)
424                == CS->getOperand(U.getOperandNo())
425                && "Argument is not where we expected it");
426
427         // Value passed to a normal call. It's only live when the corresponding
428         // argument to the called function turns out live.
429         RetOrArg Use = CreateArg(F, ArgNo);
430         return MarkIfNotLive(Use, MaybeLiveUses);
431       }
432     }
433     // Used in any other way? Value must be live.
434     return Live;
435 }
436
437 /// SurveyUses - This looks at all the uses of the given value
438 /// Returns the Liveness deduced from the uses of this value.
439 ///
440 /// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
441 /// the result is Live, MaybeLiveUses might be modified but its content should
442 /// be ignored (since it might not be complete).
443 DAE::Liveness DAE::SurveyUses(const Value *V, UseVector &MaybeLiveUses) {
444   // Assume it's dead (which will only hold if there are no uses at all..).
445   Liveness Result = MaybeLive;
446   // Check each use.
447   for (Value::const_use_iterator I = V->use_begin(),
448        E = V->use_end(); I != E; ++I) {
449     Result = SurveyUse(I, MaybeLiveUses);
450     if (Result == Live)
451       break;
452   }
453   return Result;
454 }
455
456 // SurveyFunction - This performs the initial survey of the specified function,
457 // checking out whether or not it uses any of its incoming arguments or whether
458 // any callers use the return value.  This fills in the LiveValues set and Uses
459 // map.
460 //
461 // We consider arguments of non-internal functions to be intrinsically alive as
462 // well as arguments to functions which have their "address taken".
463 //
464 void DAE::SurveyFunction(const Function &F) {
465   unsigned RetCount = NumRetVals(&F);
466   // Assume all return values are dead
467   typedef SmallVector<Liveness, 5> RetVals;
468   RetVals RetValLiveness(RetCount, MaybeLive);
469
470   typedef SmallVector<UseVector, 5> RetUses;
471   // These vectors map each return value to the uses that make it MaybeLive, so
472   // we can add those to the Uses map if the return value really turns out to be
473   // MaybeLive. Initialized to a list of RetCount empty lists.
474   RetUses MaybeLiveRetUses(RetCount);
475
476   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
477     if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
478       if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
479           != F.getFunctionType()->getReturnType()) {
480         // We don't support old style multiple return values.
481         MarkLive(F);
482         return;
483       }
484
485   if (!F.hasLocalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) {
486     MarkLive(F);
487     return;
488   }
489
490   DEBUG(dbgs() << "DAE - Inspecting callers for fn: " << F.getName() << "\n");
491   // Keep track of the number of live retvals, so we can skip checks once all
492   // of them turn out to be live.
493   unsigned NumLiveRetVals = 0;
494   const Type *STy = dyn_cast<StructType>(F.getReturnType());
495   // Loop all uses of the function.
496   for (Value::const_use_iterator I = F.use_begin(), E = F.use_end();
497        I != E; ++I) {
498     // If the function is PASSED IN as an argument, its address has been
499     // taken.
500     ImmutableCallSite CS(*I);
501     if (!CS || !CS.isCallee(I)) {
502       MarkLive(F);
503       return;
504     }
505
506     // If this use is anything other than a call site, the function is alive.
507     const Instruction *TheCall = CS.getInstruction();
508     if (!TheCall) {   // Not a direct call site?
509       MarkLive(F);
510       return;
511     }
512
513     // If we end up here, we are looking at a direct call to our function.
514
515     // Now, check how our return value(s) is/are used in this caller. Don't
516     // bother checking return values if all of them are live already.
517     if (NumLiveRetVals != RetCount) {
518       if (STy) {
519         // Check all uses of the return value.
520         for (Value::const_use_iterator I = TheCall->use_begin(),
521              E = TheCall->use_end(); I != E; ++I) {
522           const ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(*I);
523           if (Ext && Ext->hasIndices()) {
524             // This use uses a part of our return value, survey the uses of
525             // that part and store the results for this index only.
526             unsigned Idx = *Ext->idx_begin();
527             if (RetValLiveness[Idx] != Live) {
528               RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
529               if (RetValLiveness[Idx] == Live)
530                 NumLiveRetVals++;
531             }
532           } else {
533             // Used by something else than extractvalue. Mark all return
534             // values as live.
535             for (unsigned i = 0; i != RetCount; ++i )
536               RetValLiveness[i] = Live;
537             NumLiveRetVals = RetCount;
538             break;
539           }
540         }
541       } else {
542         // Single return value
543         RetValLiveness[0] = SurveyUses(TheCall, MaybeLiveRetUses[0]);
544         if (RetValLiveness[0] == Live)
545           NumLiveRetVals = RetCount;
546       }
547     }
548   }
549
550   // Now we've inspected all callers, record the liveness of our return values.
551   for (unsigned i = 0; i != RetCount; ++i)
552     MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]);
553
554   DEBUG(dbgs() << "DAE - Inspecting args for fn: " << F.getName() << "\n");
555
556   // Now, check all of our arguments.
557   unsigned i = 0;
558   UseVector MaybeLiveArgUses;
559   for (Function::const_arg_iterator AI = F.arg_begin(),
560        E = F.arg_end(); AI != E; ++AI, ++i) {
561     // See what the effect of this use is (recording any uses that cause
562     // MaybeLive in MaybeLiveArgUses).
563     Liveness Result = SurveyUses(AI, MaybeLiveArgUses);
564     // Mark the result.
565     MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
566     // Clear the vector again for the next iteration.
567     MaybeLiveArgUses.clear();
568   }
569 }
570
571 /// MarkValue - This function marks the liveness of RA depending on L. If L is
572 /// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
573 /// such that RA will be marked live if any use in MaybeLiveUses gets marked
574 /// live later on.
575 void DAE::MarkValue(const RetOrArg &RA, Liveness L,
576                     const UseVector &MaybeLiveUses) {
577   switch (L) {
578     case Live: MarkLive(RA); break;
579     case MaybeLive:
580     {
581       // Note any uses of this value, so this return value can be
582       // marked live whenever one of the uses becomes live.
583       for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
584            UE = MaybeLiveUses.end(); UI != UE; ++UI)
585         Uses.insert(std::make_pair(*UI, RA));
586       break;
587     }
588   }
589 }
590
591 /// MarkLive - Mark the given Function as alive, meaning that it cannot be
592 /// changed in any way. Additionally,
593 /// mark any values that are used as this function's parameters or by its return
594 /// values (according to Uses) live as well.
595 void DAE::MarkLive(const Function &F) {
596   DEBUG(dbgs() << "DAE - Intrinsically live fn: " << F.getName() << "\n");
597   // Mark the function as live.
598   LiveFunctions.insert(&F);
599   // Mark all arguments as live.
600   for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
601     PropagateLiveness(CreateArg(&F, i));
602   // Mark all return values as live.
603   for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i)
604     PropagateLiveness(CreateRet(&F, i));
605 }
606
607 /// MarkLive - Mark the given return value or argument as live. Additionally,
608 /// mark any values that are used by this value (according to Uses) live as
609 /// well.
610 void DAE::MarkLive(const RetOrArg &RA) {
611   if (LiveFunctions.count(RA.F))
612     return; // Function was already marked Live.
613
614   if (!LiveValues.insert(RA).second)
615     return; // We were already marked Live.
616
617   DEBUG(dbgs() << "DAE - Marking " << RA.getDescription() << " live\n");
618   PropagateLiveness(RA);
619 }
620
621 /// PropagateLiveness - Given that RA is a live value, propagate it's liveness
622 /// to any other values it uses (according to Uses).
623 void DAE::PropagateLiveness(const RetOrArg &RA) {
624   // We don't use upper_bound (or equal_range) here, because our recursive call
625   // to ourselves is likely to cause the upper_bound (which is the first value
626   // not belonging to RA) to become erased and the iterator invalidated.
627   UseMap::iterator Begin = Uses.lower_bound(RA);
628   UseMap::iterator E = Uses.end();
629   UseMap::iterator I;
630   for (I = Begin; I != E && I->first == RA; ++I)
631     MarkLive(I->second);
632
633   // Erase RA from the Uses map (from the lower bound to wherever we ended up
634   // after the loop).
635   Uses.erase(Begin, I);
636 }
637
638 // RemoveDeadStuffFromFunction - Remove any arguments and return values from F
639 // that are not in LiveValues. Transform the function and all of the callees of
640 // the function to not have these arguments and return values.
641 //
642 bool DAE::RemoveDeadStuffFromFunction(Function *F) {
643   // Don't modify fully live functions
644   if (LiveFunctions.count(F))
645     return false;
646
647   // Start by computing a new prototype for the function, which is the same as
648   // the old function, but has fewer arguments and a different return type.
649   const FunctionType *FTy = F->getFunctionType();
650   std::vector<const Type*> Params;
651
652   // Set up to build a new list of parameter attributes.
653   SmallVector<AttributeWithIndex, 8> AttributesVec;
654   const AttrListPtr &PAL = F->getAttributes();
655
656   // The existing function return attributes.
657   Attributes RAttrs = PAL.getRetAttributes();
658   Attributes FnAttrs = PAL.getFnAttributes();
659
660   // Find out the new return value.
661
662   const Type *RetTy = FTy->getReturnType();
663   const Type *NRetTy = NULL;
664   unsigned RetCount = NumRetVals(F);
665
666   // -1 means unused, other numbers are the new index
667   SmallVector<int, 5> NewRetIdxs(RetCount, -1);
668   std::vector<const Type*> RetTypes;
669   if (RetTy->isVoidTy()) {
670     NRetTy = RetTy;
671   } else {
672     const StructType *STy = dyn_cast<StructType>(RetTy);
673     if (STy)
674       // Look at each of the original return values individually.
675       for (unsigned i = 0; i != RetCount; ++i) {
676         RetOrArg Ret = CreateRet(F, i);
677         if (LiveValues.erase(Ret)) {
678           RetTypes.push_back(STy->getElementType(i));
679           NewRetIdxs[i] = RetTypes.size() - 1;
680         } else {
681           ++NumRetValsEliminated;
682           DEBUG(dbgs() << "DAE - Removing return value " << i << " from "
683                 << F->getName() << "\n");
684         }
685       }
686     else
687       // We used to return a single value.
688       if (LiveValues.erase(CreateRet(F, 0))) {
689         RetTypes.push_back(RetTy);
690         NewRetIdxs[0] = 0;
691       } else {
692         DEBUG(dbgs() << "DAE - Removing return value from " << F->getName()
693               << "\n");
694         ++NumRetValsEliminated;
695       }
696     if (RetTypes.size() > 1)
697       // More than one return type? Return a struct with them. Also, if we used
698       // to return a struct and didn't change the number of return values,
699       // return a struct again. This prevents changing {something} into
700       // something and {} into void.
701       // Make the new struct packed if we used to return a packed struct
702       // already.
703       NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked());
704     else if (RetTypes.size() == 1)
705       // One return type? Just a simple value then, but only if we didn't use to
706       // return a struct with that simple value before.
707       NRetTy = RetTypes.front();
708     else if (RetTypes.size() == 0)
709       // No return types? Make it void, but only if we didn't use to return {}.
710       NRetTy = Type::getVoidTy(F->getContext());
711   }
712
713   assert(NRetTy && "No new return type found?");
714
715   // Remove any incompatible attributes, but only if we removed all return
716   // values. Otherwise, ensure that we don't have any conflicting attributes
717   // here. Currently, this should not be possible, but special handling might be
718   // required when new return value attributes are added.
719   if (NRetTy->isVoidTy())
720     RAttrs &= ~Attribute::typeIncompatible(NRetTy);
721   else
722     assert((RAttrs & Attribute::typeIncompatible(NRetTy)) == 0
723            && "Return attributes no longer compatible?");
724
725   if (RAttrs)
726     AttributesVec.push_back(AttributeWithIndex::get(0, RAttrs));
727
728   // Remember which arguments are still alive.
729   SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
730   // Construct the new parameter list from non-dead arguments. Also construct
731   // a new set of parameter attributes to correspond. Skip the first parameter
732   // attribute, since that belongs to the return value.
733   unsigned i = 0;
734   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
735        I != E; ++I, ++i) {
736     RetOrArg Arg = CreateArg(F, i);
737     if (LiveValues.erase(Arg)) {
738       Params.push_back(I->getType());
739       ArgAlive[i] = true;
740
741       // Get the original parameter attributes (skipping the first one, that is
742       // for the return value.
743       if (Attributes Attrs = PAL.getParamAttributes(i + 1))
744         AttributesVec.push_back(AttributeWithIndex::get(Params.size(), Attrs));
745     } else {
746       ++NumArgumentsEliminated;
747       DEBUG(dbgs() << "DAE - Removing argument " << i << " (" << I->getName()
748             << ") from " << F->getName() << "\n");
749     }
750   }
751
752   if (FnAttrs != Attribute::None)
753     AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
754
755   // Reconstruct the AttributesList based on the vector we constructed.
756   AttrListPtr NewPAL = AttrListPtr::get(AttributesVec.begin(),
757                                         AttributesVec.end());
758
759   // Create the new function type based on the recomputed parameters.
760   FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
761
762   // No change?
763   if (NFTy == FTy)
764     return false;
765
766   // Create the new function body and insert it into the module...
767   Function *NF = Function::Create(NFTy, F->getLinkage());
768   NF->copyAttributesFrom(F);
769   NF->setAttributes(NewPAL);
770   // Insert the new function before the old function, so we won't be processing
771   // it again.
772   F->getParent()->getFunctionList().insert(F, NF);
773   NF->takeName(F);
774
775   // Loop over all of the callers of the function, transforming the call sites
776   // to pass in a smaller number of arguments into the new function.
777   //
778   std::vector<Value*> Args;
779   while (!F->use_empty()) {
780     CallSite CS(F->use_back());
781     Instruction *Call = CS.getInstruction();
782
783     AttributesVec.clear();
784     const AttrListPtr &CallPAL = CS.getAttributes();
785
786     // The call return attributes.
787     Attributes RAttrs = CallPAL.getRetAttributes();
788     Attributes FnAttrs = CallPAL.getFnAttributes();
789     // Adjust in case the function was changed to return void.
790     RAttrs &= ~Attribute::typeIncompatible(NF->getReturnType());
791     if (RAttrs)
792       AttributesVec.push_back(AttributeWithIndex::get(0, RAttrs));
793
794     // Declare these outside of the loops, so we can reuse them for the second
795     // loop, which loops the varargs.
796     CallSite::arg_iterator I = CS.arg_begin();
797     unsigned i = 0;
798     // Loop over those operands, corresponding to the normal arguments to the
799     // original function, and add those that are still alive.
800     for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
801       if (ArgAlive[i]) {
802         Args.push_back(*I);
803         // Get original parameter attributes, but skip return attributes.
804         if (Attributes Attrs = CallPAL.getParamAttributes(i + 1))
805           AttributesVec.push_back(AttributeWithIndex::get(Args.size(), Attrs));
806       }
807
808     // Push any varargs arguments on the list. Don't forget their attributes.
809     for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
810       Args.push_back(*I);
811       if (Attributes Attrs = CallPAL.getParamAttributes(i + 1))
812         AttributesVec.push_back(AttributeWithIndex::get(Args.size(), Attrs));
813     }
814
815     if (FnAttrs != Attribute::None)
816       AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
817
818     // Reconstruct the AttributesList based on the vector we constructed.
819     AttrListPtr NewCallPAL = AttrListPtr::get(AttributesVec.begin(),
820                                               AttributesVec.end());
821
822     Instruction *New;
823     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
824       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
825                                Args.begin(), Args.end(), "", Call);
826       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
827       cast<InvokeInst>(New)->setAttributes(NewCallPAL);
828     } else {
829       New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
830       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
831       cast<CallInst>(New)->setAttributes(NewCallPAL);
832       if (cast<CallInst>(Call)->isTailCall())
833         cast<CallInst>(New)->setTailCall();
834     }
835     New->setDebugLoc(Call->getDebugLoc());
836
837     Args.clear();
838
839     if (!Call->use_empty()) {
840       if (New->getType() == Call->getType()) {
841         // Return type not changed? Just replace users then.
842         Call->replaceAllUsesWith(New);
843         New->takeName(Call);
844       } else if (New->getType()->isVoidTy()) {
845         // Our return value has uses, but they will get removed later on.
846         // Replace by null for now.
847         if (!Call->getType()->isX86_MMXTy())
848           Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
849       } else {
850         assert(RetTy->isStructTy() &&
851                "Return type changed, but not into a void. The old return type"
852                " must have been a struct!");
853         Instruction *InsertPt = Call;
854         if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
855           BasicBlock::iterator IP = II->getNormalDest()->begin();
856           while (isa<PHINode>(IP)) ++IP;
857           InsertPt = IP;
858         }
859
860         // We used to return a struct. Instead of doing smart stuff with all the
861         // uses of this struct, we will just rebuild it using
862         // extract/insertvalue chaining and let instcombine clean that up.
863         //
864         // Start out building up our return value from undef
865         Value *RetVal = UndefValue::get(RetTy);
866         for (unsigned i = 0; i != RetCount; ++i)
867           if (NewRetIdxs[i] != -1) {
868             Value *V;
869             if (RetTypes.size() > 1)
870               // We are still returning a struct, so extract the value from our
871               // return value
872               V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret",
873                                            InsertPt);
874             else
875               // We are now returning a single element, so just insert that
876               V = New;
877             // Insert the value at the old position
878             RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", InsertPt);
879           }
880         // Now, replace all uses of the old call instruction with the return
881         // struct we built
882         Call->replaceAllUsesWith(RetVal);
883         New->takeName(Call);
884       }
885     }
886
887     // Finally, remove the old call from the program, reducing the use-count of
888     // F.
889     Call->eraseFromParent();
890   }
891
892   // Since we have now created the new function, splice the body of the old
893   // function right into the new function, leaving the old rotting hulk of the
894   // function empty.
895   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
896
897   // Loop over the argument list, transferring uses of the old arguments over to
898   // the new arguments, also transferring over the names as well.
899   i = 0;
900   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
901        I2 = NF->arg_begin(); I != E; ++I, ++i)
902     if (ArgAlive[i]) {
903       // If this is a live argument, move the name and users over to the new
904       // version.
905       I->replaceAllUsesWith(I2);
906       I2->takeName(I);
907       ++I2;
908     } else {
909       // If this argument is dead, replace any uses of it with null constants
910       // (these are guaranteed to become unused later on).
911       if (!I->getType()->isX86_MMXTy())
912         I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
913     }
914
915   // If we change the return value of the function we must rewrite any return
916   // instructions.  Check this now.
917   if (F->getReturnType() != NF->getReturnType())
918     for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
919       if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
920         Value *RetVal;
921
922         if (NFTy->getReturnType()->isVoidTy()) {
923           RetVal = 0;
924         } else {
925           assert (RetTy->isStructTy());
926           // The original return value was a struct, insert
927           // extractvalue/insertvalue chains to extract only the values we need
928           // to return and insert them into our new result.
929           // This does generate messy code, but we'll let it to instcombine to
930           // clean that up.
931           Value *OldRet = RI->getOperand(0);
932           // Start out building up our return value from undef
933           RetVal = UndefValue::get(NRetTy);
934           for (unsigned i = 0; i != RetCount; ++i)
935             if (NewRetIdxs[i] != -1) {
936               ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
937                                                               "oldret", RI);
938               if (RetTypes.size() > 1) {
939                 // We're still returning a struct, so reinsert the value into
940                 // our new return value at the new index
941
942                 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
943                                                  "newret", RI);
944               } else {
945                 // We are now only returning a simple value, so just return the
946                 // extracted value.
947                 RetVal = EV;
948               }
949             }
950         }
951         // Replace the return instruction with one returning the new return
952         // value (possibly 0 if we became void).
953         ReturnInst::Create(F->getContext(), RetVal, RI);
954         BB->getInstList().erase(RI);
955       }
956
957   // Now that the old function is dead, delete it.
958   F->eraseFromParent();
959
960   return true;
961 }
962
963 bool DAE::runOnModule(Module &M) {
964   bool Changed = false;
965
966   // First pass: Do a simple check to see if any functions can have their "..."
967   // removed.  We can do this if they never call va_start.  This loop cannot be
968   // fused with the next loop, because deleting a function invalidates
969   // information computed while surveying other functions.
970   DEBUG(dbgs() << "DAE - Deleting dead varargs\n");
971   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
972     Function &F = *I++;
973     if (F.getFunctionType()->isVarArg())
974       Changed |= DeleteDeadVarargs(F);
975   }
976
977   // Second phase:loop through the module, determining which arguments are live.
978   // We assume all arguments are dead unless proven otherwise (allowing us to
979   // determine that dead arguments passed into recursive functions are dead).
980   //
981   DEBUG(dbgs() << "DAE - Determining liveness\n");
982   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
983     SurveyFunction(*I);
984
985   // Now, remove all dead arguments and return values from each function in
986   // turn.
987   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
988     // Increment now, because the function will probably get removed (ie.
989     // replaced by a new one).
990     Function *F = I++;
991     Changed |= RemoveDeadStuffFromFunction(F);
992   }
993
994   // Finally, look for any unused parameters in functions with non-local
995   // linkage and replace the passed in parameters with undef.
996   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
997     Function& F = *I;
998
999     Changed |= RemoveDeadArgumentsFromCallers(F);
1000   }
1001
1002   return Changed;
1003 }