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