blob: f759474e40f9d14543d259493ff64a8597910096 [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
Mehdi Amini40641742016-02-10 23:31:45 +000074static cl::opt<float>
75 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
76 cl::Hidden, cl::value_desc("x"),
77 cl::desc("As we import functions, multiply the "
78 "`import-instr-limit` threshold by this factor "
79 "before processing newly imported functions"));
Piotr Padlewskiba72b952016-09-29 17:32:07 +000080
Piotr Padlewskid2869472016-09-30 03:01:17 +000081static cl::opt<float> ImportHotInstrFactor(
82 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
83 cl::value_desc("x"),
84 cl::desc("As we import functions called from hot callsite, multiply the "
85 "`import-instr-limit` threshold by this factor "
86 "before processing newly imported functions"));
87
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000088static cl::opt<float> ImportHotMultiplier(
Dehao Chen8260d662017-07-28 01:02:34 +000089 "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
Piotr Padlewskiba72b952016-09-29 17:32:07 +000090 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
91
Dehao Chen64c46572017-07-07 21:01:00 +000092static cl::opt<float> ImportCriticalMultiplier(
93 "import-critical-multiplier", cl::init(100.0), cl::Hidden,
94 cl::value_desc("x"),
95 cl::desc(
96 "Multiply the `import-instr-limit` threshold for critical callsites"));
97
Piotr Padlewskiba72b952016-09-29 17:32:07 +000098// FIXME: This multiplier was not really tuned up.
99static cl::opt<float> ImportColdMultiplier(
100 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
101 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
Mehdi Amini40641742016-02-10 23:31:45 +0000102
Teresa Johnsond29478f2016-03-27 15:27:30 +0000103static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
104 cl::desc("Print imported functions"));
105
Teresa Johnson6c475a72017-01-05 21:34:18 +0000106static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
107 cl::desc("Compute dead symbols"));
108
Piotr Padlewski3b776122016-07-08 23:01:49 +0000109static cl::opt<bool> EnableImportMetadata(
110 "enable-import-metadata", cl::init(
111#if !defined(NDEBUG)
112 true /*Enabled with asserts.*/
113#else
114 false
115#endif
116 ),
117 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
118
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000119/// Summary file to use for function importing when using -function-import from
120/// the command line.
121static cl::opt<std::string>
122 SummaryFile("summary-file",
123 cl::desc("The summary file to use for function importing."));
124
Teresa Johnson81bbf742017-12-16 00:18:12 +0000125/// Used when testing importing from distributed indexes via opt
126// -function-import.
127static cl::opt<bool>
128 ImportAllIndex("import-all-index",
129 cl::desc("Import all external functions in index."));
130
Mehdi Amini42418ab2015-11-24 06:07:49 +0000131// Load lazily a module from \p FileName in \p Context.
132static std::unique_ptr<Module> loadFile(const std::string &FileName,
133 LLVMContext &Context) {
134 SMDiagnostic Err;
135 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000136 // Metadata isn't loaded until functions are imported, to minimize
137 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +0000138 std::unique_ptr<Module> Result =
139 getLazyIRFileModule(FileName, Err, Context,
140 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000141 if (!Result) {
142 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +0000143 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000144 }
145
Mehdi Amini42418ab2015-11-24 06:07:49 +0000146 return Result;
147}
148
Mehdi Amini01e32132016-03-26 05:40:34 +0000149/// Given a list of possible callee implementation for a call site, select one
150/// that fits the \p Threshold.
151///
152/// FIXME: select "best" instead of first that fits. But what is "best"?
153/// - The smallest: more likely to be inlined.
154/// - The one with the least outgoing edges (already well optimized).
155/// - One from a module already being imported from in order to reduce the
156/// number of source modules parsed/linked.
157/// - One that has PGO data attached.
158/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000159static const GlobalValueSummary *
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000160selectCallee(const ModuleSummaryIndex &Index,
Peter Collingbourne9667b912017-05-04 18:03:25 +0000161 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
Teresa Johnson83aaf352017-01-12 22:04:45 +0000162 unsigned Threshold, StringRef CallerModulePath) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000163 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000164 CalleeSummaryList,
165 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
166 auto *GVSummary = SummaryPtr.get();
George Rimareaf51722018-01-29 08:03:30 +0000167 if (!Index.isGlobalValueLive(GVSummary))
168 return false;
169
Teresa Johnson73305f82017-08-19 18:04:25 +0000170 // For SamplePGO, in computeImportForFunction the OriginalId
171 // may have been used to locate the callee summary list (See
172 // comment there).
173 // The mapping from OriginalId to GUID may return a GUID
174 // that corresponds to a static variable. Filter it out here.
175 // This can happen when
176 // 1) There is a call to a library function which is not defined
177 // in the index.
178 // 2) There is a static variable with the OriginalGUID identical
179 // to the GUID of the library function in 1);
180 // When this happens, the logic for SamplePGO kicks in and
181 // the static variable in 2) will be found, which needs to be
182 // filtered out.
183 if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
184 return false;
Rafael Espindolaf329be82016-05-11 01:26:06 +0000185 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000186 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000187 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000188
Teresa Johnson81bbf742017-12-16 00:18:12 +0000189 auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000190
Teresa Johnson83aaf352017-01-12 22:04:45 +0000191 // If this is a local function, make sure we import the copy
192 // in the caller's module. The only time a local function can
193 // share an entry in the index is if there is a local with the same name
194 // in another module that had the same source file name (in a different
195 // directory), where each was compiled in their own directory so there
196 // was not distinguishing path.
197 // However, do the import from another module if there is only one
198 // entry in the list - in that case this must be a reference due
199 // to indirect call profile data, since a function pointer can point to
200 // a local in another module.
201 if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
202 CalleeSummaryList.size() > 1 &&
203 Summary->modulePath() != CallerModulePath)
204 return false;
205
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000206 if (Summary->instCount() > Threshold)
207 return false;
208
Teresa Johnson519465b2017-01-05 14:32:16 +0000209 if (Summary->notEligibleToImport())
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000210 return false;
211
Mehdi Amini01e32132016-03-26 05:40:34 +0000212 return true;
213 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000214 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000215 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000216
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000217 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000218}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000219
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000220namespace {
221
Teresa Johnson475b51a2016-12-15 20:48:19 +0000222using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
223 GlobalValue::GUID>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000224
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000225} // anonymous namespace
226
Teresa Johnson19580832017-09-13 15:16:38 +0000227static ValueInfo
228updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) {
229 if (!VI.getSummaryList().empty())
230 return VI;
231 // For SamplePGO, the indirect call targets for local functions will
232 // have its original name annotated in profile. We try to find the
233 // corresponding PGOFuncName as the GUID.
234 // FIXME: Consider updating the edges in the graph after building
235 // it, rather than needing to perform this mapping on each walk.
236 auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
237 if (GUID == 0)
Eugene Leviant28d8a492018-01-22 13:35:40 +0000238 return ValueInfo();
Teresa Johnson19580832017-09-13 15:16:38 +0000239 return Index.getValueInfo(GUID);
240}
241
Eugene Leviant19e23872018-03-12 10:30:50 +0000242static void computeImportForReferencedGlobals(
243 const FunctionSummary &Summary, const GVSummaryMapTy &DefinedGVSummaries,
244 FunctionImporter::ImportMapTy &ImportList,
245 StringMap<FunctionImporter::ExportSetTy> *ExportLists) {
246 for (auto &VI : Summary.refs()) {
247 if (DefinedGVSummaries.count(VI.getGUID())) {
248 DEBUG(dbgs() << "Ref ignored! Target already in destination module.\n");
249 continue;
250 }
251
252 DEBUG(dbgs() << " ref -> " << VI.getGUID() << "\n");
253
254 for (auto &RefSummary : VI.getSummaryList())
255 if (RefSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind &&
256 // Don't try to import regular LTO summaries added to dummy module.
257 !RefSummary->modulePath().empty() &&
258 !GlobalValue::isInterposableLinkage(RefSummary->linkage()) &&
259 RefSummary->refs().empty()) {
260 ImportList[RefSummary->modulePath()][VI.getGUID()] = 1;
261 if (ExportLists)
262 (*ExportLists)[RefSummary->modulePath()].insert(VI.getGUID());
263 break;
264 }
265 }
266}
267
Mehdi Amini01e32132016-03-26 05:40:34 +0000268/// Compute the list of functions to import for a given caller. Mark these
269/// imported functions and the symbols they reference in their source module as
270/// exported from their source module.
271static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000272 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000273 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000274 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000275 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000276 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Eugene Leviant19e23872018-03-12 10:30:50 +0000277 computeImportForReferencedGlobals(Summary, DefinedGVSummaries, ImportList,
278 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000279 for (auto &Edge : Summary.calls()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000280 ValueInfo VI = Edge.first;
281 DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold
282 << "\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000283
Teresa Johnson19580832017-09-13 15:16:38 +0000284 VI = updateValueInfoForIndirectCalls(Index, VI);
285 if (!VI)
286 continue;
Dehao Chen4a435e02017-03-14 17:33:01 +0000287
Peter Collingbourne9667b912017-05-04 18:03:25 +0000288 if (DefinedGVSummaries.count(VI.getGUID())) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000289 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
290 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000291 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000292
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000293 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
294 if (Hotness == CalleeInfo::HotnessType::Hot)
295 return ImportHotMultiplier;
296 if (Hotness == CalleeInfo::HotnessType::Cold)
297 return ImportColdMultiplier;
Dehao Chen64c46572017-07-07 21:01:00 +0000298 if (Hotness == CalleeInfo::HotnessType::Critical)
299 return ImportCriticalMultiplier;
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000300 return 1.0;
301 };
302
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000303 const auto NewThreshold =
Easwaran Ramanc73cec82018-01-25 19:27:17 +0000304 Threshold * GetBonusMultiplier(Edge.second.getHotness());
Piotr Padlewskid2869472016-09-30 03:01:17 +0000305
Peter Collingbourne9667b912017-05-04 18:03:25 +0000306 auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
307 Summary.modulePath());
Mehdi Amini01e32132016-03-26 05:40:34 +0000308 if (!CalleeSummary) {
309 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
310 continue;
311 }
David Blaikie2f0cc472017-07-27 15:09:06 +0000312
313 // "Resolve" the summary
Teresa Johnson81bbf742017-12-16 00:18:12 +0000314 const auto *ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary->getBaseObject());
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000315
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000316 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000317 "selectCallee() didn't honor the threshold");
318
Piotr Padlewskid2869472016-09-30 03:01:17 +0000319 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
320 // Adjust the threshold for next level of imported functions.
321 // The threshold is different for hot callsites because we can then
322 // inline chains of hot calls.
323 if (IsHotCallsite)
324 return Threshold * ImportHotInstrFactor;
325 return Threshold * ImportInstrFactor;
326 };
327
Easwaran Ramanc73cec82018-01-25 19:27:17 +0000328 bool IsHotCallsite =
329 Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000330 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
331
332 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000333 auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()];
Teresa Johnson1b859a22016-12-15 18:21:01 +0000334 /// Since the traversal of the call graph is DFS, we can revisit a function
335 /// a second time with a higher threshold. In this case, it is added back to
336 /// the worklist with the new threshold.
337 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
338 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
339 << ProcessedThreshold << "\n");
340 continue;
341 }
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000342 bool PreviouslyImported = ProcessedThreshold != 0;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000343 // Mark this function as imported in this module, with the current Threshold
344 ProcessedThreshold = AdjThreshold;
345
346 // Make exports in the source module.
347 if (ExportLists) {
348 auto &ExportList = (*ExportLists)[ExportModulePath];
Peter Collingbourne9667b912017-05-04 18:03:25 +0000349 ExportList.insert(VI.getGUID());
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000350 if (!PreviouslyImported) {
351 // This is the first time this function was exported from its source
352 // module, so mark all functions and globals it references as exported
353 // to the outside if they are defined in the same source module.
Teresa Johnsonedddca22016-12-16 04:11:51 +0000354 // For efficiency, we unconditionally add all the referenced GUIDs
355 // to the ExportList for this module, and will prune out any not
356 // defined in the module later in a single pass.
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000357 for (auto &Edge : ResolvedCalleeSummary->calls()) {
358 auto CalleeGUID = Edge.first.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000359 ExportList.insert(CalleeGUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000360 }
361 for (auto &Ref : ResolvedCalleeSummary->refs()) {
362 auto GUID = Ref.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000363 ExportList.insert(GUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000364 }
Teresa Johnson1b859a22016-12-15 18:21:01 +0000365 }
366 }
Piotr Padlewskid2869472016-09-30 03:01:17 +0000367
Mehdi Amini01e32132016-03-26 05:40:34 +0000368 // Insert the newly imported function to the worklist.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000369 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
Teresa Johnsond450da32015-11-24 21:15:19 +0000370 }
371}
372
Mehdi Amini01e32132016-03-26 05:40:34 +0000373/// Given the list of globals defined in a module, compute the list of imports
374/// as well as the list of "exports", i.e. the list of symbols referenced from
375/// another module (that may require promotion).
376static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000377 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000378 FunctionImporter::ImportMapTy &ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000379 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000380 // Worklist contains the list of function imported in this module, for which
381 // we will analyse the callees and may import further down the callgraph.
382 SmallVector<EdgeInfo, 128> Worklist;
383
384 // Populate the worklist with the import for the functions in the current
385 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000386 for (auto &GVSummary : DefinedGVSummaries) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000387 if (!Index.isGlobalValueLive(GVSummary.second)) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000388 DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
389 continue;
390 }
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000391 auto *FuncSummary =
392 dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000393 if (!FuncSummary)
394 // Skip import for global variables
395 continue;
Xinliang David Li24524f32017-08-11 17:49:20 +0000396 DEBUG(dbgs() << "Initialize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000397 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000398 DefinedGVSummaries, Worklist, ImportList,
Mehdi Amini01e32132016-03-26 05:40:34 +0000399 ExportLists);
400 }
401
Piotr Padlewskid2869472016-09-30 03:01:17 +0000402 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000403 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000404 auto FuncInfo = Worklist.pop_back_val();
Teresa Johnson475b51a2016-12-15 20:48:19 +0000405 auto *Summary = std::get<0>(FuncInfo);
406 auto Threshold = std::get<1>(FuncInfo);
407 auto GUID = std::get<2>(FuncInfo);
408
409 // Check if we later added this summary with a higher threshold.
410 // If so, skip this entry.
411 auto ExportModulePath = Summary->modulePath();
412 auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
413 if (LatestProcessedThreshold > Threshold)
414 continue;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000415
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000416 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000417 Worklist, ImportList, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000418 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000419}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000420
Eugene Leviant19e23872018-03-12 10:30:50 +0000421#ifndef NDEBUG
422static bool isGlobalVarSummary(const ModuleSummaryIndex &Index,
423 GlobalValue::GUID G) {
424 if (const auto &VI = Index.getValueInfo(G)) {
425 auto SL = VI.getSummaryList();
426 if (!SL.empty())
427 return SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
428 }
429 return false;
430}
431
432static GlobalValue::GUID getGUID(GlobalValue::GUID G) { return G; }
433
434static GlobalValue::GUID
435getGUID(const std::pair<const GlobalValue::GUID, unsigned> &P) {
436 return P.first;
437}
438
439template <class T>
440unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index, T &Cont) {
441 unsigned NumGVS = 0;
442 for (auto &V : Cont)
443 if (isGlobalVarSummary(Index, getGUID(V)))
444 ++NumGVS;
445 return NumGVS;
446}
447#endif
448
Teresa Johnsonc86af332016-04-12 21:13:11 +0000449/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000450void llvm::ComputeCrossModuleImport(
451 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000452 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000453 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000454 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000455 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000456 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000457 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000458 DEBUG(dbgs() << "Computing import for Module '"
459 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000460 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000461 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000462 }
463
Teresa Johnsonedddca22016-12-16 04:11:51 +0000464 // When computing imports we added all GUIDs referenced by anything
465 // imported from the module to its ExportList. Now we prune each ExportList
466 // of any not defined in that module. This is more efficient than checking
467 // while computing imports because some of the summary lists may be long
468 // due to linkonce (comdat) copies.
469 for (auto &ELI : ExportLists) {
470 const auto &DefinedGVSummaries =
471 ModuleToDefinedGVSummaries.lookup(ELI.first());
472 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
473 if (!DefinedGVSummaries.count(*EI))
474 EI = ELI.second.erase(EI);
475 else
476 ++EI;
477 }
478 }
479
Mehdi Amini01e32132016-03-26 05:40:34 +0000480#ifndef NDEBUG
481 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
482 << " modules:\n");
483 for (auto &ModuleImports : ImportLists) {
484 auto ModName = ModuleImports.first();
485 auto &Exports = ExportLists[ModName];
Eugene Leviant19e23872018-03-12 10:30:50 +0000486 unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
487 DEBUG(dbgs() << "* Module " << ModName << " exports "
488 << Exports.size() - NumGVS << " functions and " << NumGVS
489 << " vars. Imports from "
490 << ModuleImports.second.size() << " modules.\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000491 for (auto &Src : ModuleImports.second) {
492 auto SrcModName = Src.first();
Eugene Leviant19e23872018-03-12 10:30:50 +0000493 unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
494 DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
495 << " functions imported from " << SrcModName << "\n");
496 DEBUG(dbgs() << " - " << NumGVSPerMod << " global vars imported from "
Mehdi Amini01e32132016-03-26 05:40:34 +0000497 << SrcModName << "\n");
498 }
499 }
500#endif
501}
502
Teresa Johnson81bbf742017-12-16 00:18:12 +0000503#ifndef NDEBUG
Eugene Leviant19e23872018-03-12 10:30:50 +0000504static void dumpImportListForModule(const ModuleSummaryIndex &Index,
505 StringRef ModulePath,
Teresa Johnson81bbf742017-12-16 00:18:12 +0000506 FunctionImporter::ImportMapTy &ImportList) {
507 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
508 << ImportList.size() << " modules.\n");
509 for (auto &Src : ImportList) {
510 auto SrcModName = Src.first();
Eugene Leviant19e23872018-03-12 10:30:50 +0000511 unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
512 DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
513 << " functions imported from " << SrcModName << "\n");
514 DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from "
Teresa Johnson81bbf742017-12-16 00:18:12 +0000515 << SrcModName << "\n");
516 }
Teresa Johnson81bbf742017-12-16 00:18:12 +0000517}
Teresa Johnson69b2de82017-12-16 00:29:31 +0000518#endif
Teresa Johnson81bbf742017-12-16 00:18:12 +0000519
Teresa Johnsonc86af332016-04-12 21:13:11 +0000520/// Compute all the imports for the given module in the Index.
521void llvm::ComputeCrossModuleImportForModule(
522 StringRef ModulePath, const ModuleSummaryIndex &Index,
523 FunctionImporter::ImportMapTy &ImportList) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000524 // Collect the list of functions this module defines.
525 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000526 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000527 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000528
529 // Compute the import list for this module.
530 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000531 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000532
533#ifndef NDEBUG
Eugene Leviant19e23872018-03-12 10:30:50 +0000534 dumpImportListForModule(Index, ModulePath, ImportList);
Teresa Johnson81bbf742017-12-16 00:18:12 +0000535#endif
536}
537
538// Mark all external summaries in Index for import into the given module.
539// Used for distributed builds using a distributed index.
540void llvm::ComputeCrossModuleImportForModuleFromIndex(
541 StringRef ModulePath, const ModuleSummaryIndex &Index,
542 FunctionImporter::ImportMapTy &ImportList) {
543 for (auto &GlobalList : Index) {
544 // Ignore entries for undefined references.
545 if (GlobalList.second.SummaryList.empty())
546 continue;
547
548 auto GUID = GlobalList.first;
549 assert(GlobalList.second.SummaryList.size() == 1 &&
550 "Expected individual combined index to have one summary per GUID");
551 auto &Summary = GlobalList.second.SummaryList[0];
552 // Skip the summaries for the importing module. These are included to
553 // e.g. record required linkage changes.
554 if (Summary->modulePath() == ModulePath)
555 continue;
556 // Doesn't matter what value we plug in to the map, just needs an entry
557 // to provoke importing by thinBackend.
558 ImportList[Summary->modulePath()][GUID] = 1;
Teresa Johnsonc86af332016-04-12 21:13:11 +0000559 }
Teresa Johnson81bbf742017-12-16 00:18:12 +0000560#ifndef NDEBUG
Eugene Leviant19e23872018-03-12 10:30:50 +0000561 dumpImportListForModule(Index, ModulePath, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000562#endif
563}
564
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000565void llvm::computeDeadSymbols(
566 ModuleSummaryIndex &Index,
George Rimareaf51722018-01-29 08:03:30 +0000567 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
568 function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000569 assert(!Index.withGlobalValueDeadStripping());
Teresa Johnson6c475a72017-01-05 21:34:18 +0000570 if (!ComputeDead)
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000571 return;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000572 if (GUIDPreservedSymbols.empty())
573 // Don't do anything when nothing is live, this is friendly with tests.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000574 return;
575 unsigned LiveSymbols = 0;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000576 SmallVector<ValueInfo, 128> Worklist;
577 Worklist.reserve(GUIDPreservedSymbols.size() * 2);
578 for (auto GUID : GUIDPreservedSymbols) {
579 ValueInfo VI = Index.getValueInfo(GUID);
580 if (!VI)
581 continue;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000582 for (auto &S : VI.getSummaryList())
583 S->setLive(true);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000584 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000585
Teresa Johnson6c475a72017-01-05 21:34:18 +0000586 // Add values flagged in the index as live roots to the worklist.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000587 for (const auto &Entry : Index)
588 for (auto &S : Entry.second.SummaryList)
589 if (S->isLive()) {
590 DEBUG(dbgs() << "Live root: " << Entry.first << "\n");
Eugene Leviant28d8a492018-01-22 13:35:40 +0000591 Worklist.push_back(ValueInfo(/*IsAnalysis=*/false, &Entry));
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000592 ++LiveSymbols;
593 break;
594 }
595
596 // Make value live and add it to the worklist if it was not live before.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000597 auto visit = [&](ValueInfo VI) {
Teresa Johnson19580832017-09-13 15:16:38 +0000598 // FIXME: If we knew which edges were created for indirect call profiles,
599 // we could skip them here. Any that are live should be reached via
600 // other edges, e.g. reference edges. Otherwise, using a profile collected
601 // on a slightly different binary might provoke preserving, importing
602 // and ultimately promoting calls to functions not linked into this
603 // binary, which increases the binary size unnecessarily. Note that
604 // if this code changes, the importer needs to change so that edges
605 // to functions marked dead are skipped.
606 VI = updateValueInfoForIndirectCalls(Index, VI);
607 if (!VI)
608 return;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000609 for (auto &S : VI.getSummaryList())
Teresa Johnsonf6251182017-09-20 17:09:47 +0000610 if (S->isLive())
611 return;
George Rimareaf51722018-01-29 08:03:30 +0000612
Eric Christopher3caa0fd2018-03-09 01:25:18 +0000613 // We do not keep live symbols that are known to be non-prevailing.
614 if (isPrevailing(VI.getGUID()) == PrevailingType::No)
615 return;
George Rimareaf51722018-01-29 08:03:30 +0000616
Teresa Johnsonf6251182017-09-20 17:09:47 +0000617 for (auto &S : VI.getSummaryList())
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000618 S->setLive(true);
619 ++LiveSymbols;
620 Worklist.push_back(VI);
621 };
Teresa Johnson6c475a72017-01-05 21:34:18 +0000622
623 while (!Worklist.empty()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000624 auto VI = Worklist.pop_back_val();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000625 for (auto &Summary : VI.getSummaryList()) {
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000626 GlobalValueSummary *Base = Summary->getBaseObject();
George Rimareaf51722018-01-29 08:03:30 +0000627 // Set base value live in case it is an alias.
628 Base->setLive(true);
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000629 for (auto Ref : Base->refs())
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000630 visit(Ref);
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000631 if (auto *FS = dyn_cast<FunctionSummary>(Base))
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000632 for (auto Call : FS->calls())
633 visit(Call.first);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000634 }
635 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000636 Index.setWithGlobalValueDeadStripping();
637
638 unsigned DeadSymbols = Index.size() - LiveSymbols;
639 DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
640 << " symbols Dead \n");
641 NumDeadSymbols += DeadSymbols;
642 NumLiveSymbols += LiveSymbols;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000643}
644
Teresa Johnson84174c32016-05-10 13:48:23 +0000645/// Compute the set of summaries needed for a ThinLTO backend compilation of
646/// \p ModulePath.
647void llvm::gatherImportedSummariesForModule(
648 StringRef ModulePath,
649 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000650 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000651 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
652 // Include all summaries from the importing module.
653 ModuleToSummariesForIndex[ModulePath] =
654 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000655 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000656 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000657 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
658 const auto &DefinedGVSummaries =
659 ModuleToDefinedGVSummaries.lookup(ILI.first());
660 for (auto &GI : ILI.second) {
661 const auto &DS = DefinedGVSummaries.find(GI.first);
662 assert(DS != DefinedGVSummaries.end() &&
663 "Expected a defined summary for imported global value");
664 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000665 }
666 }
667}
668
Teresa Johnson8570fe42016-05-10 15:54:09 +0000669/// Emit the files \p ModulePath will import from into \p OutputFilename.
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000670std::error_code
671llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
672 const FunctionImporter::ImportMapTy &ModuleImports) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000673 std::error_code EC;
674 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
675 if (EC)
676 return EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000677 for (auto &ILI : ModuleImports)
678 ImportsOS << ILI.first() << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000679 return std::error_code();
680}
681
Teresa Johnson5a95c472018-02-05 15:44:27 +0000682bool llvm::convertToDeclaration(GlobalValue &GV) {
George Rimareaf51722018-01-29 08:03:30 +0000683 DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n");
684 if (Function *F = dyn_cast<Function>(&GV)) {
685 F->deleteBody();
686 F->clearMetadata();
Peter Collingbourne78736692018-01-31 02:51:03 +0000687 F->setComdat(nullptr);
George Rimareaf51722018-01-29 08:03:30 +0000688 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
689 V->setInitializer(nullptr);
690 V->setLinkage(GlobalValue::ExternalLinkage);
691 V->clearMetadata();
Peter Collingbourne78736692018-01-31 02:51:03 +0000692 V->setComdat(nullptr);
Teresa Johnson5a95c472018-02-05 15:44:27 +0000693 } else {
694 GlobalValue *NewGV;
695 if (GV.getValueType()->isFunctionTy())
696 NewGV =
697 Function::Create(cast<FunctionType>(GV.getValueType()),
698 GlobalValue::ExternalLinkage, "", GV.getParent());
699 else
700 NewGV =
701 new GlobalVariable(*GV.getParent(), GV.getValueType(),
702 /*isConstant*/ false, GlobalValue::ExternalLinkage,
703 /*init*/ nullptr, "",
704 /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
705 GV.getType()->getAddressSpace());
706 NewGV->takeName(&GV);
707 GV.replaceAllUsesWith(NewGV);
708 return false;
709 }
710 return true;
George Rimareaf51722018-01-29 08:03:30 +0000711}
712
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000713/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
714void llvm::thinLTOResolveWeakForLinkerModule(
715 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
716 auto updateLinkage = [&](GlobalValue &GV) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000717 // See if the global summary analysis computed a new resolved linkage.
718 const auto &GS = DefinedGlobals.find(GV.getGUID());
719 if (GS == DefinedGlobals.end())
720 return;
721 auto NewLinkage = GS->second->linkage();
722 if (NewLinkage == GV.getLinkage())
723 return;
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000724
725 // Switch the linkage to weakany if asked for, e.g. we do this for
726 // linker redefined symbols (via --wrap or --defsym).
Davide Italianof4891d22017-07-06 20:04:20 +0000727 // We record that the visibility should be changed here in `addThinLTO`
728 // as we need access to the resolution vectors for each input file in
729 // order to find which symbols have been redefined.
730 // We may consider reorganizing this code and moving the linkage recording
731 // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex.
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000732 if (NewLinkage == GlobalValue::WeakAnyLinkage) {
733 GV.setLinkage(NewLinkage);
734 return;
735 }
736
737 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
738 return;
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000739 // Check for a non-prevailing def that has interposable linkage
740 // (e.g. non-odr weak or linkonce). In that case we can't simply
741 // convert to available_externally, since it would lose the
742 // interposable property and possibly get inlined. Simply drop
743 // the definition in that case.
744 if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
Teresa Johnson5a95c472018-02-05 15:44:27 +0000745 GlobalValue::isInterposableLinkage(GV.getLinkage())) {
746 if (!convertToDeclaration(GV))
747 // FIXME: Change this to collect replaced GVs and later erase
748 // them from the parent module once thinLTOResolveWeakForLinkerGUID is
749 // changed to enable this for aliases.
750 llvm_unreachable("Expected GV to be converted");
751 } else {
Steven Wu33ba93c2018-02-09 18:34:08 +0000752 // If the original symbols has global unnamed addr and linkonce_odr linkage,
753 // it should be an auto hide symbol. Add hidden visibility to the symbol to
754 // preserve the property.
755 if (GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr() &&
756 NewLinkage == GlobalValue::WeakODRLinkage)
757 GV.setVisibility(GlobalValue::HiddenVisibility);
758
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000759 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
760 << GV.getLinkage() << " to " << NewLinkage << "\n");
761 GV.setLinkage(NewLinkage);
762 }
763 // Remove declarations from comdats, including available_externally
Teresa Johnson6107a412016-08-15 21:00:04 +0000764 // as this is a declaration for the linker, and will be dropped eventually.
765 // It is illegal for comdats to contain declarations.
766 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000767 if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
Teresa Johnson6107a412016-08-15 21:00:04 +0000768 GO->setComdat(nullptr);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000769 };
770
771 // Process functions and global now
772 for (auto &GV : TheModule)
773 updateLinkage(GV);
774 for (auto &GV : TheModule.globals())
775 updateLinkage(GV);
776 for (auto &GV : TheModule.aliases())
777 updateLinkage(GV);
778}
779
780/// Run internalization on \p TheModule based on symmary analysis.
781void llvm::thinLTOInternalizeModule(Module &TheModule,
782 const GVSummaryMapTy &DefinedGlobals) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000783 // Declare a callback for the internalize pass that will ask for every
784 // candidate GlobalValue if it can be internalized or not.
785 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000786 // Lookup the linkage recorded in the summaries during global analysis.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000787 auto GS = DefinedGlobals.find(GV.getGUID());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000788 if (GS == DefinedGlobals.end()) {
789 // Must have been promoted (possibly conservatively). Find original
790 // name so that we can access the correct summary and see if it can
791 // be internalized again.
792 // FIXME: Eventually we should control promotion instead of promoting
793 // and internalizing again.
794 StringRef OrigName =
795 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
796 std::string OrigId = GlobalValue::getGlobalIdentifier(
797 OrigName, GlobalValue::InternalLinkage,
798 TheModule.getSourceFileName());
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000799 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000800 if (GS == DefinedGlobals.end()) {
801 // Also check the original non-promoted non-globalized name. In some
802 // cases a preempted weak value is linked in as a local copy because
803 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
804 // In that case, since it was originally not a local value, it was
805 // recorded in the index using the original name.
806 // FIXME: This may not be needed once PR27866 is fixed.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000807 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000808 assert(GS != DefinedGlobals.end());
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000809 }
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000810 }
811 return !GlobalValue::isLocalLinkage(GS->second->linkage());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000812 };
813
814 // FIXME: See if we can just internalize directly here via linkage changes
815 // based on the index, rather than invoking internalizeModule.
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000816 internalizeModule(TheModule, MustPreserveGV);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000817}
818
Teresa Johnson81bbf742017-12-16 00:18:12 +0000819/// Make alias a clone of its aliasee.
820static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
821 Function *Fn = cast<Function>(GA->getBaseObject());
822
823 ValueToValueMapTy VMap;
824 Function *NewFn = CloneFunction(Fn, VMap);
825 // Clone should use the original alias's linkage and name, and we ensure
826 // all uses of alias instead use the new clone (casted if necessary).
827 NewFn->setLinkage(GA->getLinkage());
828 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
829 NewFn->takeName(GA);
830 return NewFn;
831}
832
Mehdi Aminic8c55172015-12-03 02:37:33 +0000833// Automatically import functions in Module \p DestModule based on the summaries
834// index.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000835Expected<bool> FunctionImporter::importFunctions(
Adrian Prantl66043792017-05-19 23:32:21 +0000836 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000837 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000838 << DestModule.getModuleIdentifier() << "\n");
Eugene Leviant19e23872018-03-12 10:30:50 +0000839 unsigned ImportedCount = 0, ImportedGVCount = 0;
Mehdi Aminic8c55172015-12-03 02:37:33 +0000840
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000841 IRMover Mover(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000842 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000843 std::set<StringRef> ModuleNameOrderedList;
844 for (auto &FunctionsToImportPerModule : ImportList) {
845 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
846 }
847 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000848 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000849 const auto &FunctionsToImportPerModule = ImportList.find(Name);
850 assert(FunctionsToImportPerModule != ImportList.end());
Peter Collingbourned9445c42016-11-13 07:00:17 +0000851 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
852 if (!SrcModuleOrErr)
853 return SrcModuleOrErr.takeError();
854 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000855 assert(&DestModule.getContext() == &SrcModule->getContext() &&
856 "Context mismatch");
857
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000858 // If modules were created with lazy metadata loading, materialize it
859 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000860 if (Error Err = SrcModule->materializeMetadata())
861 return std::move(Err);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000862
Mehdi Amini01e32132016-03-26 05:40:34 +0000863 auto &ImportGUIDs = FunctionsToImportPerModule->second;
864 // Find the globals to import
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000865 SetVector<GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000866 for (Function &F : *SrcModule) {
867 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000868 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000869 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000870 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000871 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000872 << " " << F.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000873 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000874 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000875 if (Error Err = F.materialize())
876 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +0000877 if (EnableImportMetadata) {
878 // Add 'thinlto_src_module' metadata for statistics and debugging.
879 F.setMetadata(
880 "thinlto_src_module",
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000881 MDNode::get(DestModule.getContext(),
882 {MDString::get(DestModule.getContext(),
883 SrcModule->getSourceFileName())}));
Piotr Padlewski3b776122016-07-08 23:01:49 +0000884 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000885 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000886 }
887 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000888 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000889 if (!GV.hasName())
890 continue;
891 auto GUID = GV.getGUID();
892 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000893 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
894 << " " << GV.getName() << " from "
895 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000896 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000897 if (Error Err = GV.materialize())
898 return std::move(Err);
Eugene Leviant19e23872018-03-12 10:30:50 +0000899 ImportedGVCount += GlobalsToImport.insert(&GV);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000900 }
901 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000902 for (GlobalAlias &GA : SrcModule->aliases()) {
903 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000904 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000905 auto GUID = GA.getGUID();
Teresa Johnson81bbf742017-12-16 00:18:12 +0000906 auto Import = ImportGUIDs.count(GUID);
907 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000908 << " " << GA.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000909 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson81bbf742017-12-16 00:18:12 +0000910 if (Import) {
911 if (Error Err = GA.materialize())
912 return std::move(Err);
913 // Import alias as a copy of its aliasee.
914 GlobalObject *Base = GA.getBaseObject();
915 if (Error Err = Base->materialize())
916 return std::move(Err);
917 auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
918 DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID()
919 << " " << Base->getName() << " from "
920 << SrcModule->getSourceFileName() << "\n");
921 if (EnableImportMetadata) {
922 // Add 'thinlto_src_module' metadata for statistics and debugging.
923 Fn->setMetadata(
924 "thinlto_src_module",
925 MDNode::get(DestModule.getContext(),
926 {MDString::get(DestModule.getContext(),
927 SrcModule->getSourceFileName())}));
928 }
929 GlobalsToImport.insert(Fn);
930 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000931 }
932
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000933 // Upgrade debug info after we're done materializing all the globals and we
934 // have loaded all the required metadata!
935 UpgradeDebugInfo(*SrcModule);
936
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000937 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000938 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000939 return true;
940
Teresa Johnsond29478f2016-03-27 15:27:30 +0000941 if (PrintImports) {
942 for (const auto *GV : GlobalsToImport)
943 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
944 << " from " << SrcModule->getSourceFileName() << "\n";
945 }
946
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000947 if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
948 [](GlobalValue &, IRMover::ValueAdder) {},
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +0000949 /*IsPerformingImport=*/true))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000950 report_fatal_error("Function Import: link error");
951
Mehdi Amini01e32132016-03-26 05:40:34 +0000952 ImportedCount += GlobalsToImport.size();
Teresa Johnson6c475a72017-01-05 21:34:18 +0000953 NumImportedModules++;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000954 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000955
Eugene Leviant19e23872018-03-12 10:30:50 +0000956 NumImportedFunctions += (ImportedCount - ImportedGVCount);
957 NumImportedGlobalVars += ImportedGVCount;
Teresa Johnsond29478f2016-03-27 15:27:30 +0000958
Eugene Leviant19e23872018-03-12 10:30:50 +0000959 DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
960 << " functions for Module " << DestModule.getModuleIdentifier()
961 << "\n");
962 DEBUG(dbgs() << "Imported " << ImportedGVCount
963 << " global variables for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000964 << DestModule.getModuleIdentifier() << "\n");
965 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000966}
967
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000968static bool doImportingForModule(Module &M) {
969 if (SummaryFile.empty())
970 report_fatal_error("error: -function-import requires -summary-file\n");
971 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
972 getModuleSummaryIndexForFile(SummaryFile);
973 if (!IndexPtrOrErr) {
974 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
975 "Error loading file '" + SummaryFile + "': ");
976 return false;
Teresa Johnson21241572016-07-18 21:22:24 +0000977 }
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000978 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
Teresa Johnson21241572016-07-18 21:22:24 +0000979
980 // First step is collecting the import list.
981 FunctionImporter::ImportMapTy ImportList;
Teresa Johnson81bbf742017-12-16 00:18:12 +0000982 // If requested, simply import all functions in the index. This is used
983 // when testing distributed backend handling via the opt tool, when
984 // we have distributed indexes containing exactly the summaries to import.
985 if (ImportAllIndex)
986 ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
987 ImportList);
988 else
989 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
990 ImportList);
Teresa Johnson21241572016-07-18 21:22:24 +0000991
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000992 // Conservatively mark all internal values as promoted. This interface is
993 // only used when doing importing via the function importing pass. The pass
994 // is only enabled when testing importing via the 'opt' tool, which does
995 // not do the ThinLink that would normally determine what values to promote.
996 for (auto &I : *Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000997 for (auto &S : I.second.SummaryList) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000998 if (GlobalValue::isLocalLinkage(S->linkage()))
999 S->setLinkage(GlobalValue::ExternalLinkage);
1000 }
1001 }
1002
Teresa Johnson21241572016-07-18 21:22:24 +00001003 // Next we need to promote to global scope and rename any local values that
1004 // are potentially exported to other modules.
1005 if (renameModuleForThinLTO(M, *Index, nullptr)) {
1006 errs() << "Error renaming module\n";
1007 return false;
1008 }
1009
1010 // Perform the import now.
1011 auto ModuleLoader = [&M](StringRef Identifier) {
1012 return loadFile(Identifier, M.getContext());
1013 };
1014 FunctionImporter Importer(*Index, ModuleLoader);
Peter Collingbourne37e24592017-02-02 18:42:25 +00001015 Expected<bool> Result = Importer.importFunctions(M, ImportList);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00001016
1017 // FIXME: Probably need to propagate Errors through the pass manager.
1018 if (!Result) {
1019 logAllUnhandledErrors(Result.takeError(), errs(),
1020 "Error importing module: ");
1021 return false;
1022 }
1023
1024 return *Result;
Teresa Johnson21241572016-07-18 21:22:24 +00001025}
1026
Benjamin Kramerfe2b5412015-12-24 10:03:35 +00001027namespace {
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001028
Mehdi Amini42418ab2015-11-24 06:07:49 +00001029/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +00001030class FunctionImportLegacyPass : public ModulePass {
Mehdi Amini42418ab2015-11-24 06:07:49 +00001031public:
1032 /// Pass identification, replacement for typeid
1033 static char ID;
1034
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001035 explicit FunctionImportLegacyPass() : ModulePass(ID) {}
1036
Teresa Johnson5fcbdb72015-12-07 19:21:11 +00001037 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +00001038 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +00001039
Mehdi Amini42418ab2015-11-24 06:07:49 +00001040 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001041 if (skipModule(M))
1042 return false;
1043
Peter Collingbourne598bd2a2016-12-21 00:50:12 +00001044 return doImportingForModule(M);
Mehdi Amini42418ab2015-11-24 06:07:49 +00001045 }
1046};
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001047
1048} // end anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +00001049
Teresa Johnson21241572016-07-18 21:22:24 +00001050PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001051 ModuleAnalysisManager &AM) {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +00001052 if (!doImportingForModule(M))
Teresa Johnson21241572016-07-18 21:22:24 +00001053 return PreservedAnalyses::all();
1054
1055 return PreservedAnalyses::none();
1056}
1057
1058char FunctionImportLegacyPass::ID = 0;
1059INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
1060 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +00001061
1062namespace llvm {
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001063
Peter Collingbourne598bd2a2016-12-21 00:50:12 +00001064Pass *createFunctionImportPass() {
1065 return new FunctionImportLegacyPass();
Teresa Johnson5fcbdb72015-12-07 19:21:11 +00001066}
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001067
1068} // end namespace llvm