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 1149 PassInstrumentationCallbacks PIC; 1150 StandardInstrumentations SI(CodeGenOpts.DebugPassManager); 1151 SI.registerCallbacks(PIC); 1152 PassBuilder PB(CodeGenOpts.DebugPassManager, TM.get(), PTO, PGOOpt, &PIC); 1153 1154 // Attempt to load pass plugins and register their callbacks with PB. 1155 for (auto &PluginFN : CodeGenOpts.PassPlugins) { 1156 auto PassPlugin = PassPlugin::Load(PluginFN); 1157 if (PassPlugin) { 1158 PassPlugin->registerPassBuilderCallbacks(PB); 1159 } else { 1160 Diags.Report(diag::err_fe_unable_to_load_plugin) 1161 << PluginFN << toString(PassPlugin.takeError()); 1162 } 1163 } 1164 #define HANDLE_EXTENSION(Ext) \ 1165 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB); 1166 #include "llvm/Support/Extension.def" 1167 1168 LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager); 1169 FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager); 1170 CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager); 1171 ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager); 1172 1173 // Register the AA manager first so that our version is the one used. 1174 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); }); 1175 1176 // Register the target library analysis directly and give it a customized 1177 // preset TLI. 1178 Triple TargetTriple(TheModule->getTargetTriple()); 1179 std::unique_ptr<TargetLibraryInfoImpl> TLII( 1180 createTLII(TargetTriple, CodeGenOpts)); 1181 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); }); 1182 1183 // Register all the basic analyses with the managers. 1184 PB.registerModuleAnalyses(MAM); 1185 PB.registerCGSCCAnalyses(CGAM); 1186 PB.registerFunctionAnalyses(FAM); 1187 PB.registerLoopAnalyses(LAM); 1188 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); 1189 1190 ModulePassManager MPM(CodeGenOpts.DebugPassManager); 1191 1192 if (!CodeGenOpts.DisableLLVMPasses) { 1193 // Map our optimization levels into one of the distinct levels used to 1194 // configure the pipeline. 1195 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts); 1196 1197 bool IsThinLTO = CodeGenOpts.PrepareForThinLTO; 1198 bool IsLTO = CodeGenOpts.PrepareForLTO; 1199 1200 // If we reached here with a non-empty index file name, then the index 1201 // file was empty and we are not performing ThinLTO backend compilation 1202 // (used in testing in a distributed build environment). Drop any the type 1203 // test assume sequences inserted for whole program vtables so that 1204 // codegen doesn't complain. 1205 if (!CodeGenOpts.ThinLTOIndexFile.empty()) 1206 PB.registerPipelineStartEPCallback( 1207 [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) { 1208 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr, 1209 /*ImportSummary=*/nullptr, 1210 /*DropTypeTests=*/true)); 1211 }); 1212 1213 if (Level != PassBuilder::OptimizationLevel::O0) { 1214 PB.registerPipelineStartEPCallback( 1215 [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) { 1216 MPM.addPass(createModuleToFunctionPassAdaptor( 1217 EntryExitInstrumenterPass(/*PostInlining=*/false))); 1218 }); 1219 } 1220 1221 // Register callbacks to schedule sanitizer passes at the appropriate part 1222 // of the pipeline. 1223 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) 1224 PB.registerScalarOptimizerLateEPCallback( 1225 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) { 1226 FPM.addPass(BoundsCheckingPass()); 1227 }); 1228 1229 if (CodeGenOpts.SanitizeCoverageType || 1230 CodeGenOpts.SanitizeCoverageIndirectCalls || 1231 CodeGenOpts.SanitizeCoverageTraceCmp) { 1232 PB.registerOptimizerLastEPCallback( 1233 [this](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) { 1234 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts); 1235 MPM.addPass(ModuleSanitizerCoveragePass( 1236 SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles, 1237 CodeGenOpts.SanitizeCoverageBlocklistFiles)); 1238 }); 1239 } 1240 1241 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { 1242 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins; 1243 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory); 1244 PB.registerOptimizerLastEPCallback( 1245 [TrackOrigins, Recover](ModulePassManager &MPM, 1246 PassBuilder::OptimizationLevel Level) { 1247 MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false})); 1248 MPM.addPass(createModuleToFunctionPassAdaptor( 1249 MemorySanitizerPass({TrackOrigins, Recover, false}))); 1250 }); 1251 } 1252 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 1253 PB.registerOptimizerLastEPCallback( 1254 [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) { 1255 MPM.addPass(ThreadSanitizerPass()); 1256 MPM.addPass( 1257 createModuleToFunctionPassAdaptor(ThreadSanitizerPass())); 1258 }); 1259 } 1260 1261 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) { 1262 if (LangOpts.Sanitize.has(Mask)) { 1263 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask); 1264 bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope; 1265 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts); 1266 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator; 1267 PB.registerOptimizerLastEPCallback( 1268 [CompileKernel, Recover, UseAfterScope, ModuleUseAfterScope, 1269 UseOdrIndicator](ModulePassManager &MPM, 1270 PassBuilder::OptimizationLevel Level) { 1271 MPM.addPass( 1272 RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>()); 1273 MPM.addPass(ModuleAddressSanitizerPass(CompileKernel, Recover, 1274 ModuleUseAfterScope, 1275 UseOdrIndicator)); 1276 MPM.addPass(createModuleToFunctionPassAdaptor( 1277 AddressSanitizerPass(CompileKernel, Recover, UseAfterScope))); 1278 }); 1279 } 1280 }; 1281 ASanPass(SanitizerKind::Address, false); 1282 ASanPass(SanitizerKind::KernelAddress, true); 1283 1284 auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) { 1285 if (LangOpts.Sanitize.has(Mask)) { 1286 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask); 1287 PB.registerOptimizerLastEPCallback( 1288 [CompileKernel, Recover](ModulePassManager &MPM, 1289 PassBuilder::OptimizationLevel Level) { 1290 MPM.addPass(HWAddressSanitizerPass(CompileKernel, Recover)); 1291 }); 1292 } 1293 }; 1294 HWASanPass(SanitizerKind::HWAddress, false); 1295 HWASanPass(SanitizerKind::KernelHWAddress, true); 1296 1297 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) { 1298 PB.registerOptimizerLastEPCallback( 1299 [this](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) { 1300 MPM.addPass( 1301 DataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles)); 1302 }); 1303 } 1304 1305 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts)) 1306 PB.registerPipelineStartEPCallback( 1307 [Options](ModulePassManager &MPM, 1308 PassBuilder::OptimizationLevel Level) { 1309 MPM.addPass(GCOVProfilerPass(*Options)); 1310 }); 1311 if (Optional<InstrProfOptions> Options = 1312 getInstrProfOptions(CodeGenOpts, LangOpts)) 1313 PB.registerPipelineStartEPCallback( 1314 [Options](ModulePassManager &MPM, 1315 PassBuilder::OptimizationLevel Level) { 1316 MPM.addPass(InstrProfiling(*Options, false)); 1317 }); 1318 1319 if (CodeGenOpts.OptimizationLevel == 0) { 1320 MPM = PB.buildO0DefaultPipeline(Level, IsLTO || IsThinLTO); 1321 } else if (IsThinLTO) { 1322 MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level); 1323 } else if (IsLTO) { 1324 MPM = PB.buildLTOPreLinkDefaultPipeline(Level); 1325 } else { 1326 MPM = PB.buildPerModuleDefaultPipeline(Level); 1327 } 1328 1329 // Add UniqueInternalLinkageNames Pass which renames internal linkage 1330 // symbols with unique names. 1331 if (CodeGenOpts.UniqueInternalLinkageNames) 1332 MPM.addPass(UniqueInternalLinkageNamesPass()); 1333 1334 if (!CodeGenOpts.MemoryProfileOutput.empty()) { 1335 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass())); 1336 MPM.addPass(ModuleMemProfilerPass()); 1337 } 1338 } 1339 1340 // FIXME: We still use the legacy pass manager to do code generation. We 1341 // create that pass manager here and use it as needed below. 1342 legacy::PassManager CodeGenPasses; 1343 bool NeedCodeGen = false; 1344 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS; 1345 1346 // Append any output we need to the pass manager. 1347 switch (Action) { 1348 case Backend_EmitNothing: 1349 break; 1350 1351 case Backend_EmitBC: 1352 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) { 1353 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) { 1354 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile); 1355 if (!ThinLinkOS) 1356 return; 1357 } 1358 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 1359 CodeGenOpts.EnableSplitLTOUnit); 1360 MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os() 1361 : nullptr)); 1362 } else { 1363 // Emit a module summary by default for Regular LTO except for ld64 1364 // targets 1365 bool EmitLTOSummary = 1366 (CodeGenOpts.PrepareForLTO && 1367 !CodeGenOpts.DisableLLVMPasses && 1368 llvm::Triple(TheModule->getTargetTriple()).getVendor() != 1369 llvm::Triple::Apple); 1370 if (EmitLTOSummary) { 1371 if (!TheModule->getModuleFlag("ThinLTO")) 1372 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0)); 1373 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 1374 uint32_t(1)); 1375 } 1376 MPM.addPass( 1377 BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary)); 1378 } 1379 break; 1380 1381 case Backend_EmitLL: 1382 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists)); 1383 break; 1384 1385 case Backend_EmitAssembly: 1386 case Backend_EmitMCNull: 1387 case Backend_EmitObj: 1388 NeedCodeGen = true; 1389 CodeGenPasses.add( 1390 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 1391 if (!CodeGenOpts.SplitDwarfOutput.empty()) { 1392 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput); 1393 if (!DwoOS) 1394 return; 1395 } 1396 if (!AddEmitPasses(CodeGenPasses, Action, *OS, 1397 DwoOS ? &DwoOS->os() : nullptr)) 1398 // FIXME: Should we handle this error differently? 1399 return; 1400 break; 1401 } 1402 1403 // Before executing passes, print the final values of the LLVM options. 1404 cl::PrintOptionValues(); 1405 1406 // Now that we have all of the passes ready, run them. 1407 { 1408 PrettyStackTraceString CrashInfo("Optimizer"); 1409 MPM.run(*TheModule, MAM); 1410 } 1411 1412 // Now if needed, run the legacy PM for codegen. 1413 if (NeedCodeGen) { 1414 PrettyStackTraceString CrashInfo("Code generation"); 1415 CodeGenPasses.run(*TheModule); 1416 } 1417 1418 if (ThinLinkOS) 1419 ThinLinkOS->keep(); 1420 if (DwoOS) 1421 DwoOS->keep(); 1422 } 1423 1424 static void runThinLTOBackend( 1425 DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M, 1426 const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts, 1427 const clang::TargetOptions &TOpts, const LangOptions &LOpts, 1428 std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile, 1429 std::string ProfileRemapping, BackendAction Action) { 1430 StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>> 1431 ModuleToDefinedGVSummaries; 1432 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 1433 1434 setCommandLineOpts(CGOpts); 1435 1436 // We can simply import the values mentioned in the combined index, since 1437 // we should only invoke this using the individual indexes written out 1438 // via a WriteIndexesThinBackend. 1439 FunctionImporter::ImportMapTy ImportList; 1440 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports; 1441 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap; 1442 if (!lto::loadReferencedModules(*M, *CombinedIndex, ImportList, ModuleMap, 1443 OwnedImports)) 1444 return; 1445 1446 auto AddStream = [&](size_t Task) { 1447 return std::make_unique<lto::NativeObjectStream>(std::move(OS)); 1448 }; 1449 lto::Config Conf; 1450 if (CGOpts.SaveTempsFilePrefix != "") { 1451 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".", 1452 /* UseInputModulePath */ false)) { 1453 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 1454 errs() << "Error setting up ThinLTO save-temps: " << EIB.message() 1455 << '\n'; 1456 }); 1457 } 1458 } 1459 Conf.CPU = TOpts.CPU; 1460 Conf.CodeModel = getCodeModel(CGOpts); 1461 Conf.MAttrs = TOpts.Features; 1462 Conf.RelocModel = CGOpts.RelocationModel; 1463 Conf.CGOptLevel = getCGOptLevel(CGOpts); 1464 Conf.OptLevel = CGOpts.OptimizationLevel; 1465 initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts); 1466 Conf.SampleProfile = std::move(SampleProfile); 1467 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops; 1468 // For historical reasons, loop interleaving is set to mirror setting for loop 1469 // unrolling. 1470 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops; 1471 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop; 1472 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP; 1473 // Only enable CGProfilePass when using integrated assembler, since 1474 // non-integrated assemblers don't recognize .cgprofile section. 1475 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS; 1476 1477 // Context sensitive profile. 1478 if (CGOpts.hasProfileCSIRInstr()) { 1479 Conf.RunCSIRInstr = true; 1480 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput); 1481 } else if (CGOpts.hasProfileCSIRUse()) { 1482 Conf.RunCSIRInstr = false; 1483 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath); 1484 } 1485 1486 Conf.ProfileRemapping = std::move(ProfileRemapping); 1487 Conf.UseNewPM = !CGOpts.LegacyPassManager; 1488 Conf.DebugPassManager = CGOpts.DebugPassManager; 1489 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness; 1490 Conf.RemarksFilename = CGOpts.OptRecordFile; 1491 Conf.RemarksPasses = CGOpts.OptRecordPasses; 1492 Conf.RemarksFormat = CGOpts.OptRecordFormat; 1493 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile; 1494 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput; 1495 switch (Action) { 1496 case Backend_EmitNothing: 1497 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) { 1498 return false; 1499 }; 1500 break; 1501 case Backend_EmitLL: 1502 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) { 1503 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists); 1504 return false; 1505 }; 1506 break; 1507 case Backend_EmitBC: 1508 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) { 1509 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists); 1510 return false; 1511 }; 1512 break; 1513 default: 1514 Conf.CGFileType = getCodeGenFileType(Action); 1515 break; 1516 } 1517 if (Error E = 1518 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList, 1519 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], 1520 ModuleMap, CGOpts.CmdArgs)) { 1521 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 1522 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n'; 1523 }); 1524 } 1525 } 1526 1527 void clang::EmitBackendOutput(DiagnosticsEngine &Diags, 1528 const HeaderSearchOptions &HeaderOpts, 1529 const CodeGenOptions &CGOpts, 1530 const clang::TargetOptions &TOpts, 1531 const LangOptions &LOpts, 1532 const llvm::DataLayout &TDesc, Module *M, 1533 BackendAction Action, 1534 std::unique_ptr<raw_pwrite_stream> OS) { 1535 1536 llvm::TimeTraceScope TimeScope("Backend"); 1537 1538 std::unique_ptr<llvm::Module> EmptyModule; 1539 if (!CGOpts.ThinLTOIndexFile.empty()) { 1540 // If we are performing a ThinLTO importing compile, load the function index 1541 // into memory and pass it into runThinLTOBackend, which will run the 1542 // function importer and invoke LTO passes. 1543 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr = 1544 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile, 1545 /*IgnoreEmptyThinLTOIndexFile*/true); 1546 if (!IndexOrErr) { 1547 logAllUnhandledErrors(IndexOrErr.takeError(), errs(), 1548 "Error loading index file '" + 1549 CGOpts.ThinLTOIndexFile + "': "); 1550 return; 1551 } 1552 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr); 1553 // A null CombinedIndex means we should skip ThinLTO compilation 1554 // (LLVM will optionally ignore empty index files, returning null instead 1555 // of an error). 1556 if (CombinedIndex) { 1557 if (!CombinedIndex->skipModuleByDistributedBackend()) { 1558 runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts, 1559 TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile, 1560 CGOpts.ProfileRemappingFile, Action); 1561 return; 1562 } 1563 // Distributed indexing detected that nothing from the module is needed 1564 // for the final linking. So we can skip the compilation. We sill need to 1565 // output an empty object file to make sure that a linker does not fail 1566 // trying to read it. Also for some features, like CFI, we must skip 1567 // the compilation as CombinedIndex does not contain all required 1568 // information. 1569 EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext()); 1570 EmptyModule->setTargetTriple(M->getTargetTriple()); 1571 M = EmptyModule.get(); 1572 } 1573 } 1574 1575 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M); 1576 1577 if (!CGOpts.LegacyPassManager) 1578 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS)); 1579 else 1580 AsmHelper.EmitAssembly(Action, std::move(OS)); 1581 1582 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's 1583 // DataLayout. 1584 if (AsmHelper.TM) { 1585 std::string DLDesc = M->getDataLayout().getStringRepresentation(); 1586 if (DLDesc != TDesc.getStringRepresentation()) { 1587 unsigned DiagID = Diags.getCustomDiagID( 1588 DiagnosticsEngine::Error, "backend data layout '%0' does not match " 1589 "expected target description '%1'"); 1590 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation(); 1591 } 1592 } 1593 } 1594 1595 // With -fembed-bitcode, save a copy of the llvm IR as data in the 1596 // __LLVM,__bitcode section. 1597 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, 1598 llvm::MemoryBufferRef Buf) { 1599 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off) 1600 return; 1601 llvm::EmbedBitcodeInModule( 1602 *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker, 1603 CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode, 1604 CGOpts.CmdArgs); 1605 } 1606