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