blob: c7ef2494e3b8bd87049ea9b8ab98bd5cec96a0d9 [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"
Peter Collingbournec15d60b2017-05-01 20:42:32 +000020#include "llvm/Bitcode/BitcodeReader.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000021#include "llvm/IR/AutoUpgrade.h"
22#include "llvm/IR/DiagnosticPrinter.h"
23#include "llvm/IR/IntrinsicInst.h"
24#include "llvm/IR/Module.h"
Mehdi Aminifc06b832016-12-23 18:04:51 +000025#include "llvm/IR/Verifier.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000026#include "llvm/IRReader/IRReader.h"
27#include "llvm/Linker/Linker.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000028#include "llvm/Object/IRObjectFile.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
Piotr Padlewski3b776122016-07-08 23:01:49 +000078static cl::opt<bool> EnableImportMetadata(
79 "enable-import-metadata", cl::init(
80#if !defined(NDEBUG)
81 true /*Enabled with asserts.*/
82#else
83 false
84#endif
85 ),
86 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
87
Mehdi Amini42418ab2015-11-24 06:07:49 +000088// Load lazily a module from \p FileName in \p Context.
89static std::unique_ptr<Module> loadFile(const std::string &FileName,
90 LLVMContext &Context) {
91 SMDiagnostic Err;
92 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +000093 // Metadata isn't loaded until functions are imported, to minimize
94 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +000095 std::unique_ptr<Module> Result =
96 getLazyIRFileModule(FileName, Err, Context,
97 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +000098 if (!Result) {
99 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +0000100 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000101 }
102
Mehdi Amini42418ab2015-11-24 06:07:49 +0000103 return Result;
104}
105
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000106namespace {
Mehdi Amini40641742016-02-10 23:31:45 +0000107
Mehdi Amini01e32132016-03-26 05:40:34 +0000108/// Given a list of possible callee implementation for a call site, select one
109/// that fits the \p Threshold.
110///
111/// FIXME: select "best" instead of first that fits. But what is "best"?
112/// - The smallest: more likely to be inlined.
113/// - The one with the least outgoing edges (already well optimized).
114/// - One from a module already being imported from in order to reduce the
115/// number of source modules parsed/linked.
116/// - One that has PGO data attached.
117/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000118static const GlobalValueSummary *
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000119selectCallee(const ModuleSummaryIndex &Index,
120 const GlobalValueSummaryList &CalleeSummaryList,
Teresa Johnson83aaf352017-01-12 22:04:45 +0000121 unsigned Threshold, StringRef CallerModulePath) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000122 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000123 CalleeSummaryList,
124 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
125 auto *GVSummary = SummaryPtr.get();
Rafael Espindolaf329be82016-05-11 01:26:06 +0000126 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000127 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000128 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000129 if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
130 GVSummary = &AS->getAliasee();
131 // Alias can't point to "available_externally". However when we import
132 // linkOnceODR the linkage does not change. So we import the alias
133 // and aliasee only in this case.
134 // FIXME: we should import alias as available_externally *function*,
135 // the destination module does need to know it is an alias.
136 if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
137 return false;
138 }
139
140 auto *Summary = cast<FunctionSummary>(GVSummary);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000141
Teresa Johnson83aaf352017-01-12 22:04:45 +0000142 // If this is a local function, make sure we import the copy
143 // in the caller's module. The only time a local function can
144 // share an entry in the index is if there is a local with the same name
145 // in another module that had the same source file name (in a different
146 // directory), where each was compiled in their own directory so there
147 // was not distinguishing path.
148 // However, do the import from another module if there is only one
149 // entry in the list - in that case this must be a reference due
150 // to indirect call profile data, since a function pointer can point to
151 // a local in another module.
152 if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
153 CalleeSummaryList.size() > 1 &&
154 Summary->modulePath() != CallerModulePath)
155 return false;
156
Mehdi Amini01e32132016-03-26 05:40:34 +0000157 if (Summary->instCount() > Threshold)
158 return false;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000159
Teresa Johnson519465b2017-01-05 14:32:16 +0000160 if (Summary->notEligibleToImport())
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000161 return false;
162
Mehdi Amini01e32132016-03-26 05:40:34 +0000163 return true;
164 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000165 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000166 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000167
Teresa Johnson28e457b2016-04-24 14:57:11 +0000168 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000169}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000170
Mehdi Amini01e32132016-03-26 05:40:34 +0000171/// Return the summary for the function \p GUID that fits the \p Threshold, or
172/// null if there's no match.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000173static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID,
174 unsigned Threshold,
Teresa Johnson83aaf352017-01-12 22:04:45 +0000175 const ModuleSummaryIndex &Index,
176 StringRef CallerModulePath) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000177 auto CalleeSummaryList = Index.findGlobalValueSummaryList(GUID);
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000178 if (CalleeSummaryList == Index.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000179 return nullptr; // This function does not have a summary
Teresa Johnson83aaf352017-01-12 22:04:45 +0000180 return selectCallee(Index, CalleeSummaryList->second, Threshold,
181 CallerModulePath);
Mehdi Amini01e32132016-03-26 05:40:34 +0000182}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000183
Teresa Johnson475b51a2016-12-15 20:48:19 +0000184using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
185 GlobalValue::GUID>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000186
Mehdi Amini01e32132016-03-26 05:40:34 +0000187/// Compute the list of functions to import for a given caller. Mark these
188/// imported functions and the symbols they reference in their source module as
189/// exported from their source module.
190static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000191 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000192 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000193 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000194 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000195 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000196 for (auto &Edge : Summary.calls()) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000197 auto GUID = Edge.first.getGUID();
Mehdi Amini01e32132016-03-26 05:40:34 +0000198 DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
199
Dehao Chen4a435e02017-03-14 17:33:01 +0000200 if (Index.findGlobalValueSummaryList(GUID) == Index.end()) {
201 // For SamplePGO, the indirect call targets for local functions will
202 // have its original name annotated in profile. We try to find the
203 // corresponding PGOFuncName as the GUID.
204 GUID = Index.getGUIDFromOriginalID(GUID);
205 if (GUID == 0)
206 continue;
207 }
208
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000209 if (DefinedGVSummaries.count(GUID)) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000210 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
211 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000212 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000213
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000214 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
215 if (Hotness == CalleeInfo::HotnessType::Hot)
216 return ImportHotMultiplier;
217 if (Hotness == CalleeInfo::HotnessType::Cold)
218 return ImportColdMultiplier;
219 return 1.0;
220 };
221
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000222 const auto NewThreshold =
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000223 Threshold * GetBonusMultiplier(Edge.second.Hotness);
Piotr Padlewskid2869472016-09-30 03:01:17 +0000224
Teresa Johnson83aaf352017-01-12 22:04:45 +0000225 auto *CalleeSummary =
226 selectCallee(GUID, NewThreshold, Index, Summary.modulePath());
Mehdi Amini01e32132016-03-26 05:40:34 +0000227 if (!CalleeSummary) {
228 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
229 continue;
230 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000231 // "Resolve" the summary, traversing alias,
232 const FunctionSummary *ResolvedCalleeSummary;
Mehdi Amini6968ef72016-04-20 01:04:20 +0000233 if (isa<AliasSummary>(CalleeSummary)) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000234 ResolvedCalleeSummary = cast<FunctionSummary>(
235 &cast<AliasSummary>(CalleeSummary)->getAliasee());
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000236 assert(
237 GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
238 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini6968ef72016-04-20 01:04:20 +0000239 } else
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000240 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
241
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000242 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000243 "selectCallee() didn't honor the threshold");
244
Piotr Padlewskid2869472016-09-30 03:01:17 +0000245 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
246 // Adjust the threshold for next level of imported functions.
247 // The threshold is different for hot callsites because we can then
248 // inline chains of hot calls.
249 if (IsHotCallsite)
250 return Threshold * ImportHotInstrFactor;
251 return Threshold * ImportInstrFactor;
252 };
253
254 bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000255 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
256
257 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
258 auto &ProcessedThreshold = ImportList[ExportModulePath][GUID];
259 /// Since the traversal of the call graph is DFS, we can revisit a function
260 /// a second time with a higher threshold. In this case, it is added back to
261 /// the worklist with the new threshold.
262 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
263 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
264 << ProcessedThreshold << "\n");
265 continue;
266 }
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000267 bool PreviouslyImported = ProcessedThreshold != 0;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000268 // Mark this function as imported in this module, with the current Threshold
269 ProcessedThreshold = AdjThreshold;
270
271 // Make exports in the source module.
272 if (ExportLists) {
273 auto &ExportList = (*ExportLists)[ExportModulePath];
274 ExportList.insert(GUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000275 if (!PreviouslyImported) {
276 // This is the first time this function was exported from its source
277 // module, so mark all functions and globals it references as exported
278 // to the outside if they are defined in the same source module.
Teresa Johnsonedddca22016-12-16 04:11:51 +0000279 // For efficiency, we unconditionally add all the referenced GUIDs
280 // to the ExportList for this module, and will prune out any not
281 // defined in the module later in a single pass.
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000282 for (auto &Edge : ResolvedCalleeSummary->calls()) {
283 auto CalleeGUID = Edge.first.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000284 ExportList.insert(CalleeGUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000285 }
286 for (auto &Ref : ResolvedCalleeSummary->refs()) {
287 auto GUID = Ref.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000288 ExportList.insert(GUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000289 }
Teresa Johnson1b859a22016-12-15 18:21:01 +0000290 }
291 }
Piotr Padlewskid2869472016-09-30 03:01:17 +0000292
Mehdi Amini01e32132016-03-26 05:40:34 +0000293 // Insert the newly imported function to the worklist.
Teresa Johnson475b51a2016-12-15 20:48:19 +0000294 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, GUID);
Teresa Johnsond450da32015-11-24 21:15:19 +0000295 }
296}
297
Mehdi Amini01e32132016-03-26 05:40:34 +0000298/// Given the list of globals defined in a module, compute the list of imports
299/// as well as the list of "exports", i.e. the list of symbols referenced from
300/// another module (that may require promotion).
301static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000302 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000303 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000304 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr,
305 const DenseSet<GlobalValue::GUID> *DeadSymbols = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000306 // Worklist contains the list of function imported in this module, for which
307 // we will analyse the callees and may import further down the callgraph.
308 SmallVector<EdgeInfo, 128> Worklist;
309
310 // Populate the worklist with the import for the functions in the current
311 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000312 for (auto &GVSummary : DefinedGVSummaries) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000313 if (DeadSymbols && DeadSymbols->count(GVSummary.first)) {
314 DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
315 continue;
316 }
Teresa Johnson28e457b2016-04-24 14:57:11 +0000317 auto *Summary = GVSummary.second;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000318 if (auto *AS = dyn_cast<AliasSummary>(Summary))
319 Summary = &AS->getAliasee();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000320 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
321 if (!FuncSummary)
322 // Skip import for global variables
323 continue;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000324 DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000325 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000326 DefinedGVSummaries, Worklist, ImportList,
Mehdi Amini01e32132016-03-26 05:40:34 +0000327 ExportLists);
328 }
329
Piotr Padlewskid2869472016-09-30 03:01:17 +0000330 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000331 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000332 auto FuncInfo = Worklist.pop_back_val();
Teresa Johnson475b51a2016-12-15 20:48:19 +0000333 auto *Summary = std::get<0>(FuncInfo);
334 auto Threshold = std::get<1>(FuncInfo);
335 auto GUID = std::get<2>(FuncInfo);
336
337 // Check if we later added this summary with a higher threshold.
338 // If so, skip this entry.
339 auto ExportModulePath = Summary->modulePath();
340 auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
341 if (LatestProcessedThreshold > Threshold)
342 continue;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000343
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000344 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000345 Worklist, ImportList, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000346 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000347}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000348
Mehdi Amini01e32132016-03-26 05:40:34 +0000349} // anonymous namespace
350
Teresa Johnsonc86af332016-04-12 21:13:11 +0000351/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000352void llvm::ComputeCrossModuleImport(
353 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000354 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000355 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000356 StringMap<FunctionImporter::ExportSetTy> &ExportLists,
357 const DenseSet<GlobalValue::GUID> *DeadSymbols) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000358 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000359 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000360 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000361 DEBUG(dbgs() << "Computing import for Module '"
362 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000363 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000364 &ExportLists, DeadSymbols);
Mehdi Amini01e32132016-03-26 05:40:34 +0000365 }
366
Teresa Johnsonedddca22016-12-16 04:11:51 +0000367 // When computing imports we added all GUIDs referenced by anything
368 // imported from the module to its ExportList. Now we prune each ExportList
369 // of any not defined in that module. This is more efficient than checking
370 // while computing imports because some of the summary lists may be long
371 // due to linkonce (comdat) copies.
372 for (auto &ELI : ExportLists) {
373 const auto &DefinedGVSummaries =
374 ModuleToDefinedGVSummaries.lookup(ELI.first());
375 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
376 if (!DefinedGVSummaries.count(*EI))
377 EI = ELI.second.erase(EI);
378 else
379 ++EI;
380 }
381 }
382
Mehdi Amini01e32132016-03-26 05:40:34 +0000383#ifndef NDEBUG
384 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
385 << " modules:\n");
386 for (auto &ModuleImports : ImportLists) {
387 auto ModName = ModuleImports.first();
388 auto &Exports = ExportLists[ModName];
389 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
390 << " functions. Imports from " << ModuleImports.second.size()
391 << " modules.\n");
392 for (auto &Src : ModuleImports.second) {
393 auto SrcModName = Src.first();
394 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
395 << SrcModName << "\n");
396 }
397 }
398#endif
399}
400
Teresa Johnsonc86af332016-04-12 21:13:11 +0000401/// Compute all the imports for the given module in the Index.
402void llvm::ComputeCrossModuleImportForModule(
403 StringRef ModulePath, const ModuleSummaryIndex &Index,
404 FunctionImporter::ImportMapTy &ImportList) {
405
406 // Collect the list of functions this module defines.
407 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000408 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000409 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000410
411 // Compute the import list for this module.
412 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000413 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000414
415#ifndef NDEBUG
416 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
417 << ImportList.size() << " modules.\n");
418 for (auto &Src : ImportList) {
419 auto SrcModName = Src.first();
420 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
421 << SrcModName << "\n");
422 }
423#endif
424}
425
Teresa Johnson6c475a72017-01-05 21:34:18 +0000426DenseSet<GlobalValue::GUID> llvm::computeDeadSymbols(
427 const ModuleSummaryIndex &Index,
428 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
429 if (!ComputeDead)
430 return DenseSet<GlobalValue::GUID>();
431 if (GUIDPreservedSymbols.empty())
432 // Don't do anything when nothing is live, this is friendly with tests.
433 return DenseSet<GlobalValue::GUID>();
434 DenseSet<GlobalValue::GUID> LiveSymbols = GUIDPreservedSymbols;
435 SmallVector<GlobalValue::GUID, 128> Worklist;
436 Worklist.reserve(LiveSymbols.size() * 2);
437 for (auto GUID : LiveSymbols) {
438 DEBUG(dbgs() << "Live root: " << GUID << "\n");
439 Worklist.push_back(GUID);
440 }
441 // Add values flagged in the index as live roots to the worklist.
442 for (const auto &Entry : Index) {
443 bool IsLiveRoot = llvm::any_of(
444 Entry.second,
445 [&](const std::unique_ptr<llvm::GlobalValueSummary> &Summary) {
446 return Summary->liveRoot();
447 });
448 if (!IsLiveRoot)
449 continue;
450 DEBUG(dbgs() << "Live root (summary): " << Entry.first << "\n");
451 Worklist.push_back(Entry.first);
452 }
453
454 while (!Worklist.empty()) {
455 auto GUID = Worklist.pop_back_val();
456 auto It = Index.findGlobalValueSummaryList(GUID);
457 if (It == Index.end()) {
458 DEBUG(dbgs() << "Not in index: " << GUID << "\n");
459 continue;
460 }
461
462 // FIXME: we should only make the prevailing copy live here
463 for (auto &Summary : It->second) {
464 for (auto Ref : Summary->refs()) {
465 auto RefGUID = Ref.getGUID();
466 if (LiveSymbols.insert(RefGUID).second) {
467 DEBUG(dbgs() << "Marking live (ref): " << RefGUID << "\n");
468 Worklist.push_back(RefGUID);
469 }
470 }
471 if (auto *FS = dyn_cast<FunctionSummary>(Summary.get())) {
472 for (auto Call : FS->calls()) {
473 auto CallGUID = Call.first.getGUID();
474 if (LiveSymbols.insert(CallGUID).second) {
475 DEBUG(dbgs() << "Marking live (call): " << CallGUID << "\n");
476 Worklist.push_back(CallGUID);
477 }
478 }
479 }
480 if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
481 auto AliaseeGUID = AS->getAliasee().getOriginalName();
482 if (LiveSymbols.insert(AliaseeGUID).second) {
483 DEBUG(dbgs() << "Marking live (alias): " << AliaseeGUID << "\n");
484 Worklist.push_back(AliaseeGUID);
485 }
486 }
487 }
488 }
489 DenseSet<GlobalValue::GUID> DeadSymbols;
490 DeadSymbols.reserve(
491 std::min(Index.size(), Index.size() - LiveSymbols.size()));
492 for (auto &Entry : Index) {
493 auto GUID = Entry.first;
494 if (!LiveSymbols.count(GUID)) {
495 DEBUG(dbgs() << "Marking dead: " << GUID << "\n");
496 DeadSymbols.insert(GUID);
497 }
498 }
499 DEBUG(dbgs() << LiveSymbols.size() << " symbols Live, and "
500 << DeadSymbols.size() << " symbols Dead \n");
501 NumDeadSymbols += DeadSymbols.size();
502 NumLiveSymbols += LiveSymbols.size();
503 return DeadSymbols;
504}
505
Teresa Johnson84174c32016-05-10 13:48:23 +0000506/// Compute the set of summaries needed for a ThinLTO backend compilation of
507/// \p ModulePath.
508void llvm::gatherImportedSummariesForModule(
509 StringRef ModulePath,
510 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000511 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000512 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
513 // Include all summaries from the importing module.
514 ModuleToSummariesForIndex[ModulePath] =
515 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000516 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000517 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000518 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
519 const auto &DefinedGVSummaries =
520 ModuleToDefinedGVSummaries.lookup(ILI.first());
521 for (auto &GI : ILI.second) {
522 const auto &DS = DefinedGVSummaries.find(GI.first);
523 assert(DS != DefinedGVSummaries.end() &&
524 "Expected a defined summary for imported global value");
525 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000526 }
527 }
528}
529
Teresa Johnson8570fe42016-05-10 15:54:09 +0000530/// Emit the files \p ModulePath will import from into \p OutputFilename.
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000531std::error_code
532llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
533 const FunctionImporter::ImportMapTy &ModuleImports) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000534 std::error_code EC;
535 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
536 if (EC)
537 return EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000538 for (auto &ILI : ModuleImports)
539 ImportsOS << ILI.first() << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000540 return std::error_code();
541}
542
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000543/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
544void llvm::thinLTOResolveWeakForLinkerModule(
545 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000546 auto ConvertToDeclaration = [](GlobalValue &GV) {
547 DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n");
548 if (Function *F = dyn_cast<Function>(&GV)) {
549 F->deleteBody();
550 F->clearMetadata();
551 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
552 V->setInitializer(nullptr);
553 V->setLinkage(GlobalValue::ExternalLinkage);
554 V->clearMetadata();
555 } else
556 // For now we don't resolve or drop aliases. Once we do we'll
557 // need to add support here for creating either a function or
558 // variable declaration, and return the new GlobalValue* for
559 // the caller to use.
Davide Italiano91239082017-04-14 17:22:02 +0000560 llvm_unreachable("Expected function or variable");
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000561 };
562
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000563 auto updateLinkage = [&](GlobalValue &GV) {
564 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
565 return;
566 // See if the global summary analysis computed a new resolved linkage.
567 const auto &GS = DefinedGlobals.find(GV.getGUID());
568 if (GS == DefinedGlobals.end())
569 return;
570 auto NewLinkage = GS->second->linkage();
571 if (NewLinkage == GV.getLinkage())
572 return;
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000573 // Check for a non-prevailing def that has interposable linkage
574 // (e.g. non-odr weak or linkonce). In that case we can't simply
575 // convert to available_externally, since it would lose the
576 // interposable property and possibly get inlined. Simply drop
577 // the definition in that case.
578 if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
579 GlobalValue::isInterposableLinkage(GV.getLinkage()))
580 ConvertToDeclaration(GV);
581 else {
582 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
583 << GV.getLinkage() << " to " << NewLinkage << "\n");
584 GV.setLinkage(NewLinkage);
585 }
586 // Remove declarations from comdats, including available_externally
Teresa Johnson6107a412016-08-15 21:00:04 +0000587 // as this is a declaration for the linker, and will be dropped eventually.
588 // It is illegal for comdats to contain declarations.
589 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000590 if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
Teresa Johnson6107a412016-08-15 21:00:04 +0000591 GO->setComdat(nullptr);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000592 };
593
594 // Process functions and global now
595 for (auto &GV : TheModule)
596 updateLinkage(GV);
597 for (auto &GV : TheModule.globals())
598 updateLinkage(GV);
599 for (auto &GV : TheModule.aliases())
600 updateLinkage(GV);
601}
602
603/// Run internalization on \p TheModule based on symmary analysis.
604void llvm::thinLTOInternalizeModule(Module &TheModule,
605 const GVSummaryMapTy &DefinedGlobals) {
606 // Parse inline ASM and collect the list of symbols that are not defined in
607 // the current module.
608 StringSet<> AsmUndefinedRefs;
Peter Collingbourne863cbfb2016-12-01 06:51:47 +0000609 ModuleSymbolTable::CollectAsmSymbols(
Teresa Johnsond8204472017-03-09 00:19:49 +0000610 TheModule,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000611 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
612 if (Flags & object::BasicSymbolRef::SF_Undefined)
613 AsmUndefinedRefs.insert(Name);
614 });
615
616 // Declare a callback for the internalize pass that will ask for every
617 // candidate GlobalValue if it can be internalized or not.
618 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
619 // Can't be internalized if referenced in inline asm.
620 if (AsmUndefinedRefs.count(GV.getName()))
621 return true;
622
623 // Lookup the linkage recorded in the summaries during global analysis.
624 const auto &GS = DefinedGlobals.find(GV.getGUID());
625 GlobalValue::LinkageTypes Linkage;
626 if (GS == DefinedGlobals.end()) {
627 // Must have been promoted (possibly conservatively). Find original
628 // name so that we can access the correct summary and see if it can
629 // be internalized again.
630 // FIXME: Eventually we should control promotion instead of promoting
631 // and internalizing again.
632 StringRef OrigName =
633 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
634 std::string OrigId = GlobalValue::getGlobalIdentifier(
635 OrigName, GlobalValue::InternalLinkage,
636 TheModule.getSourceFileName());
637 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000638 if (GS == DefinedGlobals.end()) {
639 // Also check the original non-promoted non-globalized name. In some
640 // cases a preempted weak value is linked in as a local copy because
641 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
642 // In that case, since it was originally not a local value, it was
643 // recorded in the index using the original name.
644 // FIXME: This may not be needed once PR27866 is fixed.
645 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
646 assert(GS != DefinedGlobals.end());
647 Linkage = GS->second->linkage();
648 } else {
649 Linkage = GS->second->linkage();
650 }
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000651 } else
652 Linkage = GS->second->linkage();
653 return !GlobalValue::isLocalLinkage(Linkage);
654 };
655
656 // FIXME: See if we can just internalize directly here via linkage changes
657 // based on the index, rather than invoking internalizeModule.
658 llvm::internalizeModule(TheModule, MustPreserveGV);
659}
660
Mehdi Aminic8c55172015-12-03 02:37:33 +0000661// Automatically import functions in Module \p DestModule based on the summaries
662// index.
663//
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000664Expected<bool> FunctionImporter::importFunctions(
Peter Collingbourne37e24592017-02-02 18:42:25 +0000665 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000666 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000667 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000668 unsigned ImportedCount = 0;
669
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000670 IRMover Mover(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000671 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000672 std::set<StringRef> ModuleNameOrderedList;
673 for (auto &FunctionsToImportPerModule : ImportList) {
674 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
675 }
676 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000677 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000678 const auto &FunctionsToImportPerModule = ImportList.find(Name);
679 assert(FunctionsToImportPerModule != ImportList.end());
Peter Collingbourned9445c42016-11-13 07:00:17 +0000680 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
681 if (!SrcModuleOrErr)
682 return SrcModuleOrErr.takeError();
683 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000684 assert(&DestModule.getContext() == &SrcModule->getContext() &&
685 "Context mismatch");
686
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000687 // If modules were created with lazy metadata loading, materialize it
688 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000689 if (Error Err = SrcModule->materializeMetadata())
690 return std::move(Err);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000691
Mehdi Amini01e32132016-03-26 05:40:34 +0000692 auto &ImportGUIDs = FunctionsToImportPerModule->second;
693 // Find the globals to import
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000694 SetVector<GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000695 for (Function &F : *SrcModule) {
696 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000697 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000698 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000699 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000700 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000701 << " " << F.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000702 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000703 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000704 if (Error Err = F.materialize())
705 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +0000706 if (EnableImportMetadata) {
707 // Add 'thinlto_src_module' metadata for statistics and debugging.
708 F.setMetadata(
709 "thinlto_src_module",
710 llvm::MDNode::get(
711 DestModule.getContext(),
712 {llvm::MDString::get(DestModule.getContext(),
713 SrcModule->getSourceFileName())}));
714 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000715 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000716 }
717 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000718 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000719 if (!GV.hasName())
720 continue;
721 auto GUID = GV.getGUID();
722 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000723 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
724 << " " << GV.getName() << " from "
725 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000726 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000727 if (Error Err = GV.materialize())
728 return std::move(Err);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000729 GlobalsToImport.insert(&GV);
730 }
731 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000732 for (GlobalAlias &GA : SrcModule->aliases()) {
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000733 // FIXME: This should eventually be controlled entirely by the summary.
734 if (FunctionImportGlobalProcessing::doImportAsDefinition(
735 &GA, &GlobalsToImport)) {
736 GlobalsToImport.insert(&GA);
737 continue;
738 }
739
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000740 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000741 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000742 auto GUID = GA.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000743 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000744 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000745 << " " << GA.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000746 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000747 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000748 // Alias can't point to "available_externally". However when we import
Teresa Johnson9aae3952016-03-27 15:01:11 +0000749 // linkOnceODR the linkage does not change. So we import the alias
Mehdi Amini6968ef72016-04-20 01:04:20 +0000750 // and aliasee only in this case. This has been handled by
751 // computeImportForFunction()
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000752 GlobalObject *GO = GA.getBaseObject();
Mehdi Amini6968ef72016-04-20 01:04:20 +0000753 assert(GO->hasLinkOnceODRLinkage() &&
754 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000755#ifndef NDEBUG
756 if (!GlobalsToImport.count(GO))
757 DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
758 << " " << GO->getName() << " from "
759 << SrcModule->getSourceFileName() << "\n");
760#endif
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000761 if (Error Err = GO->materialize())
762 return std::move(Err);
Mehdi Amini01e32132016-03-26 05:40:34 +0000763 GlobalsToImport.insert(GO);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000764 if (Error Err = GA.materialize())
765 return std::move(Err);
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000766 GlobalsToImport.insert(&GA);
Mehdi Amini01e32132016-03-26 05:40:34 +0000767 }
768 }
769
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000770 // Upgrade debug info after we're done materializing all the globals and we
771 // have loaded all the required metadata!
772 UpgradeDebugInfo(*SrcModule);
773
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000774 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000775 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000776 return true;
777
Teresa Johnsond29478f2016-03-27 15:27:30 +0000778 if (PrintImports) {
779 for (const auto *GV : GlobalsToImport)
780 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
781 << " from " << SrcModule->getSourceFileName() << "\n";
782 }
783
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000784 if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
785 [](GlobalValue &, IRMover::ValueAdder) {},
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +0000786 /*IsPerformingImport=*/true))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000787 report_fatal_error("Function Import: link error");
788
Mehdi Amini01e32132016-03-26 05:40:34 +0000789 ImportedCount += GlobalsToImport.size();
Teresa Johnson6c475a72017-01-05 21:34:18 +0000790 NumImportedModules++;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000791 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000792
Teresa Johnson6c475a72017-01-05 21:34:18 +0000793 NumImportedFunctions += ImportedCount;
Teresa Johnsond29478f2016-03-27 15:27:30 +0000794
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000795 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000796 << DestModule.getModuleIdentifier() << "\n");
797 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000798}
799
800/// Summary file to use for function importing when using -function-import from
801/// the command line.
802static cl::opt<std::string>
803 SummaryFile("summary-file",
804 cl::desc("The summary file to use for function importing."));
805
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000806static bool doImportingForModule(Module &M) {
807 if (SummaryFile.empty())
808 report_fatal_error("error: -function-import requires -summary-file\n");
809 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
810 getModuleSummaryIndexForFile(SummaryFile);
811 if (!IndexPtrOrErr) {
812 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
813 "Error loading file '" + SummaryFile + "': ");
814 return false;
Teresa Johnson21241572016-07-18 21:22:24 +0000815 }
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000816 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
Teresa Johnson21241572016-07-18 21:22:24 +0000817
818 // First step is collecting the import list.
819 FunctionImporter::ImportMapTy ImportList;
820 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
821 ImportList);
822
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000823 // Conservatively mark all internal values as promoted. This interface is
824 // only used when doing importing via the function importing pass. The pass
825 // is only enabled when testing importing via the 'opt' tool, which does
826 // not do the ThinLink that would normally determine what values to promote.
827 for (auto &I : *Index) {
828 for (auto &S : I.second) {
829 if (GlobalValue::isLocalLinkage(S->linkage()))
830 S->setLinkage(GlobalValue::ExternalLinkage);
831 }
832 }
833
Teresa Johnson21241572016-07-18 21:22:24 +0000834 // Next we need to promote to global scope and rename any local values that
835 // are potentially exported to other modules.
836 if (renameModuleForThinLTO(M, *Index, nullptr)) {
837 errs() << "Error renaming module\n";
838 return false;
839 }
840
841 // Perform the import now.
842 auto ModuleLoader = [&M](StringRef Identifier) {
843 return loadFile(Identifier, M.getContext());
844 };
845 FunctionImporter Importer(*Index, ModuleLoader);
Peter Collingbourne37e24592017-02-02 18:42:25 +0000846 Expected<bool> Result = Importer.importFunctions(M, ImportList);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000847
848 // FIXME: Probably need to propagate Errors through the pass manager.
849 if (!Result) {
850 logAllUnhandledErrors(Result.takeError(), errs(),
851 "Error importing module: ");
852 return false;
853 }
854
855 return *Result;
Teresa Johnson21241572016-07-18 21:22:24 +0000856}
857
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000858namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000859/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +0000860class FunctionImportLegacyPass : public ModulePass {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000861public:
862 /// Pass identification, replacement for typeid
863 static char ID;
864
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000865 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +0000866 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000867
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000868 explicit FunctionImportLegacyPass() : ModulePass(ID) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000869
870 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000871 if (skipModule(M))
872 return false;
873
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000874 return doImportingForModule(M);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000875 }
876};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000877} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000878
Teresa Johnson21241572016-07-18 21:22:24 +0000879PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000880 ModuleAnalysisManager &AM) {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000881 if (!doImportingForModule(M))
Teresa Johnson21241572016-07-18 21:22:24 +0000882 return PreservedAnalyses::all();
883
884 return PreservedAnalyses::none();
885}
886
887char FunctionImportLegacyPass::ID = 0;
888INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
889 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +0000890
891namespace llvm {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000892Pass *createFunctionImportPass() {
893 return new FunctionImportLegacyPass();
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000894}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000895}