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