blob: 9d7d78a30a1b88af3bba86f1ccb4b9df903619b7 [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
Mehdi Amini01e32132016-03-26 05:40:34 +000016#include "llvm/ADT/SmallVector.h"
Teresa Johnsond29478f2016-03-27 15:27:30 +000017#include "llvm/ADT/Statistic.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000018#include "llvm/ADT/StringSet.h"
19#include "llvm/IR/AutoUpgrade.h"
20#include "llvm/IR/DiagnosticPrinter.h"
21#include "llvm/IR/IntrinsicInst.h"
22#include "llvm/IR/Module.h"
23#include "llvm/IRReader/IRReader.h"
24#include "llvm/Linker/Linker.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000025#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/SourceMgr.h"
Teresa Johnson488a8002016-02-10 18:11:31 +000029#include "llvm/Transforms/Utils/FunctionImportUtils.h"
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000030
Mehdi Amini01e32132016-03-26 05:40:34 +000031#define DEBUG_TYPE "function-import"
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000032
Mehdi Amini42418ab2015-11-24 06:07:49 +000033using namespace llvm;
34
Teresa Johnsond29478f2016-03-27 15:27:30 +000035STATISTIC(NumImported, "Number of functions imported");
36
Teresa Johnson39303612015-11-24 22:55:46 +000037/// Limit on instruction count of imported functions.
38static cl::opt<unsigned> ImportInstrLimit(
39 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
40 cl::desc("Only import functions with less than N instructions"));
41
Mehdi Amini40641742016-02-10 23:31:45 +000042static cl::opt<float>
43 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
44 cl::Hidden, cl::value_desc("x"),
45 cl::desc("As we import functions, multiply the "
46 "`import-instr-limit` threshold by this factor "
47 "before processing newly imported functions"));
48
Teresa Johnsond29478f2016-03-27 15:27:30 +000049static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
50 cl::desc("Print imported functions"));
51
Mehdi Amini42418ab2015-11-24 06:07:49 +000052// Load lazily a module from \p FileName in \p Context.
53static std::unique_ptr<Module> loadFile(const std::string &FileName,
54 LLVMContext &Context) {
55 SMDiagnostic Err;
56 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +000057 // Metadata isn't loaded until functions are imported, to minimize
58 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +000059 std::unique_ptr<Module> Result =
60 getLazyIRFileModule(FileName, Err, Context,
61 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +000062 if (!Result) {
63 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +000064 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +000065 }
66
Mehdi Amini42418ab2015-11-24 06:07:49 +000067 return Result;
68}
69
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000070namespace {
Mehdi Amini40641742016-02-10 23:31:45 +000071
Mehdi Amini01e32132016-03-26 05:40:34 +000072/// Given a list of possible callee implementation for a call site, select one
73/// that fits the \p Threshold.
74///
75/// FIXME: select "best" instead of first that fits. But what is "best"?
76/// - The smallest: more likely to be inlined.
77/// - The one with the least outgoing edges (already well optimized).
78/// - One from a module already being imported from in order to reduce the
79/// number of source modules parsed/linked.
80/// - One that has PGO data attached.
81/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +000082static const GlobalValueSummary *
Mehdi Amini01e32132016-03-26 05:40:34 +000083selectCallee(const GlobalValueInfoList &CalleeInfoList, unsigned Threshold) {
84 auto It = llvm::find_if(
85 CalleeInfoList, [&](const std::unique_ptr<GlobalValueInfo> &GlobInfo) {
86 assert(GlobInfo->summary() &&
87 "We should not have a Global Info without summary");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +000088 auto *GVSummary = GlobInfo->summary();
Mehdi Amini2c719cc2016-04-20 04:17:36 +000089 if (GlobalValue::isWeakAnyLinkage(GVSummary->linkage()))
90 // There is no point in importing weak symbols, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +000091 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +000092 if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
93 GVSummary = &AS->getAliasee();
94 // Alias can't point to "available_externally". However when we import
95 // linkOnceODR the linkage does not change. So we import the alias
96 // and aliasee only in this case.
97 // FIXME: we should import alias as available_externally *function*,
98 // the destination module does need to know it is an alias.
99 if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
100 return false;
101 }
102
103 auto *Summary = cast<FunctionSummary>(GVSummary);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000104
Mehdi Amini01e32132016-03-26 05:40:34 +0000105 if (Summary->instCount() > Threshold)
106 return false;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000107
Mehdi Amini01e32132016-03-26 05:40:34 +0000108 return true;
109 });
110 if (It == CalleeInfoList.end())
111 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000112
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000113 return cast<GlobalValueSummary>((*It)->summary());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000114}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000115
Mehdi Amini01e32132016-03-26 05:40:34 +0000116/// Return the summary for the function \p GUID that fits the \p Threshold, or
117/// null if there's no match.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000118static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID,
119 unsigned Threshold,
120 const ModuleSummaryIndex &Index) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000121 auto CalleeInfoList = Index.findGlobalValueInfoList(GUID);
122 if (CalleeInfoList == Index.end()) {
123 return nullptr; // This function does not have a summary
124 }
125 return selectCallee(CalleeInfoList->second, Threshold);
126}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000127
Mehdi Amini01e32132016-03-26 05:40:34 +0000128/// Return true if the global \p GUID is exported by module \p ExportModulePath.
129static bool isGlobalExported(const ModuleSummaryIndex &Index,
Mehdi Aminiad5741b2016-04-02 05:07:53 +0000130 StringRef ExportModulePath,
131 GlobalValue::GUID GUID) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000132 auto CalleeInfoList = Index.findGlobalValueInfoList(GUID);
133 if (CalleeInfoList == Index.end())
134 // This global does not have a summary, it is not part of the ThinLTO
135 // process
136 return false;
137 auto DefinedInCalleeModule = llvm::find_if(
138 CalleeInfoList->second,
139 [&](const std::unique_ptr<GlobalValueInfo> &GlobInfo) {
140 auto *Summary = GlobInfo->summary();
141 assert(Summary && "Unexpected GlobalValueInfo without summary");
142 return Summary->modulePath() == ExportModulePath;
143 });
144 return (DefinedInCalleeModule != CalleeInfoList->second.end());
145}
Mehdi Amini40641742016-02-10 23:31:45 +0000146
Mehdi Amini01e32132016-03-26 05:40:34 +0000147using EdgeInfo = std::pair<const FunctionSummary *, unsigned /* Threshold */>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000148
Mehdi Amini01e32132016-03-26 05:40:34 +0000149/// Compute the list of functions to import for a given caller. Mark these
150/// imported functions and the symbols they reference in their source module as
151/// exported from their source module.
152static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000153 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
154 unsigned Threshold,
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000155 const std::map<GlobalValue::GUID, GlobalValueSummary *> &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000156 SmallVectorImpl<EdgeInfo> &Worklist,
157 FunctionImporter::ImportMapTy &ImportsForModule,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000158 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000159 for (auto &Edge : Summary.calls()) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000160 auto GUID = Edge.first.getGUID();
Mehdi Amini01e32132016-03-26 05:40:34 +0000161 DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
162
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000163 if (DefinedGVSummaries.count(GUID)) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000164 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
165 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000166 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000167
168 auto *CalleeSummary = selectCallee(GUID, Threshold, Index);
169 if (!CalleeSummary) {
170 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
171 continue;
172 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000173 // "Resolve" the summary, traversing alias,
174 const FunctionSummary *ResolvedCalleeSummary;
Mehdi Amini6968ef72016-04-20 01:04:20 +0000175 if (isa<AliasSummary>(CalleeSummary)) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000176 ResolvedCalleeSummary = cast<FunctionSummary>(
177 &cast<AliasSummary>(CalleeSummary)->getAliasee());
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000178 assert(
179 GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
180 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini6968ef72016-04-20 01:04:20 +0000181 } else
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000182 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
183
184 assert(ResolvedCalleeSummary->instCount() <= Threshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000185 "selectCallee() didn't honor the threshold");
186
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000187 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
188 auto &ProcessedThreshold = ImportsForModule[ExportModulePath][GUID];
Mehdi Amini01e32132016-03-26 05:40:34 +0000189 /// Since the traversal of the call graph is DFS, we can revisit a function
190 /// a second time with a higher threshold. In this case, it is added back to
191 /// the worklist with the new threshold.
192 if (ProcessedThreshold && ProcessedThreshold > Threshold) {
193 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
194 << ProcessedThreshold << "\n");
195 continue;
196 }
197 // Mark this function as imported in this module, with the current Threshold
198 ProcessedThreshold = Threshold;
199
200 // Make exports in the source module.
Teresa Johnsonc86af332016-04-12 21:13:11 +0000201 if (ExportLists) {
Mehdi Aminief7555f2016-04-13 01:52:32 +0000202 auto &ExportList = (*ExportLists)[ExportModulePath];
Teresa Johnsonc86af332016-04-12 21:13:11 +0000203 ExportList.insert(GUID);
204 // Mark all functions and globals referenced by this function as exported
205 // to the outside if they are defined in the same source module.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000206 for (auto &Edge : ResolvedCalleeSummary->calls()) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000207 auto CalleeGUID = Edge.first.getGUID();
208 if (isGlobalExported(Index, ExportModulePath, CalleeGUID))
209 ExportList.insert(CalleeGUID);
210 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000211 for (auto &Ref : ResolvedCalleeSummary->refs()) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000212 auto GUID = Ref.getGUID();
213 if (isGlobalExported(Index, ExportModulePath, GUID))
214 ExportList.insert(GUID);
215 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000216 }
217
218 // Insert the newly imported function to the worklist.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000219 Worklist.push_back(std::make_pair(ResolvedCalleeSummary, Threshold));
Teresa Johnsond450da32015-11-24 21:15:19 +0000220 }
221}
222
Mehdi Amini01e32132016-03-26 05:40:34 +0000223/// Given the list of globals defined in a module, compute the list of imports
224/// as well as the list of "exports", i.e. the list of symbols referenced from
225/// another module (that may require promotion).
226static void ComputeImportForModule(
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000227 const std::map<GlobalValue::GUID, GlobalValueSummary *> &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000228 const ModuleSummaryIndex &Index,
229 FunctionImporter::ImportMapTy &ImportsForModule,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000230 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000231 // Worklist contains the list of function imported in this module, for which
232 // we will analyse the callees and may import further down the callgraph.
233 SmallVector<EdgeInfo, 128> Worklist;
234
235 // Populate the worklist with the import for the functions in the current
236 // module
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000237 for (auto &GVInfo : DefinedGVSummaries) {
238 auto *Summary = GVInfo.second;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000239 if (auto *AS = dyn_cast<AliasSummary>(Summary))
240 Summary = &AS->getAliasee();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000241 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
242 if (!FuncSummary)
243 // Skip import for global variables
244 continue;
245 DEBUG(dbgs() << "Initalize import for " << GVInfo.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000246 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000247 DefinedGVSummaries, Worklist, ImportsForModule,
Mehdi Amini01e32132016-03-26 05:40:34 +0000248 ExportLists);
249 }
250
Mehdi Amini42418ab2015-11-24 06:07:49 +0000251 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000252 auto FuncInfo = Worklist.pop_back_val();
253 auto *Summary = FuncInfo.first;
254 auto Threshold = FuncInfo.second;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000255
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000256 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini40641742016-02-10 23:31:45 +0000257 // Adjust the threshold
258 Threshold = Threshold * ImportInstrFactor;
Mehdi Amini01e32132016-03-26 05:40:34 +0000259
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000260 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Teresa Johnson3255eec2016-04-10 15:17:26 +0000261 Worklist, ImportsForModule, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000262 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000263}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000264
Mehdi Amini01e32132016-03-26 05:40:34 +0000265} // anonymous namespace
266
Teresa Johnsonc86af332016-04-12 21:13:11 +0000267/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000268void llvm::ComputeCrossModuleImport(
269 const ModuleSummaryIndex &Index,
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000270 const StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>> &
271 ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000272 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
273 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000274 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000275 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
276 auto &ImportsForModule = ImportLists[DefinedGVSummaries.first()];
277 DEBUG(dbgs() << "Computing import for Module '"
278 << DefinedGVSummaries.first() << "'\n");
279 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportsForModule,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000280 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000281 }
282
283#ifndef NDEBUG
284 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
285 << " modules:\n");
286 for (auto &ModuleImports : ImportLists) {
287 auto ModName = ModuleImports.first();
288 auto &Exports = ExportLists[ModName];
289 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
290 << " functions. Imports from " << ModuleImports.second.size()
291 << " modules.\n");
292 for (auto &Src : ModuleImports.second) {
293 auto SrcModName = Src.first();
294 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
295 << SrcModName << "\n");
296 }
297 }
298#endif
299}
300
Teresa Johnsonc86af332016-04-12 21:13:11 +0000301/// Compute all the imports for the given module in the Index.
302void llvm::ComputeCrossModuleImportForModule(
303 StringRef ModulePath, const ModuleSummaryIndex &Index,
304 FunctionImporter::ImportMapTy &ImportList) {
305
306 // Collect the list of functions this module defines.
307 // GUID -> Summary
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000308 std::map<GlobalValue::GUID, GlobalValueSummary *> FunctionInfoMap;
Teresa Johnsonc86af332016-04-12 21:13:11 +0000309 Index.collectDefinedFunctionsForModule(ModulePath, FunctionInfoMap);
310
311 // Compute the import list for this module.
312 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
313 ComputeImportForModule(FunctionInfoMap, Index, ImportList);
314
315#ifndef NDEBUG
316 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
317 << ImportList.size() << " modules.\n");
318 for (auto &Src : ImportList) {
319 auto SrcModName = Src.first();
320 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
321 << SrcModName << "\n");
322 }
323#endif
324}
325
Mehdi Aminic8c55172015-12-03 02:37:33 +0000326// Automatically import functions in Module \p DestModule based on the summaries
327// index.
328//
Mehdi Amini01e32132016-03-26 05:40:34 +0000329bool FunctionImporter::importFunctions(
330 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000331 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000332 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000333 unsigned ImportedCount = 0;
334
Mehdi Aminic8c55172015-12-03 02:37:33 +0000335 // Linker that will be used for importing function
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000336 Linker TheLinker(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000337 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000338 std::set<StringRef> ModuleNameOrderedList;
339 for (auto &FunctionsToImportPerModule : ImportList) {
340 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
341 }
342 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000343 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000344 const auto &FunctionsToImportPerModule = ImportList.find(Name);
345 assert(FunctionsToImportPerModule != ImportList.end());
346 std::unique_ptr<Module> SrcModule = ModuleLoader(Name);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000347 assert(&DestModule.getContext() == &SrcModule->getContext() &&
348 "Context mismatch");
349
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000350 // If modules were created with lazy metadata loading, materialize it
351 // now, before linking it (otherwise this will be a noop).
352 SrcModule->materializeMetadata();
353 UpgradeDebugInfo(*SrcModule);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000354
Mehdi Amini01e32132016-03-26 05:40:34 +0000355 auto &ImportGUIDs = FunctionsToImportPerModule->second;
356 // Find the globals to import
357 DenseSet<const GlobalValue *> GlobalsToImport;
358 for (auto &GV : *SrcModule) {
Teresa Johnson0beb8582016-04-04 18:52:23 +0000359 if (!GV.hasName())
360 continue;
361 auto GUID = GV.getGUID();
362 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000363 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
364 << " " << GV.getName() << " from "
365 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000366 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000367 GV.materialize();
368 GlobalsToImport.insert(&GV);
369 }
370 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000371 for (auto &GV : SrcModule->globals()) {
372 if (!GV.hasName())
373 continue;
374 auto GUID = GV.getGUID();
375 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000376 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
377 << " " << GV.getName() << " from "
378 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000379 if (Import) {
380 GV.materialize();
381 GlobalsToImport.insert(&GV);
382 }
383 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000384 for (auto &GV : SrcModule->aliases()) {
385 if (!GV.hasName())
386 continue;
387 auto GUID = GV.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000388 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000389 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
390 << " " << GV.getName() << " from "
391 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000392 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000393 // Alias can't point to "available_externally". However when we import
Teresa Johnson9aae3952016-03-27 15:01:11 +0000394 // linkOnceODR the linkage does not change. So we import the alias
Mehdi Amini6968ef72016-04-20 01:04:20 +0000395 // and aliasee only in this case. This has been handled by
396 // computeImportForFunction()
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000397 GlobalObject *GO = GV.getBaseObject();
Mehdi Amini6968ef72016-04-20 01:04:20 +0000398 assert(GO->hasLinkOnceODRLinkage() &&
399 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000400#ifndef NDEBUG
401 if (!GlobalsToImport.count(GO))
402 DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
403 << " " << GO->getName() << " from "
404 << SrcModule->getSourceFileName() << "\n");
405#endif
406 GO->materialize();
Mehdi Amini01e32132016-03-26 05:40:34 +0000407 GlobalsToImport.insert(GO);
Mehdi Amini01e32132016-03-26 05:40:34 +0000408 GV.materialize();
409 GlobalsToImport.insert(&GV);
410 }
411 }
412
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000413 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000414 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000415 return true;
416
Teresa Johnsond29478f2016-03-27 15:27:30 +0000417 if (PrintImports) {
418 for (const auto *GV : GlobalsToImport)
419 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
420 << " from " << SrcModule->getSourceFileName() << "\n";
421 }
422
Rafael Espindola434e9562015-12-16 23:16:33 +0000423 if (TheLinker.linkInModule(std::move(SrcModule), Linker::Flags::None,
Mehdi Amini01e32132016-03-26 05:40:34 +0000424 &GlobalsToImport))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000425 report_fatal_error("Function Import: link error");
426
Mehdi Amini01e32132016-03-26 05:40:34 +0000427 ImportedCount += GlobalsToImport.size();
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000428 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000429
Teresa Johnsond29478f2016-03-27 15:27:30 +0000430 NumImported += ImportedCount;
431
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000432 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000433 << DestModule.getModuleIdentifier() << "\n");
434 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000435}
436
437/// Summary file to use for function importing when using -function-import from
438/// the command line.
439static cl::opt<std::string>
440 SummaryFile("summary-file",
441 cl::desc("The summary file to use for function importing."));
442
443static void diagnosticHandler(const DiagnosticInfo &DI) {
444 raw_ostream &OS = errs();
445 DiagnosticPrinterRawOStream DP(OS);
446 DI.print(DP);
447 OS << '\n';
448}
449
Teresa Johnson26ab5772016-03-15 00:04:37 +0000450/// Parse the summary index out of an IR file and return the summary
Mehdi Amini42418ab2015-11-24 06:07:49 +0000451/// index object if found, or nullptr if not.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000452static std::unique_ptr<ModuleSummaryIndex>
453getModuleSummaryIndexForFile(StringRef Path, std::string &Error,
454 DiagnosticHandlerFunction DiagnosticHandler) {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000455 std::unique_ptr<MemoryBuffer> Buffer;
456 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
457 MemoryBuffer::getFile(Path);
458 if (std::error_code EC = BufferOrErr.getError()) {
459 Error = EC.message();
460 return nullptr;
461 }
462 Buffer = std::move(BufferOrErr.get());
Teresa Johnson26ab5772016-03-15 00:04:37 +0000463 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
464 object::ModuleSummaryIndexObjectFile::create(Buffer->getMemBufferRef(),
465 DiagnosticHandler);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000466 if (std::error_code EC = ObjOrErr.getError()) {
467 Error = EC.message();
468 return nullptr;
469 }
470 return (*ObjOrErr)->takeIndex();
471}
472
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000473namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000474/// Pass that performs cross-module function import provided a summary file.
475class FunctionImportPass : public ModulePass {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000476 /// Optional module summary index to use for importing, otherwise
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000477 /// the summary-file option must be specified.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000478 const ModuleSummaryIndex *Index;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000479
480public:
481 /// Pass identification, replacement for typeid
482 static char ID;
483
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000484 /// Specify pass name for debug output
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000485 const char *getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000486
Teresa Johnson26ab5772016-03-15 00:04:37 +0000487 explicit FunctionImportPass(const ModuleSummaryIndex *Index = nullptr)
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000488 : ModulePass(ID), Index(Index) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000489
490 bool runOnModule(Module &M) override {
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000491 if (SummaryFile.empty() && !Index)
492 report_fatal_error("error: -function-import requires -summary-file or "
493 "file from frontend\n");
Teresa Johnson26ab5772016-03-15 00:04:37 +0000494 std::unique_ptr<ModuleSummaryIndex> IndexPtr;
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000495 if (!SummaryFile.empty()) {
496 if (Index)
497 report_fatal_error("error: -summary-file and index from frontend\n");
498 std::string Error;
Teresa Johnson26ab5772016-03-15 00:04:37 +0000499 IndexPtr =
500 getModuleSummaryIndexForFile(SummaryFile, Error, diagnosticHandler);
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000501 if (!IndexPtr) {
502 errs() << "Error loading file '" << SummaryFile << "': " << Error
503 << "\n";
504 return false;
505 }
506 Index = IndexPtr.get();
Mehdi Amini42418ab2015-11-24 06:07:49 +0000507 }
508
Teresa Johnsonc86af332016-04-12 21:13:11 +0000509 // First step is collecting the import list.
510 FunctionImporter::ImportMapTy ImportList;
511 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
512 ImportList);
Mehdi Amini01e32132016-03-26 05:40:34 +0000513
514 // Next we need to promote to global scope and rename any local values that
Teresa Johnson1b00f2d2016-01-08 17:06:29 +0000515 // are potentially exported to other modules.
Mehdi Amini01e32132016-03-26 05:40:34 +0000516 if (renameModuleForThinLTO(M, *Index, nullptr)) {
Teresa Johnson1b00f2d2016-01-08 17:06:29 +0000517 errs() << "Error renaming module\n";
518 return false;
519 }
520
Mehdi Amini42418ab2015-11-24 06:07:49 +0000521 // Perform the import now.
Mehdi Aminid16c8062015-12-08 22:39:40 +0000522 auto ModuleLoader = [&M](StringRef Identifier) {
523 return loadFile(Identifier, M.getContext());
524 };
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000525 FunctionImporter Importer(*Index, ModuleLoader);
Mehdi Amini01e32132016-03-26 05:40:34 +0000526 return Importer.importFunctions(M, ImportList);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000527 }
528};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000529} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000530
531char FunctionImportPass::ID = 0;
532INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
533 "Summary Based Function Import", false, false)
534INITIALIZE_PASS_END(FunctionImportPass, "function-import",
535 "Summary Based Function Import", false, false)
536
537namespace llvm {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000538Pass *createFunctionImportPass(const ModuleSummaryIndex *Index = nullptr) {
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000539 return new FunctionImportPass(Index);
540}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000541}