1 //===- FunctionResolution.cpp - Resolve declarations to implementations ---===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Loop over the functions that are in the module and look for functions that
11 // have the same name. More often than not, there will be things like:
13 // declare void %foo(...)
14 // void %foo(int, int) { ... }
16 // because of the way things are declared in C. If this is the case, patch
19 //===----------------------------------------------------------------------===//
21 #include "llvm/Transforms/IPO.h"
22 #include "llvm/Module.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Constants.h"
27 #include "llvm/Support/CallSite.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Assembly/Writer.h"
30 #include "llvm/ADT/Statistic.h"
35 Statistic NumResolved("funcresolve", "Number of varargs functions resolved");
36 Statistic NumGlobals("funcresolve", "Number of global variables resolved");
38 struct FunctionResolvingPass : public ModulePass {
39 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
40 AU.addRequired<TargetData>();
43 bool runOnModule(Module &M);
45 RegisterPass<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
48 ModulePass *llvm::createFunctionResolvingPass() {
49 return new FunctionResolvingPass();
52 static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
55 for (unsigned i = 0; i != Globals.size(); ++i)
56 if (Globals[i] != Concrete) {
57 Function *Old = cast<Function>(Globals[i]);
58 const FunctionType *OldFT = Old->getFunctionType();
59 const FunctionType *ConcreteFT = Concrete->getFunctionType();
61 if (OldFT->getNumParams() > ConcreteFT->getNumParams() &&
62 !ConcreteFT->isVarArg())
63 if (!Old->use_empty()) {
64 cerr << "WARNING: Linking function '" << Old->getName()
65 << "' is causing arguments to be dropped.\n";
66 cerr << "WARNING: Prototype: ";
67 WriteAsOperand(*cerr.stream(), Old);
68 cerr << " resolved to ";
69 WriteAsOperand(*cerr.stream(), Concrete);
73 // Check to make sure that if there are specified types, that they
76 unsigned NumArguments = std::min(OldFT->getNumParams(),
77 ConcreteFT->getNumParams());
79 if (!Old->use_empty() && !Concrete->use_empty())
80 for (unsigned i = 0; i < NumArguments; ++i)
81 if (OldFT->getParamType(i) != ConcreteFT->getParamType(i))
82 if (OldFT->getParamType(i)->getTypeID() !=
83 ConcreteFT->getParamType(i)->getTypeID()) {
84 cerr << "WARNING: Function [" << Old->getName()
85 << "]: Parameter types conflict for: '";
86 WriteTypeSymbolic(*cerr.stream(), OldFT, &M);
88 << Old->getParent()->getModuleIdentifier() << ") and '";
89 WriteTypeSymbolic(*cerr.stream(), ConcreteFT, &M);
91 << Concrete->getParent()->getModuleIdentifier() << ")\n";
95 // Attempt to convert all of the uses of the old function to the concrete
96 // form of the function. If there is a use of the fn that we don't
97 // understand here we punt to avoid making a bad transformation.
99 // At this point, we know that the return values are the same for our two
100 // functions and that the Old function has no varargs fns specified. In
101 // otherwords it's just <retty> (...)
103 if (!Old->use_empty()) {
104 Value *Replacement = Concrete;
105 if (Concrete->getType() != Old->getType())
106 Replacement = ConstantExpr::getCast(Concrete, Old->getType());
107 NumResolved += Old->getNumUses();
108 Old->replaceAllUsesWith(Replacement);
111 // Since there are no uses of Old anymore, remove it from the module.
112 M.getFunctionList().erase(Old);
118 static bool ResolveGlobalVariables(Module &M,
119 std::vector<GlobalValue*> &Globals,
120 GlobalVariable *Concrete) {
121 bool Changed = false;
123 for (unsigned i = 0; i != Globals.size(); ++i)
124 if (Globals[i] != Concrete) {
125 Constant *Cast = ConstantExpr::getCast(Concrete, Globals[i]->getType());
126 Globals[i]->replaceAllUsesWith(Cast);
128 // Since there are no uses of Old anymore, remove it from the module.
129 M.getGlobalList().erase(cast<GlobalVariable>(Globals[i]));
137 // Check to see if all of the callers of F ignore the return value.
138 static bool CallersAllIgnoreReturnValue(Function &F) {
139 if (F.getReturnType() == Type::VoidTy) return true;
140 for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
141 if (GlobalValue *GV = dyn_cast<GlobalValue>(*I)) {
142 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end();
144 CallSite CS = CallSite::get(*I);
145 if (!CS.getInstruction() || !CS.getInstruction()->use_empty())
149 CallSite CS = CallSite::get(*I);
150 if (!CS.getInstruction() || !CS.getInstruction()->use_empty())
157 static bool ProcessGlobalsWithSameName(Module &M, TargetData &TD,
158 std::vector<GlobalValue*> &Globals) {
159 assert(!Globals.empty() && "Globals list shouldn't be empty here!");
161 bool isFunction = isa<Function>(Globals[0]); // Is this group all functions?
162 GlobalValue *Concrete = 0; // The most concrete implementation to resolve to
164 for (unsigned i = 0; i != Globals.size(); ) {
165 if (isa<Function>(Globals[i]) != isFunction) {
166 cerr << "WARNING: Found function and global variable with the "
167 << "same name: '" << Globals[i]->getName() << "'.\n";
168 return false; // Don't know how to handle this, bail out!
172 // For functions, we look to merge functions definitions of "int (...)"
173 // to 'int (int)' or 'int ()' or whatever else is not completely generic.
175 Function *F = cast<Function>(Globals[i]);
176 if (!F->isExternal()) {
177 if (Concrete && !Concrete->isExternal())
178 return false; // Found two different functions types. Can't choose!
180 Concrete = Globals[i];
181 } else if (Concrete) {
182 if (Concrete->isExternal()) // If we have multiple external symbols...
183 if (F->getFunctionType()->getNumParams() >
184 cast<Function>(Concrete)->getFunctionType()->getNumParams())
185 Concrete = F; // We are more concrete than "Concrete"!
191 GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
192 if (!GV->isExternal()) {
194 cerr << "WARNING: Two global variables with external linkage"
195 << " exist with the same name: '" << GV->getName()
205 if (Globals.size() > 1) { // Found a multiply defined global...
206 // If there are no external declarations, and there is at most one
207 // externally visible instance of the global, then there is nothing to do.
209 bool HasExternal = false;
210 unsigned NumInstancesWithExternalLinkage = 0;
212 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
213 if (Globals[i]->isExternal())
215 else if (!Globals[i]->hasInternalLinkage())
216 NumInstancesWithExternalLinkage++;
219 if (!HasExternal && NumInstancesWithExternalLinkage <= 1)
220 return false; // Nothing to do? Must have multiple internal definitions.
222 // There are a couple of special cases we don't want to print the warning
223 // for, check them now.
224 bool DontPrintWarning = false;
225 if (Concrete && Globals.size() == 2) {
226 GlobalValue *Other = Globals[Globals[0] == Concrete];
227 // If the non-concrete global is a function which takes (...) arguments,
228 // and the return values match (or was never used), do not warn.
229 if (Function *ConcreteF = dyn_cast<Function>(Concrete))
230 if (Function *OtherF = dyn_cast<Function>(Other))
231 if ((ConcreteF->getReturnType() == OtherF->getReturnType() ||
232 CallersAllIgnoreReturnValue(*OtherF)) &&
233 OtherF->getFunctionType()->isVarArg() &&
234 OtherF->getFunctionType()->getNumParams() == 0)
235 DontPrintWarning = true;
237 // Otherwise, if the non-concrete global is a global array variable with a
238 // size of 0, and the concrete global is an array with a real size, don't
239 // warn. This occurs due to declaring 'extern int A[];'.
240 if (GlobalVariable *ConcreteGV = dyn_cast<GlobalVariable>(Concrete))
241 if (GlobalVariable *OtherGV = dyn_cast<GlobalVariable>(Other)) {
242 const Type *CTy = ConcreteGV->getType();
243 const Type *OTy = OtherGV->getType();
246 if (!OTy->isSized() || !TD.getTypeSize(OTy) ||
247 TD.getTypeSize(OTy) == TD.getTypeSize(CTy))
248 DontPrintWarning = true;
252 if (0 && !DontPrintWarning) {
253 cerr << "WARNING: Found global types that are not compatible:\n";
254 for (unsigned i = 0; i < Globals.size(); ++i) {
256 WriteTypeSymbolic(*cerr.stream(), Globals[i]->getType(), &M);
257 cerr << " %" << Globals[i]->getName() << "\n";
262 Concrete = Globals[0];
263 else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Concrete)) {
264 // Handle special case hack to change globals if it will make their types
265 // happier in the long run. The situation we do this is intentionally
266 // extremely limited.
267 if (GV->use_empty() && GV->hasInitializer() &&
268 GV->getInitializer()->isNullValue()) {
269 // Check to see if there is another (external) global with the same size
270 // and a non-empty use-list. If so, we will make IT be the real
272 unsigned TS = TD.getTypeSize(Concrete->getType()->getElementType());
273 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
274 if (Globals[i] != Concrete && !Globals[i]->use_empty() &&
275 isa<GlobalVariable>(Globals[i]) &&
276 TD.getTypeSize(Globals[i]->getType()->getElementType()) == TS) {
277 // At this point we want to replace Concrete with Globals[i]. Make
278 // concrete external, and Globals[i] have an initializer.
279 GlobalVariable *NGV = cast<GlobalVariable>(Globals[i]);
280 const Type *ElTy = NGV->getType()->getElementType();
281 NGV->setInitializer(Constant::getNullValue(ElTy));
282 cast<GlobalVariable>(Concrete)->setInitializer(0);
290 return ResolveFunctions(M, Globals, cast<Function>(Concrete));
292 return ResolveGlobalVariables(M, Globals,
293 cast<GlobalVariable>(Concrete));
298 bool FunctionResolvingPass::runOnModule(Module &M) {
299 std::map<std::string, std::vector<GlobalValue*> > Globals;
301 // Loop over the globals, adding them to the Globals map. We use a two pass
302 // algorithm here to avoid problems with iterators getting invalidated if we
303 // did a one pass scheme.
305 bool Changed = false;
306 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
308 if (F->use_empty() && F->isExternal()) {
309 M.getFunctionList().erase(F);
311 } else if (!F->hasInternalLinkage() && !F->getName().empty() &&
312 !F->getIntrinsicID())
313 Globals[F->getName()].push_back(F);
316 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
318 GlobalVariable *GV = I++;
319 if (GV->use_empty() && GV->isExternal()) {
320 M.getGlobalList().erase(GV);
322 } else if (!GV->hasInternalLinkage() && !GV->getName().empty())
323 Globals[GV->getName()].push_back(GV);
326 TargetData &TD = getAnalysis<TargetData>();
328 // Now we have a list of all functions with a particular name. If there is
329 // more than one entry in a list, merge the functions together.
331 for (std::map<std::string, std::vector<GlobalValue*> >::iterator
332 I = Globals.begin(), E = Globals.end(); I != E; ++I)
333 Changed |= ProcessGlobalsWithSameName(M, TD, I->second);
335 // Now loop over all of the globals, checking to see if any are trivially
336 // dead. If so, remove them now.
338 for (Module::iterator I = M.begin(), E = M.end(); I != E; )
339 if (I->isExternal() && I->use_empty()) {
342 M.getFunctionList().erase(F);
349 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
351 if (I->isExternal() && I->use_empty()) {
352 GlobalVariable *GV = I;
354 M.getGlobalList().erase(GV);