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
10 // Note: This code produces dead declarations, it is a good idea to run DCE
13 //===----------------------------------------------------------------------===//
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"
32 static const Type *PtrSByte = 0; // 'sbyte*' type
34 // ConvertCallTo - Convert a call to a varargs function with no arg types
35 // specified to a concrete nonvarargs method.
37 static void ConvertCallTo(CallInst *CI, Method *Dest) {
38 const MethodType::ParamTypes &ParamTys =
39 Dest->getMethodType()->getParamTypes();
40 BasicBlock *BB = CI->getParent();
42 // Get an iterator to where we want to insert cast instructions if the
43 // argument types don't agree.
45 BasicBlock::iterator BBI = find(BB->begin(), BB->end(), CI);
46 assert(BBI != BB->end() && "CallInst not in parent block?");
48 assert(CI->getNumOperands()-1 == ParamTys.size()&&
49 "Method calls resolved funny somehow, incompatible number of args");
51 vector<Value*> Params;
53 // Convert all of the call arguments over... inserting cast instructions if
54 // the types are not compatible.
55 for (unsigned i = 1; i < CI->getNumOperands(); ++i) {
56 Value *V = CI->getOperand(i);
58 if (V->getType() != ParamTys[i-1]) { // Must insert a cast...
59 Instruction *Cast = new CastInst(V, ParamTys[i-1]);
60 BBI = BB->getInstList().insert(BBI, Cast)+1;
67 // Replace the old call instruction with a new call instruction that calls
70 ReplaceInstWithInst(BB->getInstList(), BBI, new CallInst(Dest, Params));
74 // PatchUpMethodReferences - Go over the methods that are in the module and
75 // look for methods that have the same name. More often than not, there will
78 // void "foo"(int, int)
79 // because of the way things are declared in C. If this is the case, patch
82 bool CleanupGCCOutput::PatchUpMethodReferences(Module *M) {
83 SymbolTable *ST = M->getSymbolTable();
84 if (!ST) return false;
86 std::map<string, vector<Method*> > Methods;
88 // Loop over the entries in the symbol table. If an entry is a method pointer,
89 // then add it to the Methods map. We do a two pass algorithm here to avoid
90 // problems with iterators getting invalidated if we did a one pass scheme.
92 for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I)
93 if (const PointerType *PT = dyn_cast<PointerType>(I->first))
94 if (isa<MethodType>(PT->getElementType())) {
95 SymbolTable::VarMap &Plane = I->second;
96 for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
98 const string &Name = PI->first;
99 Method *M = cast<Method>(PI->second);
100 Methods[Name].push_back(M);
104 bool Changed = false;
106 // Now we have a list of all methods with a particular name. If there is more
107 // than one entry in a list, merge the methods together.
109 for (std::map<string, vector<Method*> >::iterator I = Methods.begin(),
110 E = Methods.end(); I != E; ++I) {
111 vector<Method*> &Methods = I->second;
112 Method *Implementation = 0; // Find the implementation
113 Method *Concrete = 0;
114 for (unsigned i = 0; i < Methods.size(); ) {
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];
120 // Ignore methods that are never used so they don't cause spurious
121 // warnings... here we will actually DCE the function so that it isn't
124 if (Methods[i]->use_size() == 0) {
125 M->getMethodList().remove(Methods[i]);
127 Methods.erase(Methods.begin()+i);
133 if (Methods[i] && (!Methods[i]->getMethodType()->isVarArg())) {
134 if (Concrete) { // Found two different methods types. Can't choose
138 Concrete = Methods[i];
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.
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";
154 cerr << " No linkage of methods named '" << Methods[0]->getName()
157 for (unsigned i = 0; i < Methods.size(); ++i)
158 if (Methods[i] != Concrete) {
159 Method *Old = Methods[i];
160 const MethodType *OldMT = Old->getMethodType();
161 const MethodType *ConcreteMT = Concrete->getMethodType();
164 assert(Old->getReturnType() == Concrete->getReturnType() &&
165 "Differing return types not handled yet!");
166 assert(OldMT->getParamTypes().size() <=
167 ConcreteMT->getParamTypes().size() &&
168 "Concrete type must have more specified parameters!");
170 // Check to make sure that if there are specified types, that they
173 for (unsigned i = 0; i < OldMT->getParamTypes().size(); ++i)
174 if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {
175 cerr << "Parameter types conflict for" << OldMT
176 << " and " << ConcreteMT;
179 if (Broken) break; // Can't process this one!
182 // Attempt to convert all of the uses of the old method to the
183 // concrete form of the method. If there is a use of the method
184 // that we don't understand here we punt to avoid making a bad
187 // At this point, we know that the return values are the same for
188 // our two functions and that the Old method has no varargs methods
189 // specified. In otherwords it's just <retty> (...)
191 for (unsigned i = 0; i < Old->use_size(); ) {
192 User *U = *(Old->use_begin()+i);
193 if (CastInst *CI = dyn_cast<CastInst>(U)) {
194 // Convert casts directly
195 assert(CI->getOperand(0) == Old);
196 CI->setOperand(0, Concrete);
198 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
199 // Can only fix up calls TO the argument, not args passed in.
200 if (CI->getCalledValue() == Old) {
201 ConvertCallTo(CI, Concrete);
204 cerr << "Couldn't cleanup this function call, must be an"
205 << " argument or something!" << CI;
209 cerr << "Cannot convert use of method: " << U << "\n";
222 // ShouldNukSymtabEntry - Return true if this module level symbol table entry
223 // should be eliminated.
225 static inline bool ShouldNukeSymtabEntry(const std::pair<string, Value*> &E) {
226 // Nuke all names for primitive types!
227 if (cast<Type>(E.second)->isPrimitiveType()) return true;
229 // Nuke all pointers to primitive types as well...
230 if (const PointerType *PT = dyn_cast<PointerType>(E.second))
231 if (PT->getElementType()->isPrimitiveType()) return true;
233 // The only types that could contain .'s in the program are things generated
234 // by GCC itself, including "complex.float" and friends. Nuke them too.
235 if (E.first.find('.') != string::npos) return true;
240 // doInitialization - For this pass, it removes global symbol table
241 // entries for primitive types. These are never used for linking in GCC and
242 // they make the output uglier to look at, so we nuke them.
244 bool CleanupGCCOutput::doInitialization(Module *M) {
245 bool Changed = false;
248 PtrSByte = PointerType::get(Type::SByteTy);
250 if (M->hasSymbolTable()) {
251 SymbolTable *ST = M->getSymbolTable();
253 // Go over the methods that are in the module and look for methods that have
254 // the same name. More often than not, there will be things like:
255 // void "foo"(...) and void "foo"(int, int) because of the way things are
256 // declared in C. If this is the case, patch things up.
258 Changed |= PatchUpMethodReferences(M);
260 // Check the symbol table for superfluous type entries...
262 // Grab the 'type' plane of the module symbol...
263 SymbolTable::iterator STI = ST->find(Type::TypeTy);
264 if (STI != ST->end()) {
265 // Loop over all entries in the type plane...
266 SymbolTable::VarMap &Plane = STI->second;
267 for (SymbolTable::VarMap::iterator PI = Plane.begin(); PI != Plane.end();)
268 if (ShouldNukeSymtabEntry(*PI)) { // Should we remove this entry?
269 #if MAP_IS_NOT_BRAINDEAD
270 PI = Plane.erase(PI); // STD C++ Map should support this!
272 Plane.erase(PI); // Alas, GCC 2.95.3 doesn't *SIGH*
286 // FixCastsAndPHIs - The LLVM GCC has a tendancy to intermix Cast instructions
287 // in with the PHI nodes. These cast instructions are potentially there for two
288 // different reasons:
290 // 1. The cast could be for an early PHI, and be accidentally inserted before
291 // another PHI node. In this case, the PHI node should be moved to the end
292 // of the PHI nodes in the basic block. We know that it is this case if
293 // the source for the cast is a PHI node in this basic block.
295 // 2. If not #1, the cast must be a source argument for one of the PHI nodes
296 // in the current basic block. If this is the case, the cast should be
297 // lifted into the basic block for the appropriate predecessor.
299 static inline bool FixCastsAndPHIs(BasicBlock *BB) {
300 bool Changed = false;
302 BasicBlock::iterator InsertPos = BB->begin();
304 // Find the end of the interesting instructions...
305 while (isa<PHINode>(*InsertPos) || isa<CastInst>(*InsertPos)) ++InsertPos;
307 // Back the InsertPos up to right after the last PHI node.
308 while (InsertPos != BB->begin() && isa<CastInst>(*(InsertPos-1))) --InsertPos;
310 // No PHI nodes, quick exit.
311 if (InsertPos == BB->begin()) return false;
313 // Loop over all casts trapped between the PHI's...
314 BasicBlock::iterator I = BB->begin();
315 while (I != InsertPos) {
316 if (CastInst *CI = dyn_cast<CastInst>(*I)) { // Fix all cast instructions
317 Value *Src = CI->getOperand(0);
319 // Move the cast instruction to the current insert position...
320 --InsertPos; // New position for cast to go...
321 std::swap(*InsertPos, *I); // Cast goes down, PHI goes up
323 if (isa<PHINode>(Src) && // Handle case #1
324 cast<PHINode>(Src)->getParent() == BB) {
325 // We're done for case #1
326 } else { // Handle case #2
327 // In case #2, we have to do a few things:
328 // 1. Remove the cast from the current basic block.
329 // 2. Identify the PHI node that the cast is for.
330 // 3. Find out which predecessor the value is for.
331 // 4. Move the cast to the end of the basic block that it SHOULD be
334 // Remove the cast instruction from the basic block. The remove only
335 // invalidates iterators in the basic block that are AFTER the removed
336 // element. Because we just moved the CastInst to the InsertPos, no
337 // iterators get invalidated.
339 BB->getInstList().remove(InsertPos);
341 // Find the PHI node. Since this cast was generated specifically for a
342 // PHI node, there can only be a single PHI node using it.
344 assert(CI->use_size() == 1 && "Exactly one PHI node should use cast!");
345 PHINode *PN = cast<PHINode>(*CI->use_begin());
347 // Find out which operand of the PHI it is...
349 for (i = 0; i < PN->getNumIncomingValues(); ++i)
350 if (PN->getIncomingValue(i) == CI)
352 assert(i != PN->getNumIncomingValues() && "PHI doesn't use cast!");
354 // Get the predecessor the value is for...
355 BasicBlock *Pred = PN->getIncomingBlock(i);
357 // Reinsert the cast right before the terminator in Pred.
358 Pred->getInstList().insert(Pred->end()-1, CI);
369 // RefactorPredecessor - When we find out that a basic block is a repeated
370 // predecessor in a PHI node, we have to refactor the method until there is at
371 // most a single instance of a basic block in any predecessor list.
373 static inline void RefactorPredecessor(BasicBlock *BB, BasicBlock *Pred) {
374 Method *M = BB->getParent();
375 assert(find(pred_begin(BB), pred_end(BB), Pred) != pred_end(BB) &&
376 "Pred is not a predecessor of BB!");
378 // Create a new basic block, adding it to the end of the method.
379 BasicBlock *NewBB = new BasicBlock("", M);
381 // Add an unconditional branch to BB to the new block.
382 NewBB->getInstList().push_back(new BranchInst(BB));
384 // Get the terminator that causes a branch to BB from Pred.
385 TerminatorInst *TI = Pred->getTerminator();
387 // Find the first use of BB in the terminator...
388 User::op_iterator OI = find(TI->op_begin(), TI->op_end(), BB);
389 assert(OI != TI->op_end() && "Pred does not branch to BB!!!");
391 // Change the use of BB to point to the new stub basic block
394 // Now we need to loop through all of the PHI nodes in BB and convert their
395 // first incoming value for Pred to reference the new basic block instead.
397 for (BasicBlock::iterator I = BB->begin();
398 PHINode *PN = dyn_cast<PHINode>(*I); ++I) {
399 int BBIdx = PN->getBasicBlockIndex(Pred);
400 assert(BBIdx != -1 && "PHI node doesn't have an entry for Pred!");
402 // The value that used to look like it came from Pred now comes from NewBB
403 PN->setIncomingBlock((unsigned)BBIdx, NewBB);
408 // CheckIncomingValueFor - Make sure that the specified PHI node has an entry
409 // for the provided basic block. If it doesn't, add one and return true.
411 static inline void CheckIncomingValueFor(PHINode *PN, BasicBlock *BB) {
412 if (PN->getBasicBlockIndex(BB) != -1) return; // Already has value
415 const Type *Ty = PN->getType();
417 if (const PointerType *PT = dyn_cast<PointerType>(Ty))
418 NewVal = ConstantPointerNull::get(PT);
419 else if (Ty == Type::BoolTy)
420 NewVal = ConstantBool::True;
421 else if (Ty == Type::FloatTy || Ty == Type::DoubleTy)
422 NewVal = ConstantFP::get(Ty, 42);
423 else if (Ty->isIntegral())
424 NewVal = ConstantInt::get(Ty, 42);
426 assert(NewVal && "Unknown PHI node type!");
427 PN->addIncoming(NewVal, BB);
430 // fixLocalProblems - Loop through the method and fix problems with the PHI
431 // nodes in the current method. The two problems that are handled are:
433 // 1. PHI nodes with multiple entries for the same predecessor. GCC sometimes
434 // generates code that looks like this:
436 // bb7: br bool %cond1004, label %bb8, label %bb8
437 // bb8: %reg119 = phi uint [ 0, %bb7 ], [ 1, %bb7 ]
439 // which is completely illegal LLVM code. To compensate for this, we insert
440 // an extra basic block, and convert the code to look like this:
442 // bb7: br bool %cond1004, label %bbX, label %bb8
444 // bb8: %reg119 = phi uint [ 0, %bbX ], [ 1, %bb7 ]
447 // 2. PHI nodes with fewer arguments than predecessors.
448 // These can be generated by GCC if a variable is uninitalized over a path
449 // in the CFG. We fix this by adding an entry for the missing predecessors
450 // that is initialized to either 42 for a numeric/FP value, or null if it's
451 // a pointer value. This problem can be generated by code that looks like
459 static bool fixLocalProblems(Method *M) {
460 bool Changed = false;
461 // Don't use iterators because invalidation gets messy...
462 for (unsigned MI = 0; MI < M->size(); ++MI) {
463 BasicBlock *BB = M->getBasicBlocks()[MI];
465 Changed |= FixCastsAndPHIs(BB);
467 if (isa<PHINode>(BB->front())) {
468 const vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
470 // Handle Problem #1. Sort the list of predecessors so that it is easy to
471 // decide whether or not duplicate predecessors exist.
472 vector<BasicBlock*> SortedPreds(Preds);
473 sort(SortedPreds.begin(), SortedPreds.end());
475 // Loop over the predecessors, looking for adjacent BB's that are equal.
476 BasicBlock *LastOne = 0;
477 for (unsigned i = 0; i < Preds.size(); ++i) {
478 if (SortedPreds[i] == LastOne) { // Found a duplicate.
479 RefactorPredecessor(BB, SortedPreds[i]);
482 LastOne = SortedPreds[i];
485 // Loop over all of the PHI nodes in the current BB. These PHI nodes are
486 // guaranteed to be at the beginning of the basic block.
488 for (BasicBlock::iterator I = BB->begin();
489 PHINode *PN = dyn_cast<PHINode>(*I); ++I) {
491 // Handle problem #2.
492 if (PN->getNumIncomingValues() != Preds.size()) {
493 assert(PN->getNumIncomingValues() <= Preds.size() &&
494 "Can't handle extra arguments to PHI nodes!");
495 for (unsigned i = 0; i < Preds.size(); ++i)
496 CheckIncomingValueFor(PN, Preds[i]);
508 // doPerMethodWork - This method simplifies the specified method hopefully.
510 bool CleanupGCCOutput::runOnMethod(Method *M) {
511 return fixLocalProblems(M);
514 bool CleanupGCCOutput::doFinalization(Module *M) {
515 bool Changed = false;
518 if (M->hasSymbolTable()) {
519 SymbolTable *ST = M->getSymbolTable();
520 const std::set<const Type *> &UsedTypes =
521 getAnalysis<FindUsedTypes>().getTypes();
523 // Check the symbol table for superfluous type entries that aren't used in
526 // Grab the 'type' plane of the module symbol...
527 SymbolTable::iterator STI = ST->find(Type::TypeTy);
528 if (STI != ST->end()) {
529 // Loop over all entries in the type plane...
530 SymbolTable::VarMap &Plane = STI->second;
531 for (SymbolTable::VarMap::iterator PI = Plane.begin(); PI != Plane.end();)
532 if (!UsedTypes.count(cast<Type>(PI->second))) {
533 #if MAP_IS_NOT_BRAINDEAD
534 PI = Plane.erase(PI); // STD C++ Map should support this!
536 Plane.erase(PI); // Alas, GCC 2.95.3 doesn't *SIGH*
537 PI = Plane.begin(); // N^2 algorithms are fun. :(
548 // getAnalysisUsageInfo - This function needs the results of the
549 // FindUsedTypes and FindUnsafePointerTypes analysis passes...
551 void CleanupGCCOutput::getAnalysisUsageInfo(Pass::AnalysisSet &Required,
552 Pass::AnalysisSet &Destroyed,
553 Pass::AnalysisSet &Provided) {
554 // FIXME: Invalidates the CFG
555 Required.push_back(FindUsedTypes::ID);