LLVM: lib/LTO/LTOBackend.cpp Source File (original) (raw)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

48#include

49

50using namespace llvm;

51using namespace lto;

52

53#define DEBUG_TYPE "lto-backend"

54

60

64 "Do not embed"),

66 "Embed after all optimization passes"),

68 "post-merge-pre-opt",

69 "Embed post merge, but before optimizations")),

70 cl::desc("Embed LLVM bitcode in object files produced by LTO"));

71

73 "thinlto-assume-merged", cl::init(false),

74 cl::desc("Assume the input has already undergone ThinLTO function "

75 "importing and the other pre-optimization pipeline changes."));

76

77namespace llvm {

79}

80

82 errs() << "failed to open " << Path << ": " << Msg << '\n';

84 exit(1);

85}

86

90

91 std::error_code EC;

92 if (SaveTempsArgs.empty() || SaveTempsArgs.contains("resolution")) {

94 std::make_unique<raw_fd_ostream>(OutputFileName + "resolution.txt", EC,

96 if (EC) {

99 }

100 }

101

102 auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {

103

105 Hook = [=](unsigned Task, const Module &M) {

106

107

108 if (LinkerHook && !LinkerHook(Task, M))

109 return false;

110

111 std::string PathPrefix;

112

113

114

115 if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {

116 PathPrefix = OutputFileName;

117 if (Task != (unsigned)-1)

118 PathPrefix += utostr(Task) + ".";

119 } else

120 PathPrefix = M.getModuleIdentifier() + ".";

121 std::string Path = PathPrefix + PathSuffix + ".bc";

122 std::error_code EC;

124

125

126 if (EC)

129 return true;

130 };

131 };

132

133 auto SaveCombinedIndex =

136 std::string Path = OutputFileName + "index.bc";

137 std::error_code EC;

139

140

141 if (EC)

144

145 Path = OutputFileName + "index.dot";

147 if (EC)

149 Index.exportToDot(OSDot, GUIDPreservedSymbols);

150 return true;

151 };

152

153 if (SaveTempsArgs.empty()) {

161 } else {

162 if (SaveTempsArgs.contains("preopt"))

164 if (SaveTempsArgs.contains("promote"))

166 if (SaveTempsArgs.contains("internalize"))

168 if (SaveTempsArgs.contains("import"))

170 if (SaveTempsArgs.contains("opt"))

172 if (SaveTempsArgs.contains("precodegen"))

174 if (SaveTempsArgs.contains("combinedindex"))

176 }

177

179}

180

181#define HANDLE_EXTENSION(Ext) \

182 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();

183#include "llvm/Support/Extension.def"

184#undef HANDLE_EXTENSION

185

188#define HANDLE_EXTENSION(Ext) \

189 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);

190#include "llvm/Support/Extension.def"

191#undef HANDLE_EXTENSION

192

193

194 for (auto &PluginFN : PassPlugins) {

199 }

200}

201

202static std::unique_ptr

204 const Triple &TheTriple = M.getTargetTriple();

207 for (const std::string &A : Conf.MAttrs)

209

210 std::optionalReloc::Model RelocModel;

213 else if (M.getModuleFlag("PIC Level"))

214 RelocModel =

216

217 std::optionalCodeModel::Model CodeModel;

220 else

222

226 }

227

229 TheTriple, Conf.CPU, Features.getString(), TargetOpts, RelocModel,

231

232 assert(TM && "Failed to create target machine");

233

234 if (std::optional<uint64_t> LargeDataThreshold = M.getLargeDataThreshold())

235 TM->setLargeDataThreshold(*LargeDataThreshold);

236

237 return TM;

238}

239

241 unsigned OptLevel, bool IsThinLTO,

244 std::optional PGOOpt;

256 PGOOpt =

265 }

267

272

276 SI.registerCallbacks(PIC, &MAM);

278

280

281 std::unique_ptr TLII(

284 TLII->disableAllFunctions();

286

287

290 if (auto Err = PB.parseAAPipeline(AA, Conf.AAPipeline)) {

293 }

294

295 FAM.registerPass([&] { return std::move(AA); });

296 }

297

298

299 PB.registerModuleAnalyses(MAM);

300 PB.registerCGSCCAnalyses(CGAM);

301 PB.registerFunctionAnalyses(FAM);

302 PB.registerLoopAnalyses(LAM);

304

306

309

311

312 switch (OptLevel) {

313 default:

315 case 0:

317 break;

318 case 1:

320 break;

321 case 2:

323 break;

324 case 3:

326 break;

327 }

328

329

331 if (auto Err = PB.parsePassPipeline(MPM, Conf.OptPipeline)) {

334 }

335 } else if (IsThinLTO) {

336 MPM.addPass(PB.buildThinLTODefaultPipeline(OL, ImportSummary));

337 } else {

338 MPM.addPass(PB.buildLTODefaultPipeline(OL, ExportSummary));

339 }

340

343

345 std::string PipelineStr;

348 auto PassName = PIC.getPassNameForClassName(ClassName);

350 });

351 outs() << "pipeline-passes: " << PipelineStr << '\n';

352 }

353

355}

356

358

359

360

361 return Mod.empty() && Mod.global_empty() && Mod.named_metadata_empty() &&

362 Mod.getModuleInlineAsm().empty();

363}

364

368 const std::vector<uint8_t> &CmdArgs) {

371

372

373

374

375

376

377

378

379 if (CmdArgs.empty())

381 dbgs() << "Post-(Thin)LTO merge bitcode embedding was requested, but "

382 "command line arguments are not available");

384 true, true,

385 CmdArgs);

386 }

387

388

389

390

391

393

395 ImportSummary);

396 }

398}

399

405 return;

406

409 true,

410 false,

411 std::vector<uint8_t>());

412

413 std::unique_ptr DwoOut;

415 if (!Conf.DwoDir.empty()) {

416 std::error_code EC;

419 ": " + EC.message());

420

421 DwoFile = Conf.DwoDir;

424 } else

426

427 if (!DwoFile.empty()) {

428 std::error_code EC;

429 DwoOut = std::make_unique(DwoFile, EC, sys::fs::OF_None);

430 if (EC)

432 EC.message());

433 }

434

436 AddStream(Task, Mod.getModuleIdentifier());

439 std::unique_ptr &Stream = *StreamOrErr;

441

442

443

444

445

446 {

454

455

456

457

458

459

461 CodeGenPasses.add(

466 DwoOut ? &DwoOut->os() : nullptr,

469 CodeGenPasses.run(Mod);

470

471 if (DwoOut)

472 DwoOut->keep();

473 }

474

475 if (Error Err = Stream->commit())

477}

478

481 unsigned ParallelCodeGenParallelismLevel, Module &Mod,

487

488 const auto HandleModulePartition =

489 [&](std::unique_ptr MPart) {

490

491

492

493

494

495

499

500

501 CodegenThreadPool.async(

506 if (!MOrErr)

508 std::unique_ptr MPartInCtx = std::move(MOrErr.get());

509

510 std::unique_ptr TM =

512

513 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx,

514 CombinedIndex);

515 },

516

517

519 };

520

521

522 if (!TM->splitModule(Mod, ParallelCodeGenParallelismLevel,

523 HandleModulePartition)) {

524 SplitModule(Mod, ParallelCodeGenParallelismLevel, HandleModulePartition,

525 false);

526 }

527

528

529

530

531 CodegenThreadPool.wait();

532}

533

536 if (C.OverrideTriple.empty())

537 Mod.setTargetTriple(Triple(C.OverrideTriple));

538 else if (Mod.getTargetTriple().empty())

539 Mod.setTargetTriple(Triple(C.DefaultTriple));

540

541 std::string Msg;

543 if (T)

545 return T;

546}

547

549

550

551 if (!DiagOutputFile)

554 DiagOutputFile->keep();

555 DiagOutputFile->os().flush();

557}

558

560 unsigned ParallelCodeGenParallelismLevel, Module &Mod,

564 if (!TOrErr)

566

568

570 if (C.CodeGenOnly) {

571 if (opt(C, TM.get(), 0, Mod, false,

572 &CombinedIndex, nullptr,

573 std::vector<uint8_t>()))

575 }

576

577 if (ParallelCodeGenParallelismLevel == 1) {

578 codegen(C, TM.get(), AddStream, 0, Mod, CombinedIndex);

579 } else {

580 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel, Mod,

581 CombinedIndex);

582 }

584}

585

589 std::vector<GlobalValue*> DeadGVs;

590 for (auto &GV : Mod.global_values())

592 if (!Index.isGlobalValueLive(GVS)) {

593 DeadGVs.push_back(&GV);

595 }

596

597

598

600 GV->removeDeadConstantUsers();

601

602

603 if (GV->use_empty())

604 GV->eraseFromParent();

605 }

606}

607

613 bool CodeGenOnly, AddStreamFn IRAddStream,

614 const std::vector<uint8_t> &CmdArgs) {

617 if (!TOrErr)

619

621

622

626 Task);

627 if (!DiagFileOrErr)

628 return DiagFileOrErr.takeError();

629 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);

630

631

632

633 Mod.setPartialSampleProfileRatio(CombinedIndex);

634

636 if (CodeGenOnly) {

637

638

639 codegen(Conf, TM.get(), AddStream, Task, Mod, CombinedIndex);

641 }

642

645

646 auto OptimizeAndCodegen =

649

650 if (opt(Conf, TM, Task, Mod, true,

651 nullptr, &CombinedIndex,

652 CmdArgs))

654

655

656

657

658

659 if (IRAddStream)

661

662 codegen(Conf, TM, AddStream, Task, Mod, CombinedIndex);

664 };

665

667 return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));

668

669

670

671 bool ClearDSOLocalOnDeclarations =

672 TM->getTargetTriple().isOSBinFormatELF() &&

676

678

680

683

684 if (!DefinedGlobals.empty())

686

690

691 auto ModuleLoader = [&](StringRef Identifier) {

693 assert(Mod.getContext().isODRUniquingDebugTypes() &&

694 "ODR Type uniquing should be enabled on the context");

695 if (ModuleMap) {

696 auto I = ModuleMap->find(Identifier);

698 return I->second.getLazyModule(Mod.getContext(),

699 true,

700 true);

701 }

702

705 if (!MBOrErr)

707 Twine("Error loading imported file ") + Identifier + " : ",

709

711 if (!BMOrErr)

713 Twine("Error loading imported file ") + Identifier + " : " +

716

718 BMOrErr->getLazyModule(Mod.getContext(),

719 true,

720 true);

721 if (MOrErr)

722 (*MOrErr)->setOwnedMemoryBuffer(std::move(*MBOrErr));

723 return MOrErr;

724 };

725

726 {

729 ClearDSOLocalOnDeclarations);

731 return Err;

732 }

733

734

736

739

740 return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));

741}

742

745 return BMs.begin();

746

749 if (LTOInfo && LTOInfo->IsThinLTO)

750 return &BM;

751 }

752 return nullptr;

753}

754

757 if (!BMsOrErr)

759

760

761

763 return *Bm;

764

767}

768

773 return true;

774

775

776

777 for (const auto &GlobalList : CombinedIndex) {

778

779 if (GlobalList.second.getSummaryList().empty())

780 continue;

781

782 auto GUID = GlobalList.first;

783 for (const auto &Summary : GlobalList.second.getSummaryList()) {

784

785

786 if (Summary->modulePath() == M.getModuleIdentifier())

787 continue;

788

789 ImportList.addGUID(Summary->modulePath(), GUID, Summary->importType());

790 }

791 }

792 return true;

793}

assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")

static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")

This header provides classes for managing passes over SCCs of the call graph.

#define clEnumValN(ENUMVAL, FLAGNAME, DESC)

This header defines various interfaces for pass management in LLVM.

static cl::opt< bool > ThinLTOAssumeMerged("thinlto-assume-merged", cl::init(false), cl::desc("Assume the input has already undergone ThinLTO function " "importing and the other pre-optimization pipeline changes."))

static void reportOpenError(StringRef Path, Twine Msg)

Definition LTOBackend.cpp:81

LTOBitcodeEmbedding

Definition LTOBackend.cpp:55

@ DoNotEmbed

Definition LTOBackend.cpp:56

@ EmbedOptimized

Definition LTOBackend.cpp:57

@ EmbedPostMergePreOptimized

Definition LTOBackend.cpp:58

static cl::opt< LTOBitcodeEmbedding > EmbedBitcode("lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed), cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none", "Do not embed"), clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized", "Embed after all optimization passes"), clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized, "post-merge-pre-opt", "Embed post merge, but before optimizations")), cl::desc("Embed LLVM bitcode in object files produced by LTO"))

static void splitCodeGen(const Config &C, TargetMachine *TM, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, Module &Mod, const ModuleSummaryIndex &CombinedIndex)

Definition LTOBackend.cpp:479

static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals, const ModuleSummaryIndex &Index)

Definition LTOBackend.cpp:586

static Expected< const Target * > initAndLookupTarget(const Config &C, Module &Mod)

Definition LTOBackend.cpp:534

static bool isEmptyModule(const Module &Mod)

Definition LTOBackend.cpp:357

static void RegisterPassPlugins(ArrayRef< std::string > PassPlugins, PassBuilder &PB)

Definition LTOBackend.cpp:186

static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM, unsigned OptLevel, bool IsThinLTO, ModuleSummaryIndex *ExportSummary, const ModuleSummaryIndex *ImportSummary)

Definition LTOBackend.cpp:240

This is the interface to build a ModuleSummaryIndex for a module.

static std::unique_ptr< TargetMachine > createTargetMachine(Function *F, CodeGenOptLevel OptLevel)

Create the TargetMachine object to query the backend for optimization preferences.

CGSCCAnalysisManager CGAM

if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod

FunctionAnalysisManager FAM

ModuleAnalysisManager MAM

PassInstrumentationCallbacks PIC

PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)

This header defines a class that provides bookkeeping for all standard (i.e in-tree) pass instrumenta...

static cl::opt< int > ThreadCount("threads", cl::init(0))

Defines the virtual file system interface vfs::FileSystem.

static const char PassName[]

A manager for alias analyses.

ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...

size_t size() const

size - Get the array size.

Represents a module in a bitcode file.

ValueT lookup(const_arg_type_t< KeyT > Val) const

lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...

Implements a dense probed hash-table based set.

Represents either an error or a value T.

std::error_code getError() const

Lightweight error class with error context and mandatory checking.

static ErrorSuccess success()

Create a success value.

Tagged union holding either a T or a Error.

Error takeError()

Take ownership of the stored error.

reference get()

Returns a reference to the stored T value.

The map maintains the list of imports.

void addGUID(StringRef FromModule, GlobalValue::GUID GUID, GlobalValueSummary::ImportKind ImportKind)

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.

Function and variable summary information to aid decisions and implementation of importing.

RAII handle that manages the lifetime of the ToolOutputFile used to output remarks.

std::string SplitDwarfFile

This class implements a map that also provides access to all stored values in a deterministic order.

iterator find(const KeyT &Key)

static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)

Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...

Class to hold module path string table and global value map, and encapsulate methods for operating on...

bool withWholeProgramVisibility() const

A Module instance is used to store all the information related to an LLVM module.

MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...

static LLVM_ABI const OptimizationLevel O3

Optimize for fast execution as much as possible.

static LLVM_ABI const OptimizationLevel O0

Disable as many optimizations as possible.

static LLVM_ABI const OptimizationLevel O2

Optimize for fast execution as much as possible without triggering significant incremental compile ti...

static LLVM_ABI const OptimizationLevel O1

Optimize quickly without destroying debuggability.

This class provides access to building LLVM's passes.

This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...

LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)

void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)

PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, ExtraArgTs... ExtraArgs)

Run all of the passes in this manager over the given unit of IR.

static LLVM_ABI Expected< PassPlugin > Load(const std::string &Filename)

Attempts to load a pass plugin from a given file.

void registerPassBuilderCallbacks(PassBuilder &PB) const

Invoke the PassBuilder callback registration.

void wait() override

Blocking wait for all the tasks to execute first.

SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...

StringRef str() const

Explicit conversion to StringRef.

This class provides an interface to register all the standard pass instrumentations and manages their...

StringRef - Represent a constant reference to a string, i.e.

Manages the enabling and disabling of subtarget specific features.

LLVM_ABI void getDefaultSubtargetFeatures(const Triple &Triple)

Adds the default features for the specified target triple.

LLVM_ABI std::string getString() const

Returns features as a string.

LLVM_ABI void AddFeature(StringRef String, bool Enable=true)

Adds Features.

Analysis pass providing the TargetLibraryInfo.

Implementation of the target library information.

Primary interface to the complete machine description for the target machine.

virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &, raw_pwrite_stream *, CodeGenFileType, bool=true, MachineModuleInfoWrapperPass *MMIWP=nullptr)

Add passes to the specified pass manager to get the specified file emitted.

const Triple & getTargetTriple() const

virtual bool splitModule(Module &M, unsigned NumParts, function_ref< void(std::unique_ptr< Module > MPart)> ModuleCallback)

Entry point for module splitting.

const Target & getTarget() const

void setPGOOption(std::optional< PGOOptions > PGOOpt)

MCTargetOptions MCOptions

Machine level options.

FloatABI::ABIType FloatABIType

FloatABIType - This setting is set by -float-abi=xxx option is specfied on the command line.

VectorLibrary VecLib

Vector math library to use.

std::string ObjectFilenameForDebug

Stores the filename/path of the final .o/.obj file, to be written in the debug information.

EABI EABIVersion

EABIVersion - This flag specifies the EABI version.

ExceptionHandling ExceptionModel

What exception model to use.

Target - Wrapper for Target specific information.

TargetMachine * createTargetMachine(const Triple &TT, StringRef CPU, StringRef Features, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM=std::nullopt, CodeGenOptLevel OL=CodeGenOptLevel::Default, bool JIT=false) const

createTargetMachine - Create a target specific machine implementation for the specified Triple.

auto async(Function &&F, Args &&...ArgList)

Asynchronous submission of a task to the pool.

The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.

Triple - Helper class for working with autoconf configuration names.

Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...

bool contains(const_arg_type_t< ValueT > V) const

Check if the set contains the given element.

PassManager manages ModulePassManagers.

void add(Pass *P) override

Add a pass to the queue of passes to run.

bool run(Module &M)

run - Execute all of the passes scheduled for execution.

A raw_ostream that writes to a file descriptor.

A raw_ostream that writes to an std::string.

A raw_ostream that writes to an SmallVector or SmallString.

Interfaces for registering analysis passes, producing common pass manager configurations,...

#define llvm_unreachable(msg)

Marks that the current location is not supposed to be reachable.

Abstract Attribute helper functions.

@ C

The default llvm calling convention, compatible with C.

LLVM_ABI void saveModuleForTwoRounds(const Module &TheModule, unsigned Task, AddStreamFn AddStream)

Save TheModule before the first codegen round.

ValuesClass values(OptsTy... Options)

Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...

initializer< Ty > init(const Ty &Val)

LLVM_ABI BitcodeModule * findThinLTOModule(MutableArrayRef< BitcodeModule > BMs)

Returns the BitcodeModule that is ThinLTO.

Definition LTOBackend.cpp:743

LLVM_ABI Error backend(const Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, Module &M, ModuleSummaryIndex &CombinedIndex)

Runs a regular LTO backend.

Definition LTOBackend.cpp:559

LLVM_ABI Error finalizeOptimizationRemarks(LLVMRemarkFileHandle DiagOutputFile)

Definition LTOBackend.cpp:548

LLVM_ABI Expected< LLVMRemarkFileHandle > setupLLVMOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, std::optional< uint64_t > RemarksHotnessThreshold=0, int Count=-1)

Setup optimization remarks.

LLVM_ABI bool initImportList(const Module &M, const ModuleSummaryIndex &CombinedIndex, FunctionImporter::ImportMapTy &ImportList)

Distributed ThinLTO: collect the referenced modules based on module summary and initialize ImportList...

Definition LTOBackend.cpp:769

LLVM_ABI bool opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod, bool IsThinLTO, ModuleSummaryIndex *ExportSummary, const ModuleSummaryIndex *ImportSummary, const std::vector< uint8_t > &CmdArgs)

Runs middle-end LTO optimizations on Mod.

Definition LTOBackend.cpp:365

LLVM_ABI Error thinBackend(const Config &C, unsigned Task, AddStreamFn AddStream, Module &M, const ModuleSummaryIndex &CombinedIndex, const FunctionImporter::ImportMapTy &ImportList, const GVSummaryMapTy &DefinedGlobals, MapVector< StringRef, BitcodeModule > *ModuleMap, bool CodeGenOnly, AddStreamFn IRAddStream=nullptr, const std::vector< uint8_t > &CmdArgs=std::vector< uint8_t >())

Runs a ThinLTO backend.

Definition LTOBackend.cpp:608

@ OF_Text

The file should be opened in text mode on platforms like z/OS that make this distinction.

@ OF_TextWithCRLF

The file should be opened in text mode and use a carriage linefeed '\r '.

LLVM_ABI std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)

Create all the non-existent directories in path.

LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")

Append to path.

This is an optimization pass for GlobalISel generic memory operations.

ThreadPoolStrategy heavyweight_hardware_concurrency(unsigned ThreadCount=0)

Returns a thread strategy for tasks requiring significant memory or other resources.

LLVM_ABI Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})

Read the specified bitcode file, returning the module.

LLVM_ABI void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)

Write the specified module to the specified raw output stream.

LLVM_ABI std::error_code inconvertibleErrorCode()

The value returned by this function can be returned from convertToErrorCode for Error values where no...

LLVM_ABI raw_fd_ostream & outs()

This returns a reference to a raw_fd_ostream for standard output.

DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy

Map of global value GUID to its summary, used to identify values defined in a particular module,...

LLVM_ABI bool convertToDeclaration(GlobalValue &GV)

Converts value GV to declaration, or replaces with a declaration if it is an alias.

std::string utostr(uint64_t X, bool isNeg=false)

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...

AnalysisManager< LazyCallGraph::SCC, LazyCallGraph & > CGSCCAnalysisManager

The CGSCC analysis manager.

LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)

Write the specified module summary index to the given raw output stream, where it will be written in ...

AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager

The loop analysis manager.

LLVM_ABI void embedBitcodeInModule(Module &M, MemoryBufferRef Buf, bool EmbedBitcode, bool EmbedCmdline, const std::vector< uint8_t > &CmdArgs)

If EmbedBitcode is set, save a copy of the llvm IR as data in the __LLVM,__bitcode section (....

LLVM_ABI void SplitModule(Module &M, unsigned N, function_ref< void(std::unique_ptr< Module > MPart)> ModuleCallback, bool PreserveLocals=false, bool RoundRobin=false)

Splits the module M into N linkable partitions.

LLVM_ABI cl::opt< bool > PrintPipelinePasses

Common option used by multiple tools to print pipeline passes.

LLVM_ABI void updatePublicTypeTestCalls(Module &M, bool WholeProgramVisibilityEnabledInLTO)

PassManager< Module > ModulePassManager

Convenience typedef for a pass manager over modules.

LLVM_ABI raw_ostream & dbgs()

dbgs() - This returns a reference to a raw_ostream for debugging messages.

LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)

LLVM_ABI Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)

Returns a list of modules in the specified bitcode buffer.

cl::opt< bool > NoPGOWarnMismatch

Error make_error(ArgTs &&... Args)

Make a Error instance representing failure using the given error info type.

LLVM_ABI raw_fd_ostream & errs()

This returns a reference to a raw_ostream for standard error.

@ Mod

The access may modify the value stored in memory.

LLVM_ABI void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)

Internalize TheModule based on the information recorded in the summaries during global summary-based ...

SingleThreadExecutor DefaultThreadPool

std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)

LLVM_ABI ImmutablePass * createImmutableModuleSummaryIndexWrapperPass(const ModuleSummaryIndex *Index)

LLVM_ABI Error errorCodeToError(std::error_code EC)

Helper for converting an std::error_code to a Error.

AnalysisManager< Function > FunctionAnalysisManager

Convenience typedef for the Function analysis manager.

std::function< Expected< std::unique_ptr< CachedFileStream > >( unsigned Task, const Twine &ModuleName)> AddStreamFn

This type defines the callback to add a file that is generated on the fly.

AnalysisManager< Module > ModuleAnalysisManager

Convenience typedef for the Module analysis manager.

LLVM_ABI void thinLTOFinalizeInModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals, bool PropagateAttrs)

Based on the information recorded in the summaries during global summary-based analysis:

LLVM_ABI void reportFatalUsageError(Error Err)

Report a fatal error that does not indicate a bug in LLVM.

A struct capturing PGO tunables.

static const Target * lookupTarget(StringRef TripleStr, std::string &Error)

lookupTarget - Lookup a target based on a target triple.

std::function< bool(unsigned Task, const Module &)> ModuleHookFn

The following callbacks deal with tasks, which normally represent the entire optimization and code ge...

bool DebugPassManager

Whether to emit the pass manager debuggging informations.

bool AddFSDiscriminator

Add FSAFDO discriminators.

std::optional< uint64_t > RemarksHotnessThreshold

The minimum hotness value a diagnostic needs in order to be included in optimization diagnostics.

LLVM_ABI Error addSaveTemps(std::string OutputFileName, bool UseInputModulePath=false, const DenseSet< StringRef > &SaveTempsArgs={})

This is a convenience function that configures this Config object to write temporary files named afte...

Definition LTOBackend.cpp:87

ModuleHookFn PreOptModuleHook

This module hook is called after linking (regular LTO) or loading (ThinLTO) the module,...

CombinedIndexHookFn CombinedIndexHook

std::optional< CodeModel::Model > CodeModel

std::function< void(legacy::PassManager &)> PreCodeGenPassesHook

For adding passes that run right before codegen.

std::vector< std::string > MAttrs

CodeGenOptLevel CGOptLevel

PipelineTuningOptions PTO

Tunable parameters for passes in the default pipelines.

std::unique_ptr< raw_ostream > ResolutionFile

If this field is set, LTO will write input file paths and symbol resolutions here in llvm-lto2 comman...

std::string DwoDir

The directory to store .dwo files.

std::string RemarksFilename

Optimization remarks file path.

ModuleHookFn PostPromoteModuleHook

This hook is called after promoting any internal functions (ThinLTO-specific).

std::string ProfileRemapping

Name remapping file for profile data.

std::string SplitDwarfFile

The name for the split debug info file used for the DW_AT_[GNU_]dwo_name attribute in the skeleton CU...

std::string SplitDwarfOutput

The path to write a .dwo file to.

ModuleHookFn PostOptModuleHook

This module hook is called after optimization is complete.

std::string RemarksPasses

Optimization remarks pass filter.

std::string OptPipeline

If this field is set, the set of passes run in the middle-end optimizer will be the one specified by ...

bool RunCSIRInstr

Run PGO context sensitive IR instrumentation.

ModuleHookFn PostInternalizeModuleHook

This hook is called after internalizing the module.

ModuleHookFn PostImportModuleHook

This hook is called after importing from other modules (ThinLTO-specific).

bool RemarksWithHotness

Whether to emit optimization remarks with hotness informations.

std::vector< std::string > PassPlugins

std::string CSIRProfile

Context Sensitive PGO profile path.

ModuleHookFn PreCodeGenModuleHook

This module hook is called before code generation.

std::optional< Reloc::Model > RelocModel

bool ShouldDiscardValueNames

bool PGOWarnMismatch

Turn on/off the warning about a hash mismatch in the PGO profile data.

CodeGenFileType CGFileType

bool Freestanding

Flag to indicate that the optimizer should not assume builtins are present on the target.

std::string SampleProfile

Sample PGO profile path.

std::string RemarksFormat

The format used for serializing remarks (default: YAML).

A derived class of LLVMContext that initializes itself according to a given Config object.