Trying to fix the build in a bot.
[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
28 #include <functional>
29 #include <map>
30
31 using namespace llvm;
32
33 #define DEBUG_TYPE "function-import"
34
35 /// Limit on instruction count of imported functions.
36 static cl::opt<unsigned> ImportInstrLimit(
37     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
38     cl::desc("Only import functions with less than N instructions"));
39
40 // Load lazily a module from \p FileName in \p Context.
41 static std::unique_ptr<Module> loadFile(const std::string &FileName,
42                                         LLVMContext &Context) {
43   SMDiagnostic Err;
44   DEBUG(dbgs() << "Loading '" << FileName << "'\n");
45   std::unique_ptr<Module> Result = getLazyIRFileModule(FileName, Err, Context);
46   if (!Result) {
47     Err.print("function-import", errs());
48     return nullptr;
49   }
50
51   Result->materializeMetadata();
52   UpgradeDebugInfo(*Result);
53
54   return Result;
55 }
56
57 namespace {
58 /// Helper to load on demand a Module from file and cache it for subsequent
59 /// queries. It can be used with the FunctionImporter.
60 class ModuleLazyLoaderCache {
61   /// Cache of lazily loaded module for import.
62   StringMap<std::unique_ptr<Module>> ModuleMap;
63
64   /// Retrieve a Module from the cache or lazily load it on demand.
65   std::function<std::unique_ptr<Module>(StringRef FileName)> createLazyModule;
66
67 public:
68   /// Create the loader, Module will be initialized in \p Context.
69   ModuleLazyLoaderCache(std::function<
70       std::unique_ptr<Module>(StringRef FileName)> createLazyModule)
71       : createLazyModule(createLazyModule) {}
72
73   /// Retrieve a Module from the cache or lazily load it on demand.
74   Module &operator()(StringRef FileName);
75 };
76
77 // Get a Module for \p FileName from the cache, or load it lazily.
78 Module &ModuleLazyLoaderCache::operator()(StringRef Identifier) {
79   auto &Module = ModuleMap[Identifier];
80   if (!Module)
81     Module = createLazyModule(Identifier);
82   return *Module;
83 }
84 } // anonymous namespace
85
86 /// Walk through the instructions in \p F looking for external
87 /// calls not already in the \p CalledFunctions set. If any are
88 /// found they are added to the \p Worklist for importing.
89 static void findExternalCalls(const Module &DestModule, Function &F,
90                               const FunctionInfoIndex &Index,
91                               StringSet<> &CalledFunctions,
92                               SmallVector<StringRef, 64> &Worklist) {
93   // We need to suffix internal function calls imported from other modules,
94   // prepare the suffix ahead of time.
95   std::string Suffix;
96   if (F.getParent() != &DestModule)
97     Suffix =
98         (Twine(".llvm.") +
99          Twine(Index.getModuleId(F.getParent()->getModuleIdentifier()))).str();
100
101   for (auto &BB : F) {
102     for (auto &I : BB) {
103       if (isa<CallInst>(I)) {
104         auto CalledFunction = cast<CallInst>(I).getCalledFunction();
105         // Insert any new external calls that have not already been
106         // added to set/worklist.
107         if (!CalledFunction || !CalledFunction->hasName())
108           continue;
109         // Ignore intrinsics early
110         if (CalledFunction->isIntrinsic()) {
111           assert(CalledFunction->getIntrinsicID() != 0);
112           continue;
113         }
114         auto ImportedName = CalledFunction->getName();
115         auto Renamed = (ImportedName + Suffix).str();
116         // Rename internal functions
117         if (CalledFunction->hasInternalLinkage()) {
118           ImportedName = Renamed;
119         }
120         auto It = CalledFunctions.insert(ImportedName);
121         if (!It.second) {
122           // This is a call to a function we already considered, skip.
123           continue;
124         }
125         // Ignore functions already present in the destination module
126         auto *SrcGV = DestModule.getNamedValue(ImportedName);
127         if (SrcGV) {
128           assert(isa<Function>(SrcGV) && "Name collision during import");
129           if (!cast<Function>(SrcGV)->isDeclaration()) {
130             DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Ignoring "
131                          << ImportedName << " already in DestinationModule\n");
132             continue;
133           }
134         }
135
136         Worklist.push_back(It.first->getKey());
137         DEBUG(dbgs() << DestModule.getModuleIdentifier()
138                      << ": Adding callee for : " << ImportedName << " : "
139                      << F.getName() << "\n");
140       }
141     }
142   }
143 }
144
145 // Helper function: given a worklist and an index, will process all the worklist
146 // and decide what to import based on the summary information.
147 //
148 // Nothing is actually imported, functions are materialized in their source
149 // module and analyzed there.
150 //
151 // \p ModuleToFunctionsToImportMap is filled with the set of Function to import
152 // per Module.
153 static void GetImportList(
154     Module &DestModule, SmallVector<StringRef, 64> &Worklist,
155     StringSet<> &CalledFunctions,
156     std::map<StringRef, std::pair<Module *, DenseSet<const GlobalValue *>>> &
157         ModuleToFunctionsToImportMap,
158     const FunctionInfoIndex &Index, ModuleLazyLoaderCache &ModuleLoaderCache) {
159   while (!Worklist.empty()) {
160     auto CalledFunctionName = Worklist.pop_back_val();
161     DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Process import for "
162                  << CalledFunctionName << "\n");
163
164     // Try to get a summary for this function call.
165     auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
166     if (InfoList == Index.end()) {
167       DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": No summary for "
168                    << CalledFunctionName << " Ignoring.\n");
169       continue;
170     }
171     assert(!InfoList->second.empty() && "No summary, error at import?");
172
173     // Comdat can have multiple entries, FIXME: what do we do with them?
174     auto &Info = InfoList->second[0];
175     assert(Info && "Nullptr in list, error importing summaries?\n");
176
177     auto *Summary = Info->functionSummary();
178     if (!Summary) {
179       // FIXME: in case we are lazyloading summaries, we can do it now.
180       DEBUG(dbgs() << DestModule.getModuleIdentifier()
181                    << ": Missing summary for  " << CalledFunctionName
182                    << ", error at import?\n");
183       llvm_unreachable("Missing summary");
184     }
185
186     if (Summary->instCount() > ImportInstrLimit) {
187       DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Skip import of "
188                    << CalledFunctionName << " with " << Summary->instCount()
189                    << " instructions (limit " << ImportInstrLimit << ")\n");
190       continue;
191     }
192
193     // Get the module path from the summary.
194     auto ModuleIdentifier = Summary->modulePath();
195     DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Importing "
196                  << CalledFunctionName << " from " << ModuleIdentifier << "\n");
197
198     auto &SrcModule = ModuleLoaderCache(ModuleIdentifier);
199
200     // The function that we will import!
201     GlobalValue *SGV = SrcModule.getNamedValue(CalledFunctionName);
202
203     if (!SGV) {
204       // The destination module is referencing function using their renamed name
205       // when importing a function that was originally local in the source
206       // module. The source module we have might not have been renamed so we try
207       // to remove the suffix added during the renaming to recover the original
208       // name in the source module.
209       std::pair<StringRef, StringRef> Split =
210           CalledFunctionName.split(".llvm.");
211       SGV = SrcModule.getNamedValue(Split.first);
212       assert(SGV && "Can't find function to import in source module");
213     }
214     if (!SGV) {
215       report_fatal_error(Twine("Can't load function '") + CalledFunctionName +
216                          "' in Module '" + SrcModule.getModuleIdentifier() +
217                          "', error in the summary?\n");
218     }
219
220     Function *F = dyn_cast<Function>(SGV);
221     if (!F && isa<GlobalAlias>(SGV)) {
222       auto *SGA = dyn_cast<GlobalAlias>(SGV);
223       F = dyn_cast<Function>(SGA->getBaseObject());
224       CalledFunctionName = F->getName();
225     }
226     assert(F && "Imported Function is ... not a Function");
227
228     // We cannot import weak_any functions/aliases without possibly affecting
229     // the order they are seen and selected by the linker, changing program
230     // semantics.
231     if (SGV->hasWeakAnyLinkage()) {
232       DEBUG(dbgs() << DestModule.getModuleIdentifier()
233                    << ": Ignoring import request for weak-any "
234                    << (isa<Function>(SGV) ? "function " : "alias ")
235                    << CalledFunctionName << " from "
236                    << SrcModule.getModuleIdentifier() << "\n");
237       continue;
238     }
239
240     // Add the function to the import list
241     auto &Entry = ModuleToFunctionsToImportMap[SrcModule.getModuleIdentifier()];
242     Entry.first = &SrcModule;
243     Entry.second.insert(F);
244
245     // Process the newly imported functions and add callees to the worklist.
246     F->materialize();
247     findExternalCalls(DestModule, *F, Index, CalledFunctions, Worklist);
248   }
249 }
250
251 // Automatically import functions in Module \p DestModule based on the summaries
252 // index.
253 //
254 // The current implementation imports every called functions that exists in the
255 // summaries index.
256 bool FunctionImporter::importFunctions(Module &DestModule) {
257   DEBUG(dbgs() << "Starting import for Module "
258                << DestModule.getModuleIdentifier() << "\n");
259   unsigned ImportedCount = 0;
260
261   /// First step is collecting the called external functions.
262   StringSet<> CalledFunctions;
263   SmallVector<StringRef, 64> Worklist;
264   for (auto &F : DestModule) {
265     if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
266       continue;
267     findExternalCalls(DestModule, F, Index, CalledFunctions, Worklist);
268   }
269   if (Worklist.empty())
270     return false;
271
272   /// Second step: for every call to an external function, try to import it.
273
274   // Linker that will be used for importing function
275   Linker TheLinker(DestModule);
276
277   // Map of Module -> List of Function to import from the Module
278   std::map<StringRef, std::pair<Module *, DenseSet<const GlobalValue *>>>
279       ModuleToFunctionsToImportMap;
280
281   // Analyze the summaries and get the list of functions to import by
282   // populating ModuleToFunctionsToImportMap
283   ModuleLazyLoaderCache ModuleLoaderCache(ModuleLoader);
284   GetImportList(DestModule, Worklist, CalledFunctions,
285                 ModuleToFunctionsToImportMap, Index, ModuleLoaderCache);
286   assert(Worklist.empty() && "Worklist hasn't been flushed in GetImportList");
287
288   // Do the actual import of functions now, one Module at a time
289   for (auto &FunctionsToImportPerModule : ModuleToFunctionsToImportMap) {
290     // Get the module for the import
291     auto &FunctionsToImport = FunctionsToImportPerModule.second.second;
292     auto *SrcModule = FunctionsToImportPerModule.second.first;
293     assert(&DestModule.getContext() == &SrcModule->getContext() &&
294            "Context mismatch");
295
296     // Link in the specified functions.
297     if (TheLinker.linkInModule(*SrcModule, Linker::Flags::None, &Index,
298                                &FunctionsToImport))
299       report_fatal_error("Function Import: link error");
300
301     ImportedCount += FunctionsToImport.size();
302   }
303   DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
304                << DestModule.getModuleIdentifier() << "\n");
305   return ImportedCount;
306 }
307
308 /// Summary file to use for function importing when using -function-import from
309 /// the command line.
310 static cl::opt<std::string>
311     SummaryFile("summary-file",
312                 cl::desc("The summary file to use for function importing."));
313
314 static void diagnosticHandler(const DiagnosticInfo &DI) {
315   raw_ostream &OS = errs();
316   DiagnosticPrinterRawOStream DP(OS);
317   DI.print(DP);
318   OS << '\n';
319 }
320
321 /// Parse the function index out of an IR file and return the function
322 /// index object if found, or nullptr if not.
323 static std::unique_ptr<FunctionInfoIndex>
324 getFunctionIndexForFile(StringRef Path, std::string &Error,
325                         DiagnosticHandlerFunction DiagnosticHandler) {
326   std::unique_ptr<MemoryBuffer> Buffer;
327   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
328       MemoryBuffer::getFile(Path);
329   if (std::error_code EC = BufferOrErr.getError()) {
330     Error = EC.message();
331     return nullptr;
332   }
333   Buffer = std::move(BufferOrErr.get());
334   ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
335       object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
336                                               DiagnosticHandler);
337   if (std::error_code EC = ObjOrErr.getError()) {
338     Error = EC.message();
339     return nullptr;
340   }
341   return (*ObjOrErr)->takeIndex();
342 }
343
344 /// Pass that performs cross-module function import provided a summary file.
345 class FunctionImportPass : public ModulePass {
346   /// Optional function summary index to use for importing, otherwise
347   /// the summary-file option must be specified.
348   const FunctionInfoIndex *Index;
349
350 public:
351   /// Pass identification, replacement for typeid
352   static char ID;
353
354   /// Specify pass name for debug output
355   const char *getPassName() const override {
356     return "Function Importing";
357   }
358
359   explicit FunctionImportPass(const FunctionInfoIndex *Index = nullptr)
360       : ModulePass(ID), Index(Index) {}
361
362   bool runOnModule(Module &M) override {
363     if (SummaryFile.empty() && !Index)
364       report_fatal_error("error: -function-import requires -summary-file or "
365                          "file from frontend\n");
366     std::unique_ptr<FunctionInfoIndex> IndexPtr;
367     if (!SummaryFile.empty()) {
368       if (Index)
369         report_fatal_error("error: -summary-file and index from frontend\n");
370       std::string Error;
371       IndexPtr = getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
372       if (!IndexPtr) {
373         errs() << "Error loading file '" << SummaryFile << "': " << Error
374                << "\n";
375         return false;
376       }
377       Index = IndexPtr.get();
378     }
379
380     // Perform the import now.
381     auto ModuleLoader = [&M](StringRef Identifier) {
382       return loadFile(Identifier, M.getContext());
383     };
384     FunctionImporter Importer(*Index, ModuleLoader);
385     return Importer.importFunctions(M);
386
387     return false;
388   }
389 };
390
391 char FunctionImportPass::ID = 0;
392 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
393                       "Summary Based Function Import", false, false)
394 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
395                     "Summary Based Function Import", false, false)
396
397 namespace llvm {
398 Pass *createFunctionImportPass(const FunctionInfoIndex *Index = nullptr) {
399   return new FunctionImportPass(Index);
400 }
401 }