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 "llvm/SymbolTable.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/iOther.h"
22 #include "llvm/iMemory.h"
26 static const Type *PtrArrSByte = 0; // '[sbyte]*' type
27 static const Type *PtrSByte = 0; // 'sbyte*' type
30 // ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
31 // with a value, then remove and delete the original instruction.
33 static void ReplaceInstWithValue(BasicBlock::InstListType &BIL,
34 BasicBlock::iterator &BI, Value *V) {
36 // Replaces all of the uses of the instruction with uses of the value
37 I->replaceAllUsesWith(V);
39 // Remove the unneccesary instruction now...
42 // Make sure to propogate a name if there is one already...
43 if (I->hasName() && !V->hasName())
44 V->setName(I->getName(), BIL.getParent()->getSymbolTable());
46 // Remove the dead instruction now...
51 // ReplaceInstWithInst - Replace the instruction specified by BI with the
52 // instruction specified by I. The original instruction is deleted and BI is
53 // updated to point to the new instruction.
55 static void ReplaceInstWithInst(BasicBlock::InstListType &BIL,
56 BasicBlock::iterator &BI, Instruction *I) {
57 assert(I->getParent() == 0 &&
58 "ReplaceInstWithInst: Instruction already inserted into basic block!");
60 // Insert the new instruction into the basic block...
61 BI = BIL.insert(BI, I)+1;
63 // Replace all uses of the old instruction, and delete it.
64 ReplaceInstWithValue(BIL, BI, I);
66 // Reexamine the instruction just inserted next time around the cleanup pass
73 // ConvertCallTo - Convert a call to a varargs function with no arg types
74 // specified to a concrete nonvarargs method.
76 static void ConvertCallTo(CallInst *CI, Method *Dest) {
77 const MethodType::ParamTypes &ParamTys =
78 Dest->getMethodType()->getParamTypes();
79 BasicBlock *BB = CI->getParent();
81 // Get an iterator to where we want to insert cast instructions if the
82 // argument types don't agree.
84 BasicBlock::iterator BBI = find(BB->begin(), BB->end(), CI);
85 assert(BBI != BB->end() && "CallInst not in parent block?");
87 assert(CI->getNumOperands()-1 == ParamTys.size()&&
88 "Method calls resolved funny somehow, incompatible number of args");
90 vector<Value*> Params;
92 // Convert all of the call arguments over... inserting cast instructions if
93 // the types are not compatible.
94 for (unsigned i = 1; i < CI->getNumOperands(); ++i) {
95 Value *V = CI->getOperand(i);
97 if (V->getType() != ParamTys[i-1]) { // Must insert a cast...
98 Instruction *Cast = new CastInst(V, ParamTys[i-1]);
99 BBI = BB->getInstList().insert(BBI, Cast)+1;
106 // Replace the old call instruction with a new call instruction that calls
109 ReplaceInstWithInst(BB->getInstList(), BBI, new CallInst(Dest, Params));
113 // PatchUpMethodReferences - Go over the methods that are in the module and
114 // look for methods that have the same name. More often than not, there will
117 // void "foo"(int, int)
118 // because of the way things are declared in C. If this is the case, patch
121 static bool PatchUpMethodReferences(SymbolTable *ST) {
122 map<string, vector<Method*> > Methods;
124 // Loop over the entries in the symbol table. If an entry is a method pointer,
125 // then add it to the Methods map. We do a two pass algorithm here to avoid
126 // problems with iterators getting invalidated if we did a one pass scheme.
128 for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I)
129 if (const PointerType *PT = dyn_cast<PointerType>(I->first))
130 if (const MethodType *MT = dyn_cast<MethodType>(PT->getValueType())) {
131 SymbolTable::VarMap &Plane = I->second;
132 for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
134 const string &Name = PI->first;
135 Method *M = cast<Method>(PI->second);
136 Methods[Name].push_back(M);
140 bool Changed = false;
142 // Now we have a list of all methods with a particular name. If there is more
143 // than one entry in a list, merge the methods together.
145 for (map<string, vector<Method*> >::iterator I = Methods.begin(),
146 E = Methods.end(); I != E; ++I) {
147 vector<Method*> &Methods = I->second;
148 if (Methods.size() > 1) { // Found a multiply defined method.
149 Method *Implementation = 0; // Find the implementation
150 Method *Concrete = 0;
151 for (unsigned i = 0; i < Methods.size(); ++i) {
152 if (!Methods[i]->isExternal()) { // Found an implementation
153 assert(Implementation == 0 && "Multiple definitions of the same"
154 " method. Case not handled yet!");
155 Implementation = Methods[i];
158 if (!Methods[i]->getMethodType()->isVarArg() ||
159 Methods[i]->getMethodType()->getParamTypes().size()) {
160 if (Concrete) { // Found two different methods types. Can't choose
164 Concrete = Methods[i];
168 // We should find exactly one non-vararg method definition, which is
169 // probably the implementation. Change all of the method definitions
170 // and uses to use it instead.
173 cerr << "Warning: Found methods types that are not compatible:\n";
174 for (unsigned i = 0; i < Methods.size(); ++i) {
175 cerr << "\t" << Methods[i]->getType()->getDescription() << " %"
176 << Methods[i]->getName() << endl;
178 cerr << " No linkage of methods named '" << Methods[0]->getName()
181 for (unsigned i = 0; i < Methods.size(); ++i)
182 if (Methods[i] != Concrete) {
183 Method *Old = Methods[i];
184 assert(Old->getReturnType() == Concrete->getReturnType() &&
185 "Differing return types not handled yet!");
186 assert(Old->getMethodType()->getParamTypes().size() == 0 &&
187 "Cannot handle varargs fn's with specified element types!");
189 // Attempt to convert all of the uses of the old method to the
190 // concrete form of the method. If there is a use of the method
191 // that we don't understand here we punt to avoid making a bad
194 // At this point, we know that the return values are the same for
195 // our two functions and that the Old method has no varargs methods
196 // specified. In otherwords it's just <retty> (...)
198 for (unsigned i = 0; i < Old->use_size(); ) {
199 User *U = *(Old->use_begin()+i);
200 if (CastInst *CI = dyn_cast<CastInst>(U)) {
201 // Convert casts directly
202 assert(CI->getOperand(0) == Old);
203 CI->setOperand(0, Concrete);
205 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
206 // Can only fix up calls TO the argument, not args passed in.
207 if (CI->getCalledValue() == Old) {
208 ConvertCallTo(CI, Concrete);
211 cerr << "Couldn't cleanup this function call, must be an"
212 << " argument or something!" << CI;
216 cerr << "Cannot convert use of method: " << U << endl;
229 // ShouldNukSymtabEntry - Return true if this module level symbol table entry
230 // should be eliminated.
232 static inline bool ShouldNukeSymtabEntry(const pair<string, Value*> &E) {
233 // Nuke all names for primitive types!
234 if (cast<Type>(E.second)->isPrimitiveType()) return true;
236 // The only types that could contain .'s in the program are things generated
237 // by GCC itself, including "complex.float" and friends. Nuke them too.
238 if (E.first.find('.') != string::npos) return true;
243 // doPassInitialization - For this pass, it removes global symbol table
244 // entries for primitive types. These are never used for linking in GCC and
245 // they make the output uglier to look at, so we nuke them.
247 bool CleanupGCCOutput::doPassInitialization(Module *M) {
248 bool Changed = false;
250 if (PtrArrSByte == 0) {
251 PtrArrSByte = PointerType::get(ArrayType::get(Type::SByteTy));
252 PtrSByte = PointerType::get(Type::SByteTy);
255 if (M->hasSymbolTable()) {
256 SymbolTable *ST = M->getSymbolTable();
258 // Go over the methods that are in the module and look for methods that have
259 // the same name. More often than not, there will be things like:
260 // void "foo"(...) and void "foo"(int, int) because of the way things are
261 // declared in C. If this is the case, patch things up.
263 Changed |= PatchUpMethodReferences(ST);
266 // If the module has a symbol table, they might be referring to the malloc
267 // and free functions. If this is the case, grab the method pointers that
268 // the module is using.
270 // Lookup %malloc and %free in the symbol table, for later use. If they
271 // don't exist, or are not external, we do not worry about converting calls
272 // to that function into the appropriate instruction.
274 const PointerType *MallocType = // Get the type for malloc
275 PointerType::get(MethodType::get(PointerType::get(Type::SByteTy),
276 vector<const Type*>(1, Type::UIntTy), false));
277 Malloc = cast_or_null<Method>(ST->lookup(MallocType, "malloc"));
278 if (Malloc && !Malloc->isExternal())
279 Malloc = 0; // Don't mess with locally defined versions of the fn
281 const PointerType *FreeType = // Get the type for free
282 PointerType::get(MethodType::get(Type::VoidTy,
283 vector<const Type*>(1, PointerType::get(Type::SByteTy)), false));
284 Free = cast_or_null<Method>(ST->lookup(FreeType, "free"));
285 if (Free && !Free->isExternal())
286 Free = 0; // Don't mess with locally defined versions of the fn
289 // Check the symbol table for superfluous type entries...
291 // Grab the 'type' plane of the module symbol...
292 SymbolTable::iterator STI = ST->find(Type::TypeTy);
293 if (STI != ST->end()) {
294 // Loop over all entries in the type plane...
295 SymbolTable::VarMap &Plane = STI->second;
296 for (SymbolTable::VarMap::iterator PI = Plane.begin(); PI != Plane.end();)
297 if (ShouldNukeSymtabEntry(*PI)) { // Should we remove this entry?
298 #if MAP_IS_NOT_BRAINDEAD
299 PI = Plane.erase(PI); // STD C++ Map should support this!
301 Plane.erase(PI); // Alas, GCC 2.95.3 doesn't *SIGH*
315 // doOneCleanupPass - Do one pass over the input method, fixing stuff up.
317 bool CleanupGCCOutput::doOneCleanupPass(Method *M) {
318 bool Changed = false;
319 for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
320 BasicBlock *BB = *MI;
321 BasicBlock::InstListType &BIL = BB->getInstList();
323 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
324 Instruction *I = *BI;
326 if (CallInst *CI = dyn_cast<CallInst>(I)) {
327 if (CI->getCalledValue() == Malloc) { // Replace call to malloc?
328 MallocInst *MallocI = new MallocInst(PtrArrSByte, CI->getOperand(1),
331 BI = BIL.insert(BI, MallocI)+1;
332 ReplaceInstWithInst(BIL, BI, new CastInst(MallocI, PtrSByte));
334 continue; // Skip the ++BI
335 } else if (CI->getCalledValue() == Free) { // Replace call to free?
336 ReplaceInstWithInst(BIL, BI, new FreeInst(CI->getOperand(1)));
338 continue; // Skip the ++BI
352 // doPerMethodWork - This method simplifies the specified method hopefully.
354 bool CleanupGCCOutput::doPerMethodWork(Method *M) {
355 bool Changed = false;
356 while (doOneCleanupPass(M)) Changed = true;