1 //===- 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"
27
28 #include <map>
29
30 using namespace llvm;
31
32 #define DEBUG_TYPE "function-import"
33
34 /// Limit on instruction count of imported functions.
35 static cl::opt<unsigned> ImportInstrLimit(
36 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
37 cl::desc("Only import functions with less than N instructions"));
38
39 // Load lazily a module from \p FileName in \p Context.
loadFile(const std::string & FileName,LLVMContext & Context)40 static std::unique_ptr<Module> loadFile(const std::string &FileName,
41 LLVMContext &Context) {
42 SMDiagnostic Err;
43 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
44 std::unique_ptr<Module> Result = getLazyIRFileModule(FileName, Err, Context);
45 if (!Result) {
46 Err.print("function-import", errs());
47 return nullptr;
48 }
49
50 Result->materializeMetadata();
51 UpgradeDebugInfo(*Result);
52
53 return Result;
54 }
55
56 namespace {
57 /// Helper to load on demand a Module from file and cache it for subsequent
58 /// queries. It can be used with the FunctionImporter.
59 class ModuleLazyLoaderCache {
60 /// Cache of lazily loaded module for import.
61 StringMap<std::unique_ptr<Module>> ModuleMap;
62
63 /// Retrieve a Module from the cache or lazily load it on demand.
64 std::function<std::unique_ptr<Module>(StringRef FileName)> createLazyModule;
65
66 public:
67 /// Create the loader, Module will be initialized in \p Context.
ModuleLazyLoaderCache(std::function<std::unique_ptr<Module> (StringRef FileName)> createLazyModule)68 ModuleLazyLoaderCache(std::function<
69 std::unique_ptr<Module>(StringRef FileName)> createLazyModule)
70 : createLazyModule(createLazyModule) {}
71
72 /// Retrieve a Module from the cache or lazily load it on demand.
73 Module &operator()(StringRef FileName);
74
takeModule(StringRef FileName)75 std::unique_ptr<Module> takeModule(StringRef FileName) {
76 auto I = ModuleMap.find(FileName);
77 assert(I != ModuleMap.end());
78 std::unique_ptr<Module> Ret = std::move(I->second);
79 ModuleMap.erase(I);
80 return Ret;
81 }
82 };
83
84 // Get a Module for \p FileName from the cache, or load it lazily.
operator ()(StringRef Identifier)85 Module &ModuleLazyLoaderCache::operator()(StringRef Identifier) {
86 auto &Module = ModuleMap[Identifier];
87 if (!Module)
88 Module = createLazyModule(Identifier);
89 return *Module;
90 }
91 } // anonymous namespace
92
93 /// Walk through the instructions in \p F looking for external
94 /// calls not already in the \p CalledFunctions set. If any are
95 /// found they are added to the \p Worklist for importing.
findExternalCalls(const Module & DestModule,Function & F,const FunctionInfoIndex & Index,StringSet<> & CalledFunctions,SmallVector<StringRef,64> & Worklist)96 static void findExternalCalls(const Module &DestModule, Function &F,
97 const FunctionInfoIndex &Index,
98 StringSet<> &CalledFunctions,
99 SmallVector<StringRef, 64> &Worklist) {
100 // We need to suffix internal function calls imported from other modules,
101 // prepare the suffix ahead of time.
102 std::string Suffix;
103 if (F.getParent() != &DestModule)
104 Suffix =
105 (Twine(".llvm.") +
106 Twine(Index.getModuleId(F.getParent()->getModuleIdentifier()))).str();
107
108 for (auto &BB : F) {
109 for (auto &I : BB) {
110 if (isa<CallInst>(I)) {
111 auto CalledFunction = cast<CallInst>(I).getCalledFunction();
112 // Insert any new external calls that have not already been
113 // added to set/worklist.
114 if (!CalledFunction || !CalledFunction->hasName())
115 continue;
116 // Ignore intrinsics early
117 if (CalledFunction->isIntrinsic()) {
118 assert(CalledFunction->getIntrinsicID() != 0);
119 continue;
120 }
121 auto ImportedName = CalledFunction->getName();
122 auto Renamed = (ImportedName + Suffix).str();
123 // Rename internal functions
124 if (CalledFunction->hasInternalLinkage()) {
125 ImportedName = Renamed;
126 }
127 auto It = CalledFunctions.insert(ImportedName);
128 if (!It.second) {
129 // This is a call to a function we already considered, skip.
130 continue;
131 }
132 // Ignore functions already present in the destination module
133 auto *SrcGV = DestModule.getNamedValue(ImportedName);
134 if (SrcGV) {
135 assert(isa<Function>(SrcGV) && "Name collision during import");
136 if (!cast<Function>(SrcGV)->isDeclaration()) {
137 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Ignoring "
138 << ImportedName << " already in DestinationModule\n");
139 continue;
140 }
141 }
142
143 Worklist.push_back(It.first->getKey());
144 DEBUG(dbgs() << DestModule.getModuleIdentifier()
145 << ": Adding callee for : " << ImportedName << " : "
146 << F.getName() << "\n");
147 }
148 }
149 }
150 }
151
152 // Helper function: given a worklist and an index, will process all the worklist
153 // and decide what to import based on the summary information.
154 //
155 // Nothing is actually imported, functions are materialized in their source
156 // module and analyzed there.
157 //
158 // \p ModuleToFunctionsToImportMap is filled with the set of Function to import
159 // per Module.
GetImportList(Module & DestModule,SmallVector<StringRef,64> & Worklist,StringSet<> & CalledFunctions,std::map<StringRef,DenseSet<const GlobalValue * >> & ModuleToFunctionsToImportMap,const FunctionInfoIndex & Index,ModuleLazyLoaderCache & ModuleLoaderCache)160 static void GetImportList(Module &DestModule,
161 SmallVector<StringRef, 64> &Worklist,
162 StringSet<> &CalledFunctions,
163 std::map<StringRef, DenseSet<const GlobalValue *>>
164 &ModuleToFunctionsToImportMap,
165 const FunctionInfoIndex &Index,
166 ModuleLazyLoaderCache &ModuleLoaderCache) {
167 while (!Worklist.empty()) {
168 auto CalledFunctionName = Worklist.pop_back_val();
169 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Process import for "
170 << CalledFunctionName << "\n");
171
172 // Try to get a summary for this function call.
173 auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
174 if (InfoList == Index.end()) {
175 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": No summary for "
176 << CalledFunctionName << " Ignoring.\n");
177 continue;
178 }
179 assert(!InfoList->second.empty() && "No summary, error at import?");
180
181 // Comdat can have multiple entries, FIXME: what do we do with them?
182 auto &Info = InfoList->second[0];
183 assert(Info && "Nullptr in list, error importing summaries?\n");
184
185 auto *Summary = Info->functionSummary();
186 if (!Summary) {
187 // FIXME: in case we are lazyloading summaries, we can do it now.
188 DEBUG(dbgs() << DestModule.getModuleIdentifier()
189 << ": Missing summary for " << CalledFunctionName
190 << ", error at import?\n");
191 llvm_unreachable("Missing summary");
192 }
193
194 if (Summary->instCount() > ImportInstrLimit) {
195 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Skip import of "
196 << CalledFunctionName << " with " << Summary->instCount()
197 << " instructions (limit " << ImportInstrLimit << ")\n");
198 continue;
199 }
200
201 // Get the module path from the summary.
202 auto ModuleIdentifier = Summary->modulePath();
203 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Importing "
204 << CalledFunctionName << " from " << ModuleIdentifier << "\n");
205
206 auto &SrcModule = ModuleLoaderCache(ModuleIdentifier);
207
208 // The function that we will import!
209 GlobalValue *SGV = SrcModule.getNamedValue(CalledFunctionName);
210
211 if (!SGV) {
212 // The destination module is referencing function using their renamed name
213 // when importing a function that was originally local in the source
214 // module. The source module we have might not have been renamed so we try
215 // to remove the suffix added during the renaming to recover the original
216 // name in the source module.
217 std::pair<StringRef, StringRef> Split =
218 CalledFunctionName.split(".llvm.");
219 SGV = SrcModule.getNamedValue(Split.first);
220 assert(SGV && "Can't find function to import in source module");
221 }
222 if (!SGV) {
223 report_fatal_error(Twine("Can't load function '") + CalledFunctionName +
224 "' in Module '" + SrcModule.getModuleIdentifier() +
225 "', error in the summary?\n");
226 }
227
228 Function *F = dyn_cast<Function>(SGV);
229 if (!F && isa<GlobalAlias>(SGV)) {
230 auto *SGA = dyn_cast<GlobalAlias>(SGV);
231 F = dyn_cast<Function>(SGA->getBaseObject());
232 CalledFunctionName = F->getName();
233 }
234 assert(F && "Imported Function is ... not a Function");
235
236 // We cannot import weak_any functions/aliases without possibly affecting
237 // the order they are seen and selected by the linker, changing program
238 // semantics.
239 if (SGV->hasWeakAnyLinkage()) {
240 DEBUG(dbgs() << DestModule.getModuleIdentifier()
241 << ": Ignoring import request for weak-any "
242 << (isa<Function>(SGV) ? "function " : "alias ")
243 << CalledFunctionName << " from "
244 << SrcModule.getModuleIdentifier() << "\n");
245 continue;
246 }
247
248 // Add the function to the import list
249 auto &Entry = ModuleToFunctionsToImportMap[SrcModule.getModuleIdentifier()];
250 Entry.insert(F);
251
252 // Process the newly imported functions and add callees to the worklist.
253 F->materialize();
254 findExternalCalls(DestModule, *F, Index, CalledFunctions, Worklist);
255 }
256 }
257
258 // Automatically import functions in Module \p DestModule based on the summaries
259 // index.
260 //
261 // The current implementation imports every called functions that exists in the
262 // summaries index.
importFunctions(Module & DestModule)263 bool FunctionImporter::importFunctions(Module &DestModule) {
264 DEBUG(dbgs() << "Starting import for Module "
265 << DestModule.getModuleIdentifier() << "\n");
266 unsigned ImportedCount = 0;
267
268 /// First step is collecting the called external functions.
269 StringSet<> CalledFunctions;
270 SmallVector<StringRef, 64> Worklist;
271 for (auto &F : DestModule) {
272 if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
273 continue;
274 findExternalCalls(DestModule, F, Index, CalledFunctions, Worklist);
275 }
276 if (Worklist.empty())
277 return false;
278
279 /// Second step: for every call to an external function, try to import it.
280
281 // Linker that will be used for importing function
282 Linker TheLinker(DestModule);
283
284 // Map of Module -> List of Function to import from the Module
285 std::map<StringRef, DenseSet<const GlobalValue *>>
286 ModuleToFunctionsToImportMap;
287
288 // Analyze the summaries and get the list of functions to import by
289 // populating ModuleToFunctionsToImportMap
290 ModuleLazyLoaderCache ModuleLoaderCache(ModuleLoader);
291 GetImportList(DestModule, Worklist, CalledFunctions,
292 ModuleToFunctionsToImportMap, Index, ModuleLoaderCache);
293 assert(Worklist.empty() && "Worklist hasn't been flushed in GetImportList");
294
295 StringMap<std::unique_ptr<DenseMap<unsigned, MDNode *>>>
296 ModuleToTempMDValsMap;
297
298 // Do the actual import of functions now, one Module at a time
299 for (auto &FunctionsToImportPerModule : ModuleToFunctionsToImportMap) {
300 // Get the module for the import
301 auto &FunctionsToImport = FunctionsToImportPerModule.second;
302 std::unique_ptr<Module> SrcModule =
303 ModuleLoaderCache.takeModule(FunctionsToImportPerModule.first);
304 assert(&DestModule.getContext() == &SrcModule->getContext() &&
305 "Context mismatch");
306
307 // Save the mapping of value ids to temporary metadata created when
308 // importing this function. If we have already imported from this module,
309 // add new temporary metadata to the existing mapping.
310 auto &TempMDVals = ModuleToTempMDValsMap[SrcModule->getModuleIdentifier()];
311 if (!TempMDVals)
312 TempMDVals = llvm::make_unique<DenseMap<unsigned, MDNode *>>();
313
314 // Link in the specified functions.
315 if (TheLinker.linkInModule(std::move(SrcModule), Linker::Flags::None,
316 &Index, &FunctionsToImport, TempMDVals.get()))
317 report_fatal_error("Function Import: link error");
318
319 ImportedCount += FunctionsToImport.size();
320 }
321
322 // Now link in metadata for all modules from which we imported functions.
323 for (StringMapEntry<std::unique_ptr<DenseMap<unsigned, MDNode *>>> &SME :
324 ModuleToTempMDValsMap) {
325 // Load the specified source module.
326 auto &SrcModule = ModuleLoaderCache(SME.getKey());
327
328 // Link in all necessary metadata from this module.
329 if (TheLinker.linkInMetadata(SrcModule, SME.getValue().get()))
330 return false;
331 }
332
333 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
334 << DestModule.getModuleIdentifier() << "\n");
335 return ImportedCount;
336 }
337
338 /// Summary file to use for function importing when using -function-import from
339 /// the command line.
340 static cl::opt<std::string>
341 SummaryFile("summary-file",
342 cl::desc("The summary file to use for function importing."));
343
diagnosticHandler(const DiagnosticInfo & DI)344 static void diagnosticHandler(const DiagnosticInfo &DI) {
345 raw_ostream &OS = errs();
346 DiagnosticPrinterRawOStream DP(OS);
347 DI.print(DP);
348 OS << '\n';
349 }
350
351 /// Parse the function index out of an IR file and return the function
352 /// index object if found, or nullptr if not.
353 static std::unique_ptr<FunctionInfoIndex>
getFunctionIndexForFile(StringRef Path,std::string & Error,DiagnosticHandlerFunction DiagnosticHandler)354 getFunctionIndexForFile(StringRef Path, std::string &Error,
355 DiagnosticHandlerFunction DiagnosticHandler) {
356 std::unique_ptr<MemoryBuffer> Buffer;
357 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
358 MemoryBuffer::getFile(Path);
359 if (std::error_code EC = BufferOrErr.getError()) {
360 Error = EC.message();
361 return nullptr;
362 }
363 Buffer = std::move(BufferOrErr.get());
364 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
365 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
366 DiagnosticHandler);
367 if (std::error_code EC = ObjOrErr.getError()) {
368 Error = EC.message();
369 return nullptr;
370 }
371 return (*ObjOrErr)->takeIndex();
372 }
373
374 /// Pass that performs cross-module function import provided a summary file.
375 class FunctionImportPass : public ModulePass {
376 /// Optional function summary index to use for importing, otherwise
377 /// the summary-file option must be specified.
378 const FunctionInfoIndex *Index;
379
380 public:
381 /// Pass identification, replacement for typeid
382 static char ID;
383
384 /// Specify pass name for debug output
getPassName() const385 const char *getPassName() const override {
386 return "Function Importing";
387 }
388
FunctionImportPass(const FunctionInfoIndex * Index=nullptr)389 explicit FunctionImportPass(const FunctionInfoIndex *Index = nullptr)
390 : ModulePass(ID), Index(Index) {}
391
runOnModule(Module & M)392 bool runOnModule(Module &M) override {
393 if (SummaryFile.empty() && !Index)
394 report_fatal_error("error: -function-import requires -summary-file or "
395 "file from frontend\n");
396 std::unique_ptr<FunctionInfoIndex> IndexPtr;
397 if (!SummaryFile.empty()) {
398 if (Index)
399 report_fatal_error("error: -summary-file and index from frontend\n");
400 std::string Error;
401 IndexPtr = getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
402 if (!IndexPtr) {
403 errs() << "Error loading file '" << SummaryFile << "': " << Error
404 << "\n";
405 return false;
406 }
407 Index = IndexPtr.get();
408 }
409
410 // Perform the import now.
411 auto ModuleLoader = [&M](StringRef Identifier) {
412 return loadFile(Identifier, M.getContext());
413 };
414 FunctionImporter Importer(*Index, ModuleLoader);
415 return Importer.importFunctions(M);
416
417 return false;
418 }
419 };
420
421 char FunctionImportPass::ID = 0;
422 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
423 "Summary Based Function Import", false, false)
424 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
425 "Summary Based Function Import", false, false)
426
427 namespace llvm {
createFunctionImportPass(const FunctionInfoIndex * Index=nullptr)428 Pass *createFunctionImportPass(const FunctionInfoIndex *Index = nullptr) {
429 return new FunctionImportPass(Index);
430 }
431 }
432