blob: 26d7db10880df9dcfc95ae34beb90d83a4931b65 [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"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000015#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SetVector.h"
Mehdi Amini01e32132016-03-26 05:40:34 +000018#include "llvm/ADT/SmallVector.h"
Teresa Johnsond29478f2016-03-27 15:27:30 +000019#include "llvm/ADT/Statistic.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000020#include "llvm/ADT/StringMap.h"
Simon Pilgrim0efed322018-02-18 00:01:36 +000021#include "llvm/ADT/StringRef.h"
Charles Saternosb040fcc2018-02-19 15:14:50 +000022#include "llvm/ADT/StringSet.h"
Peter Collingbournec15d60b2017-05-01 20:42:32 +000023#include "llvm/Bitcode/BitcodeReader.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000024#include "llvm/IR/AutoUpgrade.h"
Teresa Johnson81bbf742017-12-16 00:18:12 +000025#include "llvm/IR/Constants.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000026#include "llvm/IR/Function.h"
27#include "llvm/IR/GlobalAlias.h"
28#include "llvm/IR/GlobalObject.h"
29#include "llvm/IR/GlobalValue.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/Metadata.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000032#include "llvm/IR/Module.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000033#include "llvm/IR/ModuleSummaryIndex.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000034#include "llvm/IRReader/IRReader.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000035#include "llvm/Linker/IRMover.h"
36#include "llvm/Object/ModuleSymbolTable.h"
37#include "llvm/Object/SymbolicFile.h"
38#include "llvm/Pass.h"
39#include "llvm/Support/Casting.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000040#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/Debug.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000042#include "llvm/Support/Error.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/FileSystem.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000045#include "llvm/Support/SourceMgr.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000046#include "llvm/Support/raw_ostream.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000047#include "llvm/Transforms/IPO/Internalize.h"
Teresa Johnson81bbf742017-12-16 00:18:12 +000048#include "llvm/Transforms/Utils/Cloning.h"
Teresa Johnson488a8002016-02-10 18:11:31 +000049#include "llvm/Transforms/Utils/FunctionImportUtils.h"
Teresa Johnson81bbf742017-12-16 00:18:12 +000050#include "llvm/Transforms/Utils/ValueMapper.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000051#include <cassert>
52#include <memory>
53#include <set>
54#include <string>
55#include <system_error>
56#include <tuple>
57#include <utility>
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000058
Mehdi Amini42418ab2015-11-24 06:07:49 +000059using namespace llvm;
60
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000061#define DEBUG_TYPE "function-import"
62
Teresa Johnson6c475a72017-01-05 21:34:18 +000063STATISTIC(NumImportedFunctions, "Number of functions imported");
Eugene Leviant19e23872018-03-12 10:30:50 +000064STATISTIC(NumImportedGlobalVars, "Number of global variables imported");
Teresa Johnson6c475a72017-01-05 21:34:18 +000065STATISTIC(NumImportedModules, "Number of modules imported from");
66STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
67STATISTIC(NumLiveSymbols, "Number of live symbols in index");
Teresa Johnsond29478f2016-03-27 15:27:30 +000068
Teresa Johnson39303612015-11-24 22:55:46 +000069/// Limit on instruction count of imported functions.
70static cl::opt<unsigned> ImportInstrLimit(
71 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
72 cl::desc("Only import functions with less than N instructions"));
73
Teresa Johnson974706e2018-04-01 15:54:40 +000074static cl::opt<int> ImportCutoff(
75 "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"),
76 cl::desc("Only import first N functions if N>=0 (default -1)"));
77
Mehdi Amini40641742016-02-10 23:31:45 +000078static cl::opt<float>
79 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
80 cl::Hidden, cl::value_desc("x"),
81 cl::desc("As we import functions, multiply the "
82 "`import-instr-limit` threshold by this factor "
83 "before processing newly imported functions"));
Piotr Padlewskiba72b952016-09-29 17:32:07 +000084
Piotr Padlewskid2869472016-09-30 03:01:17 +000085static cl::opt<float> ImportHotInstrFactor(
86 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
87 cl::value_desc("x"),
88 cl::desc("As we import functions called from hot callsite, multiply the "
89 "`import-instr-limit` threshold by this factor "
90 "before processing newly imported functions"));
91
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000092static cl::opt<float> ImportHotMultiplier(
Dehao Chen8260d662017-07-28 01:02:34 +000093 "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
Piotr Padlewskiba72b952016-09-29 17:32:07 +000094 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
95
Dehao Chen64c46572017-07-07 21:01:00 +000096static cl::opt<float> ImportCriticalMultiplier(
97 "import-critical-multiplier", cl::init(100.0), cl::Hidden,
98 cl::value_desc("x"),
99 cl::desc(
100 "Multiply the `import-instr-limit` threshold for critical callsites"));
101
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000102// FIXME: This multiplier was not really tuned up.
103static cl::opt<float> ImportColdMultiplier(
104 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
105 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
Mehdi Amini40641742016-02-10 23:31:45 +0000106
Teresa Johnsond29478f2016-03-27 15:27:30 +0000107static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
108 cl::desc("Print imported functions"));
109
Teresa Johnson6c475a72017-01-05 21:34:18 +0000110static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
111 cl::desc("Compute dead symbols"));
112
Piotr Padlewski3b776122016-07-08 23:01:49 +0000113static cl::opt<bool> EnableImportMetadata(
114 "enable-import-metadata", cl::init(
115#if !defined(NDEBUG)
116 true /*Enabled with asserts.*/
117#else
118 false
119#endif
120 ),
121 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
122
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000123/// Summary file to use for function importing when using -function-import from
124/// the command line.
125static cl::opt<std::string>
126 SummaryFile("summary-file",
127 cl::desc("The summary file to use for function importing."));
128
Teresa Johnson81bbf742017-12-16 00:18:12 +0000129/// Used when testing importing from distributed indexes via opt
130// -function-import.
131static cl::opt<bool>
132 ImportAllIndex("import-all-index",
133 cl::desc("Import all external functions in index."));
134
Mehdi Amini42418ab2015-11-24 06:07:49 +0000135// Load lazily a module from \p FileName in \p Context.
136static std::unique_ptr<Module> loadFile(const std::string &FileName,
137 LLVMContext &Context) {
138 SMDiagnostic Err;
139 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000140 // Metadata isn't loaded until functions are imported, to minimize
141 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +0000142 std::unique_ptr<Module> Result =
143 getLazyIRFileModule(FileName, Err, Context,
144 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000145 if (!Result) {
146 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +0000147 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000148 }
149
Mehdi Amini42418ab2015-11-24 06:07:49 +0000150 return Result;
151}
152
Mehdi Amini01e32132016-03-26 05:40:34 +0000153/// Given a list of possible callee implementation for a call site, select one
154/// that fits the \p Threshold.
155///
156/// FIXME: select "best" instead of first that fits. But what is "best"?
157/// - The smallest: more likely to be inlined.
158/// - The one with the least outgoing edges (already well optimized).
159/// - One from a module already being imported from in order to reduce the
160/// number of source modules parsed/linked.
161/// - One that has PGO data attached.
162/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000163static const GlobalValueSummary *
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000164selectCallee(const ModuleSummaryIndex &Index,
Peter Collingbourne9667b912017-05-04 18:03:25 +0000165 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
Teresa Johnson83aaf352017-01-12 22:04:45 +0000166 unsigned Threshold, StringRef CallerModulePath) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000167 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000168 CalleeSummaryList,
169 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
170 auto *GVSummary = SummaryPtr.get();
George Rimareaf51722018-01-29 08:03:30 +0000171 if (!Index.isGlobalValueLive(GVSummary))
172 return false;
173
Teresa Johnson73305f82017-08-19 18:04:25 +0000174 // For SamplePGO, in computeImportForFunction the OriginalId
175 // may have been used to locate the callee summary list (See
176 // comment there).
177 // The mapping from OriginalId to GUID may return a GUID
178 // that corresponds to a static variable. Filter it out here.
179 // This can happen when
180 // 1) There is a call to a library function which is not defined
181 // in the index.
182 // 2) There is a static variable with the OriginalGUID identical
183 // to the GUID of the library function in 1);
184 // When this happens, the logic for SamplePGO kicks in and
185 // the static variable in 2) will be found, which needs to be
186 // filtered out.
187 if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
188 return false;
Rafael Espindolaf329be82016-05-11 01:26:06 +0000189 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000190 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000191 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000192
Teresa Johnson81bbf742017-12-16 00:18:12 +0000193 auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000194
Teresa Johnson83aaf352017-01-12 22:04:45 +0000195 // If this is a local function, make sure we import the copy
196 // in the caller's module. The only time a local function can
197 // share an entry in the index is if there is a local with the same name
198 // in another module that had the same source file name (in a different
199 // directory), where each was compiled in their own directory so there
200 // was not distinguishing path.
201 // However, do the import from another module if there is only one
202 // entry in the list - in that case this must be a reference due
203 // to indirect call profile data, since a function pointer can point to
204 // a local in another module.
205 if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
206 CalleeSummaryList.size() > 1 &&
207 Summary->modulePath() != CallerModulePath)
208 return false;
209
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000210 if (Summary->instCount() > Threshold)
211 return false;
212
Teresa Johnson519465b2017-01-05 14:32:16 +0000213 if (Summary->notEligibleToImport())
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000214 return false;
215
Mehdi Amini01e32132016-03-26 05:40:34 +0000216 return true;
217 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000218 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000219 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000220
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000221 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000222}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000223
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000224namespace {
225
Teresa Johnson475b51a2016-12-15 20:48:19 +0000226using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
227 GlobalValue::GUID>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000228
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000229} // anonymous namespace
230
Teresa Johnson19580832017-09-13 15:16:38 +0000231static ValueInfo
232updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) {
233 if (!VI.getSummaryList().empty())
234 return VI;
235 // For SamplePGO, the indirect call targets for local functions will
236 // have its original name annotated in profile. We try to find the
237 // corresponding PGOFuncName as the GUID.
238 // FIXME: Consider updating the edges in the graph after building
239 // it, rather than needing to perform this mapping on each walk.
240 auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
241 if (GUID == 0)
Eugene Leviant28d8a492018-01-22 13:35:40 +0000242 return ValueInfo();
Teresa Johnson19580832017-09-13 15:16:38 +0000243 return Index.getValueInfo(GUID);
244}
245
Eugene Leviant19e23872018-03-12 10:30:50 +0000246static void computeImportForReferencedGlobals(
247 const FunctionSummary &Summary, const GVSummaryMapTy &DefinedGVSummaries,
248 FunctionImporter::ImportMapTy &ImportList,
249 StringMap<FunctionImporter::ExportSetTy> *ExportLists) {
250 for (auto &VI : Summary.refs()) {
251 if (DefinedGVSummaries.count(VI.getGUID())) {
252 DEBUG(dbgs() << "Ref ignored! Target already in destination module.\n");
253 continue;
254 }
255
256 DEBUG(dbgs() << " ref -> " << VI.getGUID() << "\n");
257
258 for (auto &RefSummary : VI.getSummaryList())
259 if (RefSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind &&
260 // Don't try to import regular LTO summaries added to dummy module.
261 !RefSummary->modulePath().empty() &&
262 !GlobalValue::isInterposableLinkage(RefSummary->linkage()) &&
263 RefSummary->refs().empty()) {
264 ImportList[RefSummary->modulePath()][VI.getGUID()] = 1;
265 if (ExportLists)
266 (*ExportLists)[RefSummary->modulePath()].insert(VI.getGUID());
267 break;
268 }
269 }
270}
271
Mehdi Amini01e32132016-03-26 05:40:34 +0000272/// Compute the list of functions to import for a given caller. Mark these
273/// imported functions and the symbols they reference in their source module as
274/// exported from their source module.
275static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000276 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000277 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000278 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000279 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000280 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Eugene Leviant19e23872018-03-12 10:30:50 +0000281 computeImportForReferencedGlobals(Summary, DefinedGVSummaries, ImportList,
282 ExportLists);
Teresa Johnson974706e2018-04-01 15:54:40 +0000283 static int ImportCount = 0;
Mehdi Amini01e32132016-03-26 05:40:34 +0000284 for (auto &Edge : Summary.calls()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000285 ValueInfo VI = Edge.first;
286 DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold
287 << "\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000288
Teresa Johnson974706e2018-04-01 15:54:40 +0000289 if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
290 DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
291 << " reached.\n");
292 continue;
293 }
294
Teresa Johnson19580832017-09-13 15:16:38 +0000295 VI = updateValueInfoForIndirectCalls(Index, VI);
296 if (!VI)
297 continue;
Dehao Chen4a435e02017-03-14 17:33:01 +0000298
Peter Collingbourne9667b912017-05-04 18:03:25 +0000299 if (DefinedGVSummaries.count(VI.getGUID())) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000300 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
301 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000302 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000303
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000304 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
305 if (Hotness == CalleeInfo::HotnessType::Hot)
306 return ImportHotMultiplier;
307 if (Hotness == CalleeInfo::HotnessType::Cold)
308 return ImportColdMultiplier;
Dehao Chen64c46572017-07-07 21:01:00 +0000309 if (Hotness == CalleeInfo::HotnessType::Critical)
310 return ImportCriticalMultiplier;
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000311 return 1.0;
312 };
313
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000314 const auto NewThreshold =
Easwaran Ramanc73cec82018-01-25 19:27:17 +0000315 Threshold * GetBonusMultiplier(Edge.second.getHotness());
Piotr Padlewskid2869472016-09-30 03:01:17 +0000316
Peter Collingbourne9667b912017-05-04 18:03:25 +0000317 auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
318 Summary.modulePath());
Mehdi Amini01e32132016-03-26 05:40:34 +0000319 if (!CalleeSummary) {
320 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
321 continue;
322 }
David Blaikie2f0cc472017-07-27 15:09:06 +0000323
324 // "Resolve" the summary
Teresa Johnson81bbf742017-12-16 00:18:12 +0000325 const auto *ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary->getBaseObject());
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000326
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000327 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000328 "selectCallee() didn't honor the threshold");
329
Piotr Padlewskid2869472016-09-30 03:01:17 +0000330 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
331 // Adjust the threshold for next level of imported functions.
332 // The threshold is different for hot callsites because we can then
333 // inline chains of hot calls.
334 if (IsHotCallsite)
335 return Threshold * ImportHotInstrFactor;
336 return Threshold * ImportInstrFactor;
337 };
338
Easwaran Ramanc73cec82018-01-25 19:27:17 +0000339 bool IsHotCallsite =
340 Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000341 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
342
343 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000344 auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()];
Teresa Johnson1b859a22016-12-15 18:21:01 +0000345 /// Since the traversal of the call graph is DFS, we can revisit a function
346 /// a second time with a higher threshold. In this case, it is added back to
347 /// the worklist with the new threshold.
348 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
349 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
350 << ProcessedThreshold << "\n");
351 continue;
352 }
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000353 bool PreviouslyImported = ProcessedThreshold != 0;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000354 // Mark this function as imported in this module, with the current Threshold
355 ProcessedThreshold = AdjThreshold;
356
Teresa Johnson974706e2018-04-01 15:54:40 +0000357 ImportCount++;
358
Teresa Johnson1b859a22016-12-15 18:21:01 +0000359 // Make exports in the source module.
360 if (ExportLists) {
361 auto &ExportList = (*ExportLists)[ExportModulePath];
Peter Collingbourne9667b912017-05-04 18:03:25 +0000362 ExportList.insert(VI.getGUID());
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000363 if (!PreviouslyImported) {
364 // This is the first time this function was exported from its source
365 // module, so mark all functions and globals it references as exported
366 // to the outside if they are defined in the same source module.
Teresa Johnsonedddca22016-12-16 04:11:51 +0000367 // For efficiency, we unconditionally add all the referenced GUIDs
368 // to the ExportList for this module, and will prune out any not
369 // defined in the module later in a single pass.
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000370 for (auto &Edge : ResolvedCalleeSummary->calls()) {
371 auto CalleeGUID = Edge.first.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000372 ExportList.insert(CalleeGUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000373 }
374 for (auto &Ref : ResolvedCalleeSummary->refs()) {
375 auto GUID = Ref.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000376 ExportList.insert(GUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000377 }
Teresa Johnson1b859a22016-12-15 18:21:01 +0000378 }
379 }
Piotr Padlewskid2869472016-09-30 03:01:17 +0000380
Mehdi Amini01e32132016-03-26 05:40:34 +0000381 // Insert the newly imported function to the worklist.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000382 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
Teresa Johnsond450da32015-11-24 21:15:19 +0000383 }
384}
385
Mehdi Amini01e32132016-03-26 05:40:34 +0000386/// Given the list of globals defined in a module, compute the list of imports
387/// as well as the list of "exports", i.e. the list of symbols referenced from
388/// another module (that may require promotion).
389static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000390 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000391 FunctionImporter::ImportMapTy &ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000392 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000393 // Worklist contains the list of function imported in this module, for which
394 // we will analyse the callees and may import further down the callgraph.
395 SmallVector<EdgeInfo, 128> Worklist;
396
397 // Populate the worklist with the import for the functions in the current
398 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000399 for (auto &GVSummary : DefinedGVSummaries) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000400 if (!Index.isGlobalValueLive(GVSummary.second)) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000401 DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
402 continue;
403 }
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000404 auto *FuncSummary =
405 dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000406 if (!FuncSummary)
407 // Skip import for global variables
408 continue;
Xinliang David Li24524f32017-08-11 17:49:20 +0000409 DEBUG(dbgs() << "Initialize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000410 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000411 DefinedGVSummaries, Worklist, ImportList,
Mehdi Amini01e32132016-03-26 05:40:34 +0000412 ExportLists);
413 }
414
Piotr Padlewskid2869472016-09-30 03:01:17 +0000415 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000416 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000417 auto FuncInfo = Worklist.pop_back_val();
Teresa Johnson475b51a2016-12-15 20:48:19 +0000418 auto *Summary = std::get<0>(FuncInfo);
419 auto Threshold = std::get<1>(FuncInfo);
420 auto GUID = std::get<2>(FuncInfo);
421
422 // Check if we later added this summary with a higher threshold.
423 // If so, skip this entry.
424 auto ExportModulePath = Summary->modulePath();
425 auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
426 if (LatestProcessedThreshold > Threshold)
427 continue;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000428
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000429 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000430 Worklist, ImportList, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000431 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000432}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000433
Eugene Leviant19e23872018-03-12 10:30:50 +0000434#ifndef NDEBUG
435static bool isGlobalVarSummary(const ModuleSummaryIndex &Index,
436 GlobalValue::GUID G) {
437 if (const auto &VI = Index.getValueInfo(G)) {
438 auto SL = VI.getSummaryList();
439 if (!SL.empty())
440 return SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
441 }
442 return false;
443}
444
445static GlobalValue::GUID getGUID(GlobalValue::GUID G) { return G; }
446
447static GlobalValue::GUID
448getGUID(const std::pair<const GlobalValue::GUID, unsigned> &P) {
449 return P.first;
450}
451
452template <class T>
453unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index, T &Cont) {
454 unsigned NumGVS = 0;
455 for (auto &V : Cont)
456 if (isGlobalVarSummary(Index, getGUID(V)))
457 ++NumGVS;
458 return NumGVS;
459}
460#endif
461
Teresa Johnsonc86af332016-04-12 21:13:11 +0000462/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000463void llvm::ComputeCrossModuleImport(
464 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000465 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000466 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000467 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000468 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000469 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000470 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000471 DEBUG(dbgs() << "Computing import for Module '"
472 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000473 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000474 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000475 }
476
Teresa Johnsonedddca22016-12-16 04:11:51 +0000477 // When computing imports we added all GUIDs referenced by anything
478 // imported from the module to its ExportList. Now we prune each ExportList
479 // of any not defined in that module. This is more efficient than checking
480 // while computing imports because some of the summary lists may be long
481 // due to linkonce (comdat) copies.
482 for (auto &ELI : ExportLists) {
483 const auto &DefinedGVSummaries =
484 ModuleToDefinedGVSummaries.lookup(ELI.first());
485 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
486 if (!DefinedGVSummaries.count(*EI))
487 EI = ELI.second.erase(EI);
488 else
489 ++EI;
490 }
491 }
492
Mehdi Amini01e32132016-03-26 05:40:34 +0000493#ifndef NDEBUG
494 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
495 << " modules:\n");
496 for (auto &ModuleImports : ImportLists) {
497 auto ModName = ModuleImports.first();
498 auto &Exports = ExportLists[ModName];
Eugene Leviant19e23872018-03-12 10:30:50 +0000499 unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
500 DEBUG(dbgs() << "* Module " << ModName << " exports "
501 << Exports.size() - NumGVS << " functions and " << NumGVS
502 << " vars. Imports from "
503 << ModuleImports.second.size() << " modules.\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000504 for (auto &Src : ModuleImports.second) {
505 auto SrcModName = Src.first();
Eugene Leviant19e23872018-03-12 10:30:50 +0000506 unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
507 DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
508 << " functions imported from " << SrcModName << "\n");
509 DEBUG(dbgs() << " - " << NumGVSPerMod << " global vars imported from "
Mehdi Amini01e32132016-03-26 05:40:34 +0000510 << SrcModName << "\n");
511 }
512 }
513#endif
514}
515
Teresa Johnson81bbf742017-12-16 00:18:12 +0000516#ifndef NDEBUG
Eugene Leviant19e23872018-03-12 10:30:50 +0000517static void dumpImportListForModule(const ModuleSummaryIndex &Index,
518 StringRef ModulePath,
Teresa Johnson81bbf742017-12-16 00:18:12 +0000519 FunctionImporter::ImportMapTy &ImportList) {
520 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
521 << ImportList.size() << " modules.\n");
522 for (auto &Src : ImportList) {
523 auto SrcModName = Src.first();
Eugene Leviant19e23872018-03-12 10:30:50 +0000524 unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
525 DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
526 << " functions imported from " << SrcModName << "\n");
527 DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from "
Teresa Johnson81bbf742017-12-16 00:18:12 +0000528 << SrcModName << "\n");
529 }
Teresa Johnson81bbf742017-12-16 00:18:12 +0000530}
Teresa Johnson69b2de82017-12-16 00:29:31 +0000531#endif
Teresa Johnson81bbf742017-12-16 00:18:12 +0000532
Teresa Johnsonc86af332016-04-12 21:13:11 +0000533/// Compute all the imports for the given module in the Index.
534void llvm::ComputeCrossModuleImportForModule(
535 StringRef ModulePath, const ModuleSummaryIndex &Index,
536 FunctionImporter::ImportMapTy &ImportList) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000537 // Collect the list of functions this module defines.
538 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000539 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000540 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000541
542 // Compute the import list for this module.
543 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000544 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000545
546#ifndef NDEBUG
Eugene Leviant19e23872018-03-12 10:30:50 +0000547 dumpImportListForModule(Index, ModulePath, ImportList);
Teresa Johnson81bbf742017-12-16 00:18:12 +0000548#endif
549}
550
551// Mark all external summaries in Index for import into the given module.
552// Used for distributed builds using a distributed index.
553void llvm::ComputeCrossModuleImportForModuleFromIndex(
554 StringRef ModulePath, const ModuleSummaryIndex &Index,
555 FunctionImporter::ImportMapTy &ImportList) {
556 for (auto &GlobalList : Index) {
557 // Ignore entries for undefined references.
558 if (GlobalList.second.SummaryList.empty())
559 continue;
560
561 auto GUID = GlobalList.first;
562 assert(GlobalList.second.SummaryList.size() == 1 &&
563 "Expected individual combined index to have one summary per GUID");
564 auto &Summary = GlobalList.second.SummaryList[0];
565 // Skip the summaries for the importing module. These are included to
566 // e.g. record required linkage changes.
567 if (Summary->modulePath() == ModulePath)
568 continue;
569 // Doesn't matter what value we plug in to the map, just needs an entry
570 // to provoke importing by thinBackend.
571 ImportList[Summary->modulePath()][GUID] = 1;
Teresa Johnsonc86af332016-04-12 21:13:11 +0000572 }
Teresa Johnson81bbf742017-12-16 00:18:12 +0000573#ifndef NDEBUG
Eugene Leviant19e23872018-03-12 10:30:50 +0000574 dumpImportListForModule(Index, ModulePath, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000575#endif
576}
577
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000578void llvm::computeDeadSymbols(
579 ModuleSummaryIndex &Index,
George Rimareaf51722018-01-29 08:03:30 +0000580 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
581 function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000582 assert(!Index.withGlobalValueDeadStripping());
Teresa Johnson6c475a72017-01-05 21:34:18 +0000583 if (!ComputeDead)
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000584 return;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000585 if (GUIDPreservedSymbols.empty())
586 // Don't do anything when nothing is live, this is friendly with tests.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000587 return;
588 unsigned LiveSymbols = 0;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000589 SmallVector<ValueInfo, 128> Worklist;
590 Worklist.reserve(GUIDPreservedSymbols.size() * 2);
591 for (auto GUID : GUIDPreservedSymbols) {
592 ValueInfo VI = Index.getValueInfo(GUID);
593 if (!VI)
594 continue;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000595 for (auto &S : VI.getSummaryList())
596 S->setLive(true);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000597 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000598
Teresa Johnson6c475a72017-01-05 21:34:18 +0000599 // Add values flagged in the index as live roots to the worklist.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000600 for (const auto &Entry : Index)
601 for (auto &S : Entry.second.SummaryList)
602 if (S->isLive()) {
603 DEBUG(dbgs() << "Live root: " << Entry.first << "\n");
Eugene Leviant28d8a492018-01-22 13:35:40 +0000604 Worklist.push_back(ValueInfo(/*IsAnalysis=*/false, &Entry));
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000605 ++LiveSymbols;
606 break;
607 }
608
609 // Make value live and add it to the worklist if it was not live before.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000610 auto visit = [&](ValueInfo VI) {
Teresa Johnson19580832017-09-13 15:16:38 +0000611 // FIXME: If we knew which edges were created for indirect call profiles,
612 // we could skip them here. Any that are live should be reached via
613 // other edges, e.g. reference edges. Otherwise, using a profile collected
614 // on a slightly different binary might provoke preserving, importing
615 // and ultimately promoting calls to functions not linked into this
616 // binary, which increases the binary size unnecessarily. Note that
617 // if this code changes, the importer needs to change so that edges
618 // to functions marked dead are skipped.
619 VI = updateValueInfoForIndirectCalls(Index, VI);
620 if (!VI)
621 return;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000622 for (auto &S : VI.getSummaryList())
Teresa Johnsonf6251182017-09-20 17:09:47 +0000623 if (S->isLive())
624 return;
George Rimareaf51722018-01-29 08:03:30 +0000625
Vlad Tsyrklevichaab60002018-03-13 05:08:48 +0000626 // We only keep live symbols that are known to be non-prevailing if any are
627 // available_externally. Those symbols are discarded later in the
628 // EliminateAvailableExternally pass and setting them to not-live breaks
629 // downstreams users of liveness information (PR36483).
630 if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
631 bool AvailableExternally = false;
632 bool Interposable = false;
633 for (auto &S : VI.getSummaryList()) {
634 if (S->linkage() == GlobalValue::AvailableExternallyLinkage)
635 AvailableExternally = true;
636 else if (GlobalValue::isInterposableLinkage(S->linkage()))
637 Interposable = true;
638 }
639
640 if (!AvailableExternally)
641 return;
642
643 if (Interposable)
644 report_fatal_error("Interposable and available_externally symbol");
645 }
George Rimareaf51722018-01-29 08:03:30 +0000646
Teresa Johnsonf6251182017-09-20 17:09:47 +0000647 for (auto &S : VI.getSummaryList())
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000648 S->setLive(true);
649 ++LiveSymbols;
650 Worklist.push_back(VI);
651 };
Teresa Johnson6c475a72017-01-05 21:34:18 +0000652
653 while (!Worklist.empty()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000654 auto VI = Worklist.pop_back_val();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000655 for (auto &Summary : VI.getSummaryList()) {
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000656 GlobalValueSummary *Base = Summary->getBaseObject();
George Rimareaf51722018-01-29 08:03:30 +0000657 // Set base value live in case it is an alias.
658 Base->setLive(true);
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000659 for (auto Ref : Base->refs())
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000660 visit(Ref);
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000661 if (auto *FS = dyn_cast<FunctionSummary>(Base))
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000662 for (auto Call : FS->calls())
663 visit(Call.first);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000664 }
665 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000666 Index.setWithGlobalValueDeadStripping();
667
668 unsigned DeadSymbols = Index.size() - LiveSymbols;
669 DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
670 << " symbols Dead \n");
671 NumDeadSymbols += DeadSymbols;
672 NumLiveSymbols += LiveSymbols;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000673}
674
Teresa Johnson84174c32016-05-10 13:48:23 +0000675/// Compute the set of summaries needed for a ThinLTO backend compilation of
676/// \p ModulePath.
677void llvm::gatherImportedSummariesForModule(
678 StringRef ModulePath,
679 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000680 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000681 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
682 // Include all summaries from the importing module.
683 ModuleToSummariesForIndex[ModulePath] =
684 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000685 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000686 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000687 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
688 const auto &DefinedGVSummaries =
689 ModuleToDefinedGVSummaries.lookup(ILI.first());
690 for (auto &GI : ILI.second) {
691 const auto &DS = DefinedGVSummaries.find(GI.first);
692 assert(DS != DefinedGVSummaries.end() &&
693 "Expected a defined summary for imported global value");
694 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000695 }
696 }
697}
698
Teresa Johnson8570fe42016-05-10 15:54:09 +0000699/// Emit the files \p ModulePath will import from into \p OutputFilename.
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000700std::error_code
701llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
702 const FunctionImporter::ImportMapTy &ModuleImports) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000703 std::error_code EC;
704 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
705 if (EC)
706 return EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000707 for (auto &ILI : ModuleImports)
708 ImportsOS << ILI.first() << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000709 return std::error_code();
710}
711
Teresa Johnson5a95c472018-02-05 15:44:27 +0000712bool llvm::convertToDeclaration(GlobalValue &GV) {
George Rimareaf51722018-01-29 08:03:30 +0000713 DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n");
714 if (Function *F = dyn_cast<Function>(&GV)) {
715 F->deleteBody();
716 F->clearMetadata();
Peter Collingbourne78736692018-01-31 02:51:03 +0000717 F->setComdat(nullptr);
George Rimareaf51722018-01-29 08:03:30 +0000718 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
719 V->setInitializer(nullptr);
720 V->setLinkage(GlobalValue::ExternalLinkage);
721 V->clearMetadata();
Peter Collingbourne78736692018-01-31 02:51:03 +0000722 V->setComdat(nullptr);
Teresa Johnson5a95c472018-02-05 15:44:27 +0000723 } else {
724 GlobalValue *NewGV;
725 if (GV.getValueType()->isFunctionTy())
726 NewGV =
727 Function::Create(cast<FunctionType>(GV.getValueType()),
728 GlobalValue::ExternalLinkage, "", GV.getParent());
729 else
730 NewGV =
731 new GlobalVariable(*GV.getParent(), GV.getValueType(),
732 /*isConstant*/ false, GlobalValue::ExternalLinkage,
733 /*init*/ nullptr, "",
734 /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
735 GV.getType()->getAddressSpace());
736 NewGV->takeName(&GV);
737 GV.replaceAllUsesWith(NewGV);
738 return false;
739 }
740 return true;
George Rimareaf51722018-01-29 08:03:30 +0000741}
742
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000743/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
744void llvm::thinLTOResolveWeakForLinkerModule(
745 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
746 auto updateLinkage = [&](GlobalValue &GV) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000747 // See if the global summary analysis computed a new resolved linkage.
748 const auto &GS = DefinedGlobals.find(GV.getGUID());
749 if (GS == DefinedGlobals.end())
750 return;
751 auto NewLinkage = GS->second->linkage();
752 if (NewLinkage == GV.getLinkage())
753 return;
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000754
755 // Switch the linkage to weakany if asked for, e.g. we do this for
756 // linker redefined symbols (via --wrap or --defsym).
Davide Italianof4891d22017-07-06 20:04:20 +0000757 // We record that the visibility should be changed here in `addThinLTO`
758 // as we need access to the resolution vectors for each input file in
759 // order to find which symbols have been redefined.
760 // We may consider reorganizing this code and moving the linkage recording
761 // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex.
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000762 if (NewLinkage == GlobalValue::WeakAnyLinkage) {
763 GV.setLinkage(NewLinkage);
764 return;
765 }
766
767 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
768 return;
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000769 // Check for a non-prevailing def that has interposable linkage
770 // (e.g. non-odr weak or linkonce). In that case we can't simply
771 // convert to available_externally, since it would lose the
772 // interposable property and possibly get inlined. Simply drop
773 // the definition in that case.
774 if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
Teresa Johnson5a95c472018-02-05 15:44:27 +0000775 GlobalValue::isInterposableLinkage(GV.getLinkage())) {
776 if (!convertToDeclaration(GV))
777 // FIXME: Change this to collect replaced GVs and later erase
778 // them from the parent module once thinLTOResolveWeakForLinkerGUID is
779 // changed to enable this for aliases.
780 llvm_unreachable("Expected GV to be converted");
781 } else {
Steven Wu33ba93c2018-02-09 18:34:08 +0000782 // If the original symbols has global unnamed addr and linkonce_odr linkage,
783 // it should be an auto hide symbol. Add hidden visibility to the symbol to
784 // preserve the property.
785 if (GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr() &&
786 NewLinkage == GlobalValue::WeakODRLinkage)
787 GV.setVisibility(GlobalValue::HiddenVisibility);
788
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000789 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
790 << GV.getLinkage() << " to " << NewLinkage << "\n");
791 GV.setLinkage(NewLinkage);
792 }
793 // Remove declarations from comdats, including available_externally
Teresa Johnson6107a412016-08-15 21:00:04 +0000794 // as this is a declaration for the linker, and will be dropped eventually.
795 // It is illegal for comdats to contain declarations.
796 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000797 if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
Teresa Johnson6107a412016-08-15 21:00:04 +0000798 GO->setComdat(nullptr);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000799 };
800
801 // Process functions and global now
802 for (auto &GV : TheModule)
803 updateLinkage(GV);
804 for (auto &GV : TheModule.globals())
805 updateLinkage(GV);
806 for (auto &GV : TheModule.aliases())
807 updateLinkage(GV);
808}
809
810/// Run internalization on \p TheModule based on symmary analysis.
811void llvm::thinLTOInternalizeModule(Module &TheModule,
812 const GVSummaryMapTy &DefinedGlobals) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000813 // Declare a callback for the internalize pass that will ask for every
814 // candidate GlobalValue if it can be internalized or not.
815 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000816 // Lookup the linkage recorded in the summaries during global analysis.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000817 auto GS = DefinedGlobals.find(GV.getGUID());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000818 if (GS == DefinedGlobals.end()) {
819 // Must have been promoted (possibly conservatively). Find original
820 // name so that we can access the correct summary and see if it can
821 // be internalized again.
822 // FIXME: Eventually we should control promotion instead of promoting
823 // and internalizing again.
824 StringRef OrigName =
825 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
826 std::string OrigId = GlobalValue::getGlobalIdentifier(
827 OrigName, GlobalValue::InternalLinkage,
828 TheModule.getSourceFileName());
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000829 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000830 if (GS == DefinedGlobals.end()) {
831 // Also check the original non-promoted non-globalized name. In some
832 // cases a preempted weak value is linked in as a local copy because
833 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
834 // In that case, since it was originally not a local value, it was
835 // recorded in the index using the original name.
836 // FIXME: This may not be needed once PR27866 is fixed.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000837 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000838 assert(GS != DefinedGlobals.end());
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000839 }
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000840 }
841 return !GlobalValue::isLocalLinkage(GS->second->linkage());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000842 };
843
844 // FIXME: See if we can just internalize directly here via linkage changes
845 // based on the index, rather than invoking internalizeModule.
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000846 internalizeModule(TheModule, MustPreserveGV);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000847}
848
Teresa Johnson81bbf742017-12-16 00:18:12 +0000849/// Make alias a clone of its aliasee.
850static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
851 Function *Fn = cast<Function>(GA->getBaseObject());
852
853 ValueToValueMapTy VMap;
854 Function *NewFn = CloneFunction(Fn, VMap);
855 // Clone should use the original alias's linkage and name, and we ensure
856 // all uses of alias instead use the new clone (casted if necessary).
857 NewFn->setLinkage(GA->getLinkage());
858 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
859 NewFn->takeName(GA);
860 return NewFn;
861}
862
Mehdi Aminic8c55172015-12-03 02:37:33 +0000863// Automatically import functions in Module \p DestModule based on the summaries
864// index.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000865Expected<bool> FunctionImporter::importFunctions(
Adrian Prantl66043792017-05-19 23:32:21 +0000866 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000867 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000868 << DestModule.getModuleIdentifier() << "\n");
Eugene Leviant19e23872018-03-12 10:30:50 +0000869 unsigned ImportedCount = 0, ImportedGVCount = 0;
Mehdi Aminic8c55172015-12-03 02:37:33 +0000870
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000871 IRMover Mover(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000872 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000873 std::set<StringRef> ModuleNameOrderedList;
874 for (auto &FunctionsToImportPerModule : ImportList) {
875 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
876 }
877 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000878 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000879 const auto &FunctionsToImportPerModule = ImportList.find(Name);
880 assert(FunctionsToImportPerModule != ImportList.end());
Peter Collingbourned9445c42016-11-13 07:00:17 +0000881 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
882 if (!SrcModuleOrErr)
883 return SrcModuleOrErr.takeError();
884 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000885 assert(&DestModule.getContext() == &SrcModule->getContext() &&
886 "Context mismatch");
887
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000888 // If modules were created with lazy metadata loading, materialize it
889 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000890 if (Error Err = SrcModule->materializeMetadata())
891 return std::move(Err);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000892
Mehdi Amini01e32132016-03-26 05:40:34 +0000893 auto &ImportGUIDs = FunctionsToImportPerModule->second;
894 // Find the globals to import
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000895 SetVector<GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000896 for (Function &F : *SrcModule) {
897 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000898 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000899 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000900 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000901 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000902 << " " << F.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000903 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000904 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000905 if (Error Err = F.materialize())
906 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +0000907 if (EnableImportMetadata) {
908 // Add 'thinlto_src_module' metadata for statistics and debugging.
909 F.setMetadata(
910 "thinlto_src_module",
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000911 MDNode::get(DestModule.getContext(),
912 {MDString::get(DestModule.getContext(),
913 SrcModule->getSourceFileName())}));
Piotr Padlewski3b776122016-07-08 23:01:49 +0000914 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000915 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000916 }
917 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000918 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000919 if (!GV.hasName())
920 continue;
921 auto GUID = GV.getGUID();
922 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000923 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
924 << " " << GV.getName() << " from "
925 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000926 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000927 if (Error Err = GV.materialize())
928 return std::move(Err);
Eugene Leviant19e23872018-03-12 10:30:50 +0000929 ImportedGVCount += GlobalsToImport.insert(&GV);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000930 }
931 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000932 for (GlobalAlias &GA : SrcModule->aliases()) {
933 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000934 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000935 auto GUID = GA.getGUID();
Teresa Johnson81bbf742017-12-16 00:18:12 +0000936 auto Import = ImportGUIDs.count(GUID);
937 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000938 << " " << GA.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000939 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson81bbf742017-12-16 00:18:12 +0000940 if (Import) {
941 if (Error Err = GA.materialize())
942 return std::move(Err);
943 // Import alias as a copy of its aliasee.
944 GlobalObject *Base = GA.getBaseObject();
945 if (Error Err = Base->materialize())
946 return std::move(Err);
947 auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
948 DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID()
949 << " " << Base->getName() << " from "
950 << SrcModule->getSourceFileName() << "\n");
951 if (EnableImportMetadata) {
952 // Add 'thinlto_src_module' metadata for statistics and debugging.
953 Fn->setMetadata(
954 "thinlto_src_module",
955 MDNode::get(DestModule.getContext(),
956 {MDString::get(DestModule.getContext(),
957 SrcModule->getSourceFileName())}));
958 }
959 GlobalsToImport.insert(Fn);
960 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000961 }
962
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000963 // Upgrade debug info after we're done materializing all the globals and we
964 // have loaded all the required metadata!
965 UpgradeDebugInfo(*SrcModule);
966
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000967 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000968 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000969 return true;
970
Teresa Johnsond29478f2016-03-27 15:27:30 +0000971 if (PrintImports) {
972 for (const auto *GV : GlobalsToImport)
973 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
974 << " from " << SrcModule->getSourceFileName() << "\n";
975 }
976
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000977 if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
978 [](GlobalValue &, IRMover::ValueAdder) {},
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +0000979 /*IsPerformingImport=*/true))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000980 report_fatal_error("Function Import: link error");
981
Mehdi Amini01e32132016-03-26 05:40:34 +0000982 ImportedCount += GlobalsToImport.size();
Teresa Johnson6c475a72017-01-05 21:34:18 +0000983 NumImportedModules++;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000984 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000985
Eugene Leviant19e23872018-03-12 10:30:50 +0000986 NumImportedFunctions += (ImportedCount - ImportedGVCount);
987 NumImportedGlobalVars += ImportedGVCount;
Teresa Johnsond29478f2016-03-27 15:27:30 +0000988
Eugene Leviant19e23872018-03-12 10:30:50 +0000989 DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
990 << " functions for Module " << DestModule.getModuleIdentifier()
991 << "\n");
992 DEBUG(dbgs() << "Imported " << ImportedGVCount
993 << " global variables for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000994 << DestModule.getModuleIdentifier() << "\n");
995 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000996}
997
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000998static bool doImportingForModule(Module &M) {
999 if (SummaryFile.empty())
1000 report_fatal_error("error: -function-import requires -summary-file\n");
1001 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
1002 getModuleSummaryIndexForFile(SummaryFile);
1003 if (!IndexPtrOrErr) {
1004 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
1005 "Error loading file '" + SummaryFile + "': ");
1006 return false;
Teresa Johnson21241572016-07-18 21:22:24 +00001007 }
Peter Collingbourne598bd2a2016-12-21 00:50:12 +00001008 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
Teresa Johnson21241572016-07-18 21:22:24 +00001009
1010 // First step is collecting the import list.
1011 FunctionImporter::ImportMapTy ImportList;
Teresa Johnson81bbf742017-12-16 00:18:12 +00001012 // If requested, simply import all functions in the index. This is used
1013 // when testing distributed backend handling via the opt tool, when
1014 // we have distributed indexes containing exactly the summaries to import.
1015 if (ImportAllIndex)
1016 ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
1017 ImportList);
1018 else
1019 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
1020 ImportList);
Teresa Johnson21241572016-07-18 21:22:24 +00001021
Teresa Johnson4fef68c2016-11-14 19:21:41 +00001022 // Conservatively mark all internal values as promoted. This interface is
1023 // only used when doing importing via the function importing pass. The pass
1024 // is only enabled when testing importing via the 'opt' tool, which does
1025 // not do the ThinLink that would normally determine what values to promote.
1026 for (auto &I : *Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00001027 for (auto &S : I.second.SummaryList) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +00001028 if (GlobalValue::isLocalLinkage(S->linkage()))
1029 S->setLinkage(GlobalValue::ExternalLinkage);
1030 }
1031 }
1032
Teresa Johnson21241572016-07-18 21:22:24 +00001033 // Next we need to promote to global scope and rename any local values that
1034 // are potentially exported to other modules.
1035 if (renameModuleForThinLTO(M, *Index, nullptr)) {
1036 errs() << "Error renaming module\n";
1037 return false;
1038 }
1039
1040 // Perform the import now.
1041 auto ModuleLoader = [&M](StringRef Identifier) {
1042 return loadFile(Identifier, M.getContext());
1043 };
1044 FunctionImporter Importer(*Index, ModuleLoader);
Peter Collingbourne37e24592017-02-02 18:42:25 +00001045 Expected<bool> Result = Importer.importFunctions(M, ImportList);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00001046
1047 // FIXME: Probably need to propagate Errors through the pass manager.
1048 if (!Result) {
1049 logAllUnhandledErrors(Result.takeError(), errs(),
1050 "Error importing module: ");
1051 return false;
1052 }
1053
1054 return *Result;
Teresa Johnson21241572016-07-18 21:22:24 +00001055}
1056
Benjamin Kramerfe2b5412015-12-24 10:03:35 +00001057namespace {
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001058
Mehdi Amini42418ab2015-11-24 06:07:49 +00001059/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +00001060class FunctionImportLegacyPass : public ModulePass {
Mehdi Amini42418ab2015-11-24 06:07:49 +00001061public:
1062 /// Pass identification, replacement for typeid
1063 static char ID;
1064
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001065 explicit FunctionImportLegacyPass() : ModulePass(ID) {}
1066
Teresa Johnson5fcbdb72015-12-07 19:21:11 +00001067 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +00001068 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +00001069
Mehdi Amini42418ab2015-11-24 06:07:49 +00001070 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001071 if (skipModule(M))
1072 return false;
1073
Peter Collingbourne598bd2a2016-12-21 00:50:12 +00001074 return doImportingForModule(M);
Mehdi Amini42418ab2015-11-24 06:07:49 +00001075 }
1076};
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001077
1078} // end anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +00001079
Teresa Johnson21241572016-07-18 21:22:24 +00001080PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001081 ModuleAnalysisManager &AM) {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +00001082 if (!doImportingForModule(M))
Teresa Johnson21241572016-07-18 21:22:24 +00001083 return PreservedAnalyses::all();
1084
1085 return PreservedAnalyses::none();
1086}
1087
1088char FunctionImportLegacyPass::ID = 0;
1089INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
1090 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +00001091
1092namespace llvm {
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001093
Peter Collingbourne598bd2a2016-12-21 00:50:12 +00001094Pass *createFunctionImportPass() {
1095 return new FunctionImportLegacyPass();
Teresa Johnson5fcbdb72015-12-07 19:21:11 +00001096}
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001097
1098} // end namespace llvm