Path: blob/main/contrib/llvm-project/llvm/lib/LTO/LTOCodeGenerator.cpp
35233 views
//===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the Link Time Optimization library. This library is9// intended to be used by linker to optimize code at link time.10//11//===----------------------------------------------------------------------===//1213#include "llvm/LTO/legacy/LTOCodeGenerator.h"1415#include "llvm/ADT/Statistic.h"16#include "llvm/ADT/StringExtras.h"17#include "llvm/Analysis/Passes.h"18#include "llvm/Analysis/TargetLibraryInfo.h"19#include "llvm/Analysis/TargetTransformInfo.h"20#include "llvm/Bitcode/BitcodeWriter.h"21#include "llvm/CodeGen/CommandFlags.h"22#include "llvm/CodeGen/TargetSubtargetInfo.h"23#include "llvm/Config/config.h"24#include "llvm/IR/Constants.h"25#include "llvm/IR/DataLayout.h"26#include "llvm/IR/DebugInfo.h"27#include "llvm/IR/DerivedTypes.h"28#include "llvm/IR/DiagnosticInfo.h"29#include "llvm/IR/DiagnosticPrinter.h"30#include "llvm/IR/LLVMContext.h"31#include "llvm/IR/LLVMRemarkStreamer.h"32#include "llvm/IR/LegacyPassManager.h"33#include "llvm/IR/Mangler.h"34#include "llvm/IR/Module.h"35#include "llvm/IR/PassTimingInfo.h"36#include "llvm/IR/Verifier.h"37#include "llvm/LTO/LTO.h"38#include "llvm/LTO/LTOBackend.h"39#include "llvm/LTO/legacy/LTOModule.h"40#include "llvm/LTO/legacy/UpdateCompilerUsed.h"41#include "llvm/Linker/Linker.h"42#include "llvm/MC/MCAsmInfo.h"43#include "llvm/MC/MCContext.h"44#include "llvm/MC/TargetRegistry.h"45#include "llvm/Remarks/HotnessThresholdParser.h"46#include "llvm/Support/CommandLine.h"47#include "llvm/Support/FileSystem.h"48#include "llvm/Support/MemoryBuffer.h"49#include "llvm/Support/Process.h"50#include "llvm/Support/Signals.h"51#include "llvm/Support/TargetSelect.h"52#include "llvm/Support/ToolOutputFile.h"53#include "llvm/Support/YAMLTraits.h"54#include "llvm/Support/raw_ostream.h"55#include "llvm/Target/TargetOptions.h"56#include "llvm/TargetParser/Host.h"57#include "llvm/TargetParser/SubtargetFeature.h"58#include "llvm/Transforms/IPO.h"59#include "llvm/Transforms/IPO/Internalize.h"60#include "llvm/Transforms/IPO/WholeProgramDevirt.h"61#include "llvm/Transforms/ObjCARC.h"62#include "llvm/Transforms/Utils/ModuleUtils.h"63#include <optional>64#include <system_error>65using namespace llvm;6667const char* LTOCodeGenerator::getVersionString() {68return PACKAGE_NAME " version " PACKAGE_VERSION;69}7071namespace llvm {72cl::opt<bool> LTODiscardValueNames(73"lto-discard-value-names",74cl::desc("Strip names from Value during LTO (other than GlobalValue)."),75#ifdef NDEBUG76cl::init(true),77#else78cl::init(false),79#endif80cl::Hidden);8182cl::opt<bool> RemarksWithHotness(83"lto-pass-remarks-with-hotness",84cl::desc("With PGO, include profile count in optimization remarks"),85cl::Hidden);8687cl::opt<std::optional<uint64_t>, false, remarks::HotnessThresholdParser>88RemarksHotnessThreshold(89"lto-pass-remarks-hotness-threshold",90cl::desc("Minimum profile count required for an "91"optimization remark to be output."92" Use 'auto' to apply the threshold from profile summary."),93cl::value_desc("uint or 'auto'"), cl::init(0), cl::Hidden);9495cl::opt<std::string>96RemarksFilename("lto-pass-remarks-output",97cl::desc("Output filename for pass remarks"),98cl::value_desc("filename"));99100cl::opt<std::string>101RemarksPasses("lto-pass-remarks-filter",102cl::desc("Only record optimization remarks from passes whose "103"names match the given regular expression"),104cl::value_desc("regex"));105106cl::opt<std::string> RemarksFormat(107"lto-pass-remarks-format",108cl::desc("The format used for serializing remarks (default: YAML)"),109cl::value_desc("format"), cl::init("yaml"));110111cl::opt<std::string> LTOStatsFile(112"lto-stats-file",113cl::desc("Save statistics to the specified file"),114cl::Hidden);115116cl::opt<std::string> AIXSystemAssemblerPath(117"lto-aix-system-assembler",118cl::desc("Path to a system assembler, picked up on AIX only"),119cl::value_desc("path"));120121cl::opt<bool>122LTORunCSIRInstr("cs-profile-generate",123cl::desc("Perform context sensitive PGO instrumentation"));124125cl::opt<std::string>126LTOCSIRProfile("cs-profile-path",127cl::desc("Context sensitive profile file path"));128} // namespace llvm129130LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)131: Context(Context), MergedModule(new Module("ld-temp.o", Context)),132TheLinker(new Linker(*MergedModule)) {133Context.setDiscardValueNames(LTODiscardValueNames);134Context.enableDebugTypeODRUniquing();135136Config.CodeModel = std::nullopt;137Config.StatsFile = LTOStatsFile;138Config.PreCodeGenPassesHook = [](legacy::PassManager &PM) {139PM.add(createObjCARCContractPass());140};141142Config.RunCSIRInstr = LTORunCSIRInstr;143Config.CSIRProfile = LTOCSIRProfile;144}145146LTOCodeGenerator::~LTOCodeGenerator() = default;147148void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) {149for (const StringRef &Undef : Mod->getAsmUndefinedRefs())150AsmUndefinedRefs.insert(Undef);151}152153bool LTOCodeGenerator::addModule(LTOModule *Mod) {154assert(&Mod->getModule().getContext() == &Context &&155"Expected module in same context");156157bool ret = TheLinker->linkInModule(Mod->takeModule());158setAsmUndefinedRefs(Mod);159160// We've just changed the input, so let's make sure we verify it.161HasVerifiedInput = false;162163return !ret;164}165166void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {167assert(&Mod->getModule().getContext() == &Context &&168"Expected module in same context");169170AsmUndefinedRefs.clear();171172MergedModule = Mod->takeModule();173TheLinker = std::make_unique<Linker>(*MergedModule);174setAsmUndefinedRefs(&*Mod);175176// We've just changed the input, so let's make sure we verify it.177HasVerifiedInput = false;178}179180void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {181Config.Options = Options;182}183184void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {185switch (Debug) {186case LTO_DEBUG_MODEL_NONE:187EmitDwarfDebugInfo = false;188return;189190case LTO_DEBUG_MODEL_DWARF:191EmitDwarfDebugInfo = true;192return;193}194llvm_unreachable("Unknown debug format!");195}196197void LTOCodeGenerator::setOptLevel(unsigned Level) {198Config.OptLevel = Level;199Config.PTO.LoopVectorization = Config.OptLevel > 1;200Config.PTO.SLPVectorization = Config.OptLevel > 1;201std::optional<CodeGenOptLevel> CGOptLevelOrNone =202CodeGenOpt::getLevel(Config.OptLevel);203assert(CGOptLevelOrNone && "Unknown optimization level!");204Config.CGOptLevel = *CGOptLevelOrNone;205}206207bool LTOCodeGenerator::writeMergedModules(StringRef Path) {208if (!determineTarget())209return false;210211// We always run the verifier once on the merged module.212verifyMergedModuleOnce();213214// mark which symbols can not be internalized215applyScopeRestrictions();216217// create output file218std::error_code EC;219ToolOutputFile Out(Path, EC, sys::fs::OF_None);220if (EC) {221std::string ErrMsg = "could not open bitcode file for writing: ";222ErrMsg += Path.str() + ": " + EC.message();223emitError(ErrMsg);224return false;225}226227// write bitcode to it228WriteBitcodeToFile(*MergedModule, Out.os(), ShouldEmbedUselists);229Out.os().close();230231if (Out.os().has_error()) {232std::string ErrMsg = "could not write bitcode file: ";233ErrMsg += Path.str() + ": " + Out.os().error().message();234emitError(ErrMsg);235Out.os().clear_error();236return false;237}238239Out.keep();240return true;241}242243bool LTOCodeGenerator::useAIXSystemAssembler() {244const auto &Triple = TargetMach->getTargetTriple();245return Triple.isOSAIX() && Config.Options.DisableIntegratedAS;246}247248bool LTOCodeGenerator::runAIXSystemAssembler(SmallString<128> &AssemblyFile) {249assert(useAIXSystemAssembler() &&250"Runing AIX system assembler when integrated assembler is available!");251252// Set the system assembler path.253SmallString<256> AssemblerPath("/usr/bin/as");254if (!llvm::AIXSystemAssemblerPath.empty()) {255if (llvm::sys::fs::real_path(llvm::AIXSystemAssemblerPath, AssemblerPath,256/* expand_tilde */ true)) {257emitError(258"Cannot find the assembler specified by lto-aix-system-assembler");259return false;260}261}262263// Setup the LDR_CNTRL variable264std::string LDR_CNTRL_var = "LDR_CNTRL=MAXDATA32=0xA0000000@DSA";265if (std::optional<std::string> V = sys::Process::GetEnv("LDR_CNTRL"))266LDR_CNTRL_var += ("@" + *V);267268// Prepare inputs for the assember.269const auto &Triple = TargetMach->getTargetTriple();270const char *Arch = Triple.isArch64Bit() ? "-a64" : "-a32";271std::string ObjectFileName(AssemblyFile);272ObjectFileName[ObjectFileName.size() - 1] = 'o';273SmallVector<StringRef, 8> Args = {274"/bin/env", LDR_CNTRL_var,275AssemblerPath, Arch,276"-many", "-o",277ObjectFileName, AssemblyFile};278279// Invoke the assembler.280int RC = sys::ExecuteAndWait(Args[0], Args);281282// Handle errors.283if (RC < -1) {284emitError("LTO assembler exited abnormally");285return false;286}287if (RC < 0) {288emitError("Unable to invoke LTO assembler");289return false;290}291if (RC > 0) {292emitError("LTO assembler invocation returned non-zero");293return false;294}295296// Cleanup.297remove(AssemblyFile.c_str());298299// Fix the output file name.300AssemblyFile = ObjectFileName;301302return true;303}304305bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {306if (useAIXSystemAssembler())307setFileType(CodeGenFileType::AssemblyFile);308309// make unique temp output file to put generated code310SmallString<128> Filename;311312auto AddStream =313[&](size_t Task,314const Twine &ModuleName) -> std::unique_ptr<CachedFileStream> {315StringRef Extension(316Config.CGFileType == CodeGenFileType::AssemblyFile ? "s" : "o");317318int FD;319std::error_code EC =320sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);321if (EC)322emitError(EC.message());323324return std::make_unique<CachedFileStream>(325std::make_unique<llvm::raw_fd_ostream>(FD, true));326};327328bool genResult = compileOptimized(AddStream, 1);329330if (!genResult) {331sys::fs::remove(Twine(Filename));332return false;333}334335// If statistics were requested, save them to the specified file or336// print them out after codegen.337if (StatsFile)338PrintStatisticsJSON(StatsFile->os());339else if (AreStatisticsEnabled())340PrintStatistics();341342if (useAIXSystemAssembler())343if (!runAIXSystemAssembler(Filename))344return false;345346NativeObjectPath = Filename.c_str();347*Name = NativeObjectPath.c_str();348return true;349}350351std::unique_ptr<MemoryBuffer>352LTOCodeGenerator::compileOptimized() {353const char *name;354if (!compileOptimizedToFile(&name))355return nullptr;356357// read .o file into memory buffer358ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = MemoryBuffer::getFile(359name, /*IsText=*/false, /*RequiresNullTerminator=*/false);360if (std::error_code EC = BufferOrErr.getError()) {361emitError(EC.message());362sys::fs::remove(NativeObjectPath);363return nullptr;364}365366// remove temp files367sys::fs::remove(NativeObjectPath);368369return std::move(*BufferOrErr);370}371372bool LTOCodeGenerator::compile_to_file(const char **Name) {373if (!optimize())374return false;375376return compileOptimizedToFile(Name);377}378379std::unique_ptr<MemoryBuffer> LTOCodeGenerator::compile() {380if (!optimize())381return nullptr;382383return compileOptimized();384}385386bool LTOCodeGenerator::determineTarget() {387if (TargetMach)388return true;389390TripleStr = MergedModule->getTargetTriple();391if (TripleStr.empty()) {392TripleStr = sys::getDefaultTargetTriple();393MergedModule->setTargetTriple(TripleStr);394}395llvm::Triple Triple(TripleStr);396397// create target machine from info for merged modules398std::string ErrMsg;399MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);400if (!MArch) {401emitError(ErrMsg);402return false;403}404405// Construct LTOModule, hand over ownership of module and target. Use MAttr as406// the default set of features.407SubtargetFeatures Features(join(Config.MAttrs, ""));408Features.getDefaultSubtargetFeatures(Triple);409FeatureStr = Features.getString();410if (Config.CPU.empty())411Config.CPU = lto::getThinLTODefaultCPU(Triple);412413// If data-sections is not explicitly set or unset, set data-sections by414// default to match the behaviour of lld and gold plugin.415if (!codegen::getExplicitDataSections())416Config.Options.DataSections = true;417418TargetMach = createTargetMachine();419assert(TargetMach && "Unable to create target machine");420421return true;422}423424std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {425assert(MArch && "MArch is not set!");426return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(427TripleStr, Config.CPU, FeatureStr, Config.Options, Config.RelocModel,428std::nullopt, Config.CGOptLevel));429}430431// If a linkonce global is present in the MustPreserveSymbols, we need to make432// sure we honor this. To force the compiler to not drop it, we add it to the433// "llvm.compiler.used" global.434void LTOCodeGenerator::preserveDiscardableGVs(435Module &TheModule,436llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {437std::vector<GlobalValue *> Used;438auto mayPreserveGlobal = [&](GlobalValue &GV) {439if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||440!mustPreserveGV(GV))441return;442if (GV.hasAvailableExternallyLinkage())443return emitWarning(444(Twine("Linker asked to preserve available_externally global: '") +445GV.getName() + "'").str());446if (GV.hasInternalLinkage())447return emitWarning((Twine("Linker asked to preserve internal global: '") +448GV.getName() + "'").str());449Used.push_back(&GV);450};451for (auto &GV : TheModule)452mayPreserveGlobal(GV);453for (auto &GV : TheModule.globals())454mayPreserveGlobal(GV);455for (auto &GV : TheModule.aliases())456mayPreserveGlobal(GV);457458if (Used.empty())459return;460461appendToCompilerUsed(TheModule, Used);462}463464void LTOCodeGenerator::applyScopeRestrictions() {465if (ScopeRestrictionsDone)466return;467468// Declare a callback for the internalize pass that will ask for every469// candidate GlobalValue if it can be internalized or not.470Mangler Mang;471SmallString<64> MangledName;472auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {473// Unnamed globals can't be mangled, but they can't be preserved either.474if (!GV.hasName())475return false;476477// Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled478// with the linker supplied name, which on Darwin includes a leading479// underscore.480MangledName.clear();481MangledName.reserve(GV.getName().size() + 1);482Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);483return MustPreserveSymbols.count(MangledName);484};485486// Preserve linkonce value on linker request487preserveDiscardableGVs(*MergedModule, mustPreserveGV);488489if (!ShouldInternalize)490return;491492if (ShouldRestoreGlobalsLinkage) {493// Record the linkage type of non-local symbols so they can be restored494// prior495// to module splitting.496auto RecordLinkage = [&](const GlobalValue &GV) {497if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&498GV.hasName())499ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));500};501for (auto &GV : *MergedModule)502RecordLinkage(GV);503for (auto &GV : MergedModule->globals())504RecordLinkage(GV);505for (auto &GV : MergedModule->aliases())506RecordLinkage(GV);507}508509// Update the llvm.compiler_used globals to force preserving libcalls and510// symbols referenced from asm511updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);512513internalizeModule(*MergedModule, mustPreserveGV);514515ScopeRestrictionsDone = true;516}517518/// Restore original linkage for symbols that may have been internalized519void LTOCodeGenerator::restoreLinkageForExternals() {520if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)521return;522523assert(ScopeRestrictionsDone &&524"Cannot externalize without internalization!");525526if (ExternalSymbols.empty())527return;528529auto externalize = [this](GlobalValue &GV) {530if (!GV.hasLocalLinkage() || !GV.hasName())531return;532533auto I = ExternalSymbols.find(GV.getName());534if (I == ExternalSymbols.end())535return;536537GV.setLinkage(I->second);538};539540llvm::for_each(MergedModule->functions(), externalize);541llvm::for_each(MergedModule->globals(), externalize);542llvm::for_each(MergedModule->aliases(), externalize);543}544545void LTOCodeGenerator::verifyMergedModuleOnce() {546// Only run on the first call.547if (HasVerifiedInput)548return;549HasVerifiedInput = true;550551bool BrokenDebugInfo = false;552if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))553report_fatal_error("Broken module found, compilation aborted!");554if (BrokenDebugInfo) {555emitWarning("Invalid debug info found, debug info will be stripped");556StripDebugInfo(*MergedModule);557}558}559560void LTOCodeGenerator::finishOptimizationRemarks() {561if (DiagnosticOutputFile) {562DiagnosticOutputFile->keep();563// FIXME: LTOCodeGenerator dtor is not invoked on Darwin564DiagnosticOutputFile->os().flush();565}566}567568/// Optimize merged modules using various IPO passes569bool LTOCodeGenerator::optimize() {570if (!this->determineTarget())571return false;572573// libLTO parses options late, so re-set them here.574Context.setDiscardValueNames(LTODiscardValueNames);575576auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(577Context, RemarksFilename, RemarksPasses, RemarksFormat,578RemarksWithHotness, RemarksHotnessThreshold);579if (!DiagFileOrErr) {580errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";581report_fatal_error("Can't get an output file for the remarks");582}583DiagnosticOutputFile = std::move(*DiagFileOrErr);584585// Setup output file to emit statistics.586auto StatsFileOrErr = lto::setupStatsFile(LTOStatsFile);587if (!StatsFileOrErr) {588errs() << "Error: " << toString(StatsFileOrErr.takeError()) << "\n";589report_fatal_error("Can't get an output file for the statistics");590}591StatsFile = std::move(StatsFileOrErr.get());592593// Currently there is no support for enabling whole program visibility via a594// linker option in the old LTO API, but this call allows it to be specified595// via the internal option. Must be done before WPD invoked via the optimizer596// pipeline run below.597updatePublicTypeTestCalls(*MergedModule,598/* WholeProgramVisibilityEnabledInLTO */ false);599updateVCallVisibilityInModule(600*MergedModule,601/* WholeProgramVisibilityEnabledInLTO */ false,602// FIXME: These need linker information via a603// TBD new interface.604/*DynamicExportSymbols=*/{},605/*ValidateAllVtablesHaveTypeInfos=*/false,606/*IsVisibleToRegularObj=*/[](StringRef) { return true; });607608// We always run the verifier once on the merged module, the `DisableVerify`609// parameter only applies to subsequent verify.610verifyMergedModuleOnce();611612// Mark which symbols can not be internalized613this->applyScopeRestrictions();614615// Add an appropriate DataLayout instance for this module...616MergedModule->setDataLayout(TargetMach->createDataLayout());617618if (!SaveIRBeforeOptPath.empty()) {619std::error_code EC;620raw_fd_ostream OS(SaveIRBeforeOptPath, EC, sys::fs::OF_None);621if (EC)622report_fatal_error(Twine("Failed to open ") + SaveIRBeforeOptPath +623" to save optimized bitcode\n");624WriteBitcodeToFile(*MergedModule, OS,625/* ShouldPreserveUseListOrder */ true);626}627628ModuleSummaryIndex CombinedIndex(false);629TargetMach = createTargetMachine();630if (!opt(Config, TargetMach.get(), 0, *MergedModule, /*IsThinLTO=*/false,631/*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,632/*CmdArgs*/ std::vector<uint8_t>())) {633emitError("LTO middle-end optimizations failed");634return false;635}636637return true;638}639640bool LTOCodeGenerator::compileOptimized(AddStreamFn AddStream,641unsigned ParallelismLevel) {642if (!this->determineTarget())643return false;644645// We always run the verifier once on the merged module. If it has already646// been called in optimize(), this call will return early.647verifyMergedModuleOnce();648649// Re-externalize globals that may have been internalized to increase scope650// for splitting651restoreLinkageForExternals();652653ModuleSummaryIndex CombinedIndex(false);654655Config.CodeGenOnly = true;656Error Err = backend(Config, AddStream, ParallelismLevel, *MergedModule,657CombinedIndex);658assert(!Err && "unexpected code-generation failure");659(void)Err;660661// If statistics were requested, save them to the specified file or662// print them out after codegen.663if (StatsFile)664PrintStatisticsJSON(StatsFile->os());665else if (AreStatisticsEnabled())666PrintStatistics();667668reportAndResetTimings();669670finishOptimizationRemarks();671672return true;673}674675void LTOCodeGenerator::setCodeGenDebugOptions(ArrayRef<StringRef> Options) {676for (StringRef Option : Options)677CodegenOptions.push_back(Option.str());678}679680void LTOCodeGenerator::parseCodeGenDebugOptions() {681if (!CodegenOptions.empty())682llvm::parseCommandLineOptions(CodegenOptions);683}684685void llvm::parseCommandLineOptions(std::vector<std::string> &Options) {686if (!Options.empty()) {687// ParseCommandLineOptions() expects argv[0] to be program name.688std::vector<const char *> CodegenArgv(1, "libLLVMLTO");689for (std::string &Arg : Options)690CodegenArgv.push_back(Arg.c_str());691cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());692}693}694695void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI) {696// Map the LLVM internal diagnostic severity to the LTO diagnostic severity.697lto_codegen_diagnostic_severity_t Severity;698switch (DI.getSeverity()) {699case DS_Error:700Severity = LTO_DS_ERROR;701break;702case DS_Warning:703Severity = LTO_DS_WARNING;704break;705case DS_Remark:706Severity = LTO_DS_REMARK;707break;708case DS_Note:709Severity = LTO_DS_NOTE;710break;711}712// Create the string that will be reported to the external diagnostic handler.713std::string MsgStorage;714raw_string_ostream Stream(MsgStorage);715DiagnosticPrinterRawOStream DP(Stream);716DI.print(DP);717Stream.flush();718719// If this method has been called it means someone has set up an external720// diagnostic handler. Assert on that.721assert(DiagHandler && "Invalid diagnostic handler");722(*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);723}724725namespace {726struct LTODiagnosticHandler : public DiagnosticHandler {727LTOCodeGenerator *CodeGenerator;728LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)729: CodeGenerator(CodeGenPtr) {}730bool handleDiagnostics(const DiagnosticInfo &DI) override {731CodeGenerator->DiagnosticHandler(DI);732return true;733}734};735}736737void738LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,739void *Ctxt) {740this->DiagHandler = DiagHandler;741this->DiagContext = Ctxt;742if (!DiagHandler)743return Context.setDiagnosticHandler(nullptr);744// Register the LTOCodeGenerator stub in the LLVMContext to forward the745// diagnostic to the external DiagHandler.746Context.setDiagnosticHandler(std::make_unique<LTODiagnosticHandler>(this),747true);748}749750namespace {751class LTODiagnosticInfo : public DiagnosticInfo {752const Twine &Msg;753public:754LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)755: DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}756void print(DiagnosticPrinter &DP) const override { DP << Msg; }757};758}759760void LTOCodeGenerator::emitError(const std::string &ErrMsg) {761if (DiagHandler)762(*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);763else764Context.diagnose(LTODiagnosticInfo(ErrMsg));765}766767void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {768if (DiagHandler)769(*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);770else771Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));772}773774775