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 /// Walk through the instructions in \p F looking for external
57 /// calls not already in the \p CalledFunctions set. If any are
58 /// found they are added to the \p Worklist for importing.
59 static void findExternalCalls(const Function &F, StringSet<> &CalledFunctions,
60 SmallVector<StringRef, 64> &Worklist) {
63 if (isa<CallInst>(I)) {
64 DEBUG(dbgs() << "Found a call: '" << I << "'\n");
65 auto CalledFunction = cast<CallInst>(I).getCalledFunction();
66 // Insert any new external calls that have not already been
67 // added to set/worklist.
68 if (CalledFunction && CalledFunction->hasName() &&
69 CalledFunction->isDeclaration() &&
70 !CalledFunctions.count(CalledFunction->getName())) {
71 CalledFunctions.insert(CalledFunction->getName());
72 Worklist.push_back(CalledFunction->getName());
79 // Automatically import functions in Module \p M based on the summaries index.
81 // The current implementation imports every called functions that exists in the
83 bool FunctionImporter::importFunctions(Module &M) {
84 assert(&Context == &M.getContext());
88 /// First step is collecting the called external functions.
89 StringSet<> CalledFunctions;
90 SmallVector<StringRef, 64> Worklist;
92 if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
94 findExternalCalls(F, CalledFunctions, Worklist);
97 /// Second step: for every call to an external function, try to import it.
99 // Linker that will be used for importing function
100 Linker L(&M, DiagnosticHandler);
102 while (!Worklist.empty()) {
103 auto CalledFunctionName = Worklist.pop_back_val();
104 DEBUG(dbgs() << "Process import for " << CalledFunctionName << "\n");
106 // Try to get a summary for this function call.
107 auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
108 if (InfoList == Index.end()) {
109 DEBUG(dbgs() << "No summary for " << CalledFunctionName
113 assert(!InfoList->second.empty() && "No summary, error at import?");
115 // Comdat can have multiple entries, FIXME: what do we do with them?
116 auto &Info = InfoList->second[0];
117 assert(Info && "Nullptr in list, error importing summaries?\n");
119 auto *Summary = Info->functionSummary();
121 // FIXME: in case we are lazyloading summaries, we can do it now.
122 dbgs() << "Missing summary for " << CalledFunctionName
123 << ", error at import?\n";
124 llvm_unreachable("Missing summary");
128 // No profitability notion right now, just import all the time...
131 // Get the module path from the summary.
132 auto FileName = Summary->modulePath();
133 DEBUG(dbgs() << "Importing " << CalledFunctionName << " from " << FileName
136 // Get the module for the import (potentially from the cache).
137 auto &Module = getOrLoadModule(FileName);
139 // The function that we will import!
140 GlobalValue *SGV = Module.getNamedValue(CalledFunctionName);
141 StringRef ImportFunctionName = CalledFunctionName;
143 // Might be local in source Module, promoted/renamed in dest Module M.
144 std::pair<StringRef, StringRef> Split =
145 CalledFunctionName.split(".llvm.");
146 SGV = Module.getNamedValue(Split.first);
148 // Assert that Split.second is module id
150 assert(!Split.second.getAsInteger(10, ModuleId));
151 assert(ModuleId == Index.getModuleId(FileName));
154 Function *F = dyn_cast<Function>(SGV);
155 if (!F && isa<GlobalAlias>(SGV)) {
156 auto *SGA = dyn_cast<GlobalAlias>(SGV);
157 F = dyn_cast<Function>(SGA->getBaseObject());
158 ImportFunctionName = F->getName();
161 errs() << "Can't load function '" << CalledFunctionName << "' in Module '"
162 << FileName << "', error in the summary?\n";
163 llvm_unreachable("Can't load function in Module");
166 // We cannot import weak_any functions/aliases without possibly affecting
167 // the order they are seen and selected by the linker, changing program
169 if (SGV->hasWeakAnyLinkage()) {
170 DEBUG(dbgs() << "Ignoring import request for weak-any "
171 << (isa<Function>(SGV) ? "function " : "alias ")
172 << CalledFunctionName << " from " << FileName << "\n");
176 // Link in the specified function.
177 if (L.linkInModule(&Module, Linker::Flags::None, &Index, F))
178 report_fatal_error("Function Import: link error");
180 // Process the newly imported function and add callees to the worklist.
181 GlobalValue *NewGV = M.getNamedValue(ImportFunctionName);
183 Function *NewF = dyn_cast<Function>(NewGV);
185 findExternalCalls(*NewF, CalledFunctions, Worklist);
192 /// Summary file to use for function importing when using -function-import from
193 /// the command line.
194 static cl::opt<std::string>
195 SummaryFile("summary-file",
196 cl::desc("The summary file to use for function importing."));
198 static void diagnosticHandler(const DiagnosticInfo &DI) {
199 raw_ostream &OS = errs();
200 DiagnosticPrinterRawOStream DP(OS);
205 /// Parse the function index out of an IR file and return the function
206 /// index object if found, or nullptr if not.
207 static std::unique_ptr<FunctionInfoIndex>
208 getFunctionIndexForFile(StringRef Path, std::string &Error,
209 DiagnosticHandlerFunction DiagnosticHandler) {
210 std::unique_ptr<MemoryBuffer> Buffer;
211 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
212 MemoryBuffer::getFile(Path);
213 if (std::error_code EC = BufferOrErr.getError()) {
214 Error = EC.message();
217 Buffer = std::move(BufferOrErr.get());
218 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
219 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
221 if (std::error_code EC = ObjOrErr.getError()) {
222 Error = EC.message();
225 return (*ObjOrErr)->takeIndex();
228 /// Pass that performs cross-module function import provided a summary file.
229 class FunctionImportPass : public ModulePass {
232 /// Pass identification, replacement for typeid
235 explicit FunctionImportPass() : ModulePass(ID) {}
237 bool runOnModule(Module &M) override {
238 if (SummaryFile.empty()) {
239 report_fatal_error("error: -function-import requires -summary-file\n");
242 std::unique_ptr<FunctionInfoIndex> Index =
243 getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
245 errs() << "Error loading file '" << SummaryFile << "': " << Error << "\n";
249 // Perform the import now.
250 FunctionImporter Importer(M.getContext(), *Index, diagnosticHandler);
251 return Importer.importFunctions(M);
257 char FunctionImportPass::ID = 0;
258 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
259 "Summary Based Function Import", false, false)
260 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
261 "Summary Based Function Import", false, false)
264 Pass *createFunctionImportPass() { return new FunctionImportPass(); }