8361930e94437f6504edcada7213887eab6b6caa
[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 #include "llvm/Transforms/IPO.h"
22 #include "llvm/Module.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Pass.h"
25 #include "llvm/iOther.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 "Support/Statistic.h"
31 #include <algorithm>
32 using namespace llvm;
33
34 namespace {
35   Statistic<>NumResolved("funcresolve", "Number of varargs functions resolved");
36   Statistic<> NumGlobals("funcresolve", "Number of global variables resolved");
37
38   struct FunctionResolvingPass : public Pass {
39     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
40       AU.addRequired<TargetData>();
41     }
42
43     bool run(Module &M);
44   };
45   RegisterOpt<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
46 }
47
48 Pass *llvm::createFunctionResolvingPass() {
49   return new FunctionResolvingPass();
50 }
51
52 static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
53                              Function *Concrete) {
54   bool Changed = false;
55   for (unsigned i = 0; i != Globals.size(); ++i)
56     if (Globals[i] != Concrete) {
57       Function *Old = cast<Function>(Globals[i]);
58       const FunctionType *OldMT = Old->getFunctionType();
59       const FunctionType *ConcreteMT = Concrete->getFunctionType();
60       
61       if (OldMT->getParamTypes().size() > ConcreteMT->getParamTypes().size() &&
62           !ConcreteMT->isVarArg())
63         if (!Old->use_empty()) {
64           std::cerr << "WARNING: Linking function '" << Old->getName()
65                     << "' is causing arguments to be dropped.\n";
66           std::cerr << "WARNING: Prototype: ";
67           WriteAsOperand(std::cerr, Old);
68           std::cerr << " resolved to ";
69           WriteAsOperand(std::cerr, Concrete);
70           std::cerr << "\n";
71         }
72       
73       // Check to make sure that if there are specified types, that they
74       // match...
75       //
76       unsigned NumArguments = std::min(OldMT->getParamTypes().size(),
77                                        ConcreteMT->getParamTypes().size());
78
79       if (!Old->use_empty() && !Concrete->use_empty())
80         for (unsigned i = 0; i < NumArguments; ++i)
81           if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i])
82             if (OldMT->getParamTypes()[i]->getPrimitiveID() != 
83                 ConcreteMT->getParamTypes()[i]->getPrimitiveID()) {
84               std::cerr << "WARNING: Function [" << Old->getName()
85                         << "]: Parameter types conflict for: '";
86               WriteTypeSymbolic(std::cerr, OldMT, &M);
87               std::cerr << "' and '";
88               WriteTypeSymbolic(std::cerr, ConcreteMT, &M);
89               std::cerr << "'\n";
90               return Changed;
91             }
92       
93       // Attempt to convert all of the uses of the old function to the concrete
94       // form of the function.  If there is a use of the fn that we don't
95       // understand here we punt to avoid making a bad transformation.
96       //
97       // At this point, we know that the return values are the same for our two
98       // functions and that the Old function has no varargs fns specified.  In
99       // otherwords it's just <retty> (...)
100       //
101       if (!Old->use_empty()) {  // Avoid making the CPR unless we really need it
102         Value *Replacement = Concrete;
103         if (Concrete->getType() != Old->getType())
104           Replacement = ConstantExpr::getCast(ConstantPointerRef::get(Concrete),
105                                               Old->getType());
106         NumResolved += Old->use_size();
107         Old->replaceAllUsesWith(Replacement);
108       }
109
110       // Since there are no uses of Old anymore, remove it from the module.
111       M.getFunctionList().erase(Old);
112     }
113   return Changed;
114 }
115
116
117 static bool ResolveGlobalVariables(Module &M,
118                                    std::vector<GlobalValue*> &Globals,
119                                    GlobalVariable *Concrete) {
120   bool Changed = false;
121   Constant *CCPR = ConstantPointerRef::get(Concrete);
122
123   for (unsigned i = 0; i != Globals.size(); ++i)
124     if (Globals[i] != Concrete) {
125       Constant *Cast = ConstantExpr::getCast(CCPR, Globals[i]->getType());
126       Globals[i]->replaceAllUsesWith(Cast);
127
128       // Since there are no uses of Old anymore, remove it from the module.
129       M.getGlobalList().erase(cast<GlobalVariable>(Globals[i]));
130
131       ++NumGlobals;
132       Changed = true;
133     }
134   return Changed;
135 }
136
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 (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(*I)) {
142       for (Value::use_iterator I = CPR->use_begin(), E = CPR->use_end();
143            I != E; ++I) {
144         CallSite CS = CallSite::get(*I);
145         if (!CS.getInstruction() || !CS.getInstruction()->use_empty())
146           return false;
147       }
148     } else {
149       CallSite CS = CallSite::get(*I);
150       if (!CS.getInstruction() || !CS.getInstruction()->use_empty())
151         return false;
152     }
153   }
154   return true;
155 }
156
157 static bool ProcessGlobalsWithSameName(Module &M, TargetData &TD,
158                                        std::vector<GlobalValue*> &Globals) {
159   assert(!Globals.empty() && "Globals list shouldn't be empty here!");
160
161   bool isFunction = isa<Function>(Globals[0]);   // Is this group all functions?
162   GlobalValue *Concrete = 0;  // The most concrete implementation to resolve to
163
164   for (unsigned i = 0; i != Globals.size(); ) {
165     if (isa<Function>(Globals[i]) != isFunction) {
166       std::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!
169     }
170
171     if (isFunction) {
172       // For functions, we look to merge functions definitions of "int (...)"
173       // to 'int (int)' or 'int ()' or whatever else is not completely generic.
174       //
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!
179         
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"!
186
187       } else {
188         Concrete = F;
189       }
190     } else {
191       GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
192       if (!GV->isExternal()) {
193         if (Concrete) {
194           std::cerr << "WARNING: Two global variables with external linkage"
195                     << " exist with the same name: '" << GV->getName()
196                     << "'!\n";
197           return false;
198         }
199         Concrete = GV;
200       }
201     }
202     ++i;
203   }
204
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.
208     //
209     bool HasExternal = false;
210     unsigned NumInstancesWithExternalLinkage = 0;
211
212     for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
213       if (Globals[i]->isExternal())
214         HasExternal = true;
215       else if (!Globals[i]->hasInternalLinkage())
216         NumInstancesWithExternalLinkage++;
217     }
218     
219     if (!HasExternal && NumInstancesWithExternalLinkage <= 1)
220       return false;  // Nothing to do?  Must have multiple internal definitions.
221
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()->getParamTypes().empty())
235             DontPrintWarning = true;
236       
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           if (const ArrayType *OtherAT =
243               dyn_cast<ArrayType>(OtherGV->getType()->getElementType()))
244             if (const ArrayType *ConcreteAT =
245                 dyn_cast<ArrayType>(ConcreteGV->getType()->getElementType()))
246               if (OtherAT->getElementType() == ConcreteAT->getElementType() &&
247                   OtherAT->getNumElements() == 0)
248                 DontPrintWarning = true;
249     }
250
251     if (!DontPrintWarning) {
252       std::cerr << "WARNING: Found global types that are not compatible:\n";
253       for (unsigned i = 0; i < Globals.size(); ++i) {
254         std::cerr << "\t";
255         WriteTypeSymbolic(std::cerr, Globals[i]->getType(), &M);
256         std::cerr << " %" << Globals[i]->getName() << "\n";
257       }
258     }
259
260     if (!Concrete)
261       Concrete = Globals[0];
262     else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Concrete)) {
263       // Handle special case hack to change globals if it will make their types
264       // happier in the long run.  The situation we do this is intentionally
265       // extremely limited.
266       if (GV->use_empty() && GV->hasInitializer() &&
267           GV->getInitializer()->isNullValue()) {
268         // Check to see if there is another (external) global with the same size
269         // and a non-empty use-list.  If so, we will make IT be the real
270         // implementation.
271         unsigned TS = TD.getTypeSize(Concrete->getType()->getElementType());
272         for (unsigned i = 0, e = Globals.size(); i != e; ++i)
273           if (Globals[i] != Concrete && !Globals[i]->use_empty() &&
274               isa<GlobalVariable>(Globals[i]) &&
275               TD.getTypeSize(Globals[i]->getType()->getElementType()) == TS) {
276             // At this point we want to replace Concrete with Globals[i].  Make
277             // concrete external, and Globals[i] have an initializer.
278             GlobalVariable *NGV = cast<GlobalVariable>(Globals[i]);
279             const Type *ElTy = NGV->getType()->getElementType();
280             NGV->setInitializer(Constant::getNullValue(ElTy));
281             cast<GlobalVariable>(Concrete)->setInitializer(0);
282             Concrete = NGV;
283             break;
284           }
285       }
286     }
287
288     if (isFunction)
289       return ResolveFunctions(M, Globals, cast<Function>(Concrete));
290     else
291       return ResolveGlobalVariables(M, Globals,
292                                     cast<GlobalVariable>(Concrete));
293   }
294   return false;
295 }
296
297 bool FunctionResolvingPass::run(Module &M) {
298   std::map<std::string, std::vector<GlobalValue*> > Globals;
299
300   // Loop over the globals, adding them to the Globals map.  We use a two pass
301   // algorithm here to avoid problems with iterators getting invalidated if we
302   // did a one pass scheme.
303   //
304   bool Changed = false;
305   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
306     Function *F = I++;
307     if (F->use_empty() && F->isExternal()) {
308       M.getFunctionList().erase(F);
309       Changed = true;
310     } else if (!F->hasInternalLinkage() && !F->getName().empty())
311       Globals[F->getName()].push_back(F);
312   }
313
314   for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ) {
315     GlobalVariable *GV = I++;
316     if (GV->use_empty() && GV->isExternal()) {
317       M.getGlobalList().erase(GV);
318       Changed = true;
319     } else if (!GV->hasInternalLinkage() && !GV->getName().empty())
320       Globals[GV->getName()].push_back(GV);
321   }
322
323   TargetData &TD = getAnalysis<TargetData>();
324
325   // Now we have a list of all functions with a particular name.  If there is
326   // more than one entry in a list, merge the functions together.
327   //
328   for (std::map<std::string, std::vector<GlobalValue*> >::iterator
329          I = Globals.begin(), E = Globals.end(); I != E; ++I)
330     Changed |= ProcessGlobalsWithSameName(M, TD, I->second);
331
332   // Now loop over all of the globals, checking to see if any are trivially
333   // dead.  If so, remove them now.
334
335   for (Module::iterator I = M.begin(), E = M.end(); I != E; )
336     if (I->isExternal() && I->use_empty()) {
337       Function *F = I;
338       ++I;
339       M.getFunctionList().erase(F);
340       ++NumResolved;
341       Changed = true;
342     } else {
343       ++I;
344     }
345
346   for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
347     if (I->isExternal() && I->use_empty()) {
348       GlobalVariable *GV = I;
349       ++I;
350       M.getGlobalList().erase(GV);
351       ++NumGlobals;
352       Changed = true;
353     } else {
354       ++I;
355     }
356
357   return Changed;
358 }