1 //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Function import based on summaries.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/IPO/FunctionImport.h"
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"
29 #define DEBUG_TYPE "function-import"
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) {
35 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
36 std::unique_ptr<Module> Result = getLazyIRFileModule(FileName, Err, Context);
38 Err.print("function-import", errs());
42 Result->materializeMetadata();
43 UpgradeDebugInfo(*Result);
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];
52 Module = loadFile(FileName, Context);
56 // Automatically import functions in Module \p M based on the summaries index.
58 // The current implementation imports every called functions that exists in the
60 bool FunctionImporter::importFunctions(Module &M) {
61 assert(&Context == &M.getContext());
65 /// First step is collecting the called functions and the one defined in this
67 StringSet<> CalledFunctions;
69 if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
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());
84 /// Second step: for every call to an external function, try to import it.
86 // Linker that will be used for importing function
87 Linker L(&M, DiagnosticHandler);
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());
95 while (!Worklist.empty()) {
96 auto CalledFunctionName = Worklist.pop_back_val();
97 DEBUG(dbgs() << "Process import for " << CalledFunctionName << "\n");
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
106 assert(!InfoList->second.empty() && "No summary, error at import?");
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");
112 auto *Summary = Info->functionSummary();
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");
121 // No profitability notion right now, just import all the time...
124 // Get the module path from the summary.
125 auto FileName = Summary->modulePath();
126 DEBUG(dbgs() << "Importing " << CalledFunctionName << " from " << FileName
129 // Get the module for the import (potentially from the cache).
130 auto &Module = getOrLoadModule(FileName);
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());
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");
145 // We cannot import weak_any functions/aliases without possibly affecting
146 // the order they are seen and selected by the linker, changing program
148 if (SGV->hasWeakAnyLinkage()) {
149 DEBUG(dbgs() << "Ignoring import request for weak-any "
150 << (isa<Function>(SGV) ? "function " : "alias ")
151 << CalledFunctionName << " from " << FileName << "\n");
155 // Link in the specified function.
156 if (L.linkInModule(&Module, Linker::Flags::None, &Index, F))
157 report_fatal_error("Function Import: link error");
159 // TODO: Process the newly imported function and add callees to the
167 /// Summary file to use for function importing when using -function-import from
168 /// the command line.
169 static cl::opt<std::string>
170 SummaryFile("summary-file",
171 cl::desc("The summary file to use for function importing."));
173 static void diagnosticHandler(const DiagnosticInfo &DI) {
174 raw_ostream &OS = errs();
175 DiagnosticPrinterRawOStream DP(OS);
180 /// Parse the function index out of an IR file and return the function
181 /// index object if found, or nullptr if not.
182 static std::unique_ptr<FunctionInfoIndex>
183 getFunctionIndexForFile(StringRef Path, std::string &Error,
184 DiagnosticHandlerFunction DiagnosticHandler) {
185 std::unique_ptr<MemoryBuffer> Buffer;
186 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
187 MemoryBuffer::getFile(Path);
188 if (std::error_code EC = BufferOrErr.getError()) {
189 Error = EC.message();
192 Buffer = std::move(BufferOrErr.get());
193 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
194 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
196 if (std::error_code EC = ObjOrErr.getError()) {
197 Error = EC.message();
200 return (*ObjOrErr)->takeIndex();
203 /// Pass that performs cross-module function import provided a summary file.
204 class FunctionImportPass : public ModulePass {
207 /// Pass identification, replacement for typeid
210 explicit FunctionImportPass() : ModulePass(ID) {}
212 bool runOnModule(Module &M) override {
213 if (SummaryFile.empty()) {
214 report_fatal_error("error: -function-import requires -summary-file\n");
217 std::unique_ptr<FunctionInfoIndex> Index =
218 getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
220 errs() << "Error loading file '" << SummaryFile << "': " << Error << "\n";
224 // Perform the import now.
225 FunctionImporter Importer(M.getContext(), *Index, diagnosticHandler);
226 return Importer.importFunctions(M);
232 char FunctionImportPass::ID = 0;
233 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
234 "Summary Based Function Import", false, false)
235 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
236 "Summary Based Function Import", false, false)
239 Pass *createFunctionImportPass() { return new FunctionImportPass(); }