67d77adb650a6ef3331a46e89cc7fc9583c37a72
[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 /// Limit on instruction count of imported functions.
32 static cl::opt<unsigned> ImportInstrLimit(
33     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
34     cl::desc("Only import functions with less than N instructions"));
35
36 // Load lazily a module from \p FileName in \p Context.
37 static std::unique_ptr<Module> loadFile(const std::string &FileName,
38                                         LLVMContext &Context) {
39   SMDiagnostic Err;
40   DEBUG(dbgs() << "Loading '" << FileName << "'\n");
41   std::unique_ptr<Module> Result = getLazyIRFileModule(FileName, Err, Context);
42   if (!Result) {
43     Err.print("function-import", errs());
44     return nullptr;
45   }
46
47   Result->materializeMetadata();
48   UpgradeDebugInfo(*Result);
49
50   return Result;
51 }
52
53 // Get a Module for \p FileName from the cache, or load it lazily.
54 Module &ModuleLazyLoaderCache::operator()(StringRef FileName) {
55   auto &Module = ModuleMap[FileName];
56   if (!Module)
57     Module = loadFile(FileName, Context);
58   return *Module;
59 }
60
61 /// Walk through the instructions in \p F looking for external
62 /// calls not already in the \p CalledFunctions set. If any are
63 /// found they are added to the \p Worklist for importing.
64 static void findExternalCalls(const Function &F, StringSet<> &CalledFunctions,
65                               SmallVector<StringRef, 64> &Worklist) {
66   for (auto &BB : F) {
67     for (auto &I : BB) {
68       if (isa<CallInst>(I)) {
69         auto CalledFunction = cast<CallInst>(I).getCalledFunction();
70         // Insert any new external calls that have not already been
71         // added to set/worklist.
72         if (CalledFunction && CalledFunction->hasName() &&
73             CalledFunction->isDeclaration() &&
74             !CalledFunctions.count(CalledFunction->getName())) {
75           CalledFunctions.insert(CalledFunction->getName());
76           Worklist.push_back(CalledFunction->getName());
77         }
78       }
79     }
80   }
81 }
82
83 // Helper function: given a worklist and an index, will process all the worklist
84 // and import them based on the summary information
85 static unsigned ProcessImportWorklist(
86     Module &DestModule, SmallVector<StringRef, 64> &Worklist,
87     StringSet<> &CalledFunctions, Linker &TheLinker,
88     const FunctionInfoIndex &Index,
89     std::function<Module &(StringRef FileName)> &LazyModuleLoader) {
90   unsigned ImportCount = 0;
91   while (!Worklist.empty()) {
92     auto CalledFunctionName = Worklist.pop_back_val();
93     DEBUG(dbgs() << "Process import for " << CalledFunctionName << "\n");
94
95     // Try to get a summary for this function call.
96     auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
97     if (InfoList == Index.end()) {
98       DEBUG(dbgs() << "No summary for " << CalledFunctionName
99                    << " Ignoring.\n");
100       continue;
101     }
102     assert(!InfoList->second.empty() && "No summary, error at import?");
103
104     // Comdat can have multiple entries, FIXME: what do we do with them?
105     auto &Info = InfoList->second[0];
106     assert(Info && "Nullptr in list, error importing summaries?\n");
107
108     auto *Summary = Info->functionSummary();
109     if (!Summary) {
110       // FIXME: in case we are lazyloading summaries, we can do it now.
111       DEBUG(dbgs() << "Missing summary for  " << CalledFunctionName
112                    << ", error at import?\n");
113       llvm_unreachable("Missing summary");
114     }
115
116     if (Summary->instCount() > ImportInstrLimit) {
117       DEBUG(dbgs() << "Skip import of " << CalledFunctionName << " with "
118                    << Summary->instCount() << " instructions (limit "
119                    << ImportInstrLimit << ")\n");
120       continue;
121     }
122
123     // Get the module path from the summary.
124     auto FileName = Summary->modulePath();
125     DEBUG(dbgs() << "Importing " << CalledFunctionName << " from " << FileName
126                  << "\n");
127
128     // Get the module for the import (potentially from the cache).
129     auto &Module = LazyModuleLoader(FileName);
130     assert(&Module.getContext() == &DestModule.getContext());
131
132     // The function that we will import!
133     GlobalValue *SGV = Module.getNamedValue(CalledFunctionName);
134     StringRef ImportFunctionName = CalledFunctionName;
135     if (!SGV) {
136       // Might be local in source Module, promoted/renamed in DestModule.
137       std::pair<StringRef, StringRef> Split =
138           CalledFunctionName.split(".llvm.");
139       SGV = Module.getNamedValue(Split.first);
140 #ifndef NDEBUG
141       // Assert that Split.second is module id
142       uint64_t ModuleId;
143       assert(!Split.second.getAsInteger(10, ModuleId));
144       assert(ModuleId == Index.getModuleId(FileName));
145 #endif
146     }
147     Function *F = dyn_cast<Function>(SGV);
148     if (!F && isa<GlobalAlias>(SGV)) {
149       auto *SGA = dyn_cast<GlobalAlias>(SGV);
150       F = dyn_cast<Function>(SGA->getBaseObject());
151       ImportFunctionName = F->getName();
152     }
153     if (!F) {
154       errs() << "Can't load function '" << CalledFunctionName << "' in Module '"
155              << FileName << "', error in the summary?\n";
156       llvm_unreachable("Can't load function in Module");
157     }
158
159     // We cannot import weak_any functions/aliases without possibly affecting
160     // the order they are seen and selected by the linker, changing program
161     // semantics.
162     if (SGV->hasWeakAnyLinkage()) {
163       DEBUG(dbgs() << "Ignoring import request for weak-any "
164                    << (isa<Function>(SGV) ? "function " : "alias ")
165                    << CalledFunctionName << " from " << FileName << "\n");
166       continue;
167     }
168
169     // Link in the specified function.
170     DenseSet<const GlobalValue *> FunctionsToImport;
171     FunctionsToImport.insert(F);
172     if (TheLinker.linkInModule(Module, Linker::Flags::None, &Index,
173                                &FunctionsToImport))
174       report_fatal_error("Function Import: link error");
175
176     // Process the newly imported function and add callees to the worklist.
177     GlobalValue *NewGV = DestModule.getNamedValue(ImportFunctionName);
178     assert(NewGV);
179     Function *NewF = dyn_cast<Function>(NewGV);
180     assert(NewF);
181     findExternalCalls(*NewF, CalledFunctions, Worklist);
182     ++ImportCount;
183   }
184   return ImportCount;
185 }
186
187 // Automatically import functions in Module \p DestModule based on the summaries
188 // index.
189 //
190 // The current implementation imports every called functions that exists in the
191 // summaries index.
192 bool FunctionImporter::importFunctions(Module &DestModule) {
193   DEBUG(errs() << "Starting import for Module "
194                << DestModule.getModuleIdentifier() << "\n");
195   unsigned ImportedCount = 0;
196
197   /// First step is collecting the called external functions.
198   StringSet<> CalledFunctions;
199   SmallVector<StringRef, 64> Worklist;
200   for (auto &F : DestModule) {
201     if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
202       continue;
203     findExternalCalls(F, CalledFunctions, Worklist);
204   }
205   if (Worklist.empty())
206     return false;
207
208   /// Second step: for every call to an external function, try to import it.
209
210   // Linker that will be used for importing function
211   Linker TheLinker(DestModule, DiagnosticHandler);
212
213   ImportedCount += ProcessImportWorklist(DestModule, Worklist, CalledFunctions,
214                                          TheLinker, Index, getLazyModule);
215
216   DEBUG(errs() << "Imported " << ImportedCount << " functions for Module "
217                << DestModule.getModuleIdentifier() << "\n");
218   return ImportedCount;
219 }
220
221 /// Summary file to use for function importing when using -function-import from
222 /// the command line.
223 static cl::opt<std::string>
224     SummaryFile("summary-file",
225                 cl::desc("The summary file to use for function importing."));
226
227 static void diagnosticHandler(const DiagnosticInfo &DI) {
228   raw_ostream &OS = errs();
229   DiagnosticPrinterRawOStream DP(OS);
230   DI.print(DP);
231   OS << '\n';
232 }
233
234 /// Parse the function index out of an IR file and return the function
235 /// index object if found, or nullptr if not.
236 static std::unique_ptr<FunctionInfoIndex>
237 getFunctionIndexForFile(StringRef Path, std::string &Error,
238                         DiagnosticHandlerFunction DiagnosticHandler) {
239   std::unique_ptr<MemoryBuffer> Buffer;
240   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
241       MemoryBuffer::getFile(Path);
242   if (std::error_code EC = BufferOrErr.getError()) {
243     Error = EC.message();
244     return nullptr;
245   }
246   Buffer = std::move(BufferOrErr.get());
247   ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
248       object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
249                                               DiagnosticHandler);
250   if (std::error_code EC = ObjOrErr.getError()) {
251     Error = EC.message();
252     return nullptr;
253   }
254   return (*ObjOrErr)->takeIndex();
255 }
256
257 /// Pass that performs cross-module function import provided a summary file.
258 class FunctionImportPass : public ModulePass {
259   /// Optional function summary index to use for importing, otherwise
260   /// the summary-file option must be specified.
261   FunctionInfoIndex *Index;
262
263 public:
264   /// Pass identification, replacement for typeid
265   static char ID;
266
267   /// Specify pass name for debug output
268   const char *getPassName() const override {
269     return "Function Importing";
270   }
271
272   explicit FunctionImportPass(FunctionInfoIndex *Index = nullptr)
273       : ModulePass(ID), Index(Index) {}
274
275   bool runOnModule(Module &M) override {
276     if (SummaryFile.empty() && !Index)
277       report_fatal_error("error: -function-import requires -summary-file or "
278                          "file from frontend\n");
279     std::unique_ptr<FunctionInfoIndex> IndexPtr;
280     if (!SummaryFile.empty()) {
281       if (Index)
282         report_fatal_error("error: -summary-file and index from frontend\n");
283       std::string Error;
284       IndexPtr = getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
285       if (!IndexPtr) {
286         errs() << "Error loading file '" << SummaryFile << "': " << Error
287                << "\n";
288         return false;
289       }
290       Index = IndexPtr.get();
291     }
292
293     // Perform the import now.
294     ModuleLazyLoaderCache Loader(M.getContext());
295     FunctionImporter Importer(*Index, diagnosticHandler,
296                               [&](StringRef Name)
297                                   -> Module &{ return Loader(Name); });
298     return Importer.importFunctions(M);
299
300     return false;
301   }
302 };
303
304 char FunctionImportPass::ID = 0;
305 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
306                       "Summary Based Function Import", false, false)
307 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
308                     "Summary Based Function Import", false, false)
309
310 namespace llvm {
311 Pass *createFunctionImportPass(FunctionInfoIndex *Index = nullptr) {
312   return new FunctionImportPass(Index);
313 }
314 }