1 //===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the "backend" phase of LTO, i.e. it performs 11 // optimization and code generation on a loaded module. It is generally used 12 // internally by the LTO class but can also be used independently, for example 13 // to implement a standalone ThinLTO backend. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/LTO/LTOBackend.h" 18 #include "llvm/Analysis/AliasAnalysis.h" 19 #include "llvm/Analysis/CGSCCPassManager.h" 20 #include "llvm/Analysis/TargetLibraryInfo.h" 21 #include "llvm/Analysis/TargetTransformInfo.h" 22 #include "llvm/Bitcode/BitcodeReader.h" 23 #include "llvm/Bitcode/BitcodeWriter.h" 24 #include "llvm/IR/LegacyPassManager.h" 25 #include "llvm/IR/PassManager.h" 26 #include "llvm/IR/Verifier.h" 27 #include "llvm/LTO/LTO.h" 28 #include "llvm/LTO/legacy/UpdateCompilerUsed.h" 29 #include "llvm/MC/SubtargetFeature.h" 30 #include "llvm/Object/ModuleSymbolTable.h" 31 #include "llvm/Passes/PassBuilder.h" 32 #include "llvm/Support/Error.h" 33 #include "llvm/Support/FileSystem.h" 34 #include "llvm/Support/TargetRegistry.h" 35 #include "llvm/Support/ThreadPool.h" 36 #include "llvm/Target/TargetMachine.h" 37 #include "llvm/Transforms/IPO.h" 38 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 39 #include "llvm/Transforms/Scalar/LoopPassManager.h" 40 #include "llvm/Transforms/Utils/FunctionImportUtils.h" 41 #include "llvm/Transforms/Utils/SplitModule.h" 42 43 using namespace llvm; 44 using namespace lto; 45 46 static cl::opt<bool> 47 LTOUseNewPM("lto-use-new-pm", 48 cl::desc("Run LTO passes using the new pass manager"), 49 cl::init(false), cl::Hidden); 50 51 LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) { 52 errs() << "failed to open " << Path << ": " << Msg << '\n'; 53 errs().flush(); 54 exit(1); 55 } 56 57 Error Config::addSaveTemps(std::string OutputFileName, 58 bool UseInputModulePath) { 59 ShouldDiscardValueNames = false; 60 61 std::error_code EC; 62 ResolutionFile = llvm::make_unique<raw_fd_ostream>( 63 OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text); 64 if (EC) 65 return errorCodeToError(EC); 66 67 auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) { 68 // Keep track of the hook provided by the linker, which also needs to run. 69 ModuleHookFn LinkerHook = Hook; 70 Hook = [=](unsigned Task, const Module &M) { 71 // If the linker's hook returned false, we need to pass that result 72 // through. 73 if (LinkerHook && !LinkerHook(Task, M)) 74 return false; 75 76 std::string PathPrefix; 77 // If this is the combined module (not a ThinLTO backend compile) or the 78 // user hasn't requested using the input module's path, emit to a file 79 // named from the provided OutputFileName with the Task ID appended. 80 if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) { 81 PathPrefix = OutputFileName + utostr(Task); 82 } else 83 PathPrefix = M.getModuleIdentifier(); 84 std::string Path = PathPrefix + "." + PathSuffix + ".bc"; 85 std::error_code EC; 86 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None); 87 // Because -save-temps is a debugging feature, we report the error 88 // directly and exit. 89 if (EC) 90 reportOpenError(Path, EC.message()); 91 WriteBitcodeToFile(&M, OS, /*ShouldPreserveUseListOrder=*/false); 92 return true; 93 }; 94 }; 95 96 setHook("0.preopt", PreOptModuleHook); 97 setHook("1.promote", PostPromoteModuleHook); 98 setHook("2.internalize", PostInternalizeModuleHook); 99 setHook("3.import", PostImportModuleHook); 100 setHook("4.opt", PostOptModuleHook); 101 setHook("5.precodegen", PreCodeGenModuleHook); 102 103 CombinedIndexHook = [=](const ModuleSummaryIndex &Index) { 104 std::string Path = OutputFileName + "index.bc"; 105 std::error_code EC; 106 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None); 107 // Because -save-temps is a debugging feature, we report the error 108 // directly and exit. 109 if (EC) 110 reportOpenError(Path, EC.message()); 111 WriteIndexToFile(Index, OS); 112 return true; 113 }; 114 115 return Error::success(); 116 } 117 118 namespace { 119 120 std::unique_ptr<TargetMachine> 121 createTargetMachine(Config &Conf, StringRef TheTriple, 122 const Target *TheTarget) { 123 SubtargetFeatures Features; 124 Features.getDefaultSubtargetFeatures(Triple(TheTriple)); 125 for (const std::string &A : Conf.MAttrs) 126 Features.AddFeature(A); 127 128 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine( 129 TheTriple, Conf.CPU, Features.getString(), Conf.Options, Conf.RelocModel, 130 Conf.CodeModel, Conf.CGOptLevel)); 131 } 132 133 static void runNewPMPasses(Module &Mod, TargetMachine *TM, unsigned OptLevel) { 134 PassBuilder PB(TM); 135 AAManager AA; 136 137 // Parse a custom AA pipeline if asked to. 138 assert(PB.parseAAPipeline(AA, "default")); 139 140 LoopAnalysisManager LAM; 141 FunctionAnalysisManager FAM; 142 CGSCCAnalysisManager CGAM; 143 ModuleAnalysisManager MAM; 144 145 // Register the AA manager first so that our version is the one used. 146 FAM.registerPass([&] { return std::move(AA); }); 147 148 // Register all the basic analyses with the managers. 149 PB.registerModuleAnalyses(MAM); 150 PB.registerCGSCCAnalyses(CGAM); 151 PB.registerFunctionAnalyses(FAM); 152 PB.registerLoopAnalyses(LAM); 153 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); 154 155 ModulePassManager MPM; 156 // FIXME (davide): verify the input. 157 158 PassBuilder::OptimizationLevel OL; 159 160 switch (OptLevel) { 161 default: 162 llvm_unreachable("Invalid optimization level"); 163 case 0: 164 OL = PassBuilder::O0; 165 break; 166 case 1: 167 OL = PassBuilder::O1; 168 break; 169 case 2: 170 OL = PassBuilder::O2; 171 break; 172 case 3: 173 OL = PassBuilder::O3; 174 break; 175 } 176 177 MPM = PB.buildLTODefaultPipeline(OL, false /* DebugLogging */); 178 MPM.run(Mod, MAM); 179 180 // FIXME (davide): verify the output. 181 } 182 183 static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM, 184 std::string PipelineDesc, 185 std::string AAPipelineDesc, 186 bool DisableVerify) { 187 PassBuilder PB(TM); 188 AAManager AA; 189 190 // Parse a custom AA pipeline if asked to. 191 if (!AAPipelineDesc.empty()) 192 if (!PB.parseAAPipeline(AA, AAPipelineDesc)) 193 report_fatal_error("unable to parse AA pipeline description: " + 194 AAPipelineDesc); 195 196 LoopAnalysisManager LAM; 197 FunctionAnalysisManager FAM; 198 CGSCCAnalysisManager CGAM; 199 ModuleAnalysisManager MAM; 200 201 // Register the AA manager first so that our version is the one used. 202 FAM.registerPass([&] { return std::move(AA); }); 203 204 // Register all the basic analyses with the managers. 205 PB.registerModuleAnalyses(MAM); 206 PB.registerCGSCCAnalyses(CGAM); 207 PB.registerFunctionAnalyses(FAM); 208 PB.registerLoopAnalyses(LAM); 209 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); 210 211 ModulePassManager MPM; 212 213 // Always verify the input. 214 MPM.addPass(VerifierPass()); 215 216 // Now, add all the passes we've been requested to. 217 if (!PB.parsePassPipeline(MPM, PipelineDesc)) 218 report_fatal_error("unable to parse pass pipeline description: " + 219 PipelineDesc); 220 221 if (!DisableVerify) 222 MPM.addPass(VerifierPass()); 223 MPM.run(Mod, MAM); 224 } 225 226 static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM, 227 bool IsThinLTO, ModuleSummaryIndex *ExportSummary, 228 const ModuleSummaryIndex *ImportSummary) { 229 legacy::PassManager passes; 230 passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis())); 231 232 PassManagerBuilder PMB; 233 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple())); 234 PMB.Inliner = createFunctionInliningPass(); 235 PMB.ExportSummary = ExportSummary; 236 PMB.ImportSummary = ImportSummary; 237 // Unconditionally verify input since it is not verified before this 238 // point and has unknown origin. 239 PMB.VerifyInput = true; 240 PMB.VerifyOutput = !Conf.DisableVerify; 241 PMB.LoopVectorize = true; 242 PMB.SLPVectorize = true; 243 PMB.OptLevel = Conf.OptLevel; 244 PMB.PGOSampleUse = Conf.SampleProfile; 245 if (IsThinLTO) 246 PMB.populateThinLTOPassManager(passes); 247 else 248 PMB.populateLTOPassManager(passes); 249 passes.run(Mod); 250 } 251 252 bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod, 253 bool IsThinLTO, ModuleSummaryIndex *ExportSummary, 254 const ModuleSummaryIndex *ImportSummary) { 255 // There's still no ThinLTO pipeline hooked up in the new pass manager, 256 // once there is one, we can just remove this. 257 if (LTOUseNewPM && IsThinLTO) 258 report_fatal_error("ThinLTO not supported with the new PM yet!"); 259 260 // FIXME: Plumb the combined index into the new pass manager. 261 if (!Conf.OptPipeline.empty()) 262 runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline, 263 Conf.DisableVerify); 264 else if (LTOUseNewPM) 265 runNewPMPasses(Mod, TM, Conf.OptLevel); 266 else 267 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary); 268 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod); 269 } 270 271 void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream, 272 unsigned Task, Module &Mod) { 273 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod)) 274 return; 275 276 auto Stream = AddStream(Task); 277 legacy::PassManager CodeGenPasses; 278 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS, Conf.CGFileType)) 279 report_fatal_error("Failed to setup codegen"); 280 CodeGenPasses.run(Mod); 281 } 282 283 void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream, 284 unsigned ParallelCodeGenParallelismLevel, 285 std::unique_ptr<Module> Mod) { 286 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel); 287 unsigned ThreadCount = 0; 288 const Target *T = &TM->getTarget(); 289 290 SplitModule( 291 std::move(Mod), ParallelCodeGenParallelismLevel, 292 [&](std::unique_ptr<Module> MPart) { 293 // We want to clone the module in a new context to multi-thread the 294 // codegen. We do it by serializing partition modules to bitcode 295 // (while still on the main thread, in order to avoid data races) and 296 // spinning up new threads which deserialize the partitions into 297 // separate contexts. 298 // FIXME: Provide a more direct way to do this in LLVM. 299 SmallString<0> BC; 300 raw_svector_ostream BCOS(BC); 301 WriteBitcodeToFile(MPart.get(), BCOS); 302 303 // Enqueue the task 304 CodegenThreadPool.async( 305 [&](const SmallString<0> &BC, unsigned ThreadId) { 306 LTOLLVMContext Ctx(C); 307 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile( 308 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"), 309 Ctx); 310 if (!MOrErr) 311 report_fatal_error("Failed to read bitcode"); 312 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get()); 313 314 std::unique_ptr<TargetMachine> TM = 315 createTargetMachine(C, MPartInCtx->getTargetTriple(), T); 316 317 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx); 318 }, 319 // Pass BC using std::move to ensure that it get moved rather than 320 // copied into the thread's context. 321 std::move(BC), ThreadCount++); 322 }, 323 false); 324 325 // Because the inner lambda (which runs in a worker thread) captures our local 326 // variables, we need to wait for the worker threads to terminate before we 327 // can leave the function scope. 328 CodegenThreadPool.wait(); 329 } 330 331 Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) { 332 if (!C.OverrideTriple.empty()) 333 Mod.setTargetTriple(C.OverrideTriple); 334 else if (Mod.getTargetTriple().empty()) 335 Mod.setTargetTriple(C.DefaultTriple); 336 337 std::string Msg; 338 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg); 339 if (!T) 340 return make_error<StringError>(Msg, inconvertibleErrorCode()); 341 return T; 342 } 343 344 } 345 346 static void 347 finalizeOptimizationRemarks(std::unique_ptr<tool_output_file> DiagOutputFile) { 348 // Make sure we flush the diagnostic remarks file in case the linker doesn't 349 // call the global destructors before exiting. 350 if (!DiagOutputFile) 351 return; 352 DiagOutputFile->keep(); 353 DiagOutputFile->os().flush(); 354 } 355 356 static void handleAsmUndefinedRefs(Module &Mod, TargetMachine &TM) { 357 // Collect the list of undefined symbols used in asm and update 358 // llvm.compiler.used to prevent optimization to drop these from the output. 359 StringSet<> AsmUndefinedRefs; 360 ModuleSymbolTable::CollectAsmSymbols( 361 Mod, 362 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) { 363 if (Flags & object::BasicSymbolRef::SF_Undefined) 364 AsmUndefinedRefs.insert(Name); 365 }); 366 updateCompilerUsed(Mod, TM, AsmUndefinedRefs); 367 } 368 369 Error lto::backend(Config &C, AddStreamFn AddStream, 370 unsigned ParallelCodeGenParallelismLevel, 371 std::unique_ptr<Module> Mod, 372 ModuleSummaryIndex &CombinedIndex) { 373 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod); 374 if (!TOrErr) 375 return TOrErr.takeError(); 376 377 std::unique_ptr<TargetMachine> TM = 378 createTargetMachine(C, Mod->getTargetTriple(), *TOrErr); 379 380 handleAsmUndefinedRefs(*Mod, *TM); 381 382 // Setup optimization remarks. 383 auto DiagFileOrErr = lto::setupOptimizationRemarks( 384 Mod->getContext(), C.RemarksFilename, C.RemarksWithHotness); 385 if (!DiagFileOrErr) 386 return DiagFileOrErr.takeError(); 387 auto DiagnosticOutputFile = std::move(*DiagFileOrErr); 388 389 if (!C.CodeGenOnly) { 390 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false, 391 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr)) { 392 finalizeOptimizationRemarks(std::move(DiagnosticOutputFile)); 393 return Error::success(); 394 } 395 } 396 397 if (ParallelCodeGenParallelismLevel == 1) { 398 codegen(C, TM.get(), AddStream, 0, *Mod); 399 } else { 400 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel, 401 std::move(Mod)); 402 } 403 finalizeOptimizationRemarks(std::move(DiagnosticOutputFile)); 404 return Error::success(); 405 } 406 407 Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream, 408 Module &Mod, const ModuleSummaryIndex &CombinedIndex, 409 const FunctionImporter::ImportMapTy &ImportList, 410 const GVSummaryMapTy &DefinedGlobals, 411 MapVector<StringRef, BitcodeModule> &ModuleMap) { 412 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod); 413 if (!TOrErr) 414 return TOrErr.takeError(); 415 416 std::unique_ptr<TargetMachine> TM = 417 createTargetMachine(Conf, Mod.getTargetTriple(), *TOrErr); 418 419 handleAsmUndefinedRefs(Mod, *TM); 420 421 if (Conf.CodeGenOnly) { 422 codegen(Conf, TM.get(), AddStream, Task, Mod); 423 return Error::success(); 424 } 425 426 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod)) 427 return Error::success(); 428 429 renameModuleForThinLTO(Mod, CombinedIndex); 430 431 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals); 432 433 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod)) 434 return Error::success(); 435 436 if (!DefinedGlobals.empty()) 437 thinLTOInternalizeModule(Mod, DefinedGlobals); 438 439 if (Conf.PostInternalizeModuleHook && 440 !Conf.PostInternalizeModuleHook(Task, Mod)) 441 return Error::success(); 442 443 auto ModuleLoader = [&](StringRef Identifier) { 444 assert(Mod.getContext().isODRUniquingDebugTypes() && 445 "ODR Type uniquing should be enabled on the context"); 446 auto I = ModuleMap.find(Identifier); 447 assert(I != ModuleMap.end()); 448 return I->second.getLazyModule(Mod.getContext(), 449 /*ShouldLazyLoadMetadata=*/true, 450 /*IsImporting*/ true); 451 }; 452 453 FunctionImporter Importer(CombinedIndex, ModuleLoader); 454 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError()) 455 return Err; 456 457 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod)) 458 return Error::success(); 459 460 if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true, 461 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex)) 462 return Error::success(); 463 464 codegen(Conf, TM.get(), AddStream, Task, Mod); 465 return Error::success(); 466 } 467