1 //===-- llvm-lto2: test harness for the resolution-based LTO interface ----===// 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 program takes in a list of bitcode files, links them and performs 10 // link-time optimization according to the provided symbol resolutions using the 11 // resolution-based LTO interface, and outputs one or more object files. 12 // 13 // This program is intended to eventually replace llvm-lto which uses the legacy 14 // LTO interface. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/Bitcode/BitcodeReader.h" 19 #include "llvm/CodeGen/CommandFlags.h" 20 #include "llvm/Config/llvm-config.h" 21 #include "llvm/IR/DiagnosticPrinter.h" 22 #include "llvm/LTO/LTO.h" 23 #include "llvm/Passes/PassPlugin.h" 24 #include "llvm/Remarks/HotnessThresholdParser.h" 25 #include "llvm/Support/Caching.h" 26 #include "llvm/Support/CommandLine.h" 27 #include "llvm/Support/FileSystem.h" 28 #include "llvm/Support/InitLLVM.h" 29 #include "llvm/Support/PluginLoader.h" 30 #include "llvm/Support/TargetSelect.h" 31 #include "llvm/Support/Threading.h" 32 #include <atomic> 33 34 using namespace llvm; 35 using namespace lto; 36 37 static codegen::RegisterCodeGenFlags CGF; 38 39 static cl::opt<char> 40 OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " 41 "(default = '-O2')"), 42 cl::Prefix, cl::ZeroOrMore, cl::init('2')); 43 44 static cl::opt<char> CGOptLevel( 45 "cg-opt-level", 46 cl::desc("Codegen optimization level (0, 1, 2 or 3, default = '2')"), 47 cl::init('2')); 48 49 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore, 50 cl::desc("<input bitcode files>")); 51 52 static cl::opt<std::string> OutputFilename("o", cl::Required, 53 cl::desc("Output filename"), 54 cl::value_desc("filename")); 55 56 static cl::opt<std::string> CacheDir("cache-dir", cl::desc("Cache Directory"), 57 cl::value_desc("directory")); 58 59 static cl::opt<std::string> OptPipeline("opt-pipeline", 60 cl::desc("Optimizer Pipeline"), 61 cl::value_desc("pipeline")); 62 63 static cl::opt<std::string> AAPipeline("aa-pipeline", 64 cl::desc("Alias Analysis Pipeline"), 65 cl::value_desc("aapipeline")); 66 67 static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files")); 68 69 static cl::opt<bool> 70 ThinLTODistributedIndexes("thinlto-distributed-indexes", cl::init(false), 71 cl::desc("Write out individual index and " 72 "import files for the " 73 "distributed backend case")); 74 75 // Default to using all available threads in the system, but using only one 76 // thread per core (no SMT). 77 // Use -thinlto-threads=all to use hardware_concurrency() instead, which means 78 // to use all hardware threads or cores in the system. 79 static cl::opt<std::string> Threads("thinlto-threads"); 80 81 static cl::list<std::string> SymbolResolutions( 82 "r", 83 cl::desc("Specify a symbol resolution: filename,symbolname,resolution\n" 84 "where \"resolution\" is a sequence (which may be empty) of the\n" 85 "following characters:\n" 86 " p - prevailing: the linker has chosen this definition of the\n" 87 " symbol\n" 88 " l - local: the definition of this symbol is unpreemptable at\n" 89 " runtime and is known to be in this linkage unit\n" 90 " x - externally visible: the definition of this symbol is\n" 91 " visible outside of the LTO unit\n" 92 "A resolution for each symbol must be specified."), 93 cl::ZeroOrMore); 94 95 static cl::opt<std::string> OverrideTriple( 96 "override-triple", 97 cl::desc("Replace target triples in input files with this triple")); 98 99 static cl::opt<std::string> DefaultTriple( 100 "default-triple", 101 cl::desc( 102 "Replace unspecified target triples in input files with this triple")); 103 104 static cl::opt<bool> RemarksWithHotness( 105 "pass-remarks-with-hotness", 106 cl::desc("With PGO, include profile count in optimization remarks"), 107 cl::Hidden); 108 109 cl::opt<Optional<uint64_t>, false, remarks::HotnessThresholdParser> 110 RemarksHotnessThreshold( 111 "pass-remarks-hotness-threshold", 112 cl::desc("Minimum profile count required for an " 113 "optimization remark to be output." 114 " Use 'auto' to apply the threshold from profile summary."), 115 cl::value_desc("uint or 'auto'"), cl::init(0), cl::Hidden); 116 117 static cl::opt<std::string> 118 RemarksFilename("pass-remarks-output", 119 cl::desc("Output filename for pass remarks"), 120 cl::value_desc("filename")); 121 122 static cl::opt<std::string> 123 RemarksPasses("pass-remarks-filter", 124 cl::desc("Only record optimization remarks from passes whose " 125 "names match the given regular expression"), 126 cl::value_desc("regex")); 127 128 static cl::opt<std::string> RemarksFormat( 129 "pass-remarks-format", 130 cl::desc("The format used for serializing remarks (default: YAML)"), 131 cl::value_desc("format"), cl::init("yaml")); 132 133 static cl::opt<std::string> 134 SamplePGOFile("lto-sample-profile-file", 135 cl::desc("Specify a SamplePGO profile file")); 136 137 static cl::opt<std::string> 138 CSPGOFile("lto-cspgo-profile-file", 139 cl::desc("Specify a context sensitive PGO profile file")); 140 141 static cl::opt<bool> 142 RunCSIRInstr("lto-cspgo-gen", 143 cl::desc("Run PGO context sensitive IR instrumentation"), 144 cl::init(false), cl::Hidden); 145 146 static cl::opt<bool> 147 DebugPassManager("debug-pass-manager", cl::init(false), cl::Hidden, 148 cl::desc("Print pass management debugging information")); 149 150 static cl::opt<std::string> 151 StatsFile("stats-file", cl::desc("Filename to write statistics to")); 152 153 static cl::list<std::string> 154 PassPlugins("load-pass-plugin", 155 cl::desc("Load passes from plugin library")); 156 157 static cl::opt<bool> EnableFreestanding( 158 "lto-freestanding", 159 cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"), 160 cl::init(false), cl::Hidden); 161 162 static void check(Error E, std::string Msg) { 163 if (!E) 164 return; 165 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 166 errs() << "llvm-lto2: " << Msg << ": " << EIB.message().c_str() << '\n'; 167 }); 168 exit(1); 169 } 170 171 template <typename T> static T check(Expected<T> E, std::string Msg) { 172 if (E) 173 return std::move(*E); 174 check(E.takeError(), Msg); 175 return T(); 176 } 177 178 static void check(std::error_code EC, std::string Msg) { 179 check(errorCodeToError(EC), Msg); 180 } 181 182 template <typename T> static T check(ErrorOr<T> E, std::string Msg) { 183 if (E) 184 return std::move(*E); 185 check(E.getError(), Msg); 186 return T(); 187 } 188 189 static int usage() { 190 errs() << "Available subcommands: dump-symtab run\n"; 191 return 1; 192 } 193 194 static int run(int argc, char **argv) { 195 cl::ParseCommandLineOptions(argc, argv, "Resolution-based LTO test harness"); 196 197 // FIXME: Workaround PR30396 which means that a symbol can appear 198 // more than once if it is defined in module-level assembly and 199 // has a GV declaration. We allow (file, symbol) pairs to have multiple 200 // resolutions and apply them in the order observed. 201 std::map<std::pair<std::string, std::string>, std::list<SymbolResolution>> 202 CommandLineResolutions; 203 for (std::string R : SymbolResolutions) { 204 StringRef Rest = R; 205 StringRef FileName, SymbolName; 206 std::tie(FileName, Rest) = Rest.split(','); 207 if (Rest.empty()) { 208 llvm::errs() << "invalid resolution: " << R << '\n'; 209 return 1; 210 } 211 std::tie(SymbolName, Rest) = Rest.split(','); 212 SymbolResolution Res; 213 for (char C : Rest) { 214 if (C == 'p') 215 Res.Prevailing = true; 216 else if (C == 'l') 217 Res.FinalDefinitionInLinkageUnit = true; 218 else if (C == 'x') 219 Res.VisibleToRegularObj = true; 220 else if (C == 'r') 221 Res.LinkerRedefined = true; 222 else { 223 llvm::errs() << "invalid character " << C << " in resolution: " << R 224 << '\n'; 225 return 1; 226 } 227 } 228 CommandLineResolutions[{std::string(FileName), std::string(SymbolName)}] 229 .push_back(Res); 230 } 231 232 std::vector<std::unique_ptr<MemoryBuffer>> MBs; 233 234 Config Conf; 235 236 Conf.CPU = codegen::getMCPU(); 237 Conf.Options = codegen::InitTargetOptionsFromCodeGenFlags(Triple()); 238 Conf.MAttrs = codegen::getMAttrs(); 239 if (auto RM = codegen::getExplicitRelocModel()) 240 Conf.RelocModel = RM.getValue(); 241 Conf.CodeModel = codegen::getExplicitCodeModel(); 242 243 Conf.DebugPassManager = DebugPassManager; 244 245 if (SaveTemps) 246 check(Conf.addSaveTemps(OutputFilename + "."), 247 "Config::addSaveTemps failed"); 248 249 // Optimization remarks. 250 Conf.RemarksFilename = RemarksFilename; 251 Conf.RemarksPasses = RemarksPasses; 252 Conf.RemarksWithHotness = RemarksWithHotness; 253 Conf.RemarksHotnessThreshold = RemarksHotnessThreshold; 254 Conf.RemarksFormat = RemarksFormat; 255 256 Conf.SampleProfile = SamplePGOFile; 257 Conf.CSIRProfile = CSPGOFile; 258 Conf.RunCSIRInstr = RunCSIRInstr; 259 260 // Run a custom pipeline, if asked for. 261 Conf.OptPipeline = OptPipeline; 262 Conf.AAPipeline = AAPipeline; 263 264 Conf.OptLevel = OptLevel - '0'; 265 Conf.Freestanding = EnableFreestanding; 266 for (auto &PluginFN : PassPlugins) 267 Conf.PassPlugins.push_back(PluginFN); 268 switch (CGOptLevel) { 269 case '0': 270 Conf.CGOptLevel = CodeGenOpt::None; 271 break; 272 case '1': 273 Conf.CGOptLevel = CodeGenOpt::Less; 274 break; 275 case '2': 276 Conf.CGOptLevel = CodeGenOpt::Default; 277 break; 278 case '3': 279 Conf.CGOptLevel = CodeGenOpt::Aggressive; 280 break; 281 default: 282 llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n'; 283 return 1; 284 } 285 286 if (auto FT = codegen::getExplicitFileType()) 287 Conf.CGFileType = FT.getValue(); 288 289 Conf.OverrideTriple = OverrideTriple; 290 Conf.DefaultTriple = DefaultTriple; 291 Conf.StatsFile = StatsFile; 292 Conf.PTO.LoopVectorization = Conf.OptLevel > 1; 293 Conf.PTO.SLPVectorization = Conf.OptLevel > 1; 294 295 ThinBackend Backend; 296 if (ThinLTODistributedIndexes) 297 Backend = createWriteIndexesThinBackend(/* OldPrefix */ "", 298 /* NewPrefix */ "", 299 /* ShouldEmitImportsFiles */ true, 300 /* LinkedObjectsFile */ nullptr, 301 /* OnWrite */ {}); 302 else 303 Backend = createInProcessThinBackend( 304 llvm::heavyweight_hardware_concurrency(Threads)); 305 // Track whether we hit an error; in particular, in the multi-threaded case, 306 // we can't exit() early because the rest of the threads wouldn't have had a 307 // change to be join-ed, and that would result in a "terminate called without 308 // an active exception". Altogether, this results in nondeterministic 309 // behavior. Instead, we don't exit in the multi-threaded case, but we make 310 // sure to report the error and then at the end (after joining cleanly) 311 // exit(1). 312 std::atomic<bool> HasErrors; 313 std::atomic_init(&HasErrors, false); 314 Conf.DiagHandler = [&](const DiagnosticInfo &DI) { 315 DiagnosticPrinterRawOStream DP(errs()); 316 DI.print(DP); 317 errs() << '\n'; 318 if (DI.getSeverity() == DS_Error) 319 HasErrors = true; 320 }; 321 322 LTO Lto(std::move(Conf), std::move(Backend)); 323 324 for (std::string F : InputFilenames) { 325 std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F); 326 std::unique_ptr<InputFile> Input = 327 check(InputFile::create(MB->getMemBufferRef()), F); 328 329 std::vector<SymbolResolution> Res; 330 for (const InputFile::Symbol &Sym : Input->symbols()) { 331 auto I = CommandLineResolutions.find({F, std::string(Sym.getName())}); 332 // If it isn't found, look for ".", which would have been added 333 // (followed by a hash) when the symbol was promoted during module 334 // splitting if it was defined in one part and used in the other. 335 // Try looking up the symbol name before the suffix. 336 if (I == CommandLineResolutions.end()) { 337 auto SplitName = Sym.getName().rsplit("."); 338 I = CommandLineResolutions.find({F, std::string(SplitName.first)}); 339 } 340 if (I == CommandLineResolutions.end()) { 341 llvm::errs() << argv[0] << ": missing symbol resolution for " << F 342 << ',' << Sym.getName() << '\n'; 343 HasErrors = true; 344 } else { 345 Res.push_back(I->second.front()); 346 I->second.pop_front(); 347 if (I->second.empty()) 348 CommandLineResolutions.erase(I); 349 } 350 } 351 352 if (HasErrors) 353 continue; 354 355 MBs.push_back(std::move(MB)); 356 check(Lto.add(std::move(Input), Res), F); 357 } 358 359 if (!CommandLineResolutions.empty()) { 360 HasErrors = true; 361 for (auto UnusedRes : CommandLineResolutions) 362 llvm::errs() << argv[0] << ": unused symbol resolution for " 363 << UnusedRes.first.first << ',' << UnusedRes.first.second 364 << '\n'; 365 } 366 if (HasErrors) 367 return 1; 368 369 auto AddStream = [&](size_t Task) -> std::unique_ptr<CachedFileStream> { 370 std::string Path = OutputFilename + "." + utostr(Task); 371 372 std::error_code EC; 373 auto S = std::make_unique<raw_fd_ostream>(Path, EC, sys::fs::OF_None); 374 check(EC, Path); 375 return std::make_unique<CachedFileStream>(std::move(S), Path); 376 }; 377 378 auto AddBuffer = [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) { 379 *AddStream(Task)->OS << MB->getBuffer(); 380 }; 381 382 FileCache Cache; 383 if (!CacheDir.empty()) 384 Cache = check(localCache("ThinLTO", "Thin", CacheDir, AddBuffer), 385 "failed to create cache"); 386 387 check(Lto.run(AddStream, Cache), "LTO::run failed"); 388 return static_cast<int>(HasErrors); 389 } 390 391 static int dumpSymtab(int argc, char **argv) { 392 for (StringRef F : make_range(argv + 1, argv + argc)) { 393 std::unique_ptr<MemoryBuffer> MB = 394 check(MemoryBuffer::getFile(F), std::string(F)); 395 BitcodeFileContents BFC = 396 check(getBitcodeFileContents(*MB), std::string(F)); 397 398 if (BFC.Symtab.size() >= sizeof(irsymtab::storage::Header)) { 399 auto *Hdr = reinterpret_cast<const irsymtab::storage::Header *>( 400 BFC.Symtab.data()); 401 outs() << "version: " << Hdr->Version << '\n'; 402 if (Hdr->Version == irsymtab::storage::Header::kCurrentVersion) 403 outs() << "producer: " << Hdr->Producer.get(BFC.StrtabForSymtab) 404 << '\n'; 405 } 406 407 std::unique_ptr<InputFile> Input = 408 check(InputFile::create(MB->getMemBufferRef()), std::string(F)); 409 410 outs() << "target triple: " << Input->getTargetTriple() << '\n'; 411 Triple TT(Input->getTargetTriple()); 412 413 outs() << "source filename: " << Input->getSourceFileName() << '\n'; 414 415 if (TT.isOSBinFormatCOFF()) 416 outs() << "linker opts: " << Input->getCOFFLinkerOpts() << '\n'; 417 418 if (TT.isOSBinFormatELF()) { 419 outs() << "dependent libraries:"; 420 for (auto L : Input->getDependentLibraries()) 421 outs() << " \"" << L << "\""; 422 outs() << '\n'; 423 } 424 425 ArrayRef<std::pair<StringRef, Comdat::SelectionKind>> ComdatTable = 426 Input->getComdatTable(); 427 for (const InputFile::Symbol &Sym : Input->symbols()) { 428 switch (Sym.getVisibility()) { 429 case GlobalValue::HiddenVisibility: 430 outs() << 'H'; 431 break; 432 case GlobalValue::ProtectedVisibility: 433 outs() << 'P'; 434 break; 435 case GlobalValue::DefaultVisibility: 436 outs() << 'D'; 437 break; 438 } 439 440 auto PrintBool = [&](char C, bool B) { outs() << (B ? C : '-'); }; 441 PrintBool('U', Sym.isUndefined()); 442 PrintBool('C', Sym.isCommon()); 443 PrintBool('W', Sym.isWeak()); 444 PrintBool('I', Sym.isIndirect()); 445 PrintBool('O', Sym.canBeOmittedFromSymbolTable()); 446 PrintBool('T', Sym.isTLS()); 447 PrintBool('X', Sym.isExecutable()); 448 outs() << ' ' << Sym.getName() << '\n'; 449 450 if (Sym.isCommon()) 451 outs() << " size " << Sym.getCommonSize() << " align " 452 << Sym.getCommonAlignment() << '\n'; 453 454 int Comdat = Sym.getComdatIndex(); 455 if (Comdat != -1) { 456 outs() << " comdat "; 457 switch (ComdatTable[Comdat].second) { 458 case Comdat::Any: 459 outs() << "any"; 460 break; 461 case Comdat::ExactMatch: 462 outs() << "exactmatch"; 463 break; 464 case Comdat::Largest: 465 outs() << "largest"; 466 break; 467 case Comdat::NoDeduplicate: 468 outs() << "nodeduplicate"; 469 break; 470 case Comdat::SameSize: 471 outs() << "samesize"; 472 break; 473 } 474 outs() << ' ' << ComdatTable[Comdat].first << '\n'; 475 } 476 477 if (TT.isOSBinFormatCOFF() && Sym.isWeak() && Sym.isIndirect()) 478 outs() << " fallback " << Sym.getCOFFWeakExternalFallback() << '\n'; 479 480 if (!Sym.getSectionName().empty()) 481 outs() << " section " << Sym.getSectionName() << "\n"; 482 } 483 484 outs() << '\n'; 485 } 486 487 return 0; 488 } 489 490 int main(int argc, char **argv) { 491 InitLLVM X(argc, argv); 492 InitializeAllTargets(); 493 InitializeAllTargetMCs(); 494 InitializeAllAsmPrinters(); 495 InitializeAllAsmParsers(); 496 497 // FIXME: This should use llvm::cl subcommands, but it isn't currently 498 // possible to pass an argument not associated with a subcommand to a 499 // subcommand (e.g. -use-new-pm). 500 if (argc < 2) 501 return usage(); 502 503 StringRef Subcommand = argv[1]; 504 // Ensure that argv[0] is correct after adjusting argv/argc. 505 argv[1] = argv[0]; 506 if (Subcommand == "dump-symtab") 507 return dumpSymtab(argc - 1, argv + 1); 508 if (Subcommand == "run") 509 return run(argc - 1, argv + 1); 510 return usage(); 511 } 512