blob: 3f0d2624f5dce27cee85006a2cdf3364c2561cd2 [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 Aminibda3c972016-04-21 01:59:39 +000052// Temporary allows the function import pass to disable always linking
53// referenced discardable symbols.
54static cl::opt<bool>
55 DontForceImportReferencedDiscardableSymbols("disable-force-link-odr",
56 cl::init(false), cl::Hidden);
57
Mehdi Amini42418ab2015-11-24 06:07:49 +000058// Load lazily a module from \p FileName in \p Context.
59static std::unique_ptr<Module> loadFile(const std::string &FileName,
60 LLVMContext &Context) {
61 SMDiagnostic Err;
62 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +000063 // Metadata isn't loaded until functions are imported, to minimize
64 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +000065 std::unique_ptr<Module> Result =
66 getLazyIRFileModule(FileName, Err, Context,
67 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +000068 if (!Result) {
69 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +000070 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +000071 }
72
Mehdi Amini42418ab2015-11-24 06:07:49 +000073 return Result;
74}
75
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000076namespace {
Mehdi Amini40641742016-02-10 23:31:45 +000077
Mehdi Amini01e32132016-03-26 05:40:34 +000078/// Given a list of possible callee implementation for a call site, select one
79/// that fits the \p Threshold.
80///
81/// FIXME: select "best" instead of first that fits. But what is "best"?
82/// - The smallest: more likely to be inlined.
83/// - The one with the least outgoing edges (already well optimized).
84/// - One from a module already being imported from in order to reduce the
85/// number of source modules parsed/linked.
86/// - One that has PGO data attached.
87/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +000088static const GlobalValueSummary *
Teresa Johnson28e457b2016-04-24 14:57:11 +000089selectCallee(const GlobalValueSummaryList &CalleeSummaryList,
90 unsigned Threshold) {
Mehdi Amini01e32132016-03-26 05:40:34 +000091 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +000092 CalleeSummaryList,
93 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
94 auto *GVSummary = SummaryPtr.get();
Mehdi Amini2c719cc2016-04-20 04:17:36 +000095 if (GlobalValue::isWeakAnyLinkage(GVSummary->linkage()))
96 // There is no point in importing weak symbols, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +000097 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +000098 if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
99 GVSummary = &AS->getAliasee();
100 // Alias can't point to "available_externally". However when we import
101 // linkOnceODR the linkage does not change. So we import the alias
102 // and aliasee only in this case.
103 // FIXME: we should import alias as available_externally *function*,
104 // the destination module does need to know it is an alias.
105 if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
106 return false;
107 }
108
109 auto *Summary = cast<FunctionSummary>(GVSummary);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000110
Mehdi Amini01e32132016-03-26 05:40:34 +0000111 if (Summary->instCount() > Threshold)
112 return false;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000113
Mehdi Amini01e32132016-03-26 05:40:34 +0000114 return true;
115 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000116 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000117 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000118
Teresa Johnson28e457b2016-04-24 14:57:11 +0000119 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000120}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000121
Mehdi Amini01e32132016-03-26 05:40:34 +0000122/// Return the summary for the function \p GUID that fits the \p Threshold, or
123/// null if there's no match.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000124static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID,
125 unsigned Threshold,
126 const ModuleSummaryIndex &Index) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000127 auto CalleeSummaryList = Index.findGlobalValueSummaryList(GUID);
128 if (CalleeSummaryList == Index.end()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000129 return nullptr; // This function does not have a summary
130 }
Teresa Johnson28e457b2016-04-24 14:57:11 +0000131 return selectCallee(CalleeSummaryList->second, Threshold);
Mehdi Amini01e32132016-03-26 05:40:34 +0000132}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000133
Mehdi Aminicb874942016-04-23 23:29:24 +0000134/// Mark the global \p GUID as export by module \p ExportModulePath if found in
135/// this module. If it is a GlobalVariable, we also mark any referenced global
136/// in the current module as exported.
137static void exportGlobalInModule(const ModuleSummaryIndex &Index,
138 StringRef ExportModulePath,
139 GlobalValue::GUID GUID,
140 FunctionImporter::ExportSetTy &ExportList) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000141 auto FindGlobalSummaryInModule =
142 [&](GlobalValue::GUID GUID) -> GlobalValueSummary *{
143 auto SummaryList = Index.findGlobalValueSummaryList(GUID);
144 if (SummaryList == Index.end())
Mehdi Aminicb874942016-04-23 23:29:24 +0000145 // This global does not have a summary, it is not part of the ThinLTO
146 // process
147 return nullptr;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000148 auto SummaryIter = llvm::find_if(
149 SummaryList->second,
150 [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
Mehdi Aminicb874942016-04-23 23:29:24 +0000151 return Summary->modulePath() == ExportModulePath;
152 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000153 if (SummaryIter == SummaryList->second.end())
Mehdi Aminicb874942016-04-23 23:29:24 +0000154 return nullptr;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000155 return SummaryIter->get();
Mehdi Aminicb874942016-04-23 23:29:24 +0000156 };
157
Teresa Johnson28e457b2016-04-24 14:57:11 +0000158 auto *Summary = FindGlobalSummaryInModule(GUID);
159 if (!Summary)
Mehdi Aminicb874942016-04-23 23:29:24 +0000160 return;
161 // We found it in the current module, mark as exported
162 ExportList.insert(GUID);
163
Mehdi Aminicb874942016-04-23 23:29:24 +0000164 auto GVS = dyn_cast<GlobalVarSummary>(Summary);
165 if (!GVS)
166 return;
167 // FunctionImportGlobalProcessing::doPromoteLocalToGlobal() will always
168 // trigger importing the initializer for `constant unnamed addr` globals that
169 // are referenced. We conservatively export all the referenced symbols for
170 // every global to workaround this, so that the ExportList is accurate.
171 // FIXME: with a "isConstant" flag in the summary we could be more targetted.
172 for (auto &Ref : GVS->refs()) {
173 auto GUID = Ref.getGUID();
Teresa Johnson28e457b2016-04-24 14:57:11 +0000174 auto *RefSummary = FindGlobalSummaryInModule(GUID);
175 if (RefSummary)
Mehdi Aminicb874942016-04-23 23:29:24 +0000176 // Found a ref in the current module, mark it as exported
177 ExportList.insert(GUID);
178 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000179}
Mehdi Amini40641742016-02-10 23:31:45 +0000180
Mehdi Amini01e32132016-03-26 05:40:34 +0000181using EdgeInfo = std::pair<const FunctionSummary *, unsigned /* Threshold */>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000182
Mehdi Amini01e32132016-03-26 05:40:34 +0000183/// Compute the list of functions to import for a given caller. Mark these
184/// imported functions and the symbols they reference in their source module as
185/// exported from their source module.
186static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000187 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000188 unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000189 SmallVectorImpl<EdgeInfo> &Worklist,
190 FunctionImporter::ImportMapTy &ImportsForModule,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000191 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000192 for (auto &Edge : Summary.calls()) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000193 auto GUID = Edge.first.getGUID();
Mehdi Amini01e32132016-03-26 05:40:34 +0000194 DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
195
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000196 if (DefinedGVSummaries.count(GUID)) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000197 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
198 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000199 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000200
201 auto *CalleeSummary = selectCallee(GUID, Threshold, Index);
202 if (!CalleeSummary) {
203 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
204 continue;
205 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000206 // "Resolve" the summary, traversing alias,
207 const FunctionSummary *ResolvedCalleeSummary;
Mehdi Amini6968ef72016-04-20 01:04:20 +0000208 if (isa<AliasSummary>(CalleeSummary)) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000209 ResolvedCalleeSummary = cast<FunctionSummary>(
210 &cast<AliasSummary>(CalleeSummary)->getAliasee());
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000211 assert(
212 GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
213 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini6968ef72016-04-20 01:04:20 +0000214 } else
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000215 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
216
217 assert(ResolvedCalleeSummary->instCount() <= Threshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000218 "selectCallee() didn't honor the threshold");
219
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000220 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
221 auto &ProcessedThreshold = ImportsForModule[ExportModulePath][GUID];
Mehdi Amini01e32132016-03-26 05:40:34 +0000222 /// Since the traversal of the call graph is DFS, we can revisit a function
223 /// a second time with a higher threshold. In this case, it is added back to
224 /// the worklist with the new threshold.
225 if (ProcessedThreshold && ProcessedThreshold > Threshold) {
226 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
227 << ProcessedThreshold << "\n");
228 continue;
229 }
230 // Mark this function as imported in this module, with the current Threshold
231 ProcessedThreshold = Threshold;
232
233 // Make exports in the source module.
Teresa Johnsonc86af332016-04-12 21:13:11 +0000234 if (ExportLists) {
Mehdi Aminief7555f2016-04-13 01:52:32 +0000235 auto &ExportList = (*ExportLists)[ExportModulePath];
Teresa Johnsonc86af332016-04-12 21:13:11 +0000236 ExportList.insert(GUID);
237 // Mark all functions and globals referenced by this function as exported
238 // to the outside if they are defined in the same source module.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000239 for (auto &Edge : ResolvedCalleeSummary->calls()) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000240 auto CalleeGUID = Edge.first.getGUID();
Mehdi Aminicb874942016-04-23 23:29:24 +0000241 exportGlobalInModule(Index, ExportModulePath, CalleeGUID, ExportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000242 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000243 for (auto &Ref : ResolvedCalleeSummary->refs()) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000244 auto GUID = Ref.getGUID();
Mehdi Aminicb874942016-04-23 23:29:24 +0000245 exportGlobalInModule(Index, ExportModulePath, GUID, ExportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000246 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000247 }
248
249 // Insert the newly imported function to the worklist.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000250 Worklist.push_back(std::make_pair(ResolvedCalleeSummary, Threshold));
Teresa Johnsond450da32015-11-24 21:15:19 +0000251 }
252}
253
Mehdi Amini01e32132016-03-26 05:40:34 +0000254/// Given the list of globals defined in a module, compute the list of imports
255/// as well as the list of "exports", i.e. the list of symbols referenced from
256/// another module (that may require promotion).
257static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000258 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini01e32132016-03-26 05:40:34 +0000259 FunctionImporter::ImportMapTy &ImportsForModule,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000260 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000261 // Worklist contains the list of function imported in this module, for which
262 // we will analyse the callees and may import further down the callgraph.
263 SmallVector<EdgeInfo, 128> Worklist;
264
265 // Populate the worklist with the import for the functions in the current
266 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000267 for (auto &GVSummary : DefinedGVSummaries) {
268 auto *Summary = GVSummary.second;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000269 if (auto *AS = dyn_cast<AliasSummary>(Summary))
270 Summary = &AS->getAliasee();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000271 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
272 if (!FuncSummary)
273 // Skip import for global variables
274 continue;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000275 DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000276 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000277 DefinedGVSummaries, Worklist, ImportsForModule,
Mehdi Amini01e32132016-03-26 05:40:34 +0000278 ExportLists);
279 }
280
Mehdi Amini42418ab2015-11-24 06:07:49 +0000281 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000282 auto FuncInfo = Worklist.pop_back_val();
283 auto *Summary = FuncInfo.first;
284 auto Threshold = FuncInfo.second;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000285
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000286 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini40641742016-02-10 23:31:45 +0000287 // Adjust the threshold
288 Threshold = Threshold * ImportInstrFactor;
Mehdi Amini01e32132016-03-26 05:40:34 +0000289
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000290 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Teresa Johnson3255eec2016-04-10 15:17:26 +0000291 Worklist, ImportsForModule, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000292 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000293}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000294
Mehdi Amini01e32132016-03-26 05:40:34 +0000295} // anonymous namespace
296
Teresa Johnsonc86af332016-04-12 21:13:11 +0000297/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000298void llvm::ComputeCrossModuleImport(
299 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000300 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000301 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
302 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000303 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000304 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
305 auto &ImportsForModule = ImportLists[DefinedGVSummaries.first()];
306 DEBUG(dbgs() << "Computing import for Module '"
307 << DefinedGVSummaries.first() << "'\n");
308 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportsForModule,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000309 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000310 }
311
312#ifndef NDEBUG
313 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
314 << " modules:\n");
315 for (auto &ModuleImports : ImportLists) {
316 auto ModName = ModuleImports.first();
317 auto &Exports = ExportLists[ModName];
318 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
319 << " functions. Imports from " << ModuleImports.second.size()
320 << " modules.\n");
321 for (auto &Src : ModuleImports.second) {
322 auto SrcModName = Src.first();
323 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
324 << SrcModName << "\n");
325 }
326 }
327#endif
328}
329
Teresa Johnsonc86af332016-04-12 21:13:11 +0000330/// Compute all the imports for the given module in the Index.
331void llvm::ComputeCrossModuleImportForModule(
332 StringRef ModulePath, const ModuleSummaryIndex &Index,
333 FunctionImporter::ImportMapTy &ImportList) {
334
335 // Collect the list of functions this module defines.
336 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000337 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000338 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000339
340 // Compute the import list for this module.
341 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000342 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000343
344#ifndef NDEBUG
345 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
346 << ImportList.size() << " modules.\n");
347 for (auto &Src : ImportList) {
348 auto SrcModName = Src.first();
349 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
350 << SrcModName << "\n");
351 }
352#endif
353}
354
Mehdi Aminic8c55172015-12-03 02:37:33 +0000355// Automatically import functions in Module \p DestModule based on the summaries
356// index.
357//
Mehdi Amini01e32132016-03-26 05:40:34 +0000358bool FunctionImporter::importFunctions(
Mehdi Aminibda3c972016-04-21 01:59:39 +0000359 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList,
360 bool ForceImportReferencedDiscardableSymbols) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000361 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000362 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000363 unsigned ImportedCount = 0;
364
Mehdi Aminic8c55172015-12-03 02:37:33 +0000365 // Linker that will be used for importing function
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000366 Linker TheLinker(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000367 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000368 std::set<StringRef> ModuleNameOrderedList;
369 for (auto &FunctionsToImportPerModule : ImportList) {
370 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
371 }
372 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000373 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000374 const auto &FunctionsToImportPerModule = ImportList.find(Name);
375 assert(FunctionsToImportPerModule != ImportList.end());
376 std::unique_ptr<Module> SrcModule = ModuleLoader(Name);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000377 assert(&DestModule.getContext() == &SrcModule->getContext() &&
378 "Context mismatch");
379
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000380 // If modules were created with lazy metadata loading, materialize it
381 // now, before linking it (otherwise this will be a noop).
382 SrcModule->materializeMetadata();
383 UpgradeDebugInfo(*SrcModule);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000384
Mehdi Amini01e32132016-03-26 05:40:34 +0000385 auto &ImportGUIDs = FunctionsToImportPerModule->second;
386 // Find the globals to import
387 DenseSet<const GlobalValue *> GlobalsToImport;
388 for (auto &GV : *SrcModule) {
Teresa Johnson0beb8582016-04-04 18:52:23 +0000389 if (!GV.hasName())
390 continue;
391 auto GUID = GV.getGUID();
392 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000393 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
394 << " " << GV.getName() << " from "
395 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000396 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000397 GV.materialize();
398 GlobalsToImport.insert(&GV);
399 }
400 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000401 for (auto &GV : SrcModule->globals()) {
402 if (!GV.hasName())
403 continue;
404 auto GUID = GV.getGUID();
405 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000406 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
407 << " " << GV.getName() << " from "
408 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000409 if (Import) {
410 GV.materialize();
411 GlobalsToImport.insert(&GV);
412 }
413 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000414 for (auto &GV : SrcModule->aliases()) {
415 if (!GV.hasName())
416 continue;
417 auto GUID = GV.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000418 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000419 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
420 << " " << GV.getName() << " from "
421 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000422 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000423 // Alias can't point to "available_externally". However when we import
Teresa Johnson9aae3952016-03-27 15:01:11 +0000424 // linkOnceODR the linkage does not change. So we import the alias
Mehdi Amini6968ef72016-04-20 01:04:20 +0000425 // and aliasee only in this case. This has been handled by
426 // computeImportForFunction()
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000427 GlobalObject *GO = GV.getBaseObject();
Mehdi Amini6968ef72016-04-20 01:04:20 +0000428 assert(GO->hasLinkOnceODRLinkage() &&
429 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000430#ifndef NDEBUG
431 if (!GlobalsToImport.count(GO))
432 DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
433 << " " << GO->getName() << " from "
434 << SrcModule->getSourceFileName() << "\n");
435#endif
436 GO->materialize();
Mehdi Amini01e32132016-03-26 05:40:34 +0000437 GlobalsToImport.insert(GO);
Mehdi Amini01e32132016-03-26 05:40:34 +0000438 GV.materialize();
439 GlobalsToImport.insert(&GV);
440 }
441 }
442
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000443 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000444 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000445 return true;
446
Teresa Johnsond29478f2016-03-27 15:27:30 +0000447 if (PrintImports) {
448 for (const auto *GV : GlobalsToImport)
449 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
450 << " from " << SrcModule->getSourceFileName() << "\n";
451 }
452
Mehdi Aminibda3c972016-04-21 01:59:39 +0000453 // Instruct the linker that the client will take care of linkonce resolution
454 unsigned Flags = Linker::Flags::None;
455 if (!ForceImportReferencedDiscardableSymbols)
456 Flags |= Linker::Flags::DontForceLinkLinkonceODR;
457
458 if (TheLinker.linkInModule(std::move(SrcModule), Flags, &GlobalsToImport))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000459 report_fatal_error("Function Import: link error");
460
Mehdi Amini01e32132016-03-26 05:40:34 +0000461 ImportedCount += GlobalsToImport.size();
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000462 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000463
Teresa Johnsond29478f2016-03-27 15:27:30 +0000464 NumImported += ImportedCount;
465
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000466 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000467 << DestModule.getModuleIdentifier() << "\n");
468 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000469}
470
471/// Summary file to use for function importing when using -function-import from
472/// the command line.
473static cl::opt<std::string>
474 SummaryFile("summary-file",
475 cl::desc("The summary file to use for function importing."));
476
477static void diagnosticHandler(const DiagnosticInfo &DI) {
478 raw_ostream &OS = errs();
479 DiagnosticPrinterRawOStream DP(OS);
480 DI.print(DP);
481 OS << '\n';
482}
483
Teresa Johnson26ab5772016-03-15 00:04:37 +0000484/// Parse the summary index out of an IR file and return the summary
Mehdi Amini42418ab2015-11-24 06:07:49 +0000485/// index object if found, or nullptr if not.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000486static std::unique_ptr<ModuleSummaryIndex>
487getModuleSummaryIndexForFile(StringRef Path, std::string &Error,
488 DiagnosticHandlerFunction DiagnosticHandler) {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000489 std::unique_ptr<MemoryBuffer> Buffer;
490 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
491 MemoryBuffer::getFile(Path);
492 if (std::error_code EC = BufferOrErr.getError()) {
493 Error = EC.message();
494 return nullptr;
495 }
496 Buffer = std::move(BufferOrErr.get());
Teresa Johnson26ab5772016-03-15 00:04:37 +0000497 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
498 object::ModuleSummaryIndexObjectFile::create(Buffer->getMemBufferRef(),
499 DiagnosticHandler);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000500 if (std::error_code EC = ObjOrErr.getError()) {
501 Error = EC.message();
502 return nullptr;
503 }
504 return (*ObjOrErr)->takeIndex();
505}
506
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000507namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000508/// Pass that performs cross-module function import provided a summary file.
509class FunctionImportPass : public ModulePass {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000510 /// Optional module summary index to use for importing, otherwise
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000511 /// the summary-file option must be specified.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000512 const ModuleSummaryIndex *Index;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000513
514public:
515 /// Pass identification, replacement for typeid
516 static char ID;
517
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000518 /// Specify pass name for debug output
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000519 const char *getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000520
Teresa Johnson26ab5772016-03-15 00:04:37 +0000521 explicit FunctionImportPass(const ModuleSummaryIndex *Index = nullptr)
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000522 : ModulePass(ID), Index(Index) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000523
524 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000525 if (skipModule(M))
526 return false;
527
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000528 if (SummaryFile.empty() && !Index)
529 report_fatal_error("error: -function-import requires -summary-file or "
530 "file from frontend\n");
Teresa Johnson26ab5772016-03-15 00:04:37 +0000531 std::unique_ptr<ModuleSummaryIndex> IndexPtr;
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000532 if (!SummaryFile.empty()) {
533 if (Index)
534 report_fatal_error("error: -summary-file and index from frontend\n");
535 std::string Error;
Teresa Johnson26ab5772016-03-15 00:04:37 +0000536 IndexPtr =
537 getModuleSummaryIndexForFile(SummaryFile, Error, diagnosticHandler);
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000538 if (!IndexPtr) {
539 errs() << "Error loading file '" << SummaryFile << "': " << Error
540 << "\n";
541 return false;
542 }
543 Index = IndexPtr.get();
Mehdi Amini42418ab2015-11-24 06:07:49 +0000544 }
545
Teresa Johnsonc86af332016-04-12 21:13:11 +0000546 // First step is collecting the import list.
547 FunctionImporter::ImportMapTy ImportList;
548 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
549 ImportList);
Mehdi Amini01e32132016-03-26 05:40:34 +0000550
551 // Next we need to promote to global scope and rename any local values that
Teresa Johnson1b00f2d2016-01-08 17:06:29 +0000552 // are potentially exported to other modules.
Mehdi Amini01e32132016-03-26 05:40:34 +0000553 if (renameModuleForThinLTO(M, *Index, nullptr)) {
Teresa Johnson1b00f2d2016-01-08 17:06:29 +0000554 errs() << "Error renaming module\n";
555 return false;
556 }
557
Mehdi Amini42418ab2015-11-24 06:07:49 +0000558 // Perform the import now.
Mehdi Aminid16c8062015-12-08 22:39:40 +0000559 auto ModuleLoader = [&M](StringRef Identifier) {
560 return loadFile(Identifier, M.getContext());
561 };
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000562 FunctionImporter Importer(*Index, ModuleLoader);
Mehdi Aminibda3c972016-04-21 01:59:39 +0000563 return Importer.importFunctions(
564 M, ImportList, !DontForceImportReferencedDiscardableSymbols);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000565 }
566};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000567} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000568
569char FunctionImportPass::ID = 0;
570INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
571 "Summary Based Function Import", false, false)
572INITIALIZE_PASS_END(FunctionImportPass, "function-import",
573 "Summary Based Function Import", false, false)
574
575namespace llvm {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000576Pass *createFunctionImportPass(const ModuleSummaryIndex *Index = nullptr) {
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000577 return new FunctionImportPass(Index);
578}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000579}