1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===// 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 #include "clang/CodeGen/BackendUtil.h" 10 #include "clang/Basic/CodeGenOptions.h" 11 #include "clang/Basic/Diagnostic.h" 12 #include "clang/Basic/LangOptions.h" 13 #include "clang/Basic/TargetOptions.h" 14 #include "clang/Frontend/FrontendDiagnostic.h" 15 #include "clang/Frontend/Utils.h" 16 #include "clang/Lex/HeaderSearchOptions.h" 17 #include "llvm/ADT/SmallSet.h" 18 #include "llvm/ADT/StringExtras.h" 19 #include "llvm/ADT/StringSwitch.h" 20 #include "llvm/ADT/Triple.h" 21 #include "llvm/Analysis/StackSafetyAnalysis.h" 22 #include "llvm/Analysis/TargetLibraryInfo.h" 23 #include "llvm/Analysis/TargetTransformInfo.h" 24 #include "llvm/Bitcode/BitcodeReader.h" 25 #include "llvm/Bitcode/BitcodeWriter.h" 26 #include "llvm/Bitcode/BitcodeWriterPass.h" 27 #include "llvm/CodeGen/RegAllocRegistry.h" 28 #include "llvm/CodeGen/SchedulerRegistry.h" 29 #include "llvm/CodeGen/TargetSubtargetInfo.h" 30 #include "llvm/IR/DataLayout.h" 31 #include "llvm/IR/IRPrintingPasses.h" 32 #include "llvm/IR/LegacyPassManager.h" 33 #include "llvm/IR/Module.h" 34 #include "llvm/IR/ModuleSummaryIndex.h" 35 #include "llvm/IR/PassManager.h" 36 #include "llvm/IR/Verifier.h" 37 #include "llvm/LTO/LTOBackend.h" 38 #include "llvm/MC/MCAsmInfo.h" 39 #include "llvm/MC/SubtargetFeature.h" 40 #include "llvm/Passes/PassBuilder.h" 41 #include "llvm/Passes/PassPlugin.h" 42 #include "llvm/Passes/StandardInstrumentations.h" 43 #include "llvm/Support/BuryPointer.h" 44 #include "llvm/Support/CommandLine.h" 45 #include "llvm/Support/MemoryBuffer.h" 46 #include "llvm/Support/PrettyStackTrace.h" 47 #include "llvm/Support/TargetRegistry.h" 48 #include "llvm/Support/TimeProfiler.h" 49 #include "llvm/Support/Timer.h" 50 #include "llvm/Support/ToolOutputFile.h" 51 #include "llvm/Support/raw_ostream.h" 52 #include "llvm/Target/TargetMachine.h" 53 #include "llvm/Target/TargetOptions.h" 54 #include "llvm/Transforms/Coroutines.h" 55 #include "llvm/Transforms/Coroutines/CoroCleanup.h" 56 #include "llvm/Transforms/Coroutines/CoroEarly.h" 57 #include "llvm/Transforms/Coroutines/CoroElide.h" 58 #include "llvm/Transforms/Coroutines/CoroSplit.h" 59 #include "llvm/Transforms/IPO.h" 60 #include "llvm/Transforms/IPO/AlwaysInliner.h" 61 #include "llvm/Transforms/IPO/LowerTypeTests.h" 62 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 63 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h" 64 #include "llvm/Transforms/InstCombine/InstCombine.h" 65 #include "llvm/Transforms/Instrumentation.h" 66 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h" 67 #include "llvm/Transforms/Instrumentation/BoundsChecking.h" 68 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h" 69 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h" 70 #include "llvm/Transforms/Instrumentation/InstrProfiling.h" 71 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h" 72 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h" 73 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h" 74 #include "llvm/Transforms/ObjCARC.h" 75 #include "llvm/Transforms/Scalar.h" 76 #include "llvm/Transforms/Scalar/GVN.h" 77 #include "llvm/Transforms/Utils.h" 78 #include "llvm/Transforms/Utils/CanonicalizeAliases.h" 79 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h" 80 #include "llvm/Transforms/Utils/NameAnonGlobals.h" 81 #include "llvm/Transforms/Utils/SymbolRewriter.h" 82 #include "llvm/Transforms/Utils/UniqueInternalLinkageNames.h" 83 #include <memory> 84 using namespace clang; 85 using namespace llvm; 86 87 #define HANDLE_EXTENSION(Ext) \ 88 llvm::PassPluginLibraryInfo get##Ext##PluginInfo(); 89 #include "llvm/Support/Extension.def" 90 91 namespace { 92 93 // Default filename used for profile generation. 94 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw"; 95 96 class EmitAssemblyHelper { 97 DiagnosticsEngine &Diags; 98 const HeaderSearchOptions &HSOpts; 99 const CodeGenOptions &CodeGenOpts; 100 const clang::TargetOptions &TargetOpts; 101 const LangOptions &LangOpts; 102 Module *TheModule; 103 104 Timer CodeGenerationTime; 105 106 std::unique_ptr<raw_pwrite_stream> OS; 107 108 TargetIRAnalysis getTargetIRAnalysis() const { 109 if (TM) 110 return TM->getTargetIRAnalysis(); 111 112 return TargetIRAnalysis(); 113 } 114 115 void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM); 116 117 /// Generates the TargetMachine. 118 /// Leaves TM unchanged if it is unable to create the target machine. 119 /// Some of our clang tests specify triples which are not built 120 /// into clang. This is okay because these tests check the generated 121 /// IR, and they require DataLayout which depends on the triple. 122 /// In this case, we allow this method to fail and not report an error. 123 /// When MustCreateTM is used, we print an error if we are unable to load 124 /// the requested target. 125 void CreateTargetMachine(bool MustCreateTM); 126 127 /// Add passes necessary to emit assembly or LLVM IR. 128 /// 129 /// \return True on success. 130 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action, 131 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS); 132 133 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) { 134 std::error_code EC; 135 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC, 136 llvm::sys::fs::OF_None); 137 if (EC) { 138 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message(); 139 F.reset(); 140 } 141 return F; 142 } 143 144 public: 145 EmitAssemblyHelper(DiagnosticsEngine &_Diags, 146 const HeaderSearchOptions &HeaderSearchOpts, 147 const CodeGenOptions &CGOpts, 148 const clang::TargetOptions &TOpts, 149 const LangOptions &LOpts, Module *M) 150 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts), 151 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M), 152 CodeGenerationTime("codegen", "Code Generation Time") {} 153 154 ~EmitAssemblyHelper() { 155 if (CodeGenOpts.DisableFree) 156 BuryPointer(std::move(TM)); 157 } 158 159 std::unique_ptr<TargetMachine> TM; 160 161 void EmitAssembly(BackendAction Action, 162 std::unique_ptr<raw_pwrite_stream> OS); 163 164 void EmitAssemblyWithNewPassManager(BackendAction Action, 165 std::unique_ptr<raw_pwrite_stream> OS); 166 }; 167 168 // We need this wrapper to access LangOpts and CGOpts from extension functions 169 // that we add to the PassManagerBuilder. 170 class PassManagerBuilderWrapper : public PassManagerBuilder { 171 public: 172 PassManagerBuilderWrapper(const Triple &TargetTriple, 173 const CodeGenOptions &CGOpts, 174 const LangOptions &LangOpts) 175 : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts), 176 LangOpts(LangOpts) {} 177 const Triple &getTargetTriple() const { return TargetTriple; } 178 const CodeGenOptions &getCGOpts() const { return CGOpts; } 179 const LangOptions &getLangOpts() const { return LangOpts; } 180 181 private: 182 const Triple &TargetTriple; 183 const CodeGenOptions &CGOpts; 184 const LangOptions &LangOpts; 185 }; 186 } 187 188 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 189 if (Builder.OptLevel > 0) 190 PM.add(createObjCARCAPElimPass()); 191 } 192 193 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 194 if (Builder.OptLevel > 0) 195 PM.add(createObjCARCExpandPass()); 196 } 197 198 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 199 if (Builder.OptLevel > 0) 200 PM.add(createObjCARCOptPass()); 201 } 202 203 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder, 204 legacy::PassManagerBase &PM) { 205 PM.add(createAddDiscriminatorsPass()); 206 } 207 208 static void addBoundsCheckingPass(const PassManagerBuilder &Builder, 209 legacy::PassManagerBase &PM) { 210 PM.add(createBoundsCheckingLegacyPass()); 211 } 212 213 static SanitizerCoverageOptions 214 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) { 215 SanitizerCoverageOptions Opts; 216 Opts.CoverageType = 217 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType); 218 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls; 219 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB; 220 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp; 221 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv; 222 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep; 223 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters; 224 Opts.TracePC = CGOpts.SanitizeCoverageTracePC; 225 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard; 226 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune; 227 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters; 228 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag; 229 Opts.PCTable = CGOpts.SanitizeCoveragePCTable; 230 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth; 231 return Opts; 232 } 233 234 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder, 235 legacy::PassManagerBase &PM) { 236 const PassManagerBuilderWrapper &BuilderWrapper = 237 static_cast<const PassManagerBuilderWrapper &>(Builder); 238 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 239 auto Opts = getSancovOptsFromCGOpts(CGOpts); 240 PM.add(createModuleSanitizerCoverageLegacyPassPass( 241 Opts, CGOpts.SanitizeCoverageWhitelistFiles, 242 CGOpts.SanitizeCoverageBlacklistFiles)); 243 } 244 245 // Check if ASan should use GC-friendly instrumentation for globals. 246 // First of all, there is no point if -fdata-sections is off (expect for MachO, 247 // where this is not a factor). Also, on ELF this feature requires an assembler 248 // extension that only works with -integrated-as at the moment. 249 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) { 250 if (!CGOpts.SanitizeAddressGlobalsDeadStripping) 251 return false; 252 switch (T.getObjectFormat()) { 253 case Triple::MachO: 254 case Triple::COFF: 255 return true; 256 case Triple::ELF: 257 return CGOpts.DataSections && !CGOpts.DisableIntegratedAS; 258 case Triple::XCOFF: 259 llvm::report_fatal_error("ASan not implemented for XCOFF."); 260 case Triple::Wasm: 261 case Triple::UnknownObjectFormat: 262 break; 263 } 264 return false; 265 } 266 267 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder, 268 legacy::PassManagerBase &PM) { 269 const PassManagerBuilderWrapper &BuilderWrapper = 270 static_cast<const PassManagerBuilderWrapper&>(Builder); 271 const Triple &T = BuilderWrapper.getTargetTriple(); 272 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 273 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address); 274 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope; 275 bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator; 276 bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts); 277 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover, 278 UseAfterScope)); 279 PM.add(createModuleAddressSanitizerLegacyPassPass( 280 /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator)); 281 } 282 283 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder, 284 legacy::PassManagerBase &PM) { 285 PM.add(createAddressSanitizerFunctionPass( 286 /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false)); 287 PM.add(createModuleAddressSanitizerLegacyPassPass( 288 /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true, 289 /*UseOdrIndicator*/ false)); 290 } 291 292 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder, 293 legacy::PassManagerBase &PM) { 294 const PassManagerBuilderWrapper &BuilderWrapper = 295 static_cast<const PassManagerBuilderWrapper &>(Builder); 296 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 297 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress); 298 PM.add( 299 createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover)); 300 } 301 302 static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder, 303 legacy::PassManagerBase &PM) { 304 PM.add(createHWAddressSanitizerLegacyPassPass( 305 /*CompileKernel*/ true, /*Recover*/ true)); 306 } 307 308 static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder, 309 legacy::PassManagerBase &PM, 310 bool CompileKernel) { 311 const PassManagerBuilderWrapper &BuilderWrapper = 312 static_cast<const PassManagerBuilderWrapper&>(Builder); 313 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 314 int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins; 315 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory); 316 PM.add(createMemorySanitizerLegacyPassPass( 317 MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel})); 318 319 // MemorySanitizer inserts complex instrumentation that mostly follows 320 // the logic of the original code, but operates on "shadow" values. 321 // It can benefit from re-running some general purpose optimization passes. 322 if (Builder.OptLevel > 0) { 323 PM.add(createEarlyCSEPass()); 324 PM.add(createReassociatePass()); 325 PM.add(createLICMPass()); 326 PM.add(createGVNPass()); 327 PM.add(createInstructionCombiningPass()); 328 PM.add(createDeadStoreEliminationPass()); 329 } 330 } 331 332 static void addMemorySanitizerPass(const PassManagerBuilder &Builder, 333 legacy::PassManagerBase &PM) { 334 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false); 335 } 336 337 static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder, 338 legacy::PassManagerBase &PM) { 339 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true); 340 } 341 342 static void addThreadSanitizerPass(const PassManagerBuilder &Builder, 343 legacy::PassManagerBase &PM) { 344 PM.add(createThreadSanitizerLegacyPassPass()); 345 } 346 347 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder, 348 legacy::PassManagerBase &PM) { 349 const PassManagerBuilderWrapper &BuilderWrapper = 350 static_cast<const PassManagerBuilderWrapper&>(Builder); 351 const LangOptions &LangOpts = BuilderWrapper.getLangOpts(); 352 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles)); 353 } 354 355 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple, 356 const CodeGenOptions &CodeGenOpts) { 357 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple); 358 359 switch (CodeGenOpts.getVecLib()) { 360 case CodeGenOptions::Accelerate: 361 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate); 362 break; 363 case CodeGenOptions::MASSV: 364 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV); 365 break; 366 case CodeGenOptions::SVML: 367 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML); 368 break; 369 default: 370 break; 371 } 372 return TLII; 373 } 374 375 static void addSymbolRewriterPass(const CodeGenOptions &Opts, 376 legacy::PassManager *MPM) { 377 llvm::SymbolRewriter::RewriteDescriptorList DL; 378 379 llvm::SymbolRewriter::RewriteMapParser MapParser; 380 for (const auto &MapFile : Opts.RewriteMapFiles) 381 MapParser.parse(MapFile, &DL); 382 383 MPM->add(createRewriteSymbolsPass(DL)); 384 } 385 386 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) { 387 switch (CodeGenOpts.OptimizationLevel) { 388 default: 389 llvm_unreachable("Invalid optimization level!"); 390 case 0: 391 return CodeGenOpt::None; 392 case 1: 393 return CodeGenOpt::Less; 394 case 2: 395 return CodeGenOpt::Default; // O2/Os/Oz 396 case 3: 397 return CodeGenOpt::Aggressive; 398 } 399 } 400 401 static Optional<llvm::CodeModel::Model> 402 getCodeModel(const CodeGenOptions &CodeGenOpts) { 403 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel) 404 .Case("tiny", llvm::CodeModel::Tiny) 405 .Case("small", llvm::CodeModel::Small) 406 .Case("kernel", llvm::CodeModel::Kernel) 407 .Case("medium", llvm::CodeModel::Medium) 408 .Case("large", llvm::CodeModel::Large) 409 .Case("default", ~1u) 410 .Default(~0u); 411 assert(CodeModel != ~0u && "invalid code model!"); 412 if (CodeModel == ~1u) 413 return None; 414 return static_cast<llvm::CodeModel::Model>(CodeModel); 415 } 416 417 static CodeGenFileType getCodeGenFileType(BackendAction Action) { 418 if (Action == Backend_EmitObj) 419 return CGFT_ObjectFile; 420 else if (Action == Backend_EmitMCNull) 421 return CGFT_Null; 422 else { 423 assert(Action == Backend_EmitAssembly && "Invalid action!"); 424 return CGFT_AssemblyFile; 425 } 426 } 427 428 static void initTargetOptions(DiagnosticsEngine &Diags, 429 llvm::TargetOptions &Options, 430 const CodeGenOptions &CodeGenOpts, 431 const clang::TargetOptions &TargetOpts, 432 const LangOptions &LangOpts, 433 const HeaderSearchOptions &HSOpts) { 434 Options.ThreadModel = 435 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel) 436 .Case("posix", llvm::ThreadModel::POSIX) 437 .Case("single", llvm::ThreadModel::Single); 438 439 // Set float ABI type. 440 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" || 441 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) && 442 "Invalid Floating Point ABI!"); 443 Options.FloatABIType = 444 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI) 445 .Case("soft", llvm::FloatABI::Soft) 446 .Case("softfp", llvm::FloatABI::Soft) 447 .Case("hard", llvm::FloatABI::Hard) 448 .Default(llvm::FloatABI::Default); 449 450 // Set FP fusion mode. 451 switch (LangOpts.getDefaultFPContractMode()) { 452 case LangOptions::FPM_Off: 453 // Preserve any contraction performed by the front-end. (Strict performs 454 // splitting of the muladd intrinsic in the backend.) 455 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 456 break; 457 case LangOptions::FPM_On: 458 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 459 break; 460 case LangOptions::FPM_Fast: 461 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast; 462 break; 463 } 464 465 Options.UseInitArray = CodeGenOpts.UseInitArray; 466 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS; 467 Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections(); 468 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations; 469 470 // Set EABI version. 471 Options.EABIVersion = TargetOpts.EABIVersion; 472 473 if (LangOpts.SjLjExceptions) 474 Options.ExceptionModel = llvm::ExceptionHandling::SjLj; 475 if (LangOpts.SEHExceptions) 476 Options.ExceptionModel = llvm::ExceptionHandling::WinEH; 477 if (LangOpts.DWARFExceptions) 478 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI; 479 if (LangOpts.WasmExceptions) 480 Options.ExceptionModel = llvm::ExceptionHandling::Wasm; 481 482 Options.NoInfsFPMath = LangOpts.NoHonorInfs; 483 Options.NoNaNsFPMath = LangOpts.NoHonorNaNs; 484 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS; 485 Options.UnsafeFPMath = LangOpts.UnsafeFPMath; 486 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment; 487 488 Options.BBSections = 489 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections) 490 .Case("all", llvm::BasicBlockSection::All) 491 .Case("labels", llvm::BasicBlockSection::Labels) 492 .StartsWith("list=", llvm::BasicBlockSection::List) 493 .Case("none", llvm::BasicBlockSection::None) 494 .Default(llvm::BasicBlockSection::None); 495 496 if (Options.BBSections == llvm::BasicBlockSection::List) { 497 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = 498 MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5)); 499 if (!MBOrErr) 500 Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file) 501 << MBOrErr.getError().message(); 502 else 503 Options.BBSectionsFuncListBuf = std::move(*MBOrErr); 504 } 505 506 Options.FunctionSections = CodeGenOpts.FunctionSections; 507 Options.DataSections = CodeGenOpts.DataSections; 508 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames; 509 Options.UniqueBasicBlockSectionNames = 510 CodeGenOpts.UniqueBasicBlockSectionNames; 511 Options.TLSSize = CodeGenOpts.TLSSize; 512 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS; 513 Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS; 514 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning(); 515 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection; 516 Options.EmitAddrsig = CodeGenOpts.Addrsig; 517 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection; 518 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo; 519 520 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile; 521 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll; 522 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels; 523 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm; 524 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack; 525 Options.MCOptions.MCIncrementalLinkerCompatible = 526 CodeGenOpts.IncrementalLinkerCompatible; 527 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings; 528 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn; 529 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose; 530 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments; 531 Options.MCOptions.ABIName = TargetOpts.ABI; 532 for (const auto &Entry : HSOpts.UserEntries) 533 if (!Entry.IsFramework && 534 (Entry.Group == frontend::IncludeDirGroup::Quoted || 535 Entry.Group == frontend::IncludeDirGroup::Angled || 536 Entry.Group == frontend::IncludeDirGroup::System)) 537 Options.MCOptions.IASSearchPaths.push_back( 538 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path); 539 } 540 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) { 541 if (CodeGenOpts.DisableGCov) 542 return None; 543 if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes) 544 return None; 545 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if 546 // LLVM's -default-gcov-version flag is set to something invalid. 547 GCOVOptions Options; 548 Options.EmitNotes = CodeGenOpts.EmitGcovNotes; 549 Options.EmitData = CodeGenOpts.EmitGcovArcs; 550 llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version)); 551 Options.NoRedZone = CodeGenOpts.DisableRedZone; 552 Options.Filter = CodeGenOpts.ProfileFilterFiles; 553 Options.Exclude = CodeGenOpts.ProfileExcludeFiles; 554 return Options; 555 } 556 557 static Optional<InstrProfOptions> 558 getInstrProfOptions(const CodeGenOptions &CodeGenOpts, 559 const LangOptions &LangOpts) { 560 if (!CodeGenOpts.hasProfileClangInstr()) 561 return None; 562 InstrProfOptions Options; 563 Options.NoRedZone = CodeGenOpts.DisableRedZone; 564 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput; 565 566 // TODO: Surface the option to emit atomic profile counter increments at 567 // the driver level. 568 Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread); 569 return Options; 570 } 571 572 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM, 573 legacy::FunctionPassManager &FPM) { 574 // Handle disabling of all LLVM passes, where we want to preserve the 575 // internal module before any optimization. 576 if (CodeGenOpts.DisableLLVMPasses) 577 return; 578 579 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM 580 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling) 581 // are inserted before PMBuilder ones - they'd get the default-constructed 582 // TLI with an unknown target otherwise. 583 Triple TargetTriple(TheModule->getTargetTriple()); 584 std::unique_ptr<TargetLibraryInfoImpl> TLII( 585 createTLII(TargetTriple, CodeGenOpts)); 586 587 // If we reached here with a non-empty index file name, then the index file 588 // was empty and we are not performing ThinLTO backend compilation (used in 589 // testing in a distributed build environment). Drop any the type test 590 // assume sequences inserted for whole program vtables so that codegen doesn't 591 // complain. 592 if (!CodeGenOpts.ThinLTOIndexFile.empty()) 593 MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr, 594 /*ImportSummary=*/nullptr, 595 /*DropTypeTests=*/true)); 596 597 PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts); 598 599 // At O0 and O1 we only run the always inliner which is more efficient. At 600 // higher optimization levels we run the normal inliner. 601 if (CodeGenOpts.OptimizationLevel <= 1) { 602 bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 && 603 !CodeGenOpts.DisableLifetimeMarkers) || 604 LangOpts.Coroutines); 605 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics); 606 } else { 607 // We do not want to inline hot callsites for SamplePGO module-summary build 608 // because profile annotation will happen again in ThinLTO backend, and we 609 // want the IR of the hot path to match the profile. 610 PMBuilder.Inliner = createFunctionInliningPass( 611 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize, 612 (!CodeGenOpts.SampleProfileFile.empty() && 613 CodeGenOpts.PrepareForThinLTO)); 614 } 615 616 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel; 617 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize; 618 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP; 619 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop; 620 621 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops; 622 // Loop interleaving in the loop vectorizer has historically been set to be 623 // enabled when loop unrolling is enabled. 624 PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops; 625 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions; 626 PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO; 627 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO; 628 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops; 629 630 MPM.add(new TargetLibraryInfoWrapperPass(*TLII)); 631 632 if (TM) 633 TM->adjustPassManager(PMBuilder); 634 635 if (CodeGenOpts.DebugInfoForProfiling || 636 !CodeGenOpts.SampleProfileFile.empty()) 637 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 638 addAddDiscriminatorsPass); 639 640 // In ObjC ARC mode, add the main ARC optimization passes. 641 if (LangOpts.ObjCAutoRefCount) { 642 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 643 addObjCARCExpandPass); 644 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly, 645 addObjCARCAPElimPass); 646 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 647 addObjCARCOptPass); 648 } 649 650 if (LangOpts.Coroutines) 651 addCoroutinePassesToExtensionPoints(PMBuilder); 652 653 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) { 654 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 655 addBoundsCheckingPass); 656 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 657 addBoundsCheckingPass); 658 } 659 660 if (CodeGenOpts.SanitizeCoverageType || 661 CodeGenOpts.SanitizeCoverageIndirectCalls || 662 CodeGenOpts.SanitizeCoverageTraceCmp) { 663 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 664 addSanitizerCoveragePass); 665 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 666 addSanitizerCoveragePass); 667 } 668 669 if (LangOpts.Sanitize.has(SanitizerKind::Address)) { 670 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 671 addAddressSanitizerPasses); 672 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 673 addAddressSanitizerPasses); 674 } 675 676 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) { 677 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 678 addKernelAddressSanitizerPasses); 679 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 680 addKernelAddressSanitizerPasses); 681 } 682 683 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) { 684 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 685 addHWAddressSanitizerPasses); 686 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 687 addHWAddressSanitizerPasses); 688 } 689 690 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) { 691 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 692 addKernelHWAddressSanitizerPasses); 693 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 694 addKernelHWAddressSanitizerPasses); 695 } 696 697 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { 698 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 699 addMemorySanitizerPass); 700 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 701 addMemorySanitizerPass); 702 } 703 704 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) { 705 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 706 addKernelMemorySanitizerPass); 707 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 708 addKernelMemorySanitizerPass); 709 } 710 711 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 712 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 713 addThreadSanitizerPass); 714 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 715 addThreadSanitizerPass); 716 } 717 718 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) { 719 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 720 addDataFlowSanitizerPass); 721 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 722 addDataFlowSanitizerPass); 723 } 724 725 // Set up the per-function pass manager. 726 FPM.add(new TargetLibraryInfoWrapperPass(*TLII)); 727 if (CodeGenOpts.VerifyModule) 728 FPM.add(createVerifierPass()); 729 730 // Set up the per-module pass manager. 731 if (!CodeGenOpts.RewriteMapFiles.empty()) 732 addSymbolRewriterPass(CodeGenOpts, &MPM); 733 734 // Add UniqueInternalLinkageNames Pass which renames internal linkage symbols 735 // with unique names. 736 if (CodeGenOpts.UniqueInternalLinkageNames) { 737 MPM.add(createUniqueInternalLinkageNamesPass()); 738 } 739 740 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) { 741 MPM.add(createGCOVProfilerPass(*Options)); 742 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo) 743 MPM.add(createStripSymbolsPass(true)); 744 } 745 746 if (Optional<InstrProfOptions> Options = 747 getInstrProfOptions(CodeGenOpts, LangOpts)) 748 MPM.add(createInstrProfilingLegacyPass(*Options, false)); 749 750 bool hasIRInstr = false; 751 if (CodeGenOpts.hasProfileIRInstr()) { 752 PMBuilder.EnablePGOInstrGen = true; 753 hasIRInstr = true; 754 } 755 if (CodeGenOpts.hasProfileCSIRInstr()) { 756 assert(!CodeGenOpts.hasProfileCSIRUse() && 757 "Cannot have both CSProfileUse pass and CSProfileGen pass at the " 758 "same time"); 759 assert(!hasIRInstr && 760 "Cannot have both ProfileGen pass and CSProfileGen pass at the " 761 "same time"); 762 PMBuilder.EnablePGOCSInstrGen = true; 763 hasIRInstr = true; 764 } 765 if (hasIRInstr) { 766 if (!CodeGenOpts.InstrProfileOutput.empty()) 767 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput; 768 else 769 PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName); 770 } 771 if (CodeGenOpts.hasProfileIRUse()) { 772 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath; 773 PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse(); 774 } 775 776 if (!CodeGenOpts.SampleProfileFile.empty()) 777 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile; 778 779 PMBuilder.populateFunctionPassManager(FPM); 780 PMBuilder.populateModulePassManager(MPM); 781 } 782 783 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) { 784 SmallVector<const char *, 16> BackendArgs; 785 BackendArgs.push_back("clang"); // Fake program name. 786 if (!CodeGenOpts.DebugPass.empty()) { 787 BackendArgs.push_back("-debug-pass"); 788 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str()); 789 } 790 if (!CodeGenOpts.LimitFloatPrecision.empty()) { 791 BackendArgs.push_back("-limit-float-precision"); 792 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str()); 793 } 794 BackendArgs.push_back(nullptr); 795 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, 796 BackendArgs.data()); 797 } 798 799 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) { 800 // Create the TargetMachine for generating code. 801 std::string Error; 802 std::string Triple = TheModule->getTargetTriple(); 803 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error); 804 if (!TheTarget) { 805 if (MustCreateTM) 806 Diags.Report(diag::err_fe_unable_to_create_target) << Error; 807 return; 808 } 809 810 Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts); 811 std::string FeaturesStr = 812 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ","); 813 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel; 814 CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts); 815 816 llvm::TargetOptions Options; 817 initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts); 818 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr, 819 Options, RM, CM, OptLevel)); 820 } 821 822 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses, 823 BackendAction Action, 824 raw_pwrite_stream &OS, 825 raw_pwrite_stream *DwoOS) { 826 // Add LibraryInfo. 827 llvm::Triple TargetTriple(TheModule->getTargetTriple()); 828 std::unique_ptr<TargetLibraryInfoImpl> TLII( 829 createTLII(TargetTriple, CodeGenOpts)); 830 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII)); 831 832 // Normal mode, emit a .s or .o file by running the code generator. Note, 833 // this also adds codegenerator level optimization passes. 834 CodeGenFileType CGFT = getCodeGenFileType(Action); 835 836 // Add ObjC ARC final-cleanup optimizations. This is done as part of the 837 // "codegen" passes so that it isn't run multiple times when there is 838 // inlining happening. 839 if (CodeGenOpts.OptimizationLevel > 0) 840 CodeGenPasses.add(createObjCARCContractPass()); 841 842 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT, 843 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) { 844 Diags.Report(diag::err_fe_unable_to_interface_with_target); 845 return false; 846 } 847 848 return true; 849 } 850 851 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, 852 std::unique_ptr<raw_pwrite_stream> OS) { 853 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr); 854 855 setCommandLineOpts(CodeGenOpts); 856 857 bool UsesCodeGen = (Action != Backend_EmitNothing && 858 Action != Backend_EmitBC && 859 Action != Backend_EmitLL); 860 CreateTargetMachine(UsesCodeGen); 861 862 if (UsesCodeGen && !TM) 863 return; 864 if (TM) 865 TheModule->setDataLayout(TM->createDataLayout()); 866 867 legacy::PassManager PerModulePasses; 868 PerModulePasses.add( 869 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 870 871 legacy::FunctionPassManager PerFunctionPasses(TheModule); 872 PerFunctionPasses.add( 873 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 874 875 CreatePasses(PerModulePasses, PerFunctionPasses); 876 877 legacy::PassManager CodeGenPasses; 878 CodeGenPasses.add( 879 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 880 881 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS; 882 883 switch (Action) { 884 case Backend_EmitNothing: 885 break; 886 887 case Backend_EmitBC: 888 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) { 889 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) { 890 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile); 891 if (!ThinLinkOS) 892 return; 893 } 894 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 895 CodeGenOpts.EnableSplitLTOUnit); 896 PerModulePasses.add(createWriteThinLTOBitcodePass( 897 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr)); 898 } else { 899 // Emit a module summary by default for Regular LTO except for ld64 900 // targets 901 bool EmitLTOSummary = 902 (CodeGenOpts.PrepareForLTO && 903 !CodeGenOpts.DisableLLVMPasses && 904 llvm::Triple(TheModule->getTargetTriple()).getVendor() != 905 llvm::Triple::Apple); 906 if (EmitLTOSummary) { 907 if (!TheModule->getModuleFlag("ThinLTO")) 908 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0)); 909 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 910 uint32_t(1)); 911 } 912 913 PerModulePasses.add(createBitcodeWriterPass( 914 *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary)); 915 } 916 break; 917 918 case Backend_EmitLL: 919 PerModulePasses.add( 920 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists)); 921 break; 922 923 default: 924 if (!CodeGenOpts.SplitDwarfOutput.empty()) { 925 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput); 926 if (!DwoOS) 927 return; 928 } 929 if (!AddEmitPasses(CodeGenPasses, Action, *OS, 930 DwoOS ? &DwoOS->os() : nullptr)) 931 return; 932 } 933 934 // Before executing passes, print the final values of the LLVM options. 935 cl::PrintOptionValues(); 936 937 // Run passes. For now we do all passes at once, but eventually we 938 // would like to have the option of streaming code generation. 939 940 { 941 PrettyStackTraceString CrashInfo("Per-function optimization"); 942 llvm::TimeTraceScope TimeScope("PerFunctionPasses"); 943 944 PerFunctionPasses.doInitialization(); 945 for (Function &F : *TheModule) 946 if (!F.isDeclaration()) 947 PerFunctionPasses.run(F); 948 PerFunctionPasses.doFinalization(); 949 } 950 951 { 952 PrettyStackTraceString CrashInfo("Per-module optimization passes"); 953 llvm::TimeTraceScope TimeScope("PerModulePasses"); 954 PerModulePasses.run(*TheModule); 955 } 956 957 { 958 PrettyStackTraceString CrashInfo("Code generation"); 959 llvm::TimeTraceScope TimeScope("CodeGenPasses"); 960 CodeGenPasses.run(*TheModule); 961 } 962 963 if (ThinLinkOS) 964 ThinLinkOS->keep(); 965 if (DwoOS) 966 DwoOS->keep(); 967 } 968 969 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) { 970 switch (Opts.OptimizationLevel) { 971 default: 972 llvm_unreachable("Invalid optimization level!"); 973 974 case 1: 975 return PassBuilder::OptimizationLevel::O1; 976 977 case 2: 978 switch (Opts.OptimizeSize) { 979 default: 980 llvm_unreachable("Invalid optimization level for size!"); 981 982 case 0: 983 return PassBuilder::OptimizationLevel::O2; 984 985 case 1: 986 return PassBuilder::OptimizationLevel::Os; 987 988 case 2: 989 return PassBuilder::OptimizationLevel::Oz; 990 } 991 992 case 3: 993 return PassBuilder::OptimizationLevel::O3; 994 } 995 } 996 997 static void addCoroutinePassesAtO0(ModulePassManager &MPM, 998 const LangOptions &LangOpts, 999 const CodeGenOptions &CodeGenOpts) { 1000 if (!LangOpts.Coroutines) 1001 return; 1002 1003 MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass())); 1004 1005 CGSCCPassManager CGPM(CodeGenOpts.DebugPassManager); 1006 CGPM.addPass(CoroSplitPass()); 1007 CGPM.addPass(createCGSCCToFunctionPassAdaptor(CoroElidePass())); 1008 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM))); 1009 1010 MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass())); 1011 } 1012 1013 static void addSanitizersAtO0(ModulePassManager &MPM, 1014 const Triple &TargetTriple, 1015 const LangOptions &LangOpts, 1016 const CodeGenOptions &CodeGenOpts) { 1017 if (CodeGenOpts.SanitizeCoverageType || 1018 CodeGenOpts.SanitizeCoverageIndirectCalls || 1019 CodeGenOpts.SanitizeCoverageTraceCmp) { 1020 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts); 1021 MPM.addPass(ModuleSanitizerCoveragePass( 1022 SancovOpts, CodeGenOpts.SanitizeCoverageWhitelistFiles, 1023 CodeGenOpts.SanitizeCoverageBlacklistFiles)); 1024 } 1025 1026 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) { 1027 MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>()); 1028 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask); 1029 MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass( 1030 CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope))); 1031 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts); 1032 MPM.addPass( 1033 ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope, 1034 CodeGenOpts.SanitizeAddressUseOdrIndicator)); 1035 }; 1036 1037 if (LangOpts.Sanitize.has(SanitizerKind::Address)) { 1038 ASanPass(SanitizerKind::Address, /*CompileKernel=*/false); 1039 } 1040 1041 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) { 1042 ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true); 1043 } 1044 1045 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { 1046 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory); 1047 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins; 1048 MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false})); 1049 MPM.addPass(createModuleToFunctionPassAdaptor( 1050 MemorySanitizerPass({TrackOrigins, Recover, false}))); 1051 } 1052 1053 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) { 1054 MPM.addPass(createModuleToFunctionPassAdaptor( 1055 MemorySanitizerPass({0, false, /*Kernel=*/true}))); 1056 } 1057 1058 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 1059 MPM.addPass(ThreadSanitizerPass()); 1060 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass())); 1061 } 1062 } 1063 1064 /// A clean version of `EmitAssembly` that uses the new pass manager. 1065 /// 1066 /// Not all features are currently supported in this system, but where 1067 /// necessary it falls back to the legacy pass manager to at least provide 1068 /// basic functionality. 1069 /// 1070 /// This API is planned to have its functionality finished and then to replace 1071 /// `EmitAssembly` at some point in the future when the default switches. 1072 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager( 1073 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) { 1074 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr); 1075 setCommandLineOpts(CodeGenOpts); 1076 1077 bool RequiresCodeGen = (Action != Backend_EmitNothing && 1078 Action != Backend_EmitBC && 1079 Action != Backend_EmitLL); 1080 CreateTargetMachine(RequiresCodeGen); 1081 1082 if (RequiresCodeGen && !TM) 1083 return; 1084 if (TM) 1085 TheModule->setDataLayout(TM->createDataLayout()); 1086 1087 Optional<PGOOptions> PGOOpt; 1088 1089 if (CodeGenOpts.hasProfileIRInstr()) 1090 // -fprofile-generate. 1091 PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty() 1092 ? std::string(DefaultProfileGenName) 1093 : CodeGenOpts.InstrProfileOutput, 1094 "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction, 1095 CodeGenOpts.DebugInfoForProfiling); 1096 else if (CodeGenOpts.hasProfileIRUse()) { 1097 // -fprofile-use. 1098 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse 1099 : PGOOptions::NoCSAction; 1100 PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "", 1101 CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse, 1102 CSAction, CodeGenOpts.DebugInfoForProfiling); 1103 } else if (!CodeGenOpts.SampleProfileFile.empty()) 1104 // -fprofile-sample-use 1105 PGOOpt = 1106 PGOOptions(CodeGenOpts.SampleProfileFile, "", 1107 CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse, 1108 PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling); 1109 else if (CodeGenOpts.DebugInfoForProfiling) 1110 // -fdebug-info-for-profiling 1111 PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction, 1112 PGOOptions::NoCSAction, true); 1113 1114 // Check to see if we want to generate a CS profile. 1115 if (CodeGenOpts.hasProfileCSIRInstr()) { 1116 assert(!CodeGenOpts.hasProfileCSIRUse() && 1117 "Cannot have both CSProfileUse pass and CSProfileGen pass at " 1118 "the same time"); 1119 if (PGOOpt.hasValue()) { 1120 assert(PGOOpt->Action != PGOOptions::IRInstr && 1121 PGOOpt->Action != PGOOptions::SampleUse && 1122 "Cannot run CSProfileGen pass with ProfileGen or SampleUse " 1123 " pass"); 1124 PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty() 1125 ? std::string(DefaultProfileGenName) 1126 : CodeGenOpts.InstrProfileOutput; 1127 PGOOpt->CSAction = PGOOptions::CSIRInstr; 1128 } else 1129 PGOOpt = PGOOptions("", 1130 CodeGenOpts.InstrProfileOutput.empty() 1131 ? std::string(DefaultProfileGenName) 1132 : CodeGenOpts.InstrProfileOutput, 1133 "", PGOOptions::NoAction, PGOOptions::CSIRInstr, 1134 CodeGenOpts.DebugInfoForProfiling); 1135 } 1136 1137 PipelineTuningOptions PTO; 1138 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops; 1139 // For historical reasons, loop interleaving is set to mirror setting for loop 1140 // unrolling. 1141 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops; 1142 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop; 1143 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP; 1144 PTO.CallGraphProfile = CodeGenOpts.CallGraphProfile; 1145 PTO.Coroutines = LangOpts.Coroutines; 1146 1147 PassInstrumentationCallbacks PIC; 1148 StandardInstrumentations SI; 1149 SI.registerCallbacks(PIC); 1150 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC); 1151 1152 // Attempt to load pass plugins and register their callbacks with PB. 1153 for (auto &PluginFN : CodeGenOpts.PassPlugins) { 1154 auto PassPlugin = PassPlugin::Load(PluginFN); 1155 if (PassPlugin) { 1156 PassPlugin->registerPassBuilderCallbacks(PB); 1157 } else { 1158 Diags.Report(diag::err_fe_unable_to_load_plugin) 1159 << PluginFN << toString(PassPlugin.takeError()); 1160 } 1161 } 1162 #define HANDLE_EXTENSION(Ext) \ 1163 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB); 1164 #include "llvm/Support/Extension.def" 1165 1166 LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager); 1167 FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager); 1168 CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager); 1169 ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager); 1170 1171 // Register the AA manager first so that our version is the one used. 1172 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); }); 1173 1174 // Register the target library analysis directly and give it a customized 1175 // preset TLI. 1176 Triple TargetTriple(TheModule->getTargetTriple()); 1177 std::unique_ptr<TargetLibraryInfoImpl> TLII( 1178 createTLII(TargetTriple, CodeGenOpts)); 1179 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); }); 1180 1181 // Register all the basic analyses with the managers. 1182 PB.registerModuleAnalyses(MAM); 1183 PB.registerCGSCCAnalyses(CGAM); 1184 PB.registerFunctionAnalyses(FAM); 1185 PB.registerLoopAnalyses(LAM); 1186 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); 1187 1188 ModulePassManager MPM(CodeGenOpts.DebugPassManager); 1189 1190 if (!CodeGenOpts.DisableLLVMPasses) { 1191 bool IsThinLTO = CodeGenOpts.PrepareForThinLTO; 1192 bool IsLTO = CodeGenOpts.PrepareForLTO; 1193 1194 if (CodeGenOpts.OptimizationLevel == 0) { 1195 // If we reached here with a non-empty index file name, then the index 1196 // file was empty and we are not performing ThinLTO backend compilation 1197 // (used in testing in a distributed build environment). Drop any the type 1198 // test assume sequences inserted for whole program vtables so that 1199 // codegen doesn't complain. 1200 if (!CodeGenOpts.ThinLTOIndexFile.empty()) 1201 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr, 1202 /*ImportSummary=*/nullptr, 1203 /*DropTypeTests=*/true)); 1204 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) 1205 MPM.addPass(GCOVProfilerPass(*Options)); 1206 if (Optional<InstrProfOptions> Options = 1207 getInstrProfOptions(CodeGenOpts, LangOpts)) 1208 MPM.addPass(InstrProfiling(*Options, false)); 1209 1210 // Build a minimal pipeline based on the semantics required by Clang, 1211 // which is just that always inlining occurs. Further, disable generating 1212 // lifetime intrinsics to avoid enabling further optimizations during 1213 // code generation. 1214 // However, we need to insert lifetime intrinsics to avoid invalid access 1215 // caused by multithreaded coroutines. 1216 MPM.addPass( 1217 AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/LangOpts.Coroutines)); 1218 1219 // At -O0, we can still do PGO. Add all the requested passes for 1220 // instrumentation PGO, if requested. 1221 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr || 1222 PGOOpt->Action == PGOOptions::IRUse)) 1223 PB.addPGOInstrPassesForO0( 1224 MPM, CodeGenOpts.DebugPassManager, 1225 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr), 1226 /* IsCS */ false, PGOOpt->ProfileFile, 1227 PGOOpt->ProfileRemappingFile); 1228 1229 // At -O0 we directly run necessary sanitizer passes. 1230 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) 1231 MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass())); 1232 1233 // Add UniqueInternalLinkageNames Pass which renames internal linkage 1234 // symbols with unique names. 1235 if (CodeGenOpts.UniqueInternalLinkageNames) { 1236 MPM.addPass(UniqueInternalLinkageNamesPass()); 1237 } 1238 1239 // Lastly, add semantically necessary passes for LTO. 1240 if (IsLTO || IsThinLTO) { 1241 MPM.addPass(CanonicalizeAliasesPass()); 1242 MPM.addPass(NameAnonGlobalPass()); 1243 } 1244 } else { 1245 // Map our optimization levels into one of the distinct levels used to 1246 // configure the pipeline. 1247 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts); 1248 1249 // If we reached here with a non-empty index file name, then the index 1250 // file was empty and we are not performing ThinLTO backend compilation 1251 // (used in testing in a distributed build environment). Drop any the type 1252 // test assume sequences inserted for whole program vtables so that 1253 // codegen doesn't complain. 1254 if (!CodeGenOpts.ThinLTOIndexFile.empty()) 1255 PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) { 1256 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr, 1257 /*ImportSummary=*/nullptr, 1258 /*DropTypeTests=*/true)); 1259 }); 1260 1261 PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) { 1262 MPM.addPass(createModuleToFunctionPassAdaptor( 1263 EntryExitInstrumenterPass(/*PostInlining=*/false))); 1264 }); 1265 1266 // Register callbacks to schedule sanitizer passes at the appropriate part of 1267 // the pipeline. 1268 // FIXME: either handle asan/the remaining sanitizers or error out 1269 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) 1270 PB.registerScalarOptimizerLateEPCallback( 1271 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) { 1272 FPM.addPass(BoundsCheckingPass()); 1273 }); 1274 1275 if (CodeGenOpts.SanitizeCoverageType || 1276 CodeGenOpts.SanitizeCoverageIndirectCalls || 1277 CodeGenOpts.SanitizeCoverageTraceCmp) { 1278 PB.registerOptimizerLastEPCallback( 1279 [this](ModulePassManager &MPM, 1280 PassBuilder::OptimizationLevel Level) { 1281 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts); 1282 MPM.addPass(ModuleSanitizerCoveragePass( 1283 SancovOpts, CodeGenOpts.SanitizeCoverageWhitelistFiles, 1284 CodeGenOpts.SanitizeCoverageBlacklistFiles)); 1285 }); 1286 } 1287 1288 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { 1289 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins; 1290 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory); 1291 PB.registerPipelineStartEPCallback( 1292 [TrackOrigins, Recover](ModulePassManager &MPM) { 1293 MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false})); 1294 }); 1295 PB.registerOptimizerLastEPCallback( 1296 [TrackOrigins, Recover](ModulePassManager &MPM, 1297 PassBuilder::OptimizationLevel Level) { 1298 MPM.addPass(createModuleToFunctionPassAdaptor( 1299 MemorySanitizerPass({TrackOrigins, Recover, false}))); 1300 }); 1301 } 1302 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 1303 PB.registerPipelineStartEPCallback( 1304 [](ModulePassManager &MPM) { MPM.addPass(ThreadSanitizerPass()); }); 1305 PB.registerOptimizerLastEPCallback( 1306 [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) { 1307 MPM.addPass( 1308 createModuleToFunctionPassAdaptor(ThreadSanitizerPass())); 1309 }); 1310 } 1311 if (LangOpts.Sanitize.has(SanitizerKind::Address)) { 1312 PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM) { 1313 MPM.addPass( 1314 RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>()); 1315 }); 1316 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address); 1317 bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope; 1318 PB.registerOptimizerLastEPCallback( 1319 [Recover, UseAfterScope](ModulePassManager &MPM, 1320 PassBuilder::OptimizationLevel Level) { 1321 MPM.addPass( 1322 createModuleToFunctionPassAdaptor(AddressSanitizerPass( 1323 /*CompileKernel=*/false, Recover, UseAfterScope))); 1324 }); 1325 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts); 1326 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator; 1327 PB.registerPipelineStartEPCallback( 1328 [Recover, ModuleUseAfterScope, 1329 UseOdrIndicator](ModulePassManager &MPM) { 1330 MPM.addPass(ModuleAddressSanitizerPass( 1331 /*CompileKernel=*/false, Recover, ModuleUseAfterScope, 1332 UseOdrIndicator)); 1333 }); 1334 } 1335 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) 1336 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) { 1337 MPM.addPass(GCOVProfilerPass(*Options)); 1338 }); 1339 if (Optional<InstrProfOptions> Options = 1340 getInstrProfOptions(CodeGenOpts, LangOpts)) 1341 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) { 1342 MPM.addPass(InstrProfiling(*Options, false)); 1343 }); 1344 1345 // Add UniqueInternalLinkageNames Pass which renames internal linkage 1346 // symbols with unique names. 1347 if (CodeGenOpts.UniqueInternalLinkageNames) { 1348 MPM.addPass(UniqueInternalLinkageNamesPass()); 1349 } 1350 1351 if (IsThinLTO) { 1352 MPM = PB.buildThinLTOPreLinkDefaultPipeline( 1353 Level, CodeGenOpts.DebugPassManager); 1354 MPM.addPass(CanonicalizeAliasesPass()); 1355 MPM.addPass(NameAnonGlobalPass()); 1356 } else if (IsLTO) { 1357 MPM = PB.buildLTOPreLinkDefaultPipeline(Level, 1358 CodeGenOpts.DebugPassManager); 1359 MPM.addPass(CanonicalizeAliasesPass()); 1360 MPM.addPass(NameAnonGlobalPass()); 1361 } else { 1362 MPM = PB.buildPerModuleDefaultPipeline(Level, 1363 CodeGenOpts.DebugPassManager); 1364 } 1365 } 1366 1367 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) { 1368 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress); 1369 MPM.addPass(HWAddressSanitizerPass( 1370 /*CompileKernel=*/false, Recover)); 1371 } 1372 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) { 1373 MPM.addPass(HWAddressSanitizerPass( 1374 /*CompileKernel=*/true, /*Recover=*/true)); 1375 } 1376 1377 if (CodeGenOpts.OptimizationLevel == 0) { 1378 addCoroutinePassesAtO0(MPM, LangOpts, CodeGenOpts); 1379 addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts); 1380 } 1381 } 1382 1383 // FIXME: We still use the legacy pass manager to do code generation. We 1384 // create that pass manager here and use it as needed below. 1385 legacy::PassManager CodeGenPasses; 1386 bool NeedCodeGen = false; 1387 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS; 1388 1389 // Append any output we need to the pass manager. 1390 switch (Action) { 1391 case Backend_EmitNothing: 1392 break; 1393 1394 case Backend_EmitBC: 1395 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) { 1396 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) { 1397 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile); 1398 if (!ThinLinkOS) 1399 return; 1400 } 1401 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 1402 CodeGenOpts.EnableSplitLTOUnit); 1403 MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os() 1404 : nullptr)); 1405 } else { 1406 // Emit a module summary by default for Regular LTO except for ld64 1407 // targets 1408 bool EmitLTOSummary = 1409 (CodeGenOpts.PrepareForLTO && 1410 !CodeGenOpts.DisableLLVMPasses && 1411 llvm::Triple(TheModule->getTargetTriple()).getVendor() != 1412 llvm::Triple::Apple); 1413 if (EmitLTOSummary) { 1414 if (!TheModule->getModuleFlag("ThinLTO")) 1415 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0)); 1416 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 1417 uint32_t(1)); 1418 } 1419 MPM.addPass( 1420 BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary)); 1421 } 1422 break; 1423 1424 case Backend_EmitLL: 1425 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists)); 1426 break; 1427 1428 case Backend_EmitAssembly: 1429 case Backend_EmitMCNull: 1430 case Backend_EmitObj: 1431 NeedCodeGen = true; 1432 CodeGenPasses.add( 1433 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 1434 if (!CodeGenOpts.SplitDwarfOutput.empty()) { 1435 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput); 1436 if (!DwoOS) 1437 return; 1438 } 1439 if (!AddEmitPasses(CodeGenPasses, Action, *OS, 1440 DwoOS ? &DwoOS->os() : nullptr)) 1441 // FIXME: Should we handle this error differently? 1442 return; 1443 break; 1444 } 1445 1446 // Before executing passes, print the final values of the LLVM options. 1447 cl::PrintOptionValues(); 1448 1449 // Now that we have all of the passes ready, run them. 1450 { 1451 PrettyStackTraceString CrashInfo("Optimizer"); 1452 MPM.run(*TheModule, MAM); 1453 } 1454 1455 // Now if needed, run the legacy PM for codegen. 1456 if (NeedCodeGen) { 1457 PrettyStackTraceString CrashInfo("Code generation"); 1458 CodeGenPasses.run(*TheModule); 1459 } 1460 1461 if (ThinLinkOS) 1462 ThinLinkOS->keep(); 1463 if (DwoOS) 1464 DwoOS->keep(); 1465 } 1466 1467 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) { 1468 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef); 1469 if (!BMsOrErr) 1470 return BMsOrErr.takeError(); 1471 1472 // The bitcode file may contain multiple modules, we want the one that is 1473 // marked as being the ThinLTO module. 1474 if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr)) 1475 return *Bm; 1476 1477 return make_error<StringError>("Could not find module summary", 1478 inconvertibleErrorCode()); 1479 } 1480 1481 BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) { 1482 for (BitcodeModule &BM : BMs) { 1483 Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo(); 1484 if (LTOInfo && LTOInfo->IsThinLTO) 1485 return &BM; 1486 } 1487 return nullptr; 1488 } 1489 1490 static void runThinLTOBackend( 1491 DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M, 1492 const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts, 1493 const clang::TargetOptions &TOpts, const LangOptions &LOpts, 1494 std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile, 1495 std::string ProfileRemapping, BackendAction Action) { 1496 StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>> 1497 ModuleToDefinedGVSummaries; 1498 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 1499 1500 setCommandLineOpts(CGOpts); 1501 1502 // We can simply import the values mentioned in the combined index, since 1503 // we should only invoke this using the individual indexes written out 1504 // via a WriteIndexesThinBackend. 1505 FunctionImporter::ImportMapTy ImportList; 1506 for (auto &GlobalList : *CombinedIndex) { 1507 // Ignore entries for undefined references. 1508 if (GlobalList.second.SummaryList.empty()) 1509 continue; 1510 1511 auto GUID = GlobalList.first; 1512 for (auto &Summary : GlobalList.second.SummaryList) { 1513 // Skip the summaries for the importing module. These are included to 1514 // e.g. record required linkage changes. 1515 if (Summary->modulePath() == M->getModuleIdentifier()) 1516 continue; 1517 // Add an entry to provoke importing by thinBackend. 1518 ImportList[Summary->modulePath()].insert(GUID); 1519 } 1520 } 1521 1522 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports; 1523 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap; 1524 1525 for (auto &I : ImportList) { 1526 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr = 1527 llvm::MemoryBuffer::getFile(I.first()); 1528 if (!MBOrErr) { 1529 errs() << "Error loading imported file '" << I.first() 1530 << "': " << MBOrErr.getError().message() << "\n"; 1531 return; 1532 } 1533 1534 Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr); 1535 if (!BMOrErr) { 1536 handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) { 1537 errs() << "Error loading imported file '" << I.first() 1538 << "': " << EIB.message() << '\n'; 1539 }); 1540 return; 1541 } 1542 ModuleMap.insert({I.first(), *BMOrErr}); 1543 1544 OwnedImports.push_back(std::move(*MBOrErr)); 1545 } 1546 auto AddStream = [&](size_t Task) { 1547 return std::make_unique<lto::NativeObjectStream>(std::move(OS)); 1548 }; 1549 lto::Config Conf; 1550 if (CGOpts.SaveTempsFilePrefix != "") { 1551 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".", 1552 /* UseInputModulePath */ false)) { 1553 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 1554 errs() << "Error setting up ThinLTO save-temps: " << EIB.message() 1555 << '\n'; 1556 }); 1557 } 1558 } 1559 Conf.CPU = TOpts.CPU; 1560 Conf.CodeModel = getCodeModel(CGOpts); 1561 Conf.MAttrs = TOpts.Features; 1562 Conf.RelocModel = CGOpts.RelocationModel; 1563 Conf.CGOptLevel = getCGOptLevel(CGOpts); 1564 Conf.OptLevel = CGOpts.OptimizationLevel; 1565 initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts); 1566 Conf.SampleProfile = std::move(SampleProfile); 1567 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops; 1568 // For historical reasons, loop interleaving is set to mirror setting for loop 1569 // unrolling. 1570 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops; 1571 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop; 1572 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP; 1573 Conf.PTO.CallGraphProfile = CGOpts.CallGraphProfile; 1574 1575 // Context sensitive profile. 1576 if (CGOpts.hasProfileCSIRInstr()) { 1577 Conf.RunCSIRInstr = true; 1578 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput); 1579 } else if (CGOpts.hasProfileCSIRUse()) { 1580 Conf.RunCSIRInstr = false; 1581 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath); 1582 } 1583 1584 Conf.ProfileRemapping = std::move(ProfileRemapping); 1585 Conf.UseNewPM = CGOpts.ExperimentalNewPassManager; 1586 Conf.DebugPassManager = CGOpts.DebugPassManager; 1587 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness; 1588 Conf.RemarksFilename = CGOpts.OptRecordFile; 1589 Conf.RemarksPasses = CGOpts.OptRecordPasses; 1590 Conf.RemarksFormat = CGOpts.OptRecordFormat; 1591 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile; 1592 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput; 1593 switch (Action) { 1594 case Backend_EmitNothing: 1595 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) { 1596 return false; 1597 }; 1598 break; 1599 case Backend_EmitLL: 1600 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) { 1601 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists); 1602 return false; 1603 }; 1604 break; 1605 case Backend_EmitBC: 1606 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) { 1607 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists); 1608 return false; 1609 }; 1610 break; 1611 default: 1612 Conf.CGFileType = getCodeGenFileType(Action); 1613 break; 1614 } 1615 if (Error E = thinBackend( 1616 Conf, -1, AddStream, *M, *CombinedIndex, ImportList, 1617 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) { 1618 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 1619 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n'; 1620 }); 1621 } 1622 } 1623 1624 void clang::EmitBackendOutput(DiagnosticsEngine &Diags, 1625 const HeaderSearchOptions &HeaderOpts, 1626 const CodeGenOptions &CGOpts, 1627 const clang::TargetOptions &TOpts, 1628 const LangOptions &LOpts, 1629 const llvm::DataLayout &TDesc, Module *M, 1630 BackendAction Action, 1631 std::unique_ptr<raw_pwrite_stream> OS) { 1632 1633 llvm::TimeTraceScope TimeScope("Backend"); 1634 1635 std::unique_ptr<llvm::Module> EmptyModule; 1636 if (!CGOpts.ThinLTOIndexFile.empty()) { 1637 // If we are performing a ThinLTO importing compile, load the function index 1638 // into memory and pass it into runThinLTOBackend, which will run the 1639 // function importer and invoke LTO passes. 1640 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr = 1641 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile, 1642 /*IgnoreEmptyThinLTOIndexFile*/true); 1643 if (!IndexOrErr) { 1644 logAllUnhandledErrors(IndexOrErr.takeError(), errs(), 1645 "Error loading index file '" + 1646 CGOpts.ThinLTOIndexFile + "': "); 1647 return; 1648 } 1649 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr); 1650 // A null CombinedIndex means we should skip ThinLTO compilation 1651 // (LLVM will optionally ignore empty index files, returning null instead 1652 // of an error). 1653 if (CombinedIndex) { 1654 if (!CombinedIndex->skipModuleByDistributedBackend()) { 1655 runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts, 1656 TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile, 1657 CGOpts.ProfileRemappingFile, Action); 1658 return; 1659 } 1660 // Distributed indexing detected that nothing from the module is needed 1661 // for the final linking. So we can skip the compilation. We sill need to 1662 // output an empty object file to make sure that a linker does not fail 1663 // trying to read it. Also for some features, like CFI, we must skip 1664 // the compilation as CombinedIndex does not contain all required 1665 // information. 1666 EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext()); 1667 EmptyModule->setTargetTriple(M->getTargetTriple()); 1668 M = EmptyModule.get(); 1669 } 1670 } 1671 1672 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M); 1673 1674 if (CGOpts.ExperimentalNewPassManager) 1675 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS)); 1676 else 1677 AsmHelper.EmitAssembly(Action, std::move(OS)); 1678 1679 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's 1680 // DataLayout. 1681 if (AsmHelper.TM) { 1682 std::string DLDesc = M->getDataLayout().getStringRepresentation(); 1683 if (DLDesc != TDesc.getStringRepresentation()) { 1684 unsigned DiagID = Diags.getCustomDiagID( 1685 DiagnosticsEngine::Error, "backend data layout '%0' does not match " 1686 "expected target description '%1'"); 1687 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation(); 1688 } 1689 } 1690 } 1691 1692 // With -fembed-bitcode, save a copy of the llvm IR as data in the 1693 // __LLVM,__bitcode section. 1694 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, 1695 llvm::MemoryBufferRef Buf) { 1696 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off) 1697 return; 1698 llvm::EmbedBitcodeInModule( 1699 *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker, 1700 CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode, 1701 &CGOpts.CmdArgs); 1702 } 1703