blob: 1b1065e3e926da092b31307e1cc9c094ae687b5a [file] [log] [blame]
Chris Lattner5aa9e3e2002-05-24 20:42:13 +00001//===- FunctionResolution.cpp - Resolve declarations to implementations ---===//
2//
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:
5//
6// declare void %foo(...)
7// void %foo(int, int) { ... }
8//
9// because of the way things are declared in C. If this is the case, patch
10// things up.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattner5afe2f22002-07-23 22:04:02 +000014#include "llvm/Transforms/IPO.h"
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000015#include "llvm/Module.h"
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000016#include "llvm/SymbolTable.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Pass.h"
19#include "llvm/iOther.h"
Chris Lattner013eca002002-10-09 21:10:06 +000020#include "llvm/Constants.h"
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +000021#include "llvm/Assembly/Writer.h" // FIXME: remove when varargs implemented
Chris Lattnerbf3a0992002-10-01 22:38:41 +000022#include "Support/Statistic.h"
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000023#include <algorithm>
24
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000025namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000026 Statistic<>NumResolved("funcresolve", "Number of varargs functions resolved");
Chris Lattner013eca002002-10-09 21:10:06 +000027 Statistic<> NumGlobals("funcresolve", "Number of global variables resolved");
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000028
29 struct FunctionResolvingPass : public Pass {
Chris Lattner113f4f42002-06-25 16:13:24 +000030 bool run(Module &M);
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000031 };
Chris Lattnera2c09852002-07-26 21:12:44 +000032 RegisterOpt<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000033}
34
35Pass *createFunctionResolvingPass() {
36 return new FunctionResolvingPass();
37}
38
39// ConvertCallTo - Convert a call to a varargs function with no arg types
40// specified to a concrete nonvarargs function.
41//
42static void ConvertCallTo(CallInst *CI, Function *Dest) {
43 const FunctionType::ParamTypes &ParamTys =
44 Dest->getFunctionType()->getParamTypes();
45 BasicBlock *BB = CI->getParent();
46
Chris Lattner113f4f42002-06-25 16:13:24 +000047 // Keep an iterator to where we want to insert cast instructions if the
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000048 // argument types don't agree.
49 //
Chris Lattner68f63f72003-01-30 22:38:44 +000050 unsigned NumArgsToCopy = CI->getNumOperands()-1;
Chris Lattner04c92742003-02-14 19:12:29 +000051 if (NumArgsToCopy != ParamTys.size() &&
52 !(NumArgsToCopy > ParamTys.size() &&
Chris Lattner68f63f72003-01-30 22:38:44 +000053 Dest->getFunctionType()->isVarArg())) {
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +000054 std::cerr << "WARNING: Call arguments do not match expected number of"
55 << " parameters.\n";
56 std::cerr << "WARNING: In function '"
57 << CI->getParent()->getParent()->getName() << "': call: " << *CI;
58 std::cerr << "Function resolved to: ";
59 WriteAsOperand(std::cerr, Dest);
60 std::cerr << "\n";
Chris Lattner04c92742003-02-14 19:12:29 +000061 if (NumArgsToCopy > ParamTys.size())
62 NumArgsToCopy = ParamTys.size();
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +000063 }
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000064
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +000065 std::vector<Value*> Params;
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000066
67 // Convert all of the call arguments over... inserting cast instructions if
68 // the types are not compatible.
Chris Lattner68f63f72003-01-30 22:38:44 +000069 for (unsigned i = 1; i <= NumArgsToCopy; ++i) {
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000070 Value *V = CI->getOperand(i);
71
Chris Lattner68f63f72003-01-30 22:38:44 +000072 if (i-1 < ParamTys.size() && V->getType() != ParamTys[i-1]) {
73 // Must insert a cast...
Chris Lattnerdbb05b02003-02-27 20:55:48 +000074 V = new CastInst(V, ParamTys[i-1], "argcast", CI);
Chris Lattner68f63f72003-01-30 22:38:44 +000075 }
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000076
77 Params.push_back(V);
78 }
79
80 // Replace the old call instruction with a new call instruction that calls
81 // the real function.
82 //
Chris Lattnerdbb05b02003-02-27 20:55:48 +000083 Instruction *NewCall = new CallInst(Dest, Params, "", CI);
84 std::string Name = CI->getName(); CI->setName("");
Chris Lattner1eb9e6c2002-05-24 21:33:26 +000085
Chris Lattneraacadd12002-07-30 00:50:49 +000086 // Transfer the name over...
Chris Lattnered378562002-07-30 02:42:49 +000087 if (NewCall->getType() != Type::VoidTy)
Chris Lattnerdbb05b02003-02-27 20:55:48 +000088 NewCall->setName(Name);
Chris Lattneraacadd12002-07-30 00:50:49 +000089
Chris Lattner1eb9e6c2002-05-24 21:33:26 +000090 // Replace uses of the old instruction with the appropriate values...
91 //
92 if (NewCall->getType() == CI->getType()) {
93 CI->replaceAllUsesWith(NewCall);
Chris Lattnerdbb05b02003-02-27 20:55:48 +000094 NewCall->setName(Name);
Chris Lattner1eb9e6c2002-05-24 21:33:26 +000095
96 } else if (NewCall->getType() == Type::VoidTy) {
97 // Resolved function does not return a value but the prototype does. This
98 // often occurs because undefined functions default to returning integers.
99 // Just replace uses of the call (which are broken anyway) with dummy
100 // values.
101 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
102 } else if (CI->getType() == Type::VoidTy) {
103 // If we are gaining a new return value, we don't have to do anything
Chris Lattneraacadd12002-07-30 00:50:49 +0000104 // special here, because it will automatically be ignored.
Chris Lattner1eb9e6c2002-05-24 21:33:26 +0000105 } else {
Chris Lattneraacadd12002-07-30 00:50:49 +0000106 // Insert a cast instruction to convert the return value of the function
107 // into it's new type. Of course we only need to do this if the return
108 // value of the function is actually USED.
109 //
110 if (!CI->use_empty()) {
Chris Lattneraacadd12002-07-30 00:50:49 +0000111 // Insert the new cast instruction...
Chris Lattnerdbb05b02003-02-27 20:55:48 +0000112 CastInst *NewCast = new CastInst(NewCall, CI->getType(), Name, CI);
Chris Lattner5c447862002-09-10 17:03:06 +0000113 CI->replaceAllUsesWith(NewCast);
Chris Lattneraacadd12002-07-30 00:50:49 +0000114 }
Chris Lattner1eb9e6c2002-05-24 21:33:26 +0000115 }
116
117 // The old instruction is no longer needed, destroy it!
Chris Lattnerdbb05b02003-02-27 20:55:48 +0000118 BB->getInstList().erase(CI);
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000119}
120
121
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000122static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
Chris Lattner013eca002002-10-09 21:10:06 +0000123 Function *Concrete) {
124 bool Changed = false;
125 for (unsigned i = 0; i != Globals.size(); ++i)
126 if (Globals[i] != Concrete) {
127 Function *Old = cast<Function>(Globals[i]);
128 const FunctionType *OldMT = Old->getFunctionType();
129 const FunctionType *ConcreteMT = Concrete->getFunctionType();
130
Chris Lattner9810b942003-04-28 01:23:29 +0000131 if (OldMT->getParamTypes().size() > ConcreteMT->getParamTypes().size() &&
Chris Lattner50cbb902003-03-03 19:57:46 +0000132 !ConcreteMT->isVarArg())
Chris Lattnerdbb05b02003-02-27 20:55:48 +0000133 if (!Old->use_empty()) {
134 std::cerr << "WARNING: Linking function '" << Old->getName()
135 << "' is causing arguments to be dropped.\n";
136 std::cerr << "WARNING: Prototype: ";
137 WriteAsOperand(std::cerr, Old);
138 std::cerr << " resolved to ";
139 WriteAsOperand(std::cerr, Concrete);
140 std::cerr << "\n";
141 }
Chris Lattner013eca002002-10-09 21:10:06 +0000142
143 // Check to make sure that if there are specified types, that they
144 // match...
145 //
Chris Lattnerdbb05b02003-02-27 20:55:48 +0000146 unsigned NumArguments = std::min(OldMT->getParamTypes().size(),
147 ConcreteMT->getParamTypes().size());
148
Chris Lattner50cbb902003-03-03 19:57:46 +0000149 if (!Old->use_empty() && !Concrete->use_empty())
150 for (unsigned i = 0; i < NumArguments; ++i)
151 if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {
152 std::cerr << "WARNING: Function [" << Old->getName()
153 << "]: Parameter types conflict for: '" << OldMT
154 << "' and '" << ConcreteMT << "'\n";
155 return Changed;
156 }
Chris Lattner013eca002002-10-09 21:10:06 +0000157
Chris Lattner9810b942003-04-28 01:23:29 +0000158 // Attempt to convert all of the uses of the old function to the concrete
159 // form of the function. If there is a use of the fn that we don't
160 // understand here we punt to avoid making a bad transformation.
Chris Lattner013eca002002-10-09 21:10:06 +0000161 //
Chris Lattner9810b942003-04-28 01:23:29 +0000162 // At this point, we know that the return values are the same for our two
163 // functions and that the Old function has no varargs fns specified. In
164 // otherwords it's just <retty> (...)
Chris Lattner013eca002002-10-09 21:10:06 +0000165 //
166 for (unsigned i = 0; i < Old->use_size(); ) {
167 User *U = *(Old->use_begin()+i);
168 if (CastInst *CI = dyn_cast<CastInst>(U)) {
169 // Convert casts directly
170 assert(CI->getOperand(0) == Old);
171 CI->setOperand(0, Concrete);
172 Changed = true;
173 ++NumResolved;
174 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
175 // Can only fix up calls TO the argument, not args passed in.
176 if (CI->getCalledValue() == Old) {
177 ConvertCallTo(CI, Concrete);
178 Changed = true;
179 ++NumResolved;
180 } else {
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000181 std::cerr << "Couldn't cleanup this function call, must be an"
182 << " argument or something!" << CI;
Chris Lattner013eca002002-10-09 21:10:06 +0000183 ++i;
184 }
Chris Lattner9810b942003-04-28 01:23:29 +0000185 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(U)) {
186 if (CPR->use_size() == 1 && isa<ConstantExpr>(CPR->use_back()) &&
187 cast<ConstantExpr>(CPR->use_back())->getOpcode() ==
188 Instruction::Cast) {
189 ConstantExpr *CE = cast<ConstantExpr>(CPR->use_back());
190 Constant *NewCPR = ConstantPointerRef::get(Concrete);
191 CE->replaceAllUsesWith(ConstantExpr::getCast(NewCPR,CE->getType()));
192 CPR->destroyConstant();
193 } else {
194 std::cerr << "Cannot convert use of function: " << CPR << "\n";
195 ++i;
196 }
Chris Lattner013eca002002-10-09 21:10:06 +0000197 } else {
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000198 std::cerr << "Cannot convert use of function: " << U << "\n";
Chris Lattner013eca002002-10-09 21:10:06 +0000199 ++i;
200 }
201 }
202 }
203 return Changed;
204}
205
206
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000207static bool ResolveGlobalVariables(Module &M,
208 std::vector<GlobalValue*> &Globals,
Chris Lattner013eca002002-10-09 21:10:06 +0000209 GlobalVariable *Concrete) {
210 bool Changed = false;
211 assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&
212 "Concrete version should be an array type!");
213
214 // Get the type of the things that may be resolved to us...
Chris Lattnerdefe5c72003-04-19 00:15:27 +0000215 const ArrayType *CATy =cast<ArrayType>(Concrete->getType()->getElementType());
216 const Type *AETy = CATy->getElementType();
Chris Lattner013eca002002-10-09 21:10:06 +0000217
Chris Lattnerdefe5c72003-04-19 00:15:27 +0000218 Constant *CCPR = ConstantPointerRef::get(Concrete);
219
Chris Lattner013eca002002-10-09 21:10:06 +0000220 for (unsigned i = 0; i != Globals.size(); ++i)
221 if (Globals[i] != Concrete) {
222 GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);
Chris Lattnerdefe5c72003-04-19 00:15:27 +0000223 const ArrayType *OATy = cast<ArrayType>(Old->getType()->getElementType());
224 if (OATy->getElementType() != AETy || OATy->getNumElements() != 0) {
Chris Lattner013eca002002-10-09 21:10:06 +0000225 std::cerr << "WARNING: Two global variables exist with the same name "
226 << "that cannot be resolved!\n";
227 return false;
228 }
229
Chris Lattnerdefe5c72003-04-19 00:15:27 +0000230 Old->replaceAllUsesWith(ConstantExpr::getCast(CCPR, Old->getType()));
231
Chris Lattner013eca002002-10-09 21:10:06 +0000232 // Since there are no uses of Old anymore, remove it from the module.
233 M.getGlobalList().erase(Old);
234
235 ++NumGlobals;
236 Changed = true;
237 }
238 return Changed;
239}
240
241static bool ProcessGlobalsWithSameName(Module &M,
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000242 std::vector<GlobalValue*> &Globals) {
Chris Lattner013eca002002-10-09 21:10:06 +0000243 assert(!Globals.empty() && "Globals list shouldn't be empty here!");
244
245 bool isFunction = isa<Function>(Globals[0]); // Is this group all functions?
Chris Lattner013eca002002-10-09 21:10:06 +0000246 GlobalValue *Concrete = 0; // The most concrete implementation to resolve to
247
248 assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&
249 "Should either be function or gvar!");
250
251 for (unsigned i = 0; i != Globals.size(); ) {
252 if (isa<Function>(Globals[i]) != isFunction) {
253 std::cerr << "WARNING: Found function and global variable with the "
254 << "same name: '" << Globals[i]->getName() << "'.\n";
255 return false; // Don't know how to handle this, bail out!
256 }
257
Chris Lattner52b8fc02002-11-10 03:36:55 +0000258 if (isFunction) {
Chris Lattner013eca002002-10-09 21:10:06 +0000259 // For functions, we look to merge functions definitions of "int (...)"
260 // to 'int (int)' or 'int ()' or whatever else is not completely generic.
261 //
262 Function *F = cast<Function>(Globals[i]);
Chris Lattner5997c3d2002-11-08 00:38:20 +0000263 if (!F->isExternal()) {
Chris Lattner52b8fc02002-11-10 03:36:55 +0000264 if (Concrete && !Concrete->isExternal())
Chris Lattner013eca002002-10-09 21:10:06 +0000265 return false; // Found two different functions types. Can't choose!
266
267 Concrete = Globals[i];
Chris Lattner52b8fc02002-11-10 03:36:55 +0000268 } else if (Concrete) {
269 if (Concrete->isExternal()) // If we have multiple external symbols...x
270 if (F->getFunctionType()->getNumParams() >
271 cast<Function>(Concrete)->getFunctionType()->getNumParams())
272 Concrete = F; // We are more concrete than "Concrete"!
273
274 } else {
275 Concrete = F;
Chris Lattner013eca002002-10-09 21:10:06 +0000276 }
Chris Lattner013eca002002-10-09 21:10:06 +0000277 } else {
278 // For global variables, we have to merge C definitions int A[][4] with
Chris Lattnerdefe5c72003-04-19 00:15:27 +0000279 // int[6][4]. A[][4] is represented as A[0][4] by the CFE.
Chris Lattner013eca002002-10-09 21:10:06 +0000280 GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
Chris Lattnerdefe5c72003-04-19 00:15:27 +0000281 if (!isa<ArrayType>(GV->getType()->getElementType())) {
282 Concrete = 0;
283 break; // Non array's cannot be compatible with other types.
284 } else if (Concrete == 0) {
285 Concrete = GV;
286 } else {
287 // Must have different types... allow merging A[0][4] w/ A[6][4] if
288 // A[0][4] is external.
289 const ArrayType *NAT = cast<ArrayType>(GV->getType()->getElementType());
290 const ArrayType *CAT =
291 cast<ArrayType>(Concrete->getType()->getElementType());
Chris Lattner013eca002002-10-09 21:10:06 +0000292
Chris Lattnerdefe5c72003-04-19 00:15:27 +0000293 if (NAT->getElementType() != CAT->getElementType()) {
294 Concrete = 0; // Non-compatible types
295 break;
296 } else if (NAT->getNumElements() == 0 && GV->isExternal()) {
297 // Concrete remains the same
298 } else if (CAT->getNumElements() == 0 && Concrete->isExternal()) {
299 Concrete = GV; // Concrete becomes GV
300 } else {
301 Concrete = 0; // Cannot merge these types...
302 break;
Chris Lattner013eca002002-10-09 21:10:06 +0000303 }
304 }
Chris Lattner013eca002002-10-09 21:10:06 +0000305 }
Chris Lattnerdefe5c72003-04-19 00:15:27 +0000306 ++i;
Chris Lattner013eca002002-10-09 21:10:06 +0000307 }
308
309 if (Globals.size() > 1) { // Found a multiply defined global...
310 // We should find exactly one concrete function definition, which is
311 // probably the implementation. Change all of the function definitions and
312 // uses to use it instead.
313 //
314 if (!Concrete) {
Chris Lattnerdefe5c72003-04-19 00:15:27 +0000315 std::cerr << "WARNING: Found global types that are not compatible:\n";
Chris Lattner013eca002002-10-09 21:10:06 +0000316 for (unsigned i = 0; i < Globals.size(); ++i) {
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000317 std::cerr << "\t" << Globals[i]->getType()->getDescription() << " %"
318 << Globals[i]->getName() << "\n";
Chris Lattner013eca002002-10-09 21:10:06 +0000319 }
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000320 std::cerr << " No linkage of globals named '" << Globals[0]->getName()
321 << "' performed!\n";
Chris Lattnerdefe5c72003-04-19 00:15:27 +0000322 return false;
Chris Lattner013eca002002-10-09 21:10:06 +0000323 }
324
325 if (isFunction)
Chris Lattnerdefe5c72003-04-19 00:15:27 +0000326 return ResolveFunctions(M, Globals, cast<Function>(Concrete));
Chris Lattner013eca002002-10-09 21:10:06 +0000327 else
Chris Lattnerdefe5c72003-04-19 00:15:27 +0000328 return ResolveGlobalVariables(M, Globals,
329 cast<GlobalVariable>(Concrete));
Chris Lattner013eca002002-10-09 21:10:06 +0000330 }
Chris Lattnerdefe5c72003-04-19 00:15:27 +0000331 return false;
Chris Lattner013eca002002-10-09 21:10:06 +0000332}
333
Chris Lattner113f4f42002-06-25 16:13:24 +0000334bool FunctionResolvingPass::run(Module &M) {
Chris Lattner98cf1f52002-11-20 18:36:02 +0000335 SymbolTable &ST = M.getSymbolTable();
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000336
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000337 std::map<std::string, std::vector<GlobalValue*> > Globals;
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000338
339 // Loop over the entries in the symbol table. If an entry is a func pointer,
340 // then add it to the Functions map. We do a two pass algorithm here to avoid
341 // problems with iterators getting invalidated if we did a one pass scheme.
342 //
Chris Lattner98cf1f52002-11-20 18:36:02 +0000343 for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
Chris Lattner013eca002002-10-09 21:10:06 +0000344 if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {
345 SymbolTable::VarMap &Plane = I->second;
346 for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
347 PI != PE; ++PI) {
348 GlobalValue *GV = cast<GlobalValue>(PI->second);
349 assert(PI->first == GV->getName() &&
350 "Global name and symbol table do not agree!");
Chris Lattner9810b942003-04-28 01:23:29 +0000351 if (!GV->hasInternalLinkage()) // Only resolve decls to external fns
Chris Lattner013eca002002-10-09 21:10:06 +0000352 Globals[PI->first].push_back(GV);
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000353 }
Chris Lattner013eca002002-10-09 21:10:06 +0000354 }
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000355
356 bool Changed = false;
357
358 // Now we have a list of all functions with a particular name. If there is
359 // more than one entry in a list, merge the functions together.
360 //
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000361 for (std::map<std::string, std::vector<GlobalValue*> >::iterator
362 I = Globals.begin(), E = Globals.end(); I != E; ++I)
Chris Lattner013eca002002-10-09 21:10:06 +0000363 Changed |= ProcessGlobalsWithSameName(M, I->second);
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000364
Chris Lattner52b8fc02002-11-10 03:36:55 +0000365 // Now loop over all of the globals, checking to see if any are trivially
366 // dead. If so, remove them now.
367
368 for (Module::iterator I = M.begin(), E = M.end(); I != E; )
369 if (I->isExternal() && I->use_empty()) {
370 Function *F = I;
371 ++I;
372 M.getFunctionList().erase(F);
373 ++NumResolved;
374 Changed = true;
375 } else {
376 ++I;
377 }
378
379 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
380 if (I->isExternal() && I->use_empty()) {
381 GlobalVariable *GV = I;
382 ++I;
383 M.getGlobalList().erase(GV);
384 ++NumGlobals;
385 Changed = true;
386 } else {
387 ++I;
388 }
389
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000390 return Changed;
391}