1 //===-LTO.h - LLVM Link Time Optimizer ------------------------------------===// 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 declares functions and classes used to support LTO. It is intended 10 // to be used both by LTO classes as well as by clients (gold-plugin) that 11 // don't utilize the LTO code generator interfaces. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_LTO_LTO_H 16 #define LLVM_LTO_LTO_H 17 18 #include "llvm/ADT/MapVector.h" 19 #include "llvm/ADT/StringMap.h" 20 #include "llvm/Bitcode/BitcodeReader.h" 21 #include "llvm/IR/ModuleSummaryIndex.h" 22 #include "llvm/LTO/Config.h" 23 #include "llvm/Object/IRSymtab.h" 24 #include "llvm/Support/Caching.h" 25 #include "llvm/Support/Error.h" 26 #include "llvm/Support/thread.h" 27 #include "llvm/Transforms/IPO/FunctionAttrs.h" 28 #include "llvm/Transforms/IPO/FunctionImport.h" 29 30 namespace llvm { 31 32 class Error; 33 class IRMover; 34 class LLVMContext; 35 class MemoryBufferRef; 36 class Module; 37 class raw_pwrite_stream; 38 class ToolOutputFile; 39 40 /// Resolve linkage for prevailing symbols in the \p Index. Linkage changes 41 /// recorded in the index and the ThinLTO backends must apply the changes to 42 /// the module via thinLTOFinalizeInModule. 43 /// 44 /// This is done for correctness (if value exported, ensure we always 45 /// emit a copy), and compile-time optimization (allow drop of duplicates). 46 void thinLTOResolvePrevailingInIndex( 47 const lto::Config &C, ModuleSummaryIndex &Index, 48 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)> 49 isPrevailing, 50 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> 51 recordNewLinkage, 52 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols); 53 54 /// Update the linkages in the given \p Index to mark exported values 55 /// as external and non-exported values as internal. The ThinLTO backends 56 /// must apply the changes to the Module via thinLTOInternalizeModule. 57 void thinLTOInternalizeAndPromoteInIndex( 58 ModuleSummaryIndex &Index, 59 function_ref<bool(StringRef, ValueInfo)> isExported, 60 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)> 61 isPrevailing); 62 63 /// Computes a unique hash for the Module considering the current list of 64 /// export/import and other global analysis results. 65 /// The hash is produced in \p Key. 66 void computeLTOCacheKey( 67 SmallString<40> &Key, const lto::Config &Conf, 68 const ModuleSummaryIndex &Index, StringRef ModuleID, 69 const FunctionImporter::ImportMapTy &ImportList, 70 const FunctionImporter::ExportSetTy &ExportList, 71 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR, 72 const GVSummaryMapTy &DefinedGlobals, 73 const std::set<GlobalValue::GUID> &CfiFunctionDefs = {}, 74 const std::set<GlobalValue::GUID> &CfiFunctionDecls = {}); 75 76 namespace lto { 77 78 StringLiteral getThinLTODefaultCPU(const Triple &TheTriple); 79 80 /// Given the original \p Path to an output file, replace any path 81 /// prefix matching \p OldPrefix with \p NewPrefix. Also, create the 82 /// resulting directory if it does not yet exist. 83 std::string getThinLTOOutputFile(StringRef Path, StringRef OldPrefix, 84 StringRef NewPrefix); 85 86 /// Setup optimization remarks. 87 Expected<std::unique_ptr<ToolOutputFile>> setupLLVMOptimizationRemarks( 88 LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, 89 StringRef RemarksFormat, bool RemarksWithHotness, 90 std::optional<uint64_t> RemarksHotnessThreshold = 0, int Count = -1); 91 92 /// Setups the output file for saving statistics. 93 Expected<std::unique_ptr<ToolOutputFile>> 94 setupStatsFile(StringRef StatsFilename); 95 96 /// Produces a container ordering for optimal multi-threaded processing. Returns 97 /// ordered indices to elements in the input array. 98 std::vector<int> generateModulesOrdering(ArrayRef<BitcodeModule *> R); 99 100 /// Updates MemProf attributes (and metadata) based on whether the index 101 /// has recorded that we are linking with allocation libraries containing 102 /// the necessary APIs for downstream transformations. 103 void updateMemProfAttributes(Module &Mod, const ModuleSummaryIndex &Index); 104 105 class LTO; 106 struct SymbolResolution; 107 class ThinBackendProc; 108 109 /// An input file. This is a symbol table wrapper that only exposes the 110 /// information that an LTO client should need in order to do symbol resolution. 111 class InputFile { 112 public: 113 class Symbol; 114 115 private: 116 // FIXME: Remove LTO class friendship once we have bitcode symbol tables. 117 friend LTO; 118 InputFile() = default; 119 120 std::vector<BitcodeModule> Mods; 121 SmallVector<char, 0> Strtab; 122 std::vector<Symbol> Symbols; 123 124 // [begin, end) for each module 125 std::vector<std::pair<size_t, size_t>> ModuleSymIndices; 126 127 StringRef TargetTriple, SourceFileName, COFFLinkerOpts; 128 std::vector<StringRef> DependentLibraries; 129 std::vector<std::pair<StringRef, Comdat::SelectionKind>> ComdatTable; 130 131 public: 132 ~InputFile(); 133 134 /// Create an InputFile. 135 static Expected<std::unique_ptr<InputFile>> create(MemoryBufferRef Object); 136 137 /// The purpose of this class is to only expose the symbol information that an 138 /// LTO client should need in order to do symbol resolution. 139 class Symbol : irsymtab::Symbol { 140 friend LTO; 141 142 public: Symbol(const irsymtab::Symbol & S)143 Symbol(const irsymtab::Symbol &S) : irsymtab::Symbol(S) {} 144 145 using irsymtab::Symbol::isUndefined; 146 using irsymtab::Symbol::isCommon; 147 using irsymtab::Symbol::isWeak; 148 using irsymtab::Symbol::isIndirect; 149 using irsymtab::Symbol::getName; 150 using irsymtab::Symbol::getIRName; 151 using irsymtab::Symbol::getVisibility; 152 using irsymtab::Symbol::canBeOmittedFromSymbolTable; 153 using irsymtab::Symbol::isTLS; 154 using irsymtab::Symbol::getComdatIndex; 155 using irsymtab::Symbol::getCommonSize; 156 using irsymtab::Symbol::getCommonAlignment; 157 using irsymtab::Symbol::getCOFFWeakExternalFallback; 158 using irsymtab::Symbol::getSectionName; 159 using irsymtab::Symbol::isExecutable; 160 using irsymtab::Symbol::isUsed; 161 }; 162 163 /// A range over the symbols in this InputFile. symbols()164 ArrayRef<Symbol> symbols() const { return Symbols; } 165 166 /// Returns linker options specified in the input file. getCOFFLinkerOpts()167 StringRef getCOFFLinkerOpts() const { return COFFLinkerOpts; } 168 169 /// Returns dependent library specifiers from the input file. getDependentLibraries()170 ArrayRef<StringRef> getDependentLibraries() const { return DependentLibraries; } 171 172 /// Returns the path to the InputFile. 173 StringRef getName() const; 174 175 /// Returns the input file's target triple. getTargetTriple()176 StringRef getTargetTriple() const { return TargetTriple; } 177 178 /// Returns the source file path specified at compile time. getSourceFileName()179 StringRef getSourceFileName() const { return SourceFileName; } 180 181 // Returns a table with all the comdats used by this file. getComdatTable()182 ArrayRef<std::pair<StringRef, Comdat::SelectionKind>> getComdatTable() const { 183 return ComdatTable; 184 } 185 186 // Returns the only BitcodeModule from InputFile. 187 BitcodeModule &getSingleBitcodeModule(); 188 189 private: module_symbols(unsigned I)190 ArrayRef<Symbol> module_symbols(unsigned I) const { 191 const auto &Indices = ModuleSymIndices[I]; 192 return {Symbols.data() + Indices.first, Symbols.data() + Indices.second}; 193 } 194 }; 195 196 /// A ThinBackend defines what happens after the thin-link phase during ThinLTO. 197 /// The details of this type definition aren't important; clients can only 198 /// create a ThinBackend using one of the create*ThinBackend() functions below. 199 using ThinBackend = std::function<std::unique_ptr<ThinBackendProc>( 200 const Config &C, ModuleSummaryIndex &CombinedIndex, 201 DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries, 202 AddStreamFn AddStream, FileCache Cache)>; 203 204 /// This ThinBackend runs the individual backend jobs in-process. 205 /// The default value means to use one job per hardware core (not hyper-thread). 206 /// OnWrite is callback which receives module identifier and notifies LTO user 207 /// that index file for the module (and optionally imports file) was created. 208 /// ShouldEmitIndexFiles being true will write sharded ThinLTO index files 209 /// to the same path as the input module, with suffix ".thinlto.bc" 210 /// ShouldEmitImportsFiles is true it also writes a list of imported files to a 211 /// similar path with ".imports" appended instead. 212 using IndexWriteCallback = std::function<void(const std::string &)>; 213 ThinBackend createInProcessThinBackend(ThreadPoolStrategy Parallelism, 214 IndexWriteCallback OnWrite = nullptr, 215 bool ShouldEmitIndexFiles = false, 216 bool ShouldEmitImportsFiles = false); 217 218 /// This ThinBackend writes individual module indexes to files, instead of 219 /// running the individual backend jobs. This backend is for distributed builds 220 /// where separate processes will invoke the real backends. 221 /// 222 /// To find the path to write the index to, the backend checks if the path has a 223 /// prefix of OldPrefix; if so, it replaces that prefix with NewPrefix. It then 224 /// appends ".thinlto.bc" and writes the index to that path. If 225 /// ShouldEmitImportsFiles is true it also writes a list of imported files to a 226 /// similar path with ".imports" appended instead. 227 /// LinkedObjectsFile is an output stream to write the list of object files for 228 /// the final ThinLTO linking. Can be nullptr. If LinkedObjectsFile is not 229 /// nullptr and NativeObjectPrefix is not empty then it replaces the prefix of 230 /// the objects with NativeObjectPrefix instead of NewPrefix. OnWrite is 231 /// callback which receives module identifier and notifies LTO user that index 232 /// file for the module (and optionally imports file) was created. 233 ThinBackend createWriteIndexesThinBackend(std::string OldPrefix, 234 std::string NewPrefix, 235 std::string NativeObjectPrefix, 236 bool ShouldEmitImportsFiles, 237 raw_fd_ostream *LinkedObjectsFile, 238 IndexWriteCallback OnWrite); 239 240 /// This class implements a resolution-based interface to LLVM's LTO 241 /// functionality. It supports regular LTO, parallel LTO code generation and 242 /// ThinLTO. You can use it from a linker in the following way: 243 /// - Set hooks and code generation options (see lto::Config struct defined in 244 /// Config.h), and use the lto::Config object to create an lto::LTO object. 245 /// - Create lto::InputFile objects using lto::InputFile::create(), then use 246 /// the symbols() function to enumerate its symbols and compute a resolution 247 /// for each symbol (see SymbolResolution below). 248 /// - After the linker has visited each input file (and each regular object 249 /// file) and computed a resolution for each symbol, take each lto::InputFile 250 /// and pass it and an array of symbol resolutions to the add() function. 251 /// - Call the getMaxTasks() function to get an upper bound on the number of 252 /// native object files that LTO may add to the link. 253 /// - Call the run() function. This function will use the supplied AddStream 254 /// and Cache functions to add up to getMaxTasks() native object files to 255 /// the link. 256 class LTO { 257 friend InputFile; 258 259 public: 260 /// Unified LTO modes 261 enum LTOKind { 262 /// Any LTO mode without Unified LTO. The default mode. 263 LTOK_Default, 264 265 /// Regular LTO, with Unified LTO enabled. 266 LTOK_UnifiedRegular, 267 268 /// ThinLTO, with Unified LTO enabled. 269 LTOK_UnifiedThin, 270 }; 271 272 /// Create an LTO object. A default constructed LTO object has a reasonable 273 /// production configuration, but you can customize it by passing arguments to 274 /// this constructor. 275 /// FIXME: We do currently require the DiagHandler field to be set in Conf. 276 /// Until that is fixed, a Config argument is required. 277 LTO(Config Conf, ThinBackend Backend = nullptr, 278 unsigned ParallelCodeGenParallelismLevel = 1, 279 LTOKind LTOMode = LTOK_Default); 280 ~LTO(); 281 282 /// Add an input file to the LTO link, using the provided symbol resolutions. 283 /// The symbol resolutions must appear in the enumeration order given by 284 /// InputFile::symbols(). 285 Error add(std::unique_ptr<InputFile> Obj, ArrayRef<SymbolResolution> Res); 286 287 /// Returns an upper bound on the number of tasks that the client may expect. 288 /// This may only be called after all IR object files have been added. For a 289 /// full description of tasks see LTOBackend.h. 290 unsigned getMaxTasks() const; 291 292 /// Runs the LTO pipeline. This function calls the supplied AddStream 293 /// function to add native object files to the link. 294 /// 295 /// The Cache parameter is optional. If supplied, it will be used to cache 296 /// native object files and add them to the link. 297 /// 298 /// The client will receive at most one callback (via either AddStream or 299 /// Cache) for each task identifier. 300 Error run(AddStreamFn AddStream, FileCache Cache = nullptr); 301 302 /// Static method that returns a list of libcall symbols that can be generated 303 /// by LTO but might not be visible from bitcode symbol table. 304 static SmallVector<const char *> getRuntimeLibcallSymbols(const Triple &TT); 305 306 private: 307 Config Conf; 308 309 struct RegularLTOState { 310 RegularLTOState(unsigned ParallelCodeGenParallelismLevel, 311 const Config &Conf); 312 struct CommonResolution { 313 uint64_t Size = 0; 314 Align Alignment; 315 /// Record if at least one instance of the common was marked as prevailing 316 bool Prevailing = false; 317 }; 318 std::map<std::string, CommonResolution> Commons; 319 320 unsigned ParallelCodeGenParallelismLevel; 321 LTOLLVMContext Ctx; 322 std::unique_ptr<Module> CombinedModule; 323 std::unique_ptr<IRMover> Mover; 324 325 // This stores the information about a regular LTO module that we have added 326 // to the link. It will either be linked immediately (for modules without 327 // summaries) or after summary-based dead stripping (for modules with 328 // summaries). 329 struct AddedModule { 330 std::unique_ptr<Module> M; 331 std::vector<GlobalValue *> Keep; 332 }; 333 std::vector<AddedModule> ModsWithSummaries; 334 bool EmptyCombinedModule = true; 335 } RegularLTO; 336 337 using ModuleMapType = MapVector<StringRef, BitcodeModule>; 338 339 struct ThinLTOState { 340 ThinLTOState(ThinBackend Backend); 341 342 ThinBackend Backend; 343 ModuleSummaryIndex CombinedIndex; 344 // The full set of bitcode modules in input order. 345 ModuleMapType ModuleMap; 346 // The bitcode modules to compile, if specified by the LTO Config. 347 std::optional<ModuleMapType> ModulesToCompile; 348 DenseMap<GlobalValue::GUID, StringRef> PrevailingModuleForGUID; 349 } ThinLTO; 350 351 // The global resolution for a particular (mangled) symbol name. This is in 352 // particular necessary to track whether each symbol can be internalized. 353 // Because any input file may introduce a new cross-partition reference, we 354 // cannot make any final internalization decisions until all input files have 355 // been added and the client has called run(). During run() we apply 356 // internalization decisions either directly to the module (for regular LTO) 357 // or to the combined index (for ThinLTO). 358 struct GlobalResolution { 359 /// The unmangled name of the global. 360 std::string IRName; 361 362 /// Keep track if the symbol is visible outside of a module with a summary 363 /// (i.e. in either a regular object or a regular LTO module without a 364 /// summary). 365 bool VisibleOutsideSummary = false; 366 367 /// The symbol was exported dynamically, and therefore could be referenced 368 /// by a shared library not visible to the linker. 369 bool ExportDynamic = false; 370 371 bool UnnamedAddr = true; 372 373 /// True if module contains the prevailing definition. 374 bool Prevailing = false; 375 376 /// Returns true if module contains the prevailing definition and symbol is 377 /// an IR symbol. For example when module-level inline asm block is used, 378 /// symbol can be prevailing in module but have no IR name. isPrevailingIRSymbolGlobalResolution379 bool isPrevailingIRSymbol() const { return Prevailing && !IRName.empty(); } 380 381 /// This field keeps track of the partition number of this global. The 382 /// regular LTO object is partition 0, while each ThinLTO object has its own 383 /// partition number from 1 onwards. 384 /// 385 /// Any global that is defined or used by more than one partition, or that 386 /// is referenced externally, may not be internalized. 387 /// 388 /// Partitions generally have a one-to-one correspondence with tasks, except 389 /// that we use partition 0 for all parallel LTO code generation partitions. 390 /// Any partitioning of the combined LTO object is done internally by the 391 /// LTO backend. 392 unsigned Partition = Unknown; 393 394 /// Special partition numbers. 395 enum : unsigned { 396 /// A partition number has not yet been assigned to this global. 397 Unknown = -1u, 398 399 /// This global is either used by more than one partition or has an 400 /// external reference, and therefore cannot be internalized. 401 External = -2u, 402 403 /// The RegularLTO partition 404 RegularLTO = 0, 405 }; 406 }; 407 408 // Global mapping from mangled symbol names to resolutions. 409 // Make this an optional to guard against accessing after it has been reset 410 // (to reduce memory after we're done with it). 411 std::optional<StringMap<GlobalResolution>> GlobalResolutions; 412 413 void addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms, 414 ArrayRef<SymbolResolution> Res, unsigned Partition, 415 bool InSummary); 416 417 // These functions take a range of symbol resolutions [ResI, ResE) and consume 418 // the resolutions used by a single input module by incrementing ResI. After 419 // these functions return, [ResI, ResE) will refer to the resolution range for 420 // the remaining modules in the InputFile. 421 Error addModule(InputFile &Input, unsigned ModI, 422 const SymbolResolution *&ResI, const SymbolResolution *ResE); 423 424 Expected<RegularLTOState::AddedModule> 425 addRegularLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms, 426 const SymbolResolution *&ResI, const SymbolResolution *ResE); 427 Error linkRegularLTO(RegularLTOState::AddedModule Mod, 428 bool LivenessFromIndex); 429 430 Error addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms, 431 const SymbolResolution *&ResI, const SymbolResolution *ResE); 432 433 Error runRegularLTO(AddStreamFn AddStream); 434 Error runThinLTO(AddStreamFn AddStream, FileCache Cache, 435 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols); 436 437 Error checkPartiallySplit(); 438 439 mutable bool CalledGetMaxTasks = false; 440 441 // LTO mode when using Unified LTO. 442 LTOKind LTOMode; 443 444 // Use Optional to distinguish false from not yet initialized. 445 std::optional<bool> EnableSplitLTOUnit; 446 447 // Identify symbols exported dynamically, and that therefore could be 448 // referenced by a shared library not visible to the linker. 449 DenseSet<GlobalValue::GUID> DynamicExportSymbols; 450 451 // Diagnostic optimization remarks file 452 std::unique_ptr<ToolOutputFile> DiagnosticOutputFile; 453 }; 454 455 /// The resolution for a symbol. The linker must provide a SymbolResolution for 456 /// each global symbol based on its internal resolution of that symbol. 457 struct SymbolResolution { SymbolResolutionSymbolResolution458 SymbolResolution() 459 : Prevailing(0), FinalDefinitionInLinkageUnit(0), VisibleToRegularObj(0), 460 ExportDynamic(0), LinkerRedefined(0) {} 461 462 /// The linker has chosen this definition of the symbol. 463 unsigned Prevailing : 1; 464 465 /// The definition of this symbol is unpreemptable at runtime and is known to 466 /// be in this linkage unit. 467 unsigned FinalDefinitionInLinkageUnit : 1; 468 469 /// The definition of this symbol is visible outside of the LTO unit. 470 unsigned VisibleToRegularObj : 1; 471 472 /// The symbol was exported dynamically, and therefore could be referenced 473 /// by a shared library not visible to the linker. 474 unsigned ExportDynamic : 1; 475 476 /// Linker redefined version of the symbol which appeared in -wrap or -defsym 477 /// linker option. 478 unsigned LinkerRedefined : 1; 479 }; 480 481 } // namespace lto 482 } // namespace llvm 483 484 #endif 485