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