Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:11

0001 //===-Config.h - LLVM Link Time Optimizer Configuration ---------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file defines the lto::Config data structure, which allows clients to
0010 // configure LTO.
0011 //
0012 //===----------------------------------------------------------------------===//
0013 
0014 #ifndef LLVM_LTO_CONFIG_H
0015 #define LLVM_LTO_CONFIG_H
0016 
0017 #include "llvm/ADT/DenseSet.h"
0018 #include "llvm/Config/llvm-config.h"
0019 #include "llvm/IR/DiagnosticInfo.h"
0020 #include "llvm/IR/GlobalValue.h"
0021 #include "llvm/IR/LLVMContext.h"
0022 #include "llvm/IR/LegacyPassManager.h"
0023 #include "llvm/Passes/PassBuilder.h"
0024 #include "llvm/Support/CodeGen.h"
0025 #include "llvm/Target/TargetOptions.h"
0026 
0027 #include <functional>
0028 #include <optional>
0029 
0030 namespace llvm {
0031 
0032 class Error;
0033 class Module;
0034 class ModuleSummaryIndex;
0035 class raw_pwrite_stream;
0036 
0037 namespace lto {
0038 
0039 /// LTO configuration. A linker can configure LTO by setting fields in this data
0040 /// structure and passing it to the lto::LTO constructor.
0041 struct Config {
0042   enum VisScheme {
0043     FromPrevailing,
0044     ELF,
0045   };
0046   // Note: when adding fields here, consider whether they need to be added to
0047   // computeLTOCacheKey in LTO.cpp.
0048   std::string CPU;
0049   TargetOptions Options;
0050   std::vector<std::string> MAttrs;
0051   std::vector<std::string> MllvmArgs;
0052   std::vector<std::string> PassPlugins;
0053   /// For adding passes that run right before codegen.
0054   std::function<void(legacy::PassManager &)> PreCodeGenPassesHook;
0055   std::optional<Reloc::Model> RelocModel = Reloc::PIC_;
0056   std::optional<CodeModel::Model> CodeModel;
0057   CodeGenOptLevel CGOptLevel = CodeGenOptLevel::Default;
0058   CodeGenFileType CGFileType = CodeGenFileType::ObjectFile;
0059   unsigned OptLevel = 2;
0060   bool VerifyEach = false;
0061   bool DisableVerify = false;
0062 
0063   /// Flag to indicate that the optimizer should not assume builtins are present
0064   /// on the target.
0065   bool Freestanding = false;
0066 
0067   /// Disable entirely the optimizer, including importing for ThinLTO
0068   bool CodeGenOnly = false;
0069 
0070   /// Run PGO context sensitive IR instrumentation.
0071   bool RunCSIRInstr = false;
0072 
0073   /// Turn on/off the warning about a hash mismatch in the PGO profile data.
0074   bool PGOWarnMismatch = true;
0075 
0076   /// Asserts whether we can assume whole program visibility during the LTO
0077   /// link.
0078   bool HasWholeProgramVisibility = false;
0079 
0080   /// We're validating that all native vtables have corresponding type infos.
0081   bool ValidateAllVtablesHaveTypeInfos = false;
0082   /// If all native vtables have corresponding type infos, allow
0083   /// usage of RTTI to block devirtualization on types used in native files.
0084   bool AllVtablesHaveTypeInfos = false;
0085 
0086   /// Always emit a Regular LTO object even when it is empty because no Regular
0087   /// LTO modules were linked. This option is useful for some build system which
0088   /// want to know a priori all possible output files.
0089   bool AlwaysEmitRegularLTOObj = false;
0090 
0091   /// If true, the LTO instance creates copies of the symbol names for LTO::run.
0092   /// The lld linker uses string saver to keep symbol names alive and doesn't
0093   /// need to create copies, so it can set this field to false.
0094   bool KeepSymbolNameCopies = true;
0095 
0096   /// Allows non-imported definitions to get the potentially more constraining
0097   /// visibility from the prevailing definition. FromPrevailing is the default
0098   /// because it works for many binary formats. ELF can use the more optimized
0099   /// 'ELF' scheme.
0100   VisScheme VisibilityScheme = FromPrevailing;
0101 
0102   /// If this field is set, the set of passes run in the middle-end optimizer
0103   /// will be the one specified by the string. Only works with the new pass
0104   /// manager as the old one doesn't have this ability.
0105   std::string OptPipeline;
0106 
0107   // If this field is set, it has the same effect of specifying an AA pipeline
0108   // identified by the string. Only works with the new pass manager, in
0109   // conjunction OptPipeline.
0110   std::string AAPipeline;
0111 
0112   /// Setting this field will replace target triples in input files with this
0113   /// triple.
0114   std::string OverrideTriple;
0115 
0116   /// Setting this field will replace unspecified target triples in input files
0117   /// with this triple.
0118   std::string DefaultTriple;
0119 
0120   /// Context Sensitive PGO profile path.
0121   std::string CSIRProfile;
0122 
0123   /// Sample PGO profile path.
0124   std::string SampleProfile;
0125 
0126   /// Name remapping file for profile data.
0127   std::string ProfileRemapping;
0128 
0129   /// The directory to store .dwo files.
0130   std::string DwoDir;
0131 
0132   /// The name for the split debug info file used for the DW_AT_[GNU_]dwo_name
0133   /// attribute in the skeleton CU. This should generally only be used when
0134   /// running an individual backend directly via thinBackend(), as otherwise
0135   /// all objects would use the same .dwo file. Not used as output path.
0136   std::string SplitDwarfFile;
0137 
0138   /// The path to write a .dwo file to. This should generally only be used when
0139   /// running an individual backend directly via thinBackend(), as otherwise
0140   /// all .dwo files will be written to the same path. Not used in skeleton CU.
0141   std::string SplitDwarfOutput;
0142 
0143   /// Optimization remarks file path.
0144   std::string RemarksFilename;
0145 
0146   /// Optimization remarks pass filter.
0147   std::string RemarksPasses;
0148 
0149   /// Whether to emit optimization remarks with hotness informations.
0150   bool RemarksWithHotness = false;
0151 
0152   /// The minimum hotness value a diagnostic needs in order to be included in
0153   /// optimization diagnostics.
0154   ///
0155   /// The threshold is an Optional value, which maps to one of the 3 states:
0156   /// 1. 0            => threshold disabled. All emarks will be printed.
0157   /// 2. positive int => manual threshold by user. Remarks with hotness exceed
0158   ///                    threshold will be printed.
0159   /// 3. None         => 'auto' threshold by user. The actual value is not
0160   ///                    available at command line, but will be synced with
0161   ///                    hotness threhold from profile summary during
0162   ///                    compilation.
0163   ///
0164   /// If threshold option is not specified, it is disabled by default.
0165   std::optional<uint64_t> RemarksHotnessThreshold = 0;
0166 
0167   /// The format used for serializing remarks (default: YAML).
0168   std::string RemarksFormat;
0169 
0170   /// Whether to emit the pass manager debuggging informations.
0171   bool DebugPassManager = false;
0172 
0173   /// Statistics output file path.
0174   std::string StatsFile;
0175 
0176   /// Specific thinLTO modules to compile.
0177   std::vector<std::string> ThinLTOModulesToCompile;
0178 
0179   /// Time trace enabled.
0180   bool TimeTraceEnabled = false;
0181 
0182   /// Time trace granularity.
0183   unsigned TimeTraceGranularity = 500;
0184 
0185   bool ShouldDiscardValueNames = true;
0186   DiagnosticHandlerFunction DiagHandler;
0187 
0188   /// Add FSAFDO discriminators.
0189   bool AddFSDiscriminator = false;
0190 
0191   /// If this field is set, LTO will write input file paths and symbol
0192   /// resolutions here in llvm-lto2 command line flag format. This can be
0193   /// used for testing and for running the LTO pipeline outside of the linker
0194   /// with llvm-lto2.
0195   std::unique_ptr<raw_ostream> ResolutionFile;
0196 
0197   /// Tunable parameters for passes in the default pipelines.
0198   PipelineTuningOptions PTO;
0199 
0200   /// The following callbacks deal with tasks, which normally represent the
0201   /// entire optimization and code generation pipeline for what will become a
0202   /// single native object file. Each task has a unique identifier between 0 and
0203   /// getMaxTasks()-1, which is supplied to the callback via the Task parameter.
0204   /// A task represents the entire pipeline for ThinLTO and regular
0205   /// (non-parallel) LTO, but a parallel code generation task will be split into
0206   /// N tasks before code generation, where N is the parallelism level.
0207   ///
0208   /// LTO may decide to stop processing a task at any time, for example if the
0209   /// module is empty or if a module hook (see below) returns false. For this
0210   /// reason, the client should not expect to receive exactly getMaxTasks()
0211   /// native object files.
0212 
0213   /// A module hook may be used by a linker to perform actions during the LTO
0214   /// pipeline. For example, a linker may use this function to implement
0215   /// -save-temps. If this function returns false, any further processing for
0216   /// that task is aborted.
0217   ///
0218   /// Module hooks must be thread safe with respect to the linker's internal
0219   /// data structures. A module hook will never be called concurrently from
0220   /// multiple threads with the same task ID, or the same module.
0221   ///
0222   /// Note that in out-of-process backend scenarios, none of the hooks will be
0223   /// called for ThinLTO tasks.
0224   using ModuleHookFn = std::function<bool(unsigned Task, const Module &)>;
0225 
0226   /// This module hook is called after linking (regular LTO) or loading
0227   /// (ThinLTO) the module, before modifying it.
0228   ModuleHookFn PreOptModuleHook;
0229 
0230   /// This hook is called after promoting any internal functions
0231   /// (ThinLTO-specific).
0232   ModuleHookFn PostPromoteModuleHook;
0233 
0234   /// This hook is called after internalizing the module.
0235   ModuleHookFn PostInternalizeModuleHook;
0236 
0237   /// This hook is called after importing from other modules (ThinLTO-specific).
0238   ModuleHookFn PostImportModuleHook;
0239 
0240   /// This module hook is called after optimization is complete.
0241   ModuleHookFn PostOptModuleHook;
0242 
0243   /// This module hook is called before code generation. It is similar to the
0244   /// PostOptModuleHook, but for parallel code generation it is called after
0245   /// splitting the module.
0246   ModuleHookFn PreCodeGenModuleHook;
0247 
0248   /// A combined index hook is called after all per-module indexes have been
0249   /// combined (ThinLTO-specific). It can be used to implement -save-temps for
0250   /// the combined index.
0251   ///
0252   /// If this function returns false, any further processing for ThinLTO tasks
0253   /// is aborted.
0254   ///
0255   /// It is called regardless of whether the backend is in-process, although it
0256   /// is not called from individual backend processes.
0257   using CombinedIndexHookFn = std::function<bool(
0258       const ModuleSummaryIndex &Index,
0259       const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols)>;
0260   CombinedIndexHookFn CombinedIndexHook;
0261 
0262   /// This is a convenience function that configures this Config object to write
0263   /// temporary files named after the given OutputFileName for each of the LTO
0264   /// phases to disk. A client can use this function to implement -save-temps.
0265   ///
0266   /// FIXME: Temporary files derived from ThinLTO backends are currently named
0267   /// after the input file name, rather than the output file name, when
0268   /// UseInputModulePath is set to true.
0269   ///
0270   /// Specifically, it (1) sets each of the above module hooks and the combined
0271   /// index hook to a function that calls the hook function (if any) that was
0272   /// present in the appropriate field when the addSaveTemps function was
0273   /// called, and writes the module to a bitcode file with a name prefixed by
0274   /// the given output file name, and (2) creates a resolution file whose name
0275   /// is prefixed by the given output file name and sets ResolutionFile to its
0276   /// file handle.
0277   ///
0278   /// SaveTempsArgs can be specified to select which temps to save.
0279   /// If SaveTempsArgs is not provided, all temps are saved.
0280   Error addSaveTemps(std::string OutputFileName,
0281                      bool UseInputModulePath = false,
0282                      const DenseSet<StringRef> &SaveTempsArgs = {});
0283 };
0284 
0285 struct LTOLLVMDiagnosticHandler : public DiagnosticHandler {
0286   DiagnosticHandlerFunction *Fn;
0287   LTOLLVMDiagnosticHandler(DiagnosticHandlerFunction *DiagHandlerFn)
0288       : Fn(DiagHandlerFn) {}
0289   bool handleDiagnostics(const DiagnosticInfo &DI) override {
0290     (*Fn)(DI);
0291     return true;
0292   }
0293 };
0294 /// A derived class of LLVMContext that initializes itself according to a given
0295 /// Config object. The purpose of this class is to tie ownership of the
0296 /// diagnostic handler to the context, as opposed to the Config object (which
0297 /// may be ephemeral).
0298 // FIXME: This should not be required as diagnostic handler is not callback.
0299 struct LTOLLVMContext : LLVMContext {
0300 
0301   LTOLLVMContext(const Config &C) : DiagHandler(C.DiagHandler) {
0302     setDiscardValueNames(C.ShouldDiscardValueNames);
0303     enableDebugTypeODRUniquing();
0304     setDiagnosticHandler(
0305         std::make_unique<LTOLLVMDiagnosticHandler>(&DiagHandler), true);
0306   }
0307   DiagnosticHandlerFunction DiagHandler;
0308 };
0309 
0310 }
0311 }
0312 
0313 #endif