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