1 //===- CleanupGCCOutput.cpp - Cleanup GCC Output ----------------------------=//
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:
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.
13 // Note: This code produces dead declarations, it is a good idea to run DCE
16 //===----------------------------------------------------------------------===//
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"
27 static const Type *PtrArrSByte = 0; // '[sbyte]*' type
28 static const Type *PtrSByte = 0; // 'sbyte*' type
30 // ConvertCallTo - Convert a call to a varargs function with no arg types
31 // specified to a concrete nonvarargs method.
33 static void ConvertCallTo(CallInst *CI, Method *Dest) {
34 const MethodType::ParamTypes &ParamTys =
35 Dest->getMethodType()->getParamTypes();
36 BasicBlock *BB = CI->getParent();
38 // Get an iterator to where we want to insert cast instructions if the
39 // argument types don't agree.
41 BasicBlock::iterator BBI = find(BB->begin(), BB->end(), CI);
42 assert(BBI != BB->end() && "CallInst not in parent block?");
44 assert(CI->getNumOperands()-1 == ParamTys.size()&&
45 "Method calls resolved funny somehow, incompatible number of args");
47 vector<Value*> Params;
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);
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;
63 // Replace the old call instruction with a new call instruction that calls
66 ReplaceInstWithInst(BB->getInstList(), BBI, new CallInst(Dest, Params));
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
74 // void "foo"(int, int)
75 // because of the way things are declared in C. If this is the case, patch
78 bool CleanupGCCOutput::PatchUpMethodReferences(Module *M) {
79 SymbolTable *ST = M->getSymbolTable();
80 if (!ST) return false;
82 map<string, vector<Method*> > Methods;
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.
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();
94 const string &Name = PI->first;
95 Method *M = cast<Method>(PI->second);
96 Methods[Name].push_back(M);
100 bool Changed = false;
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.
105 for (map<string, vector<Method*> >::iterator I = Methods.begin(),
106 E = Methods.end(); I != E; ++I) {
107 vector<Method*> &Methods = I->second;
108 Method *Implementation = 0; // Find the implementation
109 Method *Concrete = 0;
110 for (unsigned i = 0; i < Methods.size(); ) {
111 if (!Methods[i]->isExternal()) { // Found an implementation
112 assert(Implementation == 0 && "Multiple definitions of the same"
113 " method. Case not handled yet!");
114 Implementation = Methods[i];
116 // Ignore methods that are never used so they don't cause spurious
117 // warnings... here we will actually DCE the function so that it isn't
120 if (Methods[i]->use_size() == 0) {
121 M->getMethodList().remove(Methods[i]);
123 Methods.erase(Methods.begin()+i);
129 if (Methods[i] && (!Methods[i]->getMethodType()->isVarArg() ||
130 Methods[i]->getMethodType()->getParamTypes().size())) {
131 if (Concrete) { // Found two different methods types. Can't choose
135 Concrete = Methods[i];
140 if (Methods.size() > 1) { // Found a multiply defined method.
141 // We should find exactly one non-vararg method definition, which is
142 // probably the implementation. Change all of the method definitions
143 // and uses to use it instead.
146 cerr << "Warning: Found methods types that are not compatible:\n";
147 for (unsigned i = 0; i < Methods.size(); ++i) {
148 cerr << "\t" << Methods[i]->getType()->getDescription() << " %"
149 << Methods[i]->getName() << endl;
151 cerr << " No linkage of methods named '" << Methods[0]->getName()
154 for (unsigned i = 0; i < Methods.size(); ++i)
155 if (Methods[i] != Concrete) {
156 Method *Old = Methods[i];
157 assert(Old->getReturnType() == Concrete->getReturnType() &&
158 "Differing return types not handled yet!");
159 assert(Old->getMethodType()->getParamTypes().size() == 0 &&
160 "Cannot handle varargs fn's with specified element types!");
162 // Attempt to convert all of the uses of the old method to the
163 // concrete form of the method. If there is a use of the method
164 // that we don't understand here we punt to avoid making a bad
167 // At this point, we know that the return values are the same for
168 // our two functions and that the Old method has no varargs methods
169 // specified. In otherwords it's just <retty> (...)
171 for (unsigned i = 0; i < Old->use_size(); ) {
172 User *U = *(Old->use_begin()+i);
173 if (CastInst *CI = dyn_cast<CastInst>(U)) {
174 // Convert casts directly
175 assert(CI->getOperand(0) == Old);
176 CI->setOperand(0, Concrete);
178 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
179 // Can only fix up calls TO the argument, not args passed in.
180 if (CI->getCalledValue() == Old) {
181 ConvertCallTo(CI, Concrete);
184 cerr << "Couldn't cleanup this function call, must be an"
185 << " argument or something!" << CI;
189 cerr << "Cannot convert use of method: " << U << endl;
202 // ShouldNukSymtabEntry - Return true if this module level symbol table entry
203 // should be eliminated.
205 static inline bool ShouldNukeSymtabEntry(const pair<string, Value*> &E) {
206 // Nuke all names for primitive types!
207 if (cast<Type>(E.second)->isPrimitiveType()) return true;
209 // The only types that could contain .'s in the program are things generated
210 // by GCC itself, including "complex.float" and friends. Nuke them too.
211 if (E.first.find('.') != string::npos) return true;
216 // doPassInitialization - For this pass, it removes global symbol table
217 // entries for primitive types. These are never used for linking in GCC and
218 // they make the output uglier to look at, so we nuke them.
220 bool CleanupGCCOutput::doPassInitialization(Module *M) {
221 bool Changed = false;
223 if (PtrArrSByte == 0) {
224 PtrArrSByte = PointerType::get(ArrayType::get(Type::SByteTy));
225 PtrSByte = PointerType::get(Type::SByteTy);
228 if (M->hasSymbolTable()) {
229 SymbolTable *ST = M->getSymbolTable();
231 // Go over the methods that are in the module and look for methods that have
232 // the same name. More often than not, there will be things like:
233 // void "foo"(...) and void "foo"(int, int) because of the way things are
234 // declared in C. If this is the case, patch things up.
236 Changed |= PatchUpMethodReferences(M);
239 // If the module has a symbol table, they might be referring to the malloc
240 // and free functions. If this is the case, grab the method pointers that
241 // the module is using.
243 // Lookup %malloc and %free in the symbol table, for later use. If they
244 // don't exist, or are not external, we do not worry about converting calls
245 // to that function into the appropriate instruction.
247 const PointerType *MallocType = // Get the type for malloc
248 PointerType::get(MethodType::get(PointerType::get(Type::SByteTy),
249 vector<const Type*>(1, Type::UIntTy), false));
250 Malloc = cast_or_null<Method>(ST->lookup(MallocType, "malloc"));
251 if (Malloc && !Malloc->isExternal())
252 Malloc = 0; // Don't mess with locally defined versions of the fn
254 const PointerType *FreeType = // Get the type for free
255 PointerType::get(MethodType::get(Type::VoidTy,
256 vector<const Type*>(1, PointerType::get(Type::SByteTy)), false));
257 Free = cast_or_null<Method>(ST->lookup(FreeType, "free"));
258 if (Free && !Free->isExternal())
259 Free = 0; // Don't mess with locally defined versions of the fn
262 // Check the symbol table for superfluous type entries...
264 // Grab the 'type' plane of the module symbol...
265 SymbolTable::iterator STI = ST->find(Type::TypeTy);
266 if (STI != ST->end()) {
267 // Loop over all entries in the type plane...
268 SymbolTable::VarMap &Plane = STI->second;
269 for (SymbolTable::VarMap::iterator PI = Plane.begin(); PI != Plane.end();)
270 if (ShouldNukeSymtabEntry(*PI)) { // Should we remove this entry?
271 #if MAP_IS_NOT_BRAINDEAD
272 PI = Plane.erase(PI); // STD C++ Map should support this!
274 Plane.erase(PI); // Alas, GCC 2.95.3 doesn't *SIGH*
288 // doOneCleanupPass - Do one pass over the input method, fixing stuff up.
290 bool CleanupGCCOutput::doOneCleanupPass(Method *M) {
291 bool Changed = false;
292 for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
293 BasicBlock *BB = *MI;
294 BasicBlock::InstListType &BIL = BB->getInstList();
296 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
297 Instruction *I = *BI;
299 if (CallInst *CI = dyn_cast<CallInst>(I)) {
300 if (CI->getCalledValue() == Malloc) { // Replace call to malloc?
301 MallocInst *MallocI = new MallocInst(PtrArrSByte, CI->getOperand(1),
304 BI = BIL.insert(BI, MallocI)+1;
305 ReplaceInstWithInst(BIL, BI, new CastInst(MallocI, PtrSByte));
307 continue; // Skip the ++BI
308 } else if (CI->getCalledValue() == Free) { // Replace call to free?
309 ReplaceInstWithInst(BIL, BI, new FreeInst(CI->getOperand(1)));
311 continue; // Skip the ++BI
323 // FixCastsAndPHIs - The LLVM GCC has a tendancy to intermix Cast instructions
324 // in with the PHI nodes. These cast instructions are potentially there for two
325 // different reasons:
327 // 1. The cast could be for an early PHI, and be accidentally inserted before
328 // another PHI node. In this case, the PHI node should be moved to the end
329 // of the PHI nodes in the basic block. We know that it is this case if
330 // the source for the cast is a PHI node in this basic block.
332 // 2. If not #1, the cast must be a source argument for one of the PHI nodes
333 // in the current basic block. If this is the case, the cast should be
334 // lifted into the basic block for the appropriate predecessor.
336 static inline bool FixCastsAndPHIs(BasicBlock *BB) {
337 bool Changed = false;
339 BasicBlock::iterator InsertPos = BB->begin();
341 // Find the end of the interesting instructions...
342 while (isa<PHINode>(*InsertPos) || isa<CastInst>(*InsertPos)) ++InsertPos;
344 // Back the InsertPos up to right after the last PHI node.
345 while (InsertPos != BB->begin() && isa<CastInst>(*(InsertPos-1))) --InsertPos;
347 // No PHI nodes, quick exit.
348 if (InsertPos == BB->begin()) return false;
350 // Loop over all casts trapped between the PHI's...
351 BasicBlock::iterator I = BB->begin();
352 while (I != InsertPos) {
353 if (CastInst *CI = dyn_cast<CastInst>(*I)) { // Fix all cast instructions
354 Value *Src = CI->getOperand(0);
356 // Move the cast instruction to the current insert position...
357 --InsertPos; // New position for cast to go...
358 swap(*InsertPos, *I); // Cast goes down, PHI goes up
360 if (isa<PHINode>(Src) && // Handle case #1
361 cast<PHINode>(Src)->getParent() == BB) {
362 // We're done for case #1
363 } else { // Handle case #2
364 // In case #2, we have to do a few things:
365 // 1. Remove the cast from the current basic block.
366 // 2. Identify the PHI node that the cast is for.
367 // 3. Find out which predecessor the value is for.
368 // 4. Move the cast to the end of the basic block that it SHOULD be
371 // Remove the cast instruction from the basic block. The remove only
372 // invalidates iterators in the basic block that are AFTER the removed
373 // element. Because we just moved the CastInst to the InsertPos, no
374 // iterators get invalidated.
376 BB->getInstList().remove(InsertPos);
378 // Find the PHI node. Since this cast was generated specifically for a
379 // PHI node, there can only be a single PHI node using it.
381 assert(CI->use_size() == 1 && "Exactly one PHI node should use cast!");
382 PHINode *PN = cast<PHINode>(*CI->use_begin());
384 // Find out which operand of the PHI it is...
386 for (i = 0; i < PN->getNumIncomingValues(); ++i)
387 if (PN->getIncomingValue(i) == CI)
389 assert(i != PN->getNumIncomingValues() && "PHI doesn't use cast!");
391 // Get the predecessor the value is for...
392 BasicBlock *Pred = PN->getIncomingBlock(i);
394 // Reinsert the cast right before the terminator in Pred.
395 Pred->getInstList().insert(Pred->end()-1, CI);
406 // RefactorPredecessor - When we find out that a basic block is a repeated
407 // predecessor in a PHI node, we have to refactor the method until there is at
408 // most a single instance of a basic block in any predecessor list.
410 static inline void RefactorPredecessor(BasicBlock *BB, BasicBlock *Pred) {
411 Method *M = BB->getParent();
412 assert(find(BB->pred_begin(), BB->pred_end(), Pred) != BB->pred_end() &&
413 "Pred is not a predecessor of BB!");
415 // Create a new basic block, adding it to the end of the method.
416 BasicBlock *NewBB = new BasicBlock("", M);
418 // Add an unconditional branch to BB to the new block.
419 NewBB->getInstList().push_back(new BranchInst(BB));
421 // Get the terminator that causes a branch to BB from Pred.
422 TerminatorInst *TI = Pred->getTerminator();
424 // Find the first use of BB in the terminator...
425 User::op_iterator OI = find(TI->op_begin(), TI->op_end(), BB);
426 assert(OI != TI->op_end() && "Pred does not branch to BB!!!");
428 // Change the use of BB to point to the new stub basic block
431 // Now we need to loop through all of the PHI nodes in BB and convert their
432 // first incoming value for Pred to reference the new basic block instead.
434 for (BasicBlock::iterator I = BB->begin();
435 PHINode *PN = dyn_cast<PHINode>(*I); ++I) {
436 int BBIdx = PN->getBasicBlockIndex(Pred);
437 assert(BBIdx != -1 && "PHI node doesn't have an entry for Pred!");
439 // The value that used to look like it came from Pred now comes from NewBB
440 PN->setIncomingBlock((unsigned)BBIdx, NewBB);
445 // CheckIncomingValueFor - Make sure that the specified PHI node has an entry
446 // for the provided basic block. If it doesn't, add one and return true.
448 static inline void CheckIncomingValueFor(PHINode *PN, BasicBlock *BB) {
449 if (PN->getBasicBlockIndex(BB) != -1) return; // Already has value
452 const Type *Ty = PN->getType();
454 if (const PointerType *PT = dyn_cast<PointerType>(Ty))
455 NewVal = ConstPoolPointerNull::get(PT);
456 else if (Ty == Type::BoolTy)
457 NewVal = ConstPoolBool::True;
458 else if (Ty == Type::FloatTy || Ty == Type::DoubleTy)
459 NewVal = ConstPoolFP::get(Ty, 42);
460 else if (Ty->isIntegral())
461 NewVal = ConstPoolInt::get(Ty, 42);
463 assert(NewVal && "Unknown PHI node type!");
464 PN->addIncoming(NewVal, BB);
467 // fixLocalProblems - Loop through the method and fix problems with the PHI
468 // nodes in the current method. The two problems that are handled are:
470 // 1. PHI nodes with multiple entries for the same predecessor. GCC sometimes
471 // generates code that looks like this:
473 // bb7: br bool %cond1004, label %bb8, label %bb8
474 // bb8: %reg119 = phi uint [ 0, %bb7 ], [ 1, %bb7 ]
476 // which is completely illegal LLVM code. To compensate for this, we insert
477 // an extra basic block, and convert the code to look like this:
479 // bb7: br bool %cond1004, label %bbX, label %bb8
481 // bb8: %reg119 = phi uint [ 0, %bbX ], [ 1, %bb7 ]
484 // 2. PHI nodes with fewer arguments than predecessors.
485 // These can be generated by GCC if a variable is uninitalized over a path
486 // in the CFG. We fix this by adding an entry for the missing predecessors
487 // that is initialized to either 42 for a numeric/FP value, or null if it's
488 // a pointer value. This problem can be generated by code that looks like
496 static bool fixLocalProblems(Method *M) {
497 bool Changed = false;
498 // Don't use iterators because invalidation gets messy...
499 for (unsigned MI = 0; MI < M->size(); ++MI) {
500 BasicBlock *BB = M->getBasicBlocks()[MI];
502 Changed |= FixCastsAndPHIs(BB);
504 if (isa<PHINode>(BB->front())) {
505 const vector<BasicBlock*> Preds(BB->pred_begin(), BB->pred_end());
507 // Handle Problem #1. Sort the list of predecessors so that it is easy to
508 // decide whether or not duplicate predecessors exist.
509 vector<BasicBlock*> SortedPreds(Preds);
510 sort(SortedPreds.begin(), SortedPreds.end());
512 // Loop over the predecessors, looking for adjacent BB's that are equal.
513 BasicBlock *LastOne = 0;
514 for (unsigned i = 0; i < Preds.size(); ++i) {
515 if (SortedPreds[i] == LastOne) { // Found a duplicate.
516 RefactorPredecessor(BB, SortedPreds[i]);
519 LastOne = SortedPreds[i];
522 // Loop over all of the PHI nodes in the current BB. These PHI nodes are
523 // guaranteed to be at the beginning of the basic block.
525 for (BasicBlock::iterator I = BB->begin();
526 PHINode *PN = dyn_cast<PHINode>(*I); ++I) {
528 // Handle problem #2.
529 if (PN->getNumIncomingValues() != Preds.size()) {
530 assert(PN->getNumIncomingValues() <= Preds.size() &&
531 "Can't handle extra arguments to PHI nodes!");
532 for (unsigned i = 0; i < Preds.size(); ++i)
533 CheckIncomingValueFor(PN, Preds[i]);
545 // doPerMethodWork - This method simplifies the specified method hopefully.
547 bool CleanupGCCOutput::doPerMethodWork(Method *M) {
548 bool Changed = fixLocalProblems(M);
549 while (doOneCleanupPass(M)) Changed = true;