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