blob: 25dd2f0c323792733a795c5c5e30e667dc148508 [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
Teresa Johnson58fbc912016-10-28 02:24:59 +0000114 if (Summary.noRename())
115 // Can't externally reference a global that needs renaming if has a section
116 // or is referenced from inline assembly, for example.
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000117 return false;
118
119 return true;
120}
121
122// Return true if \p GUID describes a GlobalValue that can be externally
123// referenced, i.e. it does not need renaming (linkage is not local) or
124// renaming is possible (does not have a section for instance).
125static bool canBeExternallyReferenced(const ModuleSummaryIndex &Index,
126 GlobalValue::GUID GUID) {
127 auto Summaries = Index.findGlobalValueSummaryList(GUID);
128 if (Summaries == Index.end())
129 return true;
130 if (Summaries->second.size() != 1)
131 // If there are multiple globals with this GUID, then we know it is
132 // not a local symbol, and it is necessarily externally referenced.
133 return true;
134
135 // We don't need to check for the module path, because if it can't be
136 // externally referenced and we call it, it is necessarilly in the same
137 // module
138 return canBeExternallyReferenced(**Summaries->second.begin());
139}
140
141// Return true if the global described by \p Summary can be imported in another
142// module.
143static bool eligibleForImport(const ModuleSummaryIndex &Index,
144 const GlobalValueSummary &Summary) {
145 if (!canBeExternallyReferenced(Summary))
146 // Can't import a global that needs renaming if has a section for instance.
147 // FIXME: we may be able to import it by copying it without promotion.
148 return false;
149
Piotr Padlewski332b3b22016-08-11 22:13:57 +0000150 // Don't import functions that are not viable to inline.
151 if (Summary.isNotViableToInline())
152 return false;
153
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000154 // Check references (and potential calls) in the same module. If the current
155 // value references a global that can't be externally referenced it is not
Teresa Johnsond5033a42016-11-14 16:40:19 +0000156 // eligible for import. First check the flag set when we have possible
157 // opaque references (e.g. inline asm calls), then check the call and
158 // reference sets.
159 if (Summary.hasInlineAsmMaybeReferencingInternal())
160 return false;
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000161 bool AllRefsCanBeExternallyReferenced =
162 llvm::all_of(Summary.refs(), [&](const ValueInfo &VI) {
163 return canBeExternallyReferenced(Index, VI.getGUID());
164 });
165 if (!AllRefsCanBeExternallyReferenced)
166 return false;
167
168 if (auto *FuncSummary = dyn_cast<FunctionSummary>(&Summary)) {
169 bool AllCallsCanBeExternallyReferenced = llvm::all_of(
170 FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
171 return canBeExternallyReferenced(Index, Edge.first.getGUID());
172 });
173 if (!AllCallsCanBeExternallyReferenced)
174 return false;
175 }
176 return true;
177}
178
Mehdi Amini01e32132016-03-26 05:40:34 +0000179/// Given a list of possible callee implementation for a call site, select one
180/// that fits the \p Threshold.
181///
182/// FIXME: select "best" instead of first that fits. But what is "best"?
183/// - The smallest: more likely to be inlined.
184/// - The one with the least outgoing edges (already well optimized).
185/// - One from a module already being imported from in order to reduce the
186/// number of source modules parsed/linked.
187/// - One that has PGO data attached.
188/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000189static const GlobalValueSummary *
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000190selectCallee(const ModuleSummaryIndex &Index,
191 const GlobalValueSummaryList &CalleeSummaryList,
Teresa Johnson28e457b2016-04-24 14:57:11 +0000192 unsigned Threshold) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000193 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000194 CalleeSummaryList,
195 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
196 auto *GVSummary = SummaryPtr.get();
Rafael Espindolaf329be82016-05-11 01:26:06 +0000197 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000198 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000199 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000200 if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
201 GVSummary = &AS->getAliasee();
202 // Alias can't point to "available_externally". However when we import
203 // linkOnceODR the linkage does not change. So we import the alias
204 // and aliasee only in this case.
205 // FIXME: we should import alias as available_externally *function*,
206 // the destination module does need to know it is an alias.
207 if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
208 return false;
209 }
210
211 auto *Summary = cast<FunctionSummary>(GVSummary);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000212
Mehdi Amini01e32132016-03-26 05:40:34 +0000213 if (Summary->instCount() > Threshold)
214 return false;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000215
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000216 if (!eligibleForImport(Index, *Summary))
217 return false;
218
Mehdi Amini01e32132016-03-26 05:40:34 +0000219 return true;
220 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000221 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000222 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000223
Teresa Johnson28e457b2016-04-24 14:57:11 +0000224 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000225}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000226
Mehdi Amini01e32132016-03-26 05:40:34 +0000227/// Return the summary for the function \p GUID that fits the \p Threshold, or
228/// null if there's no match.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000229static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID,
230 unsigned Threshold,
231 const ModuleSummaryIndex &Index) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000232 auto CalleeSummaryList = Index.findGlobalValueSummaryList(GUID);
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000233 if (CalleeSummaryList == Index.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000234 return nullptr; // This function does not have a summary
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000235 return selectCallee(Index, CalleeSummaryList->second, Threshold);
Mehdi Amini01e32132016-03-26 05:40:34 +0000236}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000237
Mehdi Aminicb874942016-04-23 23:29:24 +0000238/// Mark the global \p GUID as export by module \p ExportModulePath if found in
239/// this module. If it is a GlobalVariable, we also mark any referenced global
240/// in the current module as exported.
241static void exportGlobalInModule(const ModuleSummaryIndex &Index,
242 StringRef ExportModulePath,
243 GlobalValue::GUID GUID,
244 FunctionImporter::ExportSetTy &ExportList) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000245 auto FindGlobalSummaryInModule =
246 [&](GlobalValue::GUID GUID) -> GlobalValueSummary *{
247 auto SummaryList = Index.findGlobalValueSummaryList(GUID);
248 if (SummaryList == Index.end())
Mehdi Aminicb874942016-04-23 23:29:24 +0000249 // This global does not have a summary, it is not part of the ThinLTO
250 // process
251 return nullptr;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000252 auto SummaryIter = llvm::find_if(
253 SummaryList->second,
254 [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
Mehdi Aminicb874942016-04-23 23:29:24 +0000255 return Summary->modulePath() == ExportModulePath;
256 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000257 if (SummaryIter == SummaryList->second.end())
Mehdi Aminicb874942016-04-23 23:29:24 +0000258 return nullptr;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000259 return SummaryIter->get();
Mehdi Aminicb874942016-04-23 23:29:24 +0000260 };
261
Teresa Johnson28e457b2016-04-24 14:57:11 +0000262 auto *Summary = FindGlobalSummaryInModule(GUID);
263 if (!Summary)
Mehdi Aminicb874942016-04-23 23:29:24 +0000264 return;
265 // We found it in the current module, mark as exported
266 ExportList.insert(GUID);
267
Mehdi Aminicb874942016-04-23 23:29:24 +0000268 auto GVS = dyn_cast<GlobalVarSummary>(Summary);
269 if (!GVS)
270 return;
271 // FunctionImportGlobalProcessing::doPromoteLocalToGlobal() will always
272 // trigger importing the initializer for `constant unnamed addr` globals that
273 // are referenced. We conservatively export all the referenced symbols for
274 // every global to workaround this, so that the ExportList is accurate.
275 // FIXME: with a "isConstant" flag in the summary we could be more targetted.
276 for (auto &Ref : GVS->refs()) {
277 auto GUID = Ref.getGUID();
Teresa Johnson28e457b2016-04-24 14:57:11 +0000278 auto *RefSummary = FindGlobalSummaryInModule(GUID);
279 if (RefSummary)
Mehdi Aminicb874942016-04-23 23:29:24 +0000280 // Found a ref in the current module, mark it as exported
281 ExportList.insert(GUID);
282 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000283}
Mehdi Amini40641742016-02-10 23:31:45 +0000284
Mehdi Amini01e32132016-03-26 05:40:34 +0000285using EdgeInfo = std::pair<const FunctionSummary *, unsigned /* Threshold */>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000286
Mehdi Amini01e32132016-03-26 05:40:34 +0000287/// Compute the list of functions to import for a given caller. Mark these
288/// imported functions and the symbols they reference in their source module as
289/// exported from their source module.
290static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000291 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000292 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000293 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000294 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000295 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000296 for (auto &Edge : Summary.calls()) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000297 auto GUID = Edge.first.getGUID();
Mehdi Amini01e32132016-03-26 05:40:34 +0000298 DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
299
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000300 if (DefinedGVSummaries.count(GUID)) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000301 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
302 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000303 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000304
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000305 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
306 if (Hotness == CalleeInfo::HotnessType::Hot)
307 return ImportHotMultiplier;
308 if (Hotness == CalleeInfo::HotnessType::Cold)
309 return ImportColdMultiplier;
310 return 1.0;
311 };
312
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000313 const auto NewThreshold =
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000314 Threshold * GetBonusMultiplier(Edge.second.Hotness);
Piotr Padlewskid2869472016-09-30 03:01:17 +0000315
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000316 auto *CalleeSummary = selectCallee(GUID, NewThreshold, Index);
Mehdi Amini01e32132016-03-26 05:40:34 +0000317 if (!CalleeSummary) {
318 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
319 continue;
320 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000321 // "Resolve" the summary, traversing alias,
322 const FunctionSummary *ResolvedCalleeSummary;
Mehdi Amini6968ef72016-04-20 01:04:20 +0000323 if (isa<AliasSummary>(CalleeSummary)) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000324 ResolvedCalleeSummary = cast<FunctionSummary>(
325 &cast<AliasSummary>(CalleeSummary)->getAliasee());
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000326 assert(
327 GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
328 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini6968ef72016-04-20 01:04:20 +0000329 } else
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000330 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
331
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000332 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000333 "selectCallee() didn't honor the threshold");
334
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000335 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
Mehdi Amini9b490f12016-08-16 05:47:12 +0000336 auto &ProcessedThreshold = ImportList[ExportModulePath][GUID];
Mehdi Amini01e32132016-03-26 05:40:34 +0000337 /// Since the traversal of the call graph is DFS, we can revisit a function
338 /// a second time with a higher threshold. In this case, it is added back to
339 /// the worklist with the new threshold.
Teresa Johnson2e030942016-05-11 22:56:19 +0000340 if (ProcessedThreshold && ProcessedThreshold >= Threshold) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000341 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
342 << ProcessedThreshold << "\n");
343 continue;
344 }
345 // Mark this function as imported in this module, with the current Threshold
346 ProcessedThreshold = Threshold;
347
348 // Make exports in the source module.
Teresa Johnsonc86af332016-04-12 21:13:11 +0000349 if (ExportLists) {
Mehdi Aminief7555f2016-04-13 01:52:32 +0000350 auto &ExportList = (*ExportLists)[ExportModulePath];
Teresa Johnsonc86af332016-04-12 21:13:11 +0000351 ExportList.insert(GUID);
352 // Mark all functions and globals referenced by this function as exported
353 // to the outside if they are defined in the same source module.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000354 for (auto &Edge : ResolvedCalleeSummary->calls()) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000355 auto CalleeGUID = Edge.first.getGUID();
Mehdi Aminicb874942016-04-23 23:29:24 +0000356 exportGlobalInModule(Index, ExportModulePath, CalleeGUID, ExportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000357 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000358 for (auto &Ref : ResolvedCalleeSummary->refs()) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000359 auto GUID = Ref.getGUID();
Mehdi Aminicb874942016-04-23 23:29:24 +0000360 exportGlobalInModule(Index, ExportModulePath, GUID, ExportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000361 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000362 }
363
Piotr Padlewskid2869472016-09-30 03:01:17 +0000364 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
365 // Adjust the threshold for next level of imported functions.
366 // The threshold is different for hot callsites because we can then
367 // inline chains of hot calls.
368 if (IsHotCallsite)
369 return Threshold * ImportHotInstrFactor;
370 return Threshold * ImportInstrFactor;
371 };
372
373 bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
374
Mehdi Amini01e32132016-03-26 05:40:34 +0000375 // Insert the newly imported function to the worklist.
Piotr Padlewskid2869472016-09-30 03:01:17 +0000376 Worklist.emplace_back(ResolvedCalleeSummary,
377 GetAdjustedThreshold(Threshold, IsHotCallsite));
Teresa Johnsond450da32015-11-24 21:15:19 +0000378 }
379}
380
Mehdi Amini01e32132016-03-26 05:40:34 +0000381/// Given the list of globals defined in a module, compute the list of imports
382/// as well as the list of "exports", i.e. the list of symbols referenced from
383/// another module (that may require promotion).
384static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000385 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000386 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000387 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000388 // Worklist contains the list of function imported in this module, for which
389 // we will analyse the callees and may import further down the callgraph.
390 SmallVector<EdgeInfo, 128> Worklist;
391
392 // Populate the worklist with the import for the functions in the current
393 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000394 for (auto &GVSummary : DefinedGVSummaries) {
395 auto *Summary = GVSummary.second;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000396 if (auto *AS = dyn_cast<AliasSummary>(Summary))
397 Summary = &AS->getAliasee();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000398 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
399 if (!FuncSummary)
400 // Skip import for global variables
401 continue;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000402 DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000403 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000404 DefinedGVSummaries, Worklist, ImportList,
Mehdi Amini01e32132016-03-26 05:40:34 +0000405 ExportLists);
406 }
407
Piotr Padlewskid2869472016-09-30 03:01:17 +0000408 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000409 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000410 auto FuncInfo = Worklist.pop_back_val();
411 auto *Summary = FuncInfo.first;
412 auto Threshold = FuncInfo.second;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000413
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000414 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000415 Worklist, ImportList, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000416 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000417}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000418
Mehdi Amini01e32132016-03-26 05:40:34 +0000419} // anonymous namespace
420
Teresa Johnsonc86af332016-04-12 21:13:11 +0000421/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000422void llvm::ComputeCrossModuleImport(
423 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000424 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000425 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
426 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000427 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000428 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000429 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000430 DEBUG(dbgs() << "Computing import for Module '"
431 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000432 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000433 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000434 }
435
436#ifndef NDEBUG
437 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
438 << " modules:\n");
439 for (auto &ModuleImports : ImportLists) {
440 auto ModName = ModuleImports.first();
441 auto &Exports = ExportLists[ModName];
442 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
443 << " functions. Imports from " << ModuleImports.second.size()
444 << " modules.\n");
445 for (auto &Src : ModuleImports.second) {
446 auto SrcModName = Src.first();
447 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
448 << SrcModName << "\n");
449 }
450 }
451#endif
452}
453
Teresa Johnsonc86af332016-04-12 21:13:11 +0000454/// Compute all the imports for the given module in the Index.
455void llvm::ComputeCrossModuleImportForModule(
456 StringRef ModulePath, const ModuleSummaryIndex &Index,
457 FunctionImporter::ImportMapTy &ImportList) {
458
459 // Collect the list of functions this module defines.
460 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000461 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000462 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000463
464 // Compute the import list for this module.
465 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000466 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000467
468#ifndef NDEBUG
469 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
470 << ImportList.size() << " modules.\n");
471 for (auto &Src : ImportList) {
472 auto SrcModName = Src.first();
473 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
474 << SrcModName << "\n");
475 }
476#endif
477}
478
Teresa Johnson84174c32016-05-10 13:48:23 +0000479/// Compute the set of summaries needed for a ThinLTO backend compilation of
480/// \p ModulePath.
481void llvm::gatherImportedSummariesForModule(
482 StringRef ModulePath,
483 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000484 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000485 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
486 // Include all summaries from the importing module.
487 ModuleToSummariesForIndex[ModulePath] =
488 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000489 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000490 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000491 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
492 const auto &DefinedGVSummaries =
493 ModuleToDefinedGVSummaries.lookup(ILI.first());
494 for (auto &GI : ILI.second) {
495 const auto &DS = DefinedGVSummaries.find(GI.first);
496 assert(DS != DefinedGVSummaries.end() &&
497 "Expected a defined summary for imported global value");
498 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000499 }
500 }
501}
502
Teresa Johnson8570fe42016-05-10 15:54:09 +0000503/// Emit the files \p ModulePath will import from into \p OutputFilename.
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000504std::error_code
505llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
506 const FunctionImporter::ImportMapTy &ModuleImports) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000507 std::error_code EC;
508 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
509 if (EC)
510 return EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000511 for (auto &ILI : ModuleImports)
512 ImportsOS << ILI.first() << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000513 return std::error_code();
514}
515
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000516/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
517void llvm::thinLTOResolveWeakForLinkerModule(
518 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
519 auto updateLinkage = [&](GlobalValue &GV) {
520 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
521 return;
522 // See if the global summary analysis computed a new resolved linkage.
523 const auto &GS = DefinedGlobals.find(GV.getGUID());
524 if (GS == DefinedGlobals.end())
525 return;
526 auto NewLinkage = GS->second->linkage();
527 if (NewLinkage == GV.getLinkage())
528 return;
529 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
530 << GV.getLinkage() << " to " << NewLinkage << "\n");
531 GV.setLinkage(NewLinkage);
Teresa Johnson6107a412016-08-15 21:00:04 +0000532 // Remove functions converted to available_externally from comdats,
533 // as this is a declaration for the linker, and will be dropped eventually.
534 // It is illegal for comdats to contain declarations.
535 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
536 if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
537 assert(GO->hasAvailableExternallyLinkage() &&
538 "Expected comdat on definition (possibly available external)");
539 GO->setComdat(nullptr);
540 }
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000541 };
542
543 // Process functions and global now
544 for (auto &GV : TheModule)
545 updateLinkage(GV);
546 for (auto &GV : TheModule.globals())
547 updateLinkage(GV);
548 for (auto &GV : TheModule.aliases())
549 updateLinkage(GV);
550}
551
552/// Run internalization on \p TheModule based on symmary analysis.
553void llvm::thinLTOInternalizeModule(Module &TheModule,
554 const GVSummaryMapTy &DefinedGlobals) {
555 // Parse inline ASM and collect the list of symbols that are not defined in
556 // the current module.
557 StringSet<> AsmUndefinedRefs;
558 object::IRObjectFile::CollectAsmUndefinedRefs(
559 Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
560 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
561 if (Flags & object::BasicSymbolRef::SF_Undefined)
562 AsmUndefinedRefs.insert(Name);
563 });
564
565 // Declare a callback for the internalize pass that will ask for every
566 // candidate GlobalValue if it can be internalized or not.
567 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
568 // Can't be internalized if referenced in inline asm.
569 if (AsmUndefinedRefs.count(GV.getName()))
570 return true;
571
572 // Lookup the linkage recorded in the summaries during global analysis.
573 const auto &GS = DefinedGlobals.find(GV.getGUID());
574 GlobalValue::LinkageTypes Linkage;
575 if (GS == DefinedGlobals.end()) {
576 // Must have been promoted (possibly conservatively). Find original
577 // name so that we can access the correct summary and see if it can
578 // be internalized again.
579 // FIXME: Eventually we should control promotion instead of promoting
580 // and internalizing again.
581 StringRef OrigName =
582 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
583 std::string OrigId = GlobalValue::getGlobalIdentifier(
584 OrigName, GlobalValue::InternalLinkage,
585 TheModule.getSourceFileName());
586 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000587 if (GS == DefinedGlobals.end()) {
588 // Also check the original non-promoted non-globalized name. In some
589 // cases a preempted weak value is linked in as a local copy because
590 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
591 // In that case, since it was originally not a local value, it was
592 // recorded in the index using the original name.
593 // FIXME: This may not be needed once PR27866 is fixed.
594 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
595 assert(GS != DefinedGlobals.end());
596 Linkage = GS->second->linkage();
597 } else {
598 Linkage = GS->second->linkage();
599 }
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000600 } else
601 Linkage = GS->second->linkage();
602 return !GlobalValue::isLocalLinkage(Linkage);
603 };
604
605 // FIXME: See if we can just internalize directly here via linkage changes
606 // based on the index, rather than invoking internalizeModule.
607 llvm::internalizeModule(TheModule, MustPreserveGV);
608}
609
Mehdi Aminic8c55172015-12-03 02:37:33 +0000610// Automatically import functions in Module \p DestModule based on the summaries
611// index.
612//
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000613Expected<bool> FunctionImporter::importFunctions(
Mehdi Aminibda3c972016-04-21 01:59:39 +0000614 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList,
615 bool ForceImportReferencedDiscardableSymbols) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000616 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000617 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000618 unsigned ImportedCount = 0;
619
Mehdi Aminic8c55172015-12-03 02:37:33 +0000620 // Linker that will be used for importing function
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000621 Linker TheLinker(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000622 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000623 std::set<StringRef> ModuleNameOrderedList;
624 for (auto &FunctionsToImportPerModule : ImportList) {
625 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
626 }
627 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000628 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000629 const auto &FunctionsToImportPerModule = ImportList.find(Name);
630 assert(FunctionsToImportPerModule != ImportList.end());
Peter Collingbourned9445c42016-11-13 07:00:17 +0000631 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
632 if (!SrcModuleOrErr)
633 return SrcModuleOrErr.takeError();
634 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000635 assert(&DestModule.getContext() == &SrcModule->getContext() &&
636 "Context mismatch");
637
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000638 // If modules were created with lazy metadata loading, materialize it
639 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000640 if (Error Err = SrcModule->materializeMetadata())
641 return std::move(Err);
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000642 UpgradeDebugInfo(*SrcModule);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000643
Mehdi Amini01e32132016-03-26 05:40:34 +0000644 auto &ImportGUIDs = FunctionsToImportPerModule->second;
645 // Find the globals to import
646 DenseSet<const GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000647 for (Function &F : *SrcModule) {
648 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000649 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000650 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000651 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000652 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000653 << " " << F.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000654 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000655 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000656 if (Error Err = F.materialize())
657 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +0000658 if (EnableImportMetadata) {
659 // Add 'thinlto_src_module' metadata for statistics and debugging.
660 F.setMetadata(
661 "thinlto_src_module",
662 llvm::MDNode::get(
663 DestModule.getContext(),
664 {llvm::MDString::get(DestModule.getContext(),
665 SrcModule->getSourceFileName())}));
666 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000667 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000668 }
669 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000670 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000671 if (!GV.hasName())
672 continue;
673 auto GUID = GV.getGUID();
674 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000675 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
676 << " " << GV.getName() << " from "
677 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000678 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000679 if (Error Err = GV.materialize())
680 return std::move(Err);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000681 GlobalsToImport.insert(&GV);
682 }
683 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000684 for (GlobalAlias &GA : SrcModule->aliases()) {
685 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000686 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000687 auto GUID = GA.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000688 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000689 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000690 << " " << GA.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000691 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000692 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000693 // Alias can't point to "available_externally". However when we import
Teresa Johnson9aae3952016-03-27 15:01:11 +0000694 // linkOnceODR the linkage does not change. So we import the alias
Mehdi Amini6968ef72016-04-20 01:04:20 +0000695 // and aliasee only in this case. This has been handled by
696 // computeImportForFunction()
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000697 GlobalObject *GO = GA.getBaseObject();
Mehdi Amini6968ef72016-04-20 01:04:20 +0000698 assert(GO->hasLinkOnceODRLinkage() &&
699 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000700#ifndef NDEBUG
701 if (!GlobalsToImport.count(GO))
702 DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
703 << " " << GO->getName() << " from "
704 << SrcModule->getSourceFileName() << "\n");
705#endif
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000706 if (Error Err = GO->materialize())
707 return std::move(Err);
Mehdi Amini01e32132016-03-26 05:40:34 +0000708 GlobalsToImport.insert(GO);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000709 if (Error Err = GA.materialize())
710 return std::move(Err);
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000711 GlobalsToImport.insert(&GA);
Mehdi Amini01e32132016-03-26 05:40:34 +0000712 }
713 }
714
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000715 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000716 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000717 return true;
718
Teresa Johnsond29478f2016-03-27 15:27:30 +0000719 if (PrintImports) {
720 for (const auto *GV : GlobalsToImport)
721 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
722 << " from " << SrcModule->getSourceFileName() << "\n";
723 }
724
Mehdi Aminibda3c972016-04-21 01:59:39 +0000725 // Instruct the linker that the client will take care of linkonce resolution
726 unsigned Flags = Linker::Flags::None;
727 if (!ForceImportReferencedDiscardableSymbols)
728 Flags |= Linker::Flags::DontForceLinkLinkonceODR;
729
730 if (TheLinker.linkInModule(std::move(SrcModule), Flags, &GlobalsToImport))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000731 report_fatal_error("Function Import: link error");
732
Mehdi Amini01e32132016-03-26 05:40:34 +0000733 ImportedCount += GlobalsToImport.size();
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000734 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000735
Teresa Johnsond29478f2016-03-27 15:27:30 +0000736 NumImported += ImportedCount;
737
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000738 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000739 << DestModule.getModuleIdentifier() << "\n");
740 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000741}
742
743/// Summary file to use for function importing when using -function-import from
744/// the command line.
745static cl::opt<std::string>
746 SummaryFile("summary-file",
747 cl::desc("The summary file to use for function importing."));
748
Teresa Johnson21241572016-07-18 21:22:24 +0000749static bool doImportingForModule(Module &M, const ModuleSummaryIndex *Index) {
750 if (SummaryFile.empty() && !Index)
751 report_fatal_error("error: -function-import requires -summary-file or "
752 "file from frontend\n");
753 std::unique_ptr<ModuleSummaryIndex> IndexPtr;
754 if (!SummaryFile.empty()) {
755 if (Index)
756 report_fatal_error("error: -summary-file and index from frontend\n");
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000757 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
758 getModuleSummaryIndexForFile(SummaryFile);
759 if (!IndexPtrOrErr) {
760 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
761 "Error loading file '" + SummaryFile + "': ");
Teresa Johnson21241572016-07-18 21:22:24 +0000762 return false;
763 }
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000764 IndexPtr = std::move(*IndexPtrOrErr);
Teresa Johnson21241572016-07-18 21:22:24 +0000765 Index = IndexPtr.get();
766 }
767
768 // First step is collecting the import list.
769 FunctionImporter::ImportMapTy ImportList;
770 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
771 ImportList);
772
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000773 // Conservatively mark all internal values as promoted. This interface is
774 // only used when doing importing via the function importing pass. The pass
775 // is only enabled when testing importing via the 'opt' tool, which does
776 // not do the ThinLink that would normally determine what values to promote.
777 for (auto &I : *Index) {
778 for (auto &S : I.second) {
779 if (GlobalValue::isLocalLinkage(S->linkage()))
780 S->setLinkage(GlobalValue::ExternalLinkage);
781 }
782 }
783
Teresa Johnson21241572016-07-18 21:22:24 +0000784 // Next we need to promote to global scope and rename any local values that
785 // are potentially exported to other modules.
786 if (renameModuleForThinLTO(M, *Index, nullptr)) {
787 errs() << "Error renaming module\n";
788 return false;
789 }
790
791 // Perform the import now.
792 auto ModuleLoader = [&M](StringRef Identifier) {
793 return loadFile(Identifier, M.getContext());
794 };
795 FunctionImporter Importer(*Index, ModuleLoader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000796 Expected<bool> Result = Importer.importFunctions(
797 M, ImportList, !DontForceImportReferencedDiscardableSymbols);
798
799 // FIXME: Probably need to propagate Errors through the pass manager.
800 if (!Result) {
801 logAllUnhandledErrors(Result.takeError(), errs(),
802 "Error importing module: ");
803 return false;
804 }
805
806 return *Result;
Teresa Johnson21241572016-07-18 21:22:24 +0000807}
808
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000809namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000810/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +0000811class FunctionImportLegacyPass : public ModulePass {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000812 /// Optional module summary index to use for importing, otherwise
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000813 /// the summary-file option must be specified.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000814 const ModuleSummaryIndex *Index;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000815
816public:
817 /// Pass identification, replacement for typeid
818 static char ID;
819
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000820 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +0000821 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000822
Teresa Johnson21241572016-07-18 21:22:24 +0000823 explicit FunctionImportLegacyPass(const ModuleSummaryIndex *Index = nullptr)
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000824 : ModulePass(ID), Index(Index) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000825
826 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000827 if (skipModule(M))
828 return false;
829
Teresa Johnson21241572016-07-18 21:22:24 +0000830 return doImportingForModule(M, Index);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000831 }
832};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000833} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000834
Teresa Johnson21241572016-07-18 21:22:24 +0000835PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000836 ModuleAnalysisManager &AM) {
Teresa Johnson21241572016-07-18 21:22:24 +0000837 if (!doImportingForModule(M, Index))
838 return PreservedAnalyses::all();
839
840 return PreservedAnalyses::none();
841}
842
843char FunctionImportLegacyPass::ID = 0;
844INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
845 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +0000846
847namespace llvm {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000848Pass *createFunctionImportPass(const ModuleSummaryIndex *Index = nullptr) {
Teresa Johnson21241572016-07-18 21:22:24 +0000849 return new FunctionImportLegacyPass(Index);
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000850}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000851}