1 //===- FunctionResolution.cpp - Resolve declarations to implementations ---===//
3 // Loop over the functions that are in the module and look for functions that
4 // have the same name. More often than not, there will be things like:
6 // declare void %foo(...)
7 // void %foo(int, int) { ... }
9 // because of the way things are declared in C. If this is the case, patch
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/IPO.h"
15 #include "llvm/Module.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Pass.h"
19 #include "llvm/iOther.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Assembly/Writer.h" // FIXME: remove when varargs implemented
22 #include "Support/Statistic.h"
26 Statistic<>NumResolved("funcresolve", "Number of varargs functions resolved");
27 Statistic<> NumGlobals("funcresolve", "Number of global variables resolved");
29 struct FunctionResolvingPass : public Pass {
32 RegisterOpt<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
35 Pass *createFunctionResolvingPass() {
36 return new FunctionResolvingPass();
39 // ConvertCallTo - Convert a call to a varargs function with no arg types
40 // specified to a concrete nonvarargs function.
42 static void ConvertCallTo(CallInst *CI, Function *Dest) {
43 const FunctionType::ParamTypes &ParamTys =
44 Dest->getFunctionType()->getParamTypes();
45 BasicBlock *BB = CI->getParent();
47 // Keep an iterator to where we want to insert cast instructions if the
48 // argument types don't agree.
50 BasicBlock::iterator BBI = CI;
51 if (CI->getNumOperands()-1 != ParamTys.size()) {
52 std::cerr << "WARNING: Call arguments do not match expected number of"
54 std::cerr << "WARNING: In function '"
55 << CI->getParent()->getParent()->getName() << "': call: " << *CI;
56 std::cerr << "Function resolved to: ";
57 WriteAsOperand(std::cerr, Dest);
61 std::vector<Value*> Params;
63 // Convert all of the call arguments over... inserting cast instructions if
64 // the types are not compatible.
65 for (unsigned i = 1; i <= ParamTys.size(); ++i) {
66 Value *V = CI->getOperand(i);
68 if (V->getType() != ParamTys[i-1]) // Must insert a cast...
69 V = new CastInst(V, ParamTys[i-1], "argcast", BBI);
74 // Replace the old call instruction with a new call instruction that calls
77 Instruction *NewCall = new CallInst(Dest, Params, "", BBI);
79 // Remove the old call instruction from the program...
80 BB->getInstList().remove(BBI);
82 // Transfer the name over...
83 if (NewCall->getType() != Type::VoidTy)
84 NewCall->setName(CI->getName());
86 // Replace uses of the old instruction with the appropriate values...
88 if (NewCall->getType() == CI->getType()) {
89 CI->replaceAllUsesWith(NewCall);
90 NewCall->setName(CI->getName());
92 } else if (NewCall->getType() == Type::VoidTy) {
93 // Resolved function does not return a value but the prototype does. This
94 // often occurs because undefined functions default to returning integers.
95 // Just replace uses of the call (which are broken anyway) with dummy
97 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
98 } else if (CI->getType() == Type::VoidTy) {
99 // If we are gaining a new return value, we don't have to do anything
100 // special here, because it will automatically be ignored.
102 // Insert a cast instruction to convert the return value of the function
103 // into it's new type. Of course we only need to do this if the return
104 // value of the function is actually USED.
106 if (!CI->use_empty()) {
107 // Insert the new cast instruction...
108 CastInst *NewCast = new CastInst(NewCall, CI->getType(),
109 NewCall->getName(), BBI);
110 CI->replaceAllUsesWith(NewCast);
114 // The old instruction is no longer needed, destroy it!
119 static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
120 Function *Concrete) {
121 bool Changed = false;
122 for (unsigned i = 0; i != Globals.size(); ++i)
123 if (Globals[i] != Concrete) {
124 Function *Old = cast<Function>(Globals[i]);
125 const FunctionType *OldMT = Old->getFunctionType();
126 const FunctionType *ConcreteMT = Concrete->getFunctionType();
128 assert(OldMT->getParamTypes().size() <=
129 ConcreteMT->getParamTypes().size() &&
130 "Concrete type must have more specified parameters!");
132 // Check to make sure that if there are specified types, that they
135 for (unsigned i = 0; i < OldMT->getParamTypes().size(); ++i)
136 if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {
137 std::cerr << "funcresolve: Function [" << Old->getName()
138 << "]: Parameter types conflict for: '" << OldMT
139 << "' and '" << ConcreteMT << "'\n";
143 // Attempt to convert all of the uses of the old function to the
144 // concrete form of the function. If there is a use of the fn that
145 // we don't understand here we punt to avoid making a bad
148 // At this point, we know that the return values are the same for
149 // our two functions and that the Old function has no varargs fns
150 // specified. In otherwords it's just <retty> (...)
152 for (unsigned i = 0; i < Old->use_size(); ) {
153 User *U = *(Old->use_begin()+i);
154 if (CastInst *CI = dyn_cast<CastInst>(U)) {
155 // Convert casts directly
156 assert(CI->getOperand(0) == Old);
157 CI->setOperand(0, Concrete);
160 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
161 // Can only fix up calls TO the argument, not args passed in.
162 if (CI->getCalledValue() == Old) {
163 ConvertCallTo(CI, Concrete);
167 std::cerr << "Couldn't cleanup this function call, must be an"
168 << " argument or something!" << CI;
172 std::cerr << "Cannot convert use of function: " << U << "\n";
181 static bool ResolveGlobalVariables(Module &M,
182 std::vector<GlobalValue*> &Globals,
183 GlobalVariable *Concrete) {
184 bool Changed = false;
185 assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&
186 "Concrete version should be an array type!");
188 // Get the type of the things that may be resolved to us...
190 cast<ArrayType>(Concrete->getType()->getElementType())->getElementType();
192 std::vector<Constant*> Args;
193 Args.push_back(Constant::getNullValue(Type::LongTy));
194 Args.push_back(Constant::getNullValue(Type::LongTy));
195 ConstantExpr *Replacement =
196 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(Concrete), Args);
198 for (unsigned i = 0; i != Globals.size(); ++i)
199 if (Globals[i] != Concrete) {
200 GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);
201 if (Old->getType()->getElementType() != AETy) {
202 std::cerr << "WARNING: Two global variables exist with the same name "
203 << "that cannot be resolved!\n";
207 // In this case, Old is a pointer to T, Concrete is a pointer to array of
208 // T. Because of this, replace all uses of Old with a constantexpr
209 // getelementptr that returns the address of the first element of the
212 Old->replaceAllUsesWith(Replacement);
213 // Since there are no uses of Old anymore, remove it from the module.
214 M.getGlobalList().erase(Old);
222 static bool ProcessGlobalsWithSameName(Module &M,
223 std::vector<GlobalValue*> &Globals) {
224 assert(!Globals.empty() && "Globals list shouldn't be empty here!");
226 bool isFunction = isa<Function>(Globals[0]); // Is this group all functions?
227 bool Changed = false;
228 GlobalValue *Concrete = 0; // The most concrete implementation to resolve to
230 assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&
231 "Should either be function or gvar!");
233 for (unsigned i = 0; i != Globals.size(); ) {
234 if (isa<Function>(Globals[i]) != isFunction) {
235 std::cerr << "WARNING: Found function and global variable with the "
236 << "same name: '" << Globals[i]->getName() << "'.\n";
237 return false; // Don't know how to handle this, bail out!
241 // For functions, we look to merge functions definitions of "int (...)"
242 // to 'int (int)' or 'int ()' or whatever else is not completely generic.
244 Function *F = cast<Function>(Globals[i]);
245 if (!F->isExternal()) {
246 if (Concrete && !Concrete->isExternal())
247 return false; // Found two different functions types. Can't choose!
249 Concrete = Globals[i];
250 } else if (Concrete) {
251 if (Concrete->isExternal()) // If we have multiple external symbols...x
252 if (F->getFunctionType()->getNumParams() >
253 cast<Function>(Concrete)->getFunctionType()->getNumParams())
254 Concrete = F; // We are more concrete than "Concrete"!
261 // For global variables, we have to merge C definitions int A[][4] with
263 GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
265 if (isa<ArrayType>(GV->getType()->getElementType()))
267 } else { // Must have different types... one is an array of the other?
268 const ArrayType *AT =
269 dyn_cast<ArrayType>(GV->getType()->getElementType());
271 // If GV is an array of Concrete, then GV is the array.
272 if (AT && AT->getElementType() == Concrete->getType()->getElementType())
275 // Concrete must be an array type, check to see if the element type of
276 // concrete is already GV.
277 AT = cast<ArrayType>(Concrete->getType()->getElementType());
278 if (AT->getElementType() != GV->getType()->getElementType())
279 Concrete = 0; // Don't know how to handle it!
287 if (Globals.size() > 1) { // Found a multiply defined global...
288 // We should find exactly one concrete function definition, which is
289 // probably the implementation. Change all of the function definitions and
290 // uses to use it instead.
293 std::cerr << "WARNING: Found function types that are not compatible:\n";
294 for (unsigned i = 0; i < Globals.size(); ++i) {
295 std::cerr << "\t" << Globals[i]->getType()->getDescription() << " %"
296 << Globals[i]->getName() << "\n";
298 std::cerr << " No linkage of globals named '" << Globals[0]->getName()
304 return Changed | ResolveFunctions(M, Globals, cast<Function>(Concrete));
306 return Changed | ResolveGlobalVariables(M, Globals,
307 cast<GlobalVariable>(Concrete));
312 bool FunctionResolvingPass::run(Module &M) {
313 SymbolTable &ST = M.getSymbolTable();
315 std::map<std::string, std::vector<GlobalValue*> > Globals;
317 // Loop over the entries in the symbol table. If an entry is a func pointer,
318 // then add it to the Functions map. We do a two pass algorithm here to avoid
319 // problems with iterators getting invalidated if we did a one pass scheme.
321 for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
322 if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {
323 SymbolTable::VarMap &Plane = I->second;
324 for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
326 GlobalValue *GV = cast<GlobalValue>(PI->second);
327 assert(PI->first == GV->getName() &&
328 "Global name and symbol table do not agree!");
329 if (GV->hasExternalLinkage()) // Only resolve decls to external fns
330 Globals[PI->first].push_back(GV);
334 bool Changed = false;
336 // Now we have a list of all functions with a particular name. If there is
337 // more than one entry in a list, merge the functions together.
339 for (std::map<std::string, std::vector<GlobalValue*> >::iterator
340 I = Globals.begin(), E = Globals.end(); I != E; ++I)
341 Changed |= ProcessGlobalsWithSameName(M, I->second);
343 // Now loop over all of the globals, checking to see if any are trivially
344 // dead. If so, remove them now.
346 for (Module::iterator I = M.begin(), E = M.end(); I != E; )
347 if (I->isExternal() && I->use_empty()) {
350 M.getFunctionList().erase(F);
357 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
358 if (I->isExternal() && I->use_empty()) {
359 GlobalVariable *GV = I;
361 M.getGlobalList().erase(GV);