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 "BackendConsumer.h" 11 #include "LinkInModulesPass.h" 12 #include "clang/Basic/CodeGenOptions.h" 13 #include "clang/Basic/Diagnostic.h" 14 #include "clang/Basic/LangOptions.h" 15 #include "clang/Basic/TargetOptions.h" 16 #include "clang/Frontend/FrontendDiagnostic.h" 17 #include "clang/Frontend/Utils.h" 18 #include "clang/Lex/HeaderSearchOptions.h" 19 #include "llvm/ADT/StringExtras.h" 20 #include "llvm/ADT/StringSwitch.h" 21 #include "llvm/Analysis/GlobalsModRef.h" 22 #include "llvm/Analysis/TargetLibraryInfo.h" 23 #include "llvm/Analysis/TargetTransformInfo.h" 24 #include "llvm/Bitcode/BitcodeReader.h" 25 #include "llvm/Bitcode/BitcodeWriter.h" 26 #include "llvm/Bitcode/BitcodeWriterPass.h" 27 #include "llvm/CodeGen/TargetSubtargetInfo.h" 28 #include "llvm/Frontend/Driver/CodeGenOptions.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/IR/DebugInfo.h" 31 #include "llvm/IR/LegacyPassManager.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/IR/ModuleSummaryIndex.h" 34 #include "llvm/IR/PassManager.h" 35 #include "llvm/IR/Verifier.h" 36 #include "llvm/IRPrinter/IRPrintingPasses.h" 37 #include "llvm/LTO/LTOBackend.h" 38 #include "llvm/MC/TargetRegistry.h" 39 #include "llvm/Object/OffloadBinary.h" 40 #include "llvm/Passes/PassBuilder.h" 41 #include "llvm/Passes/PassPlugin.h" 42 #include "llvm/Passes/StandardInstrumentations.h" 43 #include "llvm/ProfileData/InstrProfCorrelator.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/Program.h" 49 #include "llvm/Support/TimeProfiler.h" 50 #include "llvm/Support/Timer.h" 51 #include "llvm/Support/ToolOutputFile.h" 52 #include "llvm/Support/VirtualFileSystem.h" 53 #include "llvm/Support/raw_ostream.h" 54 #include "llvm/Target/TargetMachine.h" 55 #include "llvm/Target/TargetOptions.h" 56 #include "llvm/TargetParser/SubtargetFeature.h" 57 #include "llvm/TargetParser/Triple.h" 58 #include "llvm/Transforms/HipStdPar/HipStdPar.h" 59 #include "llvm/Transforms/IPO/EmbedBitcodePass.h" 60 #include "llvm/Transforms/IPO/LowerTypeTests.h" 61 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h" 62 #include "llvm/Transforms/InstCombine/InstCombine.h" 63 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h" 64 #include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h" 65 #include "llvm/Transforms/Instrumentation/BoundsChecking.h" 66 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h" 67 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h" 68 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h" 69 #include "llvm/Transforms/Instrumentation/InstrProfiling.h" 70 #include "llvm/Transforms/Instrumentation/KCFI.h" 71 #include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h" 72 #include "llvm/Transforms/Instrumentation/MemProfiler.h" 73 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h" 74 #include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h" 75 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h" 76 #include "llvm/Transforms/Instrumentation/RealtimeSanitizer.h" 77 #include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h" 78 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h" 79 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h" 80 #include "llvm/Transforms/Instrumentation/TypeSanitizer.h" 81 #include "llvm/Transforms/ObjCARC.h" 82 #include "llvm/Transforms/Scalar/EarlyCSE.h" 83 #include "llvm/Transforms/Scalar/GVN.h" 84 #include "llvm/Transforms/Scalar/JumpThreading.h" 85 #include "llvm/Transforms/Utils/Debugify.h" 86 #include "llvm/Transforms/Utils/ModuleUtils.h" 87 #include <memory> 88 #include <optional> 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 llvm { 97 extern cl::opt<bool> PrintPipelinePasses; 98 99 // Experiment to move sanitizers earlier. 100 static cl::opt<bool> ClSanitizeOnOptimizerEarlyEP( 101 "sanitizer-early-opt-ep", cl::Optional, 102 cl::desc("Insert sanitizers on OptimizerEarlyEP.")); 103 104 // Experiment to mark cold functions as optsize/minsize/optnone. 105 // TODO: remove once this is exposed as a proper driver flag. 106 static cl::opt<PGOOptions::ColdFuncOpt> ClPGOColdFuncAttr( 107 "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden, 108 cl::desc( 109 "Function attribute to apply to cold functions as determined by PGO"), 110 cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default, "default", 111 "Default (no attribute)"), 112 clEnumValN(PGOOptions::ColdFuncOpt::OptSize, "optsize", 113 "Mark cold functions with optsize."), 114 clEnumValN(PGOOptions::ColdFuncOpt::MinSize, "minsize", 115 "Mark cold functions with minsize."), 116 clEnumValN(PGOOptions::ColdFuncOpt::OptNone, "optnone", 117 "Mark cold functions with optnone."))); 118 119 extern cl::opt<InstrProfCorrelator::ProfCorrelatorKind> ProfileCorrelate; 120 } // namespace llvm 121 122 namespace { 123 124 // Default filename used for profile generation. 125 std::string getDefaultProfileGenName() { 126 return DebugInfoCorrelate || ProfileCorrelate != InstrProfCorrelator::NONE 127 ? "default_%m.proflite" 128 : "default_%m.profraw"; 129 } 130 131 class EmitAssemblyHelper { 132 DiagnosticsEngine &Diags; 133 const HeaderSearchOptions &HSOpts; 134 const CodeGenOptions &CodeGenOpts; 135 const clang::TargetOptions &TargetOpts; 136 const LangOptions &LangOpts; 137 llvm::Module *TheModule; 138 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS; 139 140 Timer CodeGenerationTime; 141 142 std::unique_ptr<raw_pwrite_stream> OS; 143 144 Triple TargetTriple; 145 146 TargetIRAnalysis getTargetIRAnalysis() const { 147 if (TM) 148 return TM->getTargetIRAnalysis(); 149 150 return TargetIRAnalysis(); 151 } 152 153 /// Generates the TargetMachine. 154 /// Leaves TM unchanged if it is unable to create the target machine. 155 /// Some of our clang tests specify triples which are not built 156 /// into clang. This is okay because these tests check the generated 157 /// IR, and they require DataLayout which depends on the triple. 158 /// In this case, we allow this method to fail and not report an error. 159 /// When MustCreateTM is used, we print an error if we are unable to load 160 /// the requested target. 161 void CreateTargetMachine(bool MustCreateTM); 162 163 /// Add passes necessary to emit assembly or LLVM IR. 164 /// 165 /// \return True on success. 166 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action, 167 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS); 168 169 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) { 170 std::error_code EC; 171 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC, 172 llvm::sys::fs::OF_None); 173 if (EC) { 174 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message(); 175 F.reset(); 176 } 177 return F; 178 } 179 180 void RunOptimizationPipeline( 181 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS, 182 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC); 183 void RunCodegenPipeline(BackendAction Action, 184 std::unique_ptr<raw_pwrite_stream> &OS, 185 std::unique_ptr<llvm::ToolOutputFile> &DwoOS); 186 187 /// Check whether we should emit a module summary for regular LTO. 188 /// The module summary should be emitted by default for regular LTO 189 /// except for ld64 targets. 190 /// 191 /// \return True if the module summary should be emitted. 192 bool shouldEmitRegularLTOSummary() const { 193 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses && 194 TargetTriple.getVendor() != llvm::Triple::Apple; 195 } 196 197 /// Check whether we should emit a flag for UnifiedLTO. 198 /// The UnifiedLTO module flag should be set when UnifiedLTO is enabled for 199 /// ThinLTO or Full LTO with module summaries. 200 bool shouldEmitUnifiedLTOModueFlag() const { 201 return CodeGenOpts.UnifiedLTO && 202 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary()); 203 } 204 205 public: 206 EmitAssemblyHelper(DiagnosticsEngine &_Diags, 207 const HeaderSearchOptions &HeaderSearchOpts, 208 const CodeGenOptions &CGOpts, 209 const clang::TargetOptions &TOpts, 210 const LangOptions &LOpts, llvm::Module *M, 211 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) 212 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts), 213 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M), VFS(std::move(VFS)), 214 CodeGenerationTime("codegen", "Code Generation Time"), 215 TargetTriple(TheModule->getTargetTriple()) {} 216 217 ~EmitAssemblyHelper() { 218 if (CodeGenOpts.DisableFree) 219 BuryPointer(std::move(TM)); 220 } 221 222 std::unique_ptr<TargetMachine> TM; 223 224 // Emit output using the new pass manager for the optimization pipeline. 225 void EmitAssembly(BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS, 226 BackendConsumer *BC); 227 }; 228 } // namespace 229 230 static SanitizerCoverageOptions 231 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) { 232 SanitizerCoverageOptions Opts; 233 Opts.CoverageType = 234 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType); 235 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls; 236 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB; 237 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp; 238 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv; 239 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep; 240 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters; 241 Opts.TracePC = CGOpts.SanitizeCoverageTracePC; 242 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard; 243 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune; 244 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters; 245 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag; 246 Opts.PCTable = CGOpts.SanitizeCoveragePCTable; 247 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth; 248 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads; 249 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores; 250 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow; 251 return Opts; 252 } 253 254 static SanitizerBinaryMetadataOptions 255 getSanitizerBinaryMetadataOptions(const CodeGenOptions &CGOpts) { 256 SanitizerBinaryMetadataOptions Opts; 257 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered; 258 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics; 259 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR; 260 return Opts; 261 } 262 263 // Check if ASan should use GC-friendly instrumentation for globals. 264 // First of all, there is no point if -fdata-sections is off (expect for MachO, 265 // where this is not a factor). Also, on ELF this feature requires an assembler 266 // extension that only works with -integrated-as at the moment. 267 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) { 268 if (!CGOpts.SanitizeAddressGlobalsDeadStripping) 269 return false; 270 switch (T.getObjectFormat()) { 271 case Triple::MachO: 272 case Triple::COFF: 273 return true; 274 case Triple::ELF: 275 return !CGOpts.DisableIntegratedAS; 276 case Triple::GOFF: 277 llvm::report_fatal_error("ASan not implemented for GOFF"); 278 case Triple::XCOFF: 279 llvm::report_fatal_error("ASan not implemented for XCOFF."); 280 case Triple::Wasm: 281 case Triple::DXContainer: 282 case Triple::SPIRV: 283 case Triple::UnknownObjectFormat: 284 break; 285 } 286 return false; 287 } 288 289 static std::optional<llvm::CodeModel::Model> 290 getCodeModel(const CodeGenOptions &CodeGenOpts) { 291 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel) 292 .Case("tiny", llvm::CodeModel::Tiny) 293 .Case("small", llvm::CodeModel::Small) 294 .Case("kernel", llvm::CodeModel::Kernel) 295 .Case("medium", llvm::CodeModel::Medium) 296 .Case("large", llvm::CodeModel::Large) 297 .Case("default", ~1u) 298 .Default(~0u); 299 assert(CodeModel != ~0u && "invalid code model!"); 300 if (CodeModel == ~1u) 301 return std::nullopt; 302 return static_cast<llvm::CodeModel::Model>(CodeModel); 303 } 304 305 static CodeGenFileType getCodeGenFileType(BackendAction Action) { 306 if (Action == Backend_EmitObj) 307 return CodeGenFileType::ObjectFile; 308 else if (Action == Backend_EmitMCNull) 309 return CodeGenFileType::Null; 310 else { 311 assert(Action == Backend_EmitAssembly && "Invalid action!"); 312 return CodeGenFileType::AssemblyFile; 313 } 314 } 315 316 static bool actionRequiresCodeGen(BackendAction Action) { 317 return Action != Backend_EmitNothing && Action != Backend_EmitBC && 318 Action != Backend_EmitLL; 319 } 320 321 static std::string flattenClangCommandLine(ArrayRef<std::string> Args, 322 StringRef MainFilename) { 323 if (Args.empty()) 324 return std::string{}; 325 326 std::string FlatCmdLine; 327 raw_string_ostream OS(FlatCmdLine); 328 bool PrintedOneArg = false; 329 if (!StringRef(Args[0]).contains("-cc1")) { 330 llvm::sys::printArg(OS, "-cc1", /*Quote=*/true); 331 PrintedOneArg = true; 332 } 333 for (unsigned i = 0; i < Args.size(); i++) { 334 StringRef Arg = Args[i]; 335 if (Arg.empty()) 336 continue; 337 if (Arg == "-main-file-name" || Arg == "-o") { 338 i++; // Skip this argument and next one. 339 continue; 340 } 341 if (Arg.starts_with("-object-file-name") || Arg == MainFilename) 342 continue; 343 // Skip fmessage-length for reproducibility. 344 if (Arg.starts_with("-fmessage-length")) 345 continue; 346 if (PrintedOneArg) 347 OS << " "; 348 llvm::sys::printArg(OS, Arg, /*Quote=*/true); 349 PrintedOneArg = true; 350 } 351 return FlatCmdLine; 352 } 353 354 static bool initTargetOptions(DiagnosticsEngine &Diags, 355 llvm::TargetOptions &Options, 356 const CodeGenOptions &CodeGenOpts, 357 const clang::TargetOptions &TargetOpts, 358 const LangOptions &LangOpts, 359 const HeaderSearchOptions &HSOpts) { 360 switch (LangOpts.getThreadModel()) { 361 case LangOptions::ThreadModelKind::POSIX: 362 Options.ThreadModel = llvm::ThreadModel::POSIX; 363 break; 364 case LangOptions::ThreadModelKind::Single: 365 Options.ThreadModel = llvm::ThreadModel::Single; 366 break; 367 } 368 369 // Set float ABI type. 370 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" || 371 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) && 372 "Invalid Floating Point ABI!"); 373 Options.FloatABIType = 374 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI) 375 .Case("soft", llvm::FloatABI::Soft) 376 .Case("softfp", llvm::FloatABI::Soft) 377 .Case("hard", llvm::FloatABI::Hard) 378 .Default(llvm::FloatABI::Default); 379 380 // Set FP fusion mode. 381 switch (LangOpts.getDefaultFPContractMode()) { 382 case LangOptions::FPM_Off: 383 // Preserve any contraction performed by the front-end. (Strict performs 384 // splitting of the muladd intrinsic in the backend.) 385 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 386 break; 387 case LangOptions::FPM_On: 388 case LangOptions::FPM_FastHonorPragmas: 389 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 390 break; 391 case LangOptions::FPM_Fast: 392 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast; 393 break; 394 } 395 396 Options.BinutilsVersion = 397 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion); 398 Options.UseInitArray = CodeGenOpts.UseInitArray; 399 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS; 400 401 // Set EABI version. 402 Options.EABIVersion = TargetOpts.EABIVersion; 403 404 if (LangOpts.hasSjLjExceptions()) 405 Options.ExceptionModel = llvm::ExceptionHandling::SjLj; 406 if (LangOpts.hasSEHExceptions()) 407 Options.ExceptionModel = llvm::ExceptionHandling::WinEH; 408 if (LangOpts.hasDWARFExceptions()) 409 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI; 410 if (LangOpts.hasWasmExceptions()) 411 Options.ExceptionModel = llvm::ExceptionHandling::Wasm; 412 413 Options.NoInfsFPMath = LangOpts.NoHonorInfs; 414 Options.NoNaNsFPMath = LangOpts.NoHonorNaNs; 415 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS; 416 Options.UnsafeFPMath = LangOpts.AllowFPReassoc && LangOpts.AllowRecip && 417 LangOpts.NoSignedZero && LangOpts.ApproxFunc && 418 (LangOpts.getDefaultFPContractMode() == 419 LangOptions::FPModeKind::FPM_Fast || 420 LangOpts.getDefaultFPContractMode() == 421 LangOptions::FPModeKind::FPM_FastHonorPragmas); 422 Options.ApproxFuncFPMath = LangOpts.ApproxFunc; 423 424 Options.BBAddrMap = CodeGenOpts.BBAddrMap; 425 Options.BBSections = 426 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections) 427 .Case("all", llvm::BasicBlockSection::All) 428 .StartsWith("list=", llvm::BasicBlockSection::List) 429 .Case("none", llvm::BasicBlockSection::None) 430 .Default(llvm::BasicBlockSection::None); 431 432 if (Options.BBSections == llvm::BasicBlockSection::List) { 433 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = 434 MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5)); 435 if (!MBOrErr) { 436 Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file) 437 << MBOrErr.getError().message(); 438 return false; 439 } 440 Options.BBSectionsFuncListBuf = std::move(*MBOrErr); 441 } 442 443 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions; 444 Options.FunctionSections = CodeGenOpts.FunctionSections; 445 Options.DataSections = CodeGenOpts.DataSections; 446 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility; 447 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames; 448 Options.UniqueBasicBlockSectionNames = 449 CodeGenOpts.UniqueBasicBlockSectionNames; 450 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections; 451 Options.TLSSize = CodeGenOpts.TLSSize; 452 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC; 453 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS; 454 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning(); 455 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection; 456 Options.StackUsageOutput = CodeGenOpts.StackUsageOutput; 457 Options.EmitAddrsig = CodeGenOpts.Addrsig; 458 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection; 459 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo; 460 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI; 461 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex; 462 Options.LoopAlignment = CodeGenOpts.LoopAlignment; 463 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf; 464 Options.ObjectFilenameForDebug = CodeGenOpts.ObjectFilenameForDebug; 465 Options.Hotpatch = CodeGenOpts.HotPatch; 466 Options.JMCInstrument = CodeGenOpts.JMCInstrument; 467 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers; 468 469 switch (CodeGenOpts.getSwiftAsyncFramePointer()) { 470 case CodeGenOptions::SwiftAsyncFramePointerKind::Auto: 471 Options.SwiftAsyncFramePointer = 472 SwiftAsyncFramePointerMode::DeploymentBased; 473 break; 474 475 case CodeGenOptions::SwiftAsyncFramePointerKind::Always: 476 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always; 477 break; 478 479 case CodeGenOptions::SwiftAsyncFramePointerKind::Never: 480 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never; 481 break; 482 } 483 484 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile; 485 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind(); 486 Options.MCOptions.EmitCompactUnwindNonCanonical = 487 CodeGenOpts.EmitCompactUnwindNonCanonical; 488 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll; 489 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels; 490 Options.MCOptions.MCUseDwarfDirectory = 491 CodeGenOpts.NoDwarfDirectoryAsm 492 ? llvm::MCTargetOptions::DisableDwarfDirectory 493 : llvm::MCTargetOptions::EnableDwarfDirectory; 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.Dwarf64 = CodeGenOpts.Dwarf64; 501 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments; 502 Options.MCOptions.Crel = CodeGenOpts.Crel; 503 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms; 504 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations; 505 Options.MCOptions.CompressDebugSections = 506 CodeGenOpts.getCompressDebugSections(); 507 if (CodeGenOpts.OutputAsmVariant != 3) // 3 (default): not specified 508 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant; 509 Options.MCOptions.ABIName = TargetOpts.ABI; 510 for (const auto &Entry : HSOpts.UserEntries) 511 if (!Entry.IsFramework && 512 (Entry.Group == frontend::IncludeDirGroup::Quoted || 513 Entry.Group == frontend::IncludeDirGroup::Angled || 514 Entry.Group == frontend::IncludeDirGroup::System)) 515 Options.MCOptions.IASSearchPaths.push_back( 516 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path); 517 Options.MCOptions.Argv0 = CodeGenOpts.Argv0 ? CodeGenOpts.Argv0 : ""; 518 Options.MCOptions.CommandlineArgs = flattenClangCommandLine( 519 CodeGenOpts.CommandLineArgs, CodeGenOpts.MainFileName); 520 Options.MCOptions.AsSecureLogFile = CodeGenOpts.AsSecureLogFile; 521 Options.MCOptions.PPCUseFullRegisterNames = 522 CodeGenOpts.PPCUseFullRegisterNames; 523 Options.MisExpect = CodeGenOpts.MisExpect; 524 525 return true; 526 } 527 528 static std::optional<GCOVOptions> 529 getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts) { 530 if (CodeGenOpts.CoverageNotesFile.empty() && 531 CodeGenOpts.CoverageDataFile.empty()) 532 return std::nullopt; 533 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if 534 // LLVM's -default-gcov-version flag is set to something invalid. 535 GCOVOptions Options; 536 Options.EmitNotes = !CodeGenOpts.CoverageNotesFile.empty(); 537 Options.EmitData = !CodeGenOpts.CoverageDataFile.empty(); 538 llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version)); 539 Options.NoRedZone = CodeGenOpts.DisableRedZone; 540 Options.Filter = CodeGenOpts.ProfileFilterFiles; 541 Options.Exclude = CodeGenOpts.ProfileExcludeFiles; 542 Options.Atomic = CodeGenOpts.AtomicProfileUpdate; 543 return Options; 544 } 545 546 static std::optional<InstrProfOptions> 547 getInstrProfOptions(const CodeGenOptions &CodeGenOpts, 548 const LangOptions &LangOpts) { 549 if (!CodeGenOpts.hasProfileClangInstr()) 550 return std::nullopt; 551 InstrProfOptions Options; 552 Options.NoRedZone = CodeGenOpts.DisableRedZone; 553 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput; 554 Options.Atomic = CodeGenOpts.AtomicProfileUpdate; 555 return Options; 556 } 557 558 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) { 559 SmallVector<const char *, 16> BackendArgs; 560 BackendArgs.push_back("clang"); // Fake program name. 561 if (!CodeGenOpts.DebugPass.empty()) { 562 BackendArgs.push_back("-debug-pass"); 563 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str()); 564 } 565 if (!CodeGenOpts.LimitFloatPrecision.empty()) { 566 BackendArgs.push_back("-limit-float-precision"); 567 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str()); 568 } 569 // Check for the default "clang" invocation that won't set any cl::opt values. 570 // Skip trying to parse the command line invocation to avoid the issues 571 // described below. 572 if (BackendArgs.size() == 1) 573 return; 574 BackendArgs.push_back(nullptr); 575 // FIXME: The command line parser below is not thread-safe and shares a global 576 // state, so this call might crash or overwrite the options of another Clang 577 // instance in the same process. 578 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, 579 BackendArgs.data()); 580 } 581 582 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) { 583 // Create the TargetMachine for generating code. 584 std::string Error; 585 std::string Triple = TheModule->getTargetTriple(); 586 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error); 587 if (!TheTarget) { 588 if (MustCreateTM) 589 Diags.Report(diag::err_fe_unable_to_create_target) << Error; 590 return; 591 } 592 593 std::optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts); 594 std::string FeaturesStr = 595 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ","); 596 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel; 597 std::optional<CodeGenOptLevel> OptLevelOrNone = 598 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel); 599 assert(OptLevelOrNone && "Invalid optimization level!"); 600 CodeGenOptLevel OptLevel = *OptLevelOrNone; 601 602 llvm::TargetOptions Options; 603 if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts, 604 HSOpts)) 605 return; 606 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr, 607 Options, RM, CM, OptLevel)); 608 TM->setLargeDataThreshold(CodeGenOpts.LargeDataThreshold); 609 } 610 611 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses, 612 BackendAction Action, 613 raw_pwrite_stream &OS, 614 raw_pwrite_stream *DwoOS) { 615 // Add LibraryInfo. 616 std::unique_ptr<TargetLibraryInfoImpl> TLII( 617 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib())); 618 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII)); 619 620 // Normal mode, emit a .s or .o file by running the code generator. Note, 621 // this also adds codegenerator level optimization passes. 622 CodeGenFileType CGFT = getCodeGenFileType(Action); 623 624 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT, 625 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) { 626 Diags.Report(diag::err_fe_unable_to_interface_with_target); 627 return false; 628 } 629 630 return true; 631 } 632 633 static OptimizationLevel mapToLevel(const CodeGenOptions &Opts) { 634 switch (Opts.OptimizationLevel) { 635 default: 636 llvm_unreachable("Invalid optimization level!"); 637 638 case 0: 639 return OptimizationLevel::O0; 640 641 case 1: 642 return OptimizationLevel::O1; 643 644 case 2: 645 switch (Opts.OptimizeSize) { 646 default: 647 llvm_unreachable("Invalid optimization level for size!"); 648 649 case 0: 650 return OptimizationLevel::O2; 651 652 case 1: 653 return OptimizationLevel::Os; 654 655 case 2: 656 return OptimizationLevel::Oz; 657 } 658 659 case 3: 660 return OptimizationLevel::O3; 661 } 662 } 663 664 static void addKCFIPass(const Triple &TargetTriple, const LangOptions &LangOpts, 665 PassBuilder &PB) { 666 // If the back-end supports KCFI operand bundle lowering, skip KCFIPass. 667 if (TargetTriple.getArch() == llvm::Triple::x86_64 || 668 TargetTriple.isAArch64(64) || TargetTriple.isRISCV()) 669 return; 670 671 // Ensure we lower KCFI operand bundles with -O0. 672 PB.registerOptimizerLastEPCallback( 673 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) { 674 if (Level == OptimizationLevel::O0 && 675 LangOpts.Sanitize.has(SanitizerKind::KCFI)) 676 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass())); 677 }); 678 679 // When optimizations are requested, run KCIFPass after InstCombine to 680 // avoid unnecessary checks. 681 PB.registerPeepholeEPCallback( 682 [&](FunctionPassManager &FPM, OptimizationLevel Level) { 683 if (Level != OptimizationLevel::O0 && 684 LangOpts.Sanitize.has(SanitizerKind::KCFI)) 685 FPM.addPass(KCFIPass()); 686 }); 687 } 688 689 static void addSanitizers(const Triple &TargetTriple, 690 const CodeGenOptions &CodeGenOpts, 691 const LangOptions &LangOpts, PassBuilder &PB) { 692 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level, 693 ThinOrFullLTOPhase) { 694 if (CodeGenOpts.hasSanitizeCoverage()) { 695 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts); 696 MPM.addPass(SanitizerCoveragePass( 697 SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles, 698 CodeGenOpts.SanitizeCoverageIgnorelistFiles)); 699 } 700 701 if (CodeGenOpts.hasSanitizeBinaryMetadata()) { 702 MPM.addPass(SanitizerBinaryMetadataPass( 703 getSanitizerBinaryMetadataOptions(CodeGenOpts), 704 CodeGenOpts.SanitizeMetadataIgnorelistFiles)); 705 } 706 707 auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) { 708 if (LangOpts.Sanitize.has(Mask)) { 709 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins; 710 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask); 711 712 MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel, 713 CodeGenOpts.SanitizeMemoryParamRetval); 714 MPM.addPass(MemorySanitizerPass(options)); 715 if (Level != OptimizationLevel::O0) { 716 // MemorySanitizer inserts complex instrumentation that mostly follows 717 // the logic of the original code, but operates on "shadow" values. It 718 // can benefit from re-running some general purpose optimization 719 // passes. 720 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>()); 721 FunctionPassManager FPM; 722 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */)); 723 FPM.addPass(InstCombinePass()); 724 FPM.addPass(JumpThreadingPass()); 725 FPM.addPass(GVNPass()); 726 FPM.addPass(InstCombinePass()); 727 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 728 } 729 } 730 }; 731 MSanPass(SanitizerKind::Memory, false); 732 MSanPass(SanitizerKind::KernelMemory, true); 733 734 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 735 MPM.addPass(ModuleThreadSanitizerPass()); 736 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass())); 737 } 738 739 if (LangOpts.Sanitize.has(SanitizerKind::Type)) 740 MPM.addPass(TypeSanitizerPass()); 741 742 if (LangOpts.Sanitize.has(SanitizerKind::NumericalStability)) 743 MPM.addPass(NumericalStabilitySanitizerPass()); 744 745 if (LangOpts.Sanitize.has(SanitizerKind::Realtime)) 746 MPM.addPass(RealtimeSanitizerPass()); 747 748 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) { 749 if (LangOpts.Sanitize.has(Mask)) { 750 bool UseGlobalGC = asanUseGlobalsGC(TargetTriple, CodeGenOpts); 751 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator; 752 llvm::AsanDtorKind DestructorKind = 753 CodeGenOpts.getSanitizeAddressDtor(); 754 AddressSanitizerOptions Opts; 755 Opts.CompileKernel = CompileKernel; 756 Opts.Recover = CodeGenOpts.SanitizeRecover.has(Mask); 757 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope; 758 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn(); 759 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator, 760 DestructorKind)); 761 } 762 }; 763 ASanPass(SanitizerKind::Address, false); 764 ASanPass(SanitizerKind::KernelAddress, true); 765 766 auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) { 767 if (LangOpts.Sanitize.has(Mask)) { 768 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask); 769 MPM.addPass(HWAddressSanitizerPass( 770 {CompileKernel, Recover, 771 /*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0})); 772 } 773 }; 774 HWASanPass(SanitizerKind::HWAddress, false); 775 HWASanPass(SanitizerKind::KernelHWAddress, true); 776 777 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) { 778 MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles)); 779 } 780 }; 781 if (ClSanitizeOnOptimizerEarlyEP) { 782 PB.registerOptimizerEarlyEPCallback( 783 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level, 784 ThinOrFullLTOPhase Phase) { 785 ModulePassManager NewMPM; 786 SanitizersCallback(NewMPM, Level, Phase); 787 if (!NewMPM.isEmpty()) { 788 // Sanitizers can abandon<GlobalsAA>. 789 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>()); 790 MPM.addPass(std::move(NewMPM)); 791 } 792 }); 793 } else { 794 // LastEP does not need GlobalsAA. 795 PB.registerOptimizerLastEPCallback(SanitizersCallback); 796 } 797 798 if (LowerAllowCheckPass::IsRequested()) { 799 // We want to call it after inline, which is about OptimizerEarlyEPCallback. 800 PB.registerOptimizerEarlyEPCallback([](ModulePassManager &MPM, 801 OptimizationLevel Level, 802 ThinOrFullLTOPhase Phase) { 803 MPM.addPass(createModuleToFunctionPassAdaptor(LowerAllowCheckPass())); 804 }); 805 } 806 } 807 808 void EmitAssemblyHelper::RunOptimizationPipeline( 809 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS, 810 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) { 811 std::optional<PGOOptions> PGOOpt; 812 813 if (CodeGenOpts.hasProfileIRInstr()) 814 // -fprofile-generate. 815 PGOOpt = PGOOptions( 816 CodeGenOpts.InstrProfileOutput.empty() ? getDefaultProfileGenName() 817 : CodeGenOpts.InstrProfileOutput, 818 "", "", CodeGenOpts.MemoryProfileUsePath, nullptr, PGOOptions::IRInstr, 819 PGOOptions::NoCSAction, ClPGOColdFuncAttr, 820 CodeGenOpts.DebugInfoForProfiling, 821 /*PseudoProbeForProfiling=*/false, CodeGenOpts.AtomicProfileUpdate); 822 else if (CodeGenOpts.hasProfileIRUse()) { 823 // -fprofile-use. 824 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse 825 : PGOOptions::NoCSAction; 826 PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "", 827 CodeGenOpts.ProfileRemappingFile, 828 CodeGenOpts.MemoryProfileUsePath, VFS, 829 PGOOptions::IRUse, CSAction, ClPGOColdFuncAttr, 830 CodeGenOpts.DebugInfoForProfiling); 831 } else if (!CodeGenOpts.SampleProfileFile.empty()) 832 // -fprofile-sample-use 833 PGOOpt = PGOOptions( 834 CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile, 835 CodeGenOpts.MemoryProfileUsePath, VFS, PGOOptions::SampleUse, 836 PGOOptions::NoCSAction, ClPGOColdFuncAttr, 837 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling); 838 else if (!CodeGenOpts.MemoryProfileUsePath.empty()) 839 // -fmemory-profile-use (without any of the above options) 840 PGOOpt = PGOOptions("", "", "", CodeGenOpts.MemoryProfileUsePath, VFS, 841 PGOOptions::NoAction, PGOOptions::NoCSAction, 842 ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling); 843 else if (CodeGenOpts.PseudoProbeForProfiling) 844 // -fpseudo-probe-for-profiling 845 PGOOpt = 846 PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr, 847 PGOOptions::NoAction, PGOOptions::NoCSAction, 848 ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling, true); 849 else if (CodeGenOpts.DebugInfoForProfiling) 850 // -fdebug-info-for-profiling 851 PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr, 852 PGOOptions::NoAction, PGOOptions::NoCSAction, 853 ClPGOColdFuncAttr, true); 854 855 // Check to see if we want to generate a CS profile. 856 if (CodeGenOpts.hasProfileCSIRInstr()) { 857 assert(!CodeGenOpts.hasProfileCSIRUse() && 858 "Cannot have both CSProfileUse pass and CSProfileGen pass at " 859 "the same time"); 860 if (PGOOpt) { 861 assert(PGOOpt->Action != PGOOptions::IRInstr && 862 PGOOpt->Action != PGOOptions::SampleUse && 863 "Cannot run CSProfileGen pass with ProfileGen or SampleUse " 864 " pass"); 865 PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty() 866 ? getDefaultProfileGenName() 867 : CodeGenOpts.InstrProfileOutput; 868 PGOOpt->CSAction = PGOOptions::CSIRInstr; 869 } else 870 PGOOpt = PGOOptions("", 871 CodeGenOpts.InstrProfileOutput.empty() 872 ? getDefaultProfileGenName() 873 : CodeGenOpts.InstrProfileOutput, 874 "", /*MemoryProfile=*/"", nullptr, 875 PGOOptions::NoAction, PGOOptions::CSIRInstr, 876 ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling); 877 } 878 if (TM) 879 TM->setPGOOption(PGOOpt); 880 881 PipelineTuningOptions PTO; 882 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops; 883 // For historical reasons, loop interleaving is set to mirror setting for loop 884 // unrolling. 885 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops; 886 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop; 887 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP; 888 PTO.MergeFunctions = CodeGenOpts.MergeFunctions; 889 // Only enable CGProfilePass when using integrated assembler, since 890 // non-integrated assemblers don't recognize .cgprofile section. 891 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS; 892 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO; 893 894 LoopAnalysisManager LAM; 895 FunctionAnalysisManager FAM; 896 CGSCCAnalysisManager CGAM; 897 ModuleAnalysisManager MAM; 898 899 bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure"; 900 PassInstrumentationCallbacks PIC; 901 PrintPassOptions PrintPassOpts; 902 PrintPassOpts.Indent = DebugPassStructure; 903 PrintPassOpts.SkipAnalyses = DebugPassStructure; 904 StandardInstrumentations SI( 905 TheModule->getContext(), 906 (CodeGenOpts.DebugPassManager || DebugPassStructure), 907 CodeGenOpts.VerifyEach, PrintPassOpts); 908 SI.registerCallbacks(PIC, &MAM); 909 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC); 910 911 // Handle the assignment tracking feature options. 912 switch (CodeGenOpts.getAssignmentTrackingMode()) { 913 case CodeGenOptions::AssignmentTrackingOpts::Forced: 914 PB.registerPipelineStartEPCallback( 915 [&](ModulePassManager &MPM, OptimizationLevel Level) { 916 MPM.addPass(AssignmentTrackingPass()); 917 }); 918 break; 919 case CodeGenOptions::AssignmentTrackingOpts::Enabled: 920 // Disable assignment tracking in LTO builds for now as the performance 921 // cost is too high. Disable for LLDB tuning due to llvm.org/PR43126. 922 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO && 923 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) { 924 PB.registerPipelineStartEPCallback( 925 [&](ModulePassManager &MPM, OptimizationLevel Level) { 926 // Only use assignment tracking if optimisations are enabled. 927 if (Level != OptimizationLevel::O0) 928 MPM.addPass(AssignmentTrackingPass()); 929 }); 930 } 931 break; 932 case CodeGenOptions::AssignmentTrackingOpts::Disabled: 933 break; 934 } 935 936 // Enable verify-debuginfo-preserve-each for new PM. 937 DebugifyEachInstrumentation Debugify; 938 DebugInfoPerPass DebugInfoBeforePass; 939 if (CodeGenOpts.EnableDIPreservationVerify) { 940 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo); 941 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass); 942 943 if (!CodeGenOpts.DIBugsReportFilePath.empty()) 944 Debugify.setOrigDIVerifyBugsReportFilePath( 945 CodeGenOpts.DIBugsReportFilePath); 946 Debugify.registerCallbacks(PIC, MAM); 947 } 948 // Attempt to load pass plugins and register their callbacks with PB. 949 for (auto &PluginFN : CodeGenOpts.PassPlugins) { 950 auto PassPlugin = PassPlugin::Load(PluginFN); 951 if (PassPlugin) { 952 PassPlugin->registerPassBuilderCallbacks(PB); 953 } else { 954 Diags.Report(diag::err_fe_unable_to_load_plugin) 955 << PluginFN << toString(PassPlugin.takeError()); 956 } 957 } 958 for (const auto &PassCallback : CodeGenOpts.PassBuilderCallbacks) 959 PassCallback(PB); 960 #define HANDLE_EXTENSION(Ext) \ 961 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB); 962 #include "llvm/Support/Extension.def" 963 964 // Register the target library analysis directly and give it a customized 965 // preset TLI. 966 std::unique_ptr<TargetLibraryInfoImpl> TLII( 967 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib())); 968 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); }); 969 970 // Register all the basic analyses with the managers. 971 PB.registerModuleAnalyses(MAM); 972 PB.registerCGSCCAnalyses(CGAM); 973 PB.registerFunctionAnalyses(FAM); 974 PB.registerLoopAnalyses(LAM); 975 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); 976 977 ModulePassManager MPM; 978 // Add a verifier pass, before any other passes, to catch CodeGen issues. 979 if (CodeGenOpts.VerifyModule) 980 MPM.addPass(VerifierPass()); 981 982 if (!CodeGenOpts.DisableLLVMPasses) { 983 // Map our optimization levels into one of the distinct levels used to 984 // configure the pipeline. 985 OptimizationLevel Level = mapToLevel(CodeGenOpts); 986 987 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO; 988 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO; 989 990 if (LangOpts.ObjCAutoRefCount) { 991 PB.registerPipelineStartEPCallback( 992 [](ModulePassManager &MPM, OptimizationLevel Level) { 993 if (Level != OptimizationLevel::O0) 994 MPM.addPass( 995 createModuleToFunctionPassAdaptor(ObjCARCExpandPass())); 996 }); 997 PB.registerPipelineEarlySimplificationEPCallback( 998 [](ModulePassManager &MPM, OptimizationLevel Level, 999 ThinOrFullLTOPhase) { 1000 if (Level != OptimizationLevel::O0) 1001 MPM.addPass(ObjCARCAPElimPass()); 1002 }); 1003 PB.registerScalarOptimizerLateEPCallback( 1004 [](FunctionPassManager &FPM, OptimizationLevel Level) { 1005 if (Level != OptimizationLevel::O0) 1006 FPM.addPass(ObjCARCOptPass()); 1007 }); 1008 } 1009 1010 // If we reached here with a non-empty index file name, then the index 1011 // file was empty and we are not performing ThinLTO backend compilation 1012 // (used in testing in a distributed build environment). 1013 bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty(); 1014 // If so drop any the type test assume sequences inserted for whole program 1015 // vtables so that codegen doesn't complain. 1016 if (IsThinLTOPostLink) 1017 PB.registerPipelineStartEPCallback( 1018 [](ModulePassManager &MPM, OptimizationLevel Level) { 1019 MPM.addPass(LowerTypeTestsPass( 1020 /*ExportSummary=*/nullptr, 1021 /*ImportSummary=*/nullptr, 1022 /*DropTypeTests=*/lowertypetests::DropTestKind::Assume)); 1023 }); 1024 1025 // Register callbacks to schedule sanitizer passes at the appropriate part 1026 // of the pipeline. 1027 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) 1028 PB.registerScalarOptimizerLateEPCallback([this](FunctionPassManager &FPM, 1029 OptimizationLevel Level) { 1030 BoundsCheckingPass::BoundsCheckingOptions Options; 1031 Options.Merge = 1032 CodeGenOpts.SanitizeMergeHandlers.has(SanitizerKind::LocalBounds); 1033 if (!CodeGenOpts.SanitizeTrap.has(SanitizerKind::LocalBounds)) { 1034 Options.Rt = { 1035 /*MinRuntime=*/static_cast<bool>( 1036 CodeGenOpts.SanitizeMinimalRuntime), 1037 /*MayReturn=*/ 1038 CodeGenOpts.SanitizeRecover.has(SanitizerKind::LocalBounds), 1039 }; 1040 } 1041 FPM.addPass(BoundsCheckingPass(Options)); 1042 }); 1043 1044 // Don't add sanitizers if we are here from ThinLTO PostLink. That already 1045 // done on PreLink stage. 1046 if (!IsThinLTOPostLink) { 1047 addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB); 1048 addKCFIPass(TargetTriple, LangOpts, PB); 1049 } 1050 1051 if (std::optional<GCOVOptions> Options = 1052 getGCOVOptions(CodeGenOpts, LangOpts)) 1053 PB.registerPipelineStartEPCallback( 1054 [Options](ModulePassManager &MPM, OptimizationLevel Level) { 1055 MPM.addPass(GCOVProfilerPass(*Options)); 1056 }); 1057 if (std::optional<InstrProfOptions> Options = 1058 getInstrProfOptions(CodeGenOpts, LangOpts)) 1059 PB.registerPipelineStartEPCallback( 1060 [Options](ModulePassManager &MPM, OptimizationLevel Level) { 1061 MPM.addPass(InstrProfilingLoweringPass(*Options, false)); 1062 }); 1063 1064 // TODO: Consider passing the MemoryProfileOutput to the pass builder via 1065 // the PGOOptions, and set this up there. 1066 if (!CodeGenOpts.MemoryProfileOutput.empty()) { 1067 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM, 1068 OptimizationLevel Level, 1069 ThinOrFullLTOPhase) { 1070 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass())); 1071 MPM.addPass(ModuleMemProfilerPass()); 1072 }); 1073 } 1074 1075 if (CodeGenOpts.FatLTO) { 1076 MPM.addPass(PB.buildFatLTODefaultPipeline( 1077 Level, PrepareForThinLTO, 1078 PrepareForThinLTO || shouldEmitRegularLTOSummary())); 1079 } else if (PrepareForThinLTO) { 1080 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level)); 1081 } else if (PrepareForLTO) { 1082 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level)); 1083 } else { 1084 MPM.addPass(PB.buildPerModuleDefaultPipeline(Level)); 1085 } 1086 } 1087 1088 // Link against bitcodes supplied via the -mlink-builtin-bitcode option 1089 if (CodeGenOpts.LinkBitcodePostopt) 1090 MPM.addPass(LinkInModulesPass(BC)); 1091 1092 // Add a verifier pass if requested. We don't have to do this if the action 1093 // requires code generation because there will already be a verifier pass in 1094 // the code-generation pipeline. 1095 // Since we already added a verifier pass above, this 1096 // might even not run the analysis, if previous passes caused no changes. 1097 if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule) 1098 MPM.addPass(VerifierPass()); 1099 1100 if (Action == Backend_EmitBC || Action == Backend_EmitLL || 1101 CodeGenOpts.FatLTO) { 1102 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) { 1103 if (!TheModule->getModuleFlag("EnableSplitLTOUnit")) 1104 TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit", 1105 CodeGenOpts.EnableSplitLTOUnit); 1106 if (Action == Backend_EmitBC) { 1107 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) { 1108 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile); 1109 if (!ThinLinkOS) 1110 return; 1111 } 1112 MPM.addPass(ThinLTOBitcodeWriterPass( 1113 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr)); 1114 } else if (Action == Backend_EmitLL) { 1115 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists, 1116 /*EmitLTOSummary=*/true)); 1117 } 1118 } else { 1119 // Emit a module summary by default for Regular LTO except for ld64 1120 // targets 1121 bool EmitLTOSummary = shouldEmitRegularLTOSummary(); 1122 if (EmitLTOSummary) { 1123 if (!TheModule->getModuleFlag("ThinLTO") && !CodeGenOpts.UnifiedLTO) 1124 TheModule->addModuleFlag(llvm::Module::Error, "ThinLTO", uint32_t(0)); 1125 if (!TheModule->getModuleFlag("EnableSplitLTOUnit")) 1126 TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit", 1127 uint32_t(1)); 1128 } 1129 if (Action == Backend_EmitBC) { 1130 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, 1131 EmitLTOSummary)); 1132 } else if (Action == Backend_EmitLL) { 1133 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists, 1134 EmitLTOSummary)); 1135 } 1136 } 1137 1138 if (shouldEmitUnifiedLTOModueFlag()) 1139 TheModule->addModuleFlag(llvm::Module::Error, "UnifiedLTO", uint32_t(1)); 1140 } 1141 1142 // FIXME: This should eventually be replaced by a first-class driver option. 1143 // This should be done for both clang and flang simultaneously. 1144 // Print a textual, '-passes=' compatible, representation of pipeline if 1145 // requested. 1146 if (PrintPipelinePasses) { 1147 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) { 1148 auto PassName = PIC.getPassNameForClassName(ClassName); 1149 return PassName.empty() ? ClassName : PassName; 1150 }); 1151 outs() << "\n"; 1152 return; 1153 } 1154 1155 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice && 1156 LangOpts.HIPStdParInterposeAlloc) 1157 MPM.addPass(HipStdParAllocationInterpositionPass()); 1158 1159 // Now that we have all of the passes ready, run them. 1160 { 1161 PrettyStackTraceString CrashInfo("Optimizer"); 1162 llvm::TimeTraceScope TimeScope("Optimizer"); 1163 MPM.run(*TheModule, MAM); 1164 } 1165 } 1166 1167 void EmitAssemblyHelper::RunCodegenPipeline( 1168 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS, 1169 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) { 1170 // We still use the legacy PM to run the codegen pipeline since the new PM 1171 // does not work with the codegen pipeline. 1172 // FIXME: make the new PM work with the codegen pipeline. 1173 legacy::PassManager CodeGenPasses; 1174 1175 // Append any output we need to the pass manager. 1176 switch (Action) { 1177 case Backend_EmitAssembly: 1178 case Backend_EmitMCNull: 1179 case Backend_EmitObj: 1180 CodeGenPasses.add( 1181 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 1182 if (!CodeGenOpts.SplitDwarfOutput.empty()) { 1183 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput); 1184 if (!DwoOS) 1185 return; 1186 } 1187 if (!AddEmitPasses(CodeGenPasses, Action, *OS, 1188 DwoOS ? &DwoOS->os() : nullptr)) 1189 // FIXME: Should we handle this error differently? 1190 return; 1191 break; 1192 default: 1193 return; 1194 } 1195 1196 // If -print-pipeline-passes is requested, don't run the legacy pass manager. 1197 // FIXME: when codegen is switched to use the new pass manager, it should also 1198 // emit pass names here. 1199 if (PrintPipelinePasses) { 1200 return; 1201 } 1202 1203 { 1204 PrettyStackTraceString CrashInfo("Code generation"); 1205 llvm::TimeTraceScope TimeScope("CodeGenPasses"); 1206 CodeGenPasses.run(*TheModule); 1207 } 1208 } 1209 1210 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, 1211 std::unique_ptr<raw_pwrite_stream> OS, 1212 BackendConsumer *BC) { 1213 TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr); 1214 setCommandLineOpts(CodeGenOpts); 1215 1216 bool RequiresCodeGen = actionRequiresCodeGen(Action); 1217 CreateTargetMachine(RequiresCodeGen); 1218 1219 if (RequiresCodeGen && !TM) 1220 return; 1221 if (TM) 1222 TheModule->setDataLayout(TM->createDataLayout()); 1223 1224 // Before executing passes, print the final values of the LLVM options. 1225 cl::PrintOptionValues(); 1226 1227 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS; 1228 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC); 1229 RunCodegenPipeline(Action, OS, DwoOS); 1230 1231 if (ThinLinkOS) 1232 ThinLinkOS->keep(); 1233 if (DwoOS) 1234 DwoOS->keep(); 1235 } 1236 1237 static void runThinLTOBackend( 1238 DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, 1239 llvm::Module *M, const HeaderSearchOptions &HeaderOpts, 1240 const CodeGenOptions &CGOpts, const clang::TargetOptions &TOpts, 1241 const LangOptions &LOpts, std::unique_ptr<raw_pwrite_stream> OS, 1242 std::string SampleProfile, std::string ProfileRemapping, 1243 BackendAction Action) { 1244 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>> 1245 ModuleToDefinedGVSummaries; 1246 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 1247 1248 setCommandLineOpts(CGOpts); 1249 1250 // We can simply import the values mentioned in the combined index, since 1251 // we should only invoke this using the individual indexes written out 1252 // via a WriteIndexesThinBackend. 1253 FunctionImporter::ImportIDTable ImportIDs; 1254 FunctionImporter::ImportMapTy ImportList(ImportIDs); 1255 if (!lto::initImportList(*M, *CombinedIndex, ImportList)) 1256 return; 1257 1258 auto AddStream = [&](size_t Task, const Twine &ModuleName) { 1259 return std::make_unique<CachedFileStream>(std::move(OS), 1260 CGOpts.ObjectFilenameForDebug); 1261 }; 1262 lto::Config Conf; 1263 if (CGOpts.SaveTempsFilePrefix != "") { 1264 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".", 1265 /* UseInputModulePath */ false)) { 1266 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 1267 errs() << "Error setting up ThinLTO save-temps: " << EIB.message() 1268 << '\n'; 1269 }); 1270 } 1271 } 1272 Conf.CPU = TOpts.CPU; 1273 Conf.CodeModel = getCodeModel(CGOpts); 1274 Conf.MAttrs = TOpts.Features; 1275 Conf.RelocModel = CGOpts.RelocationModel; 1276 std::optional<CodeGenOptLevel> OptLevelOrNone = 1277 CodeGenOpt::getLevel(CGOpts.OptimizationLevel); 1278 assert(OptLevelOrNone && "Invalid optimization level!"); 1279 Conf.CGOptLevel = *OptLevelOrNone; 1280 Conf.OptLevel = CGOpts.OptimizationLevel; 1281 initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts); 1282 Conf.SampleProfile = std::move(SampleProfile); 1283 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops; 1284 // For historical reasons, loop interleaving is set to mirror setting for loop 1285 // unrolling. 1286 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops; 1287 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop; 1288 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP; 1289 // Only enable CGProfilePass when using integrated assembler, since 1290 // non-integrated assemblers don't recognize .cgprofile section. 1291 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS; 1292 1293 // Context sensitive profile. 1294 if (CGOpts.hasProfileCSIRInstr()) { 1295 Conf.RunCSIRInstr = true; 1296 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput); 1297 } else if (CGOpts.hasProfileCSIRUse()) { 1298 Conf.RunCSIRInstr = false; 1299 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath); 1300 } 1301 1302 Conf.ProfileRemapping = std::move(ProfileRemapping); 1303 Conf.DebugPassManager = CGOpts.DebugPassManager; 1304 Conf.VerifyEach = CGOpts.VerifyEach; 1305 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness; 1306 Conf.RemarksFilename = CGOpts.OptRecordFile; 1307 Conf.RemarksPasses = CGOpts.OptRecordPasses; 1308 Conf.RemarksFormat = CGOpts.OptRecordFormat; 1309 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile; 1310 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput; 1311 switch (Action) { 1312 case Backend_EmitNothing: 1313 Conf.PreCodeGenModuleHook = [](size_t Task, const llvm::Module &Mod) { 1314 return false; 1315 }; 1316 break; 1317 case Backend_EmitLL: 1318 Conf.PreCodeGenModuleHook = [&](size_t Task, const llvm::Module &Mod) { 1319 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists); 1320 return false; 1321 }; 1322 break; 1323 case Backend_EmitBC: 1324 Conf.PreCodeGenModuleHook = [&](size_t Task, const llvm::Module &Mod) { 1325 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists); 1326 return false; 1327 }; 1328 break; 1329 default: 1330 Conf.CGFileType = getCodeGenFileType(Action); 1331 break; 1332 } 1333 if (Error E = 1334 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList, 1335 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], 1336 /*ModuleMap=*/nullptr, Conf.CodeGenOnly, 1337 /*IRAddStream=*/nullptr, CGOpts.CmdArgs)) { 1338 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 1339 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n'; 1340 }); 1341 } 1342 } 1343 1344 void clang::EmitBackendOutput( 1345 DiagnosticsEngine &Diags, const HeaderSearchOptions &HeaderOpts, 1346 const CodeGenOptions &CGOpts, const clang::TargetOptions &TOpts, 1347 const LangOptions &LOpts, StringRef TDesc, llvm::Module *M, 1348 BackendAction Action, IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, 1349 std::unique_ptr<raw_pwrite_stream> OS, BackendConsumer *BC) { 1350 1351 llvm::TimeTraceScope TimeScope("Backend"); 1352 1353 std::unique_ptr<llvm::Module> EmptyModule; 1354 if (!CGOpts.ThinLTOIndexFile.empty()) { 1355 // If we are performing a ThinLTO importing compile, load the function index 1356 // into memory and pass it into runThinLTOBackend, which will run the 1357 // function importer and invoke LTO passes. 1358 std::unique_ptr<ModuleSummaryIndex> CombinedIndex; 1359 if (Error E = llvm::getModuleSummaryIndexForFile( 1360 CGOpts.ThinLTOIndexFile, 1361 /*IgnoreEmptyThinLTOIndexFile*/ true) 1362 .moveInto(CombinedIndex)) { 1363 logAllUnhandledErrors(std::move(E), errs(), 1364 "Error loading index file '" + 1365 CGOpts.ThinLTOIndexFile + "': "); 1366 return; 1367 } 1368 1369 // A null CombinedIndex means we should skip ThinLTO compilation 1370 // (LLVM will optionally ignore empty index files, returning null instead 1371 // of an error). 1372 if (CombinedIndex) { 1373 if (!CombinedIndex->skipModuleByDistributedBackend()) { 1374 runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts, 1375 TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile, 1376 CGOpts.ProfileRemappingFile, Action); 1377 return; 1378 } 1379 // Distributed indexing detected that nothing from the module is needed 1380 // for the final linking. So we can skip the compilation. We sill need to 1381 // output an empty object file to make sure that a linker does not fail 1382 // trying to read it. Also for some features, like CFI, we must skip 1383 // the compilation as CombinedIndex does not contain all required 1384 // information. 1385 EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext()); 1386 EmptyModule->setTargetTriple(M->getTargetTriple()); 1387 M = EmptyModule.get(); 1388 } 1389 } 1390 1391 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M, VFS); 1392 AsmHelper.EmitAssembly(Action, std::move(OS), BC); 1393 1394 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's 1395 // DataLayout. 1396 if (AsmHelper.TM) { 1397 std::string DLDesc = M->getDataLayout().getStringRepresentation(); 1398 if (DLDesc != TDesc) { 1399 unsigned DiagID = Diags.getCustomDiagID( 1400 DiagnosticsEngine::Error, "backend data layout '%0' does not match " 1401 "expected target description '%1'"); 1402 Diags.Report(DiagID) << DLDesc << TDesc; 1403 } 1404 } 1405 } 1406 1407 // With -fembed-bitcode, save a copy of the llvm IR as data in the 1408 // __LLVM,__bitcode section. 1409 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, 1410 llvm::MemoryBufferRef Buf) { 1411 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off) 1412 return; 1413 llvm::embedBitcodeInModule( 1414 *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker, 1415 CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode, 1416 CGOpts.CmdArgs); 1417 } 1418 1419 void clang::EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, 1420 DiagnosticsEngine &Diags) { 1421 if (CGOpts.OffloadObjects.empty()) 1422 return; 1423 1424 for (StringRef OffloadObject : CGOpts.OffloadObjects) { 1425 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr = 1426 llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject); 1427 if (ObjectOrErr.getError()) { 1428 auto DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 1429 "could not open '%0' for embedding"); 1430 Diags.Report(DiagID) << OffloadObject; 1431 return; 1432 } 1433 1434 llvm::embedBufferInModule(*M, **ObjectOrErr, ".llvm.offloading", 1435 Align(object::OffloadBinary::getAlignment())); 1436 } 1437 } 1438