* Add documentation
[oota-llvm.git] / lib / Transforms / IPO / DeadTypeElimination.cpp
1 //===- CleanupGCCOutput.cpp - Cleanup GCC Output --------------------------===//
2 //
3 // This pass is used to cleanup the output of GCC.  GCC's output is
4 // unneccessarily gross for a couple of reasons. This pass does the following
5 // things to try to clean it up:
6 //
7 // * Eliminate names for GCC types that we know can't be needed by the user.
8 // * Eliminate names for types that are unused in the entire translation unit
9 // * Fix various problems that we might have in PHI nodes and casts
10 // * Link uses of 'void %foo(...)' to 'void %foo(sometypes)'
11 //
12 // Note:  This code produces dead declarations, it is a good idea to run DCE
13 //        after this pass.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Transforms/CleanupGCCOutput.h"
18 #include "llvm/Analysis/FindUsedTypes.h"
19 #include "TransformInternals.h"
20 #include "llvm/Module.h"
21 #include "llvm/SymbolTable.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/iPHINode.h"
24 #include "llvm/iMemory.h"
25 #include "llvm/iTerminators.h"
26 #include "llvm/iOther.h"
27 #include "llvm/Support/CFG.h"
28 #include "llvm/Pass.h"
29 #include <algorithm>
30 #include <iostream>
31 using std::vector;
32 using std::string;
33 using std::cerr;
34
35 static const Type *PtrSByte = 0;    // 'sbyte*' type
36
37 namespace {
38   struct CleanupGCCOutput : public MethodPass {
39     // doPassInitialization - For this pass, it removes global symbol table
40     // entries for primitive types.  These are never used for linking in GCC and
41     // they make the output uglier to look at, so we nuke them.
42     //
43     // Also, initialize instance variables.
44     //
45     bool doInitialization(Module *M);
46     
47     // runOnFunction - This method simplifies the specified function hopefully.
48     //
49     bool runOnMethod(Function *F);
50     
51     // doPassFinalization - Strip out type names that are unused by the program
52     bool doFinalization(Module *M);
53     
54     // getAnalysisUsageInfo - This function needs FindUsedTypes to do its job...
55     //
56     virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Required,
57                                       Pass::AnalysisSet &Destroyed,
58                                       Pass::AnalysisSet &Provided) {
59       // FIXME: Invalidates the CFG
60       Required.push_back(FindUsedTypes::ID);
61     }
62   };
63 }
64
65 Pass *createCleanupGCCOutputPass() {
66   return new CleanupGCCOutput();
67 }
68
69
70
71 // ShouldNukSymtabEntry - Return true if this module level symbol table entry
72 // should be eliminated.
73 //
74 static inline bool ShouldNukeSymtabEntry(const std::pair<string, Value*> &E) {
75   // Nuke all names for primitive types!
76   if (cast<Type>(E.second)->isPrimitiveType()) return true;
77
78   // Nuke all pointers to primitive types as well...
79   if (const PointerType *PT = dyn_cast<PointerType>(E.second))
80     if (PT->getElementType()->isPrimitiveType()) return true;
81
82   // The only types that could contain .'s in the program are things generated
83   // by GCC itself, including "complex.float" and friends.  Nuke them too.
84   if (E.first.find('.') != string::npos) return true;
85
86   return false;
87 }
88
89 // doInitialization - For this pass, it removes global symbol table
90 // entries for primitive types.  These are never used for linking in GCC and
91 // they make the output uglier to look at, so we nuke them.
92 //
93 bool CleanupGCCOutput::doInitialization(Module *M) {
94   bool Changed = false;
95
96   if (PtrSByte == 0)
97     PtrSByte = PointerType::get(Type::SByteTy);
98
99   if (M->hasSymbolTable()) {
100     SymbolTable *ST = M->getSymbolTable();
101
102     // Check the symbol table for superfluous type entries...
103     //
104     // Grab the 'type' plane of the module symbol...
105     SymbolTable::iterator STI = ST->find(Type::TypeTy);
106     if (STI != ST->end()) {
107       // Loop over all entries in the type plane...
108       SymbolTable::VarMap &Plane = STI->second;
109       for (SymbolTable::VarMap::iterator PI = Plane.begin(); PI != Plane.end();)
110         if (ShouldNukeSymtabEntry(*PI)) {    // Should we remove this entry?
111 #if MAP_IS_NOT_BRAINDEAD
112           PI = Plane.erase(PI);     // STD C++ Map should support this!
113 #else
114           Plane.erase(PI);          // Alas, GCC 2.95.3 doesn't  *SIGH*
115           PI = Plane.begin();
116 #endif
117           Changed = true;
118         } else {
119           ++PI;
120         }
121     }
122   }
123
124   return Changed;
125 }
126
127
128 // FixCastsAndPHIs - The LLVM GCC has a tendancy to intermix Cast instructions
129 // in with the PHI nodes.  These cast instructions are potentially there for two
130 // different reasons:
131 //
132 //   1. The cast could be for an early PHI, and be accidentally inserted before
133 //      another PHI node.  In this case, the PHI node should be moved to the end
134 //      of the PHI nodes in the basic block.  We know that it is this case if
135 //      the source for the cast is a PHI node in this basic block.
136 //
137 //   2. If not #1, the cast must be a source argument for one of the PHI nodes
138 //      in the current basic block.  If this is the case, the cast should be
139 //      lifted into the basic block for the appropriate predecessor. 
140 //
141 static inline bool FixCastsAndPHIs(BasicBlock *BB) {
142   bool Changed = false;
143
144   BasicBlock::iterator InsertPos = BB->begin();
145
146   // Find the end of the interesting instructions...
147   while (isa<PHINode>(*InsertPos) || isa<CastInst>(*InsertPos)) ++InsertPos;
148
149   // Back the InsertPos up to right after the last PHI node.
150   while (InsertPos != BB->begin() && isa<CastInst>(*(InsertPos-1))) --InsertPos;
151
152   // No PHI nodes, quick exit.
153   if (InsertPos == BB->begin()) return false;
154
155   // Loop over all casts trapped between the PHI's...
156   BasicBlock::iterator I = BB->begin();
157   while (I != InsertPos) {
158     if (CastInst *CI = dyn_cast<CastInst>(*I)) { // Fix all cast instructions
159       Value *Src = CI->getOperand(0);
160
161       // Move the cast instruction to the current insert position...
162       --InsertPos;                 // New position for cast to go...
163       std::swap(*InsertPos, *I);   // Cast goes down, PHI goes up
164
165       if (isa<PHINode>(Src) &&                                // Handle case #1
166           cast<PHINode>(Src)->getParent() == BB) {
167         // We're done for case #1
168       } else {                                                // Handle case #2
169         // In case #2, we have to do a few things:
170         //   1. Remove the cast from the current basic block.
171         //   2. Identify the PHI node that the cast is for.
172         //   3. Find out which predecessor the value is for.
173         //   4. Move the cast to the end of the basic block that it SHOULD be
174         //
175
176         // Remove the cast instruction from the basic block.  The remove only
177         // invalidates iterators in the basic block that are AFTER the removed
178         // element.  Because we just moved the CastInst to the InsertPos, no
179         // iterators get invalidated.
180         //
181         BB->getInstList().remove(InsertPos);
182
183         // Find the PHI node.  Since this cast was generated specifically for a
184         // PHI node, there can only be a single PHI node using it.
185         //
186         assert(CI->use_size() == 1 && "Exactly one PHI node should use cast!");
187         PHINode *PN = cast<PHINode>(*CI->use_begin());
188
189         // Find out which operand of the PHI it is...
190         unsigned i;
191         for (i = 0; i < PN->getNumIncomingValues(); ++i)
192           if (PN->getIncomingValue(i) == CI)
193             break;
194         assert(i != PN->getNumIncomingValues() && "PHI doesn't use cast!");
195
196         // Get the predecessor the value is for...
197         BasicBlock *Pred = PN->getIncomingBlock(i);
198
199         // Reinsert the cast right before the terminator in Pred.
200         Pred->getInstList().insert(Pred->end()-1, CI);
201       }
202     } else {
203       ++I;
204     }
205   }
206
207   return Changed;
208 }
209
210 // RefactorPredecessor - When we find out that a basic block is a repeated
211 // predecessor in a PHI node, we have to refactor the function until there is at
212 // most a single instance of a basic block in any predecessor list.
213 //
214 static inline void RefactorPredecessor(BasicBlock *BB, BasicBlock *Pred) {
215   Function *M = BB->getParent();
216   assert(find(pred_begin(BB), pred_end(BB), Pred) != pred_end(BB) &&
217          "Pred is not a predecessor of BB!");
218
219   // Create a new basic block, adding it to the end of the function.
220   BasicBlock *NewBB = new BasicBlock("", M);
221
222   // Add an unconditional branch to BB to the new block.
223   NewBB->getInstList().push_back(new BranchInst(BB));
224
225   // Get the terminator that causes a branch to BB from Pred.
226   TerminatorInst *TI = Pred->getTerminator();
227
228   // Find the first use of BB in the terminator...
229   User::op_iterator OI = find(TI->op_begin(), TI->op_end(), BB);
230   assert(OI != TI->op_end() && "Pred does not branch to BB!!!");
231
232   // Change the use of BB to point to the new stub basic block
233   *OI = NewBB;
234
235   // Now we need to loop through all of the PHI nodes in BB and convert their
236   // first incoming value for Pred to reference the new basic block instead.
237   //
238   for (BasicBlock::iterator I = BB->begin(); 
239        PHINode *PN = dyn_cast<PHINode>(*I); ++I) {
240     int BBIdx = PN->getBasicBlockIndex(Pred);
241     assert(BBIdx != -1 && "PHI node doesn't have an entry for Pred!");
242
243     // The value that used to look like it came from Pred now comes from NewBB
244     PN->setIncomingBlock((unsigned)BBIdx, NewBB);
245   }
246 }
247
248
249 // runOnMethod - Loop through the function and fix problems with the PHI nodes
250 // in the current function.  The problem is that PHI nodes might exist with
251 // multiple entries for the same predecessor.  GCC sometimes generates code that
252 // looks like this:
253 //
254 //  bb7:  br bool %cond1004, label %bb8, label %bb8
255 //  bb8: %reg119 = phi uint [ 0, %bb7 ], [ 1, %bb7 ]
256 //     
257 //     which is completely illegal LLVM code.  To compensate for this, we insert
258 //     an extra basic block, and convert the code to look like this:
259 //
260 //  bb7: br bool %cond1004, label %bbX, label %bb8
261 //  bbX: br label bb8
262 //  bb8: %reg119 = phi uint [ 0, %bbX ], [ 1, %bb7 ]
263 //
264 //
265 bool CleanupGCCOutput::runOnMethod(Function *M) {
266   bool Changed = false;
267   // Don't use iterators because invalidation gets messy...
268   for (unsigned MI = 0; MI < M->size(); ++MI) {
269     BasicBlock *BB = M->getBasicBlocks()[MI];
270
271     Changed |= FixCastsAndPHIs(BB);
272
273     if (isa<PHINode>(BB->front())) {
274       const vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
275
276       // Handle the problem.  Sort the list of predecessors so that it is easy
277       // to decide whether or not duplicate predecessors exist.
278       vector<BasicBlock*> SortedPreds(Preds);
279       sort(SortedPreds.begin(), SortedPreds.end());
280
281       // Loop over the predecessors, looking for adjacent BB's that are equal.
282       BasicBlock *LastOne = 0;
283       for (unsigned i = 0; i < Preds.size(); ++i) {
284         if (SortedPreds[i] == LastOne) {   // Found a duplicate.
285           RefactorPredecessor(BB, SortedPreds[i]);
286           Changed = true;
287         }
288         LastOne = SortedPreds[i];
289       }
290     }
291   }
292   return Changed;
293 }
294
295 bool CleanupGCCOutput::doFinalization(Module *M) {
296   bool Changed = false;
297
298   if (M->hasSymbolTable()) {
299     SymbolTable *ST = M->getSymbolTable();
300     const std::set<const Type *> &UsedTypes =
301       getAnalysis<FindUsedTypes>().getTypes();
302
303     // Check the symbol table for superfluous type entries that aren't used in
304     // the program
305     //
306     // Grab the 'type' plane of the module symbol...
307     SymbolTable::iterator STI = ST->find(Type::TypeTy);
308     if (STI != ST->end()) {
309       // Loop over all entries in the type plane...
310       SymbolTable::VarMap &Plane = STI->second;
311       for (SymbolTable::VarMap::iterator PI = Plane.begin(); PI != Plane.end();)
312         if (!UsedTypes.count(cast<Type>(PI->second))) {
313 #if MAP_IS_NOT_BRAINDEAD
314           PI = Plane.erase(PI);     // STD C++ Map should support this!
315 #else
316           Plane.erase(PI);          // Alas, GCC 2.95.3 doesn't  *SIGH*
317           PI = Plane.begin();       // N^2 algorithms are fun.  :(
318 #endif
319           Changed = true;
320         } else {
321           ++PI;
322         }
323     }
324   }
325   return Changed;
326 }
327
328
329 //===----------------------------------------------------------------------===//
330 //
331 // FunctionResolvingPass - Go over the functions that are in the module and
332 // look for functions that have the same name.  More often than not, there will
333 // be things like:
334 //    void "foo"(...)
335 //    void "foo"(int, int)
336 // because of the way things are declared in C.  If this is the case, patch
337 // things up.
338 //
339 //===----------------------------------------------------------------------===//
340
341 namespace {
342   struct FunctionResolvingPass : public Pass {
343     bool run(Module *M);
344   };
345 }
346
347 // ConvertCallTo - Convert a call to a varargs function with no arg types
348 // specified to a concrete nonvarargs function.
349 //
350 static void ConvertCallTo(CallInst *CI, Function *Dest) {
351   const FunctionType::ParamTypes &ParamTys =
352     Dest->getFunctionType()->getParamTypes();
353   BasicBlock *BB = CI->getParent();
354
355   // Get an iterator to where we want to insert cast instructions if the
356   // argument types don't agree.
357   //
358   BasicBlock::iterator BBI = find(BB->begin(), BB->end(), CI);
359   assert(BBI != BB->end() && "CallInst not in parent block?");
360
361   assert(CI->getNumOperands()-1 == ParamTys.size()&&
362          "Function calls resolved funny somehow, incompatible number of args");
363
364   vector<Value*> Params;
365
366   // Convert all of the call arguments over... inserting cast instructions if
367   // the types are not compatible.
368   for (unsigned i = 1; i < CI->getNumOperands(); ++i) {
369     Value *V = CI->getOperand(i);
370
371     if (V->getType() != ParamTys[i-1]) { // Must insert a cast...
372       Instruction *Cast = new CastInst(V, ParamTys[i-1]);
373       BBI = BB->getInstList().insert(BBI, Cast)+1;
374       V = Cast;
375     }
376
377     Params.push_back(V);
378   }
379
380   // Replace the old call instruction with a new call instruction that calls
381   // the real function.
382   //
383   ReplaceInstWithInst(BB->getInstList(), BBI, new CallInst(Dest, Params));
384 }
385
386
387 bool FunctionResolvingPass::run(Module *M) {
388   SymbolTable *ST = M->getSymbolTable();
389   if (!ST) return false;
390
391   std::map<string, vector<Function*> > Functions;
392
393   // Loop over the entries in the symbol table. If an entry is a func pointer,
394   // then add it to the Functions map.  We do a two pass algorithm here to avoid
395   // problems with iterators getting invalidated if we did a one pass scheme.
396   //
397   for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I)
398     if (const PointerType *PT = dyn_cast<PointerType>(I->first))
399       if (isa<FunctionType>(PT->getElementType())) {
400         SymbolTable::VarMap &Plane = I->second;
401         for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
402              PI != PE; ++PI) {
403           const string &Name = PI->first;
404           Functions[Name].push_back(cast<Function>(PI->second));          
405         }
406       }
407
408   bool Changed = false;
409
410   // Now we have a list of all functions with a particular name.  If there is
411   // more than one entry in a list, merge the functions together.
412   //
413   for (std::map<string, vector<Function*> >::iterator I = Functions.begin(), 
414          E = Functions.end(); I != E; ++I) {
415     vector<Function*> &Functions = I->second;
416     Function *Implementation = 0;     // Find the implementation
417     Function *Concrete = 0;
418     for (unsigned i = 0; i < Functions.size(); ) {
419       if (!Functions[i]->isExternal()) {  // Found an implementation
420         assert(Implementation == 0 && "Multiple definitions of the same"
421                " function. Case not handled yet!");
422         Implementation = Functions[i];
423       } else {
424         // Ignore functions that are never used so they don't cause spurious
425         // warnings... here we will actually DCE the function so that it isn't
426         // used later.
427         //
428         if (Functions[i]->use_size() == 0) {
429           M->getFunctionList().remove(Functions[i]);
430           delete Functions[i];
431           Functions.erase(Functions.begin()+i);
432           Changed = true;
433           continue;
434         }
435       }
436       
437       if (Functions[i] && (!Functions[i]->getFunctionType()->isVarArg())) {
438         if (Concrete) {  // Found two different functions types.  Can't choose
439           Concrete = 0;
440           break;
441         }
442         Concrete = Functions[i];
443       }
444       ++i;
445     }
446
447     if (Functions.size() > 1) {         // Found a multiply defined function...
448       // We should find exactly one non-vararg function definition, which is
449       // probably the implementation.  Change all of the function definitions
450       // and uses to use it instead.
451       //
452       if (!Concrete) {
453         cerr << "Warning: Found functions types that are not compatible:\n";
454         for (unsigned i = 0; i < Functions.size(); ++i) {
455           cerr << "\t" << Functions[i]->getType()->getDescription() << " %"
456                << Functions[i]->getName() << "\n";
457         }
458         cerr << "  No linkage of functions named '" << Functions[0]->getName()
459              << "' performed!\n";
460       } else {
461         for (unsigned i = 0; i < Functions.size(); ++i)
462           if (Functions[i] != Concrete) {
463             Function *Old = Functions[i];
464             const FunctionType *OldMT = Old->getFunctionType();
465             const FunctionType *ConcreteMT = Concrete->getFunctionType();
466             bool Broken = false;
467
468             assert(Old->getReturnType() == Concrete->getReturnType() &&
469                    "Differing return types not handled yet!");
470             assert(OldMT->getParamTypes().size() <=
471                    ConcreteMT->getParamTypes().size() &&
472                    "Concrete type must have more specified parameters!");
473
474             // Check to make sure that if there are specified types, that they
475             // match...
476             //
477             for (unsigned i = 0; i < OldMT->getParamTypes().size(); ++i)
478               if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {
479                 cerr << "Parameter types conflict for" << OldMT
480                      << " and " << ConcreteMT;
481                 Broken = true;
482               }
483             if (Broken) break;  // Can't process this one!
484
485
486             // Attempt to convert all of the uses of the old function to the
487             // concrete form of the function.  If there is a use of the fn
488             // that we don't understand here we punt to avoid making a bad
489             // transformation.
490             //
491             // At this point, we know that the return values are the same for
492             // our two functions and that the Old function has no varargs fns
493             // specified.  In otherwords it's just <retty> (...)
494             //
495             for (unsigned i = 0; i < Old->use_size(); ) {
496               User *U = *(Old->use_begin()+i);
497               if (CastInst *CI = dyn_cast<CastInst>(U)) {
498                 // Convert casts directly
499                 assert(CI->getOperand(0) == Old);
500                 CI->setOperand(0, Concrete);
501                 Changed = true;
502               } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
503                 // Can only fix up calls TO the argument, not args passed in.
504                 if (CI->getCalledValue() == Old) {
505                   ConvertCallTo(CI, Concrete);
506                   Changed = true;
507                 } else {
508                   cerr << "Couldn't cleanup this function call, must be an"
509                        << " argument or something!" << CI;
510                   ++i;
511                 }
512               } else {
513                 cerr << "Cannot convert use of function: " << U << "\n";
514                 ++i;
515               }
516             }
517           }
518         }
519     }
520   }
521
522   return Changed;
523 }
524
525 Pass *createFunctionResolvingPass() {
526   return new FunctionResolvingPass();
527 }