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