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 /// 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"));
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) {
40 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
41 std::unique_ptr<Module> Result = getLazyIRFileModule(FileName, Err, Context);
43 Err.print("function-import", errs());
47 Result->materializeMetadata();
48 UpgradeDebugInfo(*Result);
53 // Get a Module for \p FileName from the cache, or load it lazily.
54 Module &FunctionImporter::getOrLoadModule(StringRef FileName) {
55 auto &Module = ModuleMap[FileName];
57 Module = loadFile(FileName, Context);
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) {
68 if (isa<CallInst>(I)) {
69 DEBUG(dbgs() << "Found a call: '" << I << "'\n");
70 auto CalledFunction = cast<CallInst>(I).getCalledFunction();
71 // Insert any new external calls that have not already been
72 // added to set/worklist.
73 if (CalledFunction && CalledFunction->hasName() &&
74 CalledFunction->isDeclaration() &&
75 !CalledFunctions.count(CalledFunction->getName())) {
76 CalledFunctions.insert(CalledFunction->getName());
77 Worklist.push_back(CalledFunction->getName());
84 // Automatically import functions in Module \p M based on the summaries index.
86 // The current implementation imports every called functions that exists in the
88 bool FunctionImporter::importFunctions(Module &M) {
89 assert(&Context == &M.getContext());
93 /// First step is collecting the called external functions.
94 StringSet<> CalledFunctions;
95 SmallVector<StringRef, 64> Worklist;
97 if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
99 findExternalCalls(F, CalledFunctions, Worklist);
102 /// Second step: for every call to an external function, try to import it.
104 // Linker that will be used for importing function
105 Linker L(M, DiagnosticHandler);
107 while (!Worklist.empty()) {
108 auto CalledFunctionName = Worklist.pop_back_val();
109 DEBUG(dbgs() << "Process import for " << CalledFunctionName << "\n");
111 // Try to get a summary for this function call.
112 auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
113 if (InfoList == Index.end()) {
114 DEBUG(dbgs() << "No summary for " << CalledFunctionName
118 assert(!InfoList->second.empty() && "No summary, error at import?");
120 // Comdat can have multiple entries, FIXME: what do we do with them?
121 auto &Info = InfoList->second[0];
122 assert(Info && "Nullptr in list, error importing summaries?\n");
124 auto *Summary = Info->functionSummary();
126 // FIXME: in case we are lazyloading summaries, we can do it now.
127 DEBUG(dbgs() << "Missing summary for " << CalledFunctionName
128 << ", error at import?\n");
129 llvm_unreachable("Missing summary");
132 if (Summary->instCount() > ImportInstrLimit) {
133 DEBUG(dbgs() << "Skip import of " << CalledFunctionName << " with "
134 << Summary->instCount() << " instructions (limit "
135 << ImportInstrLimit << ")\n");
139 // Get the module path from the summary.
140 auto FileName = Summary->modulePath();
141 DEBUG(dbgs() << "Importing " << CalledFunctionName << " from " << FileName
144 // Get the module for the import (potentially from the cache).
145 auto &Module = getOrLoadModule(FileName);
147 // The function that we will import!
148 GlobalValue *SGV = Module.getNamedValue(CalledFunctionName);
149 StringRef ImportFunctionName = CalledFunctionName;
151 // Might be local in source Module, promoted/renamed in dest Module M.
152 std::pair<StringRef, StringRef> Split =
153 CalledFunctionName.split(".llvm.");
154 SGV = Module.getNamedValue(Split.first);
156 // Assert that Split.second is module id
158 assert(!Split.second.getAsInteger(10, ModuleId));
159 assert(ModuleId == Index.getModuleId(FileName));
162 Function *F = dyn_cast<Function>(SGV);
163 if (!F && isa<GlobalAlias>(SGV)) {
164 auto *SGA = dyn_cast<GlobalAlias>(SGV);
165 F = dyn_cast<Function>(SGA->getBaseObject());
166 ImportFunctionName = F->getName();
169 errs() << "Can't load function '" << CalledFunctionName << "' in Module '"
170 << FileName << "', error in the summary?\n";
171 llvm_unreachable("Can't load function in Module");
174 // We cannot import weak_any functions/aliases without possibly affecting
175 // the order they are seen and selected by the linker, changing program
177 if (SGV->hasWeakAnyLinkage()) {
178 DEBUG(dbgs() << "Ignoring import request for weak-any "
179 << (isa<Function>(SGV) ? "function " : "alias ")
180 << CalledFunctionName << " from " << FileName << "\n");
184 // Link in the specified function.
185 if (L.linkInModule(Module, Linker::Flags::None, &Index, F))
186 report_fatal_error("Function Import: link error");
188 // Process the newly imported function and add callees to the worklist.
189 GlobalValue *NewGV = M.getNamedValue(ImportFunctionName);
191 Function *NewF = dyn_cast<Function>(NewGV);
193 findExternalCalls(*NewF, CalledFunctions, Worklist);
200 /// Summary file to use for function importing when using -function-import from
201 /// the command line.
202 static cl::opt<std::string>
203 SummaryFile("summary-file",
204 cl::desc("The summary file to use for function importing."));
206 static void diagnosticHandler(const DiagnosticInfo &DI) {
207 raw_ostream &OS = errs();
208 DiagnosticPrinterRawOStream DP(OS);
213 /// Parse the function index out of an IR file and return the function
214 /// index object if found, or nullptr if not.
215 static std::unique_ptr<FunctionInfoIndex>
216 getFunctionIndexForFile(StringRef Path, std::string &Error,
217 DiagnosticHandlerFunction DiagnosticHandler) {
218 std::unique_ptr<MemoryBuffer> Buffer;
219 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
220 MemoryBuffer::getFile(Path);
221 if (std::error_code EC = BufferOrErr.getError()) {
222 Error = EC.message();
225 Buffer = std::move(BufferOrErr.get());
226 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
227 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
229 if (std::error_code EC = ObjOrErr.getError()) {
230 Error = EC.message();
233 return (*ObjOrErr)->takeIndex();
236 /// Pass that performs cross-module function import provided a summary file.
237 class FunctionImportPass : public ModulePass {
240 /// Pass identification, replacement for typeid
243 explicit FunctionImportPass() : ModulePass(ID) {}
245 bool runOnModule(Module &M) override {
246 if (SummaryFile.empty()) {
247 report_fatal_error("error: -function-import requires -summary-file\n");
250 std::unique_ptr<FunctionInfoIndex> Index =
251 getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
253 errs() << "Error loading file '" << SummaryFile << "': " << Error << "\n";
257 // Perform the import now.
258 FunctionImporter Importer(M.getContext(), *Index, diagnosticHandler);
259 return Importer.importFunctions(M);
265 char FunctionImportPass::ID = 0;
266 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
267 "Summary Based Function Import", false, false)
268 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
269 "Summary Based Function Import", false, false)
272 Pass *createFunctionImportPass() { return new FunctionImportPass(); }