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