blob: 29c54dc9f9cdc4ad98a4c5c9b8afc65ff35b862c [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"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000019#include "llvm/ADT/Triple.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000020#include "llvm/IR/AutoUpgrade.h"
21#include "llvm/IR/DiagnosticPrinter.h"
22#include "llvm/IR/IntrinsicInst.h"
23#include "llvm/IR/Module.h"
24#include "llvm/IRReader/IRReader.h"
25#include "llvm/Linker/Linker.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000026#include "llvm/Object/IRObjectFile.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000027#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000028#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/SourceMgr.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000031#include "llvm/Transforms/IPO/Internalize.h"
Teresa Johnson488a8002016-02-10 18:11:31 +000032#include "llvm/Transforms/Utils/FunctionImportUtils.h"
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000033
Mehdi Amini01e32132016-03-26 05:40:34 +000034#define DEBUG_TYPE "function-import"
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000035
Mehdi Amini42418ab2015-11-24 06:07:49 +000036using namespace llvm;
37
Teresa Johnsond29478f2016-03-27 15:27:30 +000038STATISTIC(NumImported, "Number of functions imported");
39
Teresa Johnson39303612015-11-24 22:55:46 +000040/// Limit on instruction count of imported functions.
41static cl::opt<unsigned> ImportInstrLimit(
42 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
43 cl::desc("Only import functions with less than N instructions"));
44
Mehdi Amini40641742016-02-10 23:31:45 +000045static cl::opt<float>
46 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
47 cl::Hidden, cl::value_desc("x"),
48 cl::desc("As we import functions, multiply the "
49 "`import-instr-limit` threshold by this factor "
50 "before processing newly imported functions"));
Piotr Padlewskiba72b952016-09-29 17:32:07 +000051
Piotr Padlewskid2869472016-09-30 03:01:17 +000052static cl::opt<float> ImportHotInstrFactor(
53 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
54 cl::value_desc("x"),
55 cl::desc("As we import functions called from hot callsite, multiply the "
56 "`import-instr-limit` threshold by this factor "
57 "before processing newly imported functions"));
58
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000059static cl::opt<float> ImportHotMultiplier(
60 "import-hot-multiplier", cl::init(3.0), cl::Hidden, cl::value_desc("x"),
Piotr Padlewskiba72b952016-09-29 17:32:07 +000061 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
62
63// FIXME: This multiplier was not really tuned up.
64static cl::opt<float> ImportColdMultiplier(
65 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
66 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
Mehdi Amini40641742016-02-10 23:31:45 +000067
Teresa Johnsond29478f2016-03-27 15:27:30 +000068static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
69 cl::desc("Print imported functions"));
70
Mehdi Aminibda3c972016-04-21 01:59:39 +000071// Temporary allows the function import pass to disable always linking
72// referenced discardable symbols.
73static cl::opt<bool>
74 DontForceImportReferencedDiscardableSymbols("disable-force-link-odr",
75 cl::init(false), cl::Hidden);
76
Piotr Padlewski3b776122016-07-08 23:01:49 +000077static cl::opt<bool> EnableImportMetadata(
78 "enable-import-metadata", cl::init(
79#if !defined(NDEBUG)
80 true /*Enabled with asserts.*/
81#else
82 false
83#endif
84 ),
85 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
86
Mehdi Amini42418ab2015-11-24 06:07:49 +000087// Load lazily a module from \p FileName in \p Context.
88static std::unique_ptr<Module> loadFile(const std::string &FileName,
89 LLVMContext &Context) {
90 SMDiagnostic Err;
91 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +000092 // Metadata isn't loaded until functions are imported, to minimize
93 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +000094 std::unique_ptr<Module> Result =
95 getLazyIRFileModule(FileName, Err, Context,
96 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +000097 if (!Result) {
98 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +000099 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000100 }
101
Mehdi Amini42418ab2015-11-24 06:07:49 +0000102 return Result;
103}
104
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000105namespace {
Mehdi Amini40641742016-02-10 23:31:45 +0000106
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000107// Return true if the Summary describes a GlobalValue that can be externally
108// referenced, i.e. it does not need renaming (linkage is not local) or renaming
109// is possible (does not have a section for instance).
110static bool canBeExternallyReferenced(const GlobalValueSummary &Summary) {
111 if (!Summary.needsRenaming())
112 return true;
113
114 if (Summary.hasSection())
115 // Can't rename a global that needs renaming if has a section.
116 return false;
117
118 return true;
119}
120
121// Return true if \p GUID describes a GlobalValue that can be externally
122// referenced, i.e. it does not need renaming (linkage is not local) or
123// renaming is possible (does not have a section for instance).
124static bool canBeExternallyReferenced(const ModuleSummaryIndex &Index,
125 GlobalValue::GUID GUID) {
126 auto Summaries = Index.findGlobalValueSummaryList(GUID);
127 if (Summaries == Index.end())
128 return true;
129 if (Summaries->second.size() != 1)
130 // If there are multiple globals with this GUID, then we know it is
131 // not a local symbol, and it is necessarily externally referenced.
132 return true;
133
134 // We don't need to check for the module path, because if it can't be
135 // externally referenced and we call it, it is necessarilly in the same
136 // module
137 return canBeExternallyReferenced(**Summaries->second.begin());
138}
139
140// Return true if the global described by \p Summary can be imported in another
141// module.
142static bool eligibleForImport(const ModuleSummaryIndex &Index,
143 const GlobalValueSummary &Summary) {
144 if (!canBeExternallyReferenced(Summary))
145 // Can't import a global that needs renaming if has a section for instance.
146 // FIXME: we may be able to import it by copying it without promotion.
147 return false;
148
Piotr Padlewski332b3b22016-08-11 22:13:57 +0000149 // Don't import functions that are not viable to inline.
150 if (Summary.isNotViableToInline())
151 return false;
152
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000153 // Check references (and potential calls) in the same module. If the current
154 // value references a global that can't be externally referenced it is not
155 // eligible for import.
156 bool AllRefsCanBeExternallyReferenced =
157 llvm::all_of(Summary.refs(), [&](const ValueInfo &VI) {
158 return canBeExternallyReferenced(Index, VI.getGUID());
159 });
160 if (!AllRefsCanBeExternallyReferenced)
161 return false;
162
163 if (auto *FuncSummary = dyn_cast<FunctionSummary>(&Summary)) {
164 bool AllCallsCanBeExternallyReferenced = llvm::all_of(
165 FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
166 return canBeExternallyReferenced(Index, Edge.first.getGUID());
167 });
168 if (!AllCallsCanBeExternallyReferenced)
169 return false;
170 }
171 return true;
172}
173
Mehdi Amini01e32132016-03-26 05:40:34 +0000174/// Given a list of possible callee implementation for a call site, select one
175/// that fits the \p Threshold.
176///
177/// FIXME: select "best" instead of first that fits. But what is "best"?
178/// - The smallest: more likely to be inlined.
179/// - The one with the least outgoing edges (already well optimized).
180/// - One from a module already being imported from in order to reduce the
181/// number of source modules parsed/linked.
182/// - One that has PGO data attached.
183/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000184static const GlobalValueSummary *
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000185selectCallee(const ModuleSummaryIndex &Index,
186 const GlobalValueSummaryList &CalleeSummaryList,
Teresa Johnson28e457b2016-04-24 14:57:11 +0000187 unsigned Threshold) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000188 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000189 CalleeSummaryList,
190 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
191 auto *GVSummary = SummaryPtr.get();
Rafael Espindolaf329be82016-05-11 01:26:06 +0000192 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000193 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000194 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000195 if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
196 GVSummary = &AS->getAliasee();
197 // Alias can't point to "available_externally". However when we import
198 // linkOnceODR the linkage does not change. So we import the alias
199 // and aliasee only in this case.
200 // FIXME: we should import alias as available_externally *function*,
201 // the destination module does need to know it is an alias.
202 if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
203 return false;
204 }
205
206 auto *Summary = cast<FunctionSummary>(GVSummary);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000207
Mehdi Amini01e32132016-03-26 05:40:34 +0000208 if (Summary->instCount() > Threshold)
209 return false;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000210
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000211 if (!eligibleForImport(Index, *Summary))
212 return false;
213
Mehdi Amini01e32132016-03-26 05:40:34 +0000214 return true;
215 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000216 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000217 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000218
Teresa Johnson28e457b2016-04-24 14:57:11 +0000219 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000220}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000221
Mehdi Amini01e32132016-03-26 05:40:34 +0000222/// Return the summary for the function \p GUID that fits the \p Threshold, or
223/// null if there's no match.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000224static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID,
225 unsigned Threshold,
226 const ModuleSummaryIndex &Index) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000227 auto CalleeSummaryList = Index.findGlobalValueSummaryList(GUID);
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000228 if (CalleeSummaryList == Index.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000229 return nullptr; // This function does not have a summary
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000230 return selectCallee(Index, CalleeSummaryList->second, Threshold);
Mehdi Amini01e32132016-03-26 05:40:34 +0000231}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000232
Mehdi Aminicb874942016-04-23 23:29:24 +0000233/// Mark the global \p GUID as export by module \p ExportModulePath if found in
234/// this module. If it is a GlobalVariable, we also mark any referenced global
235/// in the current module as exported.
236static void exportGlobalInModule(const ModuleSummaryIndex &Index,
237 StringRef ExportModulePath,
238 GlobalValue::GUID GUID,
239 FunctionImporter::ExportSetTy &ExportList) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000240 auto FindGlobalSummaryInModule =
241 [&](GlobalValue::GUID GUID) -> GlobalValueSummary *{
242 auto SummaryList = Index.findGlobalValueSummaryList(GUID);
243 if (SummaryList == Index.end())
Mehdi Aminicb874942016-04-23 23:29:24 +0000244 // This global does not have a summary, it is not part of the ThinLTO
245 // process
246 return nullptr;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000247 auto SummaryIter = llvm::find_if(
248 SummaryList->second,
249 [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
Mehdi Aminicb874942016-04-23 23:29:24 +0000250 return Summary->modulePath() == ExportModulePath;
251 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000252 if (SummaryIter == SummaryList->second.end())
Mehdi Aminicb874942016-04-23 23:29:24 +0000253 return nullptr;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000254 return SummaryIter->get();
Mehdi Aminicb874942016-04-23 23:29:24 +0000255 };
256
Teresa Johnson28e457b2016-04-24 14:57:11 +0000257 auto *Summary = FindGlobalSummaryInModule(GUID);
258 if (!Summary)
Mehdi Aminicb874942016-04-23 23:29:24 +0000259 return;
260 // We found it in the current module, mark as exported
261 ExportList.insert(GUID);
262
Mehdi Aminicb874942016-04-23 23:29:24 +0000263 auto GVS = dyn_cast<GlobalVarSummary>(Summary);
264 if (!GVS)
265 return;
266 // FunctionImportGlobalProcessing::doPromoteLocalToGlobal() will always
267 // trigger importing the initializer for `constant unnamed addr` globals that
268 // are referenced. We conservatively export all the referenced symbols for
269 // every global to workaround this, so that the ExportList is accurate.
270 // FIXME: with a "isConstant" flag in the summary we could be more targetted.
271 for (auto &Ref : GVS->refs()) {
272 auto GUID = Ref.getGUID();
Teresa Johnson28e457b2016-04-24 14:57:11 +0000273 auto *RefSummary = FindGlobalSummaryInModule(GUID);
274 if (RefSummary)
Mehdi Aminicb874942016-04-23 23:29:24 +0000275 // Found a ref in the current module, mark it as exported
276 ExportList.insert(GUID);
277 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000278}
Mehdi Amini40641742016-02-10 23:31:45 +0000279
Mehdi Amini01e32132016-03-26 05:40:34 +0000280using EdgeInfo = std::pair<const FunctionSummary *, unsigned /* Threshold */>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000281
Mehdi Amini01e32132016-03-26 05:40:34 +0000282/// Compute the list of functions to import for a given caller. Mark these
283/// imported functions and the symbols they reference in their source module as
284/// exported from their source module.
285static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000286 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000287 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000288 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000289 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000290 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000291 for (auto &Edge : Summary.calls()) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000292 auto GUID = Edge.first.getGUID();
Mehdi Amini01e32132016-03-26 05:40:34 +0000293 DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
294
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000295 if (DefinedGVSummaries.count(GUID)) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000296 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
297 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000298 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000299
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000300 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
301 if (Hotness == CalleeInfo::HotnessType::Hot)
302 return ImportHotMultiplier;
303 if (Hotness == CalleeInfo::HotnessType::Cold)
304 return ImportColdMultiplier;
305 return 1.0;
306 };
307
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000308 const auto NewThreshold =
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000309 Threshold * GetBonusMultiplier(Edge.second.Hotness);
Piotr Padlewskid2869472016-09-30 03:01:17 +0000310
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000311 auto *CalleeSummary = selectCallee(GUID, NewThreshold, Index);
Mehdi Amini01e32132016-03-26 05:40:34 +0000312 if (!CalleeSummary) {
313 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
314 continue;
315 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000316 // "Resolve" the summary, traversing alias,
317 const FunctionSummary *ResolvedCalleeSummary;
Mehdi Amini6968ef72016-04-20 01:04:20 +0000318 if (isa<AliasSummary>(CalleeSummary)) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000319 ResolvedCalleeSummary = cast<FunctionSummary>(
320 &cast<AliasSummary>(CalleeSummary)->getAliasee());
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000321 assert(
322 GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
323 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini6968ef72016-04-20 01:04:20 +0000324 } else
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000325 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
326
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000327 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000328 "selectCallee() didn't honor the threshold");
329
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000330 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
Mehdi Amini9b490f12016-08-16 05:47:12 +0000331 auto &ProcessedThreshold = ImportList[ExportModulePath][GUID];
Mehdi Amini01e32132016-03-26 05:40:34 +0000332 /// Since the traversal of the call graph is DFS, we can revisit a function
333 /// a second time with a higher threshold. In this case, it is added back to
334 /// the worklist with the new threshold.
Teresa Johnson2e030942016-05-11 22:56:19 +0000335 if (ProcessedThreshold && ProcessedThreshold >= Threshold) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000336 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
337 << ProcessedThreshold << "\n");
338 continue;
339 }
340 // Mark this function as imported in this module, with the current Threshold
341 ProcessedThreshold = Threshold;
342
343 // Make exports in the source module.
Teresa Johnsonc86af332016-04-12 21:13:11 +0000344 if (ExportLists) {
Mehdi Aminief7555f2016-04-13 01:52:32 +0000345 auto &ExportList = (*ExportLists)[ExportModulePath];
Teresa Johnsonc86af332016-04-12 21:13:11 +0000346 ExportList.insert(GUID);
347 // Mark all functions and globals referenced by this function as exported
348 // to the outside if they are defined in the same source module.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000349 for (auto &Edge : ResolvedCalleeSummary->calls()) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000350 auto CalleeGUID = Edge.first.getGUID();
Mehdi Aminicb874942016-04-23 23:29:24 +0000351 exportGlobalInModule(Index, ExportModulePath, CalleeGUID, ExportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000352 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000353 for (auto &Ref : ResolvedCalleeSummary->refs()) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000354 auto GUID = Ref.getGUID();
Mehdi Aminicb874942016-04-23 23:29:24 +0000355 exportGlobalInModule(Index, ExportModulePath, GUID, ExportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000356 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000357 }
358
Piotr Padlewskid2869472016-09-30 03:01:17 +0000359 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
360 // Adjust the threshold for next level of imported functions.
361 // The threshold is different for hot callsites because we can then
362 // inline chains of hot calls.
363 if (IsHotCallsite)
364 return Threshold * ImportHotInstrFactor;
365 return Threshold * ImportInstrFactor;
366 };
367
368 bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
369
Mehdi Amini01e32132016-03-26 05:40:34 +0000370 // Insert the newly imported function to the worklist.
Piotr Padlewskid2869472016-09-30 03:01:17 +0000371 Worklist.emplace_back(ResolvedCalleeSummary,
372 GetAdjustedThreshold(Threshold, IsHotCallsite));
Teresa Johnsond450da32015-11-24 21:15:19 +0000373 }
374}
375
Mehdi Amini01e32132016-03-26 05:40:34 +0000376/// Given the list of globals defined in a module, compute the list of imports
377/// as well as the list of "exports", i.e. the list of symbols referenced from
378/// another module (that may require promotion).
379static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000380 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000381 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000382 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000383 // Worklist contains the list of function imported in this module, for which
384 // we will analyse the callees and may import further down the callgraph.
385 SmallVector<EdgeInfo, 128> Worklist;
386
387 // Populate the worklist with the import for the functions in the current
388 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000389 for (auto &GVSummary : DefinedGVSummaries) {
390 auto *Summary = GVSummary.second;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000391 if (auto *AS = dyn_cast<AliasSummary>(Summary))
392 Summary = &AS->getAliasee();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000393 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
394 if (!FuncSummary)
395 // Skip import for global variables
396 continue;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000397 DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000398 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000399 DefinedGVSummaries, Worklist, ImportList,
Mehdi Amini01e32132016-03-26 05:40:34 +0000400 ExportLists);
401 }
402
Piotr Padlewskid2869472016-09-30 03:01:17 +0000403 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000404 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000405 auto FuncInfo = Worklist.pop_back_val();
406 auto *Summary = FuncInfo.first;
407 auto Threshold = FuncInfo.second;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000408
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000409 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000410 Worklist, ImportList, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000411 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000412}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000413
Mehdi Amini01e32132016-03-26 05:40:34 +0000414} // anonymous namespace
415
Teresa Johnsonc86af332016-04-12 21:13:11 +0000416/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000417void llvm::ComputeCrossModuleImport(
418 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000419 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000420 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
421 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000422 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000423 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000424 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000425 DEBUG(dbgs() << "Computing import for Module '"
426 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000427 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000428 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000429 }
430
431#ifndef NDEBUG
432 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
433 << " modules:\n");
434 for (auto &ModuleImports : ImportLists) {
435 auto ModName = ModuleImports.first();
436 auto &Exports = ExportLists[ModName];
437 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
438 << " functions. Imports from " << ModuleImports.second.size()
439 << " modules.\n");
440 for (auto &Src : ModuleImports.second) {
441 auto SrcModName = Src.first();
442 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
443 << SrcModName << "\n");
444 }
445 }
446#endif
447}
448
Teresa Johnsonc86af332016-04-12 21:13:11 +0000449/// Compute all the imports for the given module in the Index.
450void llvm::ComputeCrossModuleImportForModule(
451 StringRef ModulePath, const ModuleSummaryIndex &Index,
452 FunctionImporter::ImportMapTy &ImportList) {
453
454 // Collect the list of functions this module defines.
455 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000456 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000457 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000458
459 // Compute the import list for this module.
460 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000461 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000462
463#ifndef NDEBUG
464 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
465 << ImportList.size() << " modules.\n");
466 for (auto &Src : ImportList) {
467 auto SrcModName = Src.first();
468 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
469 << SrcModName << "\n");
470 }
471#endif
472}
473
Teresa Johnson84174c32016-05-10 13:48:23 +0000474/// Compute the set of summaries needed for a ThinLTO backend compilation of
475/// \p ModulePath.
476void llvm::gatherImportedSummariesForModule(
477 StringRef ModulePath,
478 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000479 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000480 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
481 // Include all summaries from the importing module.
482 ModuleToSummariesForIndex[ModulePath] =
483 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000484 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000485 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000486 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
487 const auto &DefinedGVSummaries =
488 ModuleToDefinedGVSummaries.lookup(ILI.first());
489 for (auto &GI : ILI.second) {
490 const auto &DS = DefinedGVSummaries.find(GI.first);
491 assert(DS != DefinedGVSummaries.end() &&
492 "Expected a defined summary for imported global value");
493 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000494 }
495 }
496}
497
Teresa Johnson8570fe42016-05-10 15:54:09 +0000498/// Emit the files \p ModulePath will import from into \p OutputFilename.
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000499std::error_code
500llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
501 const FunctionImporter::ImportMapTy &ModuleImports) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000502 std::error_code EC;
503 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
504 if (EC)
505 return EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000506 for (auto &ILI : ModuleImports)
507 ImportsOS << ILI.first() << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000508 return std::error_code();
509}
510
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000511/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
512void llvm::thinLTOResolveWeakForLinkerModule(
513 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
514 auto updateLinkage = [&](GlobalValue &GV) {
515 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
516 return;
517 // See if the global summary analysis computed a new resolved linkage.
518 const auto &GS = DefinedGlobals.find(GV.getGUID());
519 if (GS == DefinedGlobals.end())
520 return;
521 auto NewLinkage = GS->second->linkage();
522 if (NewLinkage == GV.getLinkage())
523 return;
524 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
525 << GV.getLinkage() << " to " << NewLinkage << "\n");
526 GV.setLinkage(NewLinkage);
Teresa Johnson6107a412016-08-15 21:00:04 +0000527 // Remove functions converted to available_externally from comdats,
528 // as this is a declaration for the linker, and will be dropped eventually.
529 // It is illegal for comdats to contain declarations.
530 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
531 if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
532 assert(GO->hasAvailableExternallyLinkage() &&
533 "Expected comdat on definition (possibly available external)");
534 GO->setComdat(nullptr);
535 }
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000536 };
537
538 // Process functions and global now
539 for (auto &GV : TheModule)
540 updateLinkage(GV);
541 for (auto &GV : TheModule.globals())
542 updateLinkage(GV);
543 for (auto &GV : TheModule.aliases())
544 updateLinkage(GV);
545}
546
547/// Run internalization on \p TheModule based on symmary analysis.
548void llvm::thinLTOInternalizeModule(Module &TheModule,
549 const GVSummaryMapTy &DefinedGlobals) {
550 // Parse inline ASM and collect the list of symbols that are not defined in
551 // the current module.
552 StringSet<> AsmUndefinedRefs;
553 object::IRObjectFile::CollectAsmUndefinedRefs(
554 Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
555 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
556 if (Flags & object::BasicSymbolRef::SF_Undefined)
557 AsmUndefinedRefs.insert(Name);
558 });
559
560 // Declare a callback for the internalize pass that will ask for every
561 // candidate GlobalValue if it can be internalized or not.
562 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
563 // Can't be internalized if referenced in inline asm.
564 if (AsmUndefinedRefs.count(GV.getName()))
565 return true;
566
567 // Lookup the linkage recorded in the summaries during global analysis.
568 const auto &GS = DefinedGlobals.find(GV.getGUID());
569 GlobalValue::LinkageTypes Linkage;
570 if (GS == DefinedGlobals.end()) {
571 // Must have been promoted (possibly conservatively). Find original
572 // name so that we can access the correct summary and see if it can
573 // be internalized again.
574 // FIXME: Eventually we should control promotion instead of promoting
575 // and internalizing again.
576 StringRef OrigName =
577 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
578 std::string OrigId = GlobalValue::getGlobalIdentifier(
579 OrigName, GlobalValue::InternalLinkage,
580 TheModule.getSourceFileName());
581 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000582 if (GS == DefinedGlobals.end()) {
583 // Also check the original non-promoted non-globalized name. In some
584 // cases a preempted weak value is linked in as a local copy because
585 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
586 // In that case, since it was originally not a local value, it was
587 // recorded in the index using the original name.
588 // FIXME: This may not be needed once PR27866 is fixed.
589 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
590 assert(GS != DefinedGlobals.end());
591 Linkage = GS->second->linkage();
592 } else {
593 Linkage = GS->second->linkage();
594 }
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000595 } else
596 Linkage = GS->second->linkage();
597 return !GlobalValue::isLocalLinkage(Linkage);
598 };
599
600 // FIXME: See if we can just internalize directly here via linkage changes
601 // based on the index, rather than invoking internalizeModule.
602 llvm::internalizeModule(TheModule, MustPreserveGV);
603}
604
Mehdi Aminic8c55172015-12-03 02:37:33 +0000605// Automatically import functions in Module \p DestModule based on the summaries
606// index.
607//
Mehdi Amini01e32132016-03-26 05:40:34 +0000608bool FunctionImporter::importFunctions(
Mehdi Aminibda3c972016-04-21 01:59:39 +0000609 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList,
610 bool ForceImportReferencedDiscardableSymbols) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000611 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000612 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000613 unsigned ImportedCount = 0;
614
Mehdi Aminic8c55172015-12-03 02:37:33 +0000615 // Linker that will be used for importing function
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000616 Linker TheLinker(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000617 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000618 std::set<StringRef> ModuleNameOrderedList;
619 for (auto &FunctionsToImportPerModule : ImportList) {
620 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
621 }
622 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000623 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000624 const auto &FunctionsToImportPerModule = ImportList.find(Name);
625 assert(FunctionsToImportPerModule != ImportList.end());
626 std::unique_ptr<Module> SrcModule = ModuleLoader(Name);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000627 assert(&DestModule.getContext() == &SrcModule->getContext() &&
628 "Context mismatch");
629
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000630 // If modules were created with lazy metadata loading, materialize it
631 // now, before linking it (otherwise this will be a noop).
632 SrcModule->materializeMetadata();
633 UpgradeDebugInfo(*SrcModule);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000634
Mehdi Amini01e32132016-03-26 05:40:34 +0000635 auto &ImportGUIDs = FunctionsToImportPerModule->second;
636 // Find the globals to import
637 DenseSet<const GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000638 for (Function &F : *SrcModule) {
639 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000640 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000641 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000642 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000643 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000644 << " " << F.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000645 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000646 if (Import) {
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000647 F.materialize();
Piotr Padlewski3b776122016-07-08 23:01:49 +0000648 if (EnableImportMetadata) {
649 // Add 'thinlto_src_module' metadata for statistics and debugging.
650 F.setMetadata(
651 "thinlto_src_module",
652 llvm::MDNode::get(
653 DestModule.getContext(),
654 {llvm::MDString::get(DestModule.getContext(),
655 SrcModule->getSourceFileName())}));
656 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000657 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000658 }
659 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000660 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000661 if (!GV.hasName())
662 continue;
663 auto GUID = GV.getGUID();
664 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000665 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
666 << " " << GV.getName() << " from "
667 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000668 if (Import) {
669 GV.materialize();
670 GlobalsToImport.insert(&GV);
671 }
672 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000673 for (GlobalAlias &GA : SrcModule->aliases()) {
674 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000675 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000676 auto GUID = GA.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000677 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000678 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000679 << " " << GA.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000680 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000681 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000682 // Alias can't point to "available_externally". However when we import
Teresa Johnson9aae3952016-03-27 15:01:11 +0000683 // linkOnceODR the linkage does not change. So we import the alias
Mehdi Amini6968ef72016-04-20 01:04:20 +0000684 // and aliasee only in this case. This has been handled by
685 // computeImportForFunction()
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000686 GlobalObject *GO = GA.getBaseObject();
Mehdi Amini6968ef72016-04-20 01:04:20 +0000687 assert(GO->hasLinkOnceODRLinkage() &&
688 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000689#ifndef NDEBUG
690 if (!GlobalsToImport.count(GO))
691 DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
692 << " " << GO->getName() << " from "
693 << SrcModule->getSourceFileName() << "\n");
694#endif
695 GO->materialize();
Mehdi Amini01e32132016-03-26 05:40:34 +0000696 GlobalsToImport.insert(GO);
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000697 GA.materialize();
698 GlobalsToImport.insert(&GA);
Mehdi Amini01e32132016-03-26 05:40:34 +0000699 }
700 }
701
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000702 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000703 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000704 return true;
705
Teresa Johnsond29478f2016-03-27 15:27:30 +0000706 if (PrintImports) {
707 for (const auto *GV : GlobalsToImport)
708 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
709 << " from " << SrcModule->getSourceFileName() << "\n";
710 }
711
Mehdi Aminibda3c972016-04-21 01:59:39 +0000712 // Instruct the linker that the client will take care of linkonce resolution
713 unsigned Flags = Linker::Flags::None;
714 if (!ForceImportReferencedDiscardableSymbols)
715 Flags |= Linker::Flags::DontForceLinkLinkonceODR;
716
717 if (TheLinker.linkInModule(std::move(SrcModule), Flags, &GlobalsToImport))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000718 report_fatal_error("Function Import: link error");
719
Mehdi Amini01e32132016-03-26 05:40:34 +0000720 ImportedCount += GlobalsToImport.size();
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000721 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000722
Teresa Johnsond29478f2016-03-27 15:27:30 +0000723 NumImported += ImportedCount;
724
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000725 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000726 << DestModule.getModuleIdentifier() << "\n");
727 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000728}
729
730/// Summary file to use for function importing when using -function-import from
731/// the command line.
732static cl::opt<std::string>
733 SummaryFile("summary-file",
734 cl::desc("The summary file to use for function importing."));
735
736static void diagnosticHandler(const DiagnosticInfo &DI) {
737 raw_ostream &OS = errs();
738 DiagnosticPrinterRawOStream DP(OS);
739 DI.print(DP);
740 OS << '\n';
741}
742
Teresa Johnson26ab5772016-03-15 00:04:37 +0000743/// Parse the summary index out of an IR file and return the summary
Mehdi Amini42418ab2015-11-24 06:07:49 +0000744/// index object if found, or nullptr if not.
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000745static std::unique_ptr<ModuleSummaryIndex> getModuleSummaryIndexForFile(
746 StringRef Path, std::string &Error,
747 const DiagnosticHandlerFunction &DiagnosticHandler) {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000748 std::unique_ptr<MemoryBuffer> Buffer;
749 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
750 MemoryBuffer::getFile(Path);
751 if (std::error_code EC = BufferOrErr.getError()) {
752 Error = EC.message();
753 return nullptr;
754 }
755 Buffer = std::move(BufferOrErr.get());
Teresa Johnson26ab5772016-03-15 00:04:37 +0000756 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
757 object::ModuleSummaryIndexObjectFile::create(Buffer->getMemBufferRef(),
758 DiagnosticHandler);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000759 if (std::error_code EC = ObjOrErr.getError()) {
760 Error = EC.message();
761 return nullptr;
762 }
763 return (*ObjOrErr)->takeIndex();
764}
765
Teresa Johnson21241572016-07-18 21:22:24 +0000766static bool doImportingForModule(Module &M, const ModuleSummaryIndex *Index) {
767 if (SummaryFile.empty() && !Index)
768 report_fatal_error("error: -function-import requires -summary-file or "
769 "file from frontend\n");
770 std::unique_ptr<ModuleSummaryIndex> IndexPtr;
771 if (!SummaryFile.empty()) {
772 if (Index)
773 report_fatal_error("error: -summary-file and index from frontend\n");
774 std::string Error;
775 IndexPtr =
776 getModuleSummaryIndexForFile(SummaryFile, Error, diagnosticHandler);
777 if (!IndexPtr) {
778 errs() << "Error loading file '" << SummaryFile << "': " << Error << "\n";
779 return false;
780 }
781 Index = IndexPtr.get();
782 }
783
784 // First step is collecting the import list.
785 FunctionImporter::ImportMapTy ImportList;
786 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
787 ImportList);
788
789 // Next we need to promote to global scope and rename any local values that
790 // are potentially exported to other modules.
791 if (renameModuleForThinLTO(M, *Index, nullptr)) {
792 errs() << "Error renaming module\n";
793 return false;
794 }
795
796 // Perform the import now.
797 auto ModuleLoader = [&M](StringRef Identifier) {
798 return loadFile(Identifier, M.getContext());
799 };
800 FunctionImporter Importer(*Index, ModuleLoader);
801 return Importer.importFunctions(M, ImportList,
802 !DontForceImportReferencedDiscardableSymbols);
803}
804
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000805namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000806/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +0000807class FunctionImportLegacyPass : public ModulePass {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000808 /// Optional module summary index to use for importing, otherwise
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000809 /// the summary-file option must be specified.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000810 const ModuleSummaryIndex *Index;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000811
812public:
813 /// Pass identification, replacement for typeid
814 static char ID;
815
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000816 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +0000817 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000818
Teresa Johnson21241572016-07-18 21:22:24 +0000819 explicit FunctionImportLegacyPass(const ModuleSummaryIndex *Index = nullptr)
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000820 : ModulePass(ID), Index(Index) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000821
822 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000823 if (skipModule(M))
824 return false;
825
Teresa Johnson21241572016-07-18 21:22:24 +0000826 return doImportingForModule(M, Index);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000827 }
828};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000829} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000830
Teresa Johnson21241572016-07-18 21:22:24 +0000831PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000832 ModuleAnalysisManager &AM) {
Teresa Johnson21241572016-07-18 21:22:24 +0000833 if (!doImportingForModule(M, Index))
834 return PreservedAnalyses::all();
835
836 return PreservedAnalyses::none();
837}
838
839char FunctionImportLegacyPass::ID = 0;
840INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
841 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +0000842
843namespace llvm {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000844Pass *createFunctionImportPass(const ModuleSummaryIndex *Index = nullptr) {
Teresa Johnson21241572016-07-18 21:22:24 +0000845 return new FunctionImportLegacyPass(Index);
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000846}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000847}