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