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