LLVM 24.0.0git
FunctionImport.cpp
Go to the documentation of this file.
1//===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements Function import based on summaries.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SetVector.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/StringRef.h"
22#include "llvm/IR/AutoUpgrade.h"
23#include "llvm/IR/Constants.h"
24#include "llvm/IR/Function.h"
25#include "llvm/IR/GlobalAlias.h"
27#include "llvm/IR/GlobalValue.h"
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/Metadata.h"
31#include "llvm/IR/Module.h"
34#include "llvm/Linker/IRMover.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/Errc.h"
40#include "llvm/Support/Error.h"
43#include "llvm/Support/JSON.h"
44#include "llvm/Support/Path.h"
53#include <cassert>
54#include <memory>
55#include <string>
56#include <system_error>
57#include <tuple>
58#include <utility>
59
60using namespace llvm;
61
62#define DEBUG_TYPE "function-import"
63
64STATISTIC(NumImportedFunctionsThinLink,
65 "Number of functions thin link decided to import");
66STATISTIC(NumImportedHotFunctionsThinLink,
67 "Number of hot functions thin link decided to import");
68STATISTIC(NumImportedCriticalFunctionsThinLink,
69 "Number of critical functions thin link decided to import");
70STATISTIC(NumImportedGlobalVarsThinLink,
71 "Number of global variables thin link decided to import");
72STATISTIC(NumImportedFunctions, "Number of functions imported in backend");
73STATISTIC(NumRequiredDeclsThinLink,
74 "Number of function declarations thin link decided to import because "
75 "the callee is required in the caller's module (e.g. for MemProf "
76 "ICP)");
77STATISTIC(NumImportedFunctionDecls,
78 "Number of function declarations imported in backend");
79STATISTIC(NumImportedGlobalVars,
80 "Number of global variables imported in backend");
81STATISTIC(NumImportedModules, "Number of modules imported from");
82STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
83STATISTIC(NumLiveSymbols, "Number of live symbols in index");
84
85namespace llvm {
87
89 ForceImportAll("force-import-all", cl::init(false), cl::Hidden,
90 cl::desc("Import functions with noinline attribute"));
91
92/// Limit on instruction count of imported functions.
94 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
95 cl::desc("Only import functions with less than N instructions"));
96
98 "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"),
99 cl::desc("Only import first N functions if N>=0 (default -1)"));
100
101static cl::opt<float>
102 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
104 cl::desc("As we import functions, multiply the "
105 "`import-instr-limit` threshold by this factor "
106 "before processing newly imported functions"));
107
109 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
110 cl::value_desc("x"),
111 cl::desc("As we import functions called from hot callsite, multiply the "
112 "`import-instr-limit` threshold by this factor "
113 "before processing newly imported functions"));
114
116 "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
117 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
118
120 "import-critical-multiplier", cl::init(100.0), cl::Hidden,
121 cl::value_desc("x"),
122 cl::desc(
123 "Multiply the `import-instr-limit` threshold for critical callsites"));
124
125// FIXME: This multiplier was not really tuned up.
127 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
128 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
129
130static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
131 cl::desc("Print imported functions"));
132
134 "print-import-failures", cl::init(false), cl::Hidden,
135 cl::desc("Print information for functions rejected for importing"));
136
137static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
138 cl::desc("Compute dead symbols"));
139
141 "enable-import-metadata", cl::init(false), cl::Hidden,
142 cl::desc("Enable import metadata like 'thinlto_src_module' and "
143 "'thinlto_src_file'"));
144
145/// Summary file to use for function importing when using -function-import from
146/// the command line.
148 SummaryFile("summary-file",
149 cl::desc("The summary file to use for function importing."));
150
151/// Used when testing importing from distributed indexes via opt
152// -function-import.
153static cl::opt<bool>
154 ImportAllIndex("import-all-index",
155 cl::desc("Import all external functions in index."));
156
157/// This is a test-only option.
158/// If this option is enabled, the ThinLTO indexing step will import each
159/// function declaration as a fallback. In a real build this may increase ram
160/// usage of the indexing step unnecessarily.
161/// TODO: Implement selective import (based on combined summary analysis) to
162/// ensure the imported function has a use case in the postlink pipeline.
164 "import-declaration", cl::init(false), cl::Hidden,
165 cl::desc("If true, import function declaration as fallback if the function "
166 "definition is not imported."));
167
168/// Pass a workload description file - an example of workload would be the
169/// functions executed to satisfy a RPC request. A workload is defined by a root
170/// function and the list of functions that are (frequently) needed to satisfy
171/// it. The module that defines the root will have all those functions imported.
172/// The file contains a JSON dictionary. The keys are root functions, the values
173/// are lists of functions to import in the module defining the root. It is
174/// assumed -funique-internal-linkage-names was used, thus ensuring function
175/// names are unique even for local linkage ones.
177 "thinlto-workload-def",
178 cl::desc("Pass a workload definition. This is a file containing a JSON "
179 "dictionary. The keys are root functions, the values are lists of "
180 "functions to import in the module defining the root. It is "
181 "assumed -funique-internal-linkage-names was used, to ensure "
182 "local linkage functions have unique names. For example: \n"
183 "{\n"
184 " \"rootFunction_1\": [\"function_to_import_1\", "
185 "\"function_to_import_2\"], \n"
186 " \"rootFunction_2\": [\"function_to_import_3\", "
187 "\"function_to_import_4\"] \n"
188 "}"),
189 cl::Hidden);
190
192
194 "thinlto-move-ctxprof-trees",
195 cl::desc("Move contextual profiling roots and the graphs under them in "
196 "their own module."),
197 cl::Hidden, cl::init(false));
198
200
202} // end namespace llvm
203
204// Load lazily a module from \p FileName in \p Context.
205static std::unique_ptr<Module> loadFile(const std::string &FileName,
206 LLVMContext &Context) {
207 SMDiagnostic Err;
208 LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n");
209 // Metadata isn't loaded until functions are imported, to minimize
210 // the memory overhead.
211 std::unique_ptr<Module> Result =
212 getLazyIRFileModule(FileName, Err, Context,
213 /* ShouldLazyLoadMetadata = */ true);
214 if (!Result) {
215 Err.print("function-import", errs());
216 report_fatal_error("Abort");
217 }
218
219 return Result;
220}
221
223 size_t NumDefs,
224 StringRef ImporterModule) {
225 // We can import a local when there is one definition.
226 if (NumDefs == 1)
227 return false;
228 // In other cases, make sure we import the copy in the caller's module if the
229 // referenced value has local linkage. The only time a local variable can
230 // share an entry in the index is if there is a local with the same name in
231 // another module that had the same source file name (in a different
232 // directory), where each was compiled in their own directory so there was not
233 // distinguishing path.
234 return GlobalValue::isLocalLinkage(RefSummary->linkage()) &&
235 RefSummary->modulePath() != ImporterModule;
236}
237
238/// Given a list of possible callee implementation for a call site, qualify the
239/// legality of importing each. The return is a range of pairs. Each pair
240/// corresponds to a candidate. The first value is the ImportFailureReason for
241/// that candidate, the second is the candidate.
243 const ModuleSummaryIndex &Index,
244 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
245 StringRef CallerModulePath) {
246 return llvm::map_range(
247 CalleeSummaryList,
248 [&Index, CalleeSummaryList,
249 CallerModulePath](const std::unique_ptr<GlobalValueSummary> &SummaryPtr)
251 const GlobalValueSummary *> {
252 auto *GVSummary = SummaryPtr.get();
253 if (!Index.isGlobalValueLive(GVSummary))
255
256 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
258 GVSummary};
259
260 auto *Summary = dyn_cast<FunctionSummary>(GVSummary->getBaseObject());
261
262 // Ignore any callees that aren't actually functions. This could happen
263 // in the case of GUID hash collisions. It could also happen in theory
264 // for SamplePGO profiles collected on old versions of the code after
265 // renaming, since we synthesize edges to any inlined callees appearing
266 // in the profile.
267 if (!Summary)
269
270 // If this is a local function, make sure we import the copy in the
271 // caller's module. The only time a local function can share an entry in
272 // the index is if there is a local with the same name in another module
273 // that had the same source file name (in a different directory), where
274 // each was compiled in their own directory so there was not
275 // distinguishing path.
276 // If the local function is from another module, it must be a reference
277 // due to indirect call profile data since a function pointer can point
278 // to a local in another module. Do the import from another module if
279 // there is only one entry in the list or when all files in the program
280 // are compiled with full path - in both cases the local function has
281 // unique PGO name and GUID.
282 if (shouldSkipLocalInAnotherModule(Summary, CalleeSummaryList.size(),
283 CallerModulePath))
284 return {
286 GVSummary};
287
288 // Skip if it isn't legal to import (e.g. may reference unpromotable
289 // locals).
290 if (Summary->notEligibleToImport())
292 GVSummary};
293
295 });
296}
297
298/// Given a list of possible callee implementation for a call site, select one
299/// that fits the \p Threshold for function definition import. If none are
300/// found, the Reason will give the last reason for the failure (last, in the
301/// order of CalleeSummaryList entries). While looking for a callee definition,
302/// sets \p TooLargeOrNoInlineSummary to the last seen too-large or noinline
303/// candidate; other modules may want to know the function summary or
304/// declaration even if a definition is not needed.
305///
306/// FIXME: select "best" instead of first that fits. But what is "best"?
307/// - The smallest: more likely to be inlined.
308/// - The one with the least outgoing edges (already well optimized).
309/// - One from a module already being imported from in order to reduce the
310/// number of source modules parsed/linked.
311/// - One that has PGO data attached.
312/// - [insert you fancy metric here]
313static const GlobalValueSummary *
315 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
316 unsigned Threshold, StringRef CallerModulePath,
317 const GlobalValueSummary *&TooLargeOrNoInlineSummary,
319 // Records the last summary with reason noinline or too-large.
320 TooLargeOrNoInlineSummary = nullptr;
321 auto QualifiedCandidates =
322 qualifyCalleeCandidates(Index, CalleeSummaryList, CallerModulePath);
323 for (auto QualifiedValue : QualifiedCandidates) {
324 Reason = QualifiedValue.first;
325 // Skip a summary if its import is not (proved to be) legal.
327 continue;
328 auto *Summary =
329 cast<FunctionSummary>(QualifiedValue.second->getBaseObject());
330
331 // Don't bother importing the definition if the chance of inlining it is
332 // not high enough (except under `--force-import-all`).
333 if ((Summary->instCount() > Threshold) && !Summary->fflags().AlwaysInline &&
335 TooLargeOrNoInlineSummary = Summary;
337 continue;
338 }
339
340 // Don't bother importing the definition if we can't inline it anyway.
341 if (Summary->fflags().NoInline && !ForceImportAll) {
342 TooLargeOrNoInlineSummary = Summary;
344 continue;
345 }
346
347 return Summary;
348 }
349 return nullptr;
350}
351
352namespace {
353
354using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */>;
355
356} // anonymous namespace
357
360 GlobalValue::GUID GUID) {
361 auto [Def, Decl] = IDs.createImportIDs(FromModule, GUID);
362 if (!Imports.insert(Def).second)
363 // Already there.
365
366 // Remove Decl in case it's there. Note that a definition takes precedence
367 // over a declaration for a given GUID.
368 return Imports.erase(Decl) ? AddDefinitionStatus::ChangedToDefinition
370}
371
373 StringRef FromModule, GlobalValue::GUID GUID) {
374 auto [Def, Decl] = IDs.createImportIDs(FromModule, GUID);
375 // Insert Decl only if Def is not present. Note that a definition takes
376 // precedence over a declaration for a given GUID.
377 if (!Imports.contains(Def))
378 Imports.insert(Decl);
379}
380
383 SetVector<StringRef> ModuleSet;
384 for (const auto &[SrcMod, GUID, ImportType] : *this)
385 ModuleSet.insert(SrcMod);
386 SmallVector<StringRef, 0> Modules = ModuleSet.takeVector();
387 llvm::sort(Modules);
388 return Modules;
389}
390
391std::optional<GlobalValueSummary::ImportKind>
393 GlobalValue::GUID GUID) const {
394 if (auto IDPair = IDs.getImportIDs(FromModule, GUID)) {
395 auto [Def, Decl] = *IDPair;
396 if (Imports.contains(Def))
398 if (Imports.contains(Decl))
400 }
401 return std::nullopt;
402}
403
404/// Import globals referenced by a function or other globals that are being
405/// imported, if importing such global is possible.
406class GlobalsImporter final {
407 const ModuleSummaryIndex &Index;
408 const GVSummaryMapTy &DefinedGVSummaries;
410 IsPrevailing;
413
414 bool shouldImportGlobal(const ValueInfo &VI, StringRef ReferencingModule) {
415 const auto &GVS = DefinedGVSummaries.find(VI.getGUID());
416 if (GVS == DefinedGVSummaries.end())
417 return true;
418 // A local definition in the destination module cannot satisfy a reference
419 // from a different module.
420 if (shouldSkipLocalInAnotherModule(GVS->second, VI.getSummaryList().size(),
421 ReferencingModule))
422 return true;
423 // We should not skip import if the module contains a non-prevailing
424 // definition with interposable linkage type. This is required for
425 // correctness in the situation where there is a prevailing def available
426 // for import and marked read-only. In this case, the non-prevailing def
427 // will be converted to a declaration, while the prevailing one becomes
428 // internal, thus no definitions will be available for linking. In order to
429 // prevent undefined symbol link error, the prevailing definition must be
430 // imported.
431 // FIXME: Consider adding a check that the suitable prevailing definition
432 // exists and marked read-only.
433 if (VI.getSummaryList().size() > 1 &&
434 GlobalValue::isInterposableLinkage(GVS->second->linkage()) &&
435 !IsPrevailing(VI.getGUID(), GVS->second))
436 return true;
437
438 return false;
439 }
440
441 void
442 onImportingSummaryImpl(const GlobalValueSummary &Summary,
444 for (const auto &VI : Summary.refs()) {
445 if (!shouldImportGlobal(VI, Summary.modulePath())) {
447 dbgs() << "Ref ignored! Target already in destination module.\n");
448 continue;
449 }
450
451 LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n");
452
453 for (const auto &RefSummary : VI.getSummaryList()) {
454 const auto *GVS = dyn_cast<GlobalVarSummary>(RefSummary.get());
455 // Stop looking if this is not a global variable, e.g. a function.
456 // Functions could be referenced by global vars - e.g. a vtable; but we
457 // don't currently imagine a reason those would be imported here, rather
458 // than as part of the logic deciding which functions to import (i.e.
459 // based on profile information). Should we decide to handle them here,
460 // we can refactor accordingly at that time.
461 // Note that it is safe to stop looking because the one case where we
462 // might have to import (a read/write-only global variable) cannot occur
463 // if this GUID has a non-variable summary. The only case where we even
464 // might find another summary in the list that is a variable is in the
465 // case of same-named locals in different modules not compiled with
466 // enough path, and during attribute propagation we will mark all
467 // summaries for a GUID (ValueInfo) as non read/write-only if any is not
468 // a global variable.
469 if (!GVS)
470 break;
471 bool CanImportDecl = false;
472 if (shouldSkipLocalInAnotherModule(GVS, VI.getSummaryList().size(),
473 Summary.modulePath()) ||
474 !Index.canImportGlobalVar(GVS, /* AnalyzeRefs */ true,
475 CanImportDecl)) {
476 if (ImportDeclaration && CanImportDecl)
477 ImportList.maybeAddDeclaration(RefSummary->modulePath(),
478 VI.getGUID());
479
480 continue;
481 }
482
483 // If there isn't an entry for GUID, insert <GUID, Definition> pair.
484 // Otherwise, definition should take precedence over declaration.
485 if (ImportList.addDefinition(RefSummary->modulePath(), VI.getGUID()) !=
487 break;
488
489 // Only update stat and exports if we haven't already imported this
490 // variable.
491 NumImportedGlobalVarsThinLink++;
492 // Any references made by this variable will be marked exported
493 // later, in ComputeCrossModuleImport, after import decisions are
494 // complete, which is more efficient than adding them here.
495 if (ExportLists)
496 (*ExportLists)[RefSummary->modulePath()].insert(VI);
497
498 // If variable is not writeonly we attempt to recursively analyze
499 // its references in order to import referenced constants.
500 if (!Index.isWriteOnly(GVS))
501 Worklist.emplace_back(GVS);
502 break;
503 }
504 }
505 }
506
507public:
509 const ModuleSummaryIndex &Index, const GVSummaryMapTy &DefinedGVSummaries,
511 IsPrevailing,
514 : Index(Index), DefinedGVSummaries(DefinedGVSummaries),
515 IsPrevailing(IsPrevailing), ImportList(ImportList),
516 ExportLists(ExportLists) {}
517
520 onImportingSummaryImpl(Summary, Worklist);
521 while (!Worklist.empty())
522 onImportingSummaryImpl(*Worklist.pop_back_val(), Worklist);
523 }
524};
525
527
528/// Determine the list of imports and exports for each module.
530 void computeImportForFunction(
531 const FunctionSummary &Summary, unsigned Threshold,
532 const GVSummaryMapTy &DefinedGVSummaries,
533 SmallVectorImpl<EdgeInfo> &Worklist, GlobalsImporter &GVImporter,
535 FunctionImporter::ImportThresholdsTy &ImportThresholds);
536
537protected:
542 // Values exported because a declaration of them is required in an importing
543 // module (see RequiresDeclImport in computeImportForFunction). These are
544 // tracked separately from ExportLists, as unlike values exported because of
545 // an imported definition, their own references and calls should not be
546 // exported.
548
555 virtual bool canImport(ValueInfo VI) { return true; }
556
557 /// Import a declaration of the callee \p VI of a call edge requiring a
558 /// declaration import (see RequiresDeclImport in computeImportForFunction),
559 /// from a function in \p CallerModulePath that is defined in or being
560 /// imported into the current module, and isn't already defined in the
561 /// current module. This is called when the callee definition is not being
562 /// imported via that edge, and the callee summaries have not already been
563 /// qualified by selectCallee (see addRequiredDeclaration). If the
564 /// definition is (or is subsequently) imported via another edge, it takes
565 /// precedence over the declaration.
566 void importRequiredDeclaration(ValueInfo VI, StringRef CallerModulePath,
568
569 /// Import a declaration of the callee \p VI from the module containing
570 /// \p DeclSummary, which must be a candidate that is legal to import (i.e.
571 /// for which qualifyCalleeCandidates returned ImportFailureReason::None, as
572 /// is the case for the SummaryForDeclImport returned by selectCallee), and
573 /// mark it exported from that module. Does nothing if the callee definition
574 /// was already imported.
575 void addRequiredDeclaration(ValueInfo VI,
576 const GlobalValueSummary *DeclSummary,
578
579public:
580 virtual ~ModuleImportsManager() = default;
581
582 /// Values that must be exported from their defining modules because
583 /// declarations of them are required in importing modules.
587
588 /// Given the list of globals defined in a module, compute the list of imports
589 /// as well as the list of "exports", i.e. the list of symbols referenced from
590 /// another module (that may require promotion).
591 virtual void
592 computeImportForModule(const GVSummaryMapTy &DefinedGVSummaries,
593 StringRef ModName,
595
596 static std::unique_ptr<ModuleImportsManager>
598 IsPrevailing,
599 const ModuleSummaryIndex &Index,
601 nullptr);
602};
603
604/// A ModuleImportsManager that operates based on a workload definition (see
605/// -thinlto-workload-def). For modules that do not define workload roots, it
606/// applies the base ModuleImportsManager import policy.
608 // Keep a module name -> value infos to import association. We use it to
609 // determine if a module's import list should be done by the base
610 // ModuleImportsManager or by us.
612 // Track the roots to avoid importing them due to other callers. We want there
613 // to be only one variant), for which we optimize according to the contextual
614 // profile. "Variants" refers to copies due to importing - we want there to be
615 // just one instance of this function.
617
618 void
619 computeImportForModule(const GVSummaryMapTy &DefinedGVSummaries,
620 StringRef ModName,
621 FunctionImporter::ImportMapTy &ImportList) override {
622 StringRef Filename = ModName;
624 Filename = sys::path::filename(ModName);
625 // Drop the file extension.
626 Filename = Filename.substr(0, Filename.find_last_of('.'));
627 }
628 auto SetIter = Workloads.find(Filename);
629
630 if (SetIter == Workloads.end()) {
631 LLVM_DEBUG(dbgs() << "[Workload] " << ModName
632 << " does not contain the root of any context.\n");
633 return ModuleImportsManager::computeImportForModule(DefinedGVSummaries,
634 ModName, ImportList);
635 }
636 LLVM_DEBUG(dbgs() << "[Workload] " << ModName
637 << " contains the root(s) of context(s).\n");
638
639 GlobalsImporter GVI(Index, DefinedGVSummaries, IsPrevailing, ImportList,
641 auto &ValueInfos = SetIter->second;
642 for (auto &VI : llvm::make_early_inc_range(ValueInfos)) {
643 auto It = DefinedGVSummaries.find(VI.getGUID());
644 if (It != DefinedGVSummaries.end() &&
645 IsPrevailing(VI.getGUID(), It->second)) {
647 dbgs() << "[Workload] " << VI.name()
648 << " has the prevailing variant already in the module "
649 << ModName << ". No need to import\n");
650 continue;
651 }
652 auto Candidates =
653 qualifyCalleeCandidates(Index, VI.getSummaryList(), ModName);
654
655 const GlobalValueSummary *GVS = nullptr;
656 auto PotentialCandidates = llvm::map_range(
658 Candidates,
659 [&](const auto &Candidate) {
660 LLVM_DEBUG(dbgs() << "[Workflow] Candidate for " << VI.name()
661 << " from " << Candidate.second->modulePath()
662 << " ImportFailureReason: "
663 << getFailureName(Candidate.first) << "\n");
664 return Candidate.first ==
666 }),
667 [](const auto &Candidate) { return Candidate.second; });
668 if (PotentialCandidates.empty()) {
669 LLVM_DEBUG(dbgs() << "[Workload] Not importing " << VI.name()
670 << " because can't find eligible Callee. Guid is: "
671 << VI.getGUID() << "\n");
672 continue;
673 }
674 /// We will prefer importing the prevailing candidate, if not, we'll
675 /// still pick the first available candidate. The reason we want to make
676 /// sure we do import the prevailing candidate is because the goal of
677 /// workload-awareness is to enable optimizations specializing the call
678 /// graph of that workload. Suppose a function is already defined in the
679 /// module, but it's not the prevailing variant. Suppose also we do not
680 /// inline it (in fact, if it were interposable, we can't inline it),
681 /// but we could specialize it to the workload in other ways. However,
682 /// the linker would drop it in the favor of the prevailing copy.
683 /// Instead, by importing the prevailing variant (assuming also the use
684 /// of `-avail-extern-to-local`), we keep the specialization. We could
685 /// alteranatively make the non-prevailing variant local, but the
686 /// prevailing one is also the one for which we would have previously
687 /// collected profiles, making it preferrable.
688 auto PrevailingCandidates = llvm::make_filter_range(
689 PotentialCandidates, [&](const auto *Candidate) {
690 return IsPrevailing(VI.getGUID(), Candidate);
691 });
692 if (PrevailingCandidates.empty()) {
693 GVS = *PotentialCandidates.begin();
694 if (!llvm::hasSingleElement(PotentialCandidates) &&
697 dbgs()
698 << "[Workload] Found multiple non-prevailing candidates for "
699 << VI.name()
700 << ". This is unexpected. Are module paths passed to the "
701 "compiler unique for the modules passed to the linker?");
702 // We could in theory have multiple (interposable) copies of a symbol
703 // when there is no prevailing candidate, if say the prevailing copy was
704 // in a native object being linked in. However, we should in theory be
705 // marking all of these non-prevailing IR copies dead in that case, in
706 // which case they won't be candidates.
707 assert(GVS->isLive());
708 } else {
709 assert(llvm::hasSingleElement(PrevailingCandidates));
710 GVS = *PrevailingCandidates.begin();
711 }
712
713 auto ExportingModule = GVS->modulePath();
714 // We checked that for the prevailing case, but if we happen to have for
715 // example an internal that's defined in this module, it'd have no
716 // PrevailingCandidates.
717 if (ExportingModule == ModName) {
718 LLVM_DEBUG(dbgs() << "[Workload] Not importing " << VI.name()
719 << " because its defining module is the same as the "
720 "current module\n");
721 continue;
722 }
723 LLVM_DEBUG(dbgs() << "[Workload][Including]" << VI.name() << " from "
724 << ExportingModule << " : " << VI.getGUID() << "\n");
725 ImportList.addDefinition(ExportingModule, VI.getGUID());
726 GVI.onImportingSummary(*GVS);
727 if (ExportLists)
728 (*ExportLists)[ExportingModule].insert(VI);
729 }
730 LLVM_DEBUG(dbgs() << "[Workload] Done\n");
731 }
732
733 void loadFromJson() {
734 // Since the workload def uses names, we need a quick lookup
735 // name->ValueInfo.
736 StringMap<ValueInfo> NameToValueInfo;
737 StringSet<> AmbiguousNames;
738 for (auto &I : Index) {
739 ValueInfo VI = Index.getValueInfo(I);
740 if (!NameToValueInfo.insert(std::make_pair(VI.name(), VI)).second)
741 LLVM_DEBUG(AmbiguousNames.insert(VI.name()));
742 }
743 auto DbgReportIfAmbiguous = [&](StringRef Name) {
744 LLVM_DEBUG(if (AmbiguousNames.count(Name) > 0) {
745 dbgs() << "[Workload] Function name " << Name
746 << " present in the workload definition is ambiguous. Consider "
747 "compiling with -funique-internal-linkage-names.";
748 });
749 };
750 std::error_code EC;
752 if (std::error_code EC = BufferOrErr.getError()) {
753 report_fatal_error("Failed to open context file");
754 return;
755 }
756 auto Buffer = std::move(BufferOrErr.get());
757 std::map<std::string, std::vector<std::string>> WorkloadDefs;
758 json::Path::Root NullRoot;
759 // The JSON is supposed to contain a dictionary matching the type of
760 // WorkloadDefs. For example:
761 // {
762 // "rootFunction_1": ["function_to_import_1", "function_to_import_2"],
763 // "rootFunction_2": ["function_to_import_3", "function_to_import_4"]
764 // }
765 auto Parsed = json::parse(Buffer->getBuffer());
766 if (!Parsed)
767 report_fatal_error(Parsed.takeError());
768 if (!json::fromJSON(*Parsed, WorkloadDefs, NullRoot))
769 report_fatal_error("Invalid thinlto contextual profile format.");
770 for (const auto &Workload : WorkloadDefs) {
771 const auto &Root = Workload.first;
772 DbgReportIfAmbiguous(Root);
773 LLVM_DEBUG(dbgs() << "[Workload] Root: " << Root << "\n");
774 const auto &AllCallees = Workload.second;
775 auto RootIt = NameToValueInfo.find(Root);
776 if (RootIt == NameToValueInfo.end()) {
777 LLVM_DEBUG(dbgs() << "[Workload] Root " << Root
778 << " not found in this linkage unit.\n");
779 continue;
780 }
781 auto RootVI = RootIt->second;
782 if (RootVI.getSummaryList().size() != 1) {
783 LLVM_DEBUG(dbgs() << "[Workload] Root " << Root
784 << " should have exactly one summary, but has "
785 << RootVI.getSummaryList().size() << ". Skipping.\n");
786 continue;
787 }
788 StringRef RootDefiningModule =
789 RootVI.getSummaryList().front()->modulePath();
790 LLVM_DEBUG(dbgs() << "[Workload] Root defining module for " << Root
791 << " is : " << RootDefiningModule << "\n");
792 auto &Set = Workloads[RootDefiningModule];
793 for (const auto &Callee : AllCallees) {
794 LLVM_DEBUG(dbgs() << "[Workload] " << Callee << "\n");
795 DbgReportIfAmbiguous(Callee);
796 auto ElemIt = NameToValueInfo.find(Callee);
797 if (ElemIt == NameToValueInfo.end()) {
798 LLVM_DEBUG(dbgs() << "[Workload] " << Callee << " not found\n");
799 continue;
800 }
801 Set.insert(ElemIt->second);
802 }
803 }
804 }
805
806 void loadFromCtxProf() {
807 std::error_code EC;
809 if (std::error_code EC = BufferOrErr.getError()) {
810 report_fatal_error("Failed to open contextual profile file");
811 return;
812 }
813 auto Buffer = std::move(BufferOrErr.get());
814
815 PGOCtxProfileReader Reader(Buffer->getBuffer());
816 auto Ctx = Reader.loadProfiles();
817 if (!Ctx) {
818 report_fatal_error("Failed to parse contextual profiles");
819 return;
820 }
821 const auto &CtxMap = Ctx->Contexts;
822 SetVector<GlobalValue::GUID> ContainedGUIDs;
823 for (const auto &[RootGuid, Root] : CtxMap) {
824 // Avoid ContainedGUIDs to get in/out of scope. Reuse its memory for
825 // subsequent roots, but clear its contents.
826 ContainedGUIDs.clear();
827
828 auto RootVI = Index.getValueInfo(RootGuid);
829 if (!RootVI) {
830 LLVM_DEBUG(dbgs() << "[Workload] Root " << RootGuid
831 << " not found in this linkage unit.\n");
832 continue;
833 }
834 if (RootVI.getSummaryList().size() != 1) {
835 LLVM_DEBUG(dbgs() << "[Workload] Root " << RootGuid
836 << " should have exactly one summary, but has "
837 << RootVI.getSummaryList().size() << ". Skipping.\n");
838 continue;
839 }
840 std::string RootDefiningModule =
841 RootVI.getSummaryList().front()->modulePath().str();
843 RootDefiningModule = std::to_string(RootGuid);
845 dbgs() << "[Workload] Moving " << RootGuid
846 << " to a module with the filename without extension : "
847 << RootDefiningModule << "\n");
848 } else {
849 LLVM_DEBUG(dbgs() << "[Workload] Root defining module for " << RootGuid
850 << " is : " << RootDefiningModule << "\n");
851 }
852 auto &Set = Workloads[RootDefiningModule];
853 Root.getContainedGuids(ContainedGUIDs);
854 Roots.insert(RootVI);
855 for (auto Guid : ContainedGUIDs)
856 if (auto VI = Index.getValueInfo(Guid))
857 Set.insert(VI);
858 }
859 }
860
861 bool canImport(ValueInfo VI) override { return !Roots.contains(VI); }
862
863public:
870 if (UseCtxProfile.empty() == WorkloadDefinitions.empty()) {
871 report_fatal_error(
872 "Pass only one of: -thinlto-pgo-ctx-prof or -thinlto-workload-def");
873 return;
874 }
875 if (!UseCtxProfile.empty())
876 loadFromCtxProf();
877 else
878 loadFromJson();
879 LLVM_DEBUG({
880 for (const auto &[Root, Set] : Workloads) {
881 dbgs() << "[Workload] Root: " << Root << " we have " << Set.size()
882 << " distinct callees.\n";
883 for (const auto &VI : Set) {
884 dbgs() << "[Workload] Root: " << Root
885 << " Would include: " << VI.getGUID() << "\n";
886 }
887 }
888 });
889 }
890};
891
892std::unique_ptr<ModuleImportsManager> ModuleImportsManager::create(
897 if (WorkloadDefinitions.empty() && UseCtxProfile.empty()) {
898 LLVM_DEBUG(dbgs() << "[Workload] Using the regular imports manager.\n");
899 return std::unique_ptr<ModuleImportsManager>(
901 }
902 LLVM_DEBUG(dbgs() << "[Workload] Using the contextual imports manager.\n");
903 return std::make_unique<WorkloadImportsManager>(IsPrevailing, Index,
905}
906
907static const char *
909 switch (Reason) {
911 return "None";
913 return "GlobalVar";
915 return "NotLive";
917 return "TooLarge";
919 return "InterposableLinkage";
921 return "LocalLinkageNotInModule";
923 return "NotEligible";
925 return "NoInline";
926 }
927 llvm_unreachable("invalid reason");
928}
929
930/// Compute the list of functions to import for a given caller. Mark these
931/// imported functions and the symbols they reference in their source module as
932/// exported from their source module.
933void ModuleImportsManager::computeImportForFunction(
934 const FunctionSummary &Summary, const unsigned Threshold,
935 const GVSummaryMapTy &DefinedGVSummaries,
936 SmallVectorImpl<EdgeInfo> &Worklist, GlobalsImporter &GVImporter,
937 FunctionImporter::ImportMapTy &ImportList,
938 FunctionImporter::ImportThresholdsTy &ImportThresholds) {
939 GVImporter.onImportingSummary(Summary);
940 static int ImportCount = 0;
941 for (const auto &Edge : Summary.calls()) {
942 ValueInfo VI = Edge.first;
943 LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold
944 << "\n");
945
946 // Whether at least a declaration of the callee must be imported (and the
947 // callee exported from its defining module) if its definition is not
948 // imported. This is the case when the edge was marked as requiring a
949 // declaration import (e.g. for MemProf ICP), or when declaration imports
950 // are enabled via -import-declaration for an indirect call edge, since the
951 // backend may then promote the indirect call to the imported declaration
952 // (e.g. regular ICP under -icp-allow-decls), which requires that the
953 // callee not be internalized. Callees of direct calls don't need to be
954 // exported here, since they are either referenced directly from the
955 // destination module, in which case they are already treated as visible
956 // outside their defining module, or from an imported definition, in which
957 // case they are marked exported in ComputeCrossModuleImport.
958 const bool RequiresDeclImport =
959 Edge.second.requiresDeclImport() ||
960 (ImportDeclaration && Edge.second.hasIndirectCall());
961
962 if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
963 LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
964 << " reached.\n");
965 // Still import a declaration if one is required, as that doesn't
966 // affect the import cutoff count.
967 if (RequiresDeclImport && !DefinedGVSummaries.count(VI.getGUID()))
968 importRequiredDeclaration(VI, Summary.modulePath(), ImportList);
969 continue;
970 }
971
972 if (DefinedGVSummaries.count(VI.getGUID())) {
973 // FIXME: Consider not skipping import if the module contains
974 // a non-prevailing def with interposable linkage. The prevailing copy
975 // can safely be imported (see shouldImportGlobal()).
976 LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n");
977 continue;
978 }
979
980 if (!canImport(VI)) {
982 dbgs() << "Skipping over " << VI.getGUID()
983 << " because its import is handled in a different module.");
984 assert(VI.getSummaryList().size() == 1 &&
985 "The root was expected to be an external symbol");
986 continue;
987 }
988
989 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
990 if (Hotness == CalleeInfo::HotnessType::Hot)
991 return ImportHotMultiplier;
992 if (Hotness == CalleeInfo::HotnessType::Cold)
996 return 1.0;
997 };
998
999 const auto NewThreshold =
1000 Threshold * GetBonusMultiplier(Edge.second.getHotness());
1001
1002 auto IT = ImportThresholds.insert(std::make_pair(
1003 VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr)));
1004 bool PreviouslyVisited = !IT.second;
1005 auto &ProcessedThreshold = std::get<0>(IT.first->second);
1006 auto &CalleeSummary = std::get<1>(IT.first->second);
1007 auto &FailureInfo = std::get<2>(IT.first->second);
1008
1009 bool IsHotCallsite =
1010 Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
1011 bool IsCriticalCallsite =
1012 Edge.second.getHotness() == CalleeInfo::HotnessType::Critical;
1013
1014 const FunctionSummary *ResolvedCalleeSummary = nullptr;
1015 if (CalleeSummary) {
1016 assert(PreviouslyVisited);
1017 // Since the traversal of the call graph is DFS, we can revisit a function
1018 // a second time with a higher threshold. In this case, it is added back
1019 // to the worklist with the new threshold (so that its own callee chains
1020 // can be considered with the higher threshold).
1021 if (NewThreshold <= ProcessedThreshold) {
1022 LLVM_DEBUG(
1023 dbgs() << "ignored! Target was already imported with Threshold "
1024 << ProcessedThreshold << "\n");
1025 continue;
1026 }
1027 // Update with new larger threshold.
1028 ProcessedThreshold = NewThreshold;
1029 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
1030 } else {
1031 // If we already rejected importing a callee at the same or higher
1032 // threshold, don't waste time calling selectCallee.
1033 if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
1034 LLVM_DEBUG(
1035 dbgs() << "ignored! Target was already rejected with Threshold "
1036 << ProcessedThreshold << "\n");
1037 if (PrintImportFailures) {
1038 assert(FailureInfo &&
1039 "Expected FailureInfo for previously rejected candidate");
1040 FailureInfo->Attempts++;
1041 }
1042 // The callee definition was rejected when reached via a different
1043 // edge, but this edge may require that a declaration be imported and
1044 // exported.
1045 if (RequiresDeclImport)
1046 importRequiredDeclaration(VI, Summary.modulePath(), ImportList);
1047 continue;
1048 }
1049
1051
1052 // `SummaryForDeclImport` is an summary eligible for declaration import.
1053 const GlobalValueSummary *SummaryForDeclImport = nullptr;
1054 CalleeSummary =
1055 selectCallee(Index, VI.getSummaryList(), NewThreshold,
1056 Summary.modulePath(), SummaryForDeclImport, Reason);
1057 if (!CalleeSummary) {
1058 // There isn't a callee for definition import but one for declaration
1059 // import.
1060 if (SummaryForDeclImport) {
1061 if (RequiresDeclImport)
1062 // This also marks the callee exported.
1063 addRequiredDeclaration(VI, SummaryForDeclImport, ImportList);
1064 else if (ImportDeclaration)
1065 // Not exported, see the comments where RequiresDeclImport is set.
1066 ImportList.maybeAddDeclaration(SummaryForDeclImport->modulePath(),
1067 VI.getGUID());
1068 }
1069 // Update with new larger threshold if this was a retry (otherwise
1070 // we would have already inserted with NewThreshold above). Also
1071 // update failure info if requested.
1072 if (PreviouslyVisited) {
1073 ProcessedThreshold = NewThreshold;
1074 if (PrintImportFailures) {
1075 assert(FailureInfo &&
1076 "Expected FailureInfo for previously rejected candidate");
1077 FailureInfo->Reason = Reason;
1078 FailureInfo->Attempts++;
1079 FailureInfo->MaxHotness =
1080 std::max(FailureInfo->MaxHotness, Edge.second.getHotness());
1081 }
1082 } else if (PrintImportFailures) {
1083 assert(!FailureInfo &&
1084 "Expected no FailureInfo for newly rejected candidate");
1085 FailureInfo = std::make_unique<FunctionImporter::ImportFailureInfo>(
1086 VI, Edge.second.getHotness(), Reason, 1);
1087 }
1088 if (ForceImportAll) {
1089 std::string Msg = std::string("Failed to import function ") +
1090 VI.name().str() + " due to " +
1091 getFailureName(Reason);
1094 logAllUnhandledErrors(std::move(Error), errs(),
1095 "Error importing module: ");
1096 break;
1097 } else {
1099 << "ignored! No qualifying callee with summary found.\n");
1100 continue;
1101 }
1102 }
1103
1104 // "Resolve" the summary
1105 CalleeSummary = CalleeSummary->getBaseObject();
1106 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
1107
1108 assert((ResolvedCalleeSummary->fflags().AlwaysInline || ForceImportAll ||
1109 (ResolvedCalleeSummary->instCount() <= NewThreshold)) &&
1110 "selectCallee() didn't honor the threshold");
1111
1112 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
1113
1114 // Try emplace the definition entry, and update stats based on insertion
1115 // status.
1116 if (ImportList.addDefinition(ExportModulePath, VI.getGUID()) !=
1118 NumImportedFunctionsThinLink++;
1119 if (IsHotCallsite)
1120 NumImportedHotFunctionsThinLink++;
1121 if (IsCriticalCallsite)
1122 NumImportedCriticalFunctionsThinLink++;
1123 }
1124
1125 // Any calls/references made by this function will be marked exported
1126 // later, in ComputeCrossModuleImport, after import decisions are
1127 // complete, which is more efficient than adding them here.
1128 if (ExportLists)
1129 (*ExportLists)[ExportModulePath].insert(VI);
1130 }
1131
1132 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
1133 // Adjust the threshold for next level of imported functions.
1134 // The threshold is different for hot callsites because we can then
1135 // inline chains of hot calls.
1136 if (IsHotCallsite)
1137 return Threshold * ImportHotInstrFactor;
1138 return Threshold * ImportInstrFactor;
1139 };
1140
1141 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
1142
1143 ImportCount++;
1144
1145 // Insert the newly imported function to the worklist.
1146 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold);
1147 }
1148}
1149
1151 const GVSummaryMapTy &DefinedGVSummaries, StringRef ModName,
1152 FunctionImporter::ImportMapTy &ImportList) {
1153 // Worklist contains the list of function imported in this module, for which
1154 // we will analyse the callees and may import further down the callgraph.
1156 GlobalsImporter GVI(Index, DefinedGVSummaries, IsPrevailing, ImportList,
1157 ExportLists);
1158 FunctionImporter::ImportThresholdsTy ImportThresholds;
1159
1160 // Populate the worklist with the import for the functions in the current
1161 // module
1162 for (const auto &GVSummary : DefinedGVSummaries) {
1163#ifndef NDEBUG
1164 // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID
1165 // so this map look up (and possibly others) can be avoided.
1166 auto VI = Index.getValueInfo(GVSummary.first);
1167#endif
1168 if (!Index.isGlobalValueLive(GVSummary.second)) {
1169 LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n");
1170 continue;
1171 }
1172 auto *FuncSummary =
1173 dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
1174 if (!FuncSummary)
1175 // Skip import for global variables
1176 continue;
1177 LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n");
1178 computeImportForFunction(*FuncSummary, ImportInstrLimit, DefinedGVSummaries,
1179 Worklist, GVI, ImportList, ImportThresholds);
1180 }
1181
1182 // Process the newly imported functions and add callees to the worklist.
1183 while (!Worklist.empty()) {
1184 auto GVInfo = Worklist.pop_back_val();
1185 auto *Summary = std::get<0>(GVInfo);
1186 auto Threshold = std::get<1>(GVInfo);
1187
1188 computeImportForFunction(*Summary, Threshold, DefinedGVSummaries, Worklist,
1189 GVI, ImportList, ImportThresholds);
1190 }
1191
1192 // Print stats about functions considered but rejected for importing
1193 // when requested.
1194 if (PrintImportFailures) {
1195 dbgs() << "Missed imports into module " << ModName << "\n";
1196 for (auto &I : ImportThresholds) {
1197 auto &ProcessedThreshold = std::get<0>(I.second);
1198 auto &CalleeSummary = std::get<1>(I.second);
1199 auto &FailureInfo = std::get<2>(I.second);
1200 if (CalleeSummary)
1201 continue; // We are going to import.
1202 assert(FailureInfo);
1203 FunctionSummary *FS = nullptr;
1204 if (!FailureInfo->VI.getSummaryList().empty())
1206 FailureInfo->VI.getSummaryList()[0]->getBaseObject());
1207 dbgs() << FailureInfo->VI
1208 << ": Reason = " << getFailureName(FailureInfo->Reason)
1209 << ", Threshold = " << ProcessedThreshold
1210 << ", Size = " << (FS ? (int)FS->instCount() : -1)
1211 << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness)
1212 << ", Attempts = " << FailureInfo->Attempts << "\n";
1213 }
1214 }
1215}
1216
1218 ValueInfo VI, StringRef CallerModulePath,
1219 FunctionImporter::ImportMapTy &ImportList) {
1220 // Find a callee summary that we can legally import a declaration of. Note
1221 // that qualifyCalleeCandidates only checks the legality of importing each
1222 // candidate (returning ImportFailureReason::None if legal). The additional
1223 // size and noinline checks that determine whether it is worth importing a
1224 // definition (TooLarge/NoInline) are applied separately by selectCallee, and
1225 // are not relevant for a declaration import.
1226 for (auto [Reason, CandidateSummary] :
1227 qualifyCalleeCandidates(Index, VI.getSummaryList(), CallerModulePath)) {
1230 "Expected only legality checks in qualifyCalleeCandidates");
1232 addRequiredDeclaration(VI, CandidateSummary, ImportList);
1233 return;
1234 }
1235 }
1236}
1237
1239 ValueInfo VI, const GlobalValueSummary *DeclSummary,
1240 FunctionImporter::ImportMapTy &ImportList) {
1241 StringRef SrcModule = DeclSummary->modulePath();
1242 auto ExistingImportType = ImportList.getImportType(SrcModule, VI.getGUID());
1243 // Nothing to do if we already decided to import the definition, which is
1244 // also exported.
1245 if (ExistingImportType == GlobalValueSummary::Definition)
1246 return;
1247 if (!ExistingImportType) {
1248 ImportList.maybeAddDeclaration(SrcModule, VI.getGUID());
1249 NumRequiredDeclsThinLink++;
1250 }
1251 // The declaration needs to be exported so that the callee is not
1252 // internalized, and so that locals are promoted. Note this is needed even if
1253 // we already decided to import the declaration for another reason (i.e.
1254 // -import-declaration for a direct call edge), as those declaration imports
1255 // are not exported.
1256 if (ExportLists)
1257 RequiredDeclExports[SrcModule].insert(VI);
1258}
1259
1260#ifndef NDEBUG
1261static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, ValueInfo VI) {
1262 auto SL = VI.getSummaryList();
1263 return SL.empty()
1264 ? false
1265 : SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
1266}
1267
1270 if (const auto &VI = Index.getValueInfo(G))
1271 return isGlobalVarSummary(Index, VI);
1272 return false;
1273}
1274
1275// Return the number of global variable summaries in ExportSet.
1276static unsigned
1278 FunctionImporter::ExportSetTy &ExportSet) {
1279 unsigned NumGVS = 0;
1280 for (auto &VI : ExportSet)
1281 if (isGlobalVarSummary(Index, VI.getGUID()))
1282 ++NumGVS;
1283 return NumGVS;
1284}
1285
1287 unsigned NumGVS = 0;
1288 unsigned DefinedFS = 0;
1289 unsigned Count = 0;
1290};
1291
1292// Compute import statistics for each source module in ImportList.
1295 const FunctionImporter::ImportMapTy &ImportList) {
1297
1298 for (const auto &[FromModule, GUID, Type] : ImportList) {
1299 ImportStatistics &Entry = Histogram[FromModule];
1300 ++Entry.Count;
1301 if (isGlobalVarSummary(Index, GUID))
1302 ++Entry.NumGVS;
1304 ++Entry.DefinedFS;
1305 }
1306 return Histogram;
1307}
1308#endif
1309
1310#ifndef NDEBUG
1312 const ModuleSummaryIndex &Index,
1315 DenseSet<GlobalValue::GUID> FlattenedImports;
1316
1317 for (const auto &ImportPerModule : ImportLists)
1318 for (const auto &[FromModule, GUID, ImportType] : ImportPerModule.second)
1319 FlattenedImports.insert(GUID);
1320
1321 // Checks that all GUIDs of read/writeonly vars we see in export lists
1322 // are also in the import lists. Otherwise we my face linker undefs,
1323 // because readonly and writeonly vars are internalized in their
1324 // source modules. The exception would be if it has a linkage type indicating
1325 // that there may have been a copy existing in the importing module (e.g.
1326 // linkonce_odr). In that case we cannot accurately do this checking.
1327 auto IsReadOrWriteOnlyVarNeedingImporting = [&](StringRef ModulePath,
1328 const ValueInfo &VI) {
1330 Index.findSummaryInModule(VI, ModulePath));
1331 return GVS && (Index.isReadOnly(GVS) || Index.isWriteOnly(GVS)) &&
1332 !(GVS->linkage() == GlobalValue::AvailableExternallyLinkage ||
1333 GVS->linkage() == GlobalValue::WeakODRLinkage ||
1334 GVS->linkage() == GlobalValue::LinkOnceODRLinkage);
1335 };
1336
1337 for (auto &ExportPerModule : ExportLists)
1338 for (auto &VI : ExportPerModule.second)
1339 if (!FlattenedImports.count(VI.getGUID()) &&
1340 IsReadOrWriteOnlyVarNeedingImporting(ExportPerModule.first, VI))
1341 return false;
1342
1343 return true;
1344}
1345#endif
1346
1347/// Compute all the import and export for every module using the Index.
1349 const ModuleSummaryIndex &Index,
1350 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1352 isPrevailing,
1355 auto MIS = ModuleImportsManager::create(isPrevailing, Index, &ExportLists);
1356 // For each module that has function defined, compute the import/export lists.
1357 for (const auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
1358 auto &ImportList = ImportLists[DefinedGVSummaries.first];
1359 LLVM_DEBUG(dbgs() << "Computing import for Module '"
1360 << DefinedGVSummaries.first << "'\n");
1361 MIS->computeImportForModule(DefinedGVSummaries.second,
1362 DefinedGVSummaries.first, ImportList);
1363 }
1364
1365 // When computing imports we only added the variables and functions being
1366 // imported to the export list. We also need to mark any references and calls
1367 // they make as exported as well. We do this here, as it is more efficient
1368 // since we may import the same values multiple times into different modules
1369 // during the import computation.
1370 for (auto &ELI : ExportLists) {
1371 // `NewExports` tracks the VI that gets exported because the full definition
1372 // of its user/referencer gets exported.
1374 const auto &DefinedGVSummaries =
1375 ModuleToDefinedGVSummaries.lookup(ELI.first);
1376 for (auto &EI : ELI.second) {
1377 // Find the copy defined in the exporting module so that we can mark the
1378 // values it references in that specific definition as exported.
1379 // Below we will add all references and called values, without regard to
1380 // whether they are also defined in this module. We subsequently prune the
1381 // list to only include those defined in the exporting module, see comment
1382 // there as to why.
1383 auto DS = DefinedGVSummaries.find(EI.getGUID());
1384 // Anything marked exported during the import computation must have been
1385 // defined in the exporting module.
1386 assert(DS != DefinedGVSummaries.end());
1387 auto *S = DS->getSecond();
1388 S = S->getBaseObject();
1389 if (auto *GVS = dyn_cast<GlobalVarSummary>(S)) {
1390 // Export referenced functions and variables. We don't export/promote
1391 // objects referenced by writeonly variable initializer, because
1392 // we convert such variables initializers to "zeroinitializer".
1393 // See processGlobalForThinLTO.
1394 if (!Index.isWriteOnly(GVS))
1395 NewExports.insert_range(GVS->refs());
1396 } else {
1397 auto *FS = cast<FunctionSummary>(S);
1398 NewExports.insert_range(llvm::make_first_range(FS->calls()));
1399 NewExports.insert_range(FS->refs());
1400 }
1401 }
1402 // Prune list computed above to only include values defined in the
1403 // exporting module. We do this after the above insertion since we may hit
1404 // the same ref/call target multiple times in above loop, and it is more
1405 // efficient to avoid a set lookup each time.
1406 NewExports.remove_if(
1407 [&](ValueInfo VI) { return !DefinedGVSummaries.count(VI.getGUID()); });
1408 ELI.second.insert_range(NewExports);
1409 }
1410
1411 // Now add the values exported because declarations of them are required in
1412 // importing modules. We do this after the above loop since their own
1413 // references and calls should not be exported.
1414 for (auto &[ModPath, RequiredExports] : MIS->requiredDeclExports())
1415 ExportLists[ModPath].insert_range(RequiredExports);
1416
1417 assert(checkVariableImport(Index, ImportLists, ExportLists));
1418#ifndef NDEBUG
1419 LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
1420 << " modules:\n");
1421 for (const auto &ModuleImports : ImportLists) {
1422 auto ModName = ModuleImports.first;
1423 auto &Exports = ExportLists[ModName];
1424 unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
1426 collectImportStatistics(Index, ModuleImports.second);
1427 LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports "
1428 << Exports.size() - NumGVS << " functions and " << NumGVS
1429 << " vars. Imports from " << Histogram.size()
1430 << " modules.\n");
1431 for (const auto &[SrcModName, Stats] : Histogram) {
1432 LLVM_DEBUG(dbgs() << " - " << Stats.DefinedFS
1433 << " function definitions and "
1434 << Stats.Count - Stats.NumGVS - Stats.DefinedFS
1435 << " function declarations imported from " << SrcModName
1436 << "\n");
1437 LLVM_DEBUG(dbgs() << " - " << Stats.NumGVS
1438 << " global vars imported from " << SrcModName << "\n");
1439 }
1440 }
1441#endif
1442}
1443
1444#ifndef NDEBUG
1446 StringRef ModulePath,
1447 FunctionImporter::ImportMapTy &ImportList) {
1449 collectImportStatistics(Index, ImportList);
1450 LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
1451 << Histogram.size() << " modules.\n");
1452 for (const auto &[SrcModName, Stats] : Histogram) {
1453 LLVM_DEBUG(dbgs() << " - " << Stats.DefinedFS
1454 << " function definitions and "
1455 << Stats.Count - Stats.DefinedFS - Stats.NumGVS
1456 << " function declarations imported from " << SrcModName
1457 << "\n");
1458 LLVM_DEBUG(dbgs() << " - " << Stats.NumGVS << " vars imported from "
1459 << SrcModName << "\n");
1460 }
1461}
1462#endif
1463
1464/// Compute all the imports for the given module using the Index.
1465///
1466/// \p isPrevailing is a callback that will be called with a global value's GUID
1467/// and summary and should return whether the module corresponding to the
1468/// summary contains the linker-prevailing copy of that value.
1469///
1470/// \p ImportList will be populated with a map that can be passed to
1471/// FunctionImporter::importFunctions() above (see description there).
1473 StringRef ModulePath,
1475 isPrevailing,
1476 const ModuleSummaryIndex &Index,
1477 FunctionImporter::ImportMapTy &ImportList) {
1478 // Collect the list of functions this module defines.
1479 // GUID -> Summary
1480 GVSummaryMapTy FunctionSummaryMap;
1481 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
1482
1483 // Compute the import list for this module.
1484 LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
1485 auto MIS = ModuleImportsManager::create(isPrevailing, Index);
1486 MIS->computeImportForModule(FunctionSummaryMap, ModulePath, ImportList);
1487
1488#ifndef NDEBUG
1489 dumpImportListForModule(Index, ModulePath, ImportList);
1490#endif
1491}
1492
1493/// Mark all external summaries in \p Index for import into the given module.
1494/// Used for testing the case of distributed builds using a distributed index.
1495///
1496/// \p ImportList will be populated with a map that can be passed to
1497/// FunctionImporter::importFunctions() above (see description there).
1499 StringRef ModulePath, const ModuleSummaryIndex &Index,
1500 FunctionImporter::ImportMapTy &ImportList) {
1501 for (const auto &GlobalList : Index) {
1502 // Ignore entries for undefined references.
1503 if (GlobalList.second.getSummaryList().empty())
1504 continue;
1505
1506 auto GUID = GlobalList.first;
1507 assert(GlobalList.second.getSummaryList().size() == 1 &&
1508 "Expected individual combined index to have one summary per GUID");
1509 auto &Summary = GlobalList.second.getSummaryList()[0];
1510 // Skip the summaries for the importing module. These are included to
1511 // e.g. record required linkage changes.
1512 if (Summary->modulePath() == ModulePath)
1513 continue;
1514 // Add an entry to provoke importing by thinBackend.
1515 ImportList.addGUID(Summary->modulePath(), GUID, Summary->importType());
1516 }
1517#ifndef NDEBUG
1518 dumpImportListForModule(Index, ModulePath, ImportList);
1519#endif
1520}
1521
1522// For SamplePGO, the indirect call targets for local functions will
1523// have its original name annotated in profile. We try to find the
1524// corresponding PGOFuncName as the GUID, and fix up the edges
1525// accordingly.
1527 FunctionSummary *FS) {
1528 // Returns the ValueInfo that should be used in place of \p CalleeVI, or an
1529 // empty ValueInfo if no update is needed.
1530 auto GetUpdatedCallee = [&](ValueInfo CalleeVI) -> ValueInfo {
1531 if (!CalleeVI || !CalleeVI.getSummaryList().empty())
1532 return ValueInfo();
1533 auto GUID = Index.getGUIDFromOriginalID(CalleeVI.getGUID());
1534 if (GUID == 0)
1535 return ValueInfo();
1536 auto VI = Index.getValueInfo(GUID);
1537 if (llvm::any_of(
1538 VI.getSummaryList(),
1539 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
1540 // The mapping from OriginalId to GUID may return a GUID
1541 // that corresponds to a static variable. Filter it out here.
1542 // This can happen when
1543 // 1) There is a call to a library function which is not defined
1544 // in the index.
1545 // 2) There is a static variable with the OriginalGUID identical
1546 // to the GUID of the library function in 1);
1547 // When this happens the static variable in 2) will be found,
1548 // which needs to be filtered out.
1549 return SummaryPtr->getSummaryKind() ==
1550 GlobalValueSummary::GlobalVarKind;
1551 }))
1552 return ValueInfo();
1553 return VI;
1554 };
1555
1556 for (auto &EI : FS->mutableCalls()) {
1557 // Update the edge to point directly to the correct GUID.
1558 if (auto VI = GetUpdatedCallee(EI.first))
1559 EI.first = VI;
1560 }
1561
1562 // MemProf summarizes indirect callsites by synthesizing a CallsiteInfo
1563 // record for each profiled target, using the same GUIDs found in the VP
1564 // metadata (which, for local targets, may be the original name GUID when
1565 // e.g. synthesized from the MemProf profile or from a SamplePGO profile).
1566 // Update those callees as well so that they are consistent with the call
1567 // edges above, and so that the thin link's MemProf context disambiguation
1568 // can correlate the callsite with the summary for the target function.
1569 if (FS->callsites().empty())
1570 return;
1571 for (auto &CI : FS->mutableCallsites()) {
1572 if (auto VI = GetUpdatedCallee(CI.Callee))
1573 CI.Callee = VI;
1574 }
1575}
1576
1578 for (const auto &Entry : Index) {
1579 for (const auto &S : Entry.second.getSummaryList()) {
1580 if (auto *FS = dyn_cast<FunctionSummary>(S.get()))
1582 }
1583 }
1584}
1585
1587 ModuleSummaryIndex &Index,
1588 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
1590 assert(!Index.withGlobalValueDeadStripping());
1591 if (!ComputeDead ||
1592 // Don't do anything when nothing is live, this is friendly with tests.
1593 GUIDPreservedSymbols.empty()) {
1594 // Still need to update indirect calls.
1595 updateIndirectCalls(Index);
1596 return;
1597 }
1598 unsigned LiveSymbols = 0;
1600 Worklist.reserve(GUIDPreservedSymbols.size() * 2);
1601 for (auto GUID : GUIDPreservedSymbols) {
1602 ValueInfo VI = Index.getValueInfo(GUID);
1603 if (!VI)
1604 continue;
1605 for (const auto &S : VI.getSummaryList())
1606 S->setLive(true);
1607 }
1608
1609 // Add values flagged in the index as live roots to the worklist.
1610 for (const auto &Entry : Index) {
1611 auto VI = Index.getValueInfo(Entry);
1612 for (const auto &S : Entry.second.getSummaryList()) {
1613 if (auto *FS = dyn_cast<FunctionSummary>(S.get()))
1615 if (S->isLive()) {
1616 LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n");
1617 Worklist.push_back(VI);
1618 ++LiveSymbols;
1619 break;
1620 }
1621 }
1622 }
1623
1624 // Make value live and add it to the worklist if it was not live before.
1625 auto visit = [&](ValueInfo VI, bool IsAliasee) {
1626 // FIXME: If we knew which edges were created for indirect call profiles,
1627 // we could skip them here. Any that are live should be reached via
1628 // other edges, e.g. reference edges. Otherwise, using a profile collected
1629 // on a slightly different binary might provoke preserving, importing
1630 // and ultimately promoting calls to functions not linked into this
1631 // binary, which increases the binary size unnecessarily. Note that
1632 // if this code changes, the importer needs to change so that edges
1633 // to functions marked dead are skipped.
1634
1635 if (llvm::any_of(VI.getSummaryList(),
1636 [](const std::unique_ptr<llvm::GlobalValueSummary> &S) {
1637 return S->isLive();
1638 }))
1639 return;
1640
1641 // We only keep live symbols that are known to be non-prevailing if any are
1642 // available_externally, linkonceodr, weakodr. Those symbols are discarded
1643 // later in the EliminateAvailableExternally pass and setting them to
1644 // not-live could break downstreams users of liveness information (PR36483)
1645 // or limit optimization opportunities.
1646 if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
1647 bool KeepAliveLinkage = false;
1648 bool Interposable = false;
1649 for (const auto &S : VI.getSummaryList()) {
1650 if (S->linkage() == GlobalValue::AvailableExternallyLinkage ||
1651 S->linkage() == GlobalValue::WeakODRLinkage ||
1652 S->linkage() == GlobalValue::LinkOnceODRLinkage)
1653 KeepAliveLinkage = true;
1654 else if (GlobalValue::isInterposableLinkage(S->linkage()))
1655 Interposable = true;
1656 }
1657
1658 if (!IsAliasee) {
1659 if (!KeepAliveLinkage)
1660 return;
1661
1662 if (Interposable)
1664 "Interposable and available_externally/linkonce_odr/weak_odr "
1665 "symbol");
1666 }
1667 }
1668
1669 for (const auto &S : VI.getSummaryList())
1670 S->setLive(true);
1671 ++LiveSymbols;
1672 Worklist.push_back(VI);
1673 };
1674
1675 while (!Worklist.empty()) {
1676 auto VI = Worklist.pop_back_val();
1677 for (const auto &Summary : VI.getSummaryList()) {
1678 if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
1679 // If this is an alias, visit the aliasee VI to ensure that all copies
1680 // are marked live and it is added to the worklist for further
1681 // processing of its references.
1682 visit(AS->getAliaseeVI(), true);
1683 continue;
1684 }
1685 for (auto Ref : Summary->refs())
1686 visit(Ref, false);
1687 if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
1688 for (auto Call : FS->calls())
1689 visit(Call.first, false);
1690 }
1691 }
1692 Index.setWithGlobalValueDeadStripping();
1693
1694 unsigned DeadSymbols = Index.size() - LiveSymbols;
1695 LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
1696 << " symbols Dead \n");
1697 NumDeadSymbols += DeadSymbols;
1698 NumLiveSymbols += LiveSymbols;
1699}
1700
1701// Compute dead symbols and propagate constants in combined index.
1703 ModuleSummaryIndex &Index,
1704 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
1706 bool ImportEnabled) {
1707 llvm::TimeTraceScope timeScope("Drop dead symbols and propagate attributes");
1708 computeDeadSymbolsAndUpdateIndirectCalls(Index, GUIDPreservedSymbols,
1709 isPrevailing);
1710 if (ImportEnabled)
1711 Index.propagateAttributes(GUIDPreservedSymbols);
1712}
1713
1714/// Compute the set of summaries needed for a ThinLTO backend compilation of
1715/// \p ModulePath.
1717 StringRef ModulePath,
1718 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1719 const FunctionImporter::ImportMapTy &ImportList,
1720 ModuleToSummariesForIndexTy &ModuleToSummariesForIndex,
1721 GVSummaryPtrSet &DecSummaries) {
1722 // Include all summaries from the importing module.
1723 ModuleToSummariesForIndex[std::string(ModulePath)] =
1724 ModuleToDefinedGVSummaries.lookup(ModulePath);
1725
1726 // Forward port the heterogeneous std::map::operator[]() from C++26, which
1727 // lets us look up the map without allocating an instance of std::string when
1728 // the key-value pair exists in the map.
1729 // TODO: Remove this in favor of the heterogenous std::map::operator[]() from
1730 // C++26 when it becomes available for our codebase.
1731 auto LookupOrCreate = [](ModuleToSummariesForIndexTy &Map,
1733 auto It = Map.find(Key);
1734 if (It == Map.end())
1735 std::tie(It, std::ignore) =
1736 Map.try_emplace(std::string(Key), GVSummaryMapTy());
1737 return It->second;
1738 };
1739
1740 // Include summaries for imports.
1741 for (const auto &[FromModule, GUID, ImportType] : ImportList) {
1742 auto &SummariesForIndex =
1743 LookupOrCreate(ModuleToSummariesForIndex, FromModule);
1744
1745 const auto &DefinedGVSummaries = ModuleToDefinedGVSummaries.at(FromModule);
1746 const auto &DS = DefinedGVSummaries.find(GUID);
1747 assert(DS != DefinedGVSummaries.end() &&
1748 "Expected a defined summary for imported global value");
1749 if (ImportType == GlobalValueSummary::Declaration)
1750 DecSummaries.insert(DS->second);
1751
1752 SummariesForIndex[GUID] = DS->second;
1753 }
1754
1755 // When AlwaysRenamePromotedLocals is false, for each source module we import
1756 // from, also include summaries for local functions that have
1757 // NoRenameOnPromotion set. This is needed for distributed ThinLTO. Otherwise,
1758 // the local function of the source module will keep its origin name, e.g.,
1759 // foo() while the function in destination module will have name
1760 // foo.llvm.<...>() and this will cause a link failure.
1761 //
1762 // Note: this imports a superset of the necessary declarations — all locals
1763 // with NoRenameOnPromotion in each source module, not just those referenced
1764 // by the importing module. Computing the precise set would require walking
1765 // the summary reference graph from each imported function, which is more
1766 // expensive than the simple scan here.
1768 for (auto &[ModPath, SummariesForIndex] : ModuleToSummariesForIndex) {
1769 if (ModPath == ModulePath)
1770 continue;
1771 auto It = ModuleToDefinedGVSummaries.find(ModPath);
1772 if (It == ModuleToDefinedGVSummaries.end())
1773 continue;
1774 for (const auto &[GUID, Summary] : It->second) {
1775 if (Summary->noRenameOnPromotion()) {
1776 DecSummaries.insert(Summary);
1777 SummariesForIndex.try_emplace(GUID, Summary);
1778 }
1779 }
1780 }
1781 }
1782}
1783
1784/// Emit the files \p ModulePath will import from into \p OutputFilename.
1787 const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex) {
1788 std::error_code EC;
1790 if (EC)
1791 return createFileError("cannot open " + OutputFilename,
1792 errorCodeToError(EC));
1793 processImportsFiles(ModulePath, ModuleToSummariesForIndex,
1794 [&](StringRef M) { ImportsOS << M << "\n"; });
1795 return Error::success();
1796}
1797
1798/// Invoke callback \p F on the file paths from which \p ModulePath
1799/// will import.
1801 StringRef ModulePath,
1802 const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex,
1803 function_ref<void(const std::string &)> F) {
1804 for (const auto &ILI : ModuleToSummariesForIndex)
1805 // The ModuleToSummariesForIndex map includes an entry for the current
1806 // Module (needed for writing out the index files). We don't want to
1807 // include it in the imports file, however, so filter it out.
1808 if (ILI.first != ModulePath)
1809 F(ILI.first);
1810}
1811
1813 LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
1814 << "\n");
1815 MDNode *UniqueID = nullptr;
1816 if (auto *GO = dyn_cast<GlobalObject>(&GV))
1817 UniqueID = GO->getMetadata(LLVMContext::MD_guid);
1818
1819 if (Function *F = dyn_cast<Function>(&GV)) {
1820 F->deleteBody();
1821 F->clearMetadata();
1822 if (UniqueID)
1823 F->setMetadata(LLVMContext::MD_guid, UniqueID);
1824 F->setComdat(nullptr);
1825 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
1826 V->setInitializer(nullptr);
1827 V->setLinkage(GlobalValue::ExternalLinkage);
1828 V->clearMetadata();
1829 if (UniqueID)
1830 V->setMetadata(LLVMContext::MD_guid, UniqueID);
1831 V->setComdat(nullptr);
1832 } else {
1833 GlobalValue *NewGV;
1834 if (GV.getValueType()->isFunctionTy())
1835 NewGV =
1838 "", GV.getParent());
1839 else
1840 NewGV =
1841 new GlobalVariable(*GV.getParent(), GV.getValueType(),
1842 /*isConstant*/ false, GlobalValue::ExternalLinkage,
1843 /*init*/ nullptr, "",
1844 /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
1845 GV.getType()->getAddressSpace());
1846 NewGV->takeName(&GV);
1847 GV.replaceAllUsesWith(NewGV);
1848 return false;
1849 }
1850 if (!GV.isImplicitDSOLocal())
1851 GV.setDSOLocal(false);
1852 return true;
1853}
1854
1856 const GVSummaryMapTy &DefinedGlobals,
1857 bool PropagateAttrs) {
1858 llvm::TimeTraceScope timeScope("ThinLTO finalize in module");
1859 DenseSet<Comdat *> NonPrevailingComdats;
1860 auto FinalizeInModule = [&](GlobalValue &GV, bool Propagate = false) {
1861 // See if the global summary analysis computed a new resolved linkage.
1862 const auto &GS = DefinedGlobals.find(GV.getGUIDOrFallback());
1863 if (GS == DefinedGlobals.end())
1864 return;
1865
1866 if (Propagate)
1867 if (FunctionSummary *FS = dyn_cast<FunctionSummary>(GS->second)) {
1868 if (Function *F = dyn_cast<Function>(&GV)) {
1869 // TODO: propagate ReadNone and ReadOnly.
1870 if (FS->fflags().ReadNone && !F->doesNotAccessMemory())
1871 F->setDoesNotAccessMemory();
1872
1873 if (FS->fflags().ReadOnly && !F->onlyReadsMemory())
1874 F->setOnlyReadsMemory();
1875
1876 if (FS->fflags().NoRecurse && !F->doesNotRecurse())
1877 F->setDoesNotRecurse();
1878
1879 if (FS->fflags().NoUnwind && !F->doesNotThrow())
1880 F->setDoesNotThrow();
1881 }
1882 }
1883
1884 auto NewLinkage = GS->second->linkage();
1886 // Don't internalize anything here, because the code below
1887 // lacks necessary correctness checks. Leave this job to
1888 // LLVM 'internalize' pass.
1889 GlobalValue::isLocalLinkage(NewLinkage) ||
1890 // In case it was dead and already converted to declaration.
1891 GV.isDeclaration())
1892 return;
1893
1894 // Set the potentially more constraining visibility computed from summaries.
1895 // The DefaultVisibility condition is because older GlobalValueSummary does
1896 // not record DefaultVisibility and we don't want to change protected/hidden
1897 // to default.
1898 if (GS->second->getVisibility() != GlobalValue::DefaultVisibility)
1899 GV.setVisibility(GS->second->getVisibility());
1900
1901 if (NewLinkage == GV.getLinkage())
1902 return;
1903
1904 // Check for a non-prevailing def that has interposable linkage
1905 // (e.g. non-odr weak or linkonce). In that case we can't simply
1906 // convert to available_externally, since it would lose the
1907 // interposable property and possibly get inlined. Simply drop
1908 // the definition in that case.
1911 if (!convertToDeclaration(GV))
1912 // FIXME: Change this to collect replaced GVs and later erase
1913 // them from the parent module once thinLTOResolvePrevailingGUID is
1914 // changed to enable this for aliases.
1915 llvm_unreachable("Expected GV to be converted");
1916 } else {
1917 // If all copies of the original symbol had global unnamed addr and
1918 // linkonce_odr linkage, or if all of them had local unnamed addr linkage
1919 // and are constants, then it should be an auto hide symbol. In that case
1920 // the thin link would have marked it as CanAutoHide. Add hidden
1921 // visibility to the symbol to preserve the property.
1922 if (NewLinkage == GlobalValue::WeakODRLinkage &&
1923 GS->second->canAutoHide()) {
1926 }
1927
1928 LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
1929 << "` from " << GV.getLinkage() << " to " << NewLinkage
1930 << "\n");
1931 GV.setLinkage(NewLinkage);
1932 }
1933 // Remove declarations from comdats, including available_externally
1934 // as this is a declaration for the linker, and will be dropped eventually.
1935 // It is illegal for comdats to contain declarations.
1936 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
1937 if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
1938 if (GO->getComdat()->getName() == GO->getName())
1939 NonPrevailingComdats.insert(GO->getComdat());
1940 GO->setComdat(nullptr);
1941 }
1942 };
1943
1944 // Process functions and global now
1945 for (auto &GV : TheModule)
1946 FinalizeInModule(GV, PropagateAttrs);
1947 for (auto &GV : TheModule.globals())
1948 FinalizeInModule(GV);
1949 for (auto &GV : TheModule.aliases())
1950 FinalizeInModule(GV);
1951
1952 // For a non-prevailing comdat, all its members must be available_externally.
1953 // FinalizeInModule has handled non-local-linkage GlobalValues. Here we handle
1954 // local linkage GlobalValues.
1955 if (NonPrevailingComdats.empty())
1956 return;
1957 for (auto &GO : TheModule.global_objects()) {
1958 if (auto *C = GO.getComdat(); C && NonPrevailingComdats.count(C)) {
1959 GO.setComdat(nullptr);
1961 }
1962 }
1963 bool Changed;
1964 do {
1965 Changed = false;
1966 // If an alias references a GlobalValue in a non-prevailing comdat, change
1967 // it to available_externally. For simplicity we only handle GlobalValue and
1968 // ConstantExpr with a base object. ConstantExpr without a base object is
1969 // unlikely used in a COMDAT.
1970 for (auto &GA : TheModule.aliases()) {
1971 if (GA.hasAvailableExternallyLinkage())
1972 continue;
1973 GlobalObject *Obj = GA.getAliaseeObject();
1974 assert(Obj && "aliasee without an base object is unimplemented");
1975 if (Obj->hasAvailableExternallyLinkage()) {
1977 Changed = true;
1978 }
1979 }
1980 } while (Changed);
1981}
1982
1983/// Run internalization on \p TheModule based on symmary analysis.
1985 const GVSummaryMapTy &DefinedGlobals) {
1986 llvm::TimeTraceScope timeScope("ThinLTO internalize module");
1987 // Declare a callback for the internalize pass that will ask for every
1988 // candidate GlobalValue if it can be internalized or not.
1989 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
1990 // It may be the case that GV is on a chain of an ifunc, its alias and
1991 // subsequent aliases. In this case, the summary for the value is not
1992 // available.
1993 if (isa<GlobalIFunc>(&GV) ||
1994 (isa<GlobalAlias>(&GV) &&
1995 isa<GlobalIFunc>(cast<GlobalAlias>(&GV)->getAliaseeObject())))
1996 return true;
1997
1998 // Lookup the linkage recorded in the summaries during global analysis.
1999 auto GS = DefinedGlobals.find(GV.getGUIDOrFallback());
2000 if (GS == DefinedGlobals.end()) {
2001 // Must have been promoted (possibly conservatively). Find original
2002 // name so that we can access the correct summary and see if it can
2003 // be internalized again.
2004 // FIXME: Eventually we should control promotion instead of promoting
2005 // and internalizing again.
2006 StringRef OrigName =
2008 std::string OrigId = GlobalValue::getGlobalIdentifier(
2010 TheModule.getSourceFileName());
2011 GS = DefinedGlobals.find(
2013 if (GS == DefinedGlobals.end()) {
2014 // Also check the original non-promoted non-globalized name. In some
2015 // cases a preempted weak value is linked in as a local copy because
2016 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
2017 // In that case, since it was originally not a local value, it was
2018 // recorded in the index using the original name.
2019 // FIXME: This may not be needed once PR27866 is fixed.
2020 GS = DefinedGlobals.find(
2022 assert(GS != DefinedGlobals.end());
2023 }
2024 }
2025 return !GlobalValue::isLocalLinkage(GS->second->linkage());
2026 };
2027
2028 // FIXME: See if we can just internalize directly here via linkage changes
2029 // based on the index, rather than invoking internalizeModule.
2030 internalizeModule(TheModule, MustPreserveGV);
2031}
2032
2033/// Make alias a clone of its aliasee.
2036
2037 ValueToValueMapTy VMap;
2038 Function *NewFn = CloneFunction(Fn, VMap);
2039 // Clone should use the original alias's linkage, visibility and name, and we
2040 // ensure all uses of alias instead use the new clone (casted if necessary).
2041 NewFn->setLinkage(GA->getLinkage());
2042 NewFn->setVisibility(GA->getVisibility());
2043 GA->replaceAllUsesWith(NewFn);
2044 NewFn->takeName(GA);
2045 return NewFn;
2046}
2047
2048// Internalize values that we marked with specific attribute
2049// in processGlobalForThinLTO.
2051 for (auto &GV : M.globals())
2052 // Skip GVs which have been converted to declarations
2053 // by dropDeadSymbols.
2054 if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) {
2055 GV.setLinkage(GlobalValue::InternalLinkage);
2056 GV.setVisibility(GlobalValue::DefaultVisibility);
2057 }
2058}
2059
2060/// When a function carrying !implicit.ref is imported via ThinLTO, the
2061/// referenced global arrives as available_externally. This string can be dead
2062/// code eliminated since it has no IR uses -- only metadata references. Adding
2063/// it to llvm.compiler.used prevents elimination.
2067 for (Function &F : M) {
2068 if (!F.hasAvailableExternallyLinkage() ||
2069 !F.hasMetadata(LLVMContext::MD_implicit_ref))
2070 continue;
2072 F.getMetadata(LLVMContext::MD_implicit_ref, MDs);
2073 for (MDNode *MD : MDs) {
2074 auto *Op = MD->getOperand(0).get();
2075 if (!Op)
2076 continue;
2077 if (auto *VAM = dyn_cast<ValueAsMetadata>(Op))
2078 if (auto *GV = dyn_cast<GlobalVariable>(VAM->getValue()))
2079 if (GV->hasAvailableExternallyLinkage() && Seen.insert(GV).second)
2080 ToProtect.push_back(GV);
2081 }
2082 }
2083 if (!ToProtect.empty())
2084 appendToCompilerUsed(M, ToProtect);
2085}
2086
2087// Automatically import functions in Module \p DestModule based on the summaries
2088// index.
2090 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
2091 LLVM_DEBUG(dbgs() << "Starting import for Module "
2092 << DestModule.getModuleIdentifier() << "\n");
2093 unsigned ImportedCount = 0, ImportedGVCount = 0;
2094 // Before carrying out any imports, see if this module defines functions in
2095 // MoveSymbolGUID. If it does, delete them here (but leave the declaration).
2096 // The function will be imported elsewhere, as extenal linkage, and the
2097 // destination doesn't yet have its definition.
2098 DenseSet<GlobalValue::GUID> MoveSymbolGUIDSet;
2099 MoveSymbolGUIDSet.insert_range(MoveSymbolGUID);
2100 for (auto &F : DestModule)
2101 if (!F.isDeclaration() && MoveSymbolGUIDSet.contains(F.getGUIDOrFallback()))
2102 F.deleteBody();
2103
2104 IRMover Mover(DestModule);
2105
2106 // Do the actual import of functions now, one Module at a time
2107 for (const auto &ModName : ImportList.getSourceModules()) {
2108 llvm::TimeTraceScope timeScope("Import", ModName);
2109 // Get the module for the import
2110 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(ModName);
2111 if (!SrcModuleOrErr)
2112 return SrcModuleOrErr.takeError();
2113 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
2114 assert(&DestModule.getContext() == &SrcModule->getContext() &&
2115 "Context mismatch");
2116
2117 // If modules were created with lazy metadata loading, materialize it
2118 // now, before linking it (otherwise this will be a noop).
2119 if (Error Err = SrcModule->materializeMetadata())
2120 return std::move(Err);
2121
2122 // Find the globals to import
2123 SetVector<GlobalValue *> GlobalsToImport;
2124 // Functions (or aliases of functions) to import as declarations, along
2125 // with their GUIDs.
2127 {
2128 llvm::TimeTraceScope functionsScope("Functions");
2129 for (Function &F : *SrcModule) {
2130 if (!F.hasName())
2131 continue;
2132 auto GUID = F.getGUIDOrFallback();
2133 auto MaybeImportType = ImportList.getImportType(ModName, GUID);
2134 bool ImportDefinition =
2135 MaybeImportType == GlobalValueSummary::Definition;
2136
2137 LLVM_DEBUG(dbgs() << (MaybeImportType ? "Is" : "Not")
2138 << " importing function"
2139 << (ImportDefinition
2140 ? " definition "
2141 : (MaybeImportType ? " declaration " : " "))
2142 << GUID << " " << F.getName() << " from "
2143 << SrcModule->getSourceFileName() << "\n");
2144 if (ImportDefinition) {
2145 if (Error Err = F.materialize())
2146 return std::move(Err);
2147 // MemProf should match function's definition and summary,
2148 // 'thinlto_src_module' is needed.
2150 // Add 'thinlto_src_module' and 'thinlto_src_file' metadata for
2151 // statistics and debugging.
2152 F.setMetadata(
2153 "thinlto_src_module",
2154 MDNode::get(DestModule.getContext(),
2155 {MDString::get(DestModule.getContext(),
2156 SrcModule->getModuleIdentifier())}));
2157 F.setMetadata(
2158 "thinlto_src_file",
2159 MDNode::get(DestModule.getContext(),
2160 {MDString::get(DestModule.getContext(),
2161 SrcModule->getSourceFileName())}));
2162 }
2163 GlobalsToImport.insert(&F);
2164 } else if (MaybeImportType) {
2165 assert(*MaybeImportType == GlobalValueSummary::Declaration);
2166 DeclsToImport.push_back({&F, GUID});
2167 }
2168 }
2169 }
2170 {
2171 llvm::TimeTraceScope globalsScope("Globals");
2172 for (GlobalVariable &GV : SrcModule->globals()) {
2173 if (!GV.hasName())
2174 continue;
2175 auto GUID = GV.getGUIDOrFallback();
2176 auto MaybeImportType = ImportList.getImportType(ModName, GUID);
2177 bool ImportDefinition =
2178 MaybeImportType == GlobalValueSummary::Definition;
2179
2180 LLVM_DEBUG(dbgs() << (MaybeImportType ? "Is" : "Not")
2181 << " importing global"
2182 << (ImportDefinition
2183 ? " definition "
2184 : (MaybeImportType ? " declaration " : " "))
2185 << GUID << " " << GV.getName() << " from "
2186 << SrcModule->getSourceFileName() << "\n");
2187 if (ImportDefinition) {
2188 if (Error Err = GV.materialize())
2189 return std::move(Err);
2190 ImportedGVCount += GlobalsToImport.insert(&GV);
2191 }
2192 }
2193 }
2194 {
2195 llvm::TimeTraceScope aliasesScope("Aliases");
2196 for (GlobalAlias &GA : SrcModule->aliases()) {
2197 if (!GA.hasName() || isa<GlobalIFunc>(GA.getAliaseeObject()))
2198 continue;
2199 auto GUID = GA.getGUIDOrFallback();
2200 auto MaybeImportType = ImportList.getImportType(ModName, GUID);
2201 bool ImportDefinition =
2202 MaybeImportType == GlobalValueSummary::Definition;
2203
2204 LLVM_DEBUG(dbgs() << (MaybeImportType ? "Is" : "Not")
2205 << " importing alias"
2206 << (ImportDefinition
2207 ? " definition "
2208 : (MaybeImportType ? " declaration " : " "))
2209 << GUID << " " << GA.getName() << " from "
2210 << SrcModule->getSourceFileName() << "\n");
2211 if (ImportDefinition) {
2212 if (Error Err = GA.materialize())
2213 return std::move(Err);
2214 // Import alias as a copy of its aliasee.
2215 GlobalObject *GO = GA.getAliaseeObject();
2216 if (Error Err = GO->materialize())
2217 return std::move(Err);
2218 auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
2219 assert(Fn);
2220 (void)Fn;
2222 << "Is importing aliasee fn " << GO->getGUIDOrFallback()
2223 << " " << GO->getName() << " from "
2224 << SrcModule->getSourceFileName() << "\n");
2226 // Add 'thinlto_src_module', 'thinlto_src_file', and
2227 // 'thinlto_alias_guid' metadata for statistics, debugging, and
2228 // summary lookup (since Fn retains the aliasee's !guid metadata).
2229 LLVMContext &Ctx = DestModule.getContext();
2230 Fn->setMetadata(
2231 "thinlto_src_module",
2233 Ctx, SrcModule->getModuleIdentifier())}));
2234 Fn->setMetadata(
2235 "thinlto_src_file",
2237 Ctx, {MDString::get(Ctx, SrcModule->getSourceFileName())}));
2238 Fn->setMetadata(
2239 "thinlto_alias_guid",
2240 MDNode::get(Ctx, {ConstantAsMetadata::get(ConstantInt::get(
2241 Type::getInt64Ty(Ctx), GUID))}));
2242 }
2243 GlobalsToImport.insert(Fn);
2244 } else if (MaybeImportType) {
2245 assert(*MaybeImportType == GlobalValueSummary::Declaration);
2246 if (isa<FunctionType>(GA.getValueType()))
2247 DeclsToImport.push_back({&GA, GUID});
2248 }
2249 }
2250 }
2251
2252 // Upgrade debug info after we're done materializing all the globals and we
2253 // have loaded all the required metadata!
2254 UpgradeDebugInfo(*SrcModule);
2255
2256 // Set the partial sample profile ratio in the profile summary module flag
2257 // of the imported source module, if applicable, so that the profile summary
2258 // module flag will match with that of the destination module when it's
2259 // imported.
2260 SrcModule->setPartialSampleProfileRatio(Index);
2261
2262 // Link in the specified functions.
2263 renameModuleForThinLTO(*SrcModule, Index, ClearDSOLocalOnDeclarations,
2264 &GlobalsToImport);
2265
2266 // Record the information needed to create the declarations to import,
2267 // after any promotion and renaming above, since the source module is
2268 // consumed by the IRMover below.
2269 struct DeclInfo {
2270 std::string Name;
2271 FunctionType *Ty;
2272 unsigned AddrSpace;
2274 AttributeList Attrs;
2276 bool DSOLocal;
2277 GlobalValue::GUID GUID;
2278 };
2279 SmallVector<DeclInfo> DeclInfos;
2280 for (auto [GV, GUID] : DeclsToImport) {
2281 assert(!GV->hasLocalLinkage() &&
2282 "Expected imported declaration to be promoted");
2283 const Function *F = dyn_cast<Function>(GV);
2284 if (!F)
2286 cast<GlobalAlias>(GV)->getAliaseeObject());
2287 if (!F)
2288 continue;
2289 DeclInfos.push_back({GV->getName().str(), F->getFunctionType(),
2290 F->getAddressSpace(), F->getCallingConv(),
2291 F->getAttributes(), GV->getVisibility(),
2292 GV->isDSOLocal(), GUID});
2293 }
2294
2295 if (PrintImports) {
2296 for (const auto *GV : GlobalsToImport)
2297 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
2298 << " from " << SrcModule->getSourceFileName() << "\n";
2299 }
2300
2301 if (Error Err = Mover.move(std::move(SrcModule),
2302 GlobalsToImport.getArrayRef(), nullptr,
2303 /*IsPerformingImport=*/true))
2305 Twine("Function Import: link error: ") +
2306 toString(std::move(Err)));
2307
2308 ImportedCount += GlobalsToImport.size();
2309 NumImportedModules++;
2310
2311 // Now create the declarations to import, if they don't already exist in
2312 // the destination module. Declarations of direct callees will typically
2313 // already exist, either because the call is in the destination module or
2314 // because the IRMover created them when linking an imported definition
2315 // that references them. Callees reached only via indirect calls (e.g.
2316 // from value profile or MemProf call edges in the summary) have no such IR
2317 // reference, so this is mainly where declarations of those are created.
2318 //
2319 // We create these declarations by hand rather than via the IRMover: the
2320 // IRMover only creates declarations as a side effect of mapping references
2321 // from linked IR, it creates attribute-less declarations for aliases, and
2322 // it does not copy metadata from source definitions.
2323 for (auto &DI : DeclInfos) {
2324 if (DestModule.getNamedValue(DI.Name))
2325 continue;
2327 DI.AddrSpace, DI.Name, &DestModule);
2328 F->setCallingConv(DI.CC);
2329 F->setAttributes(DI.Attrs);
2330 // Note that the visibility must be set before dso_local, since
2331 // setDSOLocal(false) is not allowed on an implicitly dso_local value.
2332 F->setVisibility(DI.Visibility);
2333 F->setDSOLocal(DI.DSOLocal);
2334 // Record the GUID of the original value, which may differ from the GUID
2335 // computed from the current name if it was a promoted local. This allows
2336 // the declaration to be located via the GUID, e.g. by MemProf ICP.
2337 F->setMetadata(LLVMContext::MD_guid,
2338 MDNode::get(DestModule.getContext(),
2339 {ConstantAsMetadata::get(ConstantInt::get(
2340 Type::getInt64Ty(DestModule.getContext()),
2341 DI.GUID))}));
2342 NumImportedFunctionDecls++;
2343 }
2344 }
2345
2346 internalizeGVsAfterImport(DestModule);
2347
2348 // Protect !implicit.ref-referenced globals imported as available_externally
2349 // from DCE'd. Only needed when globals were actually imported.
2350 if (ImportedGVCount > 0)
2351 protectImplicitRefGlobals(DestModule);
2352
2353 NumImportedFunctions += (ImportedCount - ImportedGVCount);
2354 NumImportedGlobalVars += ImportedGVCount;
2355
2356 // TODO: Print counters for definitions and declarations in the debugging log.
2357 LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
2358 << " functions for Module "
2359 << DestModule.getModuleIdentifier() << "\n");
2360 LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
2361 << " global variables for Module "
2362 << DestModule.getModuleIdentifier() << "\n");
2363 return ImportedCount;
2364}
2365
2368 isPrevailing) {
2369 if (SummaryFile.empty())
2370 report_fatal_error("error: -function-import requires -summary-file\n");
2373 if (!IndexPtrOrErr) {
2374 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
2375 "Error loading file '" + SummaryFile + "': ");
2376 return false;
2377 }
2378 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
2379
2380 // First step is collecting the import list.
2382 FunctionImporter::ImportMapTy ImportList(ImportIDs);
2383 // If requested, simply import all functions in the index. This is used
2384 // when testing distributed backend handling via the opt tool, when
2385 // we have distributed indexes containing exactly the summaries to import.
2386 if (ImportAllIndex)
2388 *Index, ImportList);
2389 else
2390 ComputeCrossModuleImportForModuleForTest(M.getModuleIdentifier(),
2391 isPrevailing, *Index, ImportList);
2392
2393 // Conservatively mark all internal values as promoted. This interface is
2394 // only used when doing importing via the function importing pass. The pass
2395 // is only enabled when testing importing via the 'opt' tool, which does
2396 // not do the ThinLink that would normally determine what values to promote.
2397 for (auto &I : *Index) {
2398 for (auto &S : I.second.getSummaryList()) {
2399 if (GlobalValue::isLocalLinkage(S->linkage()))
2400 S->setExternalLinkageForTest();
2401 }
2402 }
2403
2404 // Next we need to promote to global scope and rename any local values that
2405 // are potentially exported to other modules.
2406 renameModuleForThinLTO(M, *Index, /*ClearDSOLocalOnDeclarations=*/false,
2407 /*GlobalsToImport=*/nullptr);
2408
2409 // Perform the import now.
2410 auto ModuleLoader = [&M](StringRef Identifier) {
2411 return loadFile(std::string(Identifier), M.getContext());
2412 };
2413 FunctionImporter Importer(*Index, ModuleLoader,
2414 /*ClearDSOLocalOnDeclarations=*/false);
2415 Expected<bool> Result = Importer.importFunctions(M, ImportList);
2416
2417 // FIXME: Probably need to propagate Errors through the pass manager.
2418 if (!Result) {
2419 logAllUnhandledErrors(Result.takeError(), errs(),
2420 "Error importing module: ");
2421 return true;
2422 }
2423
2424 return true;
2425}
2426
2429 // This is only used for testing the function import pass via opt, where we
2430 // don't have prevailing information from the LTO context available, so just
2431 // conservatively assume everything is prevailing (which is fine for the very
2432 // limited use of prevailing checking in this pass).
2433 auto isPrevailing = [](GlobalValue::GUID, const GlobalValueSummary *) {
2434 return true;
2435 };
2436 if (!doImportingForModuleForTest(M, isPrevailing))
2437 return PreservedAnalyses::all();
2438
2439 return PreservedAnalyses::none();
2440}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
static auto qualifyCalleeCandidates(const ModuleSummaryIndex &Index, ArrayRef< std::unique_ptr< GlobalValueSummary > > CalleeSummaryList, StringRef CallerModulePath)
Given a list of possible callee implementation for a call site, qualify the legality of importing eac...
static DenseMap< StringRef, ImportStatistics > collectImportStatistics(const ModuleSummaryIndex &Index, const FunctionImporter::ImportMapTy &ImportList)
static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index, FunctionImporter::ExportSetTy &ExportSet)
static bool checkVariableImport(const ModuleSummaryIndex &Index, FunctionImporter::ImportListsTy &ImportLists, DenseMap< StringRef, FunctionImporter::ExportSetTy > &ExportLists)
static bool doImportingForModuleForTest(Module &M, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
static const char * getFailureName(FunctionImporter::ImportFailureReason Reason)
static void internalizeGVsAfterImport(Module &M)
void updateValueInfoForIndirectCalls(ModuleSummaryIndex &Index, FunctionSummary *FS)
static std::unique_ptr< Module > loadFile(const std::string &FileName, LLVMContext &Context)
static bool shouldSkipLocalInAnotherModule(const GlobalValueSummary *RefSummary, size_t NumDefs, StringRef ImporterModule)
static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, ValueInfo VI)
static Function * replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA)
Make alias a clone of its aliasee.
static void protectImplicitRefGlobals(Module &M)
When a function carrying !implicit.ref is imported via ThinLTO, the referenced global arrives as avai...
static void dumpImportListForModule(const ModuleSummaryIndex &Index, StringRef ModulePath, FunctionImporter::ImportMapTy &ImportList)
static void ComputeCrossModuleImportForModuleFromIndexForTest(StringRef ModulePath, const ModuleSummaryIndex &Index, FunctionImporter::ImportMapTy &ImportList)
Mark all external summaries in Index for import into the given module.
static const GlobalValueSummary * selectCallee(const ModuleSummaryIndex &Index, ArrayRef< std::unique_ptr< GlobalValueSummary > > CalleeSummaryList, unsigned Threshold, StringRef CallerModulePath, const GlobalValueSummary *&TooLargeOrNoInlineSummary, FunctionImporter::ImportFailureReason &Reason)
Given a list of possible callee implementation for a call site, select one that fits the Threshold fo...
static void ComputeCrossModuleImportForModuleForTest(StringRef ModulePath, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, const ModuleSummaryIndex &Index, FunctionImporter::ImportMapTy &ImportList)
Compute all the imports for the given module using the Index.
Module.h This file contains the declarations for the Module class.
This file supports working with JSON data.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
block placement Basic Block Placement Stats
static cl::opt< std::string > OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-"))
This file contains the declarations for metadata subclasses.
static cl::opt< bool > PropagateAttrs("propagate-attrs", cl::init(true), cl::Hidden, cl::desc("Propagate attributes in index"))
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
static constexpr StringLiteral Filename
Reader for contextual iFDO profile, which comes in bitstream format.
if(PassOpts->AAPipeline)
RISCVCC::CondCode CC
const char * Msg
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Import globals referenced by a function or other globals that are being imported, if importing such g...
void onImportingSummary(const GlobalValueSummary &Summary)
GlobalsImporter(const ModuleSummaryIndex &Index, const GVSummaryMapTy &DefinedGVSummaries, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing, FunctionImporter::ImportMapTy &ImportList, DenseMap< StringRef, FunctionImporter::ExportSetTy > *ExportLists)
virtual bool canImport(ValueInfo VI)
void importRequiredDeclaration(ValueInfo VI, StringRef CallerModulePath, FunctionImporter::ImportMapTy &ImportList)
Import a declaration of the callee VI of a call edge requiring a declaration import (see RequiresDecl...
DenseMap< StringRef, FunctionImporter::ExportSetTy > *const ExportLists
void addRequiredDeclaration(ValueInfo VI, const GlobalValueSummary *DeclSummary, FunctionImporter::ImportMapTy &ImportList)
Import a declaration of the callee VI from the module containing DeclSummary, which must be a candida...
virtual ~ModuleImportsManager()=default
static std::unique_ptr< ModuleImportsManager > create(function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing, const ModuleSummaryIndex &Index, DenseMap< StringRef, FunctionImporter::ExportSetTy > *ExportLists=nullptr)
function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing
ModuleImportsManager(function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing, const ModuleSummaryIndex &Index, DenseMap< StringRef, FunctionImporter::ExportSetTy > *ExportLists=nullptr)
const ModuleSummaryIndex & Index
DenseMap< StringRef, FunctionImporter::ExportSetTy > RequiredDeclExports
DenseMap< StringRef, FunctionImporter::ExportSetTy > & requiredDeclExports()
Values that must be exported from their defining modules because declarations of them are required in...
virtual void computeImportForModule(const GVSummaryMapTy &DefinedGVSummaries, StringRef ModName, FunctionImporter::ImportMapTy &ImportList)
Given the list of globals defined in a module, compute the list of imports as well as the list of "ex...
WorkloadImportsManager(function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing, const ModuleSummaryIndex &Index, DenseMap< StringRef, FunctionImporter::ExportSetTy > *ExportLists)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:548
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
void insert_range(Range &&R)
Inserts a range of 'std::pair<KeyT, ValueT>' values into the map.
Definition DenseMap.h:894
ValueT & at(const_arg_type_t< KeyT > Val)
Return the entry for the specified key, or abort if no such entry exists.
Definition DenseMap.h:811
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
The map maintains the list of imports.
LLVM_ABI AddDefinitionStatus addDefinition(StringRef FromModule, GlobalValue::GUID GUID)
void addGUID(StringRef FromModule, GlobalValue::GUID GUID, GlobalValueSummary::ImportKind ImportKind)
LLVM_ABI SmallVector< StringRef, 0 > getSourceModules() const
LLVM_ABI std::optional< GlobalValueSummary::ImportKind > getImportType(StringRef FromModule, GlobalValue::GUID GUID) const
LLVM_ABI void maybeAddDeclaration(StringRef FromModule, GlobalValue::GUID GUID)
The function importer is automatically importing function from other modules based on the provided su...
LLVM_ABI Expected< bool > importFunctions(Module &M, const ImportMapTy &ImportList)
Import functions in Module M based on the supplied import list.
DenseMap< GlobalValue::GUID, std::tuple< unsigned, const GlobalValueSummary *, std::unique_ptr< ImportFailureInfo > > > ImportThresholdsTy
Map of callee GUID considered for import into a given module to a pair consisting of the largest thre...
ImportFailureReason
The different reasons selectCallee will chose not to import a candidate.
DenseSet< ValueInfo > ExportSetTy
The set contains an entry for every global value that the module exports.
Function summary information to aid decisions and implementation of importing.
unsigned instCount() const
Get the instruction count recorded for this function.
FFlags fflags() const
Get function summary flags.
Class to represent function types.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:730
Function and variable summary information to aid decisions and implementation of importing.
StringRef modulePath() const
Get the path to the module containing this function.
GlobalValue::LinkageTypes linkage() const
Return linkage type recorded for this global value.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
VisibilityTypes getVisibility() const
bool isImplicitDSOLocal() const
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
LinkageTypes getLinkage() const
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
LLVM_ABI GUID getGUIDOrFallback() const
Return the GUID for this value if it has been assigned, otherwise fall back to computing it based on ...
Definition Globals.cpp:110
ThreadLocalMode getThreadLocalMode() const
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
void setLinkage(LinkageTypes LT)
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:521
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
Definition Globals.cpp:234
void setVisibility(VisibilityTypes V)
static bool isInterposableLinkage(LinkageTypes Linkage)
Whether the definition of this global may be replaced by something non-equivalent at link time.
LLVM_ABI Error materialize()
Make sure this GlobalValue is fully read.
Definition Globals.cpp:52
LLVM_ABI bool canBeOmittedFromSymbolTable() const
True if GV can be left out of the object symbol table.
Definition Globals.cpp:546
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Type * getValueType() const
LLVM_ABI Error move(std::unique_ptr< Module > Src, ArrayRef< GlobalValue * > ValuesToLink, LazyCallback AddLazyFor, bool IsPerformingImport)
Move in the provide values in ValuesToLink from Src.
Definition IRMover.cpp:1683
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Metadata node.
Definition Metadata.h:1081
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:597
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static StringRef getOriginalNameBeforePromote(StringRef Name)
Helper to obtain the unpromoted name for a global value (or the original name if not promoted).
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:332
const std::string & getSourceFileName() const
Get the module's original source file name.
Definition Module.h:310
iterator_range< alias_iterator > aliases()
Definition Module.h:853
iterator_range< global_iterator > globals()
Definition Module.h:802
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition Module.h:299
iterator_range< global_object_iterator > global_objects()
Definition Module.cpp:461
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type.
Definition Module.cpp:177
LLVM_ABI Expected< PGOCtxProfile > loadProfiles()
unsigned getAddressSpace() const
Return the address space of the Pointer type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition SourceMgr.h:307
A vector that has set insertion semantics.
Definition SetVector.h:57
ArrayRef< value_type > getArrayRef() const
Definition SetVector.h:91
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
Vector takeVector()
Clear the SetVector and return the underlying vector.
Definition SetVector.h:94
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
void clear()
Completely clear the SetVector.
Definition SetVector.h:273
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
iterator end()
Definition StringMap.h:214
iterator find(StringRef Key)
Definition StringMap.h:227
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition StringMap.h:275
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition StringMap.h:311
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
char front() const
Get the first character in the string.
Definition StringRef.h:147
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition StringSet.h:25
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition StringSet.h:39
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:268
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
void insert_range(Range &&R)
Definition DenseSet.h:235
size_type size() const
Definition DenseSet.h:84
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
bool remove_if(Predicate Pred)
Remove all elements for which Pred returns true.
Definition DenseSet.h:103
An efficient, type-erasing, non-owning reference to a callable.
The root is the trivial Path to the root value.
Definition JSON.h:700
A raw_ostream that writes to a file descriptor.
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
initializer< Ty > init(const Ty &Val)
LLVM_ABI llvm::Expected< Value > parse(llvm::StringRef JSON)
Parses the provided JSON source, or returns a ParseError.
Definition JSON.cpp:681
bool fromJSON(const Value &E, std::string &Out, Path P)
Definition JSON.h:729
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition FileSystem.h:793
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition Error.cpp:61
static cl::opt< float > ImportHotMultiplier("import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"), cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"))
static cl::opt< bool > CtxprofMoveRootsToOwnModule("thinlto-move-ctxprof-trees", cl::desc("Move contextual profiling roots and the graphs under them in " "their own module."), cl::Hidden, cl::init(false))
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition Error.h:1415
bool internalizeModule(Module &TheModule, std::function< bool(const GlobalValue &)> MustPreserveGV)
Helper function to internalize functions and variables in a Module.
Definition Internalize.h:78
static cl::opt< float > ImportColdMultiplier("import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"), cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"))
std::error_code make_error_code(BitcodeError E)
cl::list< GlobalValue::GUID > MoveSymbolGUID
const char * getHotnessName(CalleeInfo::HotnessType HT)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
static cl::opt< std::string > WorkloadDefinitions("thinlto-workload-def", cl::desc("Pass a workload definition. This is a file containing a JSON " "dictionary. The keys are root functions, the values are lists of " "functions to import in the module defining the root. It is " "assumed -funique-internal-linkage-names was used, to ensure " "local linkage functions have unique names. For example: \n" "{\n" " \"rootFunction_1\": [\"function_to_import_1\", " "\"function_to_import_2\"], \n" " \"rootFunction_2\": [\"function_to_import_3\", " "\"function_to_import_4\"] \n" "}"), cl::Hidden)
Pass a workload description file - an example of workload would be the functions executed to satisfy ...
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
cl::opt< std::string > UseCtxProfile("use-ctx-profile", cl::init(""), cl::Hidden, cl::desc("Use the specified contextual profile file"))
static cl::opt< bool > PrintImportFailures("print-import-failures", cl::init(false), cl::Hidden, cl::desc("Print information for functions rejected for importing"))
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI bool convertToDeclaration(GlobalValue &GV)
Converts value GV to declaration, or replaces with a declaration if it is an alias.
static cl::opt< unsigned > ImportInstrLimit("import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"), cl::desc("Only import functions with less than N instructions"))
Limit on instruction count of imported functions.
LLVM_ABI void renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, bool ClearDSOLocalOnDeclarations, SetVector< GlobalValue * > *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
static cl::opt< float > ImportHotInstrFactor("import-hot-evolution-factor", cl::init(1.0), cl::Hidden, cl::value_desc("x"), cl::desc("As we import functions called from hot callsite, multiply the " "`import-instr-limit` threshold by this factor " "before processing newly imported functions"))
static cl::opt< bool > PrintImports("print-imports", cl::init(false), cl::Hidden, cl::desc("Print imported functions"))
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
@ not_supported
Definition Errc.h:69
@ invalid_argument
Definition Errc.h:56
LLVM_ABI void ComputeCrossModuleImport(const ModuleSummaryIndex &Index, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, FunctionImporter::ImportListsTy &ImportLists, DenseMap< StringRef, FunctionImporter::ExportSetTy > &ExportLists)
Compute all the imports and exports for every module in the Index.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
static cl::opt< float > ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7), cl::Hidden, cl::value_desc("x"), cl::desc("As we import functions, multiply the " "`import-instr-limit` threshold by this factor " "before processing newly imported functions"))
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
cl::opt< bool > AlwaysRenamePromotedLocals("always-rename-promoted-locals", cl::init(true), cl::Hidden, cl::desc("Always rename promoted locals."))
Definition LTO.cpp:112
LLVM_ABI void computeDeadSymbolsAndUpdateIndirectCalls(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, function_ref< PrevailingType(GlobalValue::GUID)> isPrevailing)
Compute all the symbols that are "dead": i.e these that can't be reached in the graph from any of the...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1415
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
bool hasSingleElement(ContainerTy &&C)
Returns true if the given container only contains a single element.
Definition STLExtras.h:300
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:552
static cl::opt< bool > ImportAllIndex("import-all-index", cl::desc("Import all external functions in index."))
Used when testing importing from distributed indexes via opt.
static cl::opt< int > ImportCutoff("import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"), cl::desc("Only import first N functions if N>=0 (default -1)"))
static cl::opt< bool > ImportDeclaration("import-declaration", cl::init(false), cl::Hidden, cl::desc("If true, import function declaration as fallback if the function " "definition is not imported."))
This is a test-only option.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI void updateIndirectCalls(ModuleSummaryIndex &Index)
Update call edges for indirect calls to local functions added from SamplePGO when needed.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
cl::opt< bool > EnableMemProfContextDisambiguation
Enable MemProf context disambiguation for thin link.
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
LLVM_ABI std::unique_ptr< Module > getLazyIRFileModule(StringRef Filename, SMDiagnostic &Err, LLVMContext &Context, bool ShouldLazyLoadMetadata=false)
If the given file holds a bitcode image, return a Module for it which does lazy deserialization of fu...
Definition IRReader.cpp:51
LLVM_ABI void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
cl::opt< bool > ForceImportAll
DWARFExpression::Operation Op
LLVM_ABI void gatherImportedSummariesForModule(StringRef ModulePath, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, const FunctionImporter::ImportMapTy &ImportList, ModuleToSummariesForIndexTy &ModuleToSummariesForIndex, GVSummaryPtrSet &DecSummaries)
Compute the set of summaries needed for a ThinLTO backend compilation of ModulePath.
static cl::opt< std::string > SummaryFile("summary-file", cl::desc("The summary file to use for function importing."))
Summary file to use for function importing when using -function-import from the command line.
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI void processImportsFiles(StringRef ModulePath, const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex, function_ref< void(const std::string &)> F)
Call F passing each of the files module ModulePath will import from.
static cl::opt< float > ImportCriticalMultiplier("import-critical-multiplier", cl::init(100.0), cl::Hidden, cl::value_desc("x"), cl::desc("Multiply the `import-instr-limit` threshold for critical callsites"))
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
PrevailingType
PrevailingType enum used as a return type of callback passed to computeDeadSymbolsAndUpdateIndirectCa...
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
static cl::opt< bool > EnableImportMetadata("enable-import-metadata", cl::init(false), cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module' and " "'thinlto_src_file'"))
SmallPtrSet< GlobalValueSummary *, 0 > GVSummaryPtrSet
A set of global value summary pointers.
LLVM_ABI Function * CloneFunction(Function *F, ValueToValueMapTy &VMap, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified function and add it to that function's module.
LLVM_ABI void computeDeadSymbolsWithConstProp(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, function_ref< PrevailingType(GlobalValue::GUID)> isPrevailing, bool ImportEnabled)
Compute dead symbols and run constant propagation in combined index after that.
LLVM_ABI Error EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex)
Emit into OutputFilename the files module ModulePath will import from.
static cl::opt< bool > ComputeDead("compute-dead", cl::init(true), cl::Hidden, cl::desc("Compute dead symbols"))
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndexForFile(StringRef Path, bool IgnoreEmptyThinLTOIndexFile=false)
Parse the module summary index out of an IR file and return the module summary index object if found,...
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI void thinLTOFinalizeInModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals, bool PropagateAttrs)
Based on the information recorded in the summaries during global summary-based analysis:
Struct that holds a reference to a particular GUID in a global value summary.