Add a FunctionImporter helper to perform summary-based cross-module function importing
[oota-llvm.git] / lib / Transforms / IPO / FunctionImport.cpp
1 //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
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 file implements Function import based on summaries.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Transforms/IPO/FunctionImport.h"
15
16 #include "llvm/ADT/StringSet.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/DiagnosticPrinter.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IRReader/IRReader.h"
22 #include "llvm/Linker/Linker.h"
23 #include "llvm/Object/FunctionIndexObjectFile.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/SourceMgr.h"
27 using namespace llvm;
28
29 #define DEBUG_TYPE "function-import"
30
31 // Load lazily a module from \p FileName in \p Context.
32 static std::unique_ptr<Module> loadFile(const std::string &FileName,
33                                         LLVMContext &Context) {
34   SMDiagnostic Err;
35   DEBUG(dbgs() << "Loading '" << FileName << "'\n");
36   std::unique_ptr<Module> Result = getLazyIRFileModule(FileName, Err, Context);
37   if (!Result) {
38     Err.print("function-import", errs());
39     return nullptr;
40   }
41
42   Result->materializeMetadata();
43   UpgradeDebugInfo(*Result);
44
45   return Result;
46 }
47
48 // Get a Module for \p FileName from the cache, or load it lazily.
49 Module &FunctionImporter::getOrLoadModule(StringRef FileName) {
50   auto &Module = ModuleMap[FileName];
51   if (!Module)
52     Module = loadFile(FileName, Context);
53   return *Module;
54 }
55
56 // Automatically import functions in Module \p M based on the summaries index.
57 //
58 // The current implementation imports every called functions that exists in the
59 // summaries index.
60 bool FunctionImporter::importFunctions(Module &M) {
61   assert(&Context == &M.getContext());
62
63   bool Changed = false;
64
65   /// First step is collecting the called functions and the one defined in this
66   /// module.
67   StringSet<> CalledFunctions;
68   for (auto &F : M) {
69     if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
70       continue;
71     for (auto &BB : F) {
72       for (auto &I : BB) {
73         if (isa<CallInst>(I)) {
74           DEBUG(dbgs() << "Found a call: '" << I << "'\n");
75           auto CalledFunction = cast<CallInst>(I).getCalledFunction();
76           if (CalledFunction && CalledFunction->hasName() &&
77               CalledFunction->isDeclaration())
78             CalledFunctions.insert(CalledFunction->getName());
79         }
80       }
81     }
82   }
83
84   /// Second step: for every call to an external function, try to import it.
85
86   // Linker that will be used for importing function
87   Linker L(&M, DiagnosticHandler);
88
89   /// Insert initial called function set in a worklist, so that we can add
90   /// transively called functions when importing.
91   SmallVector<StringRef, 64> Worklist;
92   for (auto &CalledFunction : CalledFunctions)
93     Worklist.push_back(CalledFunction.first());
94
95   while (!Worklist.empty()) {
96     auto CalledFunctionName = Worklist.pop_back_val();
97     DEBUG(dbgs() << "Process import for " << CalledFunctionName << "\n");
98
99     // Try to get a summary for this function call.
100     auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
101     if (InfoList == Index.end()) {
102       DEBUG(dbgs() << "No summary for " << CalledFunctionName
103                    << " Ignoring.\n");
104       continue;
105     }
106     assert(!InfoList->second.empty() && "No summary, error at import?");
107
108     // Comdat can have multiple entries, FIXME: what do we do with them?
109     auto &Info = InfoList->second[0];
110     assert(Info && "Nullptr in list, error importing summaries?\n");
111
112     auto *Summary = Info->functionSummary();
113     if (!Summary) {
114       // FIXME: in case we are lazyloading summaries, we can do it now.
115       dbgs() << "Missing summary for  " << CalledFunctionName
116              << ", error at import?\n";
117       llvm_unreachable("Missing summary");
118     }
119
120     //
121     // No profitability notion right now, just import all the time...
122     //
123
124     // Get the module path from the summary.
125     auto FileName = Summary->modulePath();
126     DEBUG(dbgs() << "Importing " << CalledFunctionName << " from " << FileName
127                  << "\n");
128
129     // Get the module for the import (potentially from the cache).
130     auto &Module = getOrLoadModule(FileName);
131
132     // The function that we will import!
133     GlobalValue *SGV = Module.getNamedValue(CalledFunctionName);
134     Function *F = dyn_cast<Function>(SGV);
135     if (!F && isa<GlobalAlias>(SGV)) {
136       auto *SGA = dyn_cast<GlobalAlias>(SGV);
137       F = dyn_cast<Function>(SGA->getBaseObject());
138     }
139     if (!F) {
140       errs() << "Can't load function '" << CalledFunctionName << "' in Module '"
141              << FileName << "', error in the summary?\n";
142       llvm_unreachable("Can't load function in Module");
143     }
144
145     // We cannot import weak_any functions without possibly affecting the
146     // order they are seen and selected by the linker, changing program
147     // semantics.
148     if (F->hasWeakAnyLinkage()) {
149       DEBUG(dbgs() << "Ignoring import request for weak-any function "
150                    << CalledFunctionName << " from " << FileName << "\n");
151       continue;
152     }
153
154     // Link in the specified function.
155     if (L.linkInModule(&Module, Linker::Flags::None, &Index, F))
156       report_fatal_error("Function Import: link error");
157
158     // TODO: Process the newly imported function and add callees to the
159     // worklist.
160
161     Changed = true;
162   }
163   return Changed;
164 }
165
166 /// Summary file to use for function importing when using -function-import from
167 /// the command line.
168 static cl::opt<std::string>
169     SummaryFile("summary-file",
170                 cl::desc("The summary file to use for function importing."));
171
172 static void diagnosticHandler(const DiagnosticInfo &DI) {
173   raw_ostream &OS = errs();
174   DiagnosticPrinterRawOStream DP(OS);
175   DI.print(DP);
176   OS << '\n';
177 }
178
179 /// Parse the function index out of an IR file and return the function
180 /// index object if found, or nullptr if not.
181 static std::unique_ptr<FunctionInfoIndex>
182 getFunctionIndexForFile(StringRef Path, std::string &Error,
183                         DiagnosticHandlerFunction DiagnosticHandler) {
184   std::unique_ptr<MemoryBuffer> Buffer;
185   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
186       MemoryBuffer::getFile(Path);
187   if (std::error_code EC = BufferOrErr.getError()) {
188     Error = EC.message();
189     return nullptr;
190   }
191   Buffer = std::move(BufferOrErr.get());
192   ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
193       object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
194                                               DiagnosticHandler);
195   if (std::error_code EC = ObjOrErr.getError()) {
196     Error = EC.message();
197     return nullptr;
198   }
199   return (*ObjOrErr)->takeIndex();
200 }
201
202 /// Pass that performs cross-module function import provided a summary file.
203 class FunctionImportPass : public ModulePass {
204
205 public:
206   /// Pass identification, replacement for typeid
207   static char ID;
208
209   explicit FunctionImportPass() : ModulePass(ID) {}
210
211   bool runOnModule(Module &M) override {
212     if (SummaryFile.empty()) {
213       report_fatal_error("error: -function-import requires -summary-file\n");
214     }
215     std::string Error;
216     std::unique_ptr<FunctionInfoIndex> Index =
217         getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
218     if (!Index) {
219       errs() << "Error loading file '" << SummaryFile << "': " << Error << "\n";
220       return false;
221     }
222
223     // Perform the import now.
224     FunctionImporter Importer(M.getContext(), *Index, diagnosticHandler);
225     return Importer.importFunctions(M);
226
227     return false;
228   }
229 };
230
231 char FunctionImportPass::ID = 0;
232 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
233                       "Summary Based Function Import", false, false)
234 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
235                     "Summary Based Function Import", false, false)
236
237 namespace llvm {
238 Pass *createFunctionImportPass() { return new FunctionImportPass(); }
239 }