blob: 6325a726673ee0f57709194dae66e20b203e5a28 [file] [log] [blame]
Mehdi Amini42418ab2015-11-24 06:07:49 +00001//===- 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"
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000027
28#include <map>
29
Mehdi Amini42418ab2015-11-24 06:07:49 +000030using namespace llvm;
31
32#define DEBUG_TYPE "function-import"
33
Teresa Johnson39303612015-11-24 22:55:46 +000034/// Limit on instruction count of imported functions.
35static cl::opt<unsigned> ImportInstrLimit(
36 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
37 cl::desc("Only import functions with less than N instructions"));
38
Mehdi Amini42418ab2015-11-24 06:07:49 +000039// Load lazily a module from \p FileName in \p Context.
40static std::unique_ptr<Module> loadFile(const std::string &FileName,
41 LLVMContext &Context) {
42 SMDiagnostic Err;
43 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
44 std::unique_ptr<Module> Result = getLazyIRFileModule(FileName, Err, Context);
45 if (!Result) {
46 Err.print("function-import", errs());
47 return nullptr;
48 }
49
50 Result->materializeMetadata();
51 UpgradeDebugInfo(*Result);
52
53 return Result;
54}
55
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000056namespace {
57/// Helper to load on demand a Module from file and cache it for subsequent
58/// queries. It can be used with the FunctionImporter.
59class ModuleLazyLoaderCache {
60 /// Cache of lazily loaded module for import.
61 StringMap<std::unique_ptr<Module>> ModuleMap;
62
63 /// Retrieve a Module from the cache or lazily load it on demand.
64 std::function<std::unique_ptr<Module>(StringRef FileName)> createLazyModule;
65
66public:
67 /// Create the loader, Module will be initialized in \p Context.
68 ModuleLazyLoaderCache(std::function<
69 std::unique_ptr<Module>(StringRef FileName)> createLazyModule)
70 : createLazyModule(createLazyModule) {}
71
72 /// Retrieve a Module from the cache or lazily load it on demand.
73 Module &operator()(StringRef FileName);
74};
75
76// Get a Module for \p FileName from the cache, or load it lazily.
77Module &ModuleLazyLoaderCache::operator()(StringRef Identifier) {
78 auto &Module = ModuleMap[Identifier];
79 if (!Module)
80 Module = createLazyModule(Identifier);
81 return *Module;
82}
83} // anonymous namespace
84
Teresa Johnsond450da32015-11-24 21:15:19 +000085/// Walk through the instructions in \p F looking for external
86/// calls not already in the \p CalledFunctions set. If any are
87/// found they are added to the \p Worklist for importing.
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000088static void findExternalCalls(const Module &DestModule, Function &F,
89 const FunctionInfoIndex &Index,
90 StringSet<> &CalledFunctions,
Teresa Johnsond450da32015-11-24 21:15:19 +000091 SmallVector<StringRef, 64> &Worklist) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000092 // We need to suffix internal function calls imported from other modules,
93 // prepare the suffix ahead of time.
Rafael Espindola9edc3b82015-12-09 20:41:10 +000094 std::string Suffix;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000095 if (F.getParent() != &DestModule)
96 Suffix =
97 (Twine(".llvm.") +
98 Twine(Index.getModuleId(F.getParent()->getModuleIdentifier()))).str();
99
Teresa Johnsond450da32015-11-24 21:15:19 +0000100 for (auto &BB : F) {
101 for (auto &I : BB) {
102 if (isa<CallInst>(I)) {
Teresa Johnsond450da32015-11-24 21:15:19 +0000103 auto CalledFunction = cast<CallInst>(I).getCalledFunction();
104 // Insert any new external calls that have not already been
105 // added to set/worklist.
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000106 if (!CalledFunction || !CalledFunction->hasName())
107 continue;
108 // Ignore intrinsics early
109 if (CalledFunction->isIntrinsic()) {
110 assert(CalledFunction->getIntrinsicID() != 0);
111 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000112 }
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000113 auto ImportedName = CalledFunction->getName();
114 auto Renamed = (ImportedName + Suffix).str();
115 // Rename internal functions
116 if (CalledFunction->hasInternalLinkage()) {
117 ImportedName = Renamed;
118 }
119 auto It = CalledFunctions.insert(ImportedName);
120 if (!It.second) {
121 // This is a call to a function we already considered, skip.
122 continue;
123 }
124 // Ignore functions already present in the destination module
125 auto *SrcGV = DestModule.getNamedValue(ImportedName);
126 if (SrcGV) {
127 assert(isa<Function>(SrcGV) && "Name collision during import");
128 if (!cast<Function>(SrcGV)->isDeclaration()) {
129 DEBUG(dbgs() << DestModule.getModuleIdentifier() << "Ignoring "
130 << ImportedName << " already in DestinationModule\n");
131 continue;
132 }
133 }
134
135 Worklist.push_back(It.first->getKey());
136 DEBUG(dbgs() << DestModule.getModuleIdentifier()
137 << " Adding callee for : " << ImportedName << " : "
138 << F.getName() << "\n");
Teresa Johnsond450da32015-11-24 21:15:19 +0000139 }
140 }
141 }
142}
143
Mehdi Aminic8c55172015-12-03 02:37:33 +0000144// Helper function: given a worklist and an index, will process all the worklist
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000145// and decide what to import based on the summary information.
146//
147// Nothing is actually imported, functions are materialized in their source
148// module and analyzed there.
149//
150// \p ModuleToFunctionsToImportMap is filled with the set of Function to import
151// per Module.
152static void GetImportList(
Mehdi Amini311fef62015-12-03 02:58:14 +0000153 Module &DestModule, SmallVector<StringRef, 64> &Worklist,
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000154 StringSet<> &CalledFunctions,
155 std::map<StringRef, std::pair<Module *, DenseSet<const GlobalValue *>>> &
156 ModuleToFunctionsToImportMap,
157 const FunctionInfoIndex &Index, ModuleLazyLoaderCache &ModuleLoaderCache) {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000158 while (!Worklist.empty()) {
159 auto CalledFunctionName = Worklist.pop_back_val();
Mehdi Amini5411d052015-12-08 23:04:19 +0000160 DEBUG(dbgs() << DestModule.getModuleIdentifier() << "Process import for "
161 << CalledFunctionName << "\n");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000162
163 // Try to get a summary for this function call.
164 auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
165 if (InfoList == Index.end()) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000166 DEBUG(dbgs() << DestModule.getModuleIdentifier() << "No summary for "
167 << CalledFunctionName << " Ignoring.\n");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000168 continue;
169 }
170 assert(!InfoList->second.empty() && "No summary, error at import?");
171
172 // Comdat can have multiple entries, FIXME: what do we do with them?
173 auto &Info = InfoList->second[0];
174 assert(Info && "Nullptr in list, error importing summaries?\n");
175
176 auto *Summary = Info->functionSummary();
177 if (!Summary) {
178 // FIXME: in case we are lazyloading summaries, we can do it now.
Mehdi Amini5411d052015-12-08 23:04:19 +0000179 DEBUG(dbgs() << DestModule.getModuleIdentifier()
180 << " Missing summary for " << CalledFunctionName
Teresa Johnson430110c2015-12-01 17:12:10 +0000181 << ", error at import?\n");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000182 llvm_unreachable("Missing summary");
183 }
184
Teresa Johnson39303612015-11-24 22:55:46 +0000185 if (Summary->instCount() > ImportInstrLimit) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000186 DEBUG(dbgs() << DestModule.getModuleIdentifier() << " Skip import of "
187 << CalledFunctionName << " with " << Summary->instCount()
188 << " instructions (limit " << ImportInstrLimit << ")\n");
Teresa Johnson39303612015-11-24 22:55:46 +0000189 continue;
190 }
191
Mehdi Amini42418ab2015-11-24 06:07:49 +0000192 // Get the module path from the summary.
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000193 auto ModuleIdentifier = Summary->modulePath();
194 DEBUG(dbgs() << DestModule.getModuleIdentifier() << " Importing "
195 << CalledFunctionName << " from " << ModuleIdentifier << "\n");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000196
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000197 auto &SrcModule = ModuleLoaderCache(ModuleIdentifier);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000198
199 // The function that we will import!
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000200 GlobalValue *SGV = SrcModule.getNamedValue(CalledFunctionName);
201
Teresa Johnson130de7a2015-11-24 19:55:04 +0000202 if (!SGV) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000203 // The destination module is referencing function using their renamed name
204 // when importing a function that was originally local in the source
205 // module. The source module we have might not have been renamed so we try
206 // to remove the suffix added during the renaming to recover the original
207 // name in the source module.
Teresa Johnson130de7a2015-11-24 19:55:04 +0000208 std::pair<StringRef, StringRef> Split =
209 CalledFunctionName.split(".llvm.");
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000210 SGV = SrcModule.getNamedValue(Split.first);
211 assert(SGV && "Can't find function to import in source module");
Teresa Johnson130de7a2015-11-24 19:55:04 +0000212 }
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000213 if (!SGV) {
214 report_fatal_error(Twine("Can't load function '") + CalledFunctionName +
215 "' in Module '" + SrcModule.getModuleIdentifier() +
216 "', error in the summary?\n");
217 }
218
Mehdi Amini42418ab2015-11-24 06:07:49 +0000219 Function *F = dyn_cast<Function>(SGV);
220 if (!F && isa<GlobalAlias>(SGV)) {
221 auto *SGA = dyn_cast<GlobalAlias>(SGV);
222 F = dyn_cast<Function>(SGA->getBaseObject());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000223 CalledFunctionName = F->getName();
Mehdi Amini42418ab2015-11-24 06:07:49 +0000224 }
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000225 assert(F && "Imported Function is ... not a Function");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000226
Teresa Johnson17626652015-11-24 16:10:43 +0000227 // We cannot import weak_any functions/aliases without possibly affecting
228 // the order they are seen and selected by the linker, changing program
Mehdi Amini42418ab2015-11-24 06:07:49 +0000229 // semantics.
Teresa Johnson17626652015-11-24 16:10:43 +0000230 if (SGV->hasWeakAnyLinkage()) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000231 DEBUG(dbgs() << DestModule.getModuleIdentifier()
232 << " Ignoring import request for weak-any "
Teresa Johnson17626652015-11-24 16:10:43 +0000233 << (isa<Function>(SGV) ? "function " : "alias ")
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000234 << CalledFunctionName << " from "
235 << SrcModule.getModuleIdentifier() << "\n");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000236 continue;
237 }
238
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000239 // Add the function to the import list
240 auto &Entry = ModuleToFunctionsToImportMap[SrcModule.getModuleIdentifier()];
241 Entry.first = &SrcModule;
242 Entry.second.insert(F);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000243
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000244 // Process the newly imported functions and add callees to the worklist.
245 F->materialize();
246 findExternalCalls(DestModule, *F, Index, CalledFunctions, Worklist);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000247 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000248}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000249
Mehdi Aminic8c55172015-12-03 02:37:33 +0000250// Automatically import functions in Module \p DestModule based on the summaries
251// index.
252//
253// The current implementation imports every called functions that exists in the
254// summaries index.
255bool FunctionImporter::importFunctions(Module &DestModule) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000256 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000257 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000258 unsigned ImportedCount = 0;
259
260 /// First step is collecting the called external functions.
261 StringSet<> CalledFunctions;
262 SmallVector<StringRef, 64> Worklist;
263 for (auto &F : DestModule) {
264 if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
265 continue;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000266 findExternalCalls(DestModule, F, Index, CalledFunctions, Worklist);
Mehdi Aminic8c55172015-12-03 02:37:33 +0000267 }
268 if (Worklist.empty())
269 return false;
270
271 /// Second step: for every call to an external function, try to import it.
272
273 // Linker that will be used for importing function
274 Linker TheLinker(DestModule, DiagnosticHandler);
275
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000276 // Map of Module -> List of Function to import from the Module
277 std::map<StringRef, std::pair<Module *, DenseSet<const GlobalValue *>>>
278 ModuleToFunctionsToImportMap;
Mehdi Aminic8c55172015-12-03 02:37:33 +0000279
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000280 // Analyze the summaries and get the list of functions to import by
281 // populating ModuleToFunctionsToImportMap
282 ModuleLazyLoaderCache ModuleLoaderCache(ModuleLoader);
283 GetImportList(DestModule, Worklist, CalledFunctions,
284 ModuleToFunctionsToImportMap, Index, ModuleLoaderCache);
285 assert(Worklist.empty() && "Worklist hasn't been flushed in GetImportList");
286
287 // Do the actual import of functions now, one Module at a time
288 for (auto &FunctionsToImportPerModule : ModuleToFunctionsToImportMap) {
289 // Get the module for the import
290 auto &FunctionsToImport = FunctionsToImportPerModule.second.second;
291 auto *SrcModule = FunctionsToImportPerModule.second.first;
292 assert(&DestModule.getContext() == &SrcModule->getContext() &&
293 "Context mismatch");
294
295 // Link in the specified functions.
296 if (TheLinker.linkInModule(*SrcModule, Linker::Flags::None, &Index,
297 &FunctionsToImport))
298 report_fatal_error("Function Import: link error");
299
300 ImportedCount += FunctionsToImport.size();
301 }
302 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000303 << DestModule.getModuleIdentifier() << "\n");
304 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000305}
306
307/// Summary file to use for function importing when using -function-import from
308/// the command line.
309static cl::opt<std::string>
310 SummaryFile("summary-file",
311 cl::desc("The summary file to use for function importing."));
312
313static void diagnosticHandler(const DiagnosticInfo &DI) {
314 raw_ostream &OS = errs();
315 DiagnosticPrinterRawOStream DP(OS);
316 DI.print(DP);
317 OS << '\n';
318}
319
320/// Parse the function index out of an IR file and return the function
321/// index object if found, or nullptr if not.
322static std::unique_ptr<FunctionInfoIndex>
323getFunctionIndexForFile(StringRef Path, std::string &Error,
324 DiagnosticHandlerFunction DiagnosticHandler) {
325 std::unique_ptr<MemoryBuffer> Buffer;
326 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
327 MemoryBuffer::getFile(Path);
328 if (std::error_code EC = BufferOrErr.getError()) {
329 Error = EC.message();
330 return nullptr;
331 }
332 Buffer = std::move(BufferOrErr.get());
333 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
334 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
335 DiagnosticHandler);
336 if (std::error_code EC = ObjOrErr.getError()) {
337 Error = EC.message();
338 return nullptr;
339 }
340 return (*ObjOrErr)->takeIndex();
341}
342
343/// Pass that performs cross-module function import provided a summary file.
344class FunctionImportPass : public ModulePass {
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000345 /// Optional function summary index to use for importing, otherwise
346 /// the summary-file option must be specified.
Teresa Johnson7f961e12015-12-09 19:39:47 +0000347 const FunctionInfoIndex *Index;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000348
349public:
350 /// Pass identification, replacement for typeid
351 static char ID;
352
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000353 /// Specify pass name for debug output
354 const char *getPassName() const override {
355 return "Function Importing";
356 }
357
Teresa Johnson7f961e12015-12-09 19:39:47 +0000358 explicit FunctionImportPass(const FunctionInfoIndex *Index = nullptr)
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000359 : ModulePass(ID), Index(Index) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000360
361 bool runOnModule(Module &M) override {
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000362 if (SummaryFile.empty() && !Index)
363 report_fatal_error("error: -function-import requires -summary-file or "
364 "file from frontend\n");
365 std::unique_ptr<FunctionInfoIndex> IndexPtr;
366 if (!SummaryFile.empty()) {
367 if (Index)
368 report_fatal_error("error: -summary-file and index from frontend\n");
369 std::string Error;
370 IndexPtr = getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
371 if (!IndexPtr) {
372 errs() << "Error loading file '" << SummaryFile << "': " << Error
373 << "\n";
374 return false;
375 }
376 Index = IndexPtr.get();
Mehdi Amini42418ab2015-11-24 06:07:49 +0000377 }
378
379 // Perform the import now.
Mehdi Aminid16c8062015-12-08 22:39:40 +0000380 auto ModuleLoader = [&M](StringRef Identifier) {
381 return loadFile(Identifier, M.getContext());
382 };
383 FunctionImporter Importer(*Index, diagnosticHandler, ModuleLoader);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000384 return Importer.importFunctions(M);
385
386 return false;
387 }
388};
389
390char FunctionImportPass::ID = 0;
391INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
392 "Summary Based Function Import", false, false)
393INITIALIZE_PASS_END(FunctionImportPass, "function-import",
394 "Summary Based Function Import", false, false)
395
396namespace llvm {
Teresa Johnson7f961e12015-12-09 19:39:47 +0000397Pass *createFunctionImportPass(const FunctionInfoIndex *Index = nullptr) {
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000398 return new FunctionImportPass(Index);
399}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000400}