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 /// Walk through the instructions in \p F looking for external
54 /// calls not already in the \p CalledFunctions set. If any are
55 /// found they are added to the \p Worklist for importing.
56 static void findExternalCalls(const Function &F, StringSet<> &CalledFunctions,
57 SmallVector<StringRef, 64> &Worklist) {
60 if (isa<CallInst>(I)) {
61 auto CalledFunction = cast<CallInst>(I).getCalledFunction();
62 // Insert any new external calls that have not already been
63 // added to set/worklist.
64 if (CalledFunction && CalledFunction->hasName() &&
65 CalledFunction->isDeclaration() &&
66 !CalledFunctions.count(CalledFunction->getName())) {
67 CalledFunctions.insert(CalledFunction->getName());
68 Worklist.push_back(CalledFunction->getName());
75 // Helper function: given a worklist and an index, will process all the worklist
76 // and import them based on the summary information
77 static unsigned ProcessImportWorklist(
78 Module &DestModule, SmallVector<StringRef, 64> &Worklist,
79 StringSet<> &CalledFunctions, Linker &TheLinker,
80 const FunctionInfoIndex &Index,
81 std::function<std::unique_ptr<Module>(StringRef FileName)> &
83 unsigned ImportCount = 0;
84 while (!Worklist.empty()) {
85 auto CalledFunctionName = Worklist.pop_back_val();
86 DEBUG(dbgs() << "Process import for " << CalledFunctionName << "\n");
88 // Try to get a summary for this function call.
89 auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
90 if (InfoList == Index.end()) {
91 DEBUG(dbgs() << "No summary for " << CalledFunctionName
95 assert(!InfoList->second.empty() && "No summary, error at import?");
97 // Comdat can have multiple entries, FIXME: what do we do with them?
98 auto &Info = InfoList->second[0];
99 assert(Info && "Nullptr in list, error importing summaries?\n");
101 auto *Summary = Info->functionSummary();
103 // FIXME: in case we are lazyloading summaries, we can do it now.
104 DEBUG(dbgs() << "Missing summary for " << CalledFunctionName
105 << ", error at import?\n");
106 llvm_unreachable("Missing summary");
109 if (Summary->instCount() > ImportInstrLimit) {
110 DEBUG(dbgs() << "Skip import of " << CalledFunctionName << " with "
111 << Summary->instCount() << " instructions (limit "
112 << ImportInstrLimit << ")\n");
116 // Get the module path from the summary.
117 auto FileName = Summary->modulePath();
118 DEBUG(dbgs() << "Importing " << CalledFunctionName << " from " << FileName
121 // Get the module for the import
122 auto SrcModule = LazyModuleLoader(FileName);
123 assert(&SrcModule->getContext() == &DestModule.getContext());
125 // The function that we will import!
126 GlobalValue *SGV = SrcModule->getNamedValue(CalledFunctionName);
127 StringRef ImportFunctionName = CalledFunctionName;
129 // Might be local in source Module, promoted/renamed in DestModule.
130 std::pair<StringRef, StringRef> Split =
131 CalledFunctionName.split(".llvm.");
132 SGV = SrcModule->getNamedValue(Split.first);
134 // Assert that Split.second is module id
136 assert(!Split.second.getAsInteger(10, ModuleId));
137 assert(ModuleId == Index.getModuleId(FileName));
140 Function *F = dyn_cast<Function>(SGV);
141 if (!F && isa<GlobalAlias>(SGV)) {
142 auto *SGA = dyn_cast<GlobalAlias>(SGV);
143 F = dyn_cast<Function>(SGA->getBaseObject());
144 ImportFunctionName = F->getName();
147 errs() << "Can't load function '" << CalledFunctionName << "' in Module '"
148 << FileName << "', error in the summary?\n";
149 llvm_unreachable("Can't load function in Module");
152 // We cannot import weak_any functions/aliases without possibly affecting
153 // the order they are seen and selected by the linker, changing program
155 if (SGV->hasWeakAnyLinkage()) {
156 DEBUG(dbgs() << "Ignoring import request for weak-any "
157 << (isa<Function>(SGV) ? "function " : "alias ")
158 << CalledFunctionName << " from " << FileName << "\n");
162 // Link in the specified function.
163 DenseSet<const GlobalValue *> FunctionsToImport;
164 FunctionsToImport.insert(F);
165 if (TheLinker.linkInModule(*SrcModule, Linker::Flags::None, &Index,
167 report_fatal_error("Function Import: link error");
169 // Process the newly imported function and add callees to the worklist.
170 GlobalValue *NewGV = DestModule.getNamedValue(ImportFunctionName);
172 Function *NewF = dyn_cast<Function>(NewGV);
174 findExternalCalls(*NewF, CalledFunctions, Worklist);
180 // Automatically import functions in Module \p DestModule based on the summaries
183 // The current implementation imports every called functions that exists in the
185 bool FunctionImporter::importFunctions(Module &DestModule) {
186 DEBUG(errs() << "Starting import for Module "
187 << DestModule.getModuleIdentifier() << "\n");
188 unsigned ImportedCount = 0;
190 /// First step is collecting the called external functions.
191 StringSet<> CalledFunctions;
192 SmallVector<StringRef, 64> Worklist;
193 for (auto &F : DestModule) {
194 if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
196 findExternalCalls(F, CalledFunctions, Worklist);
198 if (Worklist.empty())
201 /// Second step: for every call to an external function, try to import it.
203 // Linker that will be used for importing function
204 Linker TheLinker(DestModule, DiagnosticHandler);
206 ImportedCount += ProcessImportWorklist(DestModule, Worklist, CalledFunctions,
207 TheLinker, Index, ModuleLoader);
209 DEBUG(errs() << "Imported " << ImportedCount << " functions for Module "
210 << DestModule.getModuleIdentifier() << "\n");
211 return ImportedCount;
214 /// Summary file to use for function importing when using -function-import from
215 /// the command line.
216 static cl::opt<std::string>
217 SummaryFile("summary-file",
218 cl::desc("The summary file to use for function importing."));
220 static void diagnosticHandler(const DiagnosticInfo &DI) {
221 raw_ostream &OS = errs();
222 DiagnosticPrinterRawOStream DP(OS);
227 /// Parse the function index out of an IR file and return the function
228 /// index object if found, or nullptr if not.
229 static std::unique_ptr<FunctionInfoIndex>
230 getFunctionIndexForFile(StringRef Path, std::string &Error,
231 DiagnosticHandlerFunction DiagnosticHandler) {
232 std::unique_ptr<MemoryBuffer> Buffer;
233 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
234 MemoryBuffer::getFile(Path);
235 if (std::error_code EC = BufferOrErr.getError()) {
236 Error = EC.message();
239 Buffer = std::move(BufferOrErr.get());
240 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
241 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
243 if (std::error_code EC = ObjOrErr.getError()) {
244 Error = EC.message();
247 return (*ObjOrErr)->takeIndex();
250 /// Pass that performs cross-module function import provided a summary file.
251 class FunctionImportPass : public ModulePass {
252 /// Optional function summary index to use for importing, otherwise
253 /// the summary-file option must be specified.
254 FunctionInfoIndex *Index;
257 /// Pass identification, replacement for typeid
260 /// Specify pass name for debug output
261 const char *getPassName() const override {
262 return "Function Importing";
265 explicit FunctionImportPass(FunctionInfoIndex *Index = nullptr)
266 : ModulePass(ID), Index(Index) {}
268 bool runOnModule(Module &M) override {
269 if (SummaryFile.empty() && !Index)
270 report_fatal_error("error: -function-import requires -summary-file or "
271 "file from frontend\n");
272 std::unique_ptr<FunctionInfoIndex> IndexPtr;
273 if (!SummaryFile.empty()) {
275 report_fatal_error("error: -summary-file and index from frontend\n");
277 IndexPtr = getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
279 errs() << "Error loading file '" << SummaryFile << "': " << Error
283 Index = IndexPtr.get();
286 // Perform the import now.
287 auto ModuleLoader = [&M](StringRef Identifier) {
288 return loadFile(Identifier, M.getContext());
290 FunctionImporter Importer(*Index, diagnosticHandler, ModuleLoader);
291 return Importer.importFunctions(M);
297 char FunctionImportPass::ID = 0;
298 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
299 "Summary Based Function Import", false, false)
300 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
301 "Summary Based Function Import", false, false)
304 Pass *createFunctionImportPass(FunctionInfoIndex *Index = nullptr) {
305 return new FunctionImportPass(Index);