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