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