blob: 0187528153b542602d9656db2aea28a600a140e6 [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"
27using namespace llvm;
28
29#define DEBUG_TYPE "function-import"
30
Teresa Johnson39303612015-11-24 22:55:46 +000031/// Limit on instruction count of imported functions.
32static 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"));
35
Mehdi Amini42418ab2015-11-24 06:07:49 +000036// Load lazily a module from \p FileName in \p Context.
37static std::unique_ptr<Module> loadFile(const std::string &FileName,
38 LLVMContext &Context) {
39 SMDiagnostic Err;
40 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
41 std::unique_ptr<Module> Result = getLazyIRFileModule(FileName, Err, Context);
42 if (!Result) {
43 Err.print("function-import", errs());
44 return nullptr;
45 }
46
47 Result->materializeMetadata();
48 UpgradeDebugInfo(*Result);
49
50 return Result;
51}
52
53// Get a Module for \p FileName from the cache, or load it lazily.
Mehdi Aminia11bdc82015-12-02 02:00:29 +000054Module &ModuleLazyLoaderCache::operator()(StringRef FileName) {
Mehdi Amini42418ab2015-11-24 06:07:49 +000055 auto &Module = ModuleMap[FileName];
56 if (!Module)
57 Module = loadFile(FileName, Context);
58 return *Module;
59}
60
Teresa Johnsond450da32015-11-24 21:15:19 +000061/// 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.
64static void findExternalCalls(const Function &F, StringSet<> &CalledFunctions,
65 SmallVector<StringRef, 64> &Worklist) {
66 for (auto &BB : F) {
67 for (auto &I : BB) {
68 if (isa<CallInst>(I)) {
Teresa Johnsond450da32015-11-24 21:15:19 +000069 auto CalledFunction = cast<CallInst>(I).getCalledFunction();
70 // Insert any new external calls that have not already been
71 // added to set/worklist.
72 if (CalledFunction && CalledFunction->hasName() &&
73 CalledFunction->isDeclaration() &&
74 !CalledFunctions.count(CalledFunction->getName())) {
75 CalledFunctions.insert(CalledFunction->getName());
76 Worklist.push_back(CalledFunction->getName());
77 }
78 }
79 }
80 }
81}
82
Mehdi Amini42418ab2015-11-24 06:07:49 +000083
Mehdi Aminic8c55172015-12-03 02:37:33 +000084// Helper function: given a worklist and an index, will process all the worklist
85// and import them based on the summary information
86static unsigned ProcessImportWorklist(Module &DestModule, SmallVector<StringRef, 64> &Worklist,
87 StringSet<> &CalledFunctions,
88 Linker &TheLinker, const FunctionInfoIndex &Index,
89 std::function<Module &(StringRef FileName)> &LazyModuleLoader) {
90 unsigned ImportCount = 0;
Mehdi Amini42418ab2015-11-24 06:07:49 +000091 while (!Worklist.empty()) {
92 auto CalledFunctionName = Worklist.pop_back_val();
93 DEBUG(dbgs() << "Process import for " << CalledFunctionName << "\n");
94
95 // Try to get a summary for this function call.
96 auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
97 if (InfoList == Index.end()) {
98 DEBUG(dbgs() << "No summary for " << CalledFunctionName
99 << " Ignoring.\n");
100 continue;
101 }
102 assert(!InfoList->second.empty() && "No summary, error at import?");
103
104 // Comdat can have multiple entries, FIXME: what do we do with them?
105 auto &Info = InfoList->second[0];
106 assert(Info && "Nullptr in list, error importing summaries?\n");
107
108 auto *Summary = Info->functionSummary();
109 if (!Summary) {
110 // FIXME: in case we are lazyloading summaries, we can do it now.
Teresa Johnson430110c2015-12-01 17:12:10 +0000111 DEBUG(dbgs() << "Missing summary for " << CalledFunctionName
112 << ", error at import?\n");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000113 llvm_unreachable("Missing summary");
114 }
115
Teresa Johnson39303612015-11-24 22:55:46 +0000116 if (Summary->instCount() > ImportInstrLimit) {
Teresa Johnson430110c2015-12-01 17:12:10 +0000117 DEBUG(dbgs() << "Skip import of " << CalledFunctionName << " with "
118 << Summary->instCount() << " instructions (limit "
119 << ImportInstrLimit << ")\n");
Teresa Johnson39303612015-11-24 22:55:46 +0000120 continue;
121 }
122
Mehdi Amini42418ab2015-11-24 06:07:49 +0000123 // Get the module path from the summary.
124 auto FileName = Summary->modulePath();
125 DEBUG(dbgs() << "Importing " << CalledFunctionName << " from " << FileName
126 << "\n");
127
128 // Get the module for the import (potentially from the cache).
Mehdi Aminic8c55172015-12-03 02:37:33 +0000129 auto &Module = LazyModuleLoader(FileName);
130 assert(&Module.getContext() == &DestModule.getContext());
Mehdi Amini42418ab2015-11-24 06:07:49 +0000131
132 // The function that we will import!
133 GlobalValue *SGV = Module.getNamedValue(CalledFunctionName);
Teresa Johnson130de7a2015-11-24 19:55:04 +0000134 StringRef ImportFunctionName = CalledFunctionName;
135 if (!SGV) {
Mehdi Aminic8c55172015-12-03 02:37:33 +0000136 // Might be local in source Module, promoted/renamed in DestModule.
Teresa Johnson130de7a2015-11-24 19:55:04 +0000137 std::pair<StringRef, StringRef> Split =
138 CalledFunctionName.split(".llvm.");
139 SGV = Module.getNamedValue(Split.first);
140#ifndef NDEBUG
141 // Assert that Split.second is module id
142 uint64_t ModuleId;
143 assert(!Split.second.getAsInteger(10, ModuleId));
144 assert(ModuleId == Index.getModuleId(FileName));
145#endif
146 }
Mehdi Amini42418ab2015-11-24 06:07:49 +0000147 Function *F = dyn_cast<Function>(SGV);
148 if (!F && isa<GlobalAlias>(SGV)) {
149 auto *SGA = dyn_cast<GlobalAlias>(SGV);
150 F = dyn_cast<Function>(SGA->getBaseObject());
Teresa Johnson130de7a2015-11-24 19:55:04 +0000151 ImportFunctionName = F->getName();
Mehdi Amini42418ab2015-11-24 06:07:49 +0000152 }
153 if (!F) {
154 errs() << "Can't load function '" << CalledFunctionName << "' in Module '"
155 << FileName << "', error in the summary?\n";
156 llvm_unreachable("Can't load function in Module");
157 }
158
Teresa Johnson17626652015-11-24 16:10:43 +0000159 // We cannot import weak_any functions/aliases without possibly affecting
160 // the order they are seen and selected by the linker, changing program
Mehdi Amini42418ab2015-11-24 06:07:49 +0000161 // semantics.
Teresa Johnson17626652015-11-24 16:10:43 +0000162 if (SGV->hasWeakAnyLinkage()) {
163 DEBUG(dbgs() << "Ignoring import request for weak-any "
164 << (isa<Function>(SGV) ? "function " : "alias ")
Mehdi Amini42418ab2015-11-24 06:07:49 +0000165 << CalledFunctionName << " from " << FileName << "\n");
166 continue;
167 }
168
169 // Link in the specified function.
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000170 DenseSet<const GlobalValue *> FunctionsToImport;
171 FunctionsToImport.insert(F);
Mehdi Aminic8c55172015-12-03 02:37:33 +0000172 if (TheLinker.linkInModule(Module, Linker::Flags::None, &Index,
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000173 &FunctionsToImport))
Mehdi Amini42418ab2015-11-24 06:07:49 +0000174 report_fatal_error("Function Import: link error");
175
Teresa Johnson130de7a2015-11-24 19:55:04 +0000176 // Process the newly imported function and add callees to the worklist.
Mehdi Aminic8c55172015-12-03 02:37:33 +0000177 GlobalValue *NewGV = DestModule.getNamedValue(ImportFunctionName);
Teresa Johnson130de7a2015-11-24 19:55:04 +0000178 assert(NewGV);
179 Function *NewF = dyn_cast<Function>(NewGV);
180 assert(NewF);
Teresa Johnsond450da32015-11-24 21:15:19 +0000181 findExternalCalls(*NewF, CalledFunctions, Worklist);
Mehdi Aminic8c55172015-12-03 02:37:33 +0000182 ++ImportCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000183 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000184 return ImportCount;
185}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000186
Mehdi Aminic8c55172015-12-03 02:37:33 +0000187// Automatically import functions in Module \p DestModule based on the summaries
188// index.
189//
190// The current implementation imports every called functions that exists in the
191// summaries index.
192bool FunctionImporter::importFunctions(Module &DestModule) {
193 DEBUG(errs() << "Starting import for Module " << DestModule.getModuleIdentifier()
194 << "\n");
195 unsigned ImportedCount = 0;
196
197 /// First step is collecting the called external functions.
198 StringSet<> CalledFunctions;
199 SmallVector<StringRef, 64> Worklist;
200 for (auto &F : DestModule) {
201 if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
202 continue;
203 findExternalCalls(F, CalledFunctions, Worklist);
204 }
205 if (Worklist.empty())
206 return false;
207
208 /// Second step: for every call to an external function, try to import it.
209
210 // Linker that will be used for importing function
211 Linker TheLinker(DestModule, DiagnosticHandler);
212
213 ImportedCount += ProcessImportWorklist(DestModule, Worklist, CalledFunctions, TheLinker, Index, getLazyModule );
214
215 DEBUG(errs() << "Imported " << ImportedCount << " functions for Module "
216 << DestModule.getModuleIdentifier() << "\n");
217 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000218}
219
220/// Summary file to use for function importing when using -function-import from
221/// the command line.
222static cl::opt<std::string>
223 SummaryFile("summary-file",
224 cl::desc("The summary file to use for function importing."));
225
226static void diagnosticHandler(const DiagnosticInfo &DI) {
227 raw_ostream &OS = errs();
228 DiagnosticPrinterRawOStream DP(OS);
229 DI.print(DP);
230 OS << '\n';
231}
232
233/// Parse the function index out of an IR file and return the function
234/// index object if found, or nullptr if not.
235static std::unique_ptr<FunctionInfoIndex>
236getFunctionIndexForFile(StringRef Path, std::string &Error,
237 DiagnosticHandlerFunction DiagnosticHandler) {
238 std::unique_ptr<MemoryBuffer> Buffer;
239 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
240 MemoryBuffer::getFile(Path);
241 if (std::error_code EC = BufferOrErr.getError()) {
242 Error = EC.message();
243 return nullptr;
244 }
245 Buffer = std::move(BufferOrErr.get());
246 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
247 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
248 DiagnosticHandler);
249 if (std::error_code EC = ObjOrErr.getError()) {
250 Error = EC.message();
251 return nullptr;
252 }
253 return (*ObjOrErr)->takeIndex();
254}
255
256/// Pass that performs cross-module function import provided a summary file.
257class FunctionImportPass : public ModulePass {
258
259public:
260 /// Pass identification, replacement for typeid
261 static char ID;
262
263 explicit FunctionImportPass() : ModulePass(ID) {}
264
265 bool runOnModule(Module &M) override {
266 if (SummaryFile.empty()) {
267 report_fatal_error("error: -function-import requires -summary-file\n");
268 }
269 std::string Error;
270 std::unique_ptr<FunctionInfoIndex> Index =
271 getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
272 if (!Index) {
273 errs() << "Error loading file '" << SummaryFile << "': " << Error << "\n";
274 return false;
275 }
276
277 // Perform the import now.
Mehdi Aminia11bdc82015-12-02 02:00:29 +0000278 ModuleLazyLoaderCache Loader(M.getContext());
279 FunctionImporter Importer(*Index, diagnosticHandler,
280 [&](StringRef Name)
281 -> Module &{ return Loader(Name); });
Mehdi Amini42418ab2015-11-24 06:07:49 +0000282 return Importer.importFunctions(M);
283
284 return false;
285 }
286};
287
288char FunctionImportPass::ID = 0;
289INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
290 "Summary Based Function Import", false, false)
291INITIALIZE_PASS_END(FunctionImportPass, "function-import",
292 "Summary Based Function Import", false, false)
293
294namespace llvm {
295Pass *createFunctionImportPass() { return new FunctionImportPass(); }
296}