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