3dd3a80a15bc9723bbde8246abe31f386f1e61c8
[oota-llvm.git] / lib / Transforms / IPO / ExtractGV.cpp
1 //===-- ExtractGV.cpp - Global Value extraction pass ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass extracts global values
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Instructions.h"
15 #include "llvm/LLVMContext.h"
16 #include "llvm/Module.h"
17 #include "llvm/Pass.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Transforms/IPO.h"
20 #include "llvm/Support/Compiler.h"
21 #include <algorithm>
22 using namespace llvm;
23
24 namespace {
25   /// @brief A pass to extract specific functions and their dependencies.
26   class VISIBILITY_HIDDEN GVExtractorPass : public ModulePass {
27     std::vector<GlobalValue*> Named;
28     bool deleteStuff;
29     bool reLink;
30   public:
31     static char ID; // Pass identification, replacement for typeid
32
33     /// FunctionExtractorPass - If deleteFn is true, this pass deletes as the
34     /// specified function. Otherwise, it deletes as much of the module as
35     /// possible, except for the function specified.
36     ///
37     explicit GVExtractorPass(std::vector<GlobalValue*>& GVs, bool deleteS = true,
38                              bool relinkCallees = false)
39       : ModulePass(&ID), Named(GVs), deleteStuff(deleteS),
40         reLink(relinkCallees) {}
41
42     bool runOnModule(Module &M) {
43       if (Named.size() == 0) {
44         return false;  // Nothing to extract
45       }
46       
47       
48       if (deleteStuff)
49         return deleteGV();
50       M.setModuleInlineAsm("");
51       return isolateGV(M);
52     }
53
54     bool deleteGV() {
55       for (std::vector<GlobalValue*>::iterator GI = Named.begin(), 
56              GE = Named.end(); GI != GE; ++GI) {
57         if (Function* NamedFunc = dyn_cast<Function>(*GI)) {
58          // If we're in relinking mode, set linkage of all internal callees to
59          // external. This will allow us extract function, and then - link
60          // everything together
61          if (reLink) {
62            for (Function::iterator B = NamedFunc->begin(), BE = NamedFunc->end();
63                 B != BE; ++B) {
64              for (BasicBlock::iterator I = B->begin(), E = B->end();
65                   I != E; ++I) {
66                if (CallInst* callInst = dyn_cast<CallInst>(&*I)) {
67                  Function* Callee = callInst->getCalledFunction();
68                  if (Callee && Callee->hasLocalLinkage())
69                    Callee->setLinkage(GlobalValue::ExternalLinkage);
70                }
71              }
72            }
73          }
74          
75          NamedFunc->setLinkage(GlobalValue::ExternalLinkage);
76          NamedFunc->deleteBody();
77          assert(NamedFunc->isDeclaration() && "This didn't make the function external!");
78        } else {
79           if (!(*GI)->isDeclaration()) {
80             cast<GlobalVariable>(*GI)->setInitializer(0);  //clear the initializer
81             (*GI)->setLinkage(GlobalValue::ExternalLinkage);
82           }
83         }
84       }
85       return true;
86     }
87
88     bool isolateGV(Module &M) {
89       // Mark all globals internal
90       // FIXME: what should we do with private linkage?
91       for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
92         if (!I->isDeclaration()) {
93           I->setLinkage(GlobalValue::InternalLinkage);
94         }
95       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
96         if (!I->isDeclaration()) {
97           I->setLinkage(GlobalValue::InternalLinkage);
98         }
99
100       // Make sure our result is globally accessible...
101       // by putting them in the used array
102       {
103         std::vector<Constant *> AUGs;
104         const Type *SBP=
105               PointerType::getUnqual(Type::getInt8Ty(M.getContext()));
106         for (std::vector<GlobalValue*>::iterator GI = Named.begin(), 
107                GE = Named.end(); GI != GE; ++GI) {
108           (*GI)->setLinkage(GlobalValue::ExternalLinkage);
109           AUGs.push_back(ConstantExpr::getBitCast(*GI, SBP));
110         }
111         ArrayType *AT = ArrayType::get(SBP, AUGs.size());
112         Constant *Init = ConstantArray::get(AT, AUGs);
113         GlobalValue *gv = new GlobalVariable(M, AT, false, 
114                                              GlobalValue::AppendingLinkage, 
115                                              Init, "llvm.used");
116         gv->setSection("llvm.metadata");
117       }
118
119       // All of the functions may be used by global variables or the named
120       // globals.  Loop through them and create a new, external functions that
121       // can be "used", instead of ones with bodies.
122       std::vector<Function*> NewFunctions;
123
124       Function *Last = --M.end();  // Figure out where the last real fn is.
125
126       for (Module::iterator I = M.begin(); ; ++I) {
127         if (std::find(Named.begin(), Named.end(), &*I) == Named.end()) {
128           Function *New = Function::Create(I->getFunctionType(),
129                                            GlobalValue::ExternalLinkage);
130           New->copyAttributesFrom(I);
131
132           // If it's not the named function, delete the body of the function
133           I->dropAllReferences();
134
135           M.getFunctionList().push_back(New);
136           NewFunctions.push_back(New);
137           New->takeName(I);
138         }
139
140         if (&*I == Last) break;  // Stop after processing the last function
141       }
142
143       // Now that we have replacements all set up, loop through the module,
144       // deleting the old functions, replacing them with the newly created
145       // functions.
146       if (!NewFunctions.empty()) {
147         unsigned FuncNum = 0;
148         Module::iterator I = M.begin();
149         do {
150           if (std::find(Named.begin(), Named.end(), &*I) == Named.end()) {
151             // Make everything that uses the old function use the new dummy fn
152             I->replaceAllUsesWith(NewFunctions[FuncNum++]);
153
154             Function *Old = I;
155             ++I;  // Move the iterator to the new function
156
157             // Delete the old function!
158             M.getFunctionList().erase(Old);
159
160           } else {
161             ++I;  // Skip the function we are extracting
162           }
163         } while (&*I != NewFunctions[0]);
164       }
165
166       return true;
167     }
168   };
169
170   char GVExtractorPass::ID = 0;
171 }
172
173 ModulePass *llvm::createGVExtractionPass(std::vector<GlobalValue*>& GVs, 
174                                          bool deleteFn, bool relinkCallees) {
175   return new GVExtractorPass(GVs, deleteFn, relinkCallees);
176 }