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 bool CleanupGCCOutput::PatchUpMethodReferences(Module *M) {
122 SymbolTable *ST = M->getSymbolTable();
123 if (!ST) return false;
125 map<string, vector<Method*> > Methods;
127 // Loop over the entries in the symbol table. If an entry is a method pointer,
128 // then add it to the Methods map. We do a two pass algorithm here to avoid
129 // problems with iterators getting invalidated if we did a one pass scheme.
131 for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I)
132 if (const PointerType *PT = dyn_cast<PointerType>(I->first))
133 if (const MethodType *MT = dyn_cast<MethodType>(PT->getValueType())) {
134 SymbolTable::VarMap &Plane = I->second;
135 for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
137 const string &Name = PI->first;
138 Method *M = cast<Method>(PI->second);
139 Methods[Name].push_back(M);
143 bool Changed = false;
145 // Now we have a list of all methods with a particular name. If there is more
146 // than one entry in a list, merge the methods together.
148 for (map<string, vector<Method*> >::iterator I = Methods.begin(),
149 E = Methods.end(); I != E; ++I) {
150 vector<Method*> &Methods = I->second;
151 if (Methods.size() > 1) { // Found a multiply defined method.
152 Method *Implementation = 0; // Find the implementation
153 Method *Concrete = 0;
154 for (unsigned i = 0; i < Methods.size(); ++i) {
155 // TODO: Ignore methods that are never USED! DCE them.
156 // Remove their name. this should fix a majority of problems here.
158 if (!Methods[i]->isExternal()) { // Found an implementation
159 assert(Implementation == 0 && "Multiple definitions of the same"
160 " method. Case not handled yet!");
161 Implementation = Methods[i];
164 if (!Methods[i]->getMethodType()->isVarArg() ||
165 Methods[i]->getMethodType()->getParamTypes().size()) {
166 if (Concrete) { // Found two different methods types. Can't choose
170 Concrete = Methods[i];
174 // We should find exactly one non-vararg method definition, which is
175 // probably the implementation. Change all of the method definitions
176 // and uses to use it instead.
179 cerr << "Warning: Found methods types that are not compatible:\n";
180 for (unsigned i = 0; i < Methods.size(); ++i) {
181 cerr << "\t" << Methods[i]->getType()->getDescription() << " %"
182 << Methods[i]->getName() << endl;
184 cerr << " No linkage of methods named '" << Methods[0]->getName()
187 for (unsigned i = 0; i < Methods.size(); ++i)
188 if (Methods[i] != Concrete) {
189 Method *Old = Methods[i];
190 assert(Old->getReturnType() == Concrete->getReturnType() &&
191 "Differing return types not handled yet!");
192 assert(Old->getMethodType()->getParamTypes().size() == 0 &&
193 "Cannot handle varargs fn's with specified element types!");
195 // Attempt to convert all of the uses of the old method to the
196 // concrete form of the method. If there is a use of the method
197 // that we don't understand here we punt to avoid making a bad
200 // At this point, we know that the return values are the same for
201 // our two functions and that the Old method has no varargs methods
202 // specified. In otherwords it's just <retty> (...)
204 for (unsigned i = 0; i < Old->use_size(); ) {
205 User *U = *(Old->use_begin()+i);
206 if (CastInst *CI = dyn_cast<CastInst>(U)) {
207 // Convert casts directly
208 assert(CI->getOperand(0) == Old);
209 CI->setOperand(0, Concrete);
211 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
212 // Can only fix up calls TO the argument, not args passed in.
213 if (CI->getCalledValue() == Old) {
214 ConvertCallTo(CI, Concrete);
217 cerr << "Couldn't cleanup this function call, must be an"
218 << " argument or something!" << CI;
222 cerr << "Cannot convert use of method: " << U << endl;
235 // ShouldNukSymtabEntry - Return true if this module level symbol table entry
236 // should be eliminated.
238 static inline bool ShouldNukeSymtabEntry(const pair<string, Value*> &E) {
239 // Nuke all names for primitive types!
240 if (cast<Type>(E.second)->isPrimitiveType()) return true;
242 // The only types that could contain .'s in the program are things generated
243 // by GCC itself, including "complex.float" and friends. Nuke them too.
244 if (E.first.find('.') != string::npos) return true;
249 // doPassInitialization - For this pass, it removes global symbol table
250 // entries for primitive types. These are never used for linking in GCC and
251 // they make the output uglier to look at, so we nuke them.
253 bool CleanupGCCOutput::doPassInitialization(Module *M) {
254 bool Changed = false;
256 if (PtrArrSByte == 0) {
257 PtrArrSByte = PointerType::get(ArrayType::get(Type::SByteTy));
258 PtrSByte = PointerType::get(Type::SByteTy);
261 if (M->hasSymbolTable()) {
262 SymbolTable *ST = M->getSymbolTable();
264 // Go over the methods that are in the module and look for methods that have
265 // the same name. More often than not, there will be things like:
266 // void "foo"(...) and void "foo"(int, int) because of the way things are
267 // declared in C. If this is the case, patch things up.
269 Changed |= PatchUpMethodReferences(M);
272 // If the module has a symbol table, they might be referring to the malloc
273 // and free functions. If this is the case, grab the method pointers that
274 // the module is using.
276 // Lookup %malloc and %free in the symbol table, for later use. If they
277 // don't exist, or are not external, we do not worry about converting calls
278 // to that function into the appropriate instruction.
280 const PointerType *MallocType = // Get the type for malloc
281 PointerType::get(MethodType::get(PointerType::get(Type::SByteTy),
282 vector<const Type*>(1, Type::UIntTy), false));
283 Malloc = cast_or_null<Method>(ST->lookup(MallocType, "malloc"));
284 if (Malloc && !Malloc->isExternal())
285 Malloc = 0; // Don't mess with locally defined versions of the fn
287 const PointerType *FreeType = // Get the type for free
288 PointerType::get(MethodType::get(Type::VoidTy,
289 vector<const Type*>(1, PointerType::get(Type::SByteTy)), false));
290 Free = cast_or_null<Method>(ST->lookup(FreeType, "free"));
291 if (Free && !Free->isExternal())
292 Free = 0; // Don't mess with locally defined versions of the fn
295 // Check the symbol table for superfluous type entries...
297 // Grab the 'type' plane of the module symbol...
298 SymbolTable::iterator STI = ST->find(Type::TypeTy);
299 if (STI != ST->end()) {
300 // Loop over all entries in the type plane...
301 SymbolTable::VarMap &Plane = STI->second;
302 for (SymbolTable::VarMap::iterator PI = Plane.begin(); PI != Plane.end();)
303 if (ShouldNukeSymtabEntry(*PI)) { // Should we remove this entry?
304 #if MAP_IS_NOT_BRAINDEAD
305 PI = Plane.erase(PI); // STD C++ Map should support this!
307 Plane.erase(PI); // Alas, GCC 2.95.3 doesn't *SIGH*
321 // doOneCleanupPass - Do one pass over the input method, fixing stuff up.
323 bool CleanupGCCOutput::doOneCleanupPass(Method *M) {
324 bool Changed = false;
325 for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
326 BasicBlock *BB = *MI;
327 BasicBlock::InstListType &BIL = BB->getInstList();
329 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
330 Instruction *I = *BI;
332 if (CallInst *CI = dyn_cast<CallInst>(I)) {
333 if (CI->getCalledValue() == Malloc) { // Replace call to malloc?
334 MallocInst *MallocI = new MallocInst(PtrArrSByte, CI->getOperand(1),
337 BI = BIL.insert(BI, MallocI)+1;
338 ReplaceInstWithInst(BIL, BI, new CastInst(MallocI, PtrSByte));
340 continue; // Skip the ++BI
341 } else if (CI->getCalledValue() == Free) { // Replace call to free?
342 ReplaceInstWithInst(BIL, BI, new FreeInst(CI->getOperand(1)));
344 continue; // Skip the ++BI
357 // CheckIncomingValueFor - Make sure that the specified PHI node has an entry
358 // for the provided basic block. If it doesn't, add one and return true.
360 static inline bool CheckIncomingValueFor(PHINode *PN, BasicBlock *BB) {
361 unsigned NumArgs = PN->getNumIncomingValues();
362 for (unsigned i = 0; i < NumArgs; ++i)
363 if (PN->getIncomingBlock(i) == BB) return false; // Already has value
366 const Type *Ty = PN->getType();
367 if (const PointerType *PT = dyn_cast<PointerType>(Ty))
368 NewVal = ConstPoolPointerNull::get(PT);
369 else if (Ty == Type::BoolTy)
370 NewVal = ConstPoolBool::True;
371 else if (Ty == Type::FloatTy || Ty == Type::DoubleTy)
372 NewVal = ConstPoolFP::get(Ty, 42);
373 else if (Ty->isIntegral())
374 NewVal = ConstPoolInt::get(Ty, 42);
376 assert(NewVal && "Unknown PHI node type!");
377 PN->addIncoming(NewVal, BB);
381 // fixLocalProblems - Loop through the method and fix problems with the PHI
382 // nodes in the current method. The two problems that are handled are:
384 // 1. PHI nodes with multiple entries for the same predecessor.
386 // 2. PHI nodes with fewer arguments than predecessors.
387 // These can be generated by GCC if a variable is uninitalized over a path
388 // in the CFG. We fix this by adding an entry for the missing predecessors
389 // that is initialized to either 42 for a numeric/FP value, or null if it's
390 // a pointer value. This problem can be generated by code that looks like
398 static bool fixLocalProblems(Method *M) {
399 bool Changed = false;
400 // Don't use iterators because invalidation gets messy...
401 for (unsigned MI = 0; MI < M->size(); ++MI) {
402 BasicBlock *BB = M->getBasicBlocks()[MI];
404 if (isa<PHINode>(BB->front())) {
405 const vector<BasicBlock*> Preds(BB->pred_begin(), BB->pred_end());
407 // Loop over all of the PHI nodes in the current BB. These PHI nodes are
408 // guaranteed to be at the beginning of the basic block.
410 for (BasicBlock::iterator I = BB->begin();
411 PHINode *PN = dyn_cast<PHINode>(*I); ++I) {
413 // Handle problem #2.
414 if (PN->getNumIncomingValues() != Preds.size()) {
415 assert(PN->getNumIncomingValues() <= Preds.size() &&
416 "Can't handle extra arguments to PHI nodes!");
417 for (unsigned i = 0; i < Preds.size(); ++i)
418 Changed |= CheckIncomingValueFor(PN, Preds[i]);
429 // doPerMethodWork - This method simplifies the specified method hopefully.
431 bool CleanupGCCOutput::doPerMethodWork(Method *M) {
432 bool Changed = fixLocalProblems(M);
433 while (doOneCleanupPass(M)) Changed = true;