1 //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements Function import based on summaries.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Transforms/IPO/FunctionImport.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/StringSet.h"
23 #include "llvm/Bitcode/BitcodeReader.h"
24 #include "llvm/IR/AutoUpgrade.h"
25 #include "llvm/IR/Constants.h"
26 #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"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ModuleSummaryIndex.h"
34 #include "llvm/IRReader/IRReader.h"
35 #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"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/Error.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/FileSystem.h"
45 #include "llvm/Support/SourceMgr.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Transforms/IPO/Internalize.h"
48 #include "llvm/Transforms/Utils/Cloning.h"
49 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
50 #include "llvm/Transforms/Utils/ValueMapper.h"
51 #include <cassert>
52 #include <memory>
53 #include <set>
54 #include <string>
55 #include <system_error>
56 #include <tuple>
57 #include <utility>
58
59 using namespace llvm;
60
61 #define DEBUG_TYPE "function-import"
62
63 STATISTIC(NumImportedFunctions, "Number of functions imported");
64 STATISTIC(NumImportedGlobalVars, "Number of global variables imported");
65 STATISTIC(NumImportedModules, "Number of modules imported from");
66 STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
67 STATISTIC(NumLiveSymbols, "Number of live symbols in index");
68
69 /// Limit on instruction count of imported functions.
70 static 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
74 static 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
78 static 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"));
84
85 static 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
92 static cl::opt<float> ImportHotMultiplier(
93 "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
94 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
95
96 static 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
102 // FIXME: This multiplier was not really tuned up.
103 static 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"));
106
107 static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
108 cl::desc("Print imported functions"));
109
110 static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
111 cl::desc("Compute dead symbols"));
112
113 static 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
123 /// Summary file to use for function importing when using -function-import from
124 /// the command line.
125 static cl::opt<std::string>
126 SummaryFile("summary-file",
127 cl::desc("The summary file to use for function importing."));
128
129 /// Used when testing importing from distributed indexes via opt
130 // -function-import.
131 static cl::opt<bool>
132 ImportAllIndex("import-all-index",
133 cl::desc("Import all external functions in index."));
134
135 // Load lazily a module from \p FileName in \p Context.
loadFile(const std::string & FileName,LLVMContext & Context)136 static std::unique_ptr<Module> loadFile(const std::string &FileName,
137 LLVMContext &Context) {
138 SMDiagnostic Err;
139 LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n");
140 // Metadata isn't loaded until functions are imported, to minimize
141 // the memory overhead.
142 std::unique_ptr<Module> Result =
143 getLazyIRFileModule(FileName, Err, Context,
144 /* ShouldLazyLoadMetadata = */ true);
145 if (!Result) {
146 Err.print("function-import", errs());
147 report_fatal_error("Abort");
148 }
149
150 return Result;
151 }
152
153 /// 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]
163 static const GlobalValueSummary *
selectCallee(const ModuleSummaryIndex & Index,ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,unsigned Threshold,StringRef CallerModulePath)164 selectCallee(const ModuleSummaryIndex &Index,
165 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
166 unsigned Threshold, StringRef CallerModulePath) {
167 auto It = llvm::find_if(
168 CalleeSummaryList,
169 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
170 auto *GVSummary = SummaryPtr.get();
171 if (!Index.isGlobalValueLive(GVSummary))
172 return false;
173
174 // 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;
189 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
190 // There is no point in importing these, we can't inline them
191 return false;
192
193 auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject());
194
195 // 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
210 if (Summary->instCount() > Threshold)
211 return false;
212
213 if (Summary->notEligibleToImport())
214 return false;
215
216 return true;
217 });
218 if (It == CalleeSummaryList.end())
219 return nullptr;
220
221 return cast<GlobalValueSummary>(It->get());
222 }
223
224 namespace {
225
226 using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
227 GlobalValue::GUID>;
228
229 } // anonymous namespace
230
231 static ValueInfo
updateValueInfoForIndirectCalls(const ModuleSummaryIndex & Index,ValueInfo VI)232 updateValueInfoForIndirectCalls(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)
242 return ValueInfo();
243 return Index.getValueInfo(GUID);
244 }
245
computeImportForReferencedGlobals(const FunctionSummary & Summary,const GVSummaryMapTy & DefinedGVSummaries,FunctionImporter::ImportMapTy & ImportList,StringMap<FunctionImporter::ExportSetTy> * ExportLists)246 static 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 LLVM_DEBUG(
253 dbgs() << "Ref ignored! Target already in destination module.\n");
254 continue;
255 }
256
257 LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n");
258
259 for (auto &RefSummary : VI.getSummaryList())
260 if (RefSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind &&
261 !RefSummary->notEligibleToImport() &&
262 !GlobalValue::isInterposableLinkage(RefSummary->linkage()) &&
263 RefSummary->refs().empty()) {
264 ImportList[RefSummary->modulePath()].insert(VI.getGUID());
265 if (ExportLists)
266 (*ExportLists)[RefSummary->modulePath()].insert(VI.getGUID());
267 break;
268 }
269 }
270 }
271
272 /// 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.
computeImportForFunction(const FunctionSummary & Summary,const ModuleSummaryIndex & Index,const unsigned Threshold,const GVSummaryMapTy & DefinedGVSummaries,SmallVectorImpl<EdgeInfo> & Worklist,FunctionImporter::ImportMapTy & ImportList,StringMap<FunctionImporter::ExportSetTy> * ExportLists,FunctionImporter::ImportThresholdsTy & ImportThresholds)275 static void computeImportForFunction(
276 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
277 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
278 SmallVectorImpl<EdgeInfo> &Worklist,
279 FunctionImporter::ImportMapTy &ImportList,
280 StringMap<FunctionImporter::ExportSetTy> *ExportLists,
281 FunctionImporter::ImportThresholdsTy &ImportThresholds) {
282 computeImportForReferencedGlobals(Summary, DefinedGVSummaries, ImportList,
283 ExportLists);
284 static int ImportCount = 0;
285 for (auto &Edge : Summary.calls()) {
286 ValueInfo VI = Edge.first;
287 LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold
288 << "\n");
289
290 if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
291 LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
292 << " reached.\n");
293 continue;
294 }
295
296 VI = updateValueInfoForIndirectCalls(Index, VI);
297 if (!VI)
298 continue;
299
300 if (DefinedGVSummaries.count(VI.getGUID())) {
301 LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n");
302 continue;
303 }
304
305 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
306 if (Hotness == CalleeInfo::HotnessType::Hot)
307 return ImportHotMultiplier;
308 if (Hotness == CalleeInfo::HotnessType::Cold)
309 return ImportColdMultiplier;
310 if (Hotness == CalleeInfo::HotnessType::Critical)
311 return ImportCriticalMultiplier;
312 return 1.0;
313 };
314
315 const auto NewThreshold =
316 Threshold * GetBonusMultiplier(Edge.second.getHotness());
317
318 auto IT = ImportThresholds.insert(
319 std::make_pair(VI.getGUID(), std::make_pair(NewThreshold, nullptr)));
320 bool PreviouslyVisited = !IT.second;
321 auto &ProcessedThreshold = IT.first->second.first;
322 auto &CalleeSummary = IT.first->second.second;
323
324 const FunctionSummary *ResolvedCalleeSummary = nullptr;
325 if (CalleeSummary) {
326 assert(PreviouslyVisited);
327 // Since the traversal of the call graph is DFS, we can revisit a function
328 // a second time with a higher threshold. In this case, it is added back
329 // to the worklist with the new threshold (so that its own callee chains
330 // can be considered with the higher threshold).
331 if (NewThreshold <= ProcessedThreshold) {
332 LLVM_DEBUG(
333 dbgs() << "ignored! Target was already imported with Threshold "
334 << ProcessedThreshold << "\n");
335 continue;
336 }
337 // Update with new larger threshold.
338 ProcessedThreshold = NewThreshold;
339 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
340 } else {
341 // If we already rejected importing a callee at the same or higher
342 // threshold, don't waste time calling selectCallee.
343 if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
344 LLVM_DEBUG(
345 dbgs() << "ignored! Target was already rejected with Threshold "
346 << ProcessedThreshold << "\n");
347 continue;
348 }
349
350 CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
351 Summary.modulePath());
352 if (!CalleeSummary) {
353 // Update with new larger threshold if this was a retry (otherwise
354 // we would have already inserted with NewThreshold above).
355 if (PreviouslyVisited)
356 ProcessedThreshold = NewThreshold;
357 LLVM_DEBUG(
358 dbgs() << "ignored! No qualifying callee with summary found.\n");
359 continue;
360 }
361
362 // "Resolve" the summary
363 CalleeSummary = CalleeSummary->getBaseObject();
364 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
365
366 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
367 "selectCallee() didn't honor the threshold");
368
369 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
370 auto ILI = ImportList[ExportModulePath].insert(VI.getGUID());
371 // We previously decided to import this GUID definition if it was already
372 // inserted in the set of imports from the exporting module.
373 bool PreviouslyImported = !ILI.second;
374
375 // Make exports in the source module.
376 if (ExportLists) {
377 auto &ExportList = (*ExportLists)[ExportModulePath];
378 ExportList.insert(VI.getGUID());
379 if (!PreviouslyImported) {
380 // This is the first time this function was exported from its source
381 // module, so mark all functions and globals it references as exported
382 // to the outside if they are defined in the same source module.
383 // For efficiency, we unconditionally add all the referenced GUIDs
384 // to the ExportList for this module, and will prune out any not
385 // defined in the module later in a single pass.
386 for (auto &Edge : ResolvedCalleeSummary->calls()) {
387 auto CalleeGUID = Edge.first.getGUID();
388 ExportList.insert(CalleeGUID);
389 }
390 for (auto &Ref : ResolvedCalleeSummary->refs()) {
391 auto GUID = Ref.getGUID();
392 ExportList.insert(GUID);
393 }
394 }
395 }
396 }
397
398 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
399 // Adjust the threshold for next level of imported functions.
400 // The threshold is different for hot callsites because we can then
401 // inline chains of hot calls.
402 if (IsHotCallsite)
403 return Threshold * ImportHotInstrFactor;
404 return Threshold * ImportInstrFactor;
405 };
406
407 bool IsHotCallsite =
408 Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
409 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
410
411 ImportCount++;
412
413 // Insert the newly imported function to the worklist.
414 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
415 }
416 }
417
418 /// Given the list of globals defined in a module, compute the list of imports
419 /// as well as the list of "exports", i.e. the list of symbols referenced from
420 /// another module (that may require promotion).
ComputeImportForModule(const GVSummaryMapTy & DefinedGVSummaries,const ModuleSummaryIndex & Index,FunctionImporter::ImportMapTy & ImportList,StringMap<FunctionImporter::ExportSetTy> * ExportLists=nullptr)421 static void ComputeImportForModule(
422 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
423 FunctionImporter::ImportMapTy &ImportList,
424 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
425 // Worklist contains the list of function imported in this module, for which
426 // we will analyse the callees and may import further down the callgraph.
427 SmallVector<EdgeInfo, 128> Worklist;
428 FunctionImporter::ImportThresholdsTy ImportThresholds;
429
430 // Populate the worklist with the import for the functions in the current
431 // module
432 for (auto &GVSummary : DefinedGVSummaries) {
433 #ifndef NDEBUG
434 // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID
435 // so this map look up (and possibly others) can be avoided.
436 auto VI = Index.getValueInfo(GVSummary.first);
437 #endif
438 if (!Index.isGlobalValueLive(GVSummary.second)) {
439 LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n");
440 continue;
441 }
442 auto *FuncSummary =
443 dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
444 if (!FuncSummary)
445 // Skip import for global variables
446 continue;
447 LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n");
448 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
449 DefinedGVSummaries, Worklist, ImportList,
450 ExportLists, ImportThresholds);
451 }
452
453 // Process the newly imported functions and add callees to the worklist.
454 while (!Worklist.empty()) {
455 auto FuncInfo = Worklist.pop_back_val();
456 auto *Summary = std::get<0>(FuncInfo);
457 auto Threshold = std::get<1>(FuncInfo);
458
459 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
460 Worklist, ImportList, ExportLists,
461 ImportThresholds);
462 }
463 }
464
465 #ifndef NDEBUG
isGlobalVarSummary(const ModuleSummaryIndex & Index,GlobalValue::GUID G)466 static bool isGlobalVarSummary(const ModuleSummaryIndex &Index,
467 GlobalValue::GUID G) {
468 if (const auto &VI = Index.getValueInfo(G)) {
469 auto SL = VI.getSummaryList();
470 if (!SL.empty())
471 return SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
472 }
473 return false;
474 }
475
getGUID(GlobalValue::GUID G)476 static GlobalValue::GUID getGUID(GlobalValue::GUID G) { return G; }
477
478 template <class T>
numGlobalVarSummaries(const ModuleSummaryIndex & Index,T & Cont)479 static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index,
480 T &Cont) {
481 unsigned NumGVS = 0;
482 for (auto &V : Cont)
483 if (isGlobalVarSummary(Index, getGUID(V)))
484 ++NumGVS;
485 return NumGVS;
486 }
487 #endif
488
489 /// Compute all the import and export for every module using the Index.
ComputeCrossModuleImport(const ModuleSummaryIndex & Index,const StringMap<GVSummaryMapTy> & ModuleToDefinedGVSummaries,StringMap<FunctionImporter::ImportMapTy> & ImportLists,StringMap<FunctionImporter::ExportSetTy> & ExportLists)490 void llvm::ComputeCrossModuleImport(
491 const ModuleSummaryIndex &Index,
492 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
493 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
494 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
495 // For each module that has function defined, compute the import/export lists.
496 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
497 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
498 LLVM_DEBUG(dbgs() << "Computing import for Module '"
499 << DefinedGVSummaries.first() << "'\n");
500 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
501 &ExportLists);
502 }
503
504 // When computing imports we added all GUIDs referenced by anything
505 // imported from the module to its ExportList. Now we prune each ExportList
506 // of any not defined in that module. This is more efficient than checking
507 // while computing imports because some of the summary lists may be long
508 // due to linkonce (comdat) copies.
509 for (auto &ELI : ExportLists) {
510 const auto &DefinedGVSummaries =
511 ModuleToDefinedGVSummaries.lookup(ELI.first());
512 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
513 if (!DefinedGVSummaries.count(*EI))
514 EI = ELI.second.erase(EI);
515 else
516 ++EI;
517 }
518 }
519
520 #ifndef NDEBUG
521 LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
522 << " modules:\n");
523 for (auto &ModuleImports : ImportLists) {
524 auto ModName = ModuleImports.first();
525 auto &Exports = ExportLists[ModName];
526 unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
527 LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports "
528 << Exports.size() - NumGVS << " functions and " << NumGVS
529 << " vars. Imports from " << ModuleImports.second.size()
530 << " modules.\n");
531 for (auto &Src : ModuleImports.second) {
532 auto SrcModName = Src.first();
533 unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
534 LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
535 << " functions imported from " << SrcModName << "\n");
536 LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod
537 << " global vars imported from " << SrcModName << "\n");
538 }
539 }
540 #endif
541 }
542
543 #ifndef NDEBUG
dumpImportListForModule(const ModuleSummaryIndex & Index,StringRef ModulePath,FunctionImporter::ImportMapTy & ImportList)544 static void dumpImportListForModule(const ModuleSummaryIndex &Index,
545 StringRef ModulePath,
546 FunctionImporter::ImportMapTy &ImportList) {
547 LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
548 << ImportList.size() << " modules.\n");
549 for (auto &Src : ImportList) {
550 auto SrcModName = Src.first();
551 unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
552 LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
553 << " functions imported from " << SrcModName << "\n");
554 LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from "
555 << SrcModName << "\n");
556 }
557 }
558 #endif
559
560 /// Compute all the imports for the given module in the Index.
ComputeCrossModuleImportForModule(StringRef ModulePath,const ModuleSummaryIndex & Index,FunctionImporter::ImportMapTy & ImportList)561 void llvm::ComputeCrossModuleImportForModule(
562 StringRef ModulePath, const ModuleSummaryIndex &Index,
563 FunctionImporter::ImportMapTy &ImportList) {
564 // Collect the list of functions this module defines.
565 // GUID -> Summary
566 GVSummaryMapTy FunctionSummaryMap;
567 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
568
569 // Compute the import list for this module.
570 LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
571 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
572
573 #ifndef NDEBUG
574 dumpImportListForModule(Index, ModulePath, ImportList);
575 #endif
576 }
577
578 // Mark all external summaries in Index for import into the given module.
579 // Used for distributed builds using a distributed index.
ComputeCrossModuleImportForModuleFromIndex(StringRef ModulePath,const ModuleSummaryIndex & Index,FunctionImporter::ImportMapTy & ImportList)580 void llvm::ComputeCrossModuleImportForModuleFromIndex(
581 StringRef ModulePath, const ModuleSummaryIndex &Index,
582 FunctionImporter::ImportMapTy &ImportList) {
583 for (auto &GlobalList : Index) {
584 // Ignore entries for undefined references.
585 if (GlobalList.second.SummaryList.empty())
586 continue;
587
588 auto GUID = GlobalList.first;
589 assert(GlobalList.second.SummaryList.size() == 1 &&
590 "Expected individual combined index to have one summary per GUID");
591 auto &Summary = GlobalList.second.SummaryList[0];
592 // Skip the summaries for the importing module. These are included to
593 // e.g. record required linkage changes.
594 if (Summary->modulePath() == ModulePath)
595 continue;
596 // Add an entry to provoke importing by thinBackend.
597 ImportList[Summary->modulePath()].insert(GUID);
598 }
599 #ifndef NDEBUG
600 dumpImportListForModule(Index, ModulePath, ImportList);
601 #endif
602 }
603
computeDeadSymbols(ModuleSummaryIndex & Index,const DenseSet<GlobalValue::GUID> & GUIDPreservedSymbols,function_ref<PrevailingType (GlobalValue::GUID)> isPrevailing)604 void llvm::computeDeadSymbols(
605 ModuleSummaryIndex &Index,
606 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
607 function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
608 assert(!Index.withGlobalValueDeadStripping());
609 if (!ComputeDead)
610 return;
611 if (GUIDPreservedSymbols.empty())
612 // Don't do anything when nothing is live, this is friendly with tests.
613 return;
614 unsigned LiveSymbols = 0;
615 SmallVector<ValueInfo, 128> Worklist;
616 Worklist.reserve(GUIDPreservedSymbols.size() * 2);
617 for (auto GUID : GUIDPreservedSymbols) {
618 ValueInfo VI = Index.getValueInfo(GUID);
619 if (!VI)
620 continue;
621 for (auto &S : VI.getSummaryList())
622 S->setLive(true);
623 }
624
625 // Add values flagged in the index as live roots to the worklist.
626 for (const auto &Entry : Index) {
627 auto VI = Index.getValueInfo(Entry);
628 for (auto &S : Entry.second.SummaryList)
629 if (S->isLive()) {
630 LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n");
631 Worklist.push_back(VI);
632 ++LiveSymbols;
633 break;
634 }
635 }
636
637 // Make value live and add it to the worklist if it was not live before.
638 auto visit = [&](ValueInfo VI) {
639 // FIXME: If we knew which edges were created for indirect call profiles,
640 // we could skip them here. Any that are live should be reached via
641 // other edges, e.g. reference edges. Otherwise, using a profile collected
642 // on a slightly different binary might provoke preserving, importing
643 // and ultimately promoting calls to functions not linked into this
644 // binary, which increases the binary size unnecessarily. Note that
645 // if this code changes, the importer needs to change so that edges
646 // to functions marked dead are skipped.
647 VI = updateValueInfoForIndirectCalls(Index, VI);
648 if (!VI)
649 return;
650 for (auto &S : VI.getSummaryList())
651 if (S->isLive())
652 return;
653
654 // We only keep live symbols that are known to be non-prevailing if any are
655 // available_externally. Those symbols are discarded later in the
656 // EliminateAvailableExternally pass and setting them to not-live breaks
657 // downstreams users of liveness information (PR36483).
658 if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
659 bool AvailableExternally = false;
660 bool Interposable = false;
661 for (auto &S : VI.getSummaryList()) {
662 if (S->linkage() == GlobalValue::AvailableExternallyLinkage)
663 AvailableExternally = true;
664 else if (GlobalValue::isInterposableLinkage(S->linkage()))
665 Interposable = true;
666 }
667
668 if (!AvailableExternally)
669 return;
670
671 if (Interposable)
672 report_fatal_error("Interposable and available_externally symbol");
673 }
674
675 for (auto &S : VI.getSummaryList())
676 S->setLive(true);
677 ++LiveSymbols;
678 Worklist.push_back(VI);
679 };
680
681 while (!Worklist.empty()) {
682 auto VI = Worklist.pop_back_val();
683 for (auto &Summary : VI.getSummaryList()) {
684 GlobalValueSummary *Base = Summary->getBaseObject();
685 // Set base value live in case it is an alias.
686 Base->setLive(true);
687 for (auto Ref : Base->refs())
688 visit(Ref);
689 if (auto *FS = dyn_cast<FunctionSummary>(Base))
690 for (auto Call : FS->calls())
691 visit(Call.first);
692 }
693 }
694 Index.setWithGlobalValueDeadStripping();
695
696 unsigned DeadSymbols = Index.size() - LiveSymbols;
697 LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
698 << " symbols Dead \n");
699 NumDeadSymbols += DeadSymbols;
700 NumLiveSymbols += LiveSymbols;
701 }
702
703 /// Compute the set of summaries needed for a ThinLTO backend compilation of
704 /// \p ModulePath.
gatherImportedSummariesForModule(StringRef ModulePath,const StringMap<GVSummaryMapTy> & ModuleToDefinedGVSummaries,const FunctionImporter::ImportMapTy & ImportList,std::map<std::string,GVSummaryMapTy> & ModuleToSummariesForIndex)705 void llvm::gatherImportedSummariesForModule(
706 StringRef ModulePath,
707 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
708 const FunctionImporter::ImportMapTy &ImportList,
709 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
710 // Include all summaries from the importing module.
711 ModuleToSummariesForIndex[ModulePath] =
712 ModuleToDefinedGVSummaries.lookup(ModulePath);
713 // Include summaries for imports.
714 for (auto &ILI : ImportList) {
715 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
716 const auto &DefinedGVSummaries =
717 ModuleToDefinedGVSummaries.lookup(ILI.first());
718 for (auto &GI : ILI.second) {
719 const auto &DS = DefinedGVSummaries.find(GI);
720 assert(DS != DefinedGVSummaries.end() &&
721 "Expected a defined summary for imported global value");
722 SummariesForIndex[GI] = DS->second;
723 }
724 }
725 }
726
727 /// Emit the files \p ModulePath will import from into \p OutputFilename.
EmitImportsFiles(StringRef ModulePath,StringRef OutputFilename,const std::map<std::string,GVSummaryMapTy> & ModuleToSummariesForIndex)728 std::error_code llvm::EmitImportsFiles(
729 StringRef ModulePath, StringRef OutputFilename,
730 const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
731 std::error_code EC;
732 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
733 if (EC)
734 return EC;
735 for (auto &ILI : ModuleToSummariesForIndex)
736 // The ModuleToSummariesForIndex map includes an entry for the current
737 // Module (needed for writing out the index files). We don't want to
738 // include it in the imports file, however, so filter it out.
739 if (ILI.first != ModulePath)
740 ImportsOS << ILI.first << "\n";
741 return std::error_code();
742 }
743
convertToDeclaration(GlobalValue & GV)744 bool llvm::convertToDeclaration(GlobalValue &GV) {
745 LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
746 << "\n");
747 if (Function *F = dyn_cast<Function>(&GV)) {
748 F->deleteBody();
749 F->clearMetadata();
750 F->setComdat(nullptr);
751 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
752 V->setInitializer(nullptr);
753 V->setLinkage(GlobalValue::ExternalLinkage);
754 V->clearMetadata();
755 V->setComdat(nullptr);
756 } else {
757 GlobalValue *NewGV;
758 if (GV.getValueType()->isFunctionTy())
759 NewGV =
760 Function::Create(cast<FunctionType>(GV.getValueType()),
761 GlobalValue::ExternalLinkage, "", GV.getParent());
762 else
763 NewGV =
764 new GlobalVariable(*GV.getParent(), GV.getValueType(),
765 /*isConstant*/ false, GlobalValue::ExternalLinkage,
766 /*init*/ nullptr, "",
767 /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
768 GV.getType()->getAddressSpace());
769 NewGV->takeName(&GV);
770 GV.replaceAllUsesWith(NewGV);
771 return false;
772 }
773 return true;
774 }
775
776 /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
thinLTOResolveWeakForLinkerModule(Module & TheModule,const GVSummaryMapTy & DefinedGlobals)777 void llvm::thinLTOResolveWeakForLinkerModule(
778 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
779 auto updateLinkage = [&](GlobalValue &GV) {
780 // See if the global summary analysis computed a new resolved linkage.
781 const auto &GS = DefinedGlobals.find(GV.getGUID());
782 if (GS == DefinedGlobals.end())
783 return;
784 auto NewLinkage = GS->second->linkage();
785 if (NewLinkage == GV.getLinkage())
786 return;
787
788 // Switch the linkage to weakany if asked for, e.g. we do this for
789 // linker redefined symbols (via --wrap or --defsym).
790 // We record that the visibility should be changed here in `addThinLTO`
791 // as we need access to the resolution vectors for each input file in
792 // order to find which symbols have been redefined.
793 // We may consider reorganizing this code and moving the linkage recording
794 // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex.
795 if (NewLinkage == GlobalValue::WeakAnyLinkage) {
796 GV.setLinkage(NewLinkage);
797 return;
798 }
799
800 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
801 return;
802 // Check for a non-prevailing def that has interposable linkage
803 // (e.g. non-odr weak or linkonce). In that case we can't simply
804 // convert to available_externally, since it would lose the
805 // interposable property and possibly get inlined. Simply drop
806 // the definition in that case.
807 if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
808 GlobalValue::isInterposableLinkage(GV.getLinkage())) {
809 if (!convertToDeclaration(GV))
810 // FIXME: Change this to collect replaced GVs and later erase
811 // them from the parent module once thinLTOResolveWeakForLinkerGUID is
812 // changed to enable this for aliases.
813 llvm_unreachable("Expected GV to be converted");
814 } else {
815 // If the original symbols has global unnamed addr and linkonce_odr linkage,
816 // it should be an auto hide symbol. Add hidden visibility to the symbol to
817 // preserve the property.
818 if (GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr() &&
819 NewLinkage == GlobalValue::WeakODRLinkage)
820 GV.setVisibility(GlobalValue::HiddenVisibility);
821
822 LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
823 << "` from " << GV.getLinkage() << " to " << NewLinkage
824 << "\n");
825 GV.setLinkage(NewLinkage);
826 }
827 // Remove declarations from comdats, including available_externally
828 // as this is a declaration for the linker, and will be dropped eventually.
829 // It is illegal for comdats to contain declarations.
830 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
831 if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
832 GO->setComdat(nullptr);
833 };
834
835 // Process functions and global now
836 for (auto &GV : TheModule)
837 updateLinkage(GV);
838 for (auto &GV : TheModule.globals())
839 updateLinkage(GV);
840 for (auto &GV : TheModule.aliases())
841 updateLinkage(GV);
842 }
843
844 /// Run internalization on \p TheModule based on symmary analysis.
thinLTOInternalizeModule(Module & TheModule,const GVSummaryMapTy & DefinedGlobals)845 void llvm::thinLTOInternalizeModule(Module &TheModule,
846 const GVSummaryMapTy &DefinedGlobals) {
847 // Declare a callback for the internalize pass that will ask for every
848 // candidate GlobalValue if it can be internalized or not.
849 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
850 // Lookup the linkage recorded in the summaries during global analysis.
851 auto GS = DefinedGlobals.find(GV.getGUID());
852 if (GS == DefinedGlobals.end()) {
853 // Must have been promoted (possibly conservatively). Find original
854 // name so that we can access the correct summary and see if it can
855 // be internalized again.
856 // FIXME: Eventually we should control promotion instead of promoting
857 // and internalizing again.
858 StringRef OrigName =
859 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
860 std::string OrigId = GlobalValue::getGlobalIdentifier(
861 OrigName, GlobalValue::InternalLinkage,
862 TheModule.getSourceFileName());
863 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
864 if (GS == DefinedGlobals.end()) {
865 // Also check the original non-promoted non-globalized name. In some
866 // cases a preempted weak value is linked in as a local copy because
867 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
868 // In that case, since it was originally not a local value, it was
869 // recorded in the index using the original name.
870 // FIXME: This may not be needed once PR27866 is fixed.
871 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
872 assert(GS != DefinedGlobals.end());
873 }
874 }
875 return !GlobalValue::isLocalLinkage(GS->second->linkage());
876 };
877
878 // FIXME: See if we can just internalize directly here via linkage changes
879 // based on the index, rather than invoking internalizeModule.
880 internalizeModule(TheModule, MustPreserveGV);
881 }
882
883 /// Make alias a clone of its aliasee.
replaceAliasWithAliasee(Module * SrcModule,GlobalAlias * GA)884 static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
885 Function *Fn = cast<Function>(GA->getBaseObject());
886
887 ValueToValueMapTy VMap;
888 Function *NewFn = CloneFunction(Fn, VMap);
889 // Clone should use the original alias's linkage and name, and we ensure
890 // all uses of alias instead use the new clone (casted if necessary).
891 NewFn->setLinkage(GA->getLinkage());
892 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
893 NewFn->takeName(GA);
894 return NewFn;
895 }
896
897 // Automatically import functions in Module \p DestModule based on the summaries
898 // index.
importFunctions(Module & DestModule,const FunctionImporter::ImportMapTy & ImportList)899 Expected<bool> FunctionImporter::importFunctions(
900 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
901 LLVM_DEBUG(dbgs() << "Starting import for Module "
902 << DestModule.getModuleIdentifier() << "\n");
903 unsigned ImportedCount = 0, ImportedGVCount = 0;
904
905 IRMover Mover(DestModule);
906 // Do the actual import of functions now, one Module at a time
907 std::set<StringRef> ModuleNameOrderedList;
908 for (auto &FunctionsToImportPerModule : ImportList) {
909 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
910 }
911 for (auto &Name : ModuleNameOrderedList) {
912 // Get the module for the import
913 const auto &FunctionsToImportPerModule = ImportList.find(Name);
914 assert(FunctionsToImportPerModule != ImportList.end());
915 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
916 if (!SrcModuleOrErr)
917 return SrcModuleOrErr.takeError();
918 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
919 assert(&DestModule.getContext() == &SrcModule->getContext() &&
920 "Context mismatch");
921
922 // If modules were created with lazy metadata loading, materialize it
923 // now, before linking it (otherwise this will be a noop).
924 if (Error Err = SrcModule->materializeMetadata())
925 return std::move(Err);
926
927 auto &ImportGUIDs = FunctionsToImportPerModule->second;
928 // Find the globals to import
929 SetVector<GlobalValue *> GlobalsToImport;
930 for (Function &F : *SrcModule) {
931 if (!F.hasName())
932 continue;
933 auto GUID = F.getGUID();
934 auto Import = ImportGUIDs.count(GUID);
935 LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function "
936 << GUID << " " << F.getName() << " from "
937 << SrcModule->getSourceFileName() << "\n");
938 if (Import) {
939 if (Error Err = F.materialize())
940 return std::move(Err);
941 if (EnableImportMetadata) {
942 // Add 'thinlto_src_module' metadata for statistics and debugging.
943 F.setMetadata(
944 "thinlto_src_module",
945 MDNode::get(DestModule.getContext(),
946 {MDString::get(DestModule.getContext(),
947 SrcModule->getSourceFileName())}));
948 }
949 GlobalsToImport.insert(&F);
950 }
951 }
952 for (GlobalVariable &GV : SrcModule->globals()) {
953 if (!GV.hasName())
954 continue;
955 auto GUID = GV.getGUID();
956 auto Import = ImportGUIDs.count(GUID);
957 LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global "
958 << GUID << " " << GV.getName() << " from "
959 << SrcModule->getSourceFileName() << "\n");
960 if (Import) {
961 if (Error Err = GV.materialize())
962 return std::move(Err);
963 ImportedGVCount += GlobalsToImport.insert(&GV);
964 }
965 }
966 for (GlobalAlias &GA : SrcModule->aliases()) {
967 if (!GA.hasName())
968 continue;
969 auto GUID = GA.getGUID();
970 auto Import = ImportGUIDs.count(GUID);
971 LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias "
972 << GUID << " " << GA.getName() << " from "
973 << SrcModule->getSourceFileName() << "\n");
974 if (Import) {
975 if (Error Err = GA.materialize())
976 return std::move(Err);
977 // Import alias as a copy of its aliasee.
978 GlobalObject *Base = GA.getBaseObject();
979 if (Error Err = Base->materialize())
980 return std::move(Err);
981 auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
982 LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID()
983 << " " << Base->getName() << " from "
984 << SrcModule->getSourceFileName() << "\n");
985 if (EnableImportMetadata) {
986 // Add 'thinlto_src_module' metadata for statistics and debugging.
987 Fn->setMetadata(
988 "thinlto_src_module",
989 MDNode::get(DestModule.getContext(),
990 {MDString::get(DestModule.getContext(),
991 SrcModule->getSourceFileName())}));
992 }
993 GlobalsToImport.insert(Fn);
994 }
995 }
996
997 // Upgrade debug info after we're done materializing all the globals and we
998 // have loaded all the required metadata!
999 UpgradeDebugInfo(*SrcModule);
1000
1001 // Link in the specified functions.
1002 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
1003 return true;
1004
1005 if (PrintImports) {
1006 for (const auto *GV : GlobalsToImport)
1007 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
1008 << " from " << SrcModule->getSourceFileName() << "\n";
1009 }
1010
1011 if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
1012 [](GlobalValue &, IRMover::ValueAdder) {},
1013 /*IsPerformingImport=*/true))
1014 report_fatal_error("Function Import: link error");
1015
1016 ImportedCount += GlobalsToImport.size();
1017 NumImportedModules++;
1018 }
1019
1020 NumImportedFunctions += (ImportedCount - ImportedGVCount);
1021 NumImportedGlobalVars += ImportedGVCount;
1022
1023 LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
1024 << " functions for Module "
1025 << DestModule.getModuleIdentifier() << "\n");
1026 LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
1027 << " global variables for Module "
1028 << DestModule.getModuleIdentifier() << "\n");
1029 return ImportedCount;
1030 }
1031
doImportingForModule(Module & M)1032 static bool doImportingForModule(Module &M) {
1033 if (SummaryFile.empty())
1034 report_fatal_error("error: -function-import requires -summary-file\n");
1035 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
1036 getModuleSummaryIndexForFile(SummaryFile);
1037 if (!IndexPtrOrErr) {
1038 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
1039 "Error loading file '" + SummaryFile + "': ");
1040 return false;
1041 }
1042 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
1043
1044 // First step is collecting the import list.
1045 FunctionImporter::ImportMapTy ImportList;
1046 // If requested, simply import all functions in the index. This is used
1047 // when testing distributed backend handling via the opt tool, when
1048 // we have distributed indexes containing exactly the summaries to import.
1049 if (ImportAllIndex)
1050 ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
1051 ImportList);
1052 else
1053 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
1054 ImportList);
1055
1056 // Conservatively mark all internal values as promoted. This interface is
1057 // only used when doing importing via the function importing pass. The pass
1058 // is only enabled when testing importing via the 'opt' tool, which does
1059 // not do the ThinLink that would normally determine what values to promote.
1060 for (auto &I : *Index) {
1061 for (auto &S : I.second.SummaryList) {
1062 if (GlobalValue::isLocalLinkage(S->linkage()))
1063 S->setLinkage(GlobalValue::ExternalLinkage);
1064 }
1065 }
1066
1067 // Next we need to promote to global scope and rename any local values that
1068 // are potentially exported to other modules.
1069 if (renameModuleForThinLTO(M, *Index, nullptr)) {
1070 errs() << "Error renaming module\n";
1071 return false;
1072 }
1073
1074 // Perform the import now.
1075 auto ModuleLoader = [&M](StringRef Identifier) {
1076 return loadFile(Identifier, M.getContext());
1077 };
1078 FunctionImporter Importer(*Index, ModuleLoader);
1079 Expected<bool> Result = Importer.importFunctions(M, ImportList);
1080
1081 // FIXME: Probably need to propagate Errors through the pass manager.
1082 if (!Result) {
1083 logAllUnhandledErrors(Result.takeError(), errs(),
1084 "Error importing module: ");
1085 return false;
1086 }
1087
1088 return *Result;
1089 }
1090
1091 namespace {
1092
1093 /// Pass that performs cross-module function import provided a summary file.
1094 class FunctionImportLegacyPass : public ModulePass {
1095 public:
1096 /// Pass identification, replacement for typeid
1097 static char ID;
1098
FunctionImportLegacyPass()1099 explicit FunctionImportLegacyPass() : ModulePass(ID) {}
1100
1101 /// Specify pass name for debug output
getPassName() const1102 StringRef getPassName() const override { return "Function Importing"; }
1103
runOnModule(Module & M)1104 bool runOnModule(Module &M) override {
1105 if (skipModule(M))
1106 return false;
1107
1108 return doImportingForModule(M);
1109 }
1110 };
1111
1112 } // end anonymous namespace
1113
run(Module & M,ModuleAnalysisManager & AM)1114 PreservedAnalyses FunctionImportPass::run(Module &M,
1115 ModuleAnalysisManager &AM) {
1116 if (!doImportingForModule(M))
1117 return PreservedAnalyses::all();
1118
1119 return PreservedAnalyses::none();
1120 }
1121
1122 char FunctionImportLegacyPass::ID = 0;
1123 INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
1124 "Summary Based Function Import", false, false)
1125
1126 namespace llvm {
1127
createFunctionImportPass()1128 Pass *createFunctionImportPass() {
1129 return new FunctionImportLegacyPass();
1130 }
1131
1132 } // end namespace llvm
1133