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