Eliminate static ctors due to Statistic objects
[oota-llvm.git] / lib / Transforms / IPO / FunctionResolution.cpp
1 //===- FunctionResolution.cpp - Resolve declarations to implementations ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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:
12 //
13 //    declare void %foo(...)
14 //    void %foo(int, int) { ... }
15 //
16 // because of the way things are declared in C.  If this is the case, patch
17 // things up.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #define DEBUG_TYPE "funcresolve"
22 #include "llvm/Transforms/IPO.h"
23 #include "llvm/Module.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Constants.h"
28 #include "llvm/Support/CallSite.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Assembly/Writer.h"
31 #include "llvm/ADT/Statistic.h"
32 #include <algorithm>
33 using namespace llvm;
34
35 STATISTIC(NumResolved, "Number of varargs functions resolved");
36 STATISTIC(NumGlobals, "Number of global variables resolved");
37
38 namespace {
39   struct FunctionResolvingPass : public ModulePass {
40     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
41       AU.addRequired<TargetData>();
42     }
43
44     bool runOnModule(Module &M);
45   };
46   RegisterPass<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
47 }
48
49 ModulePass *llvm::createFunctionResolvingPass() {
50   return new FunctionResolvingPass();
51 }
52
53 static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
54                              Function *Concrete) {
55   bool Changed = false;
56   for (unsigned i = 0; i != Globals.size(); ++i)
57     if (Globals[i] != Concrete) {
58       Function *Old = cast<Function>(Globals[i]);
59       const FunctionType *OldFT = Old->getFunctionType();
60       const FunctionType *ConcreteFT = Concrete->getFunctionType();
61
62       if (OldFT->getNumParams() > ConcreteFT->getNumParams() &&
63           !ConcreteFT->isVarArg())
64         if (!Old->use_empty()) {
65           cerr << "WARNING: Linking function '" << Old->getName()
66                << "' is causing arguments to be dropped.\n";
67           cerr << "WARNING: Prototype: ";
68           WriteAsOperand(*cerr.stream(), Old);
69           cerr << " resolved to ";
70           WriteAsOperand(*cerr.stream(), Concrete);
71           cerr << "\n";
72         }
73
74       // Check to make sure that if there are specified types, that they
75       // match...
76       //
77       unsigned NumArguments = std::min(OldFT->getNumParams(),
78                                        ConcreteFT->getNumParams());
79
80       if (!Old->use_empty() && !Concrete->use_empty())
81         for (unsigned i = 0; i < NumArguments; ++i)
82           if (OldFT->getParamType(i) != ConcreteFT->getParamType(i))
83             if (OldFT->getParamType(i)->getTypeID() !=
84                 ConcreteFT->getParamType(i)->getTypeID()) {
85               cerr << "WARNING: Function [" << Old->getName()
86                    << "]: Parameter types conflict for: '";
87               WriteTypeSymbolic(*cerr.stream(), OldFT, &M);
88               cerr << "' (in " 
89                    << Old->getParent()->getModuleIdentifier() << ") and '";
90               WriteTypeSymbolic(*cerr.stream(), ConcreteFT, &M);
91               cerr << "'(in " 
92                    << Concrete->getParent()->getModuleIdentifier() << ")\n";
93               return Changed;
94             }
95
96       // Attempt to convert all of the uses of the old function to the concrete
97       // form of the function.  If there is a use of the fn that we don't
98       // understand here we punt to avoid making a bad transformation.
99       //
100       // At this point, we know that the return values are the same for our two
101       // functions and that the Old function has no varargs fns specified.  In
102       // otherwords it's just <retty> (...)
103       //
104       if (!Old->use_empty()) {
105         Value *Replacement = Concrete;
106         if (Concrete->getType() != Old->getType())
107           Replacement = ConstantExpr::getBitCast(Concrete, Old->getType());
108         NumResolved += Old->getNumUses();
109         Old->replaceAllUsesWith(Replacement);
110       }
111
112       // Since there are no uses of Old anymore, remove it from the module.
113       M.getFunctionList().erase(Old);
114     }
115   return Changed;
116 }
117
118
119 static bool ResolveGlobalVariables(Module &M,
120                                    std::vector<GlobalValue*> &Globals,
121                                    GlobalVariable *Concrete) {
122   bool Changed = false;
123
124   for (unsigned i = 0; i != Globals.size(); ++i)
125     if (Globals[i] != Concrete) {
126       Constant *Cast = ConstantExpr::getBitCast(Concrete,Globals[i]->getType());
127       Globals[i]->replaceAllUsesWith(Cast);
128
129       // Since there are no uses of Old anymore, remove it from the module.
130       M.getGlobalList().erase(cast<GlobalVariable>(Globals[i]));
131
132       ++NumGlobals;
133       Changed = true;
134     }
135   return Changed;
136 }
137
138 // Check to see if all of the callers of F ignore the return value.
139 static bool CallersAllIgnoreReturnValue(Function &F) {
140   if (F.getReturnType() == Type::VoidTy) return true;
141   for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
142     if (GlobalValue *GV = dyn_cast<GlobalValue>(*I)) {
143       for (Value::use_iterator I = GV->use_begin(), E = GV->use_end();
144            I != E; ++I) {
145         CallSite CS = CallSite::get(*I);
146         if (!CS.getInstruction() || !CS.getInstruction()->use_empty())
147           return false;
148       }
149     } else {
150       CallSite CS = CallSite::get(*I);
151       if (!CS.getInstruction() || !CS.getInstruction()->use_empty())
152         return false;
153     }
154   }
155   return true;
156 }
157
158 static bool ProcessGlobalsWithSameName(Module &M, TargetData &TD,
159                                        std::vector<GlobalValue*> &Globals) {
160   assert(!Globals.empty() && "Globals list shouldn't be empty here!");
161
162   bool isFunction = isa<Function>(Globals[0]);   // Is this group all functions?
163   GlobalValue *Concrete = 0;  // The most concrete implementation to resolve to
164
165   for (unsigned i = 0; i != Globals.size(); ) {
166     if (isa<Function>(Globals[i]) != isFunction) {
167       cerr << "WARNING: Found function and global variable with the "
168            << "same name: '" << Globals[i]->getName() << "'.\n";
169       return false;                 // Don't know how to handle this, bail out!
170     }
171
172     if (isFunction) {
173       // For functions, we look to merge functions definitions of "int (...)"
174       // to 'int (int)' or 'int ()' or whatever else is not completely generic.
175       //
176       Function *F = cast<Function>(Globals[i]);
177       if (!F->isExternal()) {
178         if (Concrete && !Concrete->isExternal())
179           return false;   // Found two different functions types.  Can't choose!
180
181         Concrete = Globals[i];
182       } else if (Concrete) {
183         if (Concrete->isExternal()) // If we have multiple external symbols...
184           if (F->getFunctionType()->getNumParams() >
185               cast<Function>(Concrete)->getFunctionType()->getNumParams())
186             Concrete = F;  // We are more concrete than "Concrete"!
187
188       } else {
189         Concrete = F;
190       }
191     } else {
192       GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
193       if (!GV->isExternal()) {
194         if (Concrete) {
195           cerr << "WARNING: Two global variables with external linkage"
196                << " exist with the same name: '" << GV->getName()
197                << "'!\n";
198           return false;
199         }
200         Concrete = GV;
201       }
202     }
203     ++i;
204   }
205
206   if (Globals.size() > 1) {         // Found a multiply defined global...
207     // If there are no external declarations, and there is at most one
208     // externally visible instance of the global, then there is nothing to do.
209     //
210     bool HasExternal = false;
211     unsigned NumInstancesWithExternalLinkage = 0;
212
213     for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
214       if (Globals[i]->isExternal())
215         HasExternal = true;
216       else if (!Globals[i]->hasInternalLinkage())
217         NumInstancesWithExternalLinkage++;
218     }
219
220     if (!HasExternal && NumInstancesWithExternalLinkage <= 1)
221       return false;  // Nothing to do?  Must have multiple internal definitions.
222
223     // There are a couple of special cases we don't want to print the warning
224     // for, check them now.
225     bool DontPrintWarning = false;
226     if (Concrete && Globals.size() == 2) {
227       GlobalValue *Other = Globals[Globals[0] == Concrete];
228       // If the non-concrete global is a function which takes (...) arguments,
229       // and the return values match (or was never used), do not warn.
230       if (Function *ConcreteF = dyn_cast<Function>(Concrete))
231         if (Function *OtherF = dyn_cast<Function>(Other))
232           if ((ConcreteF->getReturnType() == OtherF->getReturnType() ||
233                CallersAllIgnoreReturnValue(*OtherF)) &&
234               OtherF->getFunctionType()->isVarArg() &&
235               OtherF->getFunctionType()->getNumParams() == 0)
236             DontPrintWarning = true;
237
238       // Otherwise, if the non-concrete global is a global array variable with a
239       // size of 0, and the concrete global is an array with a real size, don't
240       // warn.  This occurs due to declaring 'extern int A[];'.
241       if (GlobalVariable *ConcreteGV = dyn_cast<GlobalVariable>(Concrete))
242         if (GlobalVariable *OtherGV = dyn_cast<GlobalVariable>(Other)) {
243           const Type *CTy = ConcreteGV->getType();
244           const Type *OTy = OtherGV->getType();
245
246           if (CTy->isSized())
247             if (!OTy->isSized() || !TD.getTypeSize(OTy) ||
248                 TD.getTypeSize(OTy) == TD.getTypeSize(CTy))
249               DontPrintWarning = true;
250         }
251     }
252
253     if (0 && !DontPrintWarning) {
254       cerr << "WARNING: Found global types that are not compatible:\n";
255       for (unsigned i = 0; i < Globals.size(); ++i) {
256         cerr << "\t";
257         WriteTypeSymbolic(*cerr.stream(), Globals[i]->getType(), &M);
258         cerr << " %" << Globals[i]->getName() << "\n";
259       }
260     }
261
262     if (!Concrete)
263       Concrete = Globals[0];
264     else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Concrete)) {
265       // Handle special case hack to change globals if it will make their types
266       // happier in the long run.  The situation we do this is intentionally
267       // extremely limited.
268       if (GV->use_empty() && GV->hasInitializer() &&
269           GV->getInitializer()->isNullValue()) {
270         // Check to see if there is another (external) global with the same size
271         // and a non-empty use-list.  If so, we will make IT be the real
272         // implementation.
273         unsigned TS = TD.getTypeSize(Concrete->getType()->getElementType());
274         for (unsigned i = 0, e = Globals.size(); i != e; ++i)
275           if (Globals[i] != Concrete && !Globals[i]->use_empty() &&
276               isa<GlobalVariable>(Globals[i]) &&
277               TD.getTypeSize(Globals[i]->getType()->getElementType()) == TS) {
278             // At this point we want to replace Concrete with Globals[i].  Make
279             // concrete external, and Globals[i] have an initializer.
280             GlobalVariable *NGV = cast<GlobalVariable>(Globals[i]);
281             const Type *ElTy = NGV->getType()->getElementType();
282             NGV->setInitializer(Constant::getNullValue(ElTy));
283             cast<GlobalVariable>(Concrete)->setInitializer(0);
284             Concrete = NGV;
285             break;
286           }
287       }
288     }
289
290     if (isFunction)
291       return ResolveFunctions(M, Globals, cast<Function>(Concrete));
292     else
293       return ResolveGlobalVariables(M, Globals,
294                                     cast<GlobalVariable>(Concrete));
295   }
296   return false;
297 }
298
299 bool FunctionResolvingPass::runOnModule(Module &M) {
300   std::map<std::string, std::vector<GlobalValue*> > Globals;
301
302   // Loop over the globals, adding them to the Globals map.  We use a two pass
303   // algorithm here to avoid problems with iterators getting invalidated if we
304   // did a one pass scheme.
305   //
306   bool Changed = false;
307   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
308     Function *F = I++;
309     if (F->use_empty() && F->isExternal()) {
310       M.getFunctionList().erase(F);
311       Changed = true;
312     } else if (!F->hasInternalLinkage() && !F->getName().empty() &&
313                !F->getIntrinsicID())
314       Globals[F->getName()].push_back(F);
315   }
316
317   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
318        I != E; ) {
319     GlobalVariable *GV = I++;
320     if (GV->use_empty() && GV->isExternal()) {
321       M.getGlobalList().erase(GV);
322       Changed = true;
323     } else if (!GV->hasInternalLinkage() && !GV->getName().empty())
324       Globals[GV->getName()].push_back(GV);
325   }
326
327   TargetData &TD = getAnalysis<TargetData>();
328
329   // Now we have a list of all functions with a particular name.  If there is
330   // more than one entry in a list, merge the functions together.
331   //
332   for (std::map<std::string, std::vector<GlobalValue*> >::iterator
333          I = Globals.begin(), E = Globals.end(); I != E; ++I)
334     Changed |= ProcessGlobalsWithSameName(M, TD, I->second);
335
336   // Now loop over all of the globals, checking to see if any are trivially
337   // dead.  If so, remove them now.
338
339   for (Module::iterator I = M.begin(), E = M.end(); I != E; )
340     if (I->isExternal() && I->use_empty()) {
341       Function *F = I;
342       ++I;
343       M.getFunctionList().erase(F);
344       ++NumResolved;
345       Changed = true;
346     } else {
347       ++I;
348     }
349
350   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
351        I != E; )
352     if (I->isExternal() && I->use_empty()) {
353       GlobalVariable *GV = I;
354       ++I;
355       M.getGlobalList().erase(GV);
356       ++NumGlobals;
357       Changed = true;
358     } else {
359       ++I;
360     }
361
362   return Changed;
363 }