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