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 "Support/Statistic.h"
29 Statistic<>NumResolved("funcresolve", "Number of varargs functions resolved");
30 Statistic<> NumGlobals("funcresolve", "Number of global variables resolved");
32 struct FunctionResolvingPass : public Pass {
35 RegisterOpt<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
38 Pass *createFunctionResolvingPass() {
39 return new FunctionResolvingPass();
42 // ConvertCallTo - Convert a call to a varargs function with no arg types
43 // specified to a concrete nonvarargs function.
45 static void ConvertCallTo(CallInst *CI, Function *Dest) {
46 const FunctionType::ParamTypes &ParamTys =
47 Dest->getFunctionType()->getParamTypes();
48 BasicBlock *BB = CI->getParent();
50 // Keep an iterator to where we want to insert cast instructions if the
51 // argument types don't agree.
53 BasicBlock::iterator BBI = CI;
54 assert(CI->getNumOperands()-1 == ParamTys.size() &&
55 "Function calls resolved funny somehow, incompatible number of args");
57 vector<Value*> Params;
59 // Convert all of the call arguments over... inserting cast instructions if
60 // the types are not compatible.
61 for (unsigned i = 1; i < CI->getNumOperands(); ++i) {
62 Value *V = CI->getOperand(i);
64 if (V->getType() != ParamTys[i-1]) // Must insert a cast...
65 V = new CastInst(V, ParamTys[i-1], "argcast", BBI);
70 // Replace the old call instruction with a new call instruction that calls
73 Instruction *NewCall = new CallInst(Dest, Params, "", BBI);
75 // Remove the old call instruction from the program...
76 BB->getInstList().remove(BBI);
78 // Transfer the name over...
79 if (NewCall->getType() != Type::VoidTy)
80 NewCall->setName(CI->getName());
82 // Replace uses of the old instruction with the appropriate values...
84 if (NewCall->getType() == CI->getType()) {
85 CI->replaceAllUsesWith(NewCall);
86 NewCall->setName(CI->getName());
88 } else if (NewCall->getType() == Type::VoidTy) {
89 // Resolved function does not return a value but the prototype does. This
90 // often occurs because undefined functions default to returning integers.
91 // Just replace uses of the call (which are broken anyway) with dummy
93 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
94 } else if (CI->getType() == Type::VoidTy) {
95 // If we are gaining a new return value, we don't have to do anything
96 // special here, because it will automatically be ignored.
98 // Insert a cast instruction to convert the return value of the function
99 // into it's new type. Of course we only need to do this if the return
100 // value of the function is actually USED.
102 if (!CI->use_empty()) {
103 // Insert the new cast instruction...
104 CastInst *NewCast = new CastInst(NewCall, CI->getType(),
105 NewCall->getName(), BBI);
106 CI->replaceAllUsesWith(NewCast);
110 // The old instruction is no longer needed, destroy it!
115 static bool ResolveFunctions(Module &M, vector<GlobalValue*> &Globals,
116 Function *Concrete) {
117 bool Changed = false;
118 for (unsigned i = 0; i != Globals.size(); ++i)
119 if (Globals[i] != Concrete) {
120 Function *Old = cast<Function>(Globals[i]);
121 const FunctionType *OldMT = Old->getFunctionType();
122 const FunctionType *ConcreteMT = Concrete->getFunctionType();
124 assert(OldMT->getParamTypes().size() <=
125 ConcreteMT->getParamTypes().size() &&
126 "Concrete type must have more specified parameters!");
128 // Check to make sure that if there are specified types, that they
131 for (unsigned i = 0; i < OldMT->getParamTypes().size(); ++i)
132 if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {
133 cerr << "Parameter types conflict for" << OldMT
134 << " and " << ConcreteMT;
138 // Attempt to convert all of the uses of the old function to the
139 // concrete form of the function. If there is a use of the fn that
140 // we don't understand here we punt to avoid making a bad
143 // At this point, we know that the return values are the same for
144 // our two functions and that the Old function has no varargs fns
145 // specified. In otherwords it's just <retty> (...)
147 for (unsigned i = 0; i < Old->use_size(); ) {
148 User *U = *(Old->use_begin()+i);
149 if (CastInst *CI = dyn_cast<CastInst>(U)) {
150 // Convert casts directly
151 assert(CI->getOperand(0) == Old);
152 CI->setOperand(0, Concrete);
155 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
156 // Can only fix up calls TO the argument, not args passed in.
157 if (CI->getCalledValue() == Old) {
158 ConvertCallTo(CI, Concrete);
162 cerr << "Couldn't cleanup this function call, must be an"
163 << " argument or something!" << CI;
167 cerr << "Cannot convert use of function: " << U << "\n";
176 static bool ResolveGlobalVariables(Module &M, vector<GlobalValue*> &Globals,
177 GlobalVariable *Concrete) {
178 bool Changed = false;
179 assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&
180 "Concrete version should be an array type!");
182 // Get the type of the things that may be resolved to us...
184 cast<ArrayType>(Concrete->getType()->getElementType())->getElementType();
186 std::vector<Constant*> Args;
187 Args.push_back(Constant::getNullValue(Type::LongTy));
188 Args.push_back(Constant::getNullValue(Type::LongTy));
189 ConstantExpr *Replacement =
190 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(Concrete), Args);
192 for (unsigned i = 0; i != Globals.size(); ++i)
193 if (Globals[i] != Concrete) {
194 GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);
195 if (Old->getType()->getElementType() != AETy) {
196 std::cerr << "WARNING: Two global variables exist with the same name "
197 << "that cannot be resolved!\n";
201 // In this case, Old is a pointer to T, Concrete is a pointer to array of
202 // T. Because of this, replace all uses of Old with a constantexpr
203 // getelementptr that returns the address of the first element of the
206 Old->replaceAllUsesWith(Replacement);
207 // Since there are no uses of Old anymore, remove it from the module.
208 M.getGlobalList().erase(Old);
216 static bool ProcessGlobalsWithSameName(Module &M,
217 vector<GlobalValue*> &Globals) {
218 assert(!Globals.empty() && "Globals list shouldn't be empty here!");
220 bool isFunction = isa<Function>(Globals[0]); // Is this group all functions?
221 bool Changed = false;
222 GlobalValue *Concrete = 0; // The most concrete implementation to resolve to
224 assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&
225 "Should either be function or gvar!");
227 for (unsigned i = 0; i != Globals.size(); ) {
228 if (isa<Function>(Globals[i]) != isFunction) {
229 std::cerr << "WARNING: Found function and global variable with the "
230 << "same name: '" << Globals[i]->getName() << "'.\n";
231 return false; // Don't know how to handle this, bail out!
234 // Ignore globals that are never used so they don't cause spurious
235 // warnings... here we will actually DCE the function so that it isn't used
238 if (Globals[i]->isExternal() && Globals[i]->use_empty()) {
240 M.getFunctionList().erase(cast<Function>(Globals[i]));
243 M.getGlobalList().erase(cast<GlobalVariable>(Globals[i]));
247 Globals.erase(Globals.begin()+i);
249 } else if (isFunction) {
250 // For functions, we look to merge functions definitions of "int (...)"
251 // to 'int (int)' or 'int ()' or whatever else is not completely generic.
253 Function *F = cast<Function>(Globals[i]);
254 if (!F->getFunctionType()->isVarArg() ||
255 F->getFunctionType()->getNumParams()) {
257 return false; // Found two different functions types. Can't choose!
259 Concrete = Globals[i];
263 // For global variables, we have to merge C definitions int A[][4] with
265 GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
267 if (isa<ArrayType>(GV->getType()->getElementType()))
269 } else { // Must have different types... one is an array of the other?
270 const ArrayType *AT =
271 dyn_cast<ArrayType>(GV->getType()->getElementType());
273 // If GV is an array of Concrete, then GV is the array.
274 if (AT && AT->getElementType() == Concrete->getType()->getElementType())
277 // Concrete must be an array type, check to see if the element type of
278 // concrete is already GV.
279 AT = cast<ArrayType>(Concrete->getType()->getElementType());
280 if (AT->getElementType() != GV->getType()->getElementType())
281 Concrete = 0; // Don't know how to handle it!
289 if (Globals.size() > 1) { // Found a multiply defined global...
290 // We should find exactly one concrete function definition, which is
291 // probably the implementation. Change all of the function definitions and
292 // uses to use it instead.
295 cerr << "WARNING: Found function types that are not compatible:\n";
296 for (unsigned i = 0; i < Globals.size(); ++i) {
297 cerr << "\t" << Globals[i]->getType()->getDescription() << " %"
298 << Globals[i]->getName() << "\n";
300 cerr << " No linkage of globals named '" << Globals[0]->getName()
306 return Changed | ResolveFunctions(M, Globals, cast<Function>(Concrete));
308 return Changed | ResolveGlobalVariables(M, Globals,
309 cast<GlobalVariable>(Concrete));
314 bool FunctionResolvingPass::run(Module &M) {
315 SymbolTable *ST = M.getSymbolTable();
316 if (!ST) return false;
318 std::map<string, vector<GlobalValue*> > Globals;
320 // Loop over the entries in the symbol table. If an entry is a func pointer,
321 // then add it to the Functions map. We do a two pass algorithm here to avoid
322 // problems with iterators getting invalidated if we did a one pass scheme.
324 for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I)
325 if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {
326 SymbolTable::VarMap &Plane = I->second;
327 for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
329 GlobalValue *GV = cast<GlobalValue>(PI->second);
330 assert(PI->first == GV->getName() &&
331 "Global name and symbol table do not agree!");
332 if (GV->hasExternalLinkage()) // Only resolve decls to external fns
333 Globals[PI->first].push_back(GV);
337 bool Changed = false;
339 // Now we have a list of all functions with a particular name. If there is
340 // more than one entry in a list, merge the functions together.
342 for (std::map<string, vector<GlobalValue*> >::iterator I = Globals.begin(),
343 E = Globals.end(); I != E; ++I)
344 Changed |= ProcessGlobalsWithSameName(M, I->second);