blob: 6b32f6c31f7228000aacebce86166d5377aab65c [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"
Mehdi Aminifc06b832016-12-23 18:04:51 +000024#include "llvm/IR/Verifier.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000025#include "llvm/IRReader/IRReader.h"
26#include "llvm/Linker/Linker.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000027#include "llvm/Object/IRObjectFile.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000028#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000029#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/SourceMgr.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000032#include "llvm/Transforms/IPO/Internalize.h"
Teresa Johnson488a8002016-02-10 18:11:31 +000033#include "llvm/Transforms/Utils/FunctionImportUtils.h"
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000034
Mehdi Amini01e32132016-03-26 05:40:34 +000035#define DEBUG_TYPE "function-import"
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000036
Mehdi Amini42418ab2015-11-24 06:07:49 +000037using namespace llvm;
38
Teresa Johnson6c475a72017-01-05 21:34:18 +000039STATISTIC(NumImportedFunctions, "Number of functions imported");
40STATISTIC(NumImportedModules, "Number of modules imported from");
41STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
42STATISTIC(NumLiveSymbols, "Number of live symbols in index");
Teresa Johnsond29478f2016-03-27 15:27:30 +000043
Teresa Johnson39303612015-11-24 22:55:46 +000044/// Limit on instruction count of imported functions.
45static cl::opt<unsigned> ImportInstrLimit(
46 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
47 cl::desc("Only import functions with less than N instructions"));
48
Mehdi Amini40641742016-02-10 23:31:45 +000049static cl::opt<float>
50 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
51 cl::Hidden, cl::value_desc("x"),
52 cl::desc("As we import functions, multiply the "
53 "`import-instr-limit` threshold by this factor "
54 "before processing newly imported functions"));
Piotr Padlewskiba72b952016-09-29 17:32:07 +000055
Piotr Padlewskid2869472016-09-30 03:01:17 +000056static cl::opt<float> ImportHotInstrFactor(
57 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
58 cl::value_desc("x"),
59 cl::desc("As we import functions called from hot callsite, multiply the "
60 "`import-instr-limit` threshold by this factor "
61 "before processing newly imported functions"));
62
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000063static cl::opt<float> ImportHotMultiplier(
64 "import-hot-multiplier", cl::init(3.0), cl::Hidden, cl::value_desc("x"),
Piotr Padlewskiba72b952016-09-29 17:32:07 +000065 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
66
67// FIXME: This multiplier was not really tuned up.
68static cl::opt<float> ImportColdMultiplier(
69 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
70 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
Mehdi Amini40641742016-02-10 23:31:45 +000071
Teresa Johnsond29478f2016-03-27 15:27:30 +000072static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
73 cl::desc("Print imported functions"));
74
Teresa Johnson6c475a72017-01-05 21:34:18 +000075static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
76 cl::desc("Compute dead symbols"));
77
Mehdi Aminibda3c972016-04-21 01:59:39 +000078// Temporary allows the function import pass to disable always linking
79// referenced discardable symbols.
80static cl::opt<bool>
81 DontForceImportReferencedDiscardableSymbols("disable-force-link-odr",
82 cl::init(false), cl::Hidden);
83
Piotr Padlewski3b776122016-07-08 23:01:49 +000084static cl::opt<bool> EnableImportMetadata(
85 "enable-import-metadata", cl::init(
86#if !defined(NDEBUG)
87 true /*Enabled with asserts.*/
88#else
89 false
90#endif
91 ),
92 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
93
Mehdi Amini42418ab2015-11-24 06:07:49 +000094// Load lazily a module from \p FileName in \p Context.
95static std::unique_ptr<Module> loadFile(const std::string &FileName,
96 LLVMContext &Context) {
97 SMDiagnostic Err;
98 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +000099 // Metadata isn't loaded until functions are imported, to minimize
100 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +0000101 std::unique_ptr<Module> Result =
102 getLazyIRFileModule(FileName, Err, Context,
103 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000104 if (!Result) {
105 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +0000106 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000107 }
108
Mehdi Amini42418ab2015-11-24 06:07:49 +0000109 return Result;
110}
111
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000112namespace {
Mehdi Amini40641742016-02-10 23:31:45 +0000113
Mehdi Amini01e32132016-03-26 05:40:34 +0000114/// Given a list of possible callee implementation for a call site, select one
115/// that fits the \p Threshold.
116///
117/// FIXME: select "best" instead of first that fits. But what is "best"?
118/// - The smallest: more likely to be inlined.
119/// - The one with the least outgoing edges (already well optimized).
120/// - One from a module already being imported from in order to reduce the
121/// number of source modules parsed/linked.
122/// - One that has PGO data attached.
123/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000124static const GlobalValueSummary *
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000125selectCallee(const ModuleSummaryIndex &Index,
126 const GlobalValueSummaryList &CalleeSummaryList,
Teresa Johnson28e457b2016-04-24 14:57:11 +0000127 unsigned Threshold) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000128 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000129 CalleeSummaryList,
130 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
131 auto *GVSummary = SummaryPtr.get();
Rafael Espindolaf329be82016-05-11 01:26:06 +0000132 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000133 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000134 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000135 if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
136 GVSummary = &AS->getAliasee();
137 // Alias can't point to "available_externally". However when we import
138 // linkOnceODR the linkage does not change. So we import the alias
139 // and aliasee only in this case.
140 // FIXME: we should import alias as available_externally *function*,
141 // the destination module does need to know it is an alias.
142 if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
143 return false;
144 }
145
146 auto *Summary = cast<FunctionSummary>(GVSummary);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000147
Mehdi Amini01e32132016-03-26 05:40:34 +0000148 if (Summary->instCount() > Threshold)
149 return false;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000150
Teresa Johnson519465b2017-01-05 14:32:16 +0000151 if (Summary->notEligibleToImport())
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000152 return false;
153
Mehdi Amini01e32132016-03-26 05:40:34 +0000154 return true;
155 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000156 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000157 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000158
Teresa Johnson28e457b2016-04-24 14:57:11 +0000159 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000160}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000161
Mehdi Amini01e32132016-03-26 05:40:34 +0000162/// Return the summary for the function \p GUID that fits the \p Threshold, or
163/// null if there's no match.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000164static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID,
165 unsigned Threshold,
166 const ModuleSummaryIndex &Index) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000167 auto CalleeSummaryList = Index.findGlobalValueSummaryList(GUID);
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000168 if (CalleeSummaryList == Index.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000169 return nullptr; // This function does not have a summary
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000170 return selectCallee(Index, CalleeSummaryList->second, Threshold);
Mehdi Amini01e32132016-03-26 05:40:34 +0000171}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000172
Teresa Johnson475b51a2016-12-15 20:48:19 +0000173using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
174 GlobalValue::GUID>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000175
Mehdi Amini01e32132016-03-26 05:40:34 +0000176/// Compute the list of functions to import for a given caller. Mark these
177/// imported functions and the symbols they reference in their source module as
178/// exported from their source module.
179static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000180 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000181 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000182 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000183 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000184 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000185 for (auto &Edge : Summary.calls()) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000186 auto GUID = Edge.first.getGUID();
Mehdi Amini01e32132016-03-26 05:40:34 +0000187 DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
188
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000189 if (DefinedGVSummaries.count(GUID)) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000190 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
191 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000192 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000193
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000194 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
195 if (Hotness == CalleeInfo::HotnessType::Hot)
196 return ImportHotMultiplier;
197 if (Hotness == CalleeInfo::HotnessType::Cold)
198 return ImportColdMultiplier;
199 return 1.0;
200 };
201
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000202 const auto NewThreshold =
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000203 Threshold * GetBonusMultiplier(Edge.second.Hotness);
Piotr Padlewskid2869472016-09-30 03:01:17 +0000204
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000205 auto *CalleeSummary = selectCallee(GUID, NewThreshold, Index);
Mehdi Amini01e32132016-03-26 05:40:34 +0000206 if (!CalleeSummary) {
207 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
208 continue;
209 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000210 // "Resolve" the summary, traversing alias,
211 const FunctionSummary *ResolvedCalleeSummary;
Mehdi Amini6968ef72016-04-20 01:04:20 +0000212 if (isa<AliasSummary>(CalleeSummary)) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000213 ResolvedCalleeSummary = cast<FunctionSummary>(
214 &cast<AliasSummary>(CalleeSummary)->getAliasee());
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000215 assert(
216 GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
217 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini6968ef72016-04-20 01:04:20 +0000218 } else
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000219 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
220
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000221 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000222 "selectCallee() didn't honor the threshold");
223
Piotr Padlewskid2869472016-09-30 03:01:17 +0000224 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
225 // Adjust the threshold for next level of imported functions.
226 // The threshold is different for hot callsites because we can then
227 // inline chains of hot calls.
228 if (IsHotCallsite)
229 return Threshold * ImportHotInstrFactor;
230 return Threshold * ImportInstrFactor;
231 };
232
233 bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000234 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
235
236 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
237 auto &ProcessedThreshold = ImportList[ExportModulePath][GUID];
238 /// Since the traversal of the call graph is DFS, we can revisit a function
239 /// a second time with a higher threshold. In this case, it is added back to
240 /// the worklist with the new threshold.
241 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
242 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
243 << ProcessedThreshold << "\n");
244 continue;
245 }
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000246 bool PreviouslyImported = ProcessedThreshold != 0;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000247 // Mark this function as imported in this module, with the current Threshold
248 ProcessedThreshold = AdjThreshold;
249
250 // Make exports in the source module.
251 if (ExportLists) {
252 auto &ExportList = (*ExportLists)[ExportModulePath];
253 ExportList.insert(GUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000254 if (!PreviouslyImported) {
255 // This is the first time this function was exported from its source
256 // module, so mark all functions and globals it references as exported
257 // to the outside if they are defined in the same source module.
Teresa Johnsonedddca22016-12-16 04:11:51 +0000258 // For efficiency, we unconditionally add all the referenced GUIDs
259 // to the ExportList for this module, and will prune out any not
260 // defined in the module later in a single pass.
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000261 for (auto &Edge : ResolvedCalleeSummary->calls()) {
262 auto CalleeGUID = Edge.first.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000263 ExportList.insert(CalleeGUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000264 }
265 for (auto &Ref : ResolvedCalleeSummary->refs()) {
266 auto GUID = Ref.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000267 ExportList.insert(GUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000268 }
Teresa Johnson1b859a22016-12-15 18:21:01 +0000269 }
270 }
Piotr Padlewskid2869472016-09-30 03:01:17 +0000271
Mehdi Amini01e32132016-03-26 05:40:34 +0000272 // Insert the newly imported function to the worklist.
Teresa Johnson475b51a2016-12-15 20:48:19 +0000273 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, GUID);
Teresa Johnsond450da32015-11-24 21:15:19 +0000274 }
275}
276
Mehdi Amini01e32132016-03-26 05:40:34 +0000277/// Given the list of globals defined in a module, compute the list of imports
278/// as well as the list of "exports", i.e. the list of symbols referenced from
279/// another module (that may require promotion).
280static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000281 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000282 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000283 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr,
284 const DenseSet<GlobalValue::GUID> *DeadSymbols = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000285 // Worklist contains the list of function imported in this module, for which
286 // we will analyse the callees and may import further down the callgraph.
287 SmallVector<EdgeInfo, 128> Worklist;
288
289 // Populate the worklist with the import for the functions in the current
290 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000291 for (auto &GVSummary : DefinedGVSummaries) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000292 if (DeadSymbols && DeadSymbols->count(GVSummary.first)) {
293 DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
294 continue;
295 }
Teresa Johnson28e457b2016-04-24 14:57:11 +0000296 auto *Summary = GVSummary.second;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000297 if (auto *AS = dyn_cast<AliasSummary>(Summary))
298 Summary = &AS->getAliasee();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000299 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
300 if (!FuncSummary)
301 // Skip import for global variables
302 continue;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000303 DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000304 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000305 DefinedGVSummaries, Worklist, ImportList,
Mehdi Amini01e32132016-03-26 05:40:34 +0000306 ExportLists);
307 }
308
Piotr Padlewskid2869472016-09-30 03:01:17 +0000309 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000310 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000311 auto FuncInfo = Worklist.pop_back_val();
Teresa Johnson475b51a2016-12-15 20:48:19 +0000312 auto *Summary = std::get<0>(FuncInfo);
313 auto Threshold = std::get<1>(FuncInfo);
314 auto GUID = std::get<2>(FuncInfo);
315
316 // Check if we later added this summary with a higher threshold.
317 // If so, skip this entry.
318 auto ExportModulePath = Summary->modulePath();
319 auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
320 if (LatestProcessedThreshold > Threshold)
321 continue;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000322
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000323 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000324 Worklist, ImportList, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000325 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000326}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000327
Mehdi Amini01e32132016-03-26 05:40:34 +0000328} // anonymous namespace
329
Teresa Johnsonc86af332016-04-12 21:13:11 +0000330/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000331void llvm::ComputeCrossModuleImport(
332 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000333 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000334 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000335 StringMap<FunctionImporter::ExportSetTy> &ExportLists,
336 const DenseSet<GlobalValue::GUID> *DeadSymbols) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000337 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000338 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000339 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000340 DEBUG(dbgs() << "Computing import for Module '"
341 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000342 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000343 &ExportLists, DeadSymbols);
Mehdi Amini01e32132016-03-26 05:40:34 +0000344 }
345
Teresa Johnsonedddca22016-12-16 04:11:51 +0000346 // When computing imports we added all GUIDs referenced by anything
347 // imported from the module to its ExportList. Now we prune each ExportList
348 // of any not defined in that module. This is more efficient than checking
349 // while computing imports because some of the summary lists may be long
350 // due to linkonce (comdat) copies.
351 for (auto &ELI : ExportLists) {
352 const auto &DefinedGVSummaries =
353 ModuleToDefinedGVSummaries.lookup(ELI.first());
354 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
355 if (!DefinedGVSummaries.count(*EI))
356 EI = ELI.second.erase(EI);
357 else
358 ++EI;
359 }
360 }
361
Mehdi Amini01e32132016-03-26 05:40:34 +0000362#ifndef NDEBUG
363 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
364 << " modules:\n");
365 for (auto &ModuleImports : ImportLists) {
366 auto ModName = ModuleImports.first();
367 auto &Exports = ExportLists[ModName];
368 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
369 << " functions. Imports from " << ModuleImports.second.size()
370 << " modules.\n");
371 for (auto &Src : ModuleImports.second) {
372 auto SrcModName = Src.first();
373 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
374 << SrcModName << "\n");
375 }
376 }
377#endif
378}
379
Teresa Johnsonc86af332016-04-12 21:13:11 +0000380/// Compute all the imports for the given module in the Index.
381void llvm::ComputeCrossModuleImportForModule(
382 StringRef ModulePath, const ModuleSummaryIndex &Index,
383 FunctionImporter::ImportMapTy &ImportList) {
384
385 // Collect the list of functions this module defines.
386 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000387 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000388 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000389
390 // Compute the import list for this module.
391 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000392 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000393
394#ifndef NDEBUG
395 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
396 << ImportList.size() << " modules.\n");
397 for (auto &Src : ImportList) {
398 auto SrcModName = Src.first();
399 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
400 << SrcModName << "\n");
401 }
402#endif
403}
404
Teresa Johnson6c475a72017-01-05 21:34:18 +0000405DenseSet<GlobalValue::GUID> llvm::computeDeadSymbols(
406 const ModuleSummaryIndex &Index,
407 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
408 if (!ComputeDead)
409 return DenseSet<GlobalValue::GUID>();
410 if (GUIDPreservedSymbols.empty())
411 // Don't do anything when nothing is live, this is friendly with tests.
412 return DenseSet<GlobalValue::GUID>();
413 DenseSet<GlobalValue::GUID> LiveSymbols = GUIDPreservedSymbols;
414 SmallVector<GlobalValue::GUID, 128> Worklist;
415 Worklist.reserve(LiveSymbols.size() * 2);
416 for (auto GUID : LiveSymbols) {
417 DEBUG(dbgs() << "Live root: " << GUID << "\n");
418 Worklist.push_back(GUID);
419 }
420 // Add values flagged in the index as live roots to the worklist.
421 for (const auto &Entry : Index) {
422 bool IsLiveRoot = llvm::any_of(
423 Entry.second,
424 [&](const std::unique_ptr<llvm::GlobalValueSummary> &Summary) {
425 return Summary->liveRoot();
426 });
427 if (!IsLiveRoot)
428 continue;
429 DEBUG(dbgs() << "Live root (summary): " << Entry.first << "\n");
430 Worklist.push_back(Entry.first);
431 }
432
433 while (!Worklist.empty()) {
434 auto GUID = Worklist.pop_back_val();
435 auto It = Index.findGlobalValueSummaryList(GUID);
436 if (It == Index.end()) {
437 DEBUG(dbgs() << "Not in index: " << GUID << "\n");
438 continue;
439 }
440
441 // FIXME: we should only make the prevailing copy live here
442 for (auto &Summary : It->second) {
443 for (auto Ref : Summary->refs()) {
444 auto RefGUID = Ref.getGUID();
445 if (LiveSymbols.insert(RefGUID).second) {
446 DEBUG(dbgs() << "Marking live (ref): " << RefGUID << "\n");
447 Worklist.push_back(RefGUID);
448 }
449 }
450 if (auto *FS = dyn_cast<FunctionSummary>(Summary.get())) {
451 for (auto Call : FS->calls()) {
452 auto CallGUID = Call.first.getGUID();
453 if (LiveSymbols.insert(CallGUID).second) {
454 DEBUG(dbgs() << "Marking live (call): " << CallGUID << "\n");
455 Worklist.push_back(CallGUID);
456 }
457 }
458 }
459 if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
460 auto AliaseeGUID = AS->getAliasee().getOriginalName();
461 if (LiveSymbols.insert(AliaseeGUID).second) {
462 DEBUG(dbgs() << "Marking live (alias): " << AliaseeGUID << "\n");
463 Worklist.push_back(AliaseeGUID);
464 }
465 }
466 }
467 }
468 DenseSet<GlobalValue::GUID> DeadSymbols;
469 DeadSymbols.reserve(
470 std::min(Index.size(), Index.size() - LiveSymbols.size()));
471 for (auto &Entry : Index) {
472 auto GUID = Entry.first;
473 if (!LiveSymbols.count(GUID)) {
474 DEBUG(dbgs() << "Marking dead: " << GUID << "\n");
475 DeadSymbols.insert(GUID);
476 }
477 }
478 DEBUG(dbgs() << LiveSymbols.size() << " symbols Live, and "
479 << DeadSymbols.size() << " symbols Dead \n");
480 NumDeadSymbols += DeadSymbols.size();
481 NumLiveSymbols += LiveSymbols.size();
482 return DeadSymbols;
483}
484
Teresa Johnson84174c32016-05-10 13:48:23 +0000485/// Compute the set of summaries needed for a ThinLTO backend compilation of
486/// \p ModulePath.
487void llvm::gatherImportedSummariesForModule(
488 StringRef ModulePath,
489 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000490 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000491 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
492 // Include all summaries from the importing module.
493 ModuleToSummariesForIndex[ModulePath] =
494 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000495 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000496 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000497 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
498 const auto &DefinedGVSummaries =
499 ModuleToDefinedGVSummaries.lookup(ILI.first());
500 for (auto &GI : ILI.second) {
501 const auto &DS = DefinedGVSummaries.find(GI.first);
502 assert(DS != DefinedGVSummaries.end() &&
503 "Expected a defined summary for imported global value");
504 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000505 }
506 }
507}
508
Teresa Johnson8570fe42016-05-10 15:54:09 +0000509/// Emit the files \p ModulePath will import from into \p OutputFilename.
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000510std::error_code
511llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
512 const FunctionImporter::ImportMapTy &ModuleImports) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000513 std::error_code EC;
514 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
515 if (EC)
516 return EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000517 for (auto &ILI : ModuleImports)
518 ImportsOS << ILI.first() << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000519 return std::error_code();
520}
521
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000522/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
523void llvm::thinLTOResolveWeakForLinkerModule(
524 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
525 auto updateLinkage = [&](GlobalValue &GV) {
526 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
527 return;
528 // See if the global summary analysis computed a new resolved linkage.
529 const auto &GS = DefinedGlobals.find(GV.getGUID());
530 if (GS == DefinedGlobals.end())
531 return;
532 auto NewLinkage = GS->second->linkage();
533 if (NewLinkage == GV.getLinkage())
534 return;
535 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
536 << GV.getLinkage() << " to " << NewLinkage << "\n");
537 GV.setLinkage(NewLinkage);
Teresa Johnson6107a412016-08-15 21:00:04 +0000538 // Remove functions converted to available_externally from comdats,
539 // as this is a declaration for the linker, and will be dropped eventually.
540 // It is illegal for comdats to contain declarations.
541 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
542 if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
543 assert(GO->hasAvailableExternallyLinkage() &&
544 "Expected comdat on definition (possibly available external)");
545 GO->setComdat(nullptr);
546 }
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000547 };
548
549 // Process functions and global now
550 for (auto &GV : TheModule)
551 updateLinkage(GV);
552 for (auto &GV : TheModule.globals())
553 updateLinkage(GV);
554 for (auto &GV : TheModule.aliases())
555 updateLinkage(GV);
556}
557
558/// Run internalization on \p TheModule based on symmary analysis.
559void llvm::thinLTOInternalizeModule(Module &TheModule,
560 const GVSummaryMapTy &DefinedGlobals) {
561 // Parse inline ASM and collect the list of symbols that are not defined in
562 // the current module.
563 StringSet<> AsmUndefinedRefs;
Peter Collingbourne863cbfb2016-12-01 06:51:47 +0000564 ModuleSymbolTable::CollectAsmSymbols(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000565 Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
566 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
567 if (Flags & object::BasicSymbolRef::SF_Undefined)
568 AsmUndefinedRefs.insert(Name);
569 });
570
571 // Declare a callback for the internalize pass that will ask for every
572 // candidate GlobalValue if it can be internalized or not.
573 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
574 // Can't be internalized if referenced in inline asm.
575 if (AsmUndefinedRefs.count(GV.getName()))
576 return true;
577
578 // Lookup the linkage recorded in the summaries during global analysis.
579 const auto &GS = DefinedGlobals.find(GV.getGUID());
580 GlobalValue::LinkageTypes Linkage;
581 if (GS == DefinedGlobals.end()) {
582 // Must have been promoted (possibly conservatively). Find original
583 // name so that we can access the correct summary and see if it can
584 // be internalized again.
585 // FIXME: Eventually we should control promotion instead of promoting
586 // and internalizing again.
587 StringRef OrigName =
588 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
589 std::string OrigId = GlobalValue::getGlobalIdentifier(
590 OrigName, GlobalValue::InternalLinkage,
591 TheModule.getSourceFileName());
592 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000593 if (GS == DefinedGlobals.end()) {
594 // Also check the original non-promoted non-globalized name. In some
595 // cases a preempted weak value is linked in as a local copy because
596 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
597 // In that case, since it was originally not a local value, it was
598 // recorded in the index using the original name.
599 // FIXME: This may not be needed once PR27866 is fixed.
600 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
601 assert(GS != DefinedGlobals.end());
602 Linkage = GS->second->linkage();
603 } else {
604 Linkage = GS->second->linkage();
605 }
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000606 } else
607 Linkage = GS->second->linkage();
608 return !GlobalValue::isLocalLinkage(Linkage);
609 };
610
611 // FIXME: See if we can just internalize directly here via linkage changes
612 // based on the index, rather than invoking internalizeModule.
613 llvm::internalizeModule(TheModule, MustPreserveGV);
614}
615
Mehdi Aminic8c55172015-12-03 02:37:33 +0000616// Automatically import functions in Module \p DestModule based on the summaries
617// index.
618//
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000619Expected<bool> FunctionImporter::importFunctions(
Mehdi Aminibda3c972016-04-21 01:59:39 +0000620 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList,
621 bool ForceImportReferencedDiscardableSymbols) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000622 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000623 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000624 unsigned ImportedCount = 0;
625
Mehdi Aminic8c55172015-12-03 02:37:33 +0000626 // Linker that will be used for importing function
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000627 Linker TheLinker(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000628 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000629 std::set<StringRef> ModuleNameOrderedList;
630 for (auto &FunctionsToImportPerModule : ImportList) {
631 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
632 }
633 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000634 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000635 const auto &FunctionsToImportPerModule = ImportList.find(Name);
636 assert(FunctionsToImportPerModule != ImportList.end());
Peter Collingbourned9445c42016-11-13 07:00:17 +0000637 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
638 if (!SrcModuleOrErr)
639 return SrcModuleOrErr.takeError();
640 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000641 assert(&DestModule.getContext() == &SrcModule->getContext() &&
642 "Context mismatch");
643
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000644 // If modules were created with lazy metadata loading, materialize it
645 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000646 if (Error Err = SrcModule->materializeMetadata())
647 return std::move(Err);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000648
Mehdi Amini01e32132016-03-26 05:40:34 +0000649 auto &ImportGUIDs = FunctionsToImportPerModule->second;
650 // Find the globals to import
651 DenseSet<const GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000652 for (Function &F : *SrcModule) {
653 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000654 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000655 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000656 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000657 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000658 << " " << F.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000659 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000660 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000661 if (Error Err = F.materialize())
662 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +0000663 if (EnableImportMetadata) {
664 // Add 'thinlto_src_module' metadata for statistics and debugging.
665 F.setMetadata(
666 "thinlto_src_module",
667 llvm::MDNode::get(
668 DestModule.getContext(),
669 {llvm::MDString::get(DestModule.getContext(),
670 SrcModule->getSourceFileName())}));
671 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000672 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000673 }
674 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000675 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000676 if (!GV.hasName())
677 continue;
678 auto GUID = GV.getGUID();
679 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000680 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
681 << " " << GV.getName() << " from "
682 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000683 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000684 if (Error Err = GV.materialize())
685 return std::move(Err);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000686 GlobalsToImport.insert(&GV);
687 }
688 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000689 for (GlobalAlias &GA : SrcModule->aliases()) {
690 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000691 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000692 auto GUID = GA.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000693 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000694 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000695 << " " << GA.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000696 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000697 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000698 // Alias can't point to "available_externally". However when we import
Teresa Johnson9aae3952016-03-27 15:01:11 +0000699 // linkOnceODR the linkage does not change. So we import the alias
Mehdi Amini6968ef72016-04-20 01:04:20 +0000700 // and aliasee only in this case. This has been handled by
701 // computeImportForFunction()
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000702 GlobalObject *GO = GA.getBaseObject();
Mehdi Amini6968ef72016-04-20 01:04:20 +0000703 assert(GO->hasLinkOnceODRLinkage() &&
704 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000705#ifndef NDEBUG
706 if (!GlobalsToImport.count(GO))
707 DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
708 << " " << GO->getName() << " from "
709 << SrcModule->getSourceFileName() << "\n");
710#endif
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000711 if (Error Err = GO->materialize())
712 return std::move(Err);
Mehdi Amini01e32132016-03-26 05:40:34 +0000713 GlobalsToImport.insert(GO);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000714 if (Error Err = GA.materialize())
715 return std::move(Err);
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000716 GlobalsToImport.insert(&GA);
Mehdi Amini01e32132016-03-26 05:40:34 +0000717 }
718 }
719
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000720 // Upgrade debug info after we're done materializing all the globals and we
721 // have loaded all the required metadata!
722 UpgradeDebugInfo(*SrcModule);
723
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000724 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000725 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000726 return true;
727
Teresa Johnsond29478f2016-03-27 15:27:30 +0000728 if (PrintImports) {
729 for (const auto *GV : GlobalsToImport)
730 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
731 << " from " << SrcModule->getSourceFileName() << "\n";
732 }
733
Mehdi Aminibda3c972016-04-21 01:59:39 +0000734 // Instruct the linker that the client will take care of linkonce resolution
735 unsigned Flags = Linker::Flags::None;
736 if (!ForceImportReferencedDiscardableSymbols)
737 Flags |= Linker::Flags::DontForceLinkLinkonceODR;
738
739 if (TheLinker.linkInModule(std::move(SrcModule), Flags, &GlobalsToImport))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000740 report_fatal_error("Function Import: link error");
741
Mehdi Amini01e32132016-03-26 05:40:34 +0000742 ImportedCount += GlobalsToImport.size();
Teresa Johnson6c475a72017-01-05 21:34:18 +0000743 NumImportedModules++;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000744 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000745
Teresa Johnson6c475a72017-01-05 21:34:18 +0000746 NumImportedFunctions += ImportedCount;
Teresa Johnsond29478f2016-03-27 15:27:30 +0000747
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000748 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000749 << DestModule.getModuleIdentifier() << "\n");
750 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000751}
752
753/// Summary file to use for function importing when using -function-import from
754/// the command line.
755static cl::opt<std::string>
756 SummaryFile("summary-file",
757 cl::desc("The summary file to use for function importing."));
758
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000759static bool doImportingForModule(Module &M) {
760 if (SummaryFile.empty())
761 report_fatal_error("error: -function-import requires -summary-file\n");
762 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
763 getModuleSummaryIndexForFile(SummaryFile);
764 if (!IndexPtrOrErr) {
765 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
766 "Error loading file '" + SummaryFile + "': ");
767 return false;
Teresa Johnson21241572016-07-18 21:22:24 +0000768 }
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000769 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
Teresa Johnson21241572016-07-18 21:22:24 +0000770
771 // First step is collecting the import list.
772 FunctionImporter::ImportMapTy ImportList;
773 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
774 ImportList);
775
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000776 // Conservatively mark all internal values as promoted. This interface is
777 // only used when doing importing via the function importing pass. The pass
778 // is only enabled when testing importing via the 'opt' tool, which does
779 // not do the ThinLink that would normally determine what values to promote.
780 for (auto &I : *Index) {
781 for (auto &S : I.second) {
782 if (GlobalValue::isLocalLinkage(S->linkage()))
783 S->setLinkage(GlobalValue::ExternalLinkage);
784 }
785 }
786
Teresa Johnson21241572016-07-18 21:22:24 +0000787 // Next we need to promote to global scope and rename any local values that
788 // are potentially exported to other modules.
789 if (renameModuleForThinLTO(M, *Index, nullptr)) {
790 errs() << "Error renaming module\n";
791 return false;
792 }
793
794 // Perform the import now.
795 auto ModuleLoader = [&M](StringRef Identifier) {
796 return loadFile(Identifier, M.getContext());
797 };
798 FunctionImporter Importer(*Index, ModuleLoader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000799 Expected<bool> Result = Importer.importFunctions(
800 M, ImportList, !DontForceImportReferencedDiscardableSymbols);
801
802 // FIXME: Probably need to propagate Errors through the pass manager.
803 if (!Result) {
804 logAllUnhandledErrors(Result.takeError(), errs(),
805 "Error importing module: ");
806 return false;
807 }
808
809 return *Result;
Teresa Johnson21241572016-07-18 21:22:24 +0000810}
811
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000812namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000813/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +0000814class FunctionImportLegacyPass : public ModulePass {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000815public:
816 /// Pass identification, replacement for typeid
817 static char ID;
818
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000819 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +0000820 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000821
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000822 explicit FunctionImportLegacyPass() : ModulePass(ID) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000823
824 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000825 if (skipModule(M))
826 return false;
827
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000828 return doImportingForModule(M);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000829 }
830};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000831} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000832
Teresa Johnson21241572016-07-18 21:22:24 +0000833PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000834 ModuleAnalysisManager &AM) {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000835 if (!doImportingForModule(M))
Teresa Johnson21241572016-07-18 21:22:24 +0000836 return PreservedAnalyses::all();
837
838 return PreservedAnalyses::none();
839}
840
841char FunctionImportLegacyPass::ID = 0;
842INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
843 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +0000844
845namespace llvm {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000846Pass *createFunctionImportPass() {
847 return new FunctionImportLegacyPass();
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000848}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000849}